heaptrc.pp 32 KB

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