kduma.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. /*
  2. * KDUMA - Kernel Mode Red-Zone memory allocator.
  3. * Copyright (C) 2006 Michael Eddington <meddington@gmail.com>
  4. * Copyright (C) 2006 Eric Rachner <eric@rachner.us>
  5. * Copyright (C) 2002-2005 Hayati Ayguen <h_ayguen@web.de>, Procitec GmbH
  6. * Copyright (C) 1987-1999 Bruce Perens <bruce@perens.com>
  7. * License: GNU GPL (GNU General Public License, see COPYING-GPL)
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  22. *
  23. */
  24. /* $Id$ */
  25. /* Variable: version
  26. *
  27. * KDUMA version string
  28. */
  29. static const char version[] =
  30. "KDUMA v0.1 -- Kernel Mode Red-Zone Memory Allocator\n"
  31. " Copyright (C) 2006 Michael Eddington\n"
  32. " Copyright (C) 2006 Eric Rachner\n"
  33. " Copyright (C) 2002-2005 Hayati Ayguen <h_ayguen@web.de>, Procitec GmbH\n"
  34. " Copyright (C) 1987-1999 Bruce Perens <bruce@perens.com>\n"
  35. " License: GNU GPL (GNU General Public License, see COPYING-GPL)\n";
  36. /* Variable: MEMORY_CREATION_SIZE
  37. *
  38. * MEMORY_CREATION_SIZE is the amount of memory to get from the operating
  39. * system at one time. We'll break that memory down into smaller pieces for
  40. * malloc buffers. One megabyte is probably a good value.
  41. */
  42. #define MEMORY_CREATION_SIZE 1024 * 1024
  43. /* Enum: _DUMA_SlotState
  44. *
  45. * State of slot values (empty, free, etc)
  46. */
  47. enum _DUMA_SlotState
  48. {
  49. DUMAST_EMPTY /* slot not in use */
  50. , DUMAST_FREE /* internal memory reserved, unused by user */
  51. , DUMAST_IN_USE /* memory in use by allocator; see following enum AllocType */
  52. , DUMAST_ALL_PROTECTED /* memory no more used by allocator; memory is not deallocated but protected */
  53. , DUMAST_BEGIN_PROTECTED /* most memory deallocated, but not page covering userAddress:
  54. * slot holds userAddress, userSize and allocator.
  55. */
  56. };
  57. /* Enum: _DUMA_Slot_FileSource
  58. *
  59. * Where did we get file info
  60. */
  61. enum _DUMA_Slot_FileSource
  62. {
  63. DUMAFS_EMPTY /* no filename, lineno */
  64. , DUMAFS_ALLOCATION /* filename, lineno from allocation */
  65. , DUMAFS_DEALLOCATION /* filename, lineno from deallocation */
  66. };
  67. /* Enum: _DUMA_InitState
  68. *
  69. * Whats are initialization start
  70. */
  71. enum _DUMA_InitState
  72. {
  73. DUMAIS_UNINITIALIZED = 0x1611 /* not initialized */
  74. , DUMAIS_IN_CONSTRUCTOR /* in constructor _duma_init() */
  75. , DUMAIS_OUT_CONSTRUCTOR /* construction _duma_init() finished */
  76. , DUMAIS_IN_INIT /* in initializer duma_init() */
  77. , DUMAIS_OUT_INIT /* initialization duma_init() finished */
  78. };
  79. /* Enum: _DUMA_MemRegion
  80. *
  81. * Memory region of slot. Really we should only
  82. * hang onto NORMAL memory. DMA should be released
  83. * fast.
  84. */
  85. enum _DUMA_MemRegion
  86. {
  87. DUMAMR_DMA,
  88. DUMAMR_NORMAL,
  89. DUMAMR_HIGH
  90. }
  91. /* Struct: _DUMA_Slot
  92. *
  93. * Struct Slot contains all of the information about a malloc buffer except
  94. * for the contents of its memory.
  95. */
  96. struct _DUMA_Slot
  97. {
  98. void *internalAddress;
  99. void *userAddress;
  100. void *protAddress;
  101. size_t internalSize;
  102. size_t userSize;
  103. /* save (some) space in production */
  104. unsigned short state :16;
  105. unsigned short allocator :8;
  106. unsigned short fileSource :8;
  107. #ifdef DUMA_USE_FRAMENO
  108. int frame;
  109. #endif
  110. char *filename; /* filename of allocation */
  111. int lineno; /* linenumber of allocation */
  112. #endif
  113. #ifdef DUMA_EXPLICIT_INIT
  114. int slackfill;
  115. #endif
  116. };
  117. /* Variable: DUMA_ALIGNMENT
  118. *
  119. * DUMA_ALIGNMENT is a global variable used to control the default alignment
  120. * of buffers returned by malloc(), calloc(), and realloc(). It is all-caps
  121. * so that its name matches the name of the environment variable that is used
  122. * to set it. This gives the programmer one less name to remember.
  123. */
  124. size_t DUMA_ALIGNMENT = DUMA_MIN_ALIGNMENT;
  125. /* Variable: DUMA_PROTECT_BELOW
  126. *
  127. * DUMA_PROTECT_BELOW is used to modify the behavior of the allocator. When
  128. * its value is non-zero, the allocator will place an inaccessable page
  129. * immediately _before_ the malloc buffer in the address space, instead
  130. * of _after_ it. Use this to detect malloc buffer under-runs, rather than
  131. * over-runs. It won't detect both at the same time, so you should test your
  132. * software twice, once with this value clear, and once with it set.
  133. */
  134. int DUMA_PROTECT_BELOW = 0;
  135. /* Variable: DUMA_FILL
  136. *
  137. * DUMA_FILL is set to 0-255 if DUMA should fill all new allocated
  138. * memory with the specified value. Set to -1 when DUMA should not
  139. * initialise allocated memory.
  140. * default is set to initialise with 255, cause many programs rely on
  141. * initialisation to 0!
  142. */
  143. int DUMA_FILL = 255;
  144. /* Variable: DUMA_SLACKFILL
  145. *
  146. * DUMA_SLACKFILL is set to 0-255. The slack / no mans land of all new allocated
  147. * memory is filled with the specified value.
  148. * default is set to initialise with 0xAA (=binary 10101010)
  149. * initialisation to 0!
  150. */
  151. static int DUMA_SLACKFILL = 0xAA;
  152. /* Variable: DUMA_PROTECT_FREE
  153. *
  154. * DUMA_PROTECT_FREE is used to control the disposition of memory that is
  155. * released using free(). It is all-caps so that its name
  156. * matches the name of the environment variable that is used to set it.
  157. * If its value is non-zero, memory released by free is made inaccessable.
  158. * Any software that touches free memory will then get a segmentation fault.
  159. * Depending on your application and your resources you may tell
  160. * DUMA not to use this memory ever again by setting a negative
  161. * value f.e. -1.
  162. * You can tell DUMA to limit the sum of protected memory by setting
  163. * a positive value, which is interpreted in kB.
  164. * If its value is zero, freed memory will be available for reallocation,
  165. * but will still be inaccessable until it is reallocated.
  166. */
  167. static long DUMA_PROTECT_FREE = -1L;
  168. /* Variable: DUMA_MAX_ALLOC
  169. *
  170. * DUMA_MAX_ALLOC is used to control the maximum memory print of the program
  171. * in total: When the sum of allocated and protected memory would exceed
  172. * this value in kB, the protected memory is freed/deleted.
  173. */
  174. static long DUMA_MAX_ALLOC = -1L;
  175. /* Variable: DUMA_ALLOW_MALLOC_0
  176. *
  177. * DUMA_ALLOW_MALLOC_0 is set if DUMA is to allow malloc(0). I
  178. * trap malloc(0) by default because it is a common source of bugs.
  179. * But you should know the allocation with size 0 is ANSI conform.
  180. */
  181. static int DUMA_ALLOW_MALLOC_0 = 1;
  182. /* Variable: DUMA_MALLOC_FAILEXIT
  183. *
  184. * DUMA_MALLOC_FAILEXIT controls the behaviour of DUMA when
  185. * malloc() fails and would return NULL. But most applications don't
  186. * check the return value for errors ... so
  187. * default to Exit on Fail
  188. */
  189. static int DUMA_MALLOC_FAILEXIT = 1;
  190. /* Variable: DUMA_FREE_ACCESS
  191. *
  192. * DUMA_FREE_ACCESS is set if DUMA is to write access memory before
  193. * freeing it. This makes easier using watch expressions in debuggers as the
  194. * process is interrupted even if the memory is going to be freed.
  195. */
  196. static int DUMA_FREE_ACCESS = 0;
  197. /* Variable: DUMA_SHOW_ALLOC
  198. *
  199. * DUMA_SHOW_ALLOC is set if DUMA is to print all allocations
  200. * and deallocations to the console. Although this generates a lot
  201. * of messages, the option can be useful to detect inefficient code
  202. * containing many allocations / deallocations
  203. */
  204. static int DUMA_SHOW_ALLOC = 0;
  205. /* Variable: _duma_allocList
  206. *
  207. * _DUMA_allocList points to the array of slot structures used to manage the
  208. * malloc arena.
  209. */
  210. struct _DUMA_Slot * _duma_allocList = 0;
  211. /* Variable: _duma_allocListSize
  212. *
  213. * _duma_allocListSize is the size of the allocation list. This will always
  214. * be a multiple of the page size.
  215. */
  216. static size_t _duma_allocListSize = 0;
  217. /* Variable: slotCount
  218. *
  219. * slotCount is the number of Slot structures in allocationList.
  220. */
  221. static size_t slotCount = 0;
  222. /* Variable: unUsedSlots
  223. *
  224. * unUsedSlots is the number of Slot structures that are currently available
  225. * to represent new malloc buffers. When this number gets too low, we will
  226. * create new slots.
  227. */
  228. static size_t unUsedSlots = 0;
  229. /* Variable: slotsPerPage
  230. *
  231. * slotsPerPage is the number of slot structures that fit in a virtual
  232. * memory page.
  233. */
  234. static size_t slotsPerPage = 0;
  235. /* Variable: sumAllocatedMem
  236. *
  237. * internal variable: sum of allocated -freed +protected memory in kB
  238. */
  239. static long sumAllocatedMem = 0;
  240. /* Variable: sumTotalAllocatedMem
  241. *
  242. * internal variable: sum of allocated memory in kB
  243. */
  244. static long sumTotalAllocatedMem = 0;
  245. /* Variable: sumProtectedMem
  246. *
  247. * internal variable: sum of protected memory in kB
  248. */
  249. static long sumProtectedMem = 0;
  250. /* Variable: numDeallocs
  251. *
  252. * internal variable: number of deallocations processed so far
  253. */
  254. static long numDeallocs = 0;
  255. /* Variable: numAllocs
  256. *
  257. * internal variable: number of allocations processed so far
  258. */
  259. static long numAllocs = 0;
  260. /* Variable: duma_init_done
  261. *
  262. * internal variable: state of initialization
  263. */
  264. static enum _DUMA_InitState duma_init_state = DUMAIS_UNINITIALIZED;
  265. /* Function: _duma_assert
  266. *
  267. * Print message and halt program execution in crazy way.
  268. */
  269. void _duma_assert(const char * exprstr, const char * filename, int lineno)
  270. {
  271. // !!!! Needs to be re implemented for KDUMA
  272. int *pcAddr = 0;
  273. DUMA_Print("\nDUMA: DUMA_ASSERT(%s) failed at\n%s(%i)\n", exprstr, filename, lineno );
  274. /* this is "really" bad, but it works. assert() from assert.h system header
  275. * stops only the current thread but the program goes on running under MS Visual C++.
  276. * This way the program definitely halts.
  277. */
  278. while (1)
  279. *pcAddr++ = 0;
  280. }
  281. /* Function: duma_init
  282. *
  283. * duma_init sets configuration settings. Can sometimes cause problems
  284. * when called from _duma_init.
  285. *
  286. * See Also: <_duma_init>
  287. */
  288. void duma_init(void)
  289. {
  290. char * string;
  291. void * testAlloc;
  292. /* avoid double call, when initialization already in progress */
  293. if ( duma_init_state >= DUMAIS_IN_INIT && duma_init_state <= DUMAIS_OUT_INIT )
  294. return;
  295. else
  296. duma_init_state = DUMAIS_IN_INIT;
  297. DUMA_Print(version);
  298. DUMA_Print("DUMA: Registration was successful.\n");
  299. /* initialize semaphoring */
  300. DUMA_INIT_SEMAPHORE();
  301. /*
  302. * Check whether malloc and free is available
  303. */
  304. testAlloc = kmalloc(123);
  305. if (numAllocs == 0)
  306. DUMA_Abort("kmalloc() is not bound to kduma.\nKDUMA Aborting.\n");
  307. kfree(testAlloc);
  308. if (numDeallocs == 0)
  309. DUMA_Abort("kfree() is not bound to kduma.\nKDUMA Aborting.\n");
  310. /* initialization finished */
  311. duma_init_state = DUMAIS_OUT_INIT;
  312. }
  313. /* Function: _duma_init
  314. *
  315. * _duma_init sets up the memory allocation arena and the run-time
  316. * configuration information. We will call duma_init unless DUMA_EXPLICIT_INIT
  317. * is defined at compile time.
  318. *
  319. * See Also: <duma_init>
  320. */
  321. void
  322. _duma_init(void)
  323. {
  324. size_t size = MEMORY_CREATION_SIZE;
  325. struct _DUMA_Slot * slot;
  326. int inRecursion = (duma_init_state >= DUMAIS_IN_CONSTRUCTOR && duma_init_state <= DUMAIS_OUT_INIT);
  327. /* constuction already done? this should not happen! */
  328. if (duma_init_state >= DUMAIS_OUT_CONSTRUCTOR && duma_init_state <= DUMAIS_OUT_INIT)
  329. goto duma_constructor_callinit;
  330. else
  331. duma_init_state = DUMAIS_IN_CONSTRUCTOR;
  332. if ( DUMA_PAGE_SIZE != Page_Size() )
  333. DUMA_Abort("DUMA_PAGE_SIZE is not correct. Run createconf and save results as duma_config.h");
  334. if(!inRecursion)
  335. DUMA_GET_SEMAPHORE();
  336. /* call of DUMA_GET_SEMAPHORE() may already have done the construction recursively! */
  337. if ( duma_init_state >= DUMAIS_OUT_CONSTRUCTOR )
  338. goto duma_constructor_relsem;
  339. /*
  340. * Figure out how many Slot structures to allocate at one time.
  341. */
  342. slotCount = slotsPerPage = DUMA_PAGE_SIZE / sizeof(struct _DUMA_Slot);
  343. _duma_allocListSize = DUMA_PAGE_SIZE;
  344. if ( size < _duma_allocListSize )
  345. size = _duma_allocListSize;
  346. size = ( size + DUMA_PAGE_SIZE -1 ) & ~( DUMA_PAGE_SIZE -1 );
  347. /*
  348. * Allocate memory, and break it up into two malloc buffers. The
  349. * first buffer will be used for Slot structures, the second will
  350. * be marked free.
  351. */
  352. slot = _duma_allocList = (struct _DUMA_Slot *)Page_Create(size, 0/*=exitonfail*/, 0/*=printerror*/);
  353. if ( 0 == _duma_allocList && 0L != DUMA_PROTECT_FREE )
  354. {
  355. int reduce_more;
  356. do
  357. {
  358. /* reduce as much protected memory as we need - or at least try so */
  359. reduce_more = reduceProtectedMemory( (size+1023) >>10 );
  360. /* simply try again */
  361. slot = _duma_allocList = (struct _DUMA_Slot *)Page_Create( size, 0/*=exitonfail*/, 0/*= printerror*/ );
  362. }
  363. while ( reduce_more && 0 == _duma_allocList );
  364. if ( 0 == _duma_allocList )
  365. slot = _duma_allocList = (struct _DUMA_Slot *)Page_Create( size, 1/*=exitonfail*/, 1/*= printerror*/ );
  366. }
  367. memset((char *)_duma_allocList, 0, _duma_allocListSize);
  368. /* enter _duma_allocList as slot to allow call to free() when doing allocateMoreSlots() */
  369. slot[0].internalAddress = slot[0].userAddress = _duma_allocList;
  370. slot[0].internalSize = slot[0].userSize = _duma_allocListSize;
  371. slot[0].state = DUMAST_IN_USE;
  372. slot[0].allocator = EFA_INT_ALLOC;
  373. slot[0].fileSource = DUMAFS_ALLOCATION;
  374. #ifdef DUMA_USE_FRAMENO
  375. slot[0].frame = 0;
  376. #endif
  377. slot[0].filename = __FILE__;
  378. slot[0].lineno = __LINE__;
  379. #endif
  380. if ( size > _duma_allocListSize )
  381. {
  382. slot[1].internalAddress = slot[1].userAddress
  383. = ((char *)slot[0].internalAddress) + slot[0].internalSize;
  384. slot[1].internalSize = slot[1].userSize
  385. = size - slot[0].internalSize;
  386. slot[1].state = DUMAST_FREE;
  387. slot[1].allocator = EFA_INT_ALLOC;
  388. slot[1].fileSource = DUMAFS_ALLOCATION;
  389. #ifdef DUMA_USE_FRAMENO
  390. slot[1].frame = 0;
  391. #endif
  392. slot[1].filename = __FILE__;
  393. slot[1].lineno = __LINE__;
  394. #endif
  395. }
  396. /*
  397. * Deny access to the free page, so that we will detect any software
  398. * that treads upon free memory.
  399. */
  400. Page_DenyAccess(slot[1].internalAddress, slot[1].internalSize);
  401. /*
  402. * Account for the two slot structures that we've used.
  403. */
  404. unUsedSlots = slotCount - 2;
  405. /* construction done */
  406. if ( duma_init_state < DUMAIS_OUT_CONSTRUCTOR )
  407. duma_init_state = DUMAIS_OUT_CONSTRUCTOR;
  408. /***********************/
  409. duma_constructor_relsem:
  410. if ( !inRecursion )
  411. DUMA_RELEASE_SEMAPHORE();
  412. /*************************/
  413. duma_constructor_callinit:
  414. if ( duma_init_state < DUMAIS_OUT_INIT )
  415. duma_init();
  416. }
  417. /* Function: allocateMoreSlots
  418. *
  419. * allocateMoreSlots is called when there are only enough slot structures
  420. * left to support the allocation of a single malloc buffer.
  421. *
  422. * See Also: <_duma_allocate>
  423. */
  424. static void allocateMoreSlots(void)
  425. {
  426. size_t newSize = _duma_allocListSize + DUMA_PAGE_SIZE;
  427. void * newAllocation;
  428. void * oldAllocation = _duma_allocList;
  429. newAllocation = _duma_allocate( 1 /*=alignment*/, newSize,
  430. 0 /*=protectBelow*/, -1 /*=fillByte*/, 0 /*=protectAllocList*/,
  431. EFA_INT_ALLOC, DUMA_FAIL_NULL, __FILE__, __LINE__ );
  432. if ( ! newAllocation )
  433. return;
  434. memcpy(newAllocation, _duma_allocList, _duma_allocListSize);
  435. memset(&(((char *)newAllocation)[_duma_allocListSize]), 0, DUMA_PAGE_SIZE);
  436. _duma_allocList = (struct _DUMA_Slot *)newAllocation;
  437. _duma_allocListSize = newSize;
  438. slotCount += slotsPerPage;
  439. unUsedSlots += slotsPerPage;
  440. #ifndef DUMA_NO_LEAKDETECTION
  441. _duma_deallocate( oldAllocation, 0 /*=protectAllocList*/, EFA_INT_DEALLOC, __FILE__, __LINE__ );
  442. #else
  443. _duma_deallocate( oldAllocation, 0 /*=protectAllocList*/, EFA_INT_DEALLOC);
  444. #endif
  445. }
  446. /* Function: _duma_allocate
  447. *
  448. * This is the memory allocator. When asked to allocate a buffer, allocate
  449. * it in such a way that the end of the buffer is followed by an inaccessable
  450. * memory page. If software overruns that buffer, it will touch the bad page
  451. * and get an immediate segmentation fault. It's then easy to zero in on the
  452. * offending code with a debugger.
  453. *
  454. * There are a few complications. If the user asks for an odd-sized buffer,
  455. * we would have to have that buffer start on an odd address if the byte after
  456. * the end of the buffer was to be on the inaccessable page. Unfortunately,
  457. * there is lots of software that asks for odd-sized buffers and then
  458. * requires that the returned address be word-aligned, or the size of the
  459. * buffer be a multiple of the word size. An example are the string-processing
  460. * functions on Sun systems, which do word references to the string memory
  461. * and may refer to memory up to three bytes beyond the end of the string.
  462. * For this reason, I take the alignment requests to memalign() and valloc()
  463. * seriously, and
  464. *
  465. * DUMA wastes lots of memory.
  466. *
  467. * See Also: <_duma_deallocate>
  468. */
  469. void * _duma_allocate(size_t alignment, size_t userSize, int protectBelow,
  470. int fillByte, int protectAllocList, enum _DUMA_Allocator allocator, enum _DUMA_FailReturn fail DUMA_PARAMLIST_FL)
  471. {
  472. size_t count;
  473. struct _DUMA_Slot *slot;
  474. struct _DUMA_Slot *fullSlot;
  475. struct _DUMA_Slot *emptySlots[2];
  476. DUMA_ADDR intAddr, userAddr, protAddr, endAddr;
  477. size_t internalSize;
  478. char stacktrace[601];
  479. char* ptrStacktrace;
  480. DUMA_ASSERT( 0 != _duma_allocList );
  481. /* initialize return value */
  482. userAddr = 0;
  483. /* check userSize */
  484. if ( 0 == userSize )
  485. {
  486. if ( !DUMA_ALLOW_MALLOC_0 )
  487. {
  488. DUMA_Abort("Allocating 0 bytes, probably a bug: %s(%i)", filename, lineno);
  489. }
  490. else
  491. return (void*)userAddr;
  492. }
  493. /* check alignment */
  494. if ( ! alignment )
  495. {
  496. DUMA_SIZE a = (DUMA_SIZE)DUMA_ALIGNMENT;
  497. DUMA_SIZE s = (DUMA_SIZE)userSize;
  498. if ( s < a )
  499. {
  500. /* to next lower power of 2 */
  501. for (a = s; a & (a-1); a &= a-1) ;
  502. }
  503. alignment = (size_t)a; /* this is new alignment */
  504. }
  505. if ( (int)alignment != ((int)alignment & -(int)alignment) )
  506. {
  507. #ifndef DUMA_NO_LEAKDETECTION
  508. DUMA_Abort("Alignment (=%d) is not a power of 2 requested from %s(%i)", (DUMA_SIZE)alignment, filename, lineno);
  509. #else
  510. DUMA_Abort("Alignment (=%d) is not a power of 2", (DUMA_SIZE)alignment);
  511. #endif
  512. }
  513. /* count and show allocation, if requested */
  514. numAllocs++;
  515. if (DUMA_SHOW_ALLOC)
  516. {
  517. #ifndef DUMA_NO_LEAKDETECTION
  518. DUMA_Print("\nDUMA: Allocating %d bytes at %s(%i).", (DUMA_SIZE)userSize, filename, lineno);
  519. #else
  520. DUMA_Print("\nDUMA: Allocating %d bytes.", (DUMA_SIZE)userSize);
  521. #endif
  522. }
  523. /*
  524. * If protectBelow is set, all addresses returned by malloc()
  525. * and company will be page-aligned.
  526. *
  527. * The internal size of the buffer is rounded up to the next alignment and page-size
  528. * boundary, and then we add another page's worth of memory for the dead page.
  529. */
  530. /* a bit tricky but no modulo and no if () */
  531. internalSize = ( (userSize + DUMA_PAGE_SIZE -1) & ~(DUMA_PAGE_SIZE -1) ) + DUMA_PAGE_SIZE;
  532. if ( alignment > DUMA_PAGE_SIZE )
  533. internalSize += alignment - DUMA_PAGE_SIZE;
  534. /*
  535. * These will hold the addresses of two empty Slot structures, that
  536. * can be used to hold information for any memory I create, and any
  537. * memory that I mark free.
  538. */
  539. fullSlot = emptySlots[0] = emptySlots[1] = 0;
  540. /*
  541. * The internal memory used by the allocator is currently
  542. * inaccessable, so that errant programs won't scrawl on the
  543. * allocator's arena. I'll un-protect it here so that I can make
  544. * a new allocation. I'll re-protect it before I return.
  545. */
  546. if ( protectAllocList )
  547. {
  548. IF__DUMA_INIT_DONE
  549. DUMA_GET_SEMAPHORE();
  550. Page_AllowAccess(_duma_allocList, _duma_allocListSize);
  551. }
  552. /*
  553. * If I'm running out of empty slots, create some more before
  554. * I don't have enough slots left to make an allocation.
  555. */
  556. if ( DUMAAT_INTERNAL != _duma_allocDesc[allocator].type && unUsedSlots < 7 )
  557. allocateMoreSlots();
  558. /*
  559. * Iterate through all of the slot structures. Attempt to find a slot
  560. * containing free memory of the exact right size. Accept a slot with
  561. * more memory than we want, if the exact right size is not available.
  562. * Find two slot structures that are not in use. We will need one if
  563. * we split a buffer into free and allocated parts, and the second if
  564. * we have to create new memory and mark it as free.
  565. *
  566. */
  567. for ( slot = _duma_allocList, count = slotCount ; count > 0; --count, ++slot )
  568. {
  569. /*
  570. * Windows needs special treatment, cause Page_Delete() needs exactly
  571. * the same memory region as Page_Create()!
  572. * Thus as a quick hack no memory management is done by DUMA.
  573. */
  574. #if !defined(WIN32)
  575. if ( DUMAST_FREE == slot->state && slot->internalSize >= internalSize )
  576. {
  577. if ( !fullSlot || slot->internalSize < fullSlot->internalSize )
  578. {
  579. fullSlot = slot;
  580. if ( slot->internalSize == internalSize )
  581. break; /* All done; no empty slot needed in this case */
  582. }
  583. }
  584. else
  585. #endif
  586. if ( DUMAST_EMPTY == slot->state )
  587. {
  588. if(!emptySlots[0])
  589. emptySlots[0] = slot;
  590. else if ( !emptySlots[1] )
  591. emptySlots[1] = slot;
  592. #if defined(WIN32)
  593. break;
  594. #endif
  595. }
  596. }
  597. if ( !fullSlot )
  598. {
  599. /*
  600. * I get here if I haven't been able to find a free buffer
  601. * with all of the memory I need. I'll have to create more
  602. * memory. I'll mark it all as free, and then split it into
  603. * free and allocated portions later.
  604. */
  605. size_t chunkSize;
  606. size_t chunkSizekB;
  607. #if defined(WIN32)
  608. chunkSize = internalSize;
  609. #else
  610. chunkSize = MEMORY_CREATION_SIZE;
  611. if ( chunkSize < internalSize )
  612. chunkSize = internalSize;
  613. chunkSize = ( chunkSize + DUMA_PAGE_SIZE -1 ) & ~( DUMA_PAGE_SIZE -1 );
  614. #endif
  615. chunkSizekB = (chunkSize+1023) >>10;
  616. /* Use up one of the empty slots to make the full slot. */
  617. if ( !emptySlots[0] )
  618. DUMA_Abort("Internal error in allocator: No empty slot 0.\n");
  619. #if !defined(WIN32)
  620. if ( !emptySlots[1] )
  621. DUMA_Abort("Internal error in allocator: No empty slot 1.\n");
  622. #endif
  623. fullSlot = emptySlots[0];
  624. emptySlots[0] = emptySlots[1];
  625. /* reduce protected memory when we would exceed DUMA_MAX_ALLOC */
  626. if ( DUMA_MAX_ALLOC > 0 && sumAllocatedMem + chunkSizekB > DUMA_MAX_ALLOC )
  627. reduceProtectedMemory( chunkSizekB );
  628. fullSlot->internalAddress = Page_Create( chunkSize, 0/*= exitonfail*/, 0/*= printerror*/ );
  629. if ( 0 == fullSlot->internalAddress && 0L != DUMA_PROTECT_FREE )
  630. {
  631. int reduce_more;
  632. do
  633. {
  634. /* reduce as much protected memory as we need - or at least try so */
  635. reduce_more = reduceProtectedMemory( (chunkSize+1023) >>10 );
  636. /* simply try again */
  637. fullSlot->internalAddress = Page_Create( chunkSize, 0/*= exitonfail*/, 0/*= printerror*/ );
  638. }
  639. while ( reduce_more && 0 == fullSlot->internalAddress );
  640. if ( 0 == fullSlot->internalAddress && DUMA_FAIL_ENV == fail )
  641. fullSlot->internalAddress = Page_Create( chunkSize, DUMA_MALLOC_FAILEXIT, 1/*= printerror*/ );
  642. }
  643. if ( fullSlot->internalAddress )
  644. {
  645. sumAllocatedMem += ( (chunkSize +1023) >>10 );
  646. sumTotalAllocatedMem += ( (chunkSize +1023) >>10 );
  647. fullSlot->internalSize = chunkSize;
  648. fullSlot->state = DUMAST_FREE;
  649. --unUsedSlots;
  650. }
  651. } /* end if ( !fullSlot ) */
  652. if ( fullSlot->internalSize )
  653. {
  654. if ( !protectBelow )
  655. {
  656. /*
  657. * Arrange the buffer so that it is followed by an inaccessable
  658. * memory page. A buffer overrun that touches that page will
  659. * cause a segmentation fault.
  660. * internalAddr <= userAddr < protectedAddr
  661. */
  662. /* Figure out what address to give the user. */
  663. intAddr = (DUMA_ADDR)fullSlot->internalAddress;
  664. endAddr = intAddr + internalSize;
  665. userAddr = ( intAddr + internalSize - DUMA_PAGE_SIZE - userSize )
  666. & ~(alignment -1);
  667. protAddr = ( userAddr + userSize + DUMA_PAGE_SIZE -1)
  668. & ~(DUMA_PAGE_SIZE -1);
  669. /* DUMA_ASSERT(intAddr <= userAddr && intAddr < protAddr ); */
  670. /* Set up the "live" page(s). */
  671. Page_AllowAccess( (char*)intAddr, protAddr - intAddr );
  672. /* Set up the "dead" page(s). */
  673. Page_DenyAccess( (char*)protAddr, endAddr - protAddr );
  674. }
  675. else /* if (protectBelow) */
  676. {
  677. /*
  678. * Arrange the buffer so that it is preceded by an inaccessable
  679. * memory page. A buffer underrun that touches that page will
  680. * cause a segmentation fault.
  681. */
  682. /* Figure out what address to give the user. */
  683. intAddr = (DUMA_ADDR)fullSlot->internalAddress;
  684. endAddr = intAddr + internalSize;
  685. userAddr = ( intAddr + DUMA_PAGE_SIZE + alignment -1)
  686. & ~(alignment -1);
  687. protAddr = ( userAddr & ~(DUMA_PAGE_SIZE -1) ) - DUMA_PAGE_SIZE;
  688. /* DUMA_ASSERT(intAddr < userAddr && intAddr <= protAddr ); */
  689. /* Set up the "live" page(s). userAddr == protAddr + DUMA_PAGE_SIZE ! */
  690. Page_AllowAccess( (char*)userAddr, internalSize - (userAddr - protAddr) );
  691. /* Set up the "dead" page(s). */
  692. Page_DenyAccess( (char*)intAddr, userAddr - intAddr );
  693. }
  694. /* => userAddress = internalAddress + DUMA_PAGE_SIZE */
  695. fullSlot->userAddress = (char*)userAddr;
  696. fullSlot->protAddress = (char*)protAddr;
  697. fullSlot->userSize = userSize;
  698. fullSlot->state = DUMAST_IN_USE;
  699. fullSlot->allocator = allocator;
  700. #ifndef DUMA_NO_LEAKDETECTION
  701. fullSlot->fileSource = DUMAFS_ALLOCATION;
  702. #ifdef DUMA_USE_FRAMENO
  703. fullSlot->frame = frameno;
  704. #endif
  705. fullSlot->filename = (char*)filename;
  706. #ifdef DUMA_EXPLICIT_INIT
  707. /* mark allocations from standard libraries
  708. * before duma_init() is finished with lineno = -1
  709. * to allow special treatment in leak_checking
  710. */
  711. fullSlot->lineno = (DUMAIS_OUT_INIT == duma_init_state) ? lineno : -1;
  712. #else
  713. fullSlot->lineno = lineno;
  714. #endif
  715. #endif
  716. /* initialise no mans land of slot */
  717. _duma_init_slack( fullSlot );
  718. } /* end if ( fullSlot->internalSize ) */
  719. /*
  720. * Make the pool's internal memory inaccessable, so that the program
  721. * being debugged can't stomp on it.
  722. */
  723. if ( protectAllocList )
  724. {
  725. Page_DenyAccess(_duma_allocList, _duma_allocListSize);
  726. IF__DUMA_INIT_DONE
  727. DUMA_RELEASE_SEMAPHORE();
  728. }
  729. /* Fill the memory if it was specified to do so. */
  730. if ( ((char*)userAddr) && fillByte != -1 )
  731. memset( (char*)userAddr, fillByte, userSize);
  732. return (char*)userAddr;
  733. }
  734. /* Function: _duma_deallocate
  735. *
  736. * Deallocate allocated memory after running some checks, then open
  737. * slot for use. Uses Page_Delete to free the underlying memory.
  738. *
  739. * See Also: <Page_Delete> <_duma_allocate>
  740. */
  741. void _duma_deallocate(void * address, int protectAllocList, enum _DUMA_Allocator allocator DUMA_PARAMLIST_FL)
  742. {
  743. struct _DUMA_Slot * slot;
  744. long internalSizekB;
  745. if ( 0 == _duma_allocList )
  746. {
  747. DUMA_Abort("free() called before first malloc().");
  748. }
  749. if ( 0 == address )
  750. return;
  751. if ( protectAllocList )
  752. {
  753. IF__DUMA_INIT_DONE
  754. DUMA_GET_SEMAPHORE();
  755. Page_AllowAccess(_duma_allocList, _duma_allocListSize);
  756. }
  757. if ( !(slot = slotForUserAddress(address)) )
  758. {
  759. if ( (slot = nearestSlotForUserAddress(address)) )
  760. {
  761. if ( DUMAFS_ALLOCATION == slot->fileSource )
  762. DUMA_Abort("free(%a): address not from DUMA or already freed. Address may be corrupted from %a allocated from %s(%i)",
  763. (DUMA_ADDR)address, (DUMA_ADDR)slot->userAddress, slot->filename, slot->lineno);
  764. else if ( DUMAFS_DEALLOCATION == slot->fileSource )
  765. DUMA_Abort("free(%a): address not from DUMA or already freed. Address may be corrupted from %a deallocated at %s(%i)",
  766. (DUMA_ADDR)address, (DUMA_ADDR)slot->userAddress, slot->filename, slot->lineno);
  767. else
  768. }
  769. else
  770. {
  771. DUMA_Abort("free(%a): address not from DUMA or already freed.", (DUMA_ADDR)address);
  772. }
  773. }
  774. if ( DUMAST_ALL_PROTECTED == slot->state || DUMAST_BEGIN_PROTECTED == slot->state )
  775. {
  776. if ( DUMAFS_ALLOCATION == slot->fileSource )
  777. DUMA_Abort("free(%a): memory already freed. allocated from %s(%i)",
  778. (DUMA_ADDR)address, slot->filename, slot->lineno);
  779. else if ( DUMAFS_DEALLOCATION == slot->fileSource )
  780. DUMA_Abort("free(%a): memory already freed at %s(%i)",
  781. (DUMA_ADDR)address, slot->filename, slot->lineno);
  782. else
  783. DUMA_Abort("free(%a): memory already freed.", (DUMA_ADDR)address);
  784. }
  785. else if ( _duma_allocDesc[slot->allocator].type != _duma_allocDesc[allocator].type )
  786. {
  787. if ( DUMAFS_ALLOCATION == slot->fileSource )
  788. DUMA_Abort("Free mismatch: allocator '%s' used at %s(%i)\n but deallocator '%s' called at %s(%i)!",
  789. _duma_allocDesc[slot->allocator].name, slot->filename, slot->lineno,
  790. _duma_allocDesc[allocator].name, filename, lineno );
  791. else if ( DUMAFS_DEALLOCATION == slot->fileSource )
  792. DUMA_Abort("Free mismatch: allocator '%s' used \nbut deallocator '%s' called at %s(%i)!",
  793. _duma_allocDesc[slot->allocator].name,
  794. _duma_allocDesc[allocator].name, filename, lineno );
  795. else
  796. DUMA_Abort("Free mismatch: allocator '%s' used but deallocator '%s' called!",
  797. _duma_allocDesc[slot->allocator].name, _duma_allocDesc[allocator].name );
  798. }
  799. /* count and show deallocation, if requested */
  800. numDeallocs++;
  801. if (DUMA_SHOW_ALLOC)
  802. DUMA_Print("\nDUMA: Freeing %d bytes at %s(%i) (Allocated from %s(%i)).",
  803. (DUMA_SIZE)slot->userSize, filename, lineno, slot->filename, slot->lineno);
  804. /* CHECK INTEGRITY OF NO MANS LAND */
  805. _duma_check_slack( slot );
  806. if ( DUMA_FREE_ACCESS )
  807. {
  808. volatile char *start = slot->userAddress;
  809. volatile char *cur;
  810. for (cur = (char*)slot->userAddress+slot->userSize; --cur >= start; )
  811. {
  812. char c = *cur;
  813. *cur = c-1;
  814. *cur = c;
  815. }
  816. }
  817. internalSizekB = (slot->internalSize+1023) >>10;
  818. /* protect memory, that nobody can access it */
  819. /* Free as much protected memory, that we can protect this one */
  820. /* is there need? and is there a way to free such much? */
  821. if ( DUMA_PROTECT_FREE > 0L
  822. && sumProtectedMem + internalSizekB > DUMA_PROTECT_FREE
  823. && internalSizekB < DUMA_PROTECT_FREE
  824. && sumProtectedMem >= internalSizekB)
  825. {
  826. reduceProtectedMemory( internalSizekB );
  827. }
  828. if (( EFA_INT_ALLOC != slot->allocator )
  829. && ( DUMA_PROTECT_FREE < 0L
  830. || ( DUMA_PROTECT_FREE > 0L
  831. && sumProtectedMem + internalSizekB <= DUMA_PROTECT_FREE
  832. ) )
  833. )
  834. {
  835. slot->state = DUMAST_ALL_PROTECTED;
  836. Page_DenyAccess(slot->internalAddress, slot->internalSize);
  837. sumProtectedMem += internalSizekB;
  838. if ( lineno )
  839. {
  840. slot->fileSource = DUMAFS_DEALLOCATION;
  841. slot->filename = (char*)filename;
  842. slot->lineno = lineno;
  843. }
  844. }
  845. else
  846. {
  847. /* free all the memory */
  848. Page_Delete(slot->internalAddress, slot->internalSize);
  849. sumAllocatedMem -= internalSizekB;
  850. /* free slot and userAddr */
  851. slot->internalAddress = slot->userAddress = 0;
  852. slot->internalSize = slot->userSize = 0;
  853. slot->state = DUMAST_EMPTY;
  854. slot->allocator = EFA_INT_ALLOC;
  855. slot->fileSource = DUMAFS_EMPTY;
  856. #ifdef DUMA_USE_FRAMENO
  857. slot->frame = 0;
  858. #endif
  859. slot->filename = 0;
  860. slot->lineno = 0;
  861. }
  862. if ( protectAllocList )
  863. {
  864. Page_DenyAccess(_duma_allocList, _duma_allocListSize);
  865. IF__DUMA_INIT_DONE
  866. DUMA_RELEASE_SEMAPHORE();
  867. }
  868. }
  869. /*********************************************************/
  870. /* Function: _duma_kmalloc
  871. *
  872. * A version of kmalloc.
  873. */
  874. void * _duma_kmalloc(size_t size, int flags DUMA_PARAMLIST_FL)
  875. {
  876. if ( _duma_allocList == 0 )
  877. _duma_init(); /* This sets DUMA_ALIGNMENT, DUMA_PROTECT_BELOW, DUMA_FILL, ... */
  878. return _duma_allocate(0, size, flags, DUMA_PROTECT_BELOW,
  879. DUMA_FILL, 1 /*=protectAllocList*/, EFA_MALLOC,
  880. DUMA_FAIL_ENV DUMA_PARAMS_FL);
  881. }
  882. /* Function: _duma_kfree
  883. *
  884. * A version of free.
  885. */
  886. void _duma_kfree(void * baseAdr DUMA_PARAMLIST_FL)
  887. {
  888. if ( _duma_allocList == 0 )
  889. _duma_init(); /* This sets DUMA_ALIGNMENT, DUMA_PROTECT_BELOW, DUMA_FILL, ... */
  890. _duma_deallocate(baseAdr, 1 /*=protectAllocList*/, EFA_FREE DUMA_PARAMS_FL);
  891. }
  892. /* Function: _duma_valloc
  893. *
  894. * A version of valloc.
  895. */
  896. void * _duma_valloc(size_t size DUMA_PARAMLIST_FL)
  897. {
  898. if ( _duma_allocList == 0 )
  899. _duma_init(); /* This sets DUMA_ALIGNMENT, DUMA_PROTECT_BELOW, DUMA_FILL, ... */
  900. return _duma_allocate(DUMA_PAGE_SIZE, size, DUMA_PROTECT_BELOW,
  901. DUMA_FILL, 1 /*=protectAllocList*/, EFA_VALLOC,
  902. DUMA_FAIL_ENV DUMA_PARAMS_FL);
  903. }
  904. /* Function: _duma_vfree
  905. *
  906. * A version of free.
  907. */
  908. void _duma_vfree(void * baseAdr DUMA_PARAMLIST_FL)
  909. {
  910. if ( _duma_allocList == 0 )
  911. _duma_init(); /* This sets DUMA_ALIGNMENT, DUMA_PROTECT_BELOW, DUMA_FILL, ... */
  912. _duma_deallocate(baseAdr, 1 /*=protectAllocList*/, EFA_FREE DUMA_PARAMS_FL);
  913. }
  914. /* Function: _duma_strdup
  915. *
  916. * A version of strdup.
  917. */
  918. char * _duma_strdup(const char * str DUMA_PARAMLIST_FL)
  919. {
  920. size_t size;
  921. char * dup;
  922. unsigned i;
  923. if ( _duma_allocList == 0 )
  924. _duma_init(); /* This sets DUMA_ALIGNMENT, DUMA_PROTECT_BELOW, DUMA_FILL, ... */
  925. size = 0;
  926. while (str[size])
  927. ++size;
  928. dup = _duma_allocate(0, size +1, DUMA_PROTECT_BELOW,
  929. -1 /*=fillByte*/, 1 /*=protectAllocList*/, EFA_STRDUP,
  930. DUMA_FAIL_ENV DUMA_PARAMS_FL);
  931. if (dup) /* if successful */
  932. for (i=0; i<=size; ++i) /* copy string */
  933. dup[i] = str[i];
  934. return dup;
  935. }
  936. /* Function: _duma_memcpy
  937. *
  938. * A version of memcpy that provides extra checks based on
  939. * information we know about HEAP.
  940. *
  941. * Currently the only check we perform is overlapping memory
  942. * regions. This should be expanded to include checking size
  943. * of dest to verify assumptions.
  944. */
  945. void * _duma_memcpy(void *dest, const void *src, size_t size DUMA_PARAMLIST_FL)
  946. {
  947. char * d = (char *)dest;
  948. const char * s = (const char *)src;
  949. unsigned i;
  950. if ( (s < d && d < s + size) || (d < s && s < d + size && !_duma_s.MEMCPY_OVERLAP) )
  951. DUMA_Abort("memcpy(%a, %a, %d): memory regions overlap.",
  952. (DUMA_ADDR)dest, (DUMA_ADDR)src, (DUMA_SIZE)size);
  953. for (i=0; i<size; ++i)
  954. d[i] = s[i];
  955. return dest;
  956. }
  957. /* Function: _duma_memmove
  958. *
  959. * An implementation of memmove is provied by Duma to prevent some optimized
  960. * memmove implementations from calling memcpy and generate false positive overlap
  961. * errors.
  962. */
  963. void * _duma_memmove(void *dest, const void *src, size_t size)
  964. {
  965. char * d = (char *)dest;
  966. const char * s = (const char *)src;
  967. if (d < s) {
  968. const char *end = src + size;
  969. while (s < end) {
  970. *d++ = *s++;
  971. }
  972. } else {
  973. d += size;
  974. s += size;
  975. while (s > (const char*)src) {
  976. *--d = *--s;
  977. }
  978. }
  979. return dest;
  980. }
  981. /* Function: _duma_strcpy
  982. *
  983. * A version of strcpy that provides extra checks based on
  984. * information we know about HEAP.
  985. *
  986. * Currently the only check we perform is overlapping memory
  987. * regions. This should be expanded to include checking size
  988. * of dest to verify assumptions.
  989. */
  990. char * _duma_strcpy(char *dest, const char *src DUMA_PARAMLIST_FL)
  991. {
  992. unsigned i;
  993. size_t size = strlen(src) +1;
  994. if ( src < dest && dest < src + size )
  995. DUMA_Abort("strcpy(%a, %a): memory regions overlap.", (DUMA_ADDR)dest, (DUMA_ADDR)src);
  996. for (i=0; i<size; ++i)
  997. dest[i] = src[i];
  998. return dest;
  999. }
  1000. /* Function: _duma_strncpy
  1001. *
  1002. * A version of strncpy that provides extra checks based on
  1003. * information we know about HEAP.
  1004. *
  1005. * Currently the only check we perform is overlapping memory
  1006. * regions. This should be expanded to include checking size
  1007. * of dest to verify assumptions.
  1008. */
  1009. char * _duma_strncpy(char *dest, const char *src, size_t size DUMA_PARAMLIST_FL)
  1010. {
  1011. size_t srcsize;
  1012. unsigned i;
  1013. if ( size > 0 && src < dest && dest < src + size )
  1014. DUMA_Abort("strncpy(%a, %a, %d): memory regions overlap.",
  1015. (DUMA_ADDR)dest, (DUMA_ADDR)src, (DUMA_SIZE)size);
  1016. /* calculate number of characters to copy from src to dest */
  1017. srcsize = strlen(src) + 1;
  1018. if ( srcsize > size )
  1019. srcsize = size;
  1020. /* copy src to dest */
  1021. for (i=0; i<srcsize; ++i)
  1022. dest[i] = src[i];
  1023. /* fill rest with '\0' character */
  1024. for ( ; i<size; ++i)
  1025. dest[i] = 0;
  1026. return dest;
  1027. }
  1028. /* Function: _duma_strcat
  1029. *
  1030. * A version of strcat that provides extra checks based on
  1031. * information we know about HEAP.
  1032. *
  1033. * Currently the only check we perform is overlapping memory
  1034. * regions. This should be expanded to include checking size
  1035. * of dest to verify assumptions.
  1036. */
  1037. char * _duma_strcat(char *dest, const char *src DUMA_PARAMLIST_FL)
  1038. {
  1039. unsigned i;
  1040. size_t destlen = strlen(dest);
  1041. size_t srcsize = strlen(src) + 1;
  1042. if ( src < dest +destlen && dest + destlen < src + srcsize )
  1043. DUMA_Abort("strcat(%a, %a): memory regions overlap.", (DUMA_ADDR)dest, (DUMA_ADDR)src);
  1044. for (i=0; i<srcsize; ++i)
  1045. dest[destlen+i] = src[i];
  1046. return dest;
  1047. }
  1048. /* Function: _duma_strncat
  1049. *
  1050. * A version of strncat that provides extra checks based on
  1051. * information we know about HEAP.
  1052. *
  1053. * Currently the only check we perform is overlapping memory
  1054. * regions. This should be expanded to include checking size
  1055. * of dest to verify assumptions (like is size right).
  1056. */
  1057. char * _duma_strncat(char *dest, const char *src, size_t size DUMA_PARAMLIST_FL)
  1058. {
  1059. unsigned i;
  1060. size_t destlen, srclen;
  1061. /* do nothing, when size not > 0 */
  1062. if ( size <= 0 )
  1063. return dest;
  1064. /* calculate number of characters to copy from src to dest */
  1065. destlen = strlen(dest);
  1066. srclen = strlen(src);
  1067. if ( srclen > size )
  1068. srclen = size;
  1069. /* CHECK: Verify memory regions do not overlap */
  1070. if ( src < (dest + destlen) && (dest + destlen) < (src + srclen + 1) )
  1071. DUMA_Abort("strncat(%a, %a, %d): memory regions overlap.",
  1072. (DUMA_ADDR)dest, (DUMA_ADDR)src, (DUMA_SIZE)size);
  1073. /* copy up to size characters from src to dest */
  1074. for (i=0; i<srclen; ++i)
  1075. dest[destlen+i] = src[i];
  1076. /* append single '\0' character */
  1077. dest[destlen+srclen] = 0;
  1078. return dest;
  1079. }
  1080. /*********************************************************/
  1081. /* Function DUMA_newFrame
  1082. *
  1083. * Increments the frameno variable. Not sure why we do this :)
  1084. */
  1085. void DUMA_newFrame(void)
  1086. {
  1087. #ifdef DUMA_USE_FRAMENO
  1088. ++frameno;
  1089. #endif
  1090. }
  1091. /* Function DUMA_delFrame
  1092. *
  1093. * Will output DUMA message for all in use frames along with totals.
  1094. * This method is called to when all memory should have been free'd by
  1095. * the application to locate memory leaks.
  1096. *
  1097. * Note: No frames are deleted or modified by this function.
  1098. */
  1099. void DUMA_delFrame(void)
  1100. {
  1101. if (-1 != frameno)
  1102. {
  1103. struct _DUMA_Slot * slot = _duma_allocList;
  1104. size_t count = slotCount;
  1105. int nonFreed = 0;
  1106. IF__DUMA_INIT_DONE
  1107. DUMA_GET_SEMAPHORE();
  1108. Page_AllowAccess(_duma_allocList, _duma_allocListSize);
  1109. for ( ; count > 0; --count, ++slot )
  1110. {
  1111. if ( DUMAST_IN_USE == slot->state
  1112. #ifdef DUMA_USE_FRAMENO
  1113. && frameno == slot->frame
  1114. #endif
  1115. && EFA_INT_ALLOC != slot->allocator
  1116. #ifdef DUMA_EXPLICIT_INIT
  1117. && -1 != slot->lineno
  1118. #endif
  1119. )
  1120. {
  1121. DUMA_Print("\nDUMA: ptr=0x%a size=%d alloced from %s(%i) not freed\n",
  1122. (DUMA_ADDR)slot->userAddress,
  1123. (DUMA_SIZE)slot->userSize,
  1124. slot->filename,
  1125. slot->lineno);
  1126. ++nonFreed;
  1127. }
  1128. }
  1129. if (nonFreed)
  1130. DUMA_Abort("DUMA_delFrame(): Found non free'd pointers.\n");
  1131. Page_DenyAccess(_duma_allocList, _duma_allocListSize);
  1132. IF__DUMA_INIT_DONE
  1133. DUMA_RELEASE_SEMAPHORE();
  1134. --frameno;
  1135. }
  1136. if (DUMA_SHOW_ALLOC)
  1137. DUMA_Print("\nDUMA: DUMA_delFrame(): Processed %l allocations and %l deallocations in total.\n", numAllocs, numDeallocs);
  1138. }
  1139. /* Function: _duma_exit
  1140. *
  1141. * DUMA's exit function, called atexit() or with GNU C Compiler's destructor attribute.
  1142. * This function also calls DUMA_delFrame to check for still in use memory and allert
  1143. * the user.
  1144. */
  1145. void
  1146. _duma_exit(void)
  1147. {
  1148. /* DUMA_ASSERT(0); */
  1149. while (-1 != frameno)
  1150. DUMA_delFrame();
  1151. }
  1152. /* end */