heaptrc.pp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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. procedure CheckPointer(p : pointer);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public, alias : 'FPC_CHECKPOINTER'];
  674. var
  675. i : ptrint;
  676. pp : pheap_mem_info;
  677. get_ebp,stack_top : longword;
  678. data_end : longword;
  679. label
  680. _exit;
  681. begin
  682. if p=nil then
  683. runerror(204);
  684. i:=0;
  685. {$ifdef go32v2}
  686. if ptruint(p)<$1000 then
  687. runerror(216);
  688. asm
  689. movl %ebp,get_ebp
  690. leal edata,%eax
  691. movl %eax,data_end
  692. end;
  693. stack_top:=__stkbottom+__stklen;
  694. { allow all between start of code and end of data }
  695. if ptruint(p)<=data_end then
  696. goto _exit;
  697. { stack can be above heap !! }
  698. if (ptruint(p)>=get_ebp) and (ptruint(p)<=stack_top) then
  699. goto _exit;
  700. {$endif go32v2}
  701. { I don't know where the stack is in other OS !! }
  702. {$ifdef win32}
  703. { inside stack ? }
  704. if (ptruint(p)>ptruint(get_frame)) and
  705. (ptruint(p)<Win32StackTop) then
  706. goto _exit;
  707. {$endif win32}
  708. {$ifdef linux}
  709. { inside stack ? }
  710. if (ptruint(p)>ptruint(get_frame)) and
  711. (ptruint(p)<$c0000000) then //todo: 64bit!
  712. goto _exit;
  713. { inside data or bss ? }
  714. if (ptruint(p)>=ptruint(@etext)) and (ptruint(p)<ptruint(@eend)) then
  715. goto _exit;
  716. {$endif linux}
  717. { first try valid list faster }
  718. {$ifdef EXTRA}
  719. pp:=heap_valid_last;
  720. while pp<>nil do
  721. begin
  722. { inside this valid block ! }
  723. { we can be changing the extrainfo !! }
  724. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info){+extra_info_size}) and
  725. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+extra_info_size+pp^.size) then
  726. begin
  727. { check allocated block }
  728. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  729. ((pp^.sig=calculate_sig(pp)) and usecrc) or
  730. { special case of the fill_extra_info call }
  731. ((pp=heap_valid_last) and usecrc and (pp^.sig=$DEADBEEF)
  732. and inside_trace_getmem) then
  733. goto _exit
  734. else
  735. begin
  736. writeln(ptext^,'corrupted heap_mem_info');
  737. dump_error(pp,ptext^);
  738. halt(1);
  739. end;
  740. end
  741. else
  742. pp:=pp^.prev_valid;
  743. inc(i);
  744. if i>getmem_cnt-freemem_cnt then
  745. begin
  746. writeln(ptext^,'error in linked list of heap_mem_info');
  747. halt(1);
  748. end;
  749. end;
  750. i:=0;
  751. {$endif EXTRA}
  752. pp:=heap_mem_root;
  753. while pp<>nil do
  754. begin
  755. { inside this block ! }
  756. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)) and
  757. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)+ptruint(pp^.size)) then
  758. { allocated block }
  759. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  760. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  761. goto _exit
  762. else
  763. begin
  764. writeln(ptext^,'pointer $',hexstr(ptrint(p),8),' points into invalid memory block');
  765. dump_error(pp,ptext^);
  766. runerror(204);
  767. end;
  768. pp:=pp^.previous;
  769. inc(i);
  770. if i>getmem_cnt then
  771. begin
  772. writeln(ptext^,'error in linked list of heap_mem_info');
  773. halt(1);
  774. end;
  775. end;
  776. writeln(ptext^,'pointer $',hexstr(ptrint(p),8),' does not point to valid memory block');
  777. runerror(204);
  778. _exit:
  779. end;
  780. {*****************************************************************************
  781. Dump Heap
  782. *****************************************************************************}
  783. procedure dumpheap;
  784. var
  785. pp : pheap_mem_info;
  786. i : ptrint;
  787. ExpectedHeapFree : ptrint;
  788. status : THeapStatus;
  789. begin
  790. pp:=heap_mem_root;
  791. Writeln(ptext^,'Heap dump by heaptrc unit');
  792. Writeln(ptext^,getmem_cnt, ' memory blocks allocated : ',getmem_size,'/',getmem8_size);
  793. Writeln(ptext^,freemem_cnt,' memory blocks freed : ',freemem_size,'/',freemem8_size);
  794. Writeln(ptext^,getmem_cnt-freemem_cnt,' unfreed memory blocks : ',getmem_size-freemem_size);
  795. SysGetHeapStatus(status);
  796. Write(ptext^,'True heap size : ',status.CurrHeapSize);
  797. if EntryMemUsed > 0 then
  798. Writeln(ptext^,' (',EntryMemUsed,' used in System startup)')
  799. else
  800. Writeln(ptext^);
  801. Writeln(ptext^,'True free heap : ',status.CurrHeapFree);
  802. ExpectedHeapFree:=status.CurrHeapSize-(getmem8_size-freemem8_size)-
  803. (getmem_cnt-freemem_cnt)*(sizeof(theap_mem_info)+extra_info_size)-EntryMemUsed;
  804. If ExpectedHeapFree<>status.CurrHeapFree then
  805. Writeln(ptext^,'Should be : ',ExpectedHeapFree);
  806. i:=getmem_cnt-freemem_cnt;
  807. while pp<>nil do
  808. begin
  809. if i<0 then
  810. begin
  811. Writeln(ptext^,'Error in heap memory list');
  812. Writeln(ptext^,'More memory blocks than expected');
  813. exit;
  814. end;
  815. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  816. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  817. begin
  818. { this one was not released !! }
  819. if exitcode<>203 then
  820. call_stack(pp,ptext^);
  821. dec(i);
  822. end
  823. else if pp^.sig<>$AAAAAAAA then
  824. begin
  825. dump_error(pp,ptext^);
  826. {$ifdef EXTRA}
  827. dump_error(pp,error_file);
  828. {$endif EXTRA}
  829. error_in_heap:=true;
  830. end
  831. {$ifdef EXTRA}
  832. else if pp^.release_sig<>calculate_release_sig(pp) then
  833. begin
  834. dump_change_after(pp,ptext^);
  835. dump_change_after(pp,error_file);
  836. error_in_heap:=true;
  837. end
  838. {$endif EXTRA}
  839. ;
  840. pp:=pp^.previous;
  841. end;
  842. end;
  843. procedure markheap;
  844. var
  845. pp : pheap_mem_info;
  846. begin
  847. pp:=heap_mem_root;
  848. while pp<>nil do
  849. begin
  850. pp^.sig:=$AAAAAAAA;
  851. pp:=pp^.previous;
  852. end;
  853. end;
  854. {*****************************************************************************
  855. AllocMem
  856. *****************************************************************************}
  857. function TraceAllocMem(size:ptrint):Pointer;
  858. begin
  859. TraceAllocMem:=SysAllocMem(size);
  860. end;
  861. {*****************************************************************************
  862. No specific tracing calls
  863. *****************************************************************************}
  864. procedure TraceGetHeapStatus(var status:THeapStatus);
  865. begin
  866. SysGetHeapStatus(status);
  867. end;
  868. {*****************************************************************************
  869. Program Hooks
  870. *****************************************************************************}
  871. Procedure SetHeapTraceOutput(const name : string);
  872. var i : ptrint;
  873. begin
  874. if ptext<>@stderr then
  875. begin
  876. ptext:=@stderr;
  877. close(ownfile);
  878. end;
  879. assign(ownfile,name);
  880. {$I-}
  881. append(ownfile);
  882. if IOResult<>0 then
  883. Rewrite(ownfile);
  884. {$I+}
  885. ptext:=@ownfile;
  886. for i:=0 to Paramcount do
  887. write(ptext^,paramstr(i),' ');
  888. writeln(ptext^);
  889. end;
  890. procedure SetHeapExtraInfo( size : ptrint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  891. begin
  892. { the total size must stay multiple of 8, also allocate 2 pointers for
  893. the fill and display procvars }
  894. exact_info_size:=size + sizeof(theap_extra_info);
  895. extra_info_size:=((exact_info_size+7) div 8)*8;
  896. fill_extra_info_proc:=fillproc;
  897. display_extra_info_proc:=displayproc;
  898. end;
  899. {*****************************************************************************
  900. Install MemoryManager
  901. *****************************************************************************}
  902. const
  903. TraceManager:TMemoryManager=(
  904. NeedLock : true;
  905. Getmem : @TraceGetMem;
  906. Freemem : @TraceFreeMem;
  907. FreememSize : @TraceFreeMemSize;
  908. AllocMem : @TraceAllocMem;
  909. ReAllocMem : @TraceReAllocMem;
  910. MemSize : @TraceMemSize;
  911. GetHeapStatus : @TraceGetHeapStatus;
  912. );
  913. procedure TraceInit;
  914. var
  915. initheapstatus : THeapStatus;
  916. begin
  917. SysGetHeapStatus(initheapstatus);
  918. EntryMemUsed:=initheapstatus.CurrHeapUsed;
  919. MakeCRC32Tbl;
  920. SetMemoryManager(TraceManager);
  921. ptext:=@stderr;
  922. if outputstr <> '' then
  923. SetHeapTraceOutput(outputstr);
  924. {$ifdef EXTRA}
  925. Assign(error_file,'heap.err');
  926. Rewrite(error_file);
  927. {$endif EXTRA}
  928. end;
  929. procedure TraceExit;
  930. begin
  931. { no dump if error
  932. because this gives long long listings }
  933. { clear inoutres, in case the program that quit didn't }
  934. ioresult;
  935. if (exitcode<>0) and (erroraddr<>nil) then
  936. begin
  937. Writeln(ptext^,'No heap dump by heaptrc unit');
  938. Writeln(ptext^,'Exitcode = ',exitcode);
  939. if ptext<>@stderr then
  940. begin
  941. ptext:=@stderr;
  942. close(ownfile);
  943. end;
  944. exit;
  945. end;
  946. if not error_in_heap then
  947. Dumpheap;
  948. if error_in_heap and (exitcode=0) then
  949. exitcode:=203;
  950. {$ifdef EXTRA}
  951. Close(error_file);
  952. {$endif EXTRA}
  953. if ptext<>@stderr then
  954. begin
  955. ptext:=@stderr;
  956. close(ownfile);
  957. end;
  958. end;
  959. {$ifdef win32}
  960. function GetEnvironmentStrings : pchar; stdcall;
  961. external 'kernel32' name 'GetEnvironmentStringsA';
  962. function FreeEnvironmentStrings(p : pchar) : longbool; stdcall;
  963. external 'kernel32' name 'FreeEnvironmentStringsA';
  964. Function GetEnv(envvar: string): string;
  965. var
  966. s : string;
  967. i : ptrint;
  968. hp,p : pchar;
  969. begin
  970. getenv:='';
  971. p:=GetEnvironmentStrings;
  972. hp:=p;
  973. while hp^<>#0 do
  974. begin
  975. s:=strpas(hp);
  976. i:=pos('=',s);
  977. if upcase(copy(s,1,i-1))=upcase(envvar) then
  978. begin
  979. getenv:=copy(s,i+1,length(s)-i);
  980. break;
  981. end;
  982. { next string entry}
  983. hp:=hp+strlen(hp)+1;
  984. end;
  985. FreeEnvironmentStrings(p);
  986. end;
  987. {$else}
  988. Function GetEnv(P:string):Pchar;
  989. {
  990. Searches the environment for a string with name p and
  991. returns a pchar to it's value.
  992. A pchar is used to accomodate for strings of length > 255
  993. }
  994. var
  995. ep : ppchar;
  996. i : ptrint;
  997. found : boolean;
  998. Begin
  999. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1000. ep:=envp;
  1001. found:=false;
  1002. if ep<>nil then
  1003. begin
  1004. while (not found) and (ep^<>nil) do
  1005. begin
  1006. found:=true;
  1007. for i:=1 to length(p) do
  1008. if p[i]<>ep^[i-1] then
  1009. begin
  1010. found:=false;
  1011. break;
  1012. end;
  1013. if not found then
  1014. inc(ep);
  1015. end;
  1016. end;
  1017. if found then
  1018. getenv:=ep^+length(p)
  1019. else
  1020. getenv:=nil;
  1021. end;
  1022. {$endif}
  1023. procedure LoadEnvironment;
  1024. var
  1025. i,j : ptrint;
  1026. s : string;
  1027. begin
  1028. s:=Getenv('HEAPTRC');
  1029. if pos('keepreleased',s)>0 then
  1030. keepreleased:=true;
  1031. if pos('disabled',s)>0 then
  1032. useheaptrace:=false;
  1033. if pos('nohalt',s)>0 then
  1034. haltonerror:=false;
  1035. i:=pos('log=',s);
  1036. if i>0 then
  1037. begin
  1038. outputstr:=copy(s,i+4,255);
  1039. j:=pos(' ',outputstr);
  1040. if j=0 then
  1041. j:=length(outputstr)+1;
  1042. delete(outputstr,j,255);
  1043. end;
  1044. end;
  1045. Initialization
  1046. LoadEnvironment;
  1047. { heaptrc can be disabled from the environment }
  1048. if useheaptrace then
  1049. TraceInit;
  1050. finalization
  1051. if useheaptrace then
  1052. TraceExit;
  1053. end.
  1054. {
  1055. $Log$
  1056. Revision 1.38 2005-01-21 15:56:32 peter
  1057. * uses _eend instead of _edata in checkpointer, patch by
  1058. Martin Schreiber
  1059. Revision 1.37 2004/11/22 19:34:58 peter
  1060. * GetHeapStatus added, removed MaxAvail,MemAvail,HeapSize
  1061. Revision 1.36 2004/10/25 17:04:07 peter
  1062. * fix for non-i386
  1063. Revision 1.35 2004/10/25 15:38:59 peter
  1064. * compiler defined HEAP and HEAPSIZE removed
  1065. Revision 1.34 2004/10/24 20:01:41 peter
  1066. * saveregisters calling convention is obsolete
  1067. Revision 1.33 2004/09/21 14:49:29 peter
  1068. * fix reallocmem
  1069. Revision 1.32 2004/09/16 07:21:08 michael
  1070. Fix tracememsize for ansistrings (From Peter)
  1071. Revision 1.31 2004/06/20 09:24:40 peter
  1072. fixed go32v2 compile
  1073. Revision 1.30 2004/06/17 16:16:13 peter
  1074. * New heapmanager that releases memory back to the OS, donated
  1075. by Micha Nelissen
  1076. Revision 1.29 2004/05/22 20:35:52 peter
  1077. check whether bp is in the stack value allocated by the main program
  1078. Revision 1.28 2004/04/28 20:48:20 peter
  1079. * ordinal-pointer conversions fixed
  1080. Revision 1.27 2004/03/15 21:48:26 peter
  1081. * cmem moved to rtl
  1082. * longint replaced with ptrint in heapmanagers
  1083. Revision 1.26 2004/03/15 14:22:39 michael
  1084. + Fix from peter for win32 SIGTRAp signal
  1085. Revision 1.25 2004/02/06 20:17:12 daniel
  1086. * Use $ for hex numbers instead of alien 0x
  1087. Revision 1.24 2003/09/11 15:54:27 peter
  1088. * when retrieving stackdump check if bp is smaller than the previous
  1089. bp
  1090. Revision 1.23 2003/03/17 14:30:11 peter
  1091. * changed address parameter/return values to pointer instead
  1092. of ptrint
  1093. Revision 1.22 2002/12/26 10:46:54 peter
  1094. * set p to nil when 0 is passed to reallocmem
  1095. Revision 1.21 2002/11/30 23:34:43 carl
  1096. * nil should give an error!
  1097. Revision 1.20 2002/10/30 20:39:13 peter
  1098. * MemoryManager record has a field NeedLock if the wrapper functions
  1099. need to provide locking for multithreaded programs
  1100. Revision 1.19 2002/10/05 15:19:46 carl
  1101. * bugfix of assigning to external filename output
  1102. Revision 1.18 2002/09/09 15:45:49 jonas
  1103. * made result type of calculate_release_sig() a longword instead of a
  1104. ptrint
  1105. Revision 1.17 2002/09/07 15:07:45 peter
  1106. * old logs removed and tabs fixed
  1107. }