heaptrc.pp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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 : longint;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. plongint = ^longint;
  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 : longint = 0;
  68. exact_info_size : longint = 0;
  69. EntryMemUsed : longint = 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 : longint;
  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 : longint;
  119. getmem_size,
  120. freemem_size : longint;
  121. getmem8_size,
  122. freemem8_size : longint;
  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:Longint):longword;
  145. var
  146. i : longint;
  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 : plongint;
  161. begin
  162. crc:=cardinal($ffffffff);
  163. crc:=UpdateCrc32(crc,p^.size,sizeof(longint));
  164. crc:=UpdateCrc32(crc,p^.calls,tracesize*sizeof(longint));
  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(longint));
  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 : plongint;
  180. begin
  181. crc:=$ffffffff;
  182. crc:=UpdateCrc32(crc,p^.size,sizeof(longint));
  183. crc:=UpdateCrc32(crc,p^.calls,tracesize*sizeof(longint));
  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(longint));
  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 : longint;
  205. begin
  206. writeln(ptext,'Call trace for block 0x',hexstr(longint(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 : longint;
  219. begin
  220. writeln(ptext,'Call trace for block at 0x',hexstr(longint(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 0x',HexStr(longint(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 0x',HexStr(longint(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 : longint;
  251. begin
  252. Writeln(ptext,'Marked memory at 0x',HexStr(longint(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 : longint;var ptext : text);
  263. begin
  264. Writeln(ptext,'Marked memory at 0x',HexStr(longint(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 : longint;
  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:longint):pointer;
  303. var
  304. allocsize,i : longint;
  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(longint));
  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(longint);
  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 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:longint):longint;
  388. var
  389. i,ppsize : longint;
  390. bp : pointer;
  391. pp : pheap_mem_info;
  392. {$ifdef EXTRA}
  393. pp2 : pheap_mem_info;
  394. {$endif}
  395. extra_size : longint;
  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(longint));
  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(longint));
  500. TraceFreeMemSize:=i;
  501. end;
  502. function TraceMemSize(p:pointer):Longint;
  503. var
  504. l : longint;
  505. pp : pheap_mem_info;
  506. begin
  507. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  508. l:=SysMemSize(pp);
  509. dec(l,sizeof(theap_mem_info)+pp^.extra_info_size);
  510. if add_tail then
  511. dec(l,sizeof(longint));
  512. TraceMemSize:=l;
  513. end;
  514. function TraceFreeMem(p:pointer):longint;
  515. var
  516. size : longint;
  517. pp : pheap_mem_info;
  518. begin
  519. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  520. size:=TraceMemSize(p);
  521. { this can never happend normaly }
  522. if pp^.size>size then
  523. begin
  524. dump_wrong_size(pp,size,ptext^);
  525. {$ifdef EXTRA}
  526. dump_wrong_size(pp,size,error_file);
  527. {$endif EXTRA}
  528. end;
  529. TraceFreeMem:=TraceFreeMemSize(p,pp^.size);
  530. end;
  531. {*****************************************************************************
  532. ReAllocMem
  533. *****************************************************************************}
  534. function TraceReAllocMem(var p:pointer;size:longint):Pointer;
  535. var
  536. newP: pointer;
  537. oldsize,
  538. allocsize,
  539. i : longint;
  540. bp : pointer;
  541. pl : pdword;
  542. pp : pheap_mem_info;
  543. oldextrasize,
  544. oldexactsize : longint;
  545. old_fill_extra_info_proc : tfillextrainfoproc;
  546. old_display_extra_info_proc : tdisplayextrainfoproc;
  547. begin
  548. { Free block? }
  549. if size=0 then
  550. begin
  551. if p<>nil then
  552. TraceFreeMem(p);
  553. p:=nil;
  554. TraceReallocMem:=P;
  555. exit;
  556. end;
  557. { Allocate a new block? }
  558. if p=nil then
  559. begin
  560. p:=TraceGetMem(size);
  561. TraceReallocMem:=P;
  562. exit;
  563. end;
  564. { Resize block }
  565. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  566. { test block }
  567. if ((pp^.sig<>$DEADBEEF) or usecrc) and
  568. ((pp^.sig<>calculate_sig(pp)) or not usecrc) then
  569. begin
  570. error_in_heap:=true;
  571. dump_error(pp,ptext^);
  572. {$ifdef EXTRA}
  573. dump_error(pp,error_file);
  574. {$endif EXTRA}
  575. { don't release anything in this case !! }
  576. if haltonerror then halt(1);
  577. exit;
  578. end;
  579. { save info }
  580. oldextrasize:=pp^.extra_info_size;
  581. oldexactsize:=pp^.exact_info_size;
  582. if pp^.extra_info_size>0 then
  583. begin
  584. old_fill_extra_info_proc:=pp^.extra_info^.fillproc;
  585. old_display_extra_info_proc:=pp^.extra_info^.displayproc;
  586. end;
  587. { Do the real ReAllocMem, but alloc also for the info block }
  588. allocsize:=size+sizeof(theap_mem_info)+pp^.extra_info_size;
  589. if add_tail then
  590. inc(allocsize,sizeof(longint));
  591. { Try to resize the block, if not possible we need to do a
  592. getmem, move data, freemem }
  593. if not SysTryResizeMem(pp,allocsize) then
  594. begin
  595. { get a new block }
  596. oldsize:=TraceMemSize(p);
  597. newP := TraceGetMem(size);
  598. { move the data }
  599. if newP <> nil then
  600. move(p^,newP^,oldsize);
  601. { release p }
  602. traceFreeMem(p);
  603. { return the new pointer }
  604. p:=newp;
  605. traceReAllocMem := newp;
  606. exit;
  607. end;
  608. { adjust like a freemem and then a getmem, so you get correct
  609. results in the summary display }
  610. inc(freemem_size,pp^.size);
  611. inc(freemem8_size,((pp^.size+7) div 8)*8);
  612. inc(getmem_size,size);
  613. inc(getmem8_size,((size+7) div 8)*8);
  614. { Recreate the info block }
  615. pp^.sig:=$DEADBEEF;
  616. pp^.size:=size;
  617. pp^.extra_info_size:=oldextrasize;
  618. pp^.exact_info_size:=oldexactsize;
  619. { add the new extra_info and tail }
  620. if pp^.extra_info_size>0 then
  621. begin
  622. pp^.extra_info:=pointer(pp)+allocsize-pp^.extra_info_size;
  623. fillchar(pp^.extra_info^,extra_info_size,0);
  624. pp^.extra_info^.check:=$12345678;
  625. pp^.extra_info^.fillproc:=old_fill_extra_info_proc;
  626. pp^.extra_info^.displayproc:=old_display_extra_info_proc;
  627. if assigned(pp^.extra_info^.fillproc) then
  628. pp^.extra_info^.fillproc(@pp^.extra_info^.data);
  629. end
  630. else
  631. pp^.extra_info:=nil;
  632. if add_tail then
  633. begin
  634. pl:=pointer(pp)+allocsize-pp^.extra_info_size-sizeof(longint);
  635. pl^:=$DEADBEEF;
  636. end;
  637. { generate new backtrace }
  638. bp:=get_caller_frame(get_frame);
  639. for i:=1 to tracesize do
  640. begin
  641. pp^.calls[i]:=get_caller_addr(bp);
  642. bp:=get_caller_frame(bp);
  643. end;
  644. { regenerate signature }
  645. if usecrc then
  646. pp^.sig:=calculate_sig(pp);
  647. { return the pointer }
  648. p:=pointer(pp)+sizeof(theap_mem_info);
  649. TraceReAllocmem:=p;
  650. end;
  651. {*****************************************************************************
  652. Check pointer
  653. *****************************************************************************}
  654. {$ifndef Unix}
  655. {$S-}
  656. {$endif}
  657. {$ifdef go32v2}
  658. var
  659. __stklen : longword;external name '__stklen';
  660. __stkbottom : longword;external name '__stkbottom';
  661. edata : longword; external name 'edata';
  662. heap_at_init : pointer;
  663. {$endif go32v2}
  664. {$ifdef win32}
  665. var
  666. StartUpHeapEnd : pointer;
  667. { I found no symbol for start of text section :(
  668. so we usee the _mainCRTStartup which should be
  669. in wprt0.ow or wdllprt0.ow PM }
  670. text_begin : longword;external name '_mainCRTStartup';
  671. data_end : longword;external name '__data_end__';
  672. {$endif}
  673. procedure CheckPointer(p : pointer);[saveregisters,public, alias : 'FPC_CHECKPOINTER'];
  674. var
  675. i : longint;
  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 cardinal(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 cardinal(p)<=data_end then
  696. goto _exit;
  697. { .bss section }
  698. if cardinal(p)<=cardinal(heap_at_init) then
  699. goto _exit;
  700. { stack can be above heap !! }
  701. if (cardinal(p)>=get_ebp) and (cardinal(p)<=stack_top) then
  702. goto _exit;
  703. {$endif go32v2}
  704. { I don't know where the stack is in other OS !! }
  705. {$ifdef win32}
  706. if (cardinal(p)>=$40000) and (p<=HeapOrg) then
  707. goto _exit;
  708. { inside stack ? }
  709. asm
  710. movl %ebp,get_ebp
  711. end;
  712. if (cardinal(p)>get_ebp) and
  713. (cardinal(p)<Win32StackTop) then
  714. goto _exit;
  715. {$endif win32}
  716. { first try valid list faster }
  717. {$ifdef EXTRA}
  718. pp:=heap_valid_last;
  719. while pp<>nil do
  720. begin
  721. { inside this valid block ! }
  722. { we can be changing the extrainfo !! }
  723. if (cardinal(p)>=cardinal(pp)+sizeof(theap_mem_info){+extra_info_size}) and
  724. (cardinal(p)<=cardinal(pp)+sizeof(theap_mem_info)+extra_info_size+pp^.size) then
  725. begin
  726. { check allocated block }
  727. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  728. ((pp^.sig=calculate_sig(pp)) and usecrc) or
  729. { special case of the fill_extra_info call }
  730. ((pp=heap_valid_last) and usecrc and (pp^.sig=$DEADBEEF)
  731. and inside_trace_getmem) then
  732. goto _exit
  733. else
  734. begin
  735. writeln(ptext^,'corrupted heap_mem_info');
  736. dump_error(pp,ptext^);
  737. halt(1);
  738. end;
  739. end
  740. else
  741. pp:=pp^.prev_valid;
  742. inc(i);
  743. if i>getmem_cnt-freemem_cnt then
  744. begin
  745. writeln(ptext^,'error in linked list of heap_mem_info');
  746. halt(1);
  747. end;
  748. end;
  749. i:=0;
  750. {$endif EXTRA}
  751. pp:=heap_mem_root;
  752. while pp<>nil do
  753. begin
  754. { inside this block ! }
  755. if (cardinal(p)>=cardinal(pp)+sizeof(theap_mem_info)+cardinal(extra_info_size)) and
  756. (cardinal(p)<=cardinal(pp)+sizeof(theap_mem_info)+cardinal(extra_info_size)+cardinal(pp^.size)) then
  757. { allocated block }
  758. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  759. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  760. goto _exit
  761. else
  762. begin
  763. writeln(ptext^,'pointer $',hexstr(longint(p),8),' points into invalid memory block');
  764. dump_error(pp,ptext^);
  765. runerror(204);
  766. end;
  767. pp:=pp^.previous;
  768. inc(i);
  769. if i>getmem_cnt then
  770. begin
  771. writeln(ptext^,'error in linked list of heap_mem_info');
  772. halt(1);
  773. end;
  774. end;
  775. writeln(ptext^,'pointer $',hexstr(longint(p),8),' does not point to valid memory block');
  776. runerror(204);
  777. _exit:
  778. end;
  779. {*****************************************************************************
  780. Dump Heap
  781. *****************************************************************************}
  782. procedure dumpheap;
  783. var
  784. pp : pheap_mem_info;
  785. i : longint;
  786. ExpectedMemAvail : longint;
  787. begin
  788. pp:=heap_mem_root;
  789. Writeln(ptext^,'Heap dump by heaptrc unit');
  790. Writeln(ptext^,getmem_cnt, ' memory blocks allocated : ',getmem_size,'/',getmem8_size);
  791. Writeln(ptext^,freemem_cnt,' memory blocks freed : ',freemem_size,'/',freemem8_size);
  792. Writeln(ptext^,getmem_cnt-freemem_cnt,' unfreed memory blocks : ',getmem_size-freemem_size);
  793. Write(ptext^,'True heap size : ',system.HeapSize);
  794. if EntryMemUsed > 0 then
  795. Writeln(ptext^,' (',EntryMemUsed,' used in System startup)')
  796. else
  797. Writeln(ptext^);
  798. Writeln(ptext^,'True free heap : ',MemAvail);
  799. ExpectedMemAvail:=system.HeapSize-(getmem8_size-freemem8_size)-
  800. (getmem_cnt-freemem_cnt)*(sizeof(theap_mem_info)+extra_info_size)-EntryMemUsed;
  801. If ExpectedMemAvail<>MemAvail then
  802. Writeln(ptext^,'Should be : ',ExpectedMemAvail);
  803. i:=getmem_cnt-freemem_cnt;
  804. while pp<>nil do
  805. begin
  806. if i<0 then
  807. begin
  808. Writeln(ptext^,'Error in heap memory list');
  809. Writeln(ptext^,'More memory blocks than expected');
  810. exit;
  811. end;
  812. if ((pp^.sig=$DEADBEEF) and not usecrc) or
  813. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  814. begin
  815. { this one was not released !! }
  816. if exitcode<>203 then
  817. call_stack(pp,ptext^);
  818. dec(i);
  819. end
  820. else if pp^.sig<>$AAAAAAAA then
  821. begin
  822. dump_error(pp,ptext^);
  823. {$ifdef EXTRA}
  824. dump_error(pp,error_file);
  825. {$endif EXTRA}
  826. error_in_heap:=true;
  827. end
  828. {$ifdef EXTRA}
  829. else if pp^.release_sig<>calculate_release_sig(pp) then
  830. begin
  831. dump_change_after(pp,ptext^);
  832. dump_change_after(pp,error_file);
  833. error_in_heap:=true;
  834. end
  835. {$endif EXTRA}
  836. ;
  837. pp:=pp^.previous;
  838. end;
  839. end;
  840. procedure markheap;
  841. var
  842. pp : pheap_mem_info;
  843. begin
  844. pp:=heap_mem_root;
  845. while pp<>nil do
  846. begin
  847. pp^.sig:=$AAAAAAAA;
  848. pp:=pp^.previous;
  849. end;
  850. end;
  851. {*****************************************************************************
  852. AllocMem
  853. *****************************************************************************}
  854. function TraceAllocMem(size:longint):Pointer;
  855. begin
  856. TraceAllocMem:=SysAllocMem(size);
  857. end;
  858. {*****************************************************************************
  859. No specific tracing calls
  860. *****************************************************************************}
  861. function TraceMemAvail:longint;
  862. begin
  863. TraceMemAvail:=SysMemAvail;
  864. end;
  865. function TraceMaxAvail:longint;
  866. begin
  867. TraceMaxAvail:=SysMaxAvail;
  868. end;
  869. function TraceHeapSize:longint;
  870. begin
  871. TraceHeapSize:=SysHeapSize;
  872. end;
  873. {*****************************************************************************
  874. Program Hooks
  875. *****************************************************************************}
  876. Procedure SetHeapTraceOutput(const name : string);
  877. var i : longint;
  878. begin
  879. if ptext<>@stderr then
  880. begin
  881. ptext:=@stderr;
  882. close(ownfile);
  883. end;
  884. assign(ownfile,name);
  885. {$I-}
  886. append(ownfile);
  887. if IOResult<>0 then
  888. Rewrite(ownfile);
  889. {$I+}
  890. ptext:=@ownfile;
  891. for i:=0 to Paramcount do
  892. write(ptext^,paramstr(i),' ');
  893. writeln(ptext^);
  894. end;
  895. procedure SetHeapExtraInfo( size : longint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  896. begin
  897. { the total size must stay multiple of 8, also allocate 2 pointers for
  898. the fill and display procvars }
  899. exact_info_size:=size + sizeof(theap_extra_info);
  900. extra_info_size:=((exact_info_size+7) div 8)*8;
  901. fill_extra_info_proc:=fillproc;
  902. display_extra_info_proc:=displayproc;
  903. end;
  904. {*****************************************************************************
  905. Install MemoryManager
  906. *****************************************************************************}
  907. const
  908. TraceManager:TMemoryManager=(
  909. NeedLock : true;
  910. Getmem : @TraceGetMem;
  911. Freemem : @TraceFreeMem;
  912. FreememSize : @TraceFreeMemSize;
  913. AllocMem : @TraceAllocMem;
  914. ReAllocMem : @TraceReAllocMem;
  915. MemSize : @TraceMemSize;
  916. MemAvail : @TraceMemAvail;
  917. MaxAvail : @TraceMaxAvail;
  918. HeapSize : @TraceHeapsize;
  919. );
  920. procedure TraceInit;
  921. begin
  922. EntryMemUsed:=System.HeapSize-MemAvail;
  923. MakeCRC32Tbl;
  924. SetMemoryManager(TraceManager);
  925. ptext:=@stderr;
  926. if outputstr <> '' then
  927. SetHeapTraceOutput(outputstr);
  928. {$ifdef EXTRA}
  929. Assign(error_file,'heap.err');
  930. Rewrite(error_file);
  931. {$endif EXTRA}
  932. { checkpointer init }
  933. {$ifdef go32v2}
  934. Heap_at_init:=HeapPtr;
  935. {$endif}
  936. {$ifdef win32}
  937. StartupHeapEnd:=HeapEnd;
  938. {$endif}
  939. end;
  940. procedure TraceExit;
  941. begin
  942. { no dump if error
  943. because this gives long long listings }
  944. { clear inoutres, in case the program that quit didn't }
  945. ioresult;
  946. if (exitcode<>0) and (erroraddr<>nil) then
  947. begin
  948. Writeln(ptext^,'No heap dump by heaptrc unit');
  949. Writeln(ptext^,'Exitcode = ',exitcode);
  950. if ptext<>@stderr then
  951. begin
  952. ptext:=@stderr;
  953. close(ownfile);
  954. end;
  955. exit;
  956. end;
  957. if not error_in_heap then
  958. Dumpheap;
  959. if error_in_heap and (exitcode=0) then
  960. exitcode:=203;
  961. {$ifdef EXTRA}
  962. Close(error_file);
  963. {$endif EXTRA}
  964. if ptext<>@stderr then
  965. begin
  966. ptext:=@stderr;
  967. close(ownfile);
  968. end;
  969. end;
  970. {$ifdef win32}
  971. function GetEnvironmentStrings : pchar;
  972. external 'kernel32' name 'GetEnvironmentStringsA';
  973. function FreeEnvironmentStrings(p : pchar) : longbool;
  974. external 'kernel32' name 'FreeEnvironmentStringsA';
  975. Function GetEnv(envvar: string): string;
  976. var
  977. s : string;
  978. i : longint;
  979. hp,p : pchar;
  980. begin
  981. getenv:='';
  982. p:=GetEnvironmentStrings;
  983. hp:=p;
  984. while hp^<>#0 do
  985. begin
  986. s:=strpas(hp);
  987. i:=pos('=',s);
  988. if upcase(copy(s,1,i-1))=upcase(envvar) then
  989. begin
  990. getenv:=copy(s,i+1,length(s)-i);
  991. break;
  992. end;
  993. { next string entry}
  994. hp:=hp+strlen(hp)+1;
  995. end;
  996. FreeEnvironmentStrings(p);
  997. end;
  998. {$else}
  999. Function GetEnv(P:string):Pchar;
  1000. {
  1001. Searches the environment for a string with name p and
  1002. returns a pchar to it's value.
  1003. A pchar is used to accomodate for strings of length > 255
  1004. }
  1005. var
  1006. ep : ppchar;
  1007. i : longint;
  1008. found : boolean;
  1009. Begin
  1010. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1011. ep:=envp;
  1012. found:=false;
  1013. if ep<>nil then
  1014. begin
  1015. while (not found) and (ep^<>nil) do
  1016. begin
  1017. found:=true;
  1018. for i:=1 to length(p) do
  1019. if p[i]<>ep^[i-1] then
  1020. begin
  1021. found:=false;
  1022. break;
  1023. end;
  1024. if not found then
  1025. inc(ep);
  1026. end;
  1027. end;
  1028. if found then
  1029. getenv:=ep^+length(p)
  1030. else
  1031. getenv:=nil;
  1032. end;
  1033. {$endif}
  1034. procedure LoadEnvironment;
  1035. var
  1036. i,j : longint;
  1037. s,hs : string;
  1038. begin
  1039. s:=Getenv('HEAPTRC');
  1040. if pos('keepreleased',s)>0 then
  1041. keepreleased:=true;
  1042. if pos('disabled',s)>0 then
  1043. useheaptrace:=false;
  1044. if pos('nohalt',s)>0 then
  1045. haltonerror:=false;
  1046. i:=pos('log=',s);
  1047. if i>0 then
  1048. begin
  1049. outputstr:=copy(s,i+4,255);
  1050. j:=pos(' ',outputstr);
  1051. if j=0 then
  1052. j:=length(outputstr)+1;
  1053. delete(outputstr,j,255);
  1054. end;
  1055. end;
  1056. Initialization
  1057. LoadEnvironment;
  1058. { heaptrc can be disabled from the environment }
  1059. if useheaptrace then
  1060. TraceInit;
  1061. finalization
  1062. if useheaptrace then
  1063. TraceExit;
  1064. end.
  1065. {
  1066. $Log$
  1067. Revision 1.24 2003-09-11 15:54:27 peter
  1068. * when retrieving stackdump check if bp is smaller than the previous
  1069. bp
  1070. Revision 1.23 2003/03/17 14:30:11 peter
  1071. * changed address parameter/return values to pointer instead
  1072. of longint
  1073. Revision 1.22 2002/12/26 10:46:54 peter
  1074. * set p to nil when 0 is passed to reallocmem
  1075. Revision 1.21 2002/11/30 23:34:43 carl
  1076. * nil should give an error!
  1077. Revision 1.20 2002/10/30 20:39:13 peter
  1078. * MemoryManager record has a field NeedLock if the wrapper functions
  1079. need to provide locking for multithreaded programs
  1080. Revision 1.19 2002/10/05 15:19:46 carl
  1081. * bugfix of assigning to external filename output
  1082. Revision 1.18 2002/09/09 15:45:49 jonas
  1083. * made result type of calculate_release_sig() a longword instead of a
  1084. longint
  1085. Revision 1.17 2002/09/07 15:07:45 peter
  1086. * old logs removed and tabs fixed
  1087. }