heaptrc.pp 34 KB

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