heaptrc.pp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  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. {$checkpointer off}
  12. unit heaptrc;
  13. interface
  14. {$inline on}
  15. {$ifdef FPC_HEAPTRC_EXTRA}
  16. {$define EXTRA}
  17. {$inline off}
  18. {$endif FPC_HEAPTRC_EXTRA}
  19. {$TYPEDADDRESS on}
  20. {$if defined(win32) or defined(wince)}
  21. {$define windows}
  22. {$endif}
  23. Procedure DumpHeap;
  24. Procedure DumpHeap(SkipIfNoLeaks : Boolean);
  25. { define EXTRA to add more
  26. tests :
  27. - keep all memory after release and
  28. check by CRC value if not changed after release
  29. WARNING this needs extremely much memory (PM) }
  30. type
  31. tFillExtraInfoProc = procedure(p : pointer);
  32. tdisplayextrainfoProc = procedure (var ptext : text;p : pointer);
  33. { Allows to add info pre memory block, see ppheap.pas of the compiler
  34. for example source }
  35. procedure SetHeapExtraInfo(size : ptruint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  36. { Redirection of the output to a file }
  37. procedure SetHeapTraceOutput(const name : string);overload;
  38. procedure SetHeapTraceOutput(var ATextOutput : Text);overload;
  39. procedure CheckPointer(p : pointer);
  40. const
  41. { tracing level
  42. splitted in two if memory is released !! }
  43. {$ifdef EXTRA}
  44. tracesize = 16;
  45. {$else EXTRA}
  46. tracesize = 8;
  47. {$endif EXTRA}
  48. { install heaptrc memorymanager }
  49. useheaptrace : boolean=true;
  50. { less checking }
  51. quicktrace : boolean=true;
  52. { calls halt() on error by default !! }
  53. HaltOnError : boolean = true;
  54. { Halt on exit if any memory was not freed }
  55. HaltOnNotReleased : boolean = false;
  56. { set this to true if you suspect that memory
  57. is freed several times }
  58. {$ifdef EXTRA}
  59. keepreleased : boolean=true;
  60. {$else EXTRA}
  61. keepreleased : boolean=false;
  62. {$endif EXTRA}
  63. { add a small footprint at the end of memory blocks, this
  64. can check for memory overwrites at the end of a block }
  65. add_tail : boolean = true;
  66. tail_size : longint = sizeof(ptruint);
  67. { put crc in sig
  68. this allows to test for writing into that part }
  69. usecrc : boolean = true;
  70. printleakedblock: boolean = false;
  71. printfaultyblock: boolean = false;
  72. maxprintedblocklength: integer = 128;
  73. GlobalSkipIfNoLeaks : Boolean = False;
  74. implementation
  75. const
  76. { allows to add custom info in heap_mem_info, this is the size that will
  77. be allocated for this information }
  78. extra_info_size : ptruint = 0;
  79. exact_info_size : ptruint = 0;
  80. EntryMemUsed : ptruint = 0;
  81. { function to fill this info up }
  82. fill_extra_info_proc : TFillExtraInfoProc = nil;
  83. display_extra_info_proc : TDisplayExtraInfoProc = nil;
  84. { indicates where the output will be redirected }
  85. { only set using environment variables }
  86. outputstr : shortstring = '';
  87. ReleaseSig = $AAAAAAAA;
  88. AllocateSig = $DEADBEEF;
  89. CheckSig = $12345678;
  90. type
  91. pheap_extra_info = ^theap_extra_info;
  92. theap_extra_info = record
  93. check : cardinal; { used to check if the procvar is still valid }
  94. fillproc : tfillextrainfoProc;
  95. displayproc : tdisplayextrainfoProc;
  96. data : record
  97. end;
  98. end;
  99. ppheap_mem_info = ^pheap_mem_info;
  100. pheap_mem_info = ^theap_mem_info;
  101. { warning the size of theap_mem_info
  102. must be a multiple of 8
  103. because otherwise you will get
  104. problems when releasing the usual memory part !!
  105. sizeof(theap_mem_info = 16+tracesize*4 so
  106. tracesize must be even !! PM }
  107. theap_mem_info = record
  108. previous,
  109. next : pheap_mem_info;
  110. todolist : ppheap_mem_info;
  111. todonext : pheap_mem_info;
  112. size : ptruint;
  113. sig : longword;
  114. {$ifdef EXTRA}
  115. release_sig : longword;
  116. prev_valid : pheap_mem_info;
  117. {$endif EXTRA}
  118. calls : array [1..tracesize] of codepointer;
  119. exact_info_size : word;
  120. extra_info_size : word;
  121. extra_info : pheap_extra_info;
  122. end;
  123. pheap_info = ^theap_info;
  124. theap_info = record
  125. {$ifdef EXTRA}
  126. heap_valid_first,
  127. heap_valid_last : pheap_mem_info;
  128. {$endif EXTRA}
  129. heap_mem_root : pheap_mem_info;
  130. heap_free_todo : pheap_mem_info;
  131. getmem_cnt,
  132. freemem_cnt : ptruint;
  133. getmem_size,
  134. freemem_size : ptruint;
  135. getmem8_size,
  136. freemem8_size : ptruint;
  137. error_in_heap : boolean;
  138. inside_trace_getmem : boolean;
  139. end;
  140. var
  141. useownfile, useowntextoutput : boolean;
  142. ownfile : text;
  143. {$ifdef EXTRA}
  144. error_file : text;
  145. {$endif EXTRA}
  146. main_orig_todolist: ppheap_mem_info;
  147. main_relo_todolist: ppheap_mem_info;
  148. orphaned_info: theap_info;
  149. todo_lock: trtlcriticalsection;
  150. textoutput : ^text;
  151. {$ifdef FPC_HAS_FEATURE_THREADING}
  152. threadvar
  153. {$else}
  154. var
  155. {$endif}
  156. heap_info: theap_info;
  157. {*****************************************************************************
  158. Crc 32
  159. *****************************************************************************}
  160. var
  161. Crc32Tbl : array[0..255] of longword;
  162. const
  163. Crc32Seed = $ffffffff;
  164. Crc32Pattern = $edb88320;
  165. procedure MakeCRC32Tbl;
  166. var
  167. crc : longword;
  168. i,n : byte;
  169. begin
  170. for i:=0 to 255 do
  171. begin
  172. crc:=i;
  173. for n:=1 to 8 do
  174. if odd(crc) then
  175. crc:=(crc shr 1) xor longword(CRC32Pattern)
  176. else
  177. crc:=crc shr 1;
  178. Crc32Tbl[i]:=crc;
  179. end;
  180. end;
  181. Function UpdateCrc32(InitCrc:longword;var InBuf;InLen:ptruint):longword;
  182. var
  183. i : ptruint;
  184. p : pchar;
  185. begin
  186. p:=@InBuf;
  187. for i:=1 to InLen do
  188. begin
  189. InitCrc:=Crc32Tbl[byte(InitCrc) xor byte(p^)] xor (InitCrc shr 8);
  190. inc(p);
  191. end;
  192. UpdateCrc32:=InitCrc;
  193. end;
  194. Function calculate_sig(p : pheap_mem_info) : longword;
  195. var
  196. crc : longword;
  197. pl : pptruint;
  198. begin
  199. crc:=longword(CRC32Seed);
  200. crc:=UpdateCrc32(crc,p^.size,sizeof(ptruint));
  201. crc:=UpdateCrc32(crc,p^.calls,tracesize*sizeof(codepointer));
  202. if p^.extra_info_size>0 then
  203. crc:=UpdateCrc32(crc,p^.extra_info^,p^.exact_info_size);
  204. if add_tail then
  205. begin
  206. { Check also 4 bytes just after allocation !! }
  207. pl:=pointer(p)+sizeof(theap_mem_info)+p^.size;
  208. crc:=UpdateCrc32(crc,pl^,tail_size);
  209. end;
  210. calculate_sig:=crc;
  211. end;
  212. {$ifdef EXTRA}
  213. Function calculate_release_sig(p : pheap_mem_info) : longword;
  214. var
  215. crc : longword;
  216. pl : pptruint;
  217. begin
  218. crc:=longword(CRC32Seed);
  219. crc:=UpdateCrc32(crc,p^.size,sizeof(ptruint));
  220. crc:=UpdateCrc32(crc,p^.calls,tracesize*sizeof(codepointer));
  221. if p^.extra_info_size>0 then
  222. crc:=UpdateCrc32(crc,p^.extra_info^,p^.exact_info_size);
  223. { Check the whole of the whole allocation }
  224. pl:=pointer(p)+p^.extra_info_size+sizeof(theap_mem_info);
  225. crc:=UpdateCrc32(crc,pl^,p^.size);
  226. { Check also 4 bytes just after allocation !! }
  227. if add_tail then
  228. begin
  229. { Check also 4 bytes just after allocation !! }
  230. pl:=pointer(p)+p^.extra_info_size+sizeof(theap_mem_info)+p^.size;
  231. crc:=UpdateCrc32(crc,pl^,tail_size);
  232. end;
  233. calculate_release_sig:=crc;
  234. end;
  235. {$endif EXTRA}
  236. {*****************************************************************************
  237. Helpers
  238. *****************************************************************************}
  239. function InternalFreeMemSize(loc_info: pheap_info; p: pointer; pp: pheap_mem_info;
  240. size: ptruint; release_todo_lock: boolean): ptruint; forward;
  241. function TraceFreeMem(p: pointer): ptruint; forward;
  242. procedure printhex(p : pointer; const size : PtrUInt; var ptext : text);
  243. var s: PtrUInt;
  244. i: Integer;
  245. begin
  246. s := size;
  247. if s > maxprintedblocklength then
  248. s := maxprintedblocklength;
  249. for i:=0 to s-1 do
  250. write(ptext, hexstr(pbyte(p + i)^,2));
  251. if size > maxprintedblocklength then
  252. writeln(ptext,'.. - ')
  253. else
  254. writeln(ptext, ' - ');
  255. for i:=0 to s-1 do
  256. if pchar(p + sizeof(theap_mem_info) + i)^ < ' ' then
  257. write(ptext, ' ')
  258. else
  259. write(ptext, pchar(p + i)^);
  260. if size > maxprintedblocklength then
  261. writeln(ptext,'..')
  262. else
  263. writeln(ptext);
  264. end;
  265. procedure call_stack(pp : pheap_mem_info;var ptext : text);
  266. var
  267. i : ptruint;
  268. begin
  269. writeln(ptext,'Call trace for block $',hexstr(pointer(pp)+sizeof(theap_mem_info)),' size ',pp^.size);
  270. if printleakedblock then
  271. begin
  272. write(ptext, 'Block content: ');
  273. printhex(pointer(pp) + sizeof(theap_mem_info), pp^.size, ptext);
  274. end;
  275. for i:=1 to tracesize do
  276. if pp^.calls[i]<>nil then
  277. writeln(ptext,BackTraceStrFunc(pp^.calls[i]));
  278. { the check is done to be sure that the procvar is not overwritten }
  279. if assigned(pp^.extra_info) and
  280. (pp^.extra_info^.check=cardinal(CheckSig)) and
  281. assigned(pp^.extra_info^.displayproc) then
  282. pp^.extra_info^.displayproc(ptext,@pp^.extra_info^.data);
  283. end;
  284. procedure call_free_stack(pp : pheap_mem_info;var ptext : text);
  285. var
  286. i : ptruint;
  287. begin
  288. writeln(ptext,'Call trace for block at $',hexstr(pointer(pp)+sizeof(theap_mem_info)),' size ',pp^.size);
  289. for i:=1 to tracesize div 2 do
  290. if pp^.calls[i]<>nil then
  291. writeln(ptext,BackTraceStrFunc(pp^.calls[i]));
  292. writeln(ptext,' was released at ');
  293. for i:=(tracesize div 2)+1 to tracesize do
  294. if pp^.calls[i]<>nil then
  295. writeln(ptext,BackTraceStrFunc(pp^.calls[i]));
  296. { the check is done to be sure that the procvar is not overwritten }
  297. if assigned(pp^.extra_info) and
  298. (pp^.extra_info^.check=cardinal(CheckSig)) and
  299. assigned(pp^.extra_info^.displayproc) then
  300. pp^.extra_info^.displayproc(ptext,@pp^.extra_info^.data);
  301. end;
  302. procedure dump_already_free(p : pheap_mem_info;var ptext : text);
  303. begin
  304. Writeln(ptext,'Marked memory at $',HexStr(pointer(p)+sizeof(theap_mem_info)),' released');
  305. call_free_stack(p,ptext);
  306. Writeln(ptext,'freed again at');
  307. dump_stack(ptext,1);
  308. end;
  309. procedure dump_error(p : pheap_mem_info;var ptext : text);
  310. begin
  311. Writeln(ptext,'Marked memory at $',HexStr(pointer(p)+sizeof(theap_mem_info)),' invalid');
  312. Writeln(ptext,'Wrong signature $',hexstr(p^.sig,8),' instead of ',hexstr(calculate_sig(p),8));
  313. if printfaultyblock then
  314. begin
  315. write(ptext, 'Block content: ');
  316. printhex(pointer(p) + sizeof(theap_mem_info), p^.size, ptext);
  317. end;
  318. dump_stack(ptext,1);
  319. end;
  320. function released_modified(p : pheap_mem_info;var ptext : text) : boolean;
  321. var pl : pdword;
  322. pb : pbyte;
  323. i : longint;
  324. begin
  325. released_modified:=false;
  326. { Check tail_size bytes just after allocation !! }
  327. pl:=pointer(p)+sizeof(theap_mem_info)+p^.size;
  328. pb:=pointer(p)+sizeof(theap_mem_info);
  329. for i:=0 to p^.size-1 do
  330. if pb[i]<>$F0 then
  331. begin
  332. Writeln(ptext,'offset',i,':$',hexstr(i,2*sizeof(pointer)),'"',hexstr(pb[i],2),'"');
  333. released_modified:=true;
  334. end;
  335. for i:=1 to (tail_size div sizeof(dword)) do
  336. begin
  337. if unaligned(pl^) <> AllocateSig then
  338. begin
  339. released_modified:=true;
  340. writeln(ptext,'Tail modified after release at pos ',i*sizeof(ptruint));
  341. printhex(pointer(p)+p^.extra_info_size+sizeof(theap_mem_info)+p^.size,tail_size,ptext);
  342. break;
  343. end;
  344. inc(pointer(pl),sizeof(dword));
  345. end;
  346. if released_modified then
  347. begin
  348. dump_already_free(p,ptext);
  349. if @stderr<>@ptext then
  350. dump_already_free(p,stderr);
  351. end;
  352. end;
  353. {$ifdef EXTRA}
  354. procedure dump_change_after(p : pheap_mem_info;var ptext : text);
  355. var pp : pchar;
  356. i : ptruint;
  357. begin
  358. Writeln(ptext,'Marked memory at $',HexStr(pointer(p)+sizeof(theap_mem_info)),' invalid');
  359. Writeln(ptext,'Wrong release CRC $',hexstr(p^.release_sig,8),' instead of ',hexstr(calculate_release_sig(p),8));
  360. Writeln(ptext,'This memory was changed after call to freemem !');
  361. call_free_stack(p,ptext);
  362. pp:=pointer(p)+sizeof(theap_mem_info);
  363. for i:=0 to p^.size-1 do
  364. if byte(pp[i])<>$F0 then
  365. Writeln(ptext,'offset',i,':$',hexstr(i,2*sizeof(pointer)),'"',pp[i],'"');
  366. end;
  367. {$endif EXTRA}
  368. procedure dump_wrong_size(p : pheap_mem_info;size : ptruint;var ptext : text);
  369. begin
  370. Writeln(ptext,'Marked memory at $',HexStr(pointer(p)+sizeof(theap_mem_info)),' invalid');
  371. Writeln(ptext,'Wrong size : ',p^.size,' allocated ',size,' freed');
  372. dump_stack(ptext,1);
  373. { the check is done to be sure that the procvar is not overwritten }
  374. if assigned(p^.extra_info) and
  375. (p^.extra_info^.check=cardinal(CheckSig)) and
  376. assigned(p^.extra_info^.displayproc) then
  377. p^.extra_info^.displayproc(ptext,@p^.extra_info^.data);
  378. call_stack(p,ptext);
  379. end;
  380. function is_in_getmem_list (loc_info: pheap_info; p : pheap_mem_info) : boolean;
  381. var
  382. i : ptruint;
  383. pp : pheap_mem_info;
  384. begin
  385. is_in_getmem_list:=false;
  386. pp:=loc_info^.heap_mem_root;
  387. i:=0;
  388. while pp<>nil do
  389. begin
  390. if ((pp^.sig<>longword(AllocateSig)) or usecrc) and
  391. ((pp^.sig<>calculate_sig(pp)) or not usecrc) and
  392. (pp^.sig <>longword(ReleaseSig)) then
  393. begin
  394. if useownfile then
  395. writeln(ownfile,'error in linked list of heap_mem_info')
  396. else
  397. writeln(textoutput^,'error in linked list of heap_mem_info');
  398. RunError(204);
  399. end;
  400. if pp=p then
  401. is_in_getmem_list:=true;
  402. pp:=pp^.previous;
  403. inc(i);
  404. if i>loc_info^.getmem_cnt-loc_info^.freemem_cnt then
  405. if useownfile then
  406. writeln(ownfile,'error in linked list of heap_mem_info')
  407. else
  408. writeln(textoutput^,'error in linked list of heap_mem_info');
  409. end;
  410. end;
  411. procedure finish_heap_free_todo_list(loc_info: pheap_info);
  412. var
  413. bp: pointer;
  414. pp: pheap_mem_info;
  415. list: ppheap_mem_info;
  416. begin
  417. list := @loc_info^.heap_free_todo;
  418. repeat
  419. pp := list^;
  420. list^ := list^^.todonext;
  421. bp := pointer(pp)+sizeof(theap_mem_info);
  422. InternalFreeMemSize(loc_info,bp,pp,pp^.size,false);
  423. until list^ = nil;
  424. end;
  425. procedure try_finish_heap_free_todo_list(loc_info: pheap_info);
  426. begin
  427. if loc_info^.heap_free_todo <> nil then
  428. begin
  429. {$ifdef FPC_HAS_FEATURE_THREADING}
  430. entercriticalsection(todo_lock);
  431. {$endif}
  432. finish_heap_free_todo_list(loc_info);
  433. {$ifdef FPC_HAS_FEATURE_THREADING}
  434. leavecriticalsection(todo_lock);
  435. {$endif}
  436. end;
  437. end;
  438. {*****************************************************************************
  439. TraceGetMem
  440. *****************************************************************************}
  441. Function TraceGetMem(size:ptruint):pointer;
  442. var
  443. i, allocsize : ptruint;
  444. pl : pdword;
  445. p : pointer;
  446. pp : pheap_mem_info;
  447. loc_info: pheap_info;
  448. begin
  449. loc_info := @heap_info;
  450. try_finish_heap_free_todo_list(loc_info);
  451. inc(loc_info^.getmem_size,size);
  452. inc(loc_info^.getmem8_size,(size+7) and not 7);
  453. { Do the real GetMem, but alloc also for the info block }
  454. {$ifdef cpuarm}
  455. allocsize:=(size + 3) and not 3+sizeof(theap_mem_info)+extra_info_size;
  456. {$else cpuarm}
  457. allocsize:=size+sizeof(theap_mem_info)+extra_info_size;
  458. {$endif cpuarm}
  459. if add_tail then
  460. inc(allocsize,tail_size);
  461. { if ReturnNilIfGrowHeapFails is true
  462. SysGetMem can return nil }
  463. p:=SysGetMem(allocsize);
  464. if (p=nil) then
  465. begin
  466. TraceGetMem:=nil;
  467. exit;
  468. end;
  469. pp:=pheap_mem_info(p);
  470. inc(p,sizeof(theap_mem_info));
  471. { Create the info block }
  472. pp^.sig:=longword(AllocateSig);
  473. pp^.todolist:=@loc_info^.heap_free_todo;
  474. pp^.todonext:=nil;
  475. pp^.size:=size;
  476. pp^.extra_info_size:=extra_info_size;
  477. pp^.exact_info_size:=exact_info_size;
  478. {
  479. the end of the block contains:
  480. <tail> 4 bytes
  481. <extra_info> X bytes
  482. }
  483. if extra_info_size>0 then
  484. begin
  485. pp^.extra_info:=pointer(pp)+allocsize-extra_info_size;
  486. fillchar(pp^.extra_info^,extra_info_size,0);
  487. pp^.extra_info^.check:=cardinal(CheckSig);
  488. pp^.extra_info^.fillproc:=fill_extra_info_proc;
  489. pp^.extra_info^.displayproc:=display_extra_info_proc;
  490. if assigned(fill_extra_info_proc) then
  491. begin
  492. loc_info^.inside_trace_getmem:=true;
  493. fill_extra_info_proc(@pp^.extra_info^.data);
  494. loc_info^.inside_trace_getmem:=false;
  495. end;
  496. end
  497. else
  498. pp^.extra_info:=nil;
  499. if add_tail then
  500. begin
  501. pl:=pointer(pp)+allocsize-pp^.extra_info_size-tail_size;
  502. for i:=1 to tail_size div sizeof(dword) do
  503. begin
  504. unaligned(pl^):=dword(AllocateSig);
  505. inc(pointer(pl),sizeof(dword));
  506. end;
  507. end;
  508. { clear the memory }
  509. fillchar(p^,size,#255);
  510. { retrieve backtrace info }
  511. CaptureBacktrace(1,tracesize,@pp^.calls[1]);
  512. { insert in the linked list }
  513. if loc_info^.heap_mem_root<>nil then
  514. loc_info^.heap_mem_root^.next:=pp;
  515. pp^.previous:=loc_info^.heap_mem_root;
  516. pp^.next:=nil;
  517. {$ifdef EXTRA}
  518. pp^.prev_valid:=loc_info^.heap_valid_last;
  519. loc_info^.heap_valid_last:=pp;
  520. if not assigned(loc_info^.heap_valid_first) then
  521. loc_info^.heap_valid_first:=pp;
  522. {$endif EXTRA}
  523. loc_info^.heap_mem_root:=pp;
  524. { must be changed before fill_extra_info is called
  525. because checkpointer can be called from within
  526. fill_extra_info PM }
  527. inc(loc_info^.getmem_cnt);
  528. { update the signature }
  529. if usecrc then
  530. pp^.sig:=calculate_sig(pp);
  531. TraceGetmem:=p;
  532. end;
  533. {*****************************************************************************
  534. TraceFreeMem
  535. *****************************************************************************}
  536. function CheckFreeMemSize(loc_info: pheap_info; pp: pheap_mem_info;
  537. size, ppsize: ptruint): boolean; inline;
  538. var
  539. ptext : ^text;
  540. {$ifdef EXTRA}
  541. pp2 : pheap_mem_info;
  542. {$endif}
  543. begin
  544. if useownfile then
  545. ptext:=@ownfile
  546. else
  547. ptext:=textoutput;
  548. inc(loc_info^.freemem_size,size);
  549. inc(loc_info^.freemem8_size,(size+7) and not 7);
  550. if not quicktrace then
  551. begin
  552. if not(is_in_getmem_list(loc_info, pp)) then
  553. RunError(204);
  554. end;
  555. if (pp^.sig=longword(ReleaseSig)) then
  556. begin
  557. loc_info^.error_in_heap:=true;
  558. dump_already_free(pp,ptext^);
  559. if haltonerror then halt(1);
  560. end
  561. else if ((pp^.sig<>longword(AllocateSig)) or usecrc) and
  562. ((pp^.sig<>calculate_sig(pp)) or not usecrc) then
  563. begin
  564. loc_info^.error_in_heap:=true;
  565. dump_error(pp,ptext^);
  566. {$ifdef EXTRA}
  567. dump_error(pp,error_file);
  568. {$endif EXTRA}
  569. { don't release anything in this case !! }
  570. if haltonerror then halt(1);
  571. exit;
  572. end
  573. else if pp^.size<>size then
  574. begin
  575. loc_info^.error_in_heap:=true;
  576. dump_wrong_size(pp,size,ptext^);
  577. {$ifdef EXTRA}
  578. dump_wrong_size(pp,size,error_file);
  579. {$endif EXTRA}
  580. if haltonerror then halt(1);
  581. { don't release anything in this case !! }
  582. exit;
  583. end;
  584. { now it is released !! }
  585. pp^.sig:=longword(ReleaseSig);
  586. if not keepreleased then
  587. begin
  588. if pp^.next<>nil then
  589. pp^.next^.previous:=pp^.previous;
  590. if pp^.previous<>nil then
  591. pp^.previous^.next:=pp^.next;
  592. if pp=loc_info^.heap_mem_root then
  593. loc_info^.heap_mem_root:=loc_info^.heap_mem_root^.previous;
  594. end
  595. else
  596. CaptureBacktrace(1,(tracesize div 2)-1,@pp^.calls[(tracesize div 2)+1]);
  597. inc(loc_info^.freemem_cnt);
  598. { clear the memory, $F0 will lead to GFP if used as pointer ! }
  599. fillchar((pointer(pp)+sizeof(theap_mem_info))^,size,#240);
  600. { this way we keep all info about all released memory !! }
  601. if keepreleased then
  602. begin
  603. {$ifdef EXTRA}
  604. { We want to check if the memory was changed after release !! }
  605. pp^.release_sig:=calculate_release_sig(pp);
  606. if pp=loc_info^.heap_valid_last then
  607. begin
  608. loc_info^.heap_valid_last:=pp^.prev_valid;
  609. if pp=loc_info^.heap_valid_first then
  610. loc_info^.heap_valid_first:=nil;
  611. exit(false);
  612. end;
  613. pp2:=loc_info^.heap_valid_last;
  614. while assigned(pp2) do
  615. begin
  616. if pp2^.prev_valid=pp then
  617. begin
  618. pp2^.prev_valid:=pp^.prev_valid;
  619. if pp=loc_info^.heap_valid_first then
  620. loc_info^.heap_valid_first:=pp2;
  621. exit(false);
  622. end
  623. else
  624. pp2:=pp2^.prev_valid;
  625. end;
  626. {$endif EXTRA}
  627. exit(false);
  628. end;
  629. CheckFreeMemSize:=true;
  630. end;
  631. function InternalFreeMemSize(loc_info: pheap_info; p: pointer; pp: pheap_mem_info;
  632. size: ptruint; release_todo_lock: boolean): ptruint;
  633. var
  634. i,ppsize : ptruint;
  635. extra_size: ptruint;
  636. release_mem: boolean;
  637. begin
  638. { save old values }
  639. extra_size:=pp^.extra_info_size;
  640. ppsize:= size+sizeof(theap_mem_info)+pp^.extra_info_size;
  641. if add_tail then
  642. inc(ppsize,tail_size);
  643. { do various checking }
  644. release_mem := CheckFreeMemSize(loc_info, pp, size, ppsize);
  645. {$ifdef FPC_HAS_FEATURE_THREADING}
  646. if release_todo_lock then
  647. leavecriticalsection(todo_lock);
  648. {$endif}
  649. if release_mem then
  650. begin
  651. { release the normal memory at least }
  652. i:=SysFreeMemSize(pp,ppsize);
  653. { return the correct size }
  654. dec(i,sizeof(theap_mem_info)+extra_size);
  655. if add_tail then
  656. dec(i,tail_size);
  657. InternalFreeMemSize:=i;
  658. end else
  659. InternalFreeMemSize:=size;
  660. end;
  661. function TraceFreeMemSize(p:pointer;size:ptruint):ptruint;
  662. var
  663. loc_info: pheap_info;
  664. pp: pheap_mem_info;
  665. release_lock: boolean;
  666. begin
  667. if p=nil then
  668. begin
  669. TraceFreeMemSize:=0;
  670. exit;
  671. end;
  672. loc_info:=@heap_info;
  673. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  674. release_lock:=false;
  675. if @loc_info^.heap_free_todo <> pp^.todolist then
  676. begin
  677. if pp^.todolist = main_orig_todolist then
  678. pp^.todolist := main_relo_todolist;
  679. {$ifdef FPC_HAS_FEATURE_THREADING}
  680. entercriticalsection(todo_lock);
  681. {$endif}
  682. release_lock:=true;
  683. if pp^.todolist = @orphaned_info.heap_free_todo then
  684. begin
  685. loc_info := @orphaned_info;
  686. end else
  687. if pp^.todolist <> @loc_info^.heap_free_todo then
  688. begin
  689. { allocated in different heap, push to that todolist }
  690. pp^.todonext := pp^.todolist^;
  691. pp^.todolist^ := pp;
  692. TraceFreeMemSize := pp^.size;
  693. {$ifdef FPC_HAS_FEATURE_THREADING}
  694. leavecriticalsection(todo_lock);
  695. {$endif}
  696. exit;
  697. end;
  698. end;
  699. TraceFreeMemSize:=InternalFreeMemSize(loc_info,p,pp,size,release_lock);
  700. end;
  701. function TraceMemSize(p:pointer):ptruint;
  702. var
  703. pp : pheap_mem_info;
  704. begin
  705. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  706. TraceMemSize:=pp^.size;
  707. end;
  708. function TraceFreeMem(p:pointer):ptruint;
  709. var
  710. l : ptruint;
  711. pp : pheap_mem_info;
  712. begin
  713. if p=nil then
  714. begin
  715. TraceFreeMem:=0;
  716. exit;
  717. end;
  718. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  719. l:=SysMemSize(pp);
  720. dec(l,sizeof(theap_mem_info)+pp^.extra_info_size);
  721. if add_tail then
  722. dec(l,tail_size);
  723. { this can never happend normaly }
  724. if pp^.size>l then
  725. begin
  726. if useownfile then
  727. dump_wrong_size(pp,l,ownfile)
  728. else
  729. dump_wrong_size(pp,l,textoutput^);
  730. {$ifdef EXTRA}
  731. dump_wrong_size(pp,l,error_file);
  732. {$endif EXTRA}
  733. end;
  734. TraceFreeMem:=TraceFreeMemSize(p,pp^.size);
  735. end;
  736. {*****************************************************************************
  737. ReAllocMem
  738. *****************************************************************************}
  739. function TraceReAllocMem(var p:pointer;size:ptruint):Pointer;
  740. var
  741. newP: pointer;
  742. i, allocsize,
  743. movesize : ptruint;
  744. pl : pdword;
  745. pp : pheap_mem_info;
  746. oldsize,
  747. oldextrasize,
  748. oldexactsize : ptruint;
  749. old_fill_extra_info_proc : tfillextrainfoproc;
  750. old_display_extra_info_proc : tdisplayextrainfoproc;
  751. loc_info: pheap_info;
  752. begin
  753. { Free block? }
  754. if size=0 then
  755. begin
  756. if p<>nil then
  757. TraceFreeMem(p);
  758. p:=nil;
  759. TraceReallocMem:=P;
  760. exit;
  761. end;
  762. { Allocate a new block? }
  763. if p=nil then
  764. begin
  765. p:=TraceGetMem(size);
  766. TraceReallocMem:=P;
  767. exit;
  768. end;
  769. { Resize block }
  770. loc_info:=@heap_info;
  771. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  772. { test block }
  773. if ((pp^.sig<>longword(AllocateSig)) or usecrc) and
  774. ((pp^.sig<>calculate_sig(pp)) or not usecrc) then
  775. begin
  776. loc_info^.error_in_heap:=true;
  777. if useownfile then
  778. dump_error(pp,ownfile)
  779. else
  780. dump_error(pp,textoutput^);
  781. {$ifdef EXTRA}
  782. dump_error(pp,error_file);
  783. {$endif EXTRA}
  784. { don't release anything in this case !! }
  785. if haltonerror then halt(1);
  786. exit;
  787. end;
  788. { save info }
  789. oldsize:=pp^.size;
  790. oldextrasize:=pp^.extra_info_size;
  791. oldexactsize:=pp^.exact_info_size;
  792. if pp^.extra_info_size>0 then
  793. begin
  794. old_fill_extra_info_proc:=pp^.extra_info^.fillproc;
  795. old_display_extra_info_proc:=pp^.extra_info^.displayproc;
  796. end;
  797. { Do the real ReAllocMem, but alloc also for the info block }
  798. {$ifdef cpuarm}
  799. allocsize:=(size + 3) and not 3+sizeof(theap_mem_info)+pp^.extra_info_size;
  800. {$else cpuarm}
  801. allocsize:=size+sizeof(theap_mem_info)+pp^.extra_info_size;
  802. {$endif cpuarm}
  803. if add_tail then
  804. inc(allocsize,tail_size);
  805. { Try to resize the block, if not possible we need to do a
  806. getmem, move data, freemem }
  807. if not SysTryResizeMem(pp,allocsize) then
  808. begin
  809. { get a new block }
  810. newP := TraceGetMem(size);
  811. { move the data }
  812. if newP <> nil then
  813. begin
  814. movesize:=TraceMemSize(p);
  815. {if the old size is larger than the new size,
  816. move only the new size}
  817. if movesize>size then
  818. movesize:=size;
  819. move(p^,newP^,movesize);
  820. end;
  821. { release p }
  822. traceFreeMem(p);
  823. { return the new pointer }
  824. p:=newp;
  825. traceReAllocMem := newp;
  826. exit;
  827. end;
  828. { Recreate the info block }
  829. pp^.sig:=longword(AllocateSig);
  830. pp^.size:=size;
  831. pp^.extra_info_size:=oldextrasize;
  832. pp^.exact_info_size:=oldexactsize;
  833. { add the new extra_info and tail }
  834. if pp^.extra_info_size>0 then
  835. begin
  836. pp^.extra_info:=pointer(pp)+allocsize-pp^.extra_info_size;
  837. fillchar(pp^.extra_info^,extra_info_size,0);
  838. pp^.extra_info^.check:=cardinal(CheckSig);
  839. pp^.extra_info^.fillproc:=old_fill_extra_info_proc;
  840. pp^.extra_info^.displayproc:=old_display_extra_info_proc;
  841. if assigned(pp^.extra_info^.fillproc) then
  842. pp^.extra_info^.fillproc(@pp^.extra_info^.data);
  843. end
  844. else
  845. pp^.extra_info:=nil;
  846. if add_tail then
  847. begin
  848. pl:=pointer(pp)+allocsize-pp^.extra_info_size-tail_size;
  849. for i:=1 to tail_size div sizeof(dword) do
  850. begin
  851. unaligned(pl^):=dword(AllocateSig);
  852. inc(pointer(pl),sizeof(dword));
  853. end;
  854. end;
  855. { adjust like a freemem and then a getmem, so you get correct
  856. results in the summary display }
  857. inc(loc_info^.freemem_size,oldsize);
  858. inc(loc_info^.freemem8_size,(oldsize+7) and not 7);
  859. inc(loc_info^.getmem_size,size);
  860. inc(loc_info^.getmem8_size,(size+7) and not 7);
  861. { generate new backtrace }
  862. CaptureBacktrace(1,tracesize,@pp^.calls[1]);
  863. { regenerate signature }
  864. if usecrc then
  865. pp^.sig:=calculate_sig(pp);
  866. { return the pointer }
  867. p:=pointer(pp)+sizeof(theap_mem_info);
  868. TraceReAllocmem:=p;
  869. end;
  870. {*****************************************************************************
  871. Check pointer
  872. *****************************************************************************}
  873. {$ifndef Unix}
  874. {$S-}
  875. {$endif}
  876. {$ifdef go32v2}
  877. var
  878. __stklen : longword;external name '__stklen';
  879. __stkbottom : longword;external name '__stkbottom';
  880. ebss : longword; external name 'end';
  881. {$endif go32v2}
  882. {$ifdef linux}
  883. var
  884. etext: ptruint; external name '_etext';
  885. edata : ptruint; external name '_edata';
  886. eend : ptruint; external name '_end';
  887. {$endif}
  888. {$ifdef os2}
  889. (* Currently still EMX based - possibly to be changed in the future. *)
  890. var
  891. etext: ptruint; external name '_etext';
  892. edata : ptruint; external name '_edata';
  893. eend : ptruint; external name '_end';
  894. {$endif}
  895. {$ifdef windows}
  896. var
  897. sdata : ptruint; external name '__data_start__';
  898. edata : ptruint; external name '__data_end__';
  899. sbss : ptruint; external name '__bss_start__';
  900. ebss : ptruint; external name '__bss_end__';
  901. TLSKey : PDWord; external name '_FPC_TlsKey';
  902. TLSSize : DWord; external name '_FPC_TlsSize';
  903. function TlsGetValue(dwTlsIndex : DWord) : pointer;
  904. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TlsGetValue';
  905. {$endif}
  906. {$ifdef BEOS}
  907. const
  908. B_ERROR = -1;
  909. type
  910. area_id = Longint;
  911. function area_for(addr : Pointer) : area_id;
  912. cdecl; external 'root' name 'area_for';
  913. {$endif BEOS}
  914. procedure CheckPointer(p : pointer); [public, alias : 'FPC_CHECKPOINTER'];
  915. var
  916. i : ptruint;
  917. pp : pheap_mem_info;
  918. loc_info: pheap_info;
  919. {$ifdef go32v2}
  920. get_ebp,stack_top : longword;
  921. bss_end : longword;
  922. {$endif go32v2}
  923. {$ifdef windows}
  924. datap : pointer;
  925. {$endif windows}
  926. ptext : ^text;
  927. begin
  928. if p=nil then
  929. runerror(204);
  930. i:=0;
  931. loc_info:=@heap_info;
  932. if useownfile then
  933. ptext:=@ownfile
  934. else
  935. ptext:=textoutput;
  936. {$ifdef go32v2}
  937. if ptruint(p)<$1000 then
  938. runerror(216);
  939. asm
  940. movl %ebp,get_ebp
  941. leal ebss,%eax
  942. movl %eax,bss_end
  943. end;
  944. stack_top:=__stkbottom+__stklen;
  945. { allow all between start of code and end of bss }
  946. if ptruint(p)<=bss_end then
  947. exit;
  948. { stack can be above heap !! }
  949. if (ptruint(p)>=get_ebp) and (ptruint(p)<=stack_top) then
  950. exit;
  951. {$endif go32v2}
  952. { I don't know where the stack is in other OS !! }
  953. {$ifdef windows}
  954. { inside stack ? }
  955. if (ptruint(p)>ptruint(get_frame)) and
  956. (p<StackTop) then
  957. exit;
  958. { inside data, rdata ... bss }
  959. if (ptruint(p)>=ptruint(@sdata)) and (ptruint(p)<ptruint(@ebss)) then
  960. exit;
  961. { is program multi-threaded and p inside Threadvar range? }
  962. if TlsKey^<>-1 then
  963. begin
  964. datap:=TlsGetValue(tlskey^);
  965. if ((ptruint(p)>=ptruint(datap)) and
  966. (ptruint(p)<ptruint(datap)+TlsSize)) then
  967. exit;
  968. end;
  969. {$endif windows}
  970. {$IFDEF OS2}
  971. { inside stack ? }
  972. if (PtrUInt (P) > PtrUInt (Get_Frame)) and
  973. (PtrUInt (P) < PtrUInt (StackTop)) then
  974. exit;
  975. { inside data or bss ? }
  976. if (PtrUInt (P) >= PtrUInt (@etext)) and (PtrUInt (P) < PtrUInt (@eend)) then
  977. exit;
  978. {$ENDIF OS2}
  979. {$ifdef linux}
  980. { inside stack ? }
  981. if (ptruint(p)>ptruint(get_frame)) and
  982. (ptruint(p)<ptruint(StackTop)) then
  983. exit;
  984. { inside data or bss ? }
  985. if (ptruint(p)>=ptruint(@etext)) and (ptruint(p)<ptruint(@eend)) then
  986. exit;
  987. {$endif linux}
  988. {$ifdef morphos}
  989. { inside stack ? }
  990. if (ptruint(p)<ptruint(StackTop)) and (ptruint(p)>ptruint(StackBottom)) then
  991. exit;
  992. { inside data or bss ? }
  993. {$WARNING data and bss checking missing }
  994. {$endif morphos}
  995. {$ifdef darwin}
  996. {$warning No checkpointer support yet for Darwin}
  997. exit;
  998. {$endif}
  999. {$ifdef BEOS}
  1000. // if we find the address in a known area in our current process,
  1001. // then it is a valid one
  1002. if area_for(p) <> B_ERROR then
  1003. exit;
  1004. {$endif BEOS}
  1005. { first try valid list faster }
  1006. {$ifdef EXTRA}
  1007. pp:=loc_info^.heap_valid_last;
  1008. while pp<>nil do
  1009. begin
  1010. { inside this valid block ! }
  1011. { we can be changing the extrainfo !! }
  1012. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info){+extra_info_size}) and
  1013. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+extra_info_size+pp^.size) then
  1014. begin
  1015. { check allocated block }
  1016. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1017. ((pp^.sig=calculate_sig(pp)) and usecrc) or
  1018. { special case of the fill_extra_info call }
  1019. ((pp=loc_info^.heap_valid_last) and usecrc and (pp^.sig=longword(AllocateSig))
  1020. and loc_info^.inside_trace_getmem) then
  1021. exit
  1022. else
  1023. begin
  1024. writeln(ptext^,'corrupted heap_mem_info');
  1025. dump_error(pp,ptext^);
  1026. halt(1);
  1027. end;
  1028. end
  1029. else
  1030. pp:=pp^.prev_valid;
  1031. inc(i);
  1032. if i>loc_info^.getmem_cnt-loc_info^.freemem_cnt then
  1033. begin
  1034. writeln(ptext^,'error in linked list of heap_mem_info');
  1035. halt(1);
  1036. end;
  1037. end;
  1038. i:=0;
  1039. {$endif EXTRA}
  1040. pp:=loc_info^.heap_mem_root;
  1041. while pp<>nil do
  1042. begin
  1043. { inside this block ! }
  1044. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)) and
  1045. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)+ptruint(pp^.size)) then
  1046. { allocated block }
  1047. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1048. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  1049. exit
  1050. else
  1051. begin
  1052. writeln(ptext^,'pointer $',hexstr(p),' points into invalid memory block');
  1053. dump_error(pp,ptext^);
  1054. runerror(204);
  1055. end;
  1056. pp:=pp^.previous;
  1057. inc(i);
  1058. if i>loc_info^.getmem_cnt then
  1059. begin
  1060. writeln(ptext^,'error in linked list of heap_mem_info');
  1061. halt(1);
  1062. end;
  1063. end;
  1064. writeln(ptext^,'pointer $',hexstr(p),' does not point to valid memory block');
  1065. dump_stack(ptext^,1);
  1066. runerror(204);
  1067. end;
  1068. {*****************************************************************************
  1069. Dump Heap
  1070. *****************************************************************************}
  1071. procedure dumpheap;
  1072. begin
  1073. DumpHeap(GlobalSkipIfNoLeaks);
  1074. end;
  1075. procedure dumpheap(SkipIfNoLeaks : Boolean);
  1076. var
  1077. pp : pheap_mem_info;
  1078. i : ptrint;
  1079. ExpectedHeapFree : ptruint;
  1080. status : TFPCHeapStatus;
  1081. ptext : ^text;
  1082. loc_info: pheap_info;
  1083. begin
  1084. loc_info:=@heap_info;
  1085. if useownfile then
  1086. ptext:=@ownfile
  1087. else
  1088. ptext:=textoutput;
  1089. pp:=loc_info^.heap_mem_root;
  1090. if ((loc_info^.getmem_size-loc_info^.freemem_size)=0) and SkipIfNoLeaks then
  1091. exit;
  1092. Writeln(ptext^,'Heap dump by heaptrc unit of '+ParamStr(0));
  1093. Writeln(ptext^,loc_info^.getmem_cnt, ' memory blocks allocated : ',
  1094. loc_info^.getmem_size,'/',loc_info^.getmem8_size);
  1095. Writeln(ptext^,loc_info^.freemem_cnt,' memory blocks freed : ',
  1096. loc_info^.freemem_size,'/',loc_info^.freemem8_size);
  1097. Writeln(ptext^,loc_info^.getmem_cnt-loc_info^.freemem_cnt,
  1098. ' unfreed memory blocks : ',loc_info^.getmem_size-loc_info^.freemem_size);
  1099. status:=SysGetFPCHeapStatus;
  1100. Write(ptext^,'True heap size : ',status.CurrHeapSize);
  1101. if EntryMemUsed > 0 then
  1102. Writeln(ptext^,' (',EntryMemUsed,' used in System startup)')
  1103. else
  1104. Writeln(ptext^);
  1105. Writeln(ptext^,'True free heap : ',status.CurrHeapFree);
  1106. ExpectedHeapFree:=status.CurrHeapSize
  1107. -(loc_info^.getmem8_size-loc_info^.freemem8_size)
  1108. -(loc_info^.getmem_cnt-loc_info^.freemem_cnt)*(sizeof(theap_mem_info)+extra_info_size)
  1109. -EntryMemUsed;
  1110. If ExpectedHeapFree<>status.CurrHeapFree then
  1111. Writeln(ptext^,'Should be : ',ExpectedHeapFree);
  1112. i:=loc_info^.getmem_cnt-loc_info^.freemem_cnt;
  1113. while pp<>nil do
  1114. begin
  1115. if i<0 then
  1116. begin
  1117. Writeln(ptext^,'Error in heap memory list');
  1118. Writeln(ptext^,'More memory blocks than expected');
  1119. exit;
  1120. end;
  1121. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1122. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  1123. begin
  1124. { this one was not released !! }
  1125. if exitcode<>203 then
  1126. call_stack(pp,ptext^);
  1127. dec(i);
  1128. end
  1129. else if pp^.sig<>longword(ReleaseSig) then
  1130. begin
  1131. dump_error(pp,ptext^);
  1132. if @stderr<>ptext then
  1133. dump_error(pp,stderr);
  1134. {$ifdef EXTRA}
  1135. dump_error(pp,error_file);
  1136. {$endif EXTRA}
  1137. loc_info^.error_in_heap:=true;
  1138. end
  1139. {$ifdef EXTRA}
  1140. else if pp^.release_sig<>calculate_release_sig(pp) then
  1141. begin
  1142. dump_change_after(pp,ptext^);
  1143. dump_change_after(pp,error_file);
  1144. loc_info^.error_in_heap:=true;
  1145. end
  1146. {$else not EXTRA}
  1147. else
  1148. begin
  1149. if released_modified(pp,ptext^) then
  1150. exitcode:=203;
  1151. end;
  1152. {$endif EXTRA}
  1153. ;
  1154. pp:=pp^.previous;
  1155. end;
  1156. if HaltOnNotReleased and (loc_info^.getmem_cnt<>loc_info^.freemem_cnt) then
  1157. exitcode:=203;
  1158. end;
  1159. {*****************************************************************************
  1160. AllocMem
  1161. *****************************************************************************}
  1162. function TraceAllocMem(size:ptruint):Pointer;
  1163. begin
  1164. TraceAllocMem:=SysAllocMem(size);
  1165. end;
  1166. {*****************************************************************************
  1167. No specific tracing calls
  1168. *****************************************************************************}
  1169. procedure TraceInitThread;
  1170. var
  1171. loc_info: pheap_info;
  1172. begin
  1173. loc_info := @heap_info;
  1174. {$ifdef EXTRA}
  1175. loc_info^.heap_valid_first := nil;
  1176. loc_info^.heap_valid_last := nil;
  1177. {$endif}
  1178. loc_info^.heap_mem_root := nil;
  1179. loc_info^.getmem_cnt := 0;
  1180. loc_info^.freemem_cnt := 0;
  1181. loc_info^.getmem_size := 0;
  1182. loc_info^.freemem_size := 0;
  1183. loc_info^.getmem8_size := 0;
  1184. loc_info^.freemem8_size := 0;
  1185. loc_info^.error_in_heap := false;
  1186. loc_info^.inside_trace_getmem := false;
  1187. EntryMemUsed := SysGetFPCHeapStatus.CurrHeapUsed;
  1188. end;
  1189. procedure TraceRelocateHeap;
  1190. begin
  1191. main_relo_todolist := @heap_info.heap_free_todo;
  1192. {$ifdef FPC_HAS_FEATURE_THREADING}
  1193. initcriticalsection(todo_lock);
  1194. {$endif}
  1195. end;
  1196. procedure move_heap_info(src_info, dst_info: pheap_info);
  1197. var
  1198. heap_mem: pheap_mem_info;
  1199. begin
  1200. if src_info^.heap_free_todo <> nil then
  1201. finish_heap_free_todo_list(src_info);
  1202. if dst_info^.heap_free_todo <> nil then
  1203. finish_heap_free_todo_list(dst_info);
  1204. heap_mem := src_info^.heap_mem_root;
  1205. if heap_mem <> nil then
  1206. begin
  1207. repeat
  1208. heap_mem^.todolist := @dst_info^.heap_free_todo;
  1209. if heap_mem^.previous = nil then break;
  1210. heap_mem := heap_mem^.previous;
  1211. until false;
  1212. heap_mem^.previous := dst_info^.heap_mem_root;
  1213. if dst_info^.heap_mem_root <> nil then
  1214. dst_info^.heap_mem_root^.next := heap_mem;
  1215. dst_info^.heap_mem_root := src_info^.heap_mem_root;
  1216. end;
  1217. inc(dst_info^.getmem_cnt, src_info^.getmem_cnt);
  1218. inc(dst_info^.getmem_size, src_info^.getmem_size);
  1219. inc(dst_info^.getmem8_size, src_info^.getmem8_size);
  1220. inc(dst_info^.freemem_cnt, src_info^.freemem_cnt);
  1221. inc(dst_info^.freemem_size, src_info^.freemem_size);
  1222. inc(dst_info^.freemem8_size, src_info^.freemem8_size);
  1223. dst_info^.error_in_heap := dst_info^.error_in_heap or src_info^.error_in_heap;
  1224. {$ifdef EXTRA}
  1225. if assigned(dst_info^.heap_valid_first) then
  1226. dst_info^.heap_valid_first^.prev_valid := src_info^.heap_valid_last
  1227. else
  1228. dst_info^.heap_valid_last := src_info^.heap_valid_last;
  1229. dst_info^.heap_valid_first := src_info^.heap_valid_first;
  1230. {$endif}
  1231. end;
  1232. procedure TraceExitThread;
  1233. var
  1234. loc_info: pheap_info;
  1235. begin
  1236. loc_info := @heap_info;
  1237. {$ifdef FPC_HAS_FEATURE_THREADING}
  1238. entercriticalsection(todo_lock);
  1239. {$endif}
  1240. move_heap_info(loc_info, @orphaned_info);
  1241. {$ifdef FPC_HAS_FEATURE_THREADING}
  1242. leavecriticalsection(todo_lock);
  1243. {$endif}
  1244. end;
  1245. function TraceGetHeapStatus:THeapStatus;
  1246. begin
  1247. TraceGetHeapStatus:=SysGetHeapStatus;
  1248. end;
  1249. function TraceGetFPCHeapStatus:TFPCHeapStatus;
  1250. begin
  1251. TraceGetFPCHeapStatus:=SysGetFPCHeapStatus;
  1252. end;
  1253. {*****************************************************************************
  1254. Program Hooks
  1255. *****************************************************************************}
  1256. Procedure SetHeapTraceOutput(const name : string);
  1257. var i : ptruint;
  1258. begin
  1259. if useownfile then
  1260. begin
  1261. useownfile:=false;
  1262. close(ownfile);
  1263. end;
  1264. assign(ownfile,name);
  1265. {$I-}
  1266. append(ownfile);
  1267. if IOResult<>0 then
  1268. begin
  1269. Rewrite(ownfile);
  1270. if IOResult<>0 then
  1271. begin
  1272. Writeln(textoutput^,'[heaptrc] Unable to open "',name,'", writing output to stderr instead.');
  1273. useownfile:=false;
  1274. exit;
  1275. end;
  1276. end;
  1277. {$I+}
  1278. useownfile:=true;
  1279. for i:=0 to Paramcount do
  1280. write(ownfile,paramstr(i),' ');
  1281. writeln(ownfile);
  1282. end;
  1283. procedure SetHeapTraceOutput(var ATextOutput : Text);
  1284. Begin
  1285. useowntextoutput := True;
  1286. textoutput := @ATextOutput;
  1287. end;
  1288. procedure SetHeapExtraInfo( size : ptruint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  1289. begin
  1290. { the total size must stay multiple of 8, also allocate 2 pointers for
  1291. the fill and display procvars }
  1292. exact_info_size:=size + sizeof(theap_extra_info);
  1293. extra_info_size:=(exact_info_size+7) and not 7;
  1294. fill_extra_info_proc:=fillproc;
  1295. display_extra_info_proc:=displayproc;
  1296. end;
  1297. {*****************************************************************************
  1298. Install MemoryManager
  1299. *****************************************************************************}
  1300. const
  1301. TraceManager:TMemoryManager=(
  1302. NeedLock : true;
  1303. Getmem : @TraceGetMem;
  1304. Freemem : @TraceFreeMem;
  1305. FreememSize : @TraceFreeMemSize;
  1306. AllocMem : @TraceAllocMem;
  1307. ReAllocMem : @TraceReAllocMem;
  1308. MemSize : @TraceMemSize;
  1309. InitThread: @TraceInitThread;
  1310. DoneThread: @TraceExitThread;
  1311. RelocateHeap: @TraceRelocateHeap;
  1312. GetHeapStatus : @TraceGetHeapStatus;
  1313. GetFPCHeapStatus : @TraceGetFPCHeapStatus;
  1314. );
  1315. var
  1316. PrevMemoryManager : TMemoryManager;
  1317. procedure TraceInit;
  1318. begin
  1319. textoutput := @stderr;
  1320. useowntextoutput := false;
  1321. MakeCRC32Tbl;
  1322. main_orig_todolist := @heap_info.heap_free_todo;
  1323. main_relo_todolist := nil;
  1324. TraceInitThread;
  1325. GetMemoryManager(PrevMemoryManager);
  1326. SetMemoryManager(TraceManager);
  1327. useownfile:=false;
  1328. if outputstr <> '' then
  1329. SetHeapTraceOutput(outputstr);
  1330. {$ifdef EXTRA}
  1331. {$i-}
  1332. Assign(error_file,'heap.err');
  1333. Rewrite(error_file);
  1334. {$i+}
  1335. if IOResult<>0 then
  1336. begin
  1337. writeln('[heaptrc] Unable to create heap.err extra log file, writing output to screen.');
  1338. Assign(error_file,'');
  1339. Rewrite(error_file);
  1340. end;
  1341. {$endif EXTRA}
  1342. { if multithreading was initialized before heaptrc gets initialized (this is currently
  1343. the case for windows dlls), then RelocateHeap gets never called and the lock
  1344. must be initialized already here,
  1345. however, IsMultithread is not set in this case on windows,
  1346. it is set only if a new thread is started
  1347. }
  1348. {$IfNDef WINDOWS}
  1349. if IsMultithread then
  1350. {$EndIf WINDOWS}
  1351. TraceRelocateHeap;
  1352. end;
  1353. procedure TraceExit;
  1354. begin
  1355. { no dump if error
  1356. because this gives long long listings }
  1357. { clear inoutres, in case the program that quit didn't }
  1358. ioresult;
  1359. if (exitcode<>0) and (erroraddr<>nil) then
  1360. begin
  1361. if useownfile then
  1362. begin
  1363. Writeln(ownfile,'No heap dump by heaptrc unit');
  1364. Writeln(ownfile,'Exitcode = ',exitcode);
  1365. end
  1366. else
  1367. begin
  1368. Writeln(textoutput^,'No heap dump by heaptrc unit');
  1369. Writeln(textoutput^,'Exitcode = ',exitcode);
  1370. end;
  1371. if useownfile then
  1372. begin
  1373. useownfile:=false;
  1374. close(ownfile);
  1375. end;
  1376. exit;
  1377. end;
  1378. { Disable heaptrc memory manager to avoid problems }
  1379. SetMemoryManager(PrevMemoryManager);
  1380. move_heap_info(@orphaned_info, @heap_info);
  1381. dumpheap;
  1382. if heap_info.error_in_heap and (exitcode=0) then
  1383. exitcode:=203;
  1384. {$ifdef FPC_HAS_FEATURE_THREADING}
  1385. if main_relo_todolist <> nil then
  1386. donecriticalsection(todo_lock);
  1387. {$endif}
  1388. {$ifdef EXTRA}
  1389. Close(error_file);
  1390. {$endif EXTRA}
  1391. if useownfile then
  1392. begin
  1393. useownfile:=false;
  1394. close(ownfile);
  1395. end;
  1396. if useowntextoutput then
  1397. begin
  1398. useowntextoutput := false;
  1399. close(textoutput^);
  1400. end;
  1401. end;
  1402. {$if defined(win32) or defined(win64)}
  1403. function GetEnvironmentStrings : pchar; stdcall;
  1404. external 'kernel32' name 'GetEnvironmentStringsA';
  1405. function FreeEnvironmentStrings(p : pchar) : longbool; stdcall;
  1406. external 'kernel32' name 'FreeEnvironmentStringsA';
  1407. Function GetEnv(envvar: string): string;
  1408. var
  1409. s : string;
  1410. i : ptruint;
  1411. hp,p : pchar;
  1412. begin
  1413. getenv:='';
  1414. p:=GetEnvironmentStrings;
  1415. hp:=p;
  1416. while hp^<>#0 do
  1417. begin
  1418. s:=strpas(hp);
  1419. i:=pos('=',s);
  1420. if upcase(copy(s,1,i-1))=upcase(envvar) then
  1421. begin
  1422. getenv:=copy(s,i+1,length(s)-i);
  1423. break;
  1424. end;
  1425. { next string entry}
  1426. hp:=hp+strlen(hp)+1;
  1427. end;
  1428. FreeEnvironmentStrings(p);
  1429. end;
  1430. {$elseif defined(wince)}
  1431. Function GetEnv(P:string):Pchar;
  1432. begin
  1433. { WinCE does not have environment strings.
  1434. Add some way to specify heaptrc options? }
  1435. GetEnv:=nil;
  1436. end;
  1437. {$elseif defined(msdos)}
  1438. type
  1439. PFarChar=^Char;far;
  1440. PPFarChar=^PFarChar;
  1441. var
  1442. envp: PPFarChar;external name '__fpc_envp';
  1443. Function GetEnv(P:string):string;
  1444. var
  1445. ep : ppfarchar;
  1446. pc : pfarchar;
  1447. i : smallint;
  1448. found : boolean;
  1449. Begin
  1450. getenv:='';
  1451. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1452. ep:=envp;
  1453. found:=false;
  1454. if ep<>nil then
  1455. begin
  1456. while (not found) and (ep^<>nil) do
  1457. begin
  1458. found:=true;
  1459. for i:=1 to length(p) do
  1460. if p[i]<>ep^[i-1] then
  1461. begin
  1462. found:=false;
  1463. break;
  1464. end;
  1465. if not found then
  1466. inc(ep);
  1467. end;
  1468. end;
  1469. if found then
  1470. begin
  1471. pc:=ep^+length(p);
  1472. while pc^<>#0 do
  1473. begin
  1474. getenv:=getenv+pc^;
  1475. Inc(pc);
  1476. end;
  1477. end;
  1478. end;
  1479. {$else}
  1480. Function GetEnv(P:string):Pchar;
  1481. {
  1482. Searches the environment for a string with name p and
  1483. returns a pchar to it's value.
  1484. A pchar is used to accomodate for strings of length > 255
  1485. }
  1486. var
  1487. ep : ppchar;
  1488. i : ptruint;
  1489. found : boolean;
  1490. Begin
  1491. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1492. ep:=envp;
  1493. found:=false;
  1494. if ep<>nil then
  1495. begin
  1496. while (not found) and (ep^<>nil) do
  1497. begin
  1498. found:=true;
  1499. for i:=1 to length(p) do
  1500. if p[i]<>ep^[i-1] then
  1501. begin
  1502. found:=false;
  1503. break;
  1504. end;
  1505. if not found then
  1506. inc(ep);
  1507. end;
  1508. end;
  1509. if found then
  1510. getenv:=ep^+length(p)
  1511. else
  1512. getenv:=nil;
  1513. end;
  1514. {$endif}
  1515. procedure LoadEnvironment;
  1516. var
  1517. i,j : ptruint;
  1518. s,s2 : string;
  1519. err : word;
  1520. begin
  1521. s:=Getenv('HEAPTRC');
  1522. if pos('keepreleased',s)>0 then
  1523. keepreleased:=true;
  1524. if pos('disabled',s)>0 then
  1525. useheaptrace:=false;
  1526. if pos('nohalt',s)>0 then
  1527. haltonerror:=false;
  1528. if pos('haltonnotreleased',s)>0 then
  1529. HaltOnNotReleased :=true;
  1530. if pos('skipifnoleaks',s)>0 then
  1531. GlobalSkipIfNoLeaks :=true;
  1532. if pos('tail_size=',s)>0 then
  1533. begin
  1534. i:=pos('tail_size=',s)+length('tail_size=');
  1535. s2:='';
  1536. while (i<=length(s)) and (s[i] in ['0'..'9']) do
  1537. begin
  1538. s2:=s2+s[i];
  1539. inc(i);
  1540. end;
  1541. val(s2,tail_size,err);
  1542. if err=0 then
  1543. tail_size:=((tail_size + sizeof(ptruint)-1) div sizeof(ptruint)) * sizeof(ptruint)
  1544. else
  1545. tail_size:=sizeof(ptruint);
  1546. add_tail:=(tail_size > 0);
  1547. end;
  1548. i:=pos('log=',s);
  1549. if i>0 then
  1550. begin
  1551. outputstr:=copy(s,i+4,255);
  1552. j:=pos(' ',outputstr);
  1553. if j=0 then
  1554. j:=length(outputstr)+1;
  1555. delete(outputstr,j,255);
  1556. end;
  1557. end;
  1558. Initialization
  1559. LoadEnvironment;
  1560. { heaptrc can be disabled from the environment }
  1561. if useheaptrace then
  1562. TraceInit;
  1563. finalization
  1564. if useheaptrace then
  1565. TraceExit;
  1566. end.