heaptrc.pp 32 KB

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