2
0

heaptrc.pp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  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 = 32;
  45. {$else EXTRA}
  46. tracesize = 16;
  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 freebsd}
  889. var
  890. text_start: ptruint; external name '__executable_start';
  891. etext: ptruint; external name '_etext';
  892. eend : ptruint; external name '_end';
  893. {$endif}
  894. {$ifdef os2}
  895. (* Currently still EMX based - possibly to be changed in the future. *)
  896. var
  897. etext: ptruint; external name '_etext';
  898. edata : ptruint; external name '_edata';
  899. eend : ptruint; external name '_end';
  900. {$endif}
  901. {$ifdef windows}
  902. var
  903. sdata : ptruint; external name '__data_start__';
  904. edata : ptruint; external name '__data_end__';
  905. sbss : ptruint; external name '__bss_start__';
  906. ebss : ptruint; external name '__bss_end__';
  907. TLSKey : PDWord; external name '_FPC_TlsKey';
  908. TLSSize : DWord; external name '_FPC_TlsSize';
  909. function TlsGetValue(dwTlsIndex : DWord) : pointer;
  910. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TlsGetValue';
  911. {$endif}
  912. {$ifdef BEOS}
  913. const
  914. B_ERROR = -1;
  915. type
  916. area_id = Longint;
  917. function area_for(addr : Pointer) : area_id;
  918. cdecl; external 'root' name 'area_for';
  919. {$endif BEOS}
  920. procedure CheckPointer(p : pointer); [public, alias : 'FPC_CHECKPOINTER'];
  921. var
  922. i : ptruint;
  923. pp : pheap_mem_info;
  924. loc_info: pheap_info;
  925. {$ifdef go32v2}
  926. get_ebp,stack_top : longword;
  927. bss_end : longword;
  928. {$endif go32v2}
  929. {$ifdef windows}
  930. datap : pointer;
  931. {$endif windows}
  932. ptext : ^text;
  933. begin
  934. if p=nil then
  935. runerror(204);
  936. i:=0;
  937. loc_info:=@heap_info;
  938. if useownfile then
  939. ptext:=@ownfile
  940. else
  941. ptext:=textoutput;
  942. {$ifdef go32v2}
  943. if ptruint(p)<$1000 then
  944. runerror(216);
  945. asm
  946. movl %ebp,get_ebp
  947. leal ebss,%eax
  948. movl %eax,bss_end
  949. end;
  950. stack_top:=__stkbottom+__stklen;
  951. { allow all between start of code and end of bss }
  952. if ptruint(p)<=bss_end then
  953. exit;
  954. { stack can be above heap !! }
  955. if (ptruint(p)>=get_ebp) and (ptruint(p)<=stack_top) then
  956. exit;
  957. {$endif go32v2}
  958. { I don't know where the stack is in other OS !! }
  959. {$ifdef windows}
  960. { inside stack ? }
  961. if (ptruint(p)>ptruint(get_frame)) and
  962. (p<StackTop) then
  963. exit;
  964. { inside data, rdata ... bss }
  965. if (ptruint(p)>=ptruint(@sdata)) and (ptruint(p)<ptruint(@ebss)) then
  966. exit;
  967. { is program multi-threaded and p inside Threadvar range? }
  968. if TlsKey^<>-1 then
  969. begin
  970. datap:=TlsGetValue(tlskey^);
  971. if ((ptruint(p)>=ptruint(datap)) and
  972. (ptruint(p)<ptruint(datap)+TlsSize)) then
  973. exit;
  974. end;
  975. {$endif windows}
  976. {$IFDEF OS2}
  977. { inside stack ? }
  978. if (PtrUInt (P) > PtrUInt (Get_Frame)) and
  979. (PtrUInt (P) < PtrUInt (StackTop)) then
  980. exit;
  981. { inside data or bss ? }
  982. if (PtrUInt (P) >= PtrUInt (@etext)) and (PtrUInt (P) < PtrUInt (@eend)) then
  983. exit;
  984. {$ENDIF OS2}
  985. {$ifdef linux}
  986. { inside stack ? }
  987. if (ptruint(p)>ptruint(get_frame)) and
  988. (ptruint(p)<ptruint(StackTop)) then
  989. exit;
  990. { inside data or bss ? }
  991. if (ptruint(p)>=ptruint(@etext)) and (ptruint(p)<ptruint(@eend)) then
  992. exit;
  993. {$endif linux}
  994. {$ifdef freebsd}
  995. { inside stack ? }
  996. if (ptruint(p)>ptruint(get_frame)) and
  997. (ptruint(p)<ptruint(StackTop)) then
  998. exit;
  999. { inside data or bss ? }
  1000. if (ptruint(p)>=ptruint(@text_start)) and (ptruint(p)<ptruint(@eend)) then
  1001. exit;
  1002. {$endif linux}
  1003. {$ifdef morphos}
  1004. { inside stack ? }
  1005. if (ptruint(p)<ptruint(StackTop)) and (ptruint(p)>ptruint(StackBottom)) then
  1006. exit;
  1007. { inside data or bss ? }
  1008. {$WARNING data and bss checking missing }
  1009. {$endif morphos}
  1010. {$ifdef darwin}
  1011. {$warning No checkpointer support yet for Darwin}
  1012. exit;
  1013. {$endif}
  1014. {$ifdef BEOS}
  1015. // if we find the address in a known area in our current process,
  1016. // then it is a valid one
  1017. if area_for(p) <> B_ERROR then
  1018. exit;
  1019. {$endif BEOS}
  1020. { first try valid list faster }
  1021. {$ifdef EXTRA}
  1022. pp:=loc_info^.heap_valid_last;
  1023. while pp<>nil do
  1024. begin
  1025. { inside this valid block ! }
  1026. { we can be changing the extrainfo !! }
  1027. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info){+extra_info_size}) and
  1028. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+extra_info_size+pp^.size) then
  1029. begin
  1030. { check allocated block }
  1031. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1032. ((pp^.sig=calculate_sig(pp)) and usecrc) or
  1033. { special case of the fill_extra_info call }
  1034. ((pp=loc_info^.heap_valid_last) and usecrc and (pp^.sig=longword(AllocateSig))
  1035. and loc_info^.inside_trace_getmem) then
  1036. exit
  1037. else
  1038. begin
  1039. writeln(ptext^,'corrupted heap_mem_info');
  1040. dump_error(pp,ptext^);
  1041. halt(1);
  1042. end;
  1043. end
  1044. else
  1045. pp:=pp^.prev_valid;
  1046. inc(i);
  1047. if i>loc_info^.getmem_cnt-loc_info^.freemem_cnt then
  1048. begin
  1049. writeln(ptext^,'error in linked list of heap_mem_info');
  1050. halt(1);
  1051. end;
  1052. end;
  1053. i:=0;
  1054. {$endif EXTRA}
  1055. pp:=loc_info^.heap_mem_root;
  1056. while pp<>nil do
  1057. begin
  1058. { inside this block ! }
  1059. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)) and
  1060. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)+ptruint(pp^.size)) then
  1061. { allocated block }
  1062. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1063. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  1064. exit
  1065. else
  1066. begin
  1067. writeln(ptext^,'pointer $',hexstr(p),' points into invalid memory block');
  1068. dump_error(pp,ptext^);
  1069. runerror(204);
  1070. end;
  1071. pp:=pp^.previous;
  1072. inc(i);
  1073. if i>loc_info^.getmem_cnt then
  1074. begin
  1075. writeln(ptext^,'error in linked list of heap_mem_info');
  1076. halt(1);
  1077. end;
  1078. end;
  1079. writeln(ptext^,'pointer $',hexstr(p),' does not point to valid memory block');
  1080. dump_stack(ptext^,1);
  1081. runerror(204);
  1082. end;
  1083. {*****************************************************************************
  1084. Dump Heap
  1085. *****************************************************************************}
  1086. procedure dumpheap;
  1087. begin
  1088. DumpHeap(GlobalSkipIfNoLeaks);
  1089. end;
  1090. procedure dumpheap(SkipIfNoLeaks : Boolean);
  1091. var
  1092. pp : pheap_mem_info;
  1093. i : ptrint;
  1094. ExpectedHeapFree : ptruint;
  1095. status : TFPCHeapStatus;
  1096. ptext : ^text;
  1097. loc_info: pheap_info;
  1098. begin
  1099. loc_info:=@heap_info;
  1100. if useownfile then
  1101. ptext:=@ownfile
  1102. else
  1103. ptext:=textoutput;
  1104. pp:=loc_info^.heap_mem_root;
  1105. if ((loc_info^.getmem_size-loc_info^.freemem_size)=0) and SkipIfNoLeaks then
  1106. exit;
  1107. Writeln(ptext^,'Heap dump by heaptrc unit of '+ParamStr(0));
  1108. Writeln(ptext^,loc_info^.getmem_cnt, ' memory blocks allocated : ',
  1109. loc_info^.getmem_size,'/',loc_info^.getmem8_size);
  1110. Writeln(ptext^,loc_info^.freemem_cnt,' memory blocks freed : ',
  1111. loc_info^.freemem_size,'/',loc_info^.freemem8_size);
  1112. Writeln(ptext^,loc_info^.getmem_cnt-loc_info^.freemem_cnt,
  1113. ' unfreed memory blocks : ',loc_info^.getmem_size-loc_info^.freemem_size);
  1114. status:=SysGetFPCHeapStatus;
  1115. Write(ptext^,'True heap size : ',status.CurrHeapSize);
  1116. if EntryMemUsed > 0 then
  1117. Writeln(ptext^,' (',EntryMemUsed,' used in System startup)')
  1118. else
  1119. Writeln(ptext^);
  1120. Writeln(ptext^,'True free heap : ',status.CurrHeapFree);
  1121. ExpectedHeapFree:=status.CurrHeapSize
  1122. -(loc_info^.getmem8_size-loc_info^.freemem8_size)
  1123. -(loc_info^.getmem_cnt-loc_info^.freemem_cnt)*(sizeof(theap_mem_info)+extra_info_size)
  1124. -EntryMemUsed;
  1125. If ExpectedHeapFree<>status.CurrHeapFree then
  1126. Writeln(ptext^,'Should be : ',ExpectedHeapFree);
  1127. i:=loc_info^.getmem_cnt-loc_info^.freemem_cnt;
  1128. while pp<>nil do
  1129. begin
  1130. if i<0 then
  1131. begin
  1132. Writeln(ptext^,'Error in heap memory list');
  1133. Writeln(ptext^,'More memory blocks than expected');
  1134. exit;
  1135. end;
  1136. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1137. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  1138. begin
  1139. { this one was not released !! }
  1140. if exitcode<>203 then
  1141. call_stack(pp,ptext^);
  1142. dec(i);
  1143. end
  1144. else if pp^.sig<>longword(ReleaseSig) then
  1145. begin
  1146. dump_error(pp,ptext^);
  1147. if @stderr<>ptext then
  1148. dump_error(pp,stderr);
  1149. {$ifdef EXTRA}
  1150. dump_error(pp,error_file);
  1151. {$endif EXTRA}
  1152. loc_info^.error_in_heap:=true;
  1153. end
  1154. {$ifdef EXTRA}
  1155. else if pp^.release_sig<>calculate_release_sig(pp) then
  1156. begin
  1157. dump_change_after(pp,ptext^);
  1158. dump_change_after(pp,error_file);
  1159. loc_info^.error_in_heap:=true;
  1160. end
  1161. {$else not EXTRA}
  1162. else
  1163. begin
  1164. if released_modified(pp,ptext^) then
  1165. exitcode:=203;
  1166. end;
  1167. {$endif EXTRA}
  1168. ;
  1169. pp:=pp^.previous;
  1170. end;
  1171. if HaltOnNotReleased and (loc_info^.getmem_cnt<>loc_info^.freemem_cnt) then
  1172. exitcode:=203;
  1173. end;
  1174. {*****************************************************************************
  1175. AllocMem
  1176. *****************************************************************************}
  1177. function TraceAllocMem(size:ptruint):Pointer;
  1178. begin
  1179. TraceAllocMem := TraceGetMem(size);
  1180. if Assigned(TraceAllocMem) then
  1181. FillChar(TraceAllocMem^, TraceMemSize(TraceAllocMem), 0);
  1182. end;
  1183. {*****************************************************************************
  1184. No specific tracing calls
  1185. *****************************************************************************}
  1186. procedure TraceInitThread;
  1187. var
  1188. loc_info: pheap_info;
  1189. begin
  1190. loc_info := @heap_info;
  1191. {$ifdef EXTRA}
  1192. loc_info^.heap_valid_first := nil;
  1193. loc_info^.heap_valid_last := nil;
  1194. {$endif}
  1195. loc_info^.heap_mem_root := nil;
  1196. loc_info^.getmem_cnt := 0;
  1197. loc_info^.freemem_cnt := 0;
  1198. loc_info^.getmem_size := 0;
  1199. loc_info^.freemem_size := 0;
  1200. loc_info^.getmem8_size := 0;
  1201. loc_info^.freemem8_size := 0;
  1202. loc_info^.error_in_heap := false;
  1203. loc_info^.inside_trace_getmem := false;
  1204. EntryMemUsed := SysGetFPCHeapStatus.CurrHeapUsed;
  1205. end;
  1206. procedure TraceRelocateHeap;
  1207. begin
  1208. main_relo_todolist := @heap_info.heap_free_todo;
  1209. {$ifdef FPC_HAS_FEATURE_THREADING}
  1210. initcriticalsection(todo_lock);
  1211. {$endif}
  1212. end;
  1213. procedure move_heap_info(src_info, dst_info: pheap_info);
  1214. var
  1215. heap_mem: pheap_mem_info;
  1216. begin
  1217. if src_info^.heap_free_todo <> nil then
  1218. finish_heap_free_todo_list(src_info);
  1219. if dst_info^.heap_free_todo <> nil then
  1220. finish_heap_free_todo_list(dst_info);
  1221. heap_mem := src_info^.heap_mem_root;
  1222. if heap_mem <> nil then
  1223. begin
  1224. repeat
  1225. heap_mem^.todolist := @dst_info^.heap_free_todo;
  1226. if heap_mem^.previous = nil then break;
  1227. heap_mem := heap_mem^.previous;
  1228. until false;
  1229. heap_mem^.previous := dst_info^.heap_mem_root;
  1230. if dst_info^.heap_mem_root <> nil then
  1231. dst_info^.heap_mem_root^.next := heap_mem;
  1232. dst_info^.heap_mem_root := src_info^.heap_mem_root;
  1233. end;
  1234. inc(dst_info^.getmem_cnt, src_info^.getmem_cnt);
  1235. inc(dst_info^.getmem_size, src_info^.getmem_size);
  1236. inc(dst_info^.getmem8_size, src_info^.getmem8_size);
  1237. inc(dst_info^.freemem_cnt, src_info^.freemem_cnt);
  1238. inc(dst_info^.freemem_size, src_info^.freemem_size);
  1239. inc(dst_info^.freemem8_size, src_info^.freemem8_size);
  1240. dst_info^.error_in_heap := dst_info^.error_in_heap or src_info^.error_in_heap;
  1241. {$ifdef EXTRA}
  1242. if assigned(dst_info^.heap_valid_first) then
  1243. dst_info^.heap_valid_first^.prev_valid := src_info^.heap_valid_last
  1244. else
  1245. dst_info^.heap_valid_last := src_info^.heap_valid_last;
  1246. dst_info^.heap_valid_first := src_info^.heap_valid_first;
  1247. {$endif}
  1248. end;
  1249. procedure TraceExitThread;
  1250. var
  1251. loc_info: pheap_info;
  1252. begin
  1253. loc_info := @heap_info;
  1254. {$ifdef FPC_HAS_FEATURE_THREADING}
  1255. entercriticalsection(todo_lock);
  1256. {$endif}
  1257. move_heap_info(loc_info, @orphaned_info);
  1258. {$ifdef FPC_HAS_FEATURE_THREADING}
  1259. leavecriticalsection(todo_lock);
  1260. {$endif}
  1261. end;
  1262. function TraceGetHeapStatus:THeapStatus;
  1263. begin
  1264. TraceGetHeapStatus:=SysGetHeapStatus;
  1265. end;
  1266. function TraceGetFPCHeapStatus:TFPCHeapStatus;
  1267. begin
  1268. TraceGetFPCHeapStatus:=SysGetFPCHeapStatus;
  1269. end;
  1270. {*****************************************************************************
  1271. Program Hooks
  1272. *****************************************************************************}
  1273. Procedure SetHeapTraceOutput(const name : string);
  1274. var i : ptruint;
  1275. begin
  1276. if useownfile then
  1277. begin
  1278. useownfile:=false;
  1279. close(ownfile);
  1280. end;
  1281. assign(ownfile,name);
  1282. {$I-}
  1283. append(ownfile);
  1284. if IOResult<>0 then
  1285. begin
  1286. Rewrite(ownfile);
  1287. if IOResult<>0 then
  1288. begin
  1289. Writeln(textoutput^,'[heaptrc] Unable to open "',name,'", writing output to stderr instead.');
  1290. useownfile:=false;
  1291. exit;
  1292. end;
  1293. end;
  1294. {$I+}
  1295. useownfile:=true;
  1296. for i:=0 to Paramcount do
  1297. write(ownfile,paramstr(i),' ');
  1298. writeln(ownfile);
  1299. end;
  1300. procedure SetHeapTraceOutput(var ATextOutput : Text);
  1301. Begin
  1302. useowntextoutput := True;
  1303. textoutput := @ATextOutput;
  1304. end;
  1305. procedure SetHeapExtraInfo( size : ptruint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  1306. begin
  1307. { the total size must stay multiple of 8, also allocate 2 pointers for
  1308. the fill and display procvars }
  1309. exact_info_size:=size + sizeof(theap_extra_info);
  1310. extra_info_size:=(exact_info_size+7) and not 7;
  1311. fill_extra_info_proc:=fillproc;
  1312. display_extra_info_proc:=displayproc;
  1313. end;
  1314. {*****************************************************************************
  1315. Install MemoryManager
  1316. *****************************************************************************}
  1317. const
  1318. TraceManager:TMemoryManager=(
  1319. NeedLock : true;
  1320. Getmem : @TraceGetMem;
  1321. Freemem : @TraceFreeMem;
  1322. FreememSize : @TraceFreeMemSize;
  1323. AllocMem : @TraceAllocMem;
  1324. ReAllocMem : @TraceReAllocMem;
  1325. MemSize : @TraceMemSize;
  1326. InitThread: @TraceInitThread;
  1327. DoneThread: @TraceExitThread;
  1328. RelocateHeap: @TraceRelocateHeap;
  1329. GetHeapStatus : @TraceGetHeapStatus;
  1330. GetFPCHeapStatus : @TraceGetFPCHeapStatus;
  1331. );
  1332. var
  1333. PrevMemoryManager : TMemoryManager;
  1334. procedure TraceInit;
  1335. begin
  1336. textoutput := @stderr;
  1337. useowntextoutput := false;
  1338. MakeCRC32Tbl;
  1339. main_orig_todolist := @heap_info.heap_free_todo;
  1340. main_relo_todolist := nil;
  1341. TraceInitThread;
  1342. GetMemoryManager(PrevMemoryManager);
  1343. SetMemoryManager(TraceManager);
  1344. useownfile:=false;
  1345. if outputstr <> '' then
  1346. SetHeapTraceOutput(outputstr);
  1347. {$ifdef EXTRA}
  1348. {$i-}
  1349. Assign(error_file,'heap.err');
  1350. Rewrite(error_file);
  1351. {$i+}
  1352. if IOResult<>0 then
  1353. begin
  1354. writeln('[heaptrc] Unable to create heap.err extra log file, writing output to screen.');
  1355. Assign(error_file,'');
  1356. Rewrite(error_file);
  1357. end;
  1358. {$endif EXTRA}
  1359. { if multithreading was initialized before heaptrc gets initialized (this is currently
  1360. the case for windows dlls), then RelocateHeap gets never called and the lock
  1361. must be initialized already here,
  1362. however, IsMultithread is not set in this case on windows,
  1363. it is set only if a new thread is started
  1364. }
  1365. {$IfNDef WINDOWS}
  1366. if IsMultithread then
  1367. {$EndIf WINDOWS}
  1368. TraceRelocateHeap;
  1369. end;
  1370. procedure TraceExit;
  1371. begin
  1372. { no dump if error
  1373. because this gives long long listings }
  1374. { clear inoutres, in case the program that quit didn't }
  1375. ioresult;
  1376. if (exitcode<>0) and (erroraddr<>nil) then
  1377. begin
  1378. if useownfile then
  1379. begin
  1380. Writeln(ownfile,'No heap dump by heaptrc unit');
  1381. Writeln(ownfile,'Exitcode = ',exitcode);
  1382. end
  1383. else
  1384. begin
  1385. Writeln(textoutput^,'No heap dump by heaptrc unit');
  1386. Writeln(textoutput^,'Exitcode = ',exitcode);
  1387. end;
  1388. if useownfile then
  1389. begin
  1390. useownfile:=false;
  1391. close(ownfile);
  1392. end;
  1393. exit;
  1394. end;
  1395. { Disable heaptrc memory manager to avoid problems }
  1396. SetMemoryManager(PrevMemoryManager);
  1397. move_heap_info(@orphaned_info, @heap_info);
  1398. dumpheap;
  1399. if heap_info.error_in_heap and (exitcode=0) then
  1400. exitcode:=203;
  1401. {$ifdef FPC_HAS_FEATURE_THREADING}
  1402. if main_relo_todolist <> nil then
  1403. donecriticalsection(todo_lock);
  1404. {$endif}
  1405. {$ifdef EXTRA}
  1406. Close(error_file);
  1407. {$endif EXTRA}
  1408. if useownfile then
  1409. begin
  1410. useownfile:=false;
  1411. close(ownfile);
  1412. end;
  1413. if useowntextoutput then
  1414. begin
  1415. useowntextoutput := false;
  1416. close(textoutput^);
  1417. end;
  1418. end;
  1419. {$if defined(win32) or defined(win64)}
  1420. function GetEnvironmentStrings : pchar; stdcall;
  1421. external 'kernel32' name 'GetEnvironmentStringsA';
  1422. function FreeEnvironmentStrings(p : pchar) : longbool; stdcall;
  1423. external 'kernel32' name 'FreeEnvironmentStringsA';
  1424. Function GetEnv(envvar: string): string;
  1425. var
  1426. s : string;
  1427. i : ptruint;
  1428. hp,p : pchar;
  1429. begin
  1430. getenv:='';
  1431. p:=GetEnvironmentStrings;
  1432. hp:=p;
  1433. while hp^<>#0 do
  1434. begin
  1435. s:=strpas(hp);
  1436. i:=pos('=',s);
  1437. if upcase(copy(s,1,i-1))=upcase(envvar) then
  1438. begin
  1439. getenv:=copy(s,i+1,length(s)-i);
  1440. break;
  1441. end;
  1442. { next string entry}
  1443. hp:=hp+strlen(hp)+1;
  1444. end;
  1445. FreeEnvironmentStrings(p);
  1446. end;
  1447. {$elseif defined(wince)}
  1448. Function GetEnv(P:string):Pchar;
  1449. begin
  1450. { WinCE does not have environment strings.
  1451. Add some way to specify heaptrc options? }
  1452. GetEnv:=nil;
  1453. end;
  1454. {$elseif defined(msdos)}
  1455. type
  1456. PFarChar=^Char;far;
  1457. PPFarChar=^PFarChar;
  1458. var
  1459. envp: PPFarChar;external name '__fpc_envp';
  1460. Function GetEnv(P:string):string;
  1461. var
  1462. ep : ppfarchar;
  1463. pc : pfarchar;
  1464. i : smallint;
  1465. found : boolean;
  1466. Begin
  1467. getenv:='';
  1468. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1469. ep:=envp;
  1470. found:=false;
  1471. if ep<>nil then
  1472. begin
  1473. while (not found) and (ep^<>nil) do
  1474. begin
  1475. found:=true;
  1476. for i:=1 to length(p) do
  1477. if p[i]<>ep^[i-1] then
  1478. begin
  1479. found:=false;
  1480. break;
  1481. end;
  1482. if not found then
  1483. inc(ep);
  1484. end;
  1485. end;
  1486. if found then
  1487. begin
  1488. pc:=ep^+length(p);
  1489. while pc^<>#0 do
  1490. begin
  1491. getenv:=getenv+pc^;
  1492. Inc(pc);
  1493. end;
  1494. end;
  1495. end;
  1496. {$else}
  1497. Function GetEnv(P:string):Pchar;
  1498. {
  1499. Searches the environment for a string with name p and
  1500. returns a pchar to it's value.
  1501. A pchar is used to accomodate for strings of length > 255
  1502. }
  1503. var
  1504. ep : ppchar;
  1505. i : ptruint;
  1506. found : boolean;
  1507. Begin
  1508. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1509. ep:=envp;
  1510. found:=false;
  1511. if ep<>nil then
  1512. begin
  1513. while (not found) and (ep^<>nil) do
  1514. begin
  1515. found:=true;
  1516. for i:=1 to length(p) do
  1517. if p[i]<>ep^[i-1] then
  1518. begin
  1519. found:=false;
  1520. break;
  1521. end;
  1522. if not found then
  1523. inc(ep);
  1524. end;
  1525. end;
  1526. if found then
  1527. getenv:=ep^+length(p)
  1528. else
  1529. getenv:=nil;
  1530. end;
  1531. {$endif}
  1532. procedure LoadEnvironment;
  1533. var
  1534. i,j : ptruint;
  1535. s,s2 : string;
  1536. err : word;
  1537. begin
  1538. s:=Getenv('HEAPTRC');
  1539. if pos('keepreleased',s)>0 then
  1540. keepreleased:=true;
  1541. if pos('disabled',s)>0 then
  1542. useheaptrace:=false;
  1543. if pos('nohalt',s)>0 then
  1544. haltonerror:=false;
  1545. if pos('haltonnotreleased',s)>0 then
  1546. HaltOnNotReleased :=true;
  1547. if pos('skipifnoleaks',s)>0 then
  1548. GlobalSkipIfNoLeaks :=true;
  1549. if pos('tail_size=',s)>0 then
  1550. begin
  1551. i:=pos('tail_size=',s)+length('tail_size=');
  1552. s2:='';
  1553. while (i<=length(s)) and (s[i] in ['0'..'9']) do
  1554. begin
  1555. s2:=s2+s[i];
  1556. inc(i);
  1557. end;
  1558. val(s2,tail_size,err);
  1559. if err=0 then
  1560. tail_size:=((tail_size + sizeof(ptruint)-1) div sizeof(ptruint)) * sizeof(ptruint)
  1561. else
  1562. tail_size:=sizeof(ptruint);
  1563. add_tail:=(tail_size > 0);
  1564. end;
  1565. i:=pos('log=',s);
  1566. if i>0 then
  1567. begin
  1568. outputstr:=copy(s,i+4,255);
  1569. j:=pos(' ',outputstr);
  1570. if j=0 then
  1571. j:=length(outputstr)+1;
  1572. delete(outputstr,j,255);
  1573. end;
  1574. end;
  1575. Initialization
  1576. LoadEnvironment;
  1577. { heaptrc can be disabled from the environment }
  1578. if useheaptrace then
  1579. TraceInit;
  1580. finalization
  1581. if useheaptrace then
  1582. TraceExit;
  1583. end.