heaptrc.pp 43 KB

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