heaptrc.pp 47 KB

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