heaptrc.pp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by the Free Pascal development team.
  4. Heap tracer
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. unit heaptrc;
  12. interface
  13. {$goto on}
  14. Procedure DumpHeap;
  15. Procedure MarkHeap;
  16. { define EXTRA to add more
  17. tests :
  18. - keep all memory after release and
  19. check by CRC value if not changed after release
  20. WARNING this needs extremely much memory (PM) }
  21. type
  22. tFillExtraInfoProc = procedure(p : pointer);
  23. tdisplayextrainfoProc = procedure (var ptext : text;p : pointer);
  24. { Allows to add info pre memory block, see ppheap.pas of the compiler
  25. for example source }
  26. procedure SetHeapExtraInfo( size : ptrint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  27. { Redirection of the output to a file }
  28. procedure SetHeapTraceOutput(const name : string);
  29. const
  30. { tracing level
  31. splitted in two if memory is released !! }
  32. {$ifdef EXTRA}
  33. tracesize = 16;
  34. {$else EXTRA}
  35. tracesize = 8;
  36. {$endif EXTRA}
  37. { install heaptrc memorymanager }
  38. useheaptrace : boolean=true;
  39. { less checking }
  40. quicktrace : boolean=true;
  41. { calls halt() on error by default !! }
  42. HaltOnError : boolean = true;
  43. { set this to true if you suspect that memory
  44. is freed several times }
  45. {$ifdef EXTRA}
  46. keepreleased : boolean=true;
  47. {$else EXTRA}
  48. keepreleased : boolean=false;
  49. {$endif EXTRA}
  50. { add a small footprint at the end of memory blocks, this
  51. can check for memory overwrites at the end of a block }
  52. add_tail : boolean = true;
  53. { put crc in sig
  54. this allows to test for writing into that part }
  55. usecrc : boolean = true;
  56. implementation
  57. type
  58. pptrint = ^ptrint;
  59. const
  60. { allows to add custom info in heap_mem_info, this is the size that will
  61. be allocated for this information }
  62. extra_info_size : ptrint = 0;
  63. exact_info_size : ptrint = 0;
  64. EntryMemUsed : ptrint = 0;
  65. { function to fill this info up }
  66. fill_extra_info_proc : TFillExtraInfoProc = nil;
  67. display_extra_info_proc : TDisplayExtraInfoProc = nil;
  68. error_in_heap : boolean = false;
  69. inside_trace_getmem : boolean = false;
  70. { indicates where the output will be redirected }
  71. { only set using environment variables }
  72. outputstr : shortstring = '';
  73. type
  74. pheap_extra_info = ^theap_extra_info;
  75. theap_extra_info = record
  76. check : cardinal; { used to check if the procvar is still valid }
  77. fillproc : tfillextrainfoProc;
  78. displayproc : tdisplayextrainfoProc;
  79. data : record
  80. end;
  81. end;
  82. { warning the size of theap_mem_info
  83. must be a multiple of 8
  84. because otherwise you will get
  85. problems when releasing the usual memory part !!
  86. sizeof(theap_mem_info = 16+tracesize*4 so
  87. tracesize must be even !! PM }
  88. pheap_mem_info = ^theap_mem_info;
  89. theap_mem_info = record
  90. previous,
  91. next : pheap_mem_info;
  92. size : ptrint;
  93. sig : longword;
  94. {$ifdef EXTRA}
  95. release_sig : longword;
  96. prev_valid : pheap_mem_info;
  97. {$endif EXTRA}
  98. calls : array [1..tracesize] of pointer;
  99. exact_info_size : word;
  100. extra_info_size : word;
  101. extra_info : pheap_extra_info;
  102. end;
  103. var
  104. ptext : ^text;
  105. ownfile : text;
  106. {$ifdef EXTRA}
  107. error_file : text;
  108. heap_valid_first,
  109. heap_valid_last : pheap_mem_info;
  110. {$endif EXTRA}
  111. heap_mem_root : pheap_mem_info;
  112. getmem_cnt,
  113. freemem_cnt : ptrint;
  114. getmem_size,
  115. freemem_size : ptrint;
  116. getmem8_size,
  117. freemem8_size : ptrint;
  118. {*****************************************************************************
  119. Crc 32
  120. *****************************************************************************}
  121. var
  122. Crc32Tbl : array[0..255] of longword;
  123. procedure MakeCRC32Tbl;
  124. var
  125. crc : longword;
  126. i,n : byte;
  127. begin
  128. for i:=0 to 255 do
  129. begin
  130. crc:=i;
  131. for n:=1 to 8 do
  132. if odd(crc) then
  133. crc:=(crc shr 1) xor $edb88320
  134. else
  135. crc:=crc shr 1;
  136. Crc32Tbl[i]:=crc;
  137. end;
  138. end;
  139. Function UpdateCrc32(InitCrc:longword;var InBuf;InLen:ptrint):longword;
  140. var
  141. i : ptrint;
  142. p : pchar;
  143. begin
  144. p:=@InBuf;
  145. for i:=1 to InLen do
  146. begin
  147. InitCrc:=Crc32Tbl[byte(InitCrc) xor byte(p^)] xor (InitCrc shr 8);
  148. inc(p);
  149. end;
  150. UpdateCrc32:=InitCrc;
  151. end;
  152. Function calculate_sig(p : pheap_mem_info) : longword;
  153. var
  154. crc : longword;
  155. pl : pptrint;
  156. begin
  157. crc:=cardinal($ffffffff);
  158. crc:=UpdateCrc32(crc,p^.size,sizeof(ptrint));
  159. crc:=UpdateCrc32(crc,p^.calls,tracesize*sizeof(ptrint));
  160. if p^.extra_info_size>0 then
  161. crc:=UpdateCrc32(crc,p^.extra_info^,p^.exact_info_size);
  162. if add_tail then
  163. begin
  164. { Check also 4 bytes just after allocation !! }
  165. pl:=pointer(p)+p^.extra_info_size+sizeof(theap_mem_info)+p^.size;
  166. crc:=UpdateCrc32(crc,pl^,sizeof(ptrint));
  167. end;
  168. calculate_sig:=crc;
  169. end;
  170. {$ifdef EXTRA}
  171. Function calculate_release_sig(p : pheap_mem_info) : longword;
  172. var
  173. crc : longword;
  174. pl : pptrint;
  175. begin
  176. crc:=$ffffffff;
  177. crc:=UpdateCrc32(crc,p^.size,sizeof(ptrint));
  178. crc:=UpdateCrc32(crc,p^.calls,tracesize*sizeof(ptrint));
  179. if p^.extra_info_size>0 then
  180. crc:=UpdateCrc32(crc,p^.extra_info^,p^.exact_info_size);
  181. { Check the whole of the whole allocation }
  182. pl:=pointer(p)+p^.extra_info_size+sizeof(theap_mem_info);
  183. crc:=UpdateCrc32(crc,pl^,p^.size);
  184. { Check also 4 bytes just after allocation !! }
  185. if add_tail then
  186. begin
  187. { Check also 4 bytes just after allocation !! }
  188. pl:=pointer(p)+p^.extra_info_size+sizeof(theap_mem_info)+p^.size;
  189. crc:=UpdateCrc32(crc,pl^,sizeof(ptrint));
  190. end;
  191. calculate_release_sig:=crc;
  192. end;
  193. {$endif EXTRA}
  194. {*****************************************************************************
  195. Helpers
  196. *****************************************************************************}
  197. procedure call_stack(pp : pheap_mem_info;var ptext : text);
  198. var
  199. i : ptrint;
  200. begin
  201. writeln(ptext,'Call trace for block $',hexstr(ptrint(pointer(pp)+sizeof(theap_mem_info)),8),' size ',pp^.size);
  202. for i:=1 to tracesize do
  203. if pp^.calls[i]<>nil then
  204. writeln(ptext,BackTraceStrFunc(pp^.calls[i]));
  205. { the check is done to be sure that the procvar is not overwritten }
  206. if assigned(pp^.extra_info) and
  207. (pp^.extra_info^.check=$12345678) and
  208. assigned(pp^.extra_info^.displayproc) then
  209. pp^.extra_info^.displayproc(ptext,@pp^.extra_info^.data);
  210. end;
  211. procedure call_free_stack(pp : pheap_mem_info;var ptext : text);
  212. var
  213. i : ptrint;
  214. begin
  215. writeln(ptext,'Call trace for block at $',hexstr(ptrint(pointer(pp)+sizeof(theap_mem_info)),8),' size ',pp^.size);
  216. for i:=1 to tracesize div 2 do
  217. if pp^.calls[i]<>nil then
  218. writeln(ptext,BackTraceStrFunc(pp^.calls[i]));
  219. writeln(ptext,' was released at ');
  220. for i:=(tracesize div 2)+1 to tracesize do
  221. if pp^.calls[i]<>nil then
  222. writeln(ptext,BackTraceStrFunc(pp^.calls[i]));
  223. { the check is done to be sure that the procvar is not overwritten }
  224. if assigned(pp^.extra_info) and
  225. (pp^.extra_info^.check=$12345678) and
  226. assigned(pp^.extra_info^.displayproc) then
  227. pp^.extra_info^.displayproc(ptext,@pp^.extra_info^.data);
  228. end;
  229. procedure dump_already_free(p : pheap_mem_info;var ptext : text);
  230. begin
  231. Writeln(ptext,'Marked memory at $',HexStr(ptrint(pointer(p)+sizeof(theap_mem_info)),8),' released');
  232. call_free_stack(p,ptext);
  233. Writeln(ptext,'freed again at');
  234. dump_stack(ptext,get_caller_frame(get_frame));
  235. end;
  236. procedure dump_error(p : pheap_mem_info;var ptext : text);
  237. begin
  238. Writeln(ptext,'Marked memory at $',HexStr(ptrint(pointer(p)+sizeof(theap_mem_info)),8),' invalid');
  239. Writeln(ptext,'Wrong signature $',hexstr(p^.sig,8),' instead of ',hexstr(calculate_sig(p),8));
  240. dump_stack(ptext,get_caller_frame(get_frame));
  241. end;
  242. {$ifdef EXTRA}
  243. procedure dump_change_after(p : pheap_mem_info;var ptext : text);
  244. var pp : pchar;
  245. i : ptrint;
  246. begin
  247. Writeln(ptext,'Marked memory at $',HexStr(ptrint(pointer(p)+sizeof(theap_mem_info)),8),' invalid');
  248. Writeln(ptext,'Wrong release CRC $',hexstr(p^.release_sig,8),' instead of ',hexstr(calculate_release_sig(p),8));
  249. Writeln(ptext,'This memory was changed after call to freemem !');
  250. call_free_stack(p,ptext);
  251. pp:=pointer(p)+sizeof(theap_mem_info);
  252. for i:=0 to p^.size-1 do
  253. if byte(pp[i])<>$F0 then
  254. Writeln(ptext,'offset',i,':$',hexstr(i,8),'"',pp[i],'"');
  255. end;
  256. {$endif EXTRA}
  257. procedure dump_wrong_size(p : pheap_mem_info;size : ptrint;var ptext : text);
  258. begin
  259. Writeln(ptext,'Marked memory at $',HexStr(ptrint(pointer(p)+sizeof(theap_mem_info)),8),' invalid');
  260. Writeln(ptext,'Wrong size : ',p^.size,' allocated ',size,' freed');
  261. dump_stack(ptext,get_caller_frame(get_frame));
  262. { the check is done to be sure that the procvar is not overwritten }
  263. if assigned(p^.extra_info) and
  264. (p^.extra_info^.check=$12345678) and
  265. assigned(p^.extra_info^.displayproc) then
  266. p^.extra_info^.displayproc(ptext,@p^.extra_info^.data);
  267. call_stack(p,ptext);
  268. end;
  269. function is_in_getmem_list (p : pheap_mem_info) : boolean;
  270. var
  271. i : ptrint;
  272. pp : pheap_mem_info;
  273. begin
  274. is_in_getmem_list:=false;
  275. pp:=heap_mem_root;
  276. i:=0;
  277. while pp<>nil do
  278. begin
  279. if ((pp^.sig<>$DEADBEEF) or usecrc) and
  280. ((pp^.sig<>calculate_sig(pp)) or not usecrc) and
  281. (pp^.sig <>$AAAAAAAA) then
  282. begin
  283. writeln(ptext^,'error in linked list of heap_mem_info');
  284. RunError(204);
  285. end;
  286. if pp=p then
  287. is_in_getmem_list:=true;
  288. pp:=pp^.previous;
  289. inc(i);
  290. if i>getmem_cnt-freemem_cnt then
  291. writeln(ptext^,'error in linked list of heap_mem_info');
  292. end;
  293. end;
  294. {*****************************************************************************
  295. TraceGetMem
  296. *****************************************************************************}
  297. Function TraceGetMem(size:ptrint):pointer;
  298. var
  299. allocsize,i : ptrint;
  300. oldbp,
  301. bp : pointer;
  302. pl : pdword;
  303. p : pointer;
  304. pp : pheap_mem_info;
  305. begin
  306. inc(getmem_size,size);
  307. inc(getmem8_size,((size+7) div 8)*8);
  308. { Do the real GetMem, but alloc also for the info block }
  309. allocsize:=size+sizeof(theap_mem_info)+extra_info_size;
  310. if add_tail then
  311. inc(allocsize,sizeof(ptrint));
  312. p:=SysGetMem(allocsize);
  313. pp:=pheap_mem_info(p);
  314. inc(p,sizeof(theap_mem_info));
  315. { Create the info block }
  316. pp^.sig:=$DEADBEEF;
  317. pp^.size:=size;
  318. pp^.extra_info_size:=extra_info_size;
  319. pp^.exact_info_size:=exact_info_size;
  320. {
  321. the end of the block contains:
  322. <tail> 4 bytes
  323. <extra_info> X bytes
  324. }
  325. if extra_info_size>0 then
  326. begin
  327. pp^.extra_info:=pointer(pp)+allocsize-extra_info_size;
  328. fillchar(pp^.extra_info^,extra_info_size,0);
  329. pp^.extra_info^.check:=$12345678;
  330. pp^.extra_info^.fillproc:=fill_extra_info_proc;
  331. pp^.extra_info^.displayproc:=display_extra_info_proc;
  332. if assigned(fill_extra_info_proc) then
  333. begin
  334. inside_trace_getmem:=true;
  335. fill_extra_info_proc(@pp^.extra_info^.data);
  336. inside_trace_getmem:=false;
  337. end;
  338. end
  339. else
  340. pp^.extra_info:=nil;
  341. if add_tail then
  342. begin
  343. pl:=pointer(pp)+allocsize-pp^.extra_info_size-sizeof(ptrint);
  344. pl^:=$DEADBEEF;
  345. end;
  346. { clear the memory }
  347. fillchar(p^,size,#255);
  348. { retrieve backtrace info }
  349. bp:=get_caller_frame(get_frame);
  350. for i:=1 to tracesize do
  351. begin
  352. pp^.calls[i]:=get_caller_addr(bp);
  353. oldbp:=bp;
  354. bp:=get_caller_frame(bp);
  355. if (bp<oldbp) or (bp>(StackBottom + StackLength)) then
  356. bp:=nil;
  357. end;
  358. { insert in the linked list }
  359. if heap_mem_root<>nil then
  360. heap_mem_root^.next:=pp;
  361. pp^.previous:=heap_mem_root;
  362. pp^.next:=nil;
  363. {$ifdef EXTRA}
  364. pp^.prev_valid:=heap_valid_last;
  365. heap_valid_last:=pp;
  366. if not assigned(heap_valid_first) then
  367. heap_valid_first:=pp;
  368. {$endif EXTRA}
  369. heap_mem_root:=pp;
  370. { must be changed before fill_extra_info is called
  371. because checkpointer can be called from within
  372. fill_extra_info PM }
  373. inc(getmem_cnt);
  374. { update the signature }
  375. if usecrc then
  376. pp^.sig:=calculate_sig(pp);
  377. TraceGetmem:=p;
  378. end;
  379. {*****************************************************************************
  380. TraceFreeMem
  381. *****************************************************************************}
  382. function TraceFreeMemSize(p:pointer;size:ptrint):ptrint;
  383. var
  384. i,ppsize : ptrint;
  385. bp : pointer;
  386. pp : pheap_mem_info;
  387. {$ifdef EXTRA}
  388. pp2 : pheap_mem_info;
  389. {$endif}
  390. extra_size : ptrint;
  391. begin
  392. if p=nil then
  393. begin
  394. TraceFreeMemSize:=0;
  395. exit;
  396. end;
  397. inc(freemem_size,size);
  398. inc(freemem8_size,((size+7) div 8)*8);
  399. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  400. ppsize:= size + sizeof(theap_mem_info)+pp^.extra_info_size;
  401. if add_tail then
  402. inc(ppsize,sizeof(ptrint));
  403. if not quicktrace then
  404. begin
  405. if not(is_in_getmem_list(pp)) then
  406. RunError(204);
  407. end;
  408. if (pp^.sig=$AAAAAAAA) and not usecrc then
  409. begin
  410. error_in_heap:=true;
  411. dump_already_free(pp,ptext^);
  412. if haltonerror then halt(1);
  413. end
  414. else if ((pp^.sig<>$DEADBEEF) or usecrc) and
  415. ((pp^.sig<>calculate_sig(pp)) or not usecrc) then
  416. begin
  417. error_in_heap:=true;
  418. dump_error(pp,ptext^);
  419. {$ifdef EXTRA}
  420. dump_error(pp,error_file);
  421. {$endif EXTRA}
  422. { don't release anything in this case !! }
  423. if haltonerror then halt(1);
  424. exit;
  425. end
  426. else if pp^.size<>size then
  427. begin
  428. error_in_heap:=true;
  429. dump_wrong_size(pp,size,ptext^);
  430. {$ifdef EXTRA}
  431. dump_wrong_size(pp,size,error_file);
  432. {$endif EXTRA}
  433. if haltonerror then halt(1);
  434. { don't release anything in this case !! }
  435. exit;
  436. end;
  437. { save old values }
  438. extra_size:=pp^.extra_info_size;
  439. { now it is released !! }
  440. pp^.sig:=$AAAAAAAA;
  441. if not keepreleased then
  442. begin
  443. if pp^.next<>nil then
  444. pp^.next^.previous:=pp^.previous;
  445. if pp^.previous<>nil then
  446. pp^.previous^.next:=pp^.next;
  447. if pp=heap_mem_root then
  448. heap_mem_root:=heap_mem_root^.previous;
  449. end
  450. else
  451. begin
  452. bp:=get_caller_frame(get_frame);
  453. for i:=(tracesize div 2)+1 to tracesize do
  454. begin
  455. pp^.calls[i]:=get_caller_addr(bp);
  456. bp:=get_caller_frame(bp);
  457. end;
  458. end;
  459. inc(freemem_cnt);
  460. { clear the memory }
  461. fillchar(p^,size,#240); { $F0 will lead to GFP if used as pointer ! }
  462. { this way we keep all info about all released memory !! }
  463. if keepreleased then
  464. begin
  465. {$ifdef EXTRA}
  466. { We want to check if the memory was changed after release !! }
  467. pp^.release_sig:=calculate_release_sig(pp);
  468. if pp=heap_valid_last then
  469. begin
  470. heap_valid_last:=pp^.prev_valid;
  471. if pp=heap_valid_first then
  472. heap_valid_first:=nil;
  473. TraceFreememsize:=size;
  474. exit;
  475. end;
  476. pp2:=heap_valid_last;
  477. while assigned(pp2) do
  478. begin
  479. if pp2^.prev_valid=pp then
  480. begin
  481. pp2^.prev_valid:=pp^.prev_valid;
  482. if pp=heap_valid_first then
  483. heap_valid_first:=pp2;
  484. TraceFreememsize:=size;
  485. exit;
  486. end
  487. else
  488. pp2:=pp2^.prev_valid;
  489. end;
  490. {$endif EXTRA}
  491. TraceFreememsize:=size;
  492. exit;
  493. end;
  494. { release the normal memory at least }
  495. i:=SysFreeMemSize(pp,ppsize);
  496. { return the correct size }
  497. dec(i,sizeof(theap_mem_info)+extra_size);
  498. if add_tail then
  499. dec(i,sizeof(ptrint));
  500. TraceFreeMemSize:=i;
  501. end;
  502. function TraceMemSize(p:pointer):ptrint;
  503. var
  504. pp : pheap_mem_info;
  505. begin
  506. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  507. TraceMemSize:=pp^.size;
  508. end;
  509. function TraceFreeMem(p:pointer):ptrint;
  510. var
  511. l : ptrint;
  512. pp : pheap_mem_info;
  513. begin
  514. if p=nil then
  515. begin
  516. TraceFreeMem:=0;
  517. exit;
  518. end;
  519. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  520. l:=SysMemSize(pp);
  521. dec(l,sizeof(theap_mem_info)+pp^.extra_info_size);
  522. if add_tail then
  523. dec(l,sizeof(ptrint));
  524. { this can never happend normaly }
  525. if pp^.size>l then
  526. begin
  527. dump_wrong_size(pp,l,ptext^);
  528. {$ifdef EXTRA}
  529. dump_wrong_size(pp,l,error_file);
  530. {$endif EXTRA}
  531. end;
  532. TraceFreeMem:=TraceFreeMemSize(p,pp^.size);
  533. end;
  534. {*****************************************************************************
  535. ReAllocMem
  536. *****************************************************************************}
  537. function TraceReAllocMem(var p:pointer;size:ptrint):Pointer;
  538. var
  539. newP: pointer;
  540. allocsize,
  541. movesize,
  542. i : ptrint;
  543. bp : pointer;
  544. pl : pdword;
  545. pp : pheap_mem_info;
  546. oldsize,
  547. oldextrasize,
  548. oldexactsize : ptrint;
  549. old_fill_extra_info_proc : tfillextrainfoproc;
  550. old_display_extra_info_proc : tdisplayextrainfoproc;
  551. begin
  552. { Free block? }
  553. if size=0 then
  554. begin
  555. if p<>nil then
  556. TraceFreeMem(p);
  557. p:=nil;
  558. TraceReallocMem:=P;
  559. exit;
  560. end;
  561. { Allocate a new block? }
  562. if p=nil then
  563. begin
  564. p:=TraceGetMem(size);
  565. TraceReallocMem:=P;
  566. exit;
  567. end;
  568. { Resize block }
  569. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  570. { test block }
  571. if ((pp^.sig<>$DEADBEEF) or usecrc) and
  572. ((pp^.sig<>calculate_sig(pp)) or not usecrc) then
  573. begin
  574. error_in_heap:=true;
  575. dump_error(pp,ptext^);
  576. {$ifdef EXTRA}
  577. dump_error(pp,error_file);
  578. {$endif EXTRA}
  579. { don't release anything in this case !! }
  580. if haltonerror then halt(1);
  581. exit;
  582. end;
  583. { save info }
  584. oldsize:=pp^.size;
  585. oldextrasize:=pp^.extra_info_size;
  586. oldexactsize:=pp^.exact_info_size;
  587. if pp^.extra_info_size>0 then
  588. begin
  589. old_fill_extra_info_proc:=pp^.extra_info^.fillproc;
  590. old_display_extra_info_proc:=pp^.extra_info^.displayproc;
  591. end;
  592. { Do the real ReAllocMem, but alloc also for the info block }
  593. allocsize:=size+sizeof(theap_mem_info)+pp^.extra_info_size;
  594. if add_tail then
  595. inc(allocsize,sizeof(ptrint));
  596. { Try to resize the block, if not possible we need to do a
  597. getmem, move data, freemem }
  598. if not SysTryResizeMem(pp,allocsize) then
  599. begin
  600. { get a new block }
  601. newP := TraceGetMem(size);
  602. { move the data }
  603. if newP <> nil then
  604. begin
  605. movesize:=TraceMemSize(p);
  606. {if the old size is larger than the new size,
  607. move only the new size}
  608. if movesize>size then
  609. movesize:=size;
  610. move(p^,newP^,movesize);
  611. end;
  612. { release p }
  613. traceFreeMem(p);
  614. { return the new pointer }
  615. p:=newp;
  616. traceReAllocMem := newp;
  617. exit;
  618. end;
  619. { Recreate the info block }
  620. pp^.sig:=$DEADBEEF;
  621. pp^.size:=size;
  622. pp^.extra_info_size:=oldextrasize;
  623. pp^.exact_info_size:=oldexactsize;
  624. { add the new extra_info and tail }
  625. if pp^.extra_info_size>0 then
  626. begin
  627. pp^.extra_info:=pointer(pp)+allocsize-pp^.extra_info_size;
  628. fillchar(pp^.extra_info^,extra_info_size,0);
  629. pp^.extra_info^.check:=$12345678;
  630. pp^.extra_info^.fillproc:=old_fill_extra_info_proc;
  631. pp^.extra_info^.displayproc:=old_display_extra_info_proc;
  632. if assigned(pp^.extra_info^.fillproc) then
  633. pp^.extra_info^.fillproc(@pp^.extra_info^.data);
  634. end
  635. else
  636. pp^.extra_info:=nil;
  637. if add_tail then
  638. begin
  639. pl:=pointer(pp)+allocsize-pp^.extra_info_size-sizeof(ptrint);
  640. pl^:=$DEADBEEF;
  641. end;
  642. { adjust like a freemem and then a getmem, so you get correct
  643. results in the summary display }
  644. inc(freemem_size,oldsize);
  645. inc(freemem8_size,((oldsize+7) div 8)*8);
  646. inc(getmem_size,size);
  647. inc(getmem8_size,((size+7) div 8)*8);
  648. { generate new backtrace }
  649. bp:=get_caller_frame(get_frame);
  650. for i:=1 to tracesize do
  651. begin
  652. pp^.calls[i]:=get_caller_addr(bp);
  653. bp:=get_caller_frame(bp);
  654. end;
  655. { regenerate signature }
  656. if usecrc then
  657. pp^.sig:=calculate_sig(pp);
  658. { return the pointer }
  659. p:=pointer(pp)+sizeof(theap_mem_info);
  660. TraceReAllocmem:=p;
  661. end;
  662. {*****************************************************************************
  663. Check pointer
  664. *****************************************************************************}
  665. {$ifndef Unix}
  666. {$S-}
  667. {$endif}
  668. {$ifdef go32v2}
  669. var
  670. __stklen : longword;external name '__stklen';
  671. __stkbottom : longword;external name '__stkbottom';
  672. edata : longword; external name 'edata';
  673. {$endif go32v2}
  674. {$ifdef linux}
  675. var
  676. etext: ptruint; external name '_etext';
  677. edata : ptruint; external name '_edata';
  678. eend : ptruint; external name '_end';
  679. {$endif}
  680. {$ifdef win32}
  681. var
  682. sdata : ptruint; external name '__data_start__';
  683. edata : ptruint; external name '__data_end__';
  684. sbss : ptruint; external name '__bss_start__';
  685. ebss : ptruint; external name '__bss_end__';
  686. {$endif}
  687. procedure CheckPointer(p : pointer); [public, alias : 'FPC_CHECKPOINTER'];
  688. var
  689. i : ptrint;
  690. pp : pheap_mem_info;
  691. {$ifdef go32v2}
  692. get_ebp,stack_top : longword;
  693. data_end : longword;
  694. {$endif go32v2}
  695. label
  696. _exit;
  697. begin
  698. if p=nil then
  699. runerror(204);
  700. i:=0;
  701. {$ifdef go32v2}
  702. if ptruint(p)<$1000 then
  703. runerror(216);
  704. asm
  705. movl %ebp,get_ebp
  706. leal edata,%eax
  707. movl %eax,data_end
  708. end;
  709. stack_top:=__stkbottom+__stklen;
  710. { allow all between start of code and end of data }
  711. if ptruint(p)<=data_end then
  712. goto _exit;
  713. { stack can be above heap !! }
  714. if (ptruint(p)>=get_ebp) and (ptruint(p)<=stack_top) then
  715. goto _exit;
  716. {$endif go32v2}
  717. { I don't know where the stack is in other OS !! }
  718. {$ifdef win32}
  719. { inside stack ? }
  720. if (ptruint(p)>ptruint(get_frame)) and
  721. (ptruint(p)<Win32StackTop) then
  722. goto _exit;
  723. { inside data ? }
  724. if (ptruint(p)>=ptruint(@sdata)) and (ptruint(p)<ptruint(@edata)) then
  725. goto _exit;
  726. { inside bss ? }
  727. if (ptruint(p)>=ptruint(@sbss)) and (ptruint(p)<ptruint(@ebss)) then
  728. goto _exit;
  729. {$endif win32}
  730. {$ifdef linux}
  731. { inside stack ? }
  732. if (ptruint(p)>ptruint(get_frame)) and
  733. (ptruint(p)<$c0000000) then //todo: 64bit!
  734. goto _exit;
  735. { inside data or bss ? }
  736. if (ptruint(p)>=ptruint(@etext)) and (ptruint(p)<ptruint(@eend)) then
  737. goto _exit;
  738. {$endif linux}
  739. { first try valid list faster }
  740. {$ifdef EXTRA}
  741. pp:=heap_valid_last;
  742. while pp<>nil do
  743. begin
  744. { inside this valid block ! }
  745. { we can be changing the extrainfo !! }
  746. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info){+extra_info_size}) and
  747. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+extra_info_size+pp^.size) then
  748. begin
  749. { check allocated block }
  750. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  751. ((pp^.sig=calculate_sig(pp)) and usecrc) or
  752. { special case of the fill_extra_info call }
  753. ((pp=heap_valid_last) and usecrc and (pp^.sig=$DEADBEEF)
  754. and inside_trace_getmem) then
  755. goto _exit
  756. else
  757. begin
  758. writeln(ptext^,'corrupted heap_mem_info');
  759. dump_error(pp,ptext^);
  760. halt(1);
  761. end;
  762. end
  763. else
  764. pp:=pp^.prev_valid;
  765. inc(i);
  766. if i>getmem_cnt-freemem_cnt then
  767. begin
  768. writeln(ptext^,'error in linked list of heap_mem_info');
  769. halt(1);
  770. end;
  771. end;
  772. i:=0;
  773. {$endif EXTRA}
  774. pp:=heap_mem_root;
  775. while pp<>nil do
  776. begin
  777. { inside this block ! }
  778. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)) and
  779. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)+ptruint(pp^.size)) then
  780. { allocated block }
  781. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  782. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  783. goto _exit
  784. else
  785. begin
  786. writeln(ptext^,'pointer $',hexstr(ptrint(p),8),' points into invalid memory block');
  787. dump_error(pp,ptext^);
  788. runerror(204);
  789. end;
  790. pp:=pp^.previous;
  791. inc(i);
  792. if i>getmem_cnt then
  793. begin
  794. writeln(ptext^,'error in linked list of heap_mem_info');
  795. halt(1);
  796. end;
  797. end;
  798. writeln(ptext^,'pointer $',hexstr(ptrint(p),8),' does not point to valid memory block');
  799. runerror(204);
  800. _exit:
  801. end;
  802. {*****************************************************************************
  803. Dump Heap
  804. *****************************************************************************}
  805. procedure dumpheap;
  806. var
  807. pp : pheap_mem_info;
  808. i : ptrint;
  809. ExpectedHeapFree : ptrint;
  810. status : TFPCHeapStatus;
  811. begin
  812. pp:=heap_mem_root;
  813. Writeln(ptext^,'Heap dump by heaptrc unit');
  814. Writeln(ptext^,getmem_cnt, ' memory blocks allocated : ',getmem_size,'/',getmem8_size);
  815. Writeln(ptext^,freemem_cnt,' memory blocks freed : ',freemem_size,'/',freemem8_size);
  816. Writeln(ptext^,getmem_cnt-freemem_cnt,' unfreed memory blocks : ',getmem_size-freemem_size);
  817. status:=SysGetFPCHeapStatus;
  818. Write(ptext^,'True heap size : ',status.CurrHeapSize);
  819. if EntryMemUsed > 0 then
  820. Writeln(ptext^,' (',EntryMemUsed,' used in System startup)')
  821. else
  822. Writeln(ptext^);
  823. Writeln(ptext^,'True free heap : ',status.CurrHeapFree);
  824. ExpectedHeapFree:=status.CurrHeapSize-(getmem8_size-freemem8_size)-
  825. (getmem_cnt-freemem_cnt)*(sizeof(theap_mem_info)+extra_info_size)-EntryMemUsed;
  826. If ExpectedHeapFree<>status.CurrHeapFree then
  827. Writeln(ptext^,'Should be : ',ExpectedHeapFree);
  828. i:=getmem_cnt-freemem_cnt;
  829. while pp<>nil do
  830. begin
  831. if i<0 then
  832. begin
  833. Writeln(ptext^,'Error in heap memory list');
  834. Writeln(ptext^,'More memory blocks than expected');
  835. exit;
  836. end;
  837. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  838. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  839. begin
  840. { this one was not released !! }
  841. if exitcode<>203 then
  842. call_stack(pp,ptext^);
  843. dec(i);
  844. end
  845. else if pp^.sig<>$AAAAAAAA then
  846. begin
  847. dump_error(pp,ptext^);
  848. {$ifdef EXTRA}
  849. dump_error(pp,error_file);
  850. {$endif EXTRA}
  851. error_in_heap:=true;
  852. end
  853. {$ifdef EXTRA}
  854. else if pp^.release_sig<>calculate_release_sig(pp) then
  855. begin
  856. dump_change_after(pp,ptext^);
  857. dump_change_after(pp,error_file);
  858. error_in_heap:=true;
  859. end
  860. {$endif EXTRA}
  861. ;
  862. pp:=pp^.previous;
  863. end;
  864. end;
  865. procedure markheap;
  866. var
  867. pp : pheap_mem_info;
  868. begin
  869. pp:=heap_mem_root;
  870. while pp<>nil do
  871. begin
  872. pp^.sig:=$AAAAAAAA;
  873. pp:=pp^.previous;
  874. end;
  875. end;
  876. {*****************************************************************************
  877. AllocMem
  878. *****************************************************************************}
  879. function TraceAllocMem(size:ptrint):Pointer;
  880. begin
  881. TraceAllocMem:=SysAllocMem(size);
  882. end;
  883. {*****************************************************************************
  884. No specific tracing calls
  885. *****************************************************************************}
  886. function TraceGetHeapStatus:THeapStatus;
  887. begin
  888. TraceGetHeapStatus:=SysGetHeapStatus;
  889. end;
  890. function TraceGetFPCHeapStatus:TFPCHeapStatus;
  891. begin
  892. TraceGetFPCHeapStatus:=SysGetFPCHeapStatus;
  893. end;
  894. {*****************************************************************************
  895. Program Hooks
  896. *****************************************************************************}
  897. Procedure SetHeapTraceOutput(const name : string);
  898. var i : ptrint;
  899. begin
  900. if ptext<>@stderr then
  901. begin
  902. ptext:=@stderr;
  903. close(ownfile);
  904. end;
  905. assign(ownfile,name);
  906. {$I-}
  907. append(ownfile);
  908. if IOResult<>0 then
  909. Rewrite(ownfile);
  910. {$I+}
  911. ptext:=@ownfile;
  912. for i:=0 to Paramcount do
  913. write(ptext^,paramstr(i),' ');
  914. writeln(ptext^);
  915. end;
  916. procedure SetHeapExtraInfo( size : ptrint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  917. begin
  918. { the total size must stay multiple of 8, also allocate 2 pointers for
  919. the fill and display procvars }
  920. exact_info_size:=size + sizeof(theap_extra_info);
  921. extra_info_size:=((exact_info_size+7) div 8)*8;
  922. fill_extra_info_proc:=fillproc;
  923. display_extra_info_proc:=displayproc;
  924. end;
  925. {*****************************************************************************
  926. Install MemoryManager
  927. *****************************************************************************}
  928. const
  929. TraceManager:TMemoryManager=(
  930. NeedLock : true;
  931. Getmem : @TraceGetMem;
  932. Freemem : @TraceFreeMem;
  933. FreememSize : @TraceFreeMemSize;
  934. AllocMem : @TraceAllocMem;
  935. ReAllocMem : @TraceReAllocMem;
  936. MemSize : @TraceMemSize;
  937. GetHeapStatus : @TraceGetHeapStatus;
  938. GetFPCHeapStatus : @TraceGetFPCHeapStatus;
  939. );
  940. procedure TraceInit;
  941. var
  942. initheapstatus : TFPCHeapStatus;
  943. begin
  944. initheapstatus:=SysGetFPCHeapStatus;
  945. EntryMemUsed:=initheapstatus.CurrHeapUsed;
  946. MakeCRC32Tbl;
  947. SetMemoryManager(TraceManager);
  948. ptext:=@stderr;
  949. if outputstr <> '' then
  950. SetHeapTraceOutput(outputstr);
  951. {$ifdef EXTRA}
  952. Assign(error_file,'heap.err');
  953. Rewrite(error_file);
  954. {$endif EXTRA}
  955. end;
  956. procedure TraceExit;
  957. begin
  958. { no dump if error
  959. because this gives long long listings }
  960. { clear inoutres, in case the program that quit didn't }
  961. ioresult;
  962. if (exitcode<>0) and (erroraddr<>nil) then
  963. begin
  964. Writeln(ptext^,'No heap dump by heaptrc unit');
  965. Writeln(ptext^,'Exitcode = ',exitcode);
  966. if ptext<>@stderr then
  967. begin
  968. ptext:=@stderr;
  969. close(ownfile);
  970. end;
  971. exit;
  972. end;
  973. if not error_in_heap then
  974. Dumpheap;
  975. if error_in_heap and (exitcode=0) then
  976. exitcode:=203;
  977. {$ifdef EXTRA}
  978. Close(error_file);
  979. {$endif EXTRA}
  980. if ptext<>@stderr then
  981. begin
  982. ptext:=@stderr;
  983. close(ownfile);
  984. end;
  985. end;
  986. {$ifdef win32}
  987. function GetEnvironmentStrings : pchar; stdcall;
  988. external 'kernel32' name 'GetEnvironmentStringsA';
  989. function FreeEnvironmentStrings(p : pchar) : longbool; stdcall;
  990. external 'kernel32' name 'FreeEnvironmentStringsA';
  991. Function GetEnv(envvar: string): string;
  992. var
  993. s : string;
  994. i : ptrint;
  995. hp,p : pchar;
  996. begin
  997. getenv:='';
  998. p:=GetEnvironmentStrings;
  999. hp:=p;
  1000. while hp^<>#0 do
  1001. begin
  1002. s:=strpas(hp);
  1003. i:=pos('=',s);
  1004. if upcase(copy(s,1,i-1))=upcase(envvar) then
  1005. begin
  1006. getenv:=copy(s,i+1,length(s)-i);
  1007. break;
  1008. end;
  1009. { next string entry}
  1010. hp:=hp+strlen(hp)+1;
  1011. end;
  1012. FreeEnvironmentStrings(p);
  1013. end;
  1014. {$else}
  1015. Function GetEnv(P:string):Pchar;
  1016. {
  1017. Searches the environment for a string with name p and
  1018. returns a pchar to it's value.
  1019. A pchar is used to accomodate for strings of length > 255
  1020. }
  1021. var
  1022. ep : ppchar;
  1023. i : ptrint;
  1024. found : boolean;
  1025. Begin
  1026. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1027. ep:=envp;
  1028. found:=false;
  1029. if ep<>nil then
  1030. begin
  1031. while (not found) and (ep^<>nil) do
  1032. begin
  1033. found:=true;
  1034. for i:=1 to length(p) do
  1035. if p[i]<>ep^[i-1] then
  1036. begin
  1037. found:=false;
  1038. break;
  1039. end;
  1040. if not found then
  1041. inc(ep);
  1042. end;
  1043. end;
  1044. if found then
  1045. getenv:=ep^+length(p)
  1046. else
  1047. getenv:=nil;
  1048. end;
  1049. {$endif}
  1050. procedure LoadEnvironment;
  1051. var
  1052. i,j : ptrint;
  1053. s : string;
  1054. begin
  1055. s:=Getenv('HEAPTRC');
  1056. if pos('keepreleased',s)>0 then
  1057. keepreleased:=true;
  1058. if pos('disabled',s)>0 then
  1059. useheaptrace:=false;
  1060. if pos('nohalt',s)>0 then
  1061. haltonerror:=false;
  1062. i:=pos('log=',s);
  1063. if i>0 then
  1064. begin
  1065. outputstr:=copy(s,i+4,255);
  1066. j:=pos(' ',outputstr);
  1067. if j=0 then
  1068. j:=length(outputstr)+1;
  1069. delete(outputstr,j,255);
  1070. end;
  1071. end;
  1072. Initialization
  1073. LoadEnvironment;
  1074. { heaptrc can be disabled from the environment }
  1075. if useheaptrace then
  1076. TraceInit;
  1077. finalization
  1078. if useheaptrace then
  1079. TraceExit;
  1080. end.