heaptrc.pp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  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. { Do the real GetMem, but alloc also for the info block }
  452. {$ifdef cpuarm}
  453. allocsize:=(size + 3) and not 3+sizeof(theap_mem_info)+extra_info_size;
  454. {$else cpuarm}
  455. allocsize:=size+sizeof(theap_mem_info)+extra_info_size;
  456. {$endif cpuarm}
  457. if add_tail then
  458. inc(allocsize,tail_size);
  459. { if ReturnNilIfGrowHeapFails is true
  460. SysGetMem can return nil }
  461. p:=SysGetMem(allocsize);
  462. if (p=nil) then
  463. begin
  464. TraceGetMem:=nil;
  465. exit;
  466. end;
  467. pp:=pheap_mem_info(p);
  468. inc(p,sizeof(theap_mem_info));
  469. { Update getmem_size and getmem8_size only after successful call
  470. to SysGetMem }
  471. inc(loc_info^.getmem_size,size);
  472. inc(loc_info^.getmem8_size,(size+7) and not 7);
  473. { Create the info block }
  474. pp^.sig:=longword(AllocateSig);
  475. pp^.todolist:=@loc_info^.heap_free_todo;
  476. pp^.todonext:=nil;
  477. pp^.size:=size;
  478. pp^.extra_info_size:=extra_info_size;
  479. pp^.exact_info_size:=exact_info_size;
  480. fillchar(pp^.calls[1],sizeof(pp^.calls),#0);
  481. {
  482. the end of the block contains:
  483. <tail> 4 bytes
  484. <extra_info> X bytes
  485. }
  486. if extra_info_size>0 then
  487. begin
  488. pp^.extra_info:=pointer(pp)+allocsize-extra_info_size;
  489. fillchar(pp^.extra_info^,extra_info_size,0);
  490. pp^.extra_info^.check:=cardinal(CheckSig);
  491. pp^.extra_info^.fillproc:=fill_extra_info_proc;
  492. pp^.extra_info^.displayproc:=display_extra_info_proc;
  493. if assigned(fill_extra_info_proc) then
  494. begin
  495. loc_info^.inside_trace_getmem:=true;
  496. fill_extra_info_proc(@pp^.extra_info^.data);
  497. loc_info^.inside_trace_getmem:=false;
  498. end;
  499. end
  500. else
  501. pp^.extra_info:=nil;
  502. if add_tail then
  503. begin
  504. { Calculate position from start because of arm
  505. specific alignment }
  506. pl:=pointer(pp)+sizeof(theap_mem_info)+pp^.size;
  507. for i:=1 to tail_size div sizeof(dword) do
  508. begin
  509. unaligned(pl^):=dword(AllocateSig);
  510. inc(pointer(pl),sizeof(dword));
  511. end;
  512. end;
  513. { clear the memory }
  514. fillchar(p^,size,#255);
  515. { retrieve backtrace info }
  516. CaptureBacktrace(1,tracesize,@pp^.calls[1]);
  517. { insert in the linked list }
  518. if loc_info^.heap_mem_root<>nil then
  519. loc_info^.heap_mem_root^.next:=pp;
  520. pp^.previous:=loc_info^.heap_mem_root;
  521. pp^.next:=nil;
  522. {$ifdef EXTRA}
  523. pp^.prev_valid:=loc_info^.heap_valid_last;
  524. loc_info^.heap_valid_last:=pp;
  525. if not assigned(loc_info^.heap_valid_first) then
  526. loc_info^.heap_valid_first:=pp;
  527. {$endif EXTRA}
  528. loc_info^.heap_mem_root:=pp;
  529. { must be changed before fill_extra_info is called
  530. because checkpointer can be called from within
  531. fill_extra_info PM }
  532. inc(loc_info^.getmem_cnt);
  533. { update the signature }
  534. if usecrc then
  535. pp^.sig:=calculate_sig(pp);
  536. TraceGetmem:=p;
  537. end;
  538. {*****************************************************************************
  539. TraceFreeMem
  540. *****************************************************************************}
  541. function CheckFreeMemSize(loc_info: pheap_info; pp: pheap_mem_info;
  542. size, ppsize: ptruint): boolean; inline;
  543. var
  544. ptext : ^text;
  545. {$ifdef EXTRA}
  546. pp2 : pheap_mem_info;
  547. {$endif}
  548. begin
  549. if useownfile then
  550. ptext:=@ownfile
  551. else
  552. ptext:=textoutput;
  553. inc(loc_info^.freemem_size,size);
  554. inc(loc_info^.freemem8_size,(size+7) and not 7);
  555. if not quicktrace then
  556. begin
  557. if not(is_in_getmem_list(loc_info, pp)) then
  558. RunError(204);
  559. end;
  560. if (pp^.sig=longword(ReleaseSig)) then
  561. begin
  562. loc_info^.error_in_heap:=true;
  563. dump_already_free(pp,ptext^);
  564. if haltonerror then halt(1);
  565. end
  566. else if ((pp^.sig<>longword(AllocateSig)) or usecrc) and
  567. ((pp^.sig<>calculate_sig(pp)) or not usecrc) then
  568. begin
  569. loc_info^.error_in_heap:=true;
  570. dump_error(pp,ptext^);
  571. {$ifdef EXTRA}
  572. dump_error(pp,error_file);
  573. {$endif EXTRA}
  574. { don't release anything in this case !! }
  575. if haltonerror then halt(1);
  576. exit;
  577. end
  578. else if pp^.size<>size then
  579. begin
  580. loc_info^.error_in_heap:=true;
  581. dump_wrong_size(pp,size,ptext^);
  582. {$ifdef EXTRA}
  583. dump_wrong_size(pp,size,error_file);
  584. {$endif EXTRA}
  585. if haltonerror then halt(1);
  586. { don't release anything in this case !! }
  587. exit;
  588. end;
  589. { now it is released !! }
  590. pp^.sig:=longword(ReleaseSig);
  591. if not keepreleased then
  592. begin
  593. if pp^.next<>nil then
  594. pp^.next^.previous:=pp^.previous;
  595. if pp^.previous<>nil then
  596. pp^.previous^.next:=pp^.next;
  597. if pp=loc_info^.heap_mem_root then
  598. loc_info^.heap_mem_root:=loc_info^.heap_mem_root^.previous;
  599. end
  600. else
  601. CaptureBacktrace(1,(tracesize div 2)-1,@pp^.calls[(tracesize div 2)+1]);
  602. inc(loc_info^.freemem_cnt);
  603. { clear the memory, $F0 will lead to GFP if used as pointer ! }
  604. fillchar((pointer(pp)+sizeof(theap_mem_info))^,size,#240);
  605. { this way we keep all info about all released memory !! }
  606. if keepreleased then
  607. begin
  608. {$ifdef EXTRA}
  609. { We want to check if the memory was changed after release !! }
  610. pp^.release_sig:=calculate_release_sig(pp);
  611. if pp=loc_info^.heap_valid_last then
  612. begin
  613. loc_info^.heap_valid_last:=pp^.prev_valid;
  614. if pp=loc_info^.heap_valid_first then
  615. loc_info^.heap_valid_first:=nil;
  616. exit(false);
  617. end;
  618. pp2:=loc_info^.heap_valid_last;
  619. while assigned(pp2) do
  620. begin
  621. if pp2^.prev_valid=pp then
  622. begin
  623. pp2^.prev_valid:=pp^.prev_valid;
  624. if pp=loc_info^.heap_valid_first then
  625. loc_info^.heap_valid_first:=pp2;
  626. exit(false);
  627. end
  628. else
  629. pp2:=pp2^.prev_valid;
  630. end;
  631. {$endif EXTRA}
  632. exit(false);
  633. end;
  634. CheckFreeMemSize:=true;
  635. end;
  636. function InternalFreeMemSize(loc_info: pheap_info; p: pointer; pp: pheap_mem_info;
  637. size: ptruint; release_todo_lock: boolean): ptruint;
  638. var
  639. i,ppsize : ptruint;
  640. extra_size: ptruint;
  641. release_mem: boolean;
  642. begin
  643. { save old values }
  644. extra_size:=pp^.extra_info_size;
  645. ppsize:= size+sizeof(theap_mem_info)+pp^.extra_info_size;
  646. if add_tail then
  647. inc(ppsize,tail_size);
  648. { do various checking }
  649. release_mem := CheckFreeMemSize(loc_info, pp, size, ppsize);
  650. {$ifdef FPC_HAS_FEATURE_THREADING}
  651. if release_todo_lock then
  652. leavecriticalsection(todo_lock);
  653. {$endif}
  654. if release_mem then
  655. begin
  656. { release the normal memory at least }
  657. i:=SysFreeMemSize(pp,ppsize);
  658. { return the correct size }
  659. dec(i,sizeof(theap_mem_info)+extra_size);
  660. if add_tail then
  661. dec(i,tail_size);
  662. InternalFreeMemSize:=i;
  663. end else
  664. InternalFreeMemSize:=size;
  665. end;
  666. function TraceFreeMemSize(p:pointer;size:ptruint):ptruint;
  667. var
  668. loc_info: pheap_info;
  669. pp: pheap_mem_info;
  670. release_lock: boolean;
  671. begin
  672. if p=nil then
  673. begin
  674. TraceFreeMemSize:=0;
  675. exit;
  676. end;
  677. loc_info:=@heap_info;
  678. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  679. release_lock:=false;
  680. if @loc_info^.heap_free_todo <> pp^.todolist then
  681. begin
  682. if pp^.todolist = main_orig_todolist then
  683. pp^.todolist := main_relo_todolist;
  684. {$ifdef FPC_HAS_FEATURE_THREADING}
  685. entercriticalsection(todo_lock);
  686. {$endif}
  687. release_lock:=true;
  688. if pp^.todolist = @orphaned_info.heap_free_todo then
  689. begin
  690. loc_info := @orphaned_info;
  691. end else
  692. if pp^.todolist <> @loc_info^.heap_free_todo then
  693. begin
  694. { allocated in different heap, push to that todolist }
  695. pp^.todonext := pp^.todolist^;
  696. pp^.todolist^ := pp;
  697. TraceFreeMemSize := pp^.size;
  698. {$ifdef FPC_HAS_FEATURE_THREADING}
  699. leavecriticalsection(todo_lock);
  700. {$endif}
  701. exit;
  702. end;
  703. end;
  704. TraceFreeMemSize:=InternalFreeMemSize(loc_info,p,pp,size,release_lock);
  705. end;
  706. function TraceMemSize(p:pointer):ptruint;
  707. var
  708. pp : pheap_mem_info;
  709. begin
  710. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  711. TraceMemSize:=pp^.size;
  712. end;
  713. function TraceFreeMem(p:pointer):ptruint;
  714. var
  715. l : ptruint;
  716. pp : pheap_mem_info;
  717. begin
  718. if p=nil then
  719. begin
  720. TraceFreeMem:=0;
  721. exit;
  722. end;
  723. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  724. l:=SysMemSize(pp);
  725. dec(l,sizeof(theap_mem_info)+pp^.extra_info_size);
  726. if add_tail then
  727. dec(l,tail_size);
  728. { this can never happend normaly }
  729. if pp^.size>l then
  730. begin
  731. if useownfile then
  732. dump_wrong_size(pp,l,ownfile)
  733. else
  734. dump_wrong_size(pp,l,textoutput^);
  735. {$ifdef EXTRA}
  736. dump_wrong_size(pp,l,error_file);
  737. {$endif EXTRA}
  738. end;
  739. TraceFreeMem:=TraceFreeMemSize(p,pp^.size);
  740. end;
  741. {*****************************************************************************
  742. ReAllocMem
  743. *****************************************************************************}
  744. function TraceReAllocMem(var p:pointer;size:ptruint):Pointer;
  745. var
  746. newP: pointer;
  747. i, allocsize,
  748. movesize : ptruint;
  749. pl : pdword;
  750. pp,prevpp{$ifdef EXTRA},ppv{$endif} : pheap_mem_info;
  751. oldsize,
  752. oldextrasize,
  753. oldexactsize : ptruint;
  754. old_fill_extra_info_proc : tfillextrainfoproc;
  755. old_display_extra_info_proc : tdisplayextrainfoproc;
  756. loc_info: pheap_info;
  757. begin
  758. { Free block? }
  759. if size=0 then
  760. begin
  761. if p<>nil then
  762. TraceFreeMem(p);
  763. p:=nil;
  764. TraceReallocMem:=P;
  765. exit;
  766. end;
  767. { Allocate a new block? }
  768. if p=nil then
  769. begin
  770. p:=TraceGetMem(size);
  771. TraceReallocMem:=P;
  772. exit;
  773. end;
  774. { Resize block }
  775. loc_info:=@heap_info;
  776. pp:=pheap_mem_info(p-sizeof(theap_mem_info));
  777. { test block }
  778. if ((pp^.sig<>longword(AllocateSig)) or usecrc) and
  779. ((pp^.sig<>calculate_sig(pp)) or not usecrc) then
  780. begin
  781. loc_info^.error_in_heap:=true;
  782. if useownfile then
  783. dump_error(pp,ownfile)
  784. else
  785. dump_error(pp,textoutput^);
  786. {$ifdef EXTRA}
  787. dump_error(pp,error_file);
  788. {$endif EXTRA}
  789. { don't release anything in this case !! }
  790. if haltonerror then halt(1);
  791. exit;
  792. end;
  793. { save info }
  794. oldsize:=pp^.size;
  795. oldextrasize:=pp^.extra_info_size;
  796. oldexactsize:=pp^.exact_info_size;
  797. if pp^.extra_info_size>0 then
  798. begin
  799. old_fill_extra_info_proc:=pp^.extra_info^.fillproc;
  800. old_display_extra_info_proc:=pp^.extra_info^.displayproc;
  801. end;
  802. { Do the real ReAllocMem, but alloc also for the info block }
  803. {$ifdef cpuarm}
  804. allocsize:=(size + 3) and not 3+sizeof(theap_mem_info)+pp^.extra_info_size;
  805. {$else cpuarm}
  806. allocsize:=size+sizeof(theap_mem_info)+pp^.extra_info_size;
  807. {$endif cpuarm}
  808. if add_tail then
  809. inc(allocsize,tail_size);
  810. { Try to resize the block, if not possible we need to do a
  811. getmem, move data, freemem }
  812. prevpp:=pp;
  813. if not SysTryResizeMem(pp,allocsize) then
  814. begin
  815. { get a new block }
  816. newP := TraceGetMem(size);
  817. { move the data }
  818. if newP <> nil then
  819. begin
  820. movesize:=TraceMemSize(p);
  821. {if the old size is larger than the new size,
  822. move only the new size}
  823. if movesize>size then
  824. movesize:=size;
  825. move(p^,newP^,movesize);
  826. end;
  827. { release p }
  828. traceFreeMem(p);
  829. { return the new pointer }
  830. p:=newp;
  831. traceReAllocMem := newp;
  832. exit;
  833. end
  834. else
  835. begin
  836. if (pp<>prevpp) then
  837. begin
  838. { We need to update the previous/next chains }
  839. if assigned(pp^.previous) then
  840. pp^.previous^.next:=pp;
  841. if assigned(pp^.next) then
  842. pp^.next^.previous:=pp;
  843. if prevpp=loc_info^.heap_mem_root then
  844. loc_info^.heap_mem_root:=pp;
  845. {$ifdef EXTRA}
  846. { remove prevpp from prev_valid chain }
  847. ppv:=loc_info^.heap_valid_last;
  848. if (ppv=prevpp) then
  849. loc_info^.heap_valid_last:=pp^.prev_valid
  850. else
  851. begin
  852. while assigned(ppv) do
  853. begin
  854. if (ppv^.prev_valid=prevpp) then
  855. begin
  856. ppv^.prev_valid:=pp^.prev_valid;
  857. if prevpp=loc_info^.heap_valid_first then
  858. loc_info^.heap_valid_first:=ppv;
  859. ppv:=nil;
  860. end
  861. else
  862. ppv:=ppv^.prev_valid;
  863. end;
  864. end;
  865. { Reinsert new value in last position }
  866. pp^.prev_valid:=loc_info^.heap_valid_last;
  867. loc_info^.heap_valid_last:=pp;
  868. if not assigned(loc_info^.heap_valid_first) then
  869. loc_info^.heap_valid_first:=pp;
  870. {$endif EXTRA}
  871. end;
  872. end;
  873. { Recreate the info block }
  874. pp^.sig:=longword(AllocateSig);
  875. pp^.size:=size;
  876. pp^.extra_info_size:=oldextrasize;
  877. pp^.exact_info_size:=oldexactsize;
  878. { add the new extra_info and tail }
  879. if pp^.extra_info_size>0 then
  880. begin
  881. pp^.extra_info:=pointer(pp)+allocsize-pp^.extra_info_size;
  882. fillchar(pp^.extra_info^,extra_info_size,0);
  883. pp^.extra_info^.check:=cardinal(CheckSig);
  884. pp^.extra_info^.fillproc:=old_fill_extra_info_proc;
  885. pp^.extra_info^.displayproc:=old_display_extra_info_proc;
  886. if assigned(pp^.extra_info^.fillproc) then
  887. pp^.extra_info^.fillproc(@pp^.extra_info^.data);
  888. end
  889. else
  890. pp^.extra_info:=nil;
  891. if add_tail then
  892. begin
  893. { Calculate position from start because of arm
  894. specific alignment }
  895. pl:=pointer(pp)+sizeof(theap_mem_info)+pp^.size;
  896. for i:=1 to tail_size div sizeof(dword) do
  897. begin
  898. unaligned(pl^):=dword(AllocateSig);
  899. inc(pointer(pl),sizeof(dword));
  900. end;
  901. end;
  902. { adjust like a freemem and then a getmem, so you get correct
  903. results in the summary display }
  904. inc(loc_info^.freemem_size,oldsize);
  905. inc(loc_info^.freemem8_size,(oldsize+7) and not 7);
  906. inc(loc_info^.getmem_size,size);
  907. inc(loc_info^.getmem8_size,(size+7) and not 7);
  908. { generate new backtrace }
  909. CaptureBacktrace(1,tracesize,@pp^.calls[1]);
  910. { regenerate signature }
  911. if usecrc then
  912. pp^.sig:=calculate_sig(pp);
  913. { return the pointer }
  914. p:=pointer(pp)+sizeof(theap_mem_info);
  915. TraceReAllocmem:=p;
  916. end;
  917. {*****************************************************************************
  918. Check pointer
  919. *****************************************************************************}
  920. {$ifndef Unix}
  921. {$S-}
  922. {$endif}
  923. {$ifdef go32v2}
  924. var
  925. __stklen : longword;external name '__stklen';
  926. __stkbottom : longword;external name '__stkbottom';
  927. ebss : longword; external name 'end';
  928. {$endif go32v2}
  929. {$ifdef linux}
  930. var
  931. etext: ptruint; external name '_etext';
  932. edata : ptruint; external name '_edata';
  933. eend : ptruint; external name '_end';
  934. {$endif}
  935. {$ifdef freebsd}
  936. var
  937. text_start: ptruint; external name '__executable_start';
  938. etext: ptruint; external name '_etext';
  939. eend : ptruint; external name '_end';
  940. {$endif}
  941. {$ifdef os2}
  942. (* Currently still EMX based - possibly to be changed in the future. *)
  943. var
  944. etext: ptruint; external name '_etext';
  945. edata : ptruint; external name '_edata';
  946. eend : ptruint; external name '_end';
  947. {$endif}
  948. {$ifdef windows}
  949. var
  950. sdata : ptruint; external name '__data_start__';
  951. edata : ptruint; external name '__data_end__';
  952. sbss : ptruint; external name '__bss_start__';
  953. ebss : ptruint; external name '__bss_end__';
  954. TLSKey : PDWord; external name '_FPC_TlsKey';
  955. TLSSize : DWord; external name '_FPC_TlsSize';
  956. function TlsGetValue(dwTlsIndex : DWord) : pointer;
  957. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TlsGetValue';
  958. {$endif}
  959. {$ifdef BEOS}
  960. const
  961. B_ERROR = -1;
  962. type
  963. area_id = Longint;
  964. function area_for(addr : Pointer) : area_id;
  965. cdecl; external 'root' name 'area_for';
  966. {$endif BEOS}
  967. procedure CheckPointer(p : pointer); [public, alias : 'FPC_CHECKPOINTER'];
  968. var
  969. i : ptruint;
  970. pp : pheap_mem_info;
  971. loc_info: pheap_info;
  972. {$ifdef go32v2}
  973. get_ebp,stack_top : longword;
  974. bss_end : longword;
  975. {$endif go32v2}
  976. {$ifdef windows}
  977. datap : pointer;
  978. {$endif windows}
  979. ptext : ^text;
  980. begin
  981. if p=nil then
  982. runerror(204);
  983. i:=0;
  984. loc_info:=@heap_info;
  985. if useownfile then
  986. ptext:=@ownfile
  987. else
  988. ptext:=textoutput;
  989. {$ifdef go32v2}
  990. if ptruint(p)<$1000 then
  991. runerror(216);
  992. asm
  993. movl %ebp,get_ebp
  994. leal ebss,%eax
  995. movl %eax,bss_end
  996. end;
  997. stack_top:=__stkbottom+__stklen;
  998. { allow all between start of code and end of bss }
  999. if ptruint(p)<=bss_end then
  1000. exit;
  1001. { stack can be above heap !! }
  1002. if (ptruint(p)>=get_ebp) and (ptruint(p)<=stack_top) then
  1003. exit;
  1004. {$endif go32v2}
  1005. { I don't know where the stack is in other OS !! }
  1006. {$ifdef windows}
  1007. { inside stack ? }
  1008. if (ptruint(p)>ptruint(get_frame)) and
  1009. (p<StackTop) then
  1010. exit;
  1011. { inside data, rdata ... bss }
  1012. if (ptruint(p)>=ptruint(@sdata)) and (ptruint(p)<ptruint(@ebss)) then
  1013. exit;
  1014. { is program multi-threaded and p inside Threadvar range? }
  1015. if TlsKey^<>-1 then
  1016. begin
  1017. datap:=TlsGetValue(tlskey^);
  1018. if ((ptruint(p)>=ptruint(datap)) and
  1019. (ptruint(p)<ptruint(datap)+TlsSize)) then
  1020. exit;
  1021. end;
  1022. {$endif windows}
  1023. {$IFDEF OS2}
  1024. { inside stack ? }
  1025. if (PtrUInt (P) > PtrUInt (Get_Frame)) and
  1026. (PtrUInt (P) < PtrUInt (StackTop)) then
  1027. exit;
  1028. { inside data or bss ? }
  1029. if (PtrUInt (P) >= PtrUInt (@etext)) and (PtrUInt (P) < PtrUInt (@eend)) then
  1030. exit;
  1031. {$ENDIF OS2}
  1032. {$ifdef linux}
  1033. { inside stack ? }
  1034. if (ptruint(p)>ptruint(get_frame)) and
  1035. (ptruint(p)<ptruint(StackTop)) then
  1036. exit;
  1037. { inside data or bss ? }
  1038. if (ptruint(p)>=ptruint(@etext)) and (ptruint(p)<ptruint(@eend)) then
  1039. exit;
  1040. {$endif linux}
  1041. {$ifdef freebsd}
  1042. { inside stack ? }
  1043. if (ptruint(p)>ptruint(get_frame)) and
  1044. (ptruint(p)<ptruint(StackTop)) then
  1045. exit;
  1046. { inside data or bss ? }
  1047. if (ptruint(p)>=ptruint(@text_start)) and (ptruint(p)<ptruint(@eend)) then
  1048. exit;
  1049. {$endif linux}
  1050. {$ifdef morphos}
  1051. { inside stack ? }
  1052. if (ptruint(p)<ptruint(StackTop)) and (ptruint(p)>ptruint(StackBottom)) then
  1053. exit;
  1054. { inside data or bss ? }
  1055. {$WARNING data and bss checking missing }
  1056. {$endif morphos}
  1057. {$ifdef darwin}
  1058. {$warning No checkpointer support yet for Darwin}
  1059. exit;
  1060. {$endif}
  1061. {$ifdef BEOS}
  1062. // if we find the address in a known area in our current process,
  1063. // then it is a valid one
  1064. if area_for(p) <> B_ERROR then
  1065. exit;
  1066. {$endif BEOS}
  1067. { first try valid list faster }
  1068. {$ifdef EXTRA}
  1069. pp:=loc_info^.heap_valid_last;
  1070. while pp<>nil do
  1071. begin
  1072. { inside this valid block ! }
  1073. { we can be changing the extrainfo !! }
  1074. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info){+extra_info_size}) and
  1075. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+extra_info_size+pp^.size) then
  1076. begin
  1077. { check allocated block }
  1078. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1079. ((pp^.sig=calculate_sig(pp)) and usecrc) or
  1080. { special case of the fill_extra_info call }
  1081. ((pp=loc_info^.heap_valid_last) and usecrc and (pp^.sig=longword(AllocateSig))
  1082. and loc_info^.inside_trace_getmem) then
  1083. exit
  1084. else
  1085. begin
  1086. writeln(ptext^,'corrupted heap_mem_info');
  1087. dump_error(pp,ptext^);
  1088. halt(1);
  1089. end;
  1090. end
  1091. else
  1092. pp:=pp^.prev_valid;
  1093. inc(i);
  1094. if i>loc_info^.getmem_cnt-loc_info^.freemem_cnt then
  1095. begin
  1096. writeln(ptext^,'error in linked list of heap_mem_info');
  1097. halt(1);
  1098. end;
  1099. end;
  1100. i:=0;
  1101. {$endif EXTRA}
  1102. pp:=loc_info^.heap_mem_root;
  1103. while pp<>nil do
  1104. begin
  1105. { inside this block ! }
  1106. if (ptruint(p)>=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)) and
  1107. (ptruint(p)<=ptruint(pp)+sizeof(theap_mem_info)+ptruint(extra_info_size)+ptruint(pp^.size)) then
  1108. { allocated block }
  1109. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1110. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  1111. exit
  1112. else
  1113. begin
  1114. writeln(ptext^,'pointer $',hexstr(p),' points into invalid memory block');
  1115. dump_error(pp,ptext^);
  1116. runerror(204);
  1117. end;
  1118. pp:=pp^.previous;
  1119. inc(i);
  1120. if i>loc_info^.getmem_cnt then
  1121. begin
  1122. writeln(ptext^,'error in linked list of heap_mem_info');
  1123. halt(1);
  1124. end;
  1125. end;
  1126. writeln(ptext^,'pointer $',hexstr(p),' does not point to valid memory block');
  1127. dump_stack(ptext^,1);
  1128. runerror(204);
  1129. end;
  1130. {*****************************************************************************
  1131. Dump Heap
  1132. *****************************************************************************}
  1133. procedure dumpheap;
  1134. begin
  1135. DumpHeap(GlobalSkipIfNoLeaks);
  1136. end;
  1137. const
  1138. {$ifdef BSD} // dlopen is in libc on FreeBSD.
  1139. LibDL = 'c';
  1140. {$else}
  1141. {$ifdef HAIKU}
  1142. LibDL = 'root';
  1143. {$else}
  1144. LibDL = 'dl';
  1145. {$endif}
  1146. {$endif}
  1147. {$if defined(LINUX) or defined(BSD)}
  1148. type
  1149. Pdl_info = ^dl_info;
  1150. dl_info = record
  1151. dli_fname : Pchar;
  1152. dli_fbase : pointer;
  1153. dli_sname : Pchar;
  1154. dli_saddr : pointer;
  1155. end;
  1156. function _dladdr(Lib:pointer; info: Pdl_info): Longint; cdecl; external LibDL name 'dladdr';
  1157. {$elseif defined(MSWINDOWS)}
  1158. function _GetModuleFileNameA(hModule:HModule;lpFilename:PAnsiChar;nSize:cardinal):cardinal;stdcall; external 'kernel32' name 'GetModuleFileNameA';
  1159. {$endif}
  1160. function GetModuleName:string;
  1161. {$ifdef MSWINDOWS}
  1162. var
  1163. sz:cardinal;
  1164. buf:array[0..8191] of char;
  1165. {$endif}
  1166. {$if defined(LINUX) or defined(BSD)}
  1167. var
  1168. res:integer;
  1169. dli:dl_info;
  1170. {$endif}
  1171. begin
  1172. GetModuleName:='';
  1173. {$if defined(LINUX) or defined(BSD)}
  1174. res:=_dladdr(@ParamStr,@dli); { get any non-eliminated address in SO space }
  1175. if res<=0 then
  1176. exit;
  1177. if Assigned(dli.dli_fname) then
  1178. GetModuleName:=PAnsiChar(dli.dli_fname);
  1179. {$elseif defined(MSWINDOWS)}
  1180. sz:=_GetModuleFileNameA(hInstance,PChar(@buf),sizeof(buf));
  1181. if sz>0 then
  1182. setstring(GetModuleName,PAnsiChar(@buf),sz)
  1183. {$else}
  1184. GetModuleName:=ParamStr(0);
  1185. {$endif}
  1186. end;
  1187. procedure dumpheap(SkipIfNoLeaks : Boolean);
  1188. var
  1189. pp : pheap_mem_info;
  1190. i : ptrint;
  1191. ExpectedHeapFree : ptruint;
  1192. status : TFPCHeapStatus;
  1193. ptext : ^text;
  1194. loc_info: pheap_info;
  1195. begin
  1196. loc_info:=@heap_info;
  1197. if useownfile then
  1198. ptext:=@ownfile
  1199. else
  1200. ptext:=textoutput;
  1201. pp:=loc_info^.heap_mem_root;
  1202. if ((loc_info^.getmem_size-loc_info^.freemem_size)=0) and SkipIfNoLeaks then
  1203. exit;
  1204. Writeln(ptext^,'Heap dump by heaptrc unit of "'+GetModuleName()+'"');
  1205. Writeln(ptext^,loc_info^.getmem_cnt, ' memory blocks allocated : ',
  1206. loc_info^.getmem_size,'/',loc_info^.getmem8_size);
  1207. Writeln(ptext^,loc_info^.freemem_cnt,' memory blocks freed : ',
  1208. loc_info^.freemem_size,'/',loc_info^.freemem8_size);
  1209. Writeln(ptext^,loc_info^.getmem_cnt-loc_info^.freemem_cnt,
  1210. ' unfreed memory blocks : ',loc_info^.getmem_size-loc_info^.freemem_size);
  1211. status:=SysGetFPCHeapStatus;
  1212. Write(ptext^,'True heap size : ',status.CurrHeapSize);
  1213. if EntryMemUsed > 0 then
  1214. Writeln(ptext^,' (',EntryMemUsed,' used in System startup)')
  1215. else
  1216. Writeln(ptext^);
  1217. Writeln(ptext^,'True free heap : ',status.CurrHeapFree);
  1218. ExpectedHeapFree:=status.CurrHeapSize
  1219. -(loc_info^.getmem8_size-loc_info^.freemem8_size)
  1220. -(loc_info^.getmem_cnt-loc_info^.freemem_cnt)*(sizeof(theap_mem_info)+extra_info_size)
  1221. -EntryMemUsed;
  1222. If ExpectedHeapFree<>status.CurrHeapFree then
  1223. Writeln(ptext^,'Should be : ',ExpectedHeapFree);
  1224. i:=loc_info^.getmem_cnt-loc_info^.freemem_cnt;
  1225. while pp<>nil do
  1226. begin
  1227. if i<0 then
  1228. begin
  1229. Writeln(ptext^,'Error in heap memory list');
  1230. Writeln(ptext^,'More memory blocks than expected');
  1231. exit;
  1232. end;
  1233. if ((pp^.sig=longword(AllocateSig)) and not usecrc) or
  1234. ((pp^.sig=calculate_sig(pp)) and usecrc) then
  1235. begin
  1236. { this one was not released !! }
  1237. if exitcode<>203 then
  1238. call_stack(pp,ptext^);
  1239. dec(i);
  1240. end
  1241. else if pp^.sig<>longword(ReleaseSig) then
  1242. begin
  1243. dump_error(pp,ptext^);
  1244. if @stderr<>ptext then
  1245. dump_error(pp,stderr);
  1246. {$ifdef EXTRA}
  1247. dump_error(pp,error_file);
  1248. {$endif EXTRA}
  1249. loc_info^.error_in_heap:=true;
  1250. end
  1251. {$ifdef EXTRA}
  1252. else if pp^.release_sig<>calculate_release_sig(pp) then
  1253. begin
  1254. dump_change_after(pp,ptext^);
  1255. dump_change_after(pp,error_file);
  1256. loc_info^.error_in_heap:=true;
  1257. end
  1258. {$else not EXTRA}
  1259. else
  1260. begin
  1261. if released_modified(pp,ptext^) then
  1262. exitcode:=203;
  1263. end;
  1264. {$endif EXTRA}
  1265. ;
  1266. pp:=pp^.previous;
  1267. end;
  1268. if HaltOnNotReleased and (loc_info^.getmem_cnt<>loc_info^.freemem_cnt) then
  1269. exitcode:=203;
  1270. end;
  1271. {*****************************************************************************
  1272. AllocMem
  1273. *****************************************************************************}
  1274. function TraceAllocMem(size:ptruint):Pointer;
  1275. begin
  1276. TraceAllocMem := TraceGetMem(size);
  1277. if Assigned(TraceAllocMem) then
  1278. FillChar(TraceAllocMem^, TraceMemSize(TraceAllocMem), 0);
  1279. end;
  1280. {*****************************************************************************
  1281. No specific tracing calls
  1282. *****************************************************************************}
  1283. procedure TraceInitThread;
  1284. var
  1285. loc_info: pheap_info;
  1286. begin
  1287. loc_info := @heap_info;
  1288. {$ifdef EXTRA}
  1289. loc_info^.heap_valid_first := nil;
  1290. loc_info^.heap_valid_last := nil;
  1291. {$endif}
  1292. loc_info^.heap_mem_root := nil;
  1293. loc_info^.getmem_cnt := 0;
  1294. loc_info^.freemem_cnt := 0;
  1295. loc_info^.getmem_size := 0;
  1296. loc_info^.freemem_size := 0;
  1297. loc_info^.getmem8_size := 0;
  1298. loc_info^.freemem8_size := 0;
  1299. loc_info^.error_in_heap := false;
  1300. loc_info^.inside_trace_getmem := false;
  1301. EntryMemUsed := SysGetFPCHeapStatus.CurrHeapUsed;
  1302. end;
  1303. procedure TraceRelocateHeap;
  1304. begin
  1305. main_relo_todolist := @heap_info.heap_free_todo;
  1306. {$ifdef FPC_HAS_FEATURE_THREADING}
  1307. initcriticalsection(todo_lock);
  1308. {$endif}
  1309. end;
  1310. procedure move_heap_info(src_info, dst_info: pheap_info);
  1311. var
  1312. heap_mem: pheap_mem_info;
  1313. begin
  1314. if src_info^.heap_free_todo <> nil then
  1315. finish_heap_free_todo_list(src_info);
  1316. if dst_info^.heap_free_todo <> nil then
  1317. finish_heap_free_todo_list(dst_info);
  1318. heap_mem := src_info^.heap_mem_root;
  1319. if heap_mem <> nil then
  1320. begin
  1321. repeat
  1322. heap_mem^.todolist := @dst_info^.heap_free_todo;
  1323. if heap_mem^.previous = nil then break;
  1324. heap_mem := heap_mem^.previous;
  1325. until false;
  1326. heap_mem^.previous := dst_info^.heap_mem_root;
  1327. if dst_info^.heap_mem_root <> nil then
  1328. dst_info^.heap_mem_root^.next := heap_mem;
  1329. dst_info^.heap_mem_root := src_info^.heap_mem_root;
  1330. end;
  1331. inc(dst_info^.getmem_cnt, src_info^.getmem_cnt);
  1332. inc(dst_info^.getmem_size, src_info^.getmem_size);
  1333. inc(dst_info^.getmem8_size, src_info^.getmem8_size);
  1334. inc(dst_info^.freemem_cnt, src_info^.freemem_cnt);
  1335. inc(dst_info^.freemem_size, src_info^.freemem_size);
  1336. inc(dst_info^.freemem8_size, src_info^.freemem8_size);
  1337. dst_info^.error_in_heap := dst_info^.error_in_heap or src_info^.error_in_heap;
  1338. {$ifdef EXTRA}
  1339. if assigned(dst_info^.heap_valid_first) then
  1340. dst_info^.heap_valid_first^.prev_valid := src_info^.heap_valid_last
  1341. else
  1342. dst_info^.heap_valid_last := src_info^.heap_valid_last;
  1343. dst_info^.heap_valid_first := src_info^.heap_valid_first;
  1344. {$endif}
  1345. end;
  1346. procedure TraceExitThread;
  1347. var
  1348. loc_info: pheap_info;
  1349. begin
  1350. loc_info := @heap_info;
  1351. {$ifdef FPC_HAS_FEATURE_THREADING}
  1352. entercriticalsection(todo_lock);
  1353. {$endif}
  1354. move_heap_info(loc_info, @orphaned_info);
  1355. {$ifdef FPC_HAS_FEATURE_THREADING}
  1356. leavecriticalsection(todo_lock);
  1357. {$endif}
  1358. end;
  1359. function TraceGetHeapStatus:THeapStatus;
  1360. begin
  1361. TraceGetHeapStatus:=SysGetHeapStatus;
  1362. end;
  1363. function TraceGetFPCHeapStatus:TFPCHeapStatus;
  1364. begin
  1365. TraceGetFPCHeapStatus:=SysGetFPCHeapStatus;
  1366. end;
  1367. {*****************************************************************************
  1368. Program Hooks
  1369. *****************************************************************************}
  1370. Procedure SetHeapTraceOutput(const name : string);
  1371. var i : ptruint;
  1372. begin
  1373. if useownfile then
  1374. begin
  1375. useownfile:=false;
  1376. close(ownfile);
  1377. end;
  1378. assign(ownfile,name);
  1379. {$I-}
  1380. append(ownfile);
  1381. if IOResult<>0 then
  1382. begin
  1383. Rewrite(ownfile);
  1384. if IOResult<>0 then
  1385. begin
  1386. Writeln(textoutput^,'[heaptrc] Unable to open "',name,'", writing output to stderr instead.');
  1387. useownfile:=false;
  1388. exit;
  1389. end;
  1390. end;
  1391. {$I+}
  1392. useownfile:=true;
  1393. for i:=0 to Paramcount do
  1394. write(ownfile,paramstr(i),' ');
  1395. writeln(ownfile);
  1396. end;
  1397. procedure SetHeapTraceOutput(var ATextOutput : Text);
  1398. Begin
  1399. useowntextoutput := True;
  1400. textoutput := @ATextOutput;
  1401. end;
  1402. procedure SetHeapExtraInfo( size : ptruint;fillproc : tfillextrainfoproc;displayproc : tdisplayextrainfoproc);
  1403. begin
  1404. { the total size must stay multiple of 8, also allocate 2 pointers for
  1405. the fill and display procvars }
  1406. exact_info_size:=size + sizeof(theap_extra_info);
  1407. extra_info_size:=(exact_info_size+7) and not 7;
  1408. fill_extra_info_proc:=fillproc;
  1409. display_extra_info_proc:=displayproc;
  1410. end;
  1411. {*****************************************************************************
  1412. Install MemoryManager
  1413. *****************************************************************************}
  1414. const
  1415. TraceManager:TMemoryManager=(
  1416. NeedLock : true;
  1417. Getmem : @TraceGetMem;
  1418. Freemem : @TraceFreeMem;
  1419. FreememSize : @TraceFreeMemSize;
  1420. AllocMem : @TraceAllocMem;
  1421. ReAllocMem : @TraceReAllocMem;
  1422. MemSize : @TraceMemSize;
  1423. InitThread: @TraceInitThread;
  1424. DoneThread: @TraceExitThread;
  1425. RelocateHeap: @TraceRelocateHeap;
  1426. GetHeapStatus : @TraceGetHeapStatus;
  1427. GetFPCHeapStatus : @TraceGetFPCHeapStatus;
  1428. );
  1429. var
  1430. PrevMemoryManager : TMemoryManager;
  1431. procedure TraceInit;
  1432. begin
  1433. textoutput := @stderr;
  1434. useowntextoutput := false;
  1435. MakeCRC32Tbl;
  1436. main_orig_todolist := @heap_info.heap_free_todo;
  1437. main_relo_todolist := nil;
  1438. TraceInitThread;
  1439. GetMemoryManager(PrevMemoryManager);
  1440. SetMemoryManager(TraceManager);
  1441. useownfile:=false;
  1442. if outputstr <> '' then
  1443. SetHeapTraceOutput(outputstr);
  1444. {$ifdef EXTRA}
  1445. {$i-}
  1446. Assign(error_file,'heap.err');
  1447. Rewrite(error_file);
  1448. {$i+}
  1449. if IOResult<>0 then
  1450. begin
  1451. writeln('[heaptrc] Unable to create heap.err extra log file, writing output to screen.');
  1452. Assign(error_file,'');
  1453. Rewrite(error_file);
  1454. end;
  1455. {$endif EXTRA}
  1456. { if multithreading was initialized before heaptrc gets initialized (this is currently
  1457. the case for windows dlls), then RelocateHeap gets never called and the lock
  1458. must be initialized already here,
  1459. however, IsMultithread is not set in this case on windows,
  1460. it is set only if a new thread is started
  1461. }
  1462. {$IfNDef WINDOWS}
  1463. if IsMultithread then
  1464. {$EndIf WINDOWS}
  1465. TraceRelocateHeap;
  1466. end;
  1467. procedure TraceExit;
  1468. begin
  1469. { no dump if error
  1470. because this gives long long listings }
  1471. { clear inoutres, in case the program that quit didn't }
  1472. ioresult;
  1473. if (exitcode<>0) and (erroraddr<>nil) then
  1474. begin
  1475. if useownfile then
  1476. begin
  1477. Writeln(ownfile,'No heap dump by heaptrc unit');
  1478. Writeln(ownfile,'Exitcode = ',exitcode);
  1479. end
  1480. else
  1481. begin
  1482. Writeln(textoutput^,'No heap dump by heaptrc unit');
  1483. Writeln(textoutput^,'Exitcode = ',exitcode);
  1484. end;
  1485. if useownfile then
  1486. begin
  1487. useownfile:=false;
  1488. close(ownfile);
  1489. end;
  1490. exit;
  1491. end;
  1492. { Disable heaptrc memory manager to avoid problems }
  1493. SetMemoryManager(PrevMemoryManager);
  1494. move_heap_info(@orphaned_info, @heap_info);
  1495. dumpheap;
  1496. if heap_info.error_in_heap and (exitcode=0) then
  1497. exitcode:=203;
  1498. {$ifdef FPC_HAS_FEATURE_THREADING}
  1499. if main_relo_todolist <> nil then
  1500. donecriticalsection(todo_lock);
  1501. {$endif}
  1502. {$ifdef EXTRA}
  1503. Close(error_file);
  1504. {$endif EXTRA}
  1505. if useownfile then
  1506. begin
  1507. useownfile:=false;
  1508. close(ownfile);
  1509. end;
  1510. if useowntextoutput then
  1511. begin
  1512. useowntextoutput := false;
  1513. close(textoutput^);
  1514. end;
  1515. end;
  1516. {$if defined(win32) or defined(win64)}
  1517. function GetEnvironmentStrings : pchar; stdcall;
  1518. external 'kernel32' name 'GetEnvironmentStringsA';
  1519. function FreeEnvironmentStrings(p : pchar) : longbool; stdcall;
  1520. external 'kernel32' name 'FreeEnvironmentStringsA';
  1521. Function GetEnv(envvar: string): string;
  1522. var
  1523. s : string;
  1524. i : ptruint;
  1525. hp,p : pchar;
  1526. begin
  1527. getenv:='';
  1528. p:=GetEnvironmentStrings;
  1529. hp:=p;
  1530. while hp^<>#0 do
  1531. begin
  1532. s:=strpas(hp);
  1533. i:=pos('=',s);
  1534. if upcase(copy(s,1,i-1))=upcase(envvar) then
  1535. begin
  1536. getenv:=copy(s,i+1,length(s)-i);
  1537. break;
  1538. end;
  1539. { next string entry}
  1540. hp:=hp+strlen(hp)+1;
  1541. end;
  1542. FreeEnvironmentStrings(p);
  1543. end;
  1544. {$elseif defined(wince)}
  1545. Function GetEnv(P:string):Pchar;
  1546. begin
  1547. { WinCE does not have environment strings.
  1548. Add some way to specify heaptrc options? }
  1549. GetEnv:=nil;
  1550. end;
  1551. {$elseif defined(msdos) or defined(msxdos)}
  1552. type
  1553. PFarChar=^Char;far;
  1554. PPFarChar=^PFarChar;
  1555. var
  1556. envp: PPFarChar;external name '__fpc_envp';
  1557. Function GetEnv(P:string):string;
  1558. var
  1559. ep : ppfarchar;
  1560. pc : pfarchar;
  1561. i : smallint;
  1562. found : boolean;
  1563. Begin
  1564. getenv:='';
  1565. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1566. ep:=envp;
  1567. found:=false;
  1568. if ep<>nil then
  1569. begin
  1570. while (not found) and (ep^<>nil) do
  1571. begin
  1572. found:=true;
  1573. for i:=1 to length(p) do
  1574. if p[i]<>ep^[i-1] then
  1575. begin
  1576. found:=false;
  1577. break;
  1578. end;
  1579. if not found then
  1580. inc(ep);
  1581. end;
  1582. end;
  1583. if found then
  1584. begin
  1585. pc:=ep^+length(p);
  1586. while pc^<>#0 do
  1587. begin
  1588. getenv:=getenv+pc^;
  1589. Inc(pc);
  1590. end;
  1591. end;
  1592. end;
  1593. {$else}
  1594. Function GetEnv(P:string):Pchar;
  1595. {
  1596. Searches the environment for a string with name p and
  1597. returns a pchar to it's value.
  1598. A pchar is used to accomodate for strings of length > 255
  1599. }
  1600. var
  1601. ep : ppchar;
  1602. i : ptruint;
  1603. found : boolean;
  1604. Begin
  1605. p:=p+'='; {Else HOST will also find HOSTNAME, etc}
  1606. ep:=envp;
  1607. found:=false;
  1608. if ep<>nil then
  1609. begin
  1610. while (not found) and (ep^<>nil) do
  1611. begin
  1612. found:=true;
  1613. for i:=1 to length(p) do
  1614. if p[i]<>ep^[i-1] then
  1615. begin
  1616. found:=false;
  1617. break;
  1618. end;
  1619. if not found then
  1620. inc(ep);
  1621. end;
  1622. end;
  1623. if found then
  1624. getenv:=ep^+length(p)
  1625. else
  1626. getenv:=nil;
  1627. end;
  1628. {$endif}
  1629. procedure LoadEnvironment;
  1630. var
  1631. i,j : ptruint;
  1632. s,s2 : string;
  1633. err : word;
  1634. begin
  1635. s:=Getenv('HEAPTRC');
  1636. if pos('keepreleased',s)>0 then
  1637. keepreleased:=true;
  1638. if pos('disabled',s)>0 then
  1639. useheaptrace:=false;
  1640. if pos('nohalt',s)>0 then
  1641. haltonerror:=false;
  1642. if pos('haltonnotreleased',s)>0 then
  1643. HaltOnNotReleased :=true;
  1644. if pos('skipifnoleaks',s)>0 then
  1645. GlobalSkipIfNoLeaks :=true;
  1646. if pos('tail_size=',s)>0 then
  1647. begin
  1648. i:=pos('tail_size=',s)+length('tail_size=');
  1649. s2:='';
  1650. while (i<=length(s)) and (s[i] in ['0'..'9']) do
  1651. begin
  1652. s2:=s2+s[i];
  1653. inc(i);
  1654. end;
  1655. val(s2,tail_size,err);
  1656. if err=0 then
  1657. tail_size:=((tail_size + sizeof(ptruint)-1) div sizeof(ptruint)) * sizeof(ptruint)
  1658. else
  1659. tail_size:=sizeof(ptruint);
  1660. add_tail:=(tail_size > 0);
  1661. end;
  1662. i:=pos('log=',s);
  1663. if i>0 then
  1664. begin
  1665. outputstr:=copy(s,i+4,255);
  1666. j:=pos(' ',outputstr);
  1667. if j=0 then
  1668. j:=length(outputstr)+1;
  1669. delete(outputstr,j,255);
  1670. end;
  1671. end;
  1672. Initialization
  1673. LoadEnvironment;
  1674. { heaptrc can be disabled from the environment }
  1675. if useheaptrace then
  1676. TraceInit;
  1677. finalization
  1678. if useheaptrace then
  1679. TraceExit;
  1680. end.