heaptrc.pp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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)),2*sizeof(pointer)),' 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)),2*sizeof(pointer)),' 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)),2*sizeof(pointer)),' 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)),2*sizeof(pointer)),' 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)),2*sizeof(pointer)),' 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,2*sizeof(pointer)),'"',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)),2*sizeof(pointer)),' 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 os2}
  681. (* Currently still EMX based - possibly to be changed in the future. *)
  682. var
  683. etext: ptruint; external name '_etext';
  684. edata : ptruint; external name '_edata';
  685. eend : ptruint; external name '_end';
  686. {$endif}
  687. {$ifdef win32}
  688. var
  689. sdata : ptruint; external name '__data_start__';
  690. edata : ptruint; external name '__data_end__';
  691. sbss : ptruint; external name '__bss_start__';
  692. ebss : ptruint; external name '__bss_end__';
  693. {$endif}
  694. procedure CheckPointer(p : pointer); [public, alias : 'FPC_CHECKPOINTER'];
  695. var
  696. i : ptrint;
  697. pp : pheap_mem_info;
  698. {$ifdef go32v2}
  699. get_ebp,stack_top : longword;
  700. data_end : longword;
  701. {$endif go32v2}
  702. label
  703. _exit;
  704. begin
  705. if p=nil then
  706. runerror(204);
  707. i:=0;
  708. {$ifdef go32v2}
  709. if ptruint(p)<$1000 then
  710. runerror(216);
  711. asm
  712. movl %ebp,get_ebp
  713. leal edata,%eax
  714. movl %eax,data_end
  715. end;
  716. stack_top:=__stkbottom+__stklen;
  717. { allow all between start of code and end of data }
  718. if ptruint(p)<=data_end then
  719. goto _exit;
  720. { stack can be above heap !! }
  721. if (ptruint(p)>=get_ebp) and (ptruint(p)<=stack_top) then
  722. goto _exit;
  723. {$endif go32v2}
  724. { I don't know where the stack is in other OS !! }
  725. {$ifdef win32}
  726. { inside stack ? }
  727. if (ptruint(p)>ptruint(get_frame)) and
  728. (ptruint(p)<Win32StackTop) then
  729. goto _exit;
  730. { inside data ? }
  731. if (ptruint(p)>=ptruint(@sdata)) and (ptruint(p)<ptruint(@edata)) then
  732. goto _exit;
  733. { inside bss ? }
  734. if (ptruint(p)>=ptruint(@sbss)) and (ptruint(p)<ptruint(@ebss)) then
  735. goto _exit;
  736. {$endif win32}
  737. {$IFDEF OS2}
  738. { inside stack ? }
  739. if (PtrUInt (P) > PtrUInt (Get_Frame)) and
  740. (PtrUInt (P) < StackTop) then
  741. goto _exit;
  742. { inside data or bss ? }
  743. if (PtrUInt (P) >= PtrUInt (@etext)) and (PtrUInt (P) < PtrUInt (@eend)) then
  744. goto _exit;
  745. {$ENDIF OS2}
  746. {$ifdef linux}
  747. { inside stack ? }
  748. if (ptruint(p)>ptruint(get_frame)) and
  749. (ptruint(p)<$c0000000) then //todo: 64bit!
  750. goto _exit;
  751. { inside data or bss ? }
  752. if (ptruint(p)>=ptruint(@etext)) and (ptruint(p)<ptruint(@eend)) then
  753. goto _exit;
  754. {$endif linux}
  755. { first try valid list faster }
  756. {$ifdef EXTRA}
  757. pp:=heap_valid_last;
  758. while pp<>nil do
  759. begin
  760. { inside this valid block ! }
  761. { we can be changing the extrainfo !! }
  762. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info){+extra_info_size}) and
  763. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+extra_info_size+pp^.size) then
  764. begin
  765. { check allocated block }
  766. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  767. ((pp^.sig=calculate_sig(pp)) and usecrc) or
  768. { special case of the fill_extra_info call }
  769. ((pp=heap_valid_last) and usecrc and (pp^.sig=$DEADBEEF)
  770. and inside_trace_getmem) then
  771. goto _exit
  772. else
  773. begin
  774. writeln(ptext^,'corrupted heap_mem_info');
  775. dump_error(pp,ptext^);
  776. halt(1);
  777. end;
  778. end
  779. else
  780. pp:=pp^.prev_valid;
  781. inc(i);
  782. if i>getmem_cnt-freemem_cnt then
  783. begin
  784. writeln(ptext^,'error in linked list of heap_mem_info');
  785. halt(1);
  786. end;
  787. end;
  788. i:=0;
  789. {$endif EXTRA}
  790. pp:=heap_mem_root;
  791. while pp<>nil do
  792. begin
  793. { inside this block ! }
  794. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)) and
  795. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)+ptruint(pp^.size)) then
  796. { allocated block }
  797. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  798. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  799. goto _exit
  800. else
  801. begin
  802. writeln(ptext^,'pointer $',hexstr(ptrint(p),2*sizeof(pointer)),' points into invalid memory block');
  803. dump_error(pp,ptext^);
  804. runerror(204);
  805. end;
  806. pp:=pp^.previous;
  807. inc(i);
  808. if i>getmem_cnt then
  809. begin
  810. writeln(ptext^,'error in linked list of heap_mem_info');
  811. halt(1);
  812. end;
  813. end;
  814. writeln(ptext^,'pointer $',hexstr(ptrint(p),2*sizeof(pointer)),' does not point to valid memory block');
  815. runerror(204);
  816. _exit:
  817. end;
  818. {*****************************************************************************
  819. Dump Heap
  820. *****************************************************************************}
  821. procedure dumpheap;
  822. var
  823. pp : pheap_mem_info;
  824. i : ptrint;
  825. ExpectedHeapFree : ptrint;
  826. status : TFPCHeapStatus;
  827. begin
  828. pp:=heap_mem_root;
  829. Writeln(ptext^,'Heap dump by heaptrc unit');
  830. Writeln(ptext^,getmem_cnt, ' memory blocks allocated : ',getmem_size,'/',getmem8_size);
  831. Writeln(ptext^,freemem_cnt,' memory blocks freed : ',freemem_size,'/',freemem8_size);
  832. Writeln(ptext^,getmem_cnt-freemem_cnt,' unfreed memory blocks : ',getmem_size-freemem_size);
  833. status:=SysGetFPCHeapStatus;
  834. Write(ptext^,'True heap size : ',status.CurrHeapSize);
  835. if EntryMemUsed > 0 then
  836. Writeln(ptext^,' (',EntryMemUsed,' used in System startup)')
  837. else
  838. Writeln(ptext^);
  839. Writeln(ptext^,'True free heap : ',status.CurrHeapFree);
  840. ExpectedHeapFree:=status.CurrHeapSize-(getmem8_size-freemem8_size)-
  841. (getmem_cnt-freemem_cnt)*(sizeof(theap_mem_info)+extra_info_size)-EntryMemUsed;
  842. If ExpectedHeapFree<>status.CurrHeapFree then
  843. Writeln(ptext^,'Should be : ',ExpectedHeapFree);
  844. i:=getmem_cnt-freemem_cnt;
  845. while pp<>nil do
  846. begin
  847. if i<0 then
  848. begin
  849. Writeln(ptext^,'Error in heap memory list');
  850. Writeln(ptext^,'More memory blocks than expected');
  851. exit;
  852. end;
  853. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  854. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  855. begin
  856. { this one was not released !! }
  857. if exitcode<>203 then
  858. call_stack(pp,ptext^);
  859. dec(i);
  860. end
  861. else if pp^.sig<>$AAAAAAAA then
  862. begin
  863. dump_error(pp,ptext^);
  864. {$ifdef EXTRA}
  865. dump_error(pp,error_file);
  866. {$endif EXTRA}
  867. error_in_heap:=true;
  868. end
  869. {$ifdef EXTRA}
  870. else if pp^.release_sig<>calculate_release_sig(pp) then
  871. begin
  872. dump_change_after(pp,ptext^);
  873. dump_change_after(pp,error_file);
  874. error_in_heap:=true;
  875. end
  876. {$endif EXTRA}
  877. ;
  878. pp:=pp^.previous;
  879. end;
  880. end;
  881. procedure markheap;
  882. var
  883. pp : pheap_mem_info;
  884. begin
  885. pp:=heap_mem_root;
  886. while pp<>nil do
  887. begin
  888. pp^.sig:=$AAAAAAAA;
  889. pp:=pp^.previous;
  890. end;
  891. end;
  892. {*****************************************************************************
  893. AllocMem
  894. *****************************************************************************}
  895. function TraceAllocMem(size:ptrint):Pointer;
  896. begin
  897. TraceAllocMem:=SysAllocMem(size);
  898. end;
  899. {*****************************************************************************
  900. No specific tracing calls
  901. *****************************************************************************}
  902. function TraceGetHeapStatus:THeapStatus;
  903. begin
  904. TraceGetHeapStatus:=SysGetHeapStatus;
  905. end;
  906. function TraceGetFPCHeapStatus:TFPCHeapStatus;
  907. begin
  908. TraceGetFPCHeapStatus:=SysGetFPCHeapStatus;
  909. end;
  910. {*****************************************************************************
  911. Program Hooks
  912. *****************************************************************************}
  913. Procedure SetHeapTraceOutput(const name : string);
  914. var i : ptrint;
  915. begin
  916. if ptext<>@stderr then
  917. begin
  918. ptext:=@stderr;
  919. close(ownfile);
  920. end;
  921. assign(ownfile,name);
  922. {$I-}
  923. append(ownfile);
  924. if IOResult<>0 then
  925. Rewrite(ownfile);
  926. {$I+}
  927. ptext:=@ownfile;
  928. for i:=0 to Paramcount do
  929. write(ptext^,paramstr(i),' ');
  930. writeln(ptext^);
  931. end;
  932. procedure SetHeapExtraInfo( size : ptrint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  933. begin
  934. { the total size must stay multiple of 8, also allocate 2 pointers for
  935. the fill and display procvars }
  936. exact_info_size:=size + sizeof(theap_extra_info);
  937. extra_info_size:=((exact_info_size+7) div 8)*8;
  938. fill_extra_info_proc:=fillproc;
  939. display_extra_info_proc:=displayproc;
  940. end;
  941. {*****************************************************************************
  942. Install MemoryManager
  943. *****************************************************************************}
  944. const
  945. TraceManager:TMemoryManager=(
  946. NeedLock : true;
  947. Getmem : @TraceGetMem;
  948. Freemem : @TraceFreeMem;
  949. FreememSize : @TraceFreeMemSize;
  950. AllocMem : @TraceAllocMem;
  951. ReAllocMem : @TraceReAllocMem;
  952. MemSize : @TraceMemSize;
  953. GetHeapStatus : @TraceGetHeapStatus;
  954. GetFPCHeapStatus : @TraceGetFPCHeapStatus;
  955. );
  956. procedure TraceInit;
  957. var
  958. initheapstatus : TFPCHeapStatus;
  959. begin
  960. initheapstatus:=SysGetFPCHeapStatus;
  961. EntryMemUsed:=initheapstatus.CurrHeapUsed;
  962. MakeCRC32Tbl;
  963. SetMemoryManager(TraceManager);
  964. ptext:=@stderr;
  965. if outputstr <> '' then
  966. SetHeapTraceOutput(outputstr);
  967. {$ifdef EXTRA}
  968. Assign(error_file,'heap.err');
  969. Rewrite(error_file);
  970. {$endif EXTRA}
  971. end;
  972. procedure TraceExit;
  973. begin
  974. { no dump if error
  975. because this gives long long listings }
  976. { clear inoutres, in case the program that quit didn't }
  977. ioresult;
  978. if (exitcode<>0) and (erroraddr<>nil) then
  979. begin
  980. Writeln(ptext^,'No heap dump by heaptrc unit');
  981. Writeln(ptext^,'Exitcode = ',exitcode);
  982. if ptext<>@stderr then
  983. begin
  984. ptext:=@stderr;
  985. close(ownfile);
  986. end;
  987. exit;
  988. end;
  989. if not error_in_heap then
  990. Dumpheap;
  991. if error_in_heap and (exitcode=0) then
  992. exitcode:=203;
  993. {$ifdef EXTRA}
  994. Close(error_file);
  995. {$endif EXTRA}
  996. if ptext<>@stderr then
  997. begin
  998. ptext:=@stderr;
  999. close(ownfile);
  1000. end;
  1001. end;
  1002. {$ifdef win32}
  1003. function GetEnvironmentStrings : pchar; stdcall;
  1004. external 'kernel32' name 'GetEnvironmentStringsA';
  1005. function FreeEnvironmentStrings(p : pchar) : longbool; stdcall;
  1006. external 'kernel32' name 'FreeEnvironmentStringsA';
  1007. Function GetEnv(envvar: string): string;
  1008. var
  1009. s : string;
  1010. i : ptrint;
  1011. hp,p : pchar;
  1012. begin
  1013. getenv:='';
  1014. p:=GetEnvironmentStrings;
  1015. hp:=p;
  1016. while hp^<>#0 do
  1017. begin
  1018. s:=strpas(hp);
  1019. i:=pos('=',s);
  1020. if upcase(copy(s,1,i-1))=upcase(envvar) then
  1021. begin
  1022. getenv:=copy(s,i+1,length(s)-i);
  1023. break;
  1024. end;
  1025. { next string entry}
  1026. hp:=hp+strlen(hp)+1;
  1027. end;
  1028. FreeEnvironmentStrings(p);
  1029. end;
  1030. {$else}
  1031. Function GetEnv(P:string):Pchar;
  1032. {
  1033. Searches the environment for a string with name p and
  1034. returns a pchar to it's value.
  1035. A pchar is used to accomodate for strings of length > 255
  1036. }
  1037. var
  1038. ep : ppchar;
  1039. i : ptrint;
  1040. found : boolean;
  1041. Begin
  1042. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1043. ep:=envp;
  1044. found:=false;
  1045. if ep<>nil then
  1046. begin
  1047. while (not found) and (ep^<>nil) do
  1048. begin
  1049. found:=true;
  1050. for i:=1 to length(p) do
  1051. if p[i]<>ep^[i-1] then
  1052. begin
  1053. found:=false;
  1054. break;
  1055. end;
  1056. if not found then
  1057. inc(ep);
  1058. end;
  1059. end;
  1060. if found then
  1061. getenv:=ep^+length(p)
  1062. else
  1063. getenv:=nil;
  1064. end;
  1065. {$endif}
  1066. procedure LoadEnvironment;
  1067. var
  1068. i,j : ptrint;
  1069. s : string;
  1070. begin
  1071. s:=Getenv('HEAPTRC');
  1072. if pos('keepreleased',s)>0 then
  1073. keepreleased:=true;
  1074. if pos('disabled',s)>0 then
  1075. useheaptrace:=false;
  1076. if pos('nohalt',s)>0 then
  1077. haltonerror:=false;
  1078. i:=pos('log=',s);
  1079. if i>0 then
  1080. begin
  1081. outputstr:=copy(s,i+4,255);
  1082. j:=pos(' ',outputstr);
  1083. if j=0 then
  1084. j:=length(outputstr)+1;
  1085. delete(outputstr,j,255);
  1086. end;
  1087. end;
  1088. Initialization
  1089. LoadEnvironment;
  1090. { heaptrc can be disabled from the environment }
  1091. if useheaptrace then
  1092. TraceInit;
  1093. finalization
  1094. if useheaptrace then
  1095. TraceExit;
  1096. end.