heaptrc.pp 33 KB

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