heaptrc.pp 47 KB

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