Debian Codegraph @

gcc/ada/libgnat/g-debpoo.adb

raw
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- G N A T . D E B U G _ P O O L S --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2025, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. --
17 -- --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
21 -- --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
26 -- --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
29 -- --
30 ------------------------------------------------------------------------------
31
32 with GNAT.IO; use GNAT.IO;
33
34 with System.CRTL;
35 with System.Memory; use System.Memory;
36 with System.Soft_Links; use System.Soft_Links;
37
38 with System.Traceback_Entries;
39
40 with GNAT.Debug_Utilities; use GNAT.Debug_Utilities;
41 with GNAT.HTable;
42 with GNAT.Traceback; use GNAT.Traceback;
43
44 with Ada.Finalization;
45 with Ada.Unchecked_Conversion;
46
47 package body GNAT.Debug_Pools is
48
49 Storage_Alignment : constant := Standard'Maximum_Alignment;
50 -- Alignment enforced for all the memory chunks returned by Allocate,
51 -- maximized to make sure that it will be compatible with all types.
52 --
53 -- The addresses returned by the underlying low-level allocator (be it
54 -- 'new' or a straight 'malloc') aren't guaranteed to be that much aligned
55 -- on some targets, so we manage the needed alignment padding ourselves
56 -- systematically. Use of a common value for every allocation allows
57 -- significant simplifications in the code, nevertheless, for improved
58 -- robustness and efficiency overall.
59
60 -- We combine a few internal devices to offer the pool services:
61 --
62 -- * A management header attached to each allocated memory block, located
63 -- right ahead of it, like so:
64 --
65 -- Storage Address returned by the pool,
66 -- aligned on Storage_Alignment
67 -- v
68 -- +------+--------+---------------------
69 -- | ~~~~ | HEADER | USER DATA ... |
70 -- +------+--------+---------------------
71 -- <---->
72 -- alignment
73 -- padding
74 --
75 -- The alignment padding is required
76 --
77 -- * A validity bitmap, which holds a validity bit for blocks managed by
78 -- the pool. Enforcing Storage_Alignment on those blocks allows efficient
79 -- validity management.
80 --
81 -- * A list of currently used blocks.
82
83 Max_Ignored_Levels : constant Natural := 10;
84 -- Maximum number of levels that will be ignored in backtraces. This is so
85 -- that we still have enough significant levels in the tracebacks returned
86 -- to the user.
87 --
88 -- The value 10 is chosen as being greater than the maximum callgraph
89 -- in this package. Its actual value is not really relevant, as long as it
90 -- is high enough to make sure we still have enough frames to return to
91 -- the user after we have hidden the frames internal to this package.
92
93 Disable : Boolean := False;
94 -- This variable is used to avoid infinite loops, where this package would
95 -- itself allocate memory and then call itself recursively, forever. Useful
96 -- when System_Memory_Debug_Pool_Enabled is True.
97
98 System_Memory_Debug_Pool_Enabled : Boolean := False;
99 -- If True, System.Memory allocation uses Debug_Pool
100
101 Allow_Unhandled_Memory : Boolean := False;
102 -- If True, protects Deallocate against releasing memory allocated before
103 -- System_Memory_Debug_Pool_Enabled was set.
104
105 Traceback_Count : Byte_Count := 0;
106 -- Total number of traceback elements
107
108 ---------------------------
109 -- Back Trace Hash Table --
110 ---------------------------
111
112 -- This package needs to store one set of tracebacks for each allocation
113 -- point (when was it allocated or deallocated). This would use too much
114 -- memory, so the tracebacks are actually stored in a hash table, and
115 -- we reference elements in this hash table instead.
116
117 -- This hash-table will remain empty if the discriminant Stack_Trace_Depth
118 -- for the pools is set to 0.
119
120 -- This table is a global table, that can be shared among all debug pools
121 -- with no problems.
122
123 type Header is range 1 .. 1023;
124 -- Number of elements in the hash-table
125
126 type Tracebacks_Array_Access is access Tracebacks_Array;
127
128 type Traceback_Kind is (Alloc, Dealloc, Indirect_Alloc, Indirect_Dealloc);
129
130 type Traceback_Htable_Elem;
131 type Traceback_Htable_Elem_Ptr
132 is access Traceback_Htable_Elem;
133
134 type Traceback_Htable_Elem is record
135 Traceback : Tracebacks_Array_Access;
136 Kind : Traceback_Kind;
137 Count : Natural;
138 -- Size of the memory allocated/freed at Traceback since last Reset call
139
140 Total : Byte_Count;
141 -- Number of chunk of memory allocated/freed at Traceback since last
142 -- Reset call.
143
144 Frees : Natural;
145 -- Number of chunk of memory allocated at Traceback, currently freed
146 -- since last Reset call. (only for Alloc & Indirect_Alloc elements)
147
148 Total_Frees : Byte_Count;
149 -- Size of the memory allocated at Traceback, currently freed since last
150 -- Reset call. (only for Alloc & Indirect_Alloc elements)
151
152 Next : Traceback_Htable_Elem_Ptr;
153 end record;
154
155 -- Subprograms used for the Backtrace_Htable instantiation
156
157 procedure Set_Next
158 (E : Traceback_Htable_Elem_Ptr;
159 Next : Traceback_Htable_Elem_Ptr);
160 pragma Inline (Set_Next);
161
162 function Next
163 (E : Traceback_Htable_Elem_Ptr) return Traceback_Htable_Elem_Ptr;
164 pragma Inline (Next);
165
166 function Get_Key
167 (E : Traceback_Htable_Elem_Ptr) return Tracebacks_Array_Access;
168 pragma Inline (Get_Key);
169
170 function Hash (T : Tracebacks_Array_Access) return Header;
171 pragma Inline (Hash);
172
173 function Equal (K1, K2 : Tracebacks_Array_Access) return Boolean;
174 -- Why is this not inlined???
175
176 -- The hash table for back traces
177
178 package Backtrace_Htable is new GNAT.HTable.Static_HTable
179 (Header_Num => Header,
180 Element => Traceback_Htable_Elem,
181 Elmt_Ptr => Traceback_Htable_Elem_Ptr,
182 Null_Ptr => null,
183 Set_Next => Set_Next,
184 Next => Next,
185 Key => Tracebacks_Array_Access,
186 Get_Key => Get_Key,
187 Hash => Hash,
188 Equal => Equal);
189
190 -----------------------
191 -- Allocations table --
192 -----------------------
193
194 type Allocation_Header;
195 type Allocation_Header_Access is access Allocation_Header;
196
197 type Traceback_Ptr_Or_Address is new System.Address;
198 -- A type that acts as a C union, and is either a System.Address or a
199 -- Traceback_Htable_Elem_Ptr.
200
201 -- The following record stores extra information that needs to be
202 -- memorized for each block allocated with the special debug pool.
203
204 type Allocation_Header is record
205 Allocation_Address : System.Address;
206 -- Address of the block returned by malloc, possibly unaligned
207
208 Block_Size : Storage_Offset;
209 -- Needed only for advanced freeing algorithms (traverse all allocated
210 -- blocks for potential references). This value is negated when the
211 -- chunk of memory has been logically freed by the application. This
212 -- chunk has not been physically released yet.
213
214 Alloc_Traceback : Traceback_Htable_Elem_Ptr;
215 -- ??? comment required
216
217 Dealloc_Traceback : Traceback_Ptr_Or_Address;
218 -- Pointer to the traceback for the allocation (if the memory chunk is
219 -- still valid), or to the first deallocation otherwise. Make sure this
220 -- is a thin pointer to save space.
221 --
222 -- Dealloc_Traceback is also for blocks that are still allocated to
223 -- point to the previous block in the list. This saves space in this
224 -- header, and make manipulation of the lists of allocated pointers
225 -- faster.
226
227 Next : System.Address;
228 -- Point to the next block of the same type (either allocated or
229 -- logically freed) in memory. This points to the beginning of the user
230 -- data, and does not include the header of that block.
231 end record;
232
233 function Header_Of
234 (Address : System.Address) return Allocation_Header_Access;
235 pragma Inline (Header_Of);
236 -- Return the header corresponding to a previously allocated address
237
238 function To_Address is new Ada.Unchecked_Conversion
239 (Traceback_Ptr_Or_Address, System.Address);
240
241 function To_Address is new Ada.Unchecked_Conversion
242 (System.Address, Traceback_Ptr_Or_Address);
243
244 function To_Traceback is new Ada.Unchecked_Conversion
245 (Traceback_Ptr_Or_Address, Traceback_Htable_Elem_Ptr);
246
247 function To_Traceback is new Ada.Unchecked_Conversion
248 (Traceback_Htable_Elem_Ptr, Traceback_Ptr_Or_Address);
249
250 Header_Offset : constant Storage_Count :=
251 (Allocation_Header'Object_Size / System.Storage_Unit);
252 -- Offset, in bytes, from start of allocation Header to start of User
253 -- data. The start of user data is assumed to be aligned at least as much
254 -- as what the header type requires, so applying this offset yields a
255 -- suitably aligned address as well.
256
257 Extra_Allocation : constant Storage_Count :=
258 (Storage_Alignment - 1 + Header_Offset);
259 -- Amount we need to secure in addition to the user data for a given
260 -- allocation request: room for the allocation header plus worst-case
261 -- alignment padding.
262
263 -----------------------
264 -- Local subprograms --
265 -----------------------
266
267 function Align (Addr : Integer_Address) return Integer_Address;
268 pragma Inline (Align);
269 -- Return the next address aligned on Storage_Alignment from Addr.
270
271 function Find_Or_Create_Traceback
272 (Pool : Debug_Pool;
273 Kind : Traceback_Kind;
274 Size : Storage_Count;
275 Ignored_Frame_Start : System.Address;
276 Ignored_Frame_End : System.Address) return Traceback_Htable_Elem_Ptr;
277 -- Return an element matching the current traceback (omitting the frames
278 -- that are in the current package). If this traceback already existed in
279 -- the htable, a pointer to this is returned to spare memory. Null is
280 -- returned if the pool is set not to store tracebacks. If the traceback
281 -- already existed in the table, the count is incremented so that
282 -- Dump_Tracebacks returns useful results. All addresses up to, and
283 -- including, an address between Ignored_Frame_Start .. Ignored_Frame_End
284 -- are ignored.
285
286 function Output_File (Pool : Debug_Pool) return File_Type;
287 pragma Inline (Output_File);
288 -- Returns file_type on which error messages have to be generated for Pool
289
290 procedure Put_Line
291 (File : File_Type;
292 Depth : Natural;
293 Traceback : Tracebacks_Array_Access;
294 Ignored_Frame_Start : System.Address := System.Null_Address;
295 Ignored_Frame_End : System.Address := System.Null_Address);
296 -- Print Traceback to File. If Traceback is null, print the call_chain
297 -- at the current location, up to Depth levels, ignoring all addresses
298 -- up to the first one in the range:
299 -- Ignored_Frame_Start .. Ignored_Frame_End
300
301 procedure Stdout_Put (S : String);
302 -- Wrapper for Put that ensures we always write to stdout instead of the
303 -- current output file defined in GNAT.IO.
304
305 procedure Stdout_Put_Line (S : String);
306 -- Wrapper for Put_Line that ensures we always write to stdout instead of
307 -- the current output file defined in GNAT.IO.
308
309 procedure Print_Traceback
310 (Output_File : File_Type;
311 Prefix : String;
312 Traceback : Traceback_Htable_Elem_Ptr);
313 -- Output Prefix & Traceback & EOL. Print nothing if Traceback is null.
314
315 procedure Print_Address (File : File_Type; Addr : Address);
316 -- Output System.Address without using secondary stack.
317 -- When System.Memory uses Debug_Pool, secondary stack cannot be used
318 -- during Allocate calls, as some Allocate calls are done to
319 -- register/initialize a secondary stack for a foreign thread.
320 -- During these calls, the secondary stack is not available yet.
321
322 package Validity is
323 function Is_Handled (Storage : System.Address) return Boolean;
324 pragma Inline (Is_Handled);
325 -- Return True if Storage is the address of a block that the debug pool
326 -- already had under its control. Used to allow System.Memory to use
327 -- Debug_Pools
328
329 function Is_Valid (Storage : System.Address) return Boolean;
330 pragma Inline (Is_Valid);
331 -- Return True if Storage is the address of a block that the debug pool
332 -- has under its control, in which case Header_Of may be used to access
333 -- the associated allocation header.
334
335 procedure Set_Valid (Storage : System.Address; Value : Boolean);
336 pragma Inline (Set_Valid);
337 -- Mark the address Storage as being under control of the memory pool
338 -- (if Value is True), or not (if Value is False).
339
340 Validity_Count : Byte_Count := 0;
341 -- Total number of validity elements
342
343 end Validity;
344
345 use Validity;
346
347 procedure Set_Dead_Beef
348 (Storage_Address : System.Address;
349 Size_In_Storage_Elements : Storage_Count);
350 -- Set the contents of the memory block pointed to by Storage_Address to
351 -- the 16#DEADBEEF# pattern. If Size_In_Storage_Elements is not a multiple
352 -- of the length of this pattern, the last instance may be partial.
353
354 procedure Free_Physically (Pool : in out Debug_Pool);
355 -- Start to physically release some memory to the system, until the amount
356 -- of logically (but not physically) freed memory is lower than the
357 -- expected amount in Pool.
358
359 procedure Allocate_End;
360 procedure Deallocate_End;
361 procedure Dereference_End;
362 -- These procedures are used as markers when computing the stacktraces,
363 -- so that addresses in the debug pool itself are not reported to the user.
364
365 procedure Skip_Levels
366 (Depth : Natural;
367 Trace : Tracebacks_Array;
368 Start : out Natural;
369 Len : in out Natural;
370 Ignored_Frame_Start : System.Address;
371 Ignored_Frame_End : System.Address);
372 -- Set Start .. Len to the range of values from Trace that should be output
373 -- to the user. This range of values excludes any address prior to the
374 -- first one in Ignored_Frame_Start .. Ignored_Frame_End (basically
375 -- addresses internal to this package). Depth is the number of levels that
376 -- the user is interested in.
377
378 package STBE renames System.Traceback_Entries;
379
380 function PC_For (TB_Entry : STBE.Traceback_Entry) return System.Address
381 renames STBE.PC_For;
382
383 type Scope_Lock is
384 new Ada.Finalization.Limited_Controlled with null record;
385 -- Used to handle Lock_Task/Unlock_Task calls
386
387 overriding procedure Initialize (This : in out Scope_Lock);
388 -- Lock task on initialization
389
390 overriding procedure Finalize (This : in out Scope_Lock);
391 -- Unlock task on finalization
392
393 ----------------
394 -- Initialize --
395 ----------------
396
397 procedure Initialize (This : in out Scope_Lock) is
398 pragma Unreferenced (This);
399 begin
400 Lock_Task.all;
401 end Initialize;
402
403 --------------
404 -- Finalize --
405 --------------
406
407 procedure Finalize (This : in out Scope_Lock) is
408 pragma Unreferenced (This);
409 begin
410 Unlock_Task.all;
411 end Finalize;
412
413 -----------
414 -- Align --
415 -----------
416
417 function Align (Addr : Integer_Address) return Integer_Address is
418 Factor : constant Integer_Address := Storage_Alignment;
419 begin
420 return ((Addr + Factor - 1) / Factor) * Factor;
421 end Align;
422
423 ---------------
424 -- Header_Of --
425 ---------------
426
427 function Header_Of
428 (Address : System.Address) return Allocation_Header_Access
429 is
430 function Convert is
431 new Ada.Unchecked_Conversion
432 (System.Address,
433 Allocation_Header_Access);
434 begin
435 return Convert (Address - Header_Offset);
436 end Header_Of;
437
438 --------------
439 -- Set_Next --
440 --------------
441
442 procedure Set_Next
443 (E : Traceback_Htable_Elem_Ptr;
444 Next : Traceback_Htable_Elem_Ptr)
445 is
446 begin
447 E.Next := Next;
448 end Set_Next;
449
450 ----------
451 -- Next --
452 ----------
453
454 function Next
455 (E : Traceback_Htable_Elem_Ptr) return Traceback_Htable_Elem_Ptr
456 is
457 begin
458 return E.Next;
459 end Next;
460
461 -----------
462 -- Equal --
463 -----------
464
465 function Equal (K1, K2 : Tracebacks_Array_Access) return Boolean is
466 use type Tracebacks_Array;
467 begin
468 return K1.all = K2.all;
469 end Equal;
470
471 -------------
472 -- Get_Key --
473 -------------
474
475 function Get_Key
476 (E : Traceback_Htable_Elem_Ptr) return Tracebacks_Array_Access
477 is
478 begin
479 return E.Traceback;
480 end Get_Key;
481
482 ----------
483 -- Hash --
484 ----------
485
486 function Hash (T : Tracebacks_Array_Access) return Header is
487 Result : Integer_Address := 0;
488
489 begin
490 for X in T'Range loop
491 Result := Result + To_Integer (PC_For (T (X)));
492 end loop;
493
494 return Header (1 + Result mod Integer_Address (Header'Last));
495 end Hash;
496
497 -----------------
498 -- Output_File --
499 -----------------
500
501 function Output_File (Pool : Debug_Pool) return File_Type is
502 begin
503 if Pool.Errors_To_Stdout then
504 return Standard_Output;
505 else
506 return Standard_Error;
507 end if;
508 end Output_File;
509
510 -------------------
511 -- Print_Address --
512 -------------------
513
514 procedure Print_Address (File : File_Type; Addr : Address) is
515 begin
516 -- Warning: secondary stack cannot be used here. When System.Memory
517 -- implementation uses Debug_Pool, Print_Address can be called during
518 -- secondary stack creation for foreign threads.
519
520 Put (File, Image_C (Addr));
521 end Print_Address;
522
523 --------------
524 -- Put_Line --
525 --------------
526
527 procedure Put_Line
528 (File : File_Type;
529 Depth : Natural;
530 Traceback : Tracebacks_Array_Access;
531 Ignored_Frame_Start : System.Address := System.Null_Address;
532 Ignored_Frame_End : System.Address := System.Null_Address)
533 is
534 procedure Print (Tr : Tracebacks_Array);
535 -- Print the traceback to standard_output
536
537 -----------
538 -- Print --
539 -----------
540
541 procedure Print (Tr : Tracebacks_Array) is
542 begin
543 for J in Tr'Range loop
544 Print_Address (File, PC_For (Tr (J)));
545 Put (File, ' ');
546 end loop;
547 Put (File, ASCII.LF);
548 end Print;
549
550 -- Start of processing for Put_Line
551
552 begin
553 if Traceback = null then
554 declare
555 Len : Natural;
556 Start : Natural;
557 Trace : aliased Tracebacks_Array (1 .. Depth + Max_Ignored_Levels);
558
559 begin
560 Call_Chain (Trace, Len);
561 Skip_Levels
562 (Depth => Depth,
563 Trace => Trace,
564 Start => Start,
565 Len => Len,
566 Ignored_Frame_Start => Ignored_Frame_Start,
567 Ignored_Frame_End => Ignored_Frame_End);
568 Print (Trace (Start .. Len));
569 end;
570
571 else
572 Print (Traceback.all);
573 end if;
574 end Put_Line;
575
576 -----------------
577 -- Skip_Levels --
578 -----------------
579
580 procedure Skip_Levels
581 (Depth : Natural;
582 Trace : Tracebacks_Array;
583 Start : out Natural;
584 Len : in out Natural;
585 Ignored_Frame_Start : System.Address;
586 Ignored_Frame_End : System.Address)
587 is
588 begin
589 Start := Trace'First;
590
591 while Start <= Len
592 and then (PC_For (Trace (Start)) < Ignored_Frame_Start
593 or else PC_For (Trace (Start)) > Ignored_Frame_End)
594 loop
595 Start := Start + 1;
596 end loop;
597
598 Start := Start + 1;
599
600 -- Just in case: make sure we have a traceback even if Ignore_Till
601 -- wasn't found.
602
603 if Start > Len then
604 Start := 1;
605 end if;
606
607 if Len - Start + 1 > Depth then
608 Len := Depth + Start - 1;
609 end if;
610 end Skip_Levels;
611
612 ------------------------------
613 -- Find_Or_Create_Traceback --
614 ------------------------------
615
616 function Find_Or_Create_Traceback
617 (Pool : Debug_Pool;
618 Kind : Traceback_Kind;
619 Size : Storage_Count;
620 Ignored_Frame_Start : System.Address;
621 Ignored_Frame_End : System.Address) return Traceback_Htable_Elem_Ptr
622 is
623 begin
624 if Pool.Stack_Trace_Depth = 0 then
625 return null;
626 end if;
627
628 declare
629 Disable_Exit_Value : constant Boolean := Disable;
630
631 Elem : Traceback_Htable_Elem_Ptr;
632 Len : Natural;
633 Start : Natural;
634 Trace : aliased Tracebacks_Array
635 (1 .. Integer (Pool.Stack_Trace_Depth) +
636 Max_Ignored_Levels);
637
638 begin
639 Disable := True;
640 Call_Chain (Trace, Len);
641 Skip_Levels
642 (Depth => Pool.Stack_Trace_Depth,
643 Trace => Trace,
644 Start => Start,
645 Len => Len,
646 Ignored_Frame_Start => Ignored_Frame_Start,
647 Ignored_Frame_End => Ignored_Frame_End);
648
649 -- Check if the traceback is already in the table
650
651 Elem :=
652 Backtrace_Htable.Get (Trace (Start .. Len)'Unrestricted_Access);
653
654 -- If not, insert it
655
656 if Elem = null then
657 Elem :=
658 new Traceback_Htable_Elem'
659 (Traceback =>
660 new Tracebacks_Array'(Trace (Start .. Len)),
661 Count => 1,
662 Kind => Kind,
663 Total => Byte_Count (Size),
664 Frees => 0,
665 Total_Frees => 0,
666 Next => null);
667 Traceback_Count := Traceback_Count + 1;
668 Backtrace_Htable.Set (Elem);
669
670 else
671 Elem.Count := Elem.Count + 1;
672 Elem.Total := Elem.Total + Byte_Count (Size);
673 end if;
674
675 Disable := Disable_Exit_Value;
676 return Elem;
677 exception
678 when others =>
679 Disable := Disable_Exit_Value;
680 raise;
681 end;
682 end Find_Or_Create_Traceback;
683
684 --------------
685 -- Validity --
686 --------------
687
688 package body Validity is
689
690 -- The validity bits of the allocated blocks are kept in a has table.
691 -- Each component of the hash table contains the validity bits for a
692 -- 16 Mbyte memory chunk.
693
694 -- The reason the validity bits are kept for chunks of memory rather
695 -- than in a big array is that on some 64 bit platforms, it may happen
696 -- that two chunk of allocated data are very far from each other.
697
698 Memory_Chunk_Size : constant Integer_Address := 2 ** 24; -- 16 MB
699 Validity_Divisor : constant := Storage_Alignment * System.Storage_Unit;
700
701 Max_Validity_Byte_Index : constant :=
702 Memory_Chunk_Size / Validity_Divisor;
703
704 subtype Validity_Byte_Index is
705 Integer_Address range 0 .. Max_Validity_Byte_Index - 1;
706
707 type Byte is mod 2 ** System.Storage_Unit;
708
709 type Validity_Bits_Part is array (Validity_Byte_Index) of Byte;
710 type Validity_Bits_Part_Ref is access all Validity_Bits_Part;
711 No_Validity_Bits_Part : constant Validity_Bits_Part_Ref := null;
712
713 type Validity_Bits is record
714 Valid : Validity_Bits_Part_Ref := No_Validity_Bits_Part;
715 -- True if chunk of memory at this address is currently allocated
716
717 Handled : Validity_Bits_Part_Ref := No_Validity_Bits_Part;
718 -- True if chunk of memory at this address was allocated once after
719 -- Allow_Unhandled_Memory was set to True. Used to know on Deallocate
720 -- if chunk of memory should be handled a block allocated by this
721 -- package.
722
723 end record;
724
725 type Validity_Bits_Ref is access all Validity_Bits;
726 No_Validity_Bits : constant Validity_Bits_Ref := null;
727
728 Max_Header_Num : constant := 1023;
729
730 type Header_Num is range 0 .. Max_Header_Num - 1;
731
732 function Hash (F : Integer_Address) return Header_Num;
733
734 function Is_Valid_Or_Handled
735 (Storage : System.Address;
736 Valid : Boolean) return Boolean;
737 pragma Inline (Is_Valid_Or_Handled);
738 -- Internal implementation of Is_Valid and Is_Handled.
739 -- Valid is used to select Valid or Handled arrays.
740
741 package Validy_Htable is new GNAT.HTable.Simple_HTable
742 (Header_Num => Header_Num,
743 Element => Validity_Bits_Ref,
744 No_Element => No_Validity_Bits,
745 Key => Integer_Address,
746 Hash => Hash,
747 Equal => "=");
748 -- Table to keep the validity and handled bit blocks for the allocated
749 -- data.
750
751 function To_Pointer is new Ada.Unchecked_Conversion
752 (System.Address, Validity_Bits_Part_Ref);
753
754 procedure Memset (A : Address; C : Integer; N : size_t);
755 pragma Import (C, Memset, "memset");
756
757 ----------
758 -- Hash --
759 ----------
760
761 function Hash (F : Integer_Address) return Header_Num is
762 begin
763 return Header_Num (F mod Max_Header_Num);
764 end Hash;
765
766 -------------------------
767 -- Is_Valid_Or_Handled --
768 -------------------------
769
770 function Is_Valid_Or_Handled
771 (Storage : System.Address;
772 Valid : Boolean) return Boolean is
773 Int_Storage : constant Integer_Address := To_Integer (Storage);
774
775 begin
776 -- The pool only returns addresses aligned on Storage_Alignment so
777 -- anything off cannot be a valid block address and we can return
778 -- early in this case. We actually have to since our data structures
779 -- map validity bits for such aligned addresses only.
780
781 if Int_Storage mod Storage_Alignment /= 0 then
782 return False;
783 end if;
784
785 declare
786 Block_Number : constant Integer_Address :=
787 Int_Storage / Memory_Chunk_Size;
788 Ptr : constant Validity_Bits_Ref :=
789 Validy_Htable.Get (Block_Number);
790 Offset : constant Integer_Address :=
791 (Int_Storage -
792 (Block_Number * Memory_Chunk_Size)) /
793 Storage_Alignment;
794 Bit : constant Byte :=
795 2 ** Natural (Offset mod System.Storage_Unit);
796 begin
797 if Ptr = No_Validity_Bits then
798 return False;
799 else
800 if Valid then
801 return (Ptr.Valid (Offset / System.Storage_Unit)
802 and Bit) /= 0;
803 else
804 if Ptr.Handled = No_Validity_Bits_Part then
805 return False;
806 else
807 return (Ptr.Handled (Offset / System.Storage_Unit)
808 and Bit) /= 0;
809 end if;
810 end if;
811 end if;
812 end;
813 end Is_Valid_Or_Handled;
814
815 --------------
816 -- Is_Valid --
817 --------------
818
819 function Is_Valid (Storage : System.Address) return Boolean is
820 begin
821 return Is_Valid_Or_Handled (Storage => Storage, Valid => True);
822 end Is_Valid;
823
824 -----------------
825 -- Is_Handled --
826 -----------------
827
828 function Is_Handled (Storage : System.Address) return Boolean is
829 begin
830 return Is_Valid_Or_Handled (Storage => Storage, Valid => False);
831 end Is_Handled;
832
833 ---------------
834 -- Set_Valid --
835 ---------------
836
837 procedure Set_Valid (Storage : System.Address; Value : Boolean) is
838 Int_Storage : constant Integer_Address := To_Integer (Storage);
839 Block_Number : constant Integer_Address :=
840 Int_Storage / Memory_Chunk_Size;
841 Ptr : Validity_Bits_Ref := Validy_Htable.Get (Block_Number);
842 Offset : constant Integer_Address :=
843 (Int_Storage - (Block_Number * Memory_Chunk_Size)) /
844 Storage_Alignment;
845 Bit : constant Byte :=
846 2 ** Natural (Offset mod System.Storage_Unit);
847
848 procedure Set_Handled;
849 pragma Inline (Set_Handled);
850 -- if Allow_Unhandled_Memory set Handled bit in table.
851
852 -----------------
853 -- Set_Handled --
854 -----------------
855
856 procedure Set_Handled is
857 begin
858 if Allow_Unhandled_Memory then
859 if Ptr.Handled = No_Validity_Bits_Part then
860 Ptr.Handled :=
861 To_Pointer (Alloc (size_t (Max_Validity_Byte_Index)));
862 Memset
863 (A => Ptr.Handled.all'Address,
864 C => 0,
865 N => size_t (Max_Validity_Byte_Index));
866 end if;
867
868 Ptr.Handled (Offset / System.Storage_Unit) :=
869 Ptr.Handled (Offset / System.Storage_Unit) or Bit;
870 end if;
871 end Set_Handled;
872
873 -- Start of processing for Set_Valid
874
875 begin
876 if Ptr = No_Validity_Bits then
877
878 -- First time in this memory area: allocate a new block and put
879 -- it in the table.
880
881 if Value then
882 Ptr := new Validity_Bits;
883 Validity_Count := Validity_Count + 1;
884 Ptr.Valid :=
885 To_Pointer (Alloc (size_t (Max_Validity_Byte_Index)));
886 Validy_Htable.Set (Block_Number, Ptr);
887 Memset
888 (A => Ptr.Valid.all'Address,
889 C => 0,
890 N => size_t (Max_Validity_Byte_Index));
891 Ptr.Valid (Offset / System.Storage_Unit) := Bit;
892 Set_Handled;
893 end if;
894
895 else
896 if Value then
897 Ptr.Valid (Offset / System.Storage_Unit) :=
898 Ptr.Valid (Offset / System.Storage_Unit) or Bit;
899 Set_Handled;
900 else
901 Ptr.Valid (Offset / System.Storage_Unit) :=
902 Ptr.Valid (Offset / System.Storage_Unit) and not Bit;
903 end if;
904 end if;
905 end Set_Valid;
906 end Validity;
907
908 --------------
909 -- Allocate --
910 --------------
911
912 procedure Allocate
913 (Pool : in out Debug_Pool;
914 Storage_Address : out Address;
915 Size_In_Storage_Elements : Storage_Count;
916 Alignment : Storage_Count)
917 is
918 pragma Unreferenced (Alignment);
919 -- Ignored, we always force Storage_Alignment
920
921 type Local_Storage_Array is new Storage_Array
922 (1 .. Size_In_Storage_Elements + Extra_Allocation);
923
924 type Ptr is access Local_Storage_Array;
925 -- On some systems, we might want to physically protect pages against
926 -- writing when they have been freed (of course, this is expensive in
927 -- terms of wasted memory). To do that, all we should have to do it to
928 -- set the size of this array to the page size. See mprotect().
929
930 Current : Byte_Count;
931 P : Ptr;
932 Trace : Traceback_Htable_Elem_Ptr;
933
934 Reset_Disable_At_Exit : Boolean := False;
935
936 Lock : Scope_Lock;
937 pragma Unreferenced (Lock);
938
939 begin
940 if Disable then
941 Storage_Address :=
942 System.CRTL.malloc (System.CRTL.size_t (Size_In_Storage_Elements));
943 return;
944 end if;
945
946 Reset_Disable_At_Exit := True;
947 Disable := True;
948
949 Pool.Alloc_Count := Pool.Alloc_Count + 1;
950
951 -- If necessary, start physically releasing memory. The reason this is
952 -- done here, although Pool.Logically_Deallocated has not changed above,
953 -- is so that we do this only after a series of deallocations (e.g loop
954 -- that deallocates a big array). If we were doing that in Deallocate,
955 -- we might be physically freeing memory several times during the loop,
956 -- which is expensive.
957
958 if Pool.Logically_Deallocated >
959 Byte_Count (Pool.Maximum_Logically_Freed_Memory)
960 then
961 Free_Physically (Pool);
962 end if;
963
964 -- Use standard (i.e. through malloc) allocations. This automatically
965 -- raises Storage_Error if needed. We also try once more to physically
966 -- release memory, so that even marked blocks, in the advanced scanning,
967 -- are freed. Note that we do not initialize the storage array since it
968 -- is not necessary to do so (however this will cause bogus valgrind
969 -- warnings, which should simply be ignored).
970
971 begin
972 P := new Local_Storage_Array;
973
974 exception
975 when Storage_Error =>
976 Free_Physically (Pool);
977 P := new Local_Storage_Array;
978 end;
979
980 -- Compute Storage_Address, aimed at receiving user data. We need room
981 -- for the allocation header just ahead of the user data space plus
982 -- alignment padding so Storage_Address is aligned on Storage_Alignment,
983 -- like so:
984 --
985 -- Storage_Address, aligned
986 -- on Storage_Alignment
987 -- v
988 -- | ~~~~ | Header | User data ... |
989 -- ^........^
990 -- Header_Offset
991 --
992 -- Header_Offset is fixed so moving back and forth between user data
993 -- and allocation header is straightforward. The value is also such
994 -- that the header type alignment is honored when starting from
995 -- Default_alignment.
996
997 -- For the purpose of computing Storage_Address, we just do as if the
998 -- header was located first, followed by the alignment padding:
999
1000 Storage_Address :=
1001 To_Address (Align (To_Integer (P.all'Address) +
1002 Integer_Address (Header_Offset)));
1003 -- Computation is done in Integer_Address, not Storage_Offset, because
1004 -- the range of Storage_Offset may not be large enough.
1005
1006 pragma Assert ((Storage_Address - System.Null_Address)
1007 mod Storage_Alignment = 0);
1008 pragma Assert (Storage_Address + Size_In_Storage_Elements
1009 <= P.all'Address + P'Length);
1010
1011 Trace :=
1012 Find_Or_Create_Traceback
1013 (Pool => Pool,
1014 Kind => Alloc,
1015 Size => Size_In_Storage_Elements,
1016 Ignored_Frame_Start => Allocate'Code_Address,
1017 Ignored_Frame_End => Allocate_End'Code_Address);
1018
1019 pragma Warnings (Off);
1020 -- Turn warning on alignment for convert call off. We know that in fact
1021 -- this conversion is safe since P itself is always aligned on
1022 -- Storage_Alignment.
1023
1024 Header_Of (Storage_Address).all :=
1025 (Allocation_Address => P.all'Address,
1026 Alloc_Traceback => Trace,
1027 Dealloc_Traceback => To_Traceback (null),
1028 Next => Pool.First_Used_Block,
1029 Block_Size => Size_In_Storage_Elements);
1030
1031 pragma Warnings (On);
1032
1033 -- Link this block in the list of used blocks. This will be used to list
1034 -- memory leaks in Print_Info, and for the advanced schemes of
1035 -- Physical_Free, where we want to traverse all allocated blocks and
1036 -- search for possible references.
1037
1038 -- We insert in front, since most likely we'll be freeing the most
1039 -- recently allocated blocks first (the older one might stay allocated
1040 -- for the whole life of the application).
1041
1042 if Pool.First_Used_Block /= System.Null_Address then
1043 Header_Of (Pool.First_Used_Block).Dealloc_Traceback :=
1044 To_Address (Storage_Address);
1045 end if;
1046
1047 Pool.First_Used_Block := Storage_Address;
1048
1049 -- Mark the new address as valid
1050
1051 Set_Valid (Storage_Address, True);
1052
1053 if Pool.Low_Level_Traces then
1054 Put (Output_File (Pool),
1055 "info: Allocated"
1056 & Storage_Count'Image (Size_In_Storage_Elements)
1057 & " bytes at ");
1058 Print_Address (Output_File (Pool), Storage_Address);
1059 Put (Output_File (Pool),
1060 " (physically:"
1061 & Storage_Count'Image (Local_Storage_Array'Length)
1062 & " bytes at ");
1063 Print_Address (Output_File (Pool), P.all'Address);
1064 Put (Output_File (Pool),
1065 "), at ");
1066 Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null,
1067 Allocate'Code_Address,
1068 Deallocate_End'Code_Address);
1069 end if;
1070
1071 -- Update internal data
1072
1073 Pool.Allocated :=
1074 Pool.Allocated + Byte_Count (Size_In_Storage_Elements);
1075
1076 Current := Pool.Current_Water_Mark;
1077
1078 if Current > Pool.High_Water then
1079 Pool.High_Water := Current;
1080 end if;
1081
1082 Disable := False;
1083
1084 exception
1085 when others =>
1086 if Reset_Disable_At_Exit then
1087 Disable := False;
1088 end if;
1089 raise;
1090 end Allocate;
1091
1092 ------------------
1093 -- Allocate_End --
1094 ------------------
1095
1096 -- DO NOT MOVE, this must be right after Allocate. This is similar to what
1097 -- is done in a-except, so that we can hide the traceback frames internal
1098 -- to this package
1099
1100 procedure Allocate_End is null;
1101
1102 -------------------
1103 -- Set_Dead_Beef --
1104 -------------------
1105
1106 procedure Set_Dead_Beef
1107 (Storage_Address : System.Address;
1108 Size_In_Storage_Elements : Storage_Count)
1109 is
1110 Dead_Bytes : constant := 4;
1111
1112 type Data is mod 2 ** (Dead_Bytes * 8);
1113 for Data'Size use Dead_Bytes * 8;
1114
1115 Dead : constant Data := 16#DEAD_BEEF#;
1116
1117 type Dead_Memory is array
1118 (1 .. Size_In_Storage_Elements / Dead_Bytes) of Data;
1119 type Mem_Ptr is access Dead_Memory;
1120
1121 type Byte is mod 2 ** 8;
1122 for Byte'Size use 8;
1123
1124 type Dead_Memory_Bytes is array (0 .. 2) of Byte;
1125 type Dead_Memory_Bytes_Ptr is access Dead_Memory_Bytes;
1126
1127 function From_Ptr is new Ada.Unchecked_Conversion
1128 (System.Address, Mem_Ptr);
1129
1130 function From_Ptr is new Ada.Unchecked_Conversion
1131 (System.Address, Dead_Memory_Bytes_Ptr);
1132
1133 M : constant Mem_Ptr := From_Ptr (Storage_Address);
1134 M2 : Dead_Memory_Bytes_Ptr;
1135 Modulo : constant Storage_Count :=
1136 Size_In_Storage_Elements mod Dead_Bytes;
1137 begin
1138 M.all := [others => Dead];
1139
1140 -- Any bytes left (up to three of them)
1141
1142 if Modulo /= 0 then
1143 M2 := From_Ptr (Storage_Address + M'Length * Dead_Bytes);
1144
1145 M2 (0) := 16#DE#;
1146 if Modulo >= 2 then
1147 M2 (1) := 16#AD#;
1148
1149 if Modulo >= 3 then
1150 M2 (2) := 16#BE#;
1151 end if;
1152 end if;
1153 end if;
1154 end Set_Dead_Beef;
1155
1156 ---------------------
1157 -- Free_Physically --
1158 ---------------------
1159
1160 procedure Free_Physically (Pool : in out Debug_Pool) is
1161 type Byte is mod 256;
1162 type Byte_Access is access Byte;
1163
1164 function To_Byte is new Ada.Unchecked_Conversion
1165 (System.Address, Byte_Access);
1166
1167 type Address_Access is access System.Address;
1168
1169 function To_Address_Access is new Ada.Unchecked_Conversion
1170 (System.Address, Address_Access);
1171
1172 In_Use_Mark : constant Byte := 16#D#;
1173 Free_Mark : constant Byte := 16#F#;
1174
1175 Total_Freed : Storage_Count := 0;
1176
1177 procedure Reset_Marks;
1178 -- Unmark all the logically freed blocks, so that they are considered
1179 -- for physical deallocation
1180
1181 procedure Mark
1182 (H : Allocation_Header_Access; A : System.Address; In_Use : Boolean);
1183 -- Mark the user data block starting at A. For a block of size zero,
1184 -- nothing is done. For a block with a different size, the first byte
1185 -- is set to either "D" (in use) or "F" (free).
1186
1187 function Marked (A : System.Address) return Boolean;
1188 -- Return true if the user data block starting at A might be in use
1189 -- somewhere else
1190
1191 procedure Mark_Blocks;
1192 -- Traverse all allocated blocks, and search for possible references
1193 -- to logically freed blocks. Mark them appropriately
1194
1195 procedure Free_Blocks (Ignore_Marks : Boolean);
1196 -- Physically release blocks. Only the blocks that haven't been marked
1197 -- will be released, unless Ignore_Marks is true.
1198
1199 -----------------
1200 -- Free_Blocks --
1201 -----------------
1202
1203 procedure Free_Blocks (Ignore_Marks : Boolean) is
1204 Header : Allocation_Header_Access;
1205 Tmp : System.Address := Pool.First_Free_Block;
1206 Next : System.Address;
1207 Previous : System.Address := System.Null_Address;
1208
1209 begin
1210 while Tmp /= System.Null_Address
1211 and then
1212 not (Total_Freed > Pool.Minimum_To_Free
1213 and Pool.Logically_Deallocated <
1214 Byte_Count (Pool.Maximum_Logically_Freed_Memory))
1215 loop
1216 Header := Header_Of (Tmp);
1217
1218 -- If we know, or at least assume, the block is no longer
1219 -- referenced anywhere, we can free it physically.
1220
1221 if Ignore_Marks or else not Marked (Tmp) then
1222 declare
1223 pragma Suppress (All_Checks);
1224 -- Suppress the checks on this section. If they are overflow
1225 -- errors, it isn't critical, and we'd rather avoid a
1226 -- Constraint_Error in that case.
1227
1228 begin
1229 -- Note that block_size < zero for freed blocks
1230
1231 Pool.Physically_Deallocated :=
1232 Pool.Physically_Deallocated -
1233 Byte_Count (Header.Block_Size);
1234
1235 Pool.Logically_Deallocated :=
1236 Pool.Logically_Deallocated +
1237 Byte_Count (Header.Block_Size);
1238
1239 Total_Freed := Total_Freed - Header.Block_Size;
1240 end;
1241
1242 Next := Header.Next;
1243
1244 if Pool.Low_Level_Traces then
1245 Put
1246 (Output_File (Pool),
1247 "info: Freeing physical memory "
1248 & Storage_Count'Image
1249 ((abs Header.Block_Size) + Extra_Allocation)
1250 & " bytes at ");
1251 Print_Address (Output_File (Pool),
1252 Header.Allocation_Address);
1253 Put_Line (Output_File (Pool), "");
1254 end if;
1255
1256 if System_Memory_Debug_Pool_Enabled then
1257 System.CRTL.free (Header.Allocation_Address);
1258 else
1259 System.Memory.Free (Header.Allocation_Address);
1260 end if;
1261
1262 Set_Valid (Tmp, False);
1263
1264 -- Remove this block from the list
1265
1266 if Previous = System.Null_Address then
1267 Pool.First_Free_Block := Next;
1268 else
1269 Header_Of (Previous).Next := Next;
1270 end if;
1271
1272 Tmp := Next;
1273
1274 else
1275 Previous := Tmp;
1276 Tmp := Header.Next;
1277 end if;
1278 end loop;
1279 end Free_Blocks;
1280
1281 ----------
1282 -- Mark --
1283 ----------
1284
1285 procedure Mark
1286 (H : Allocation_Header_Access;
1287 A : System.Address;
1288 In_Use : Boolean)
1289 is
1290 begin
1291 if H.Block_Size /= 0 then
1292 To_Byte (A).all := (if In_Use then In_Use_Mark else Free_Mark);
1293 end if;
1294 end Mark;
1295
1296 -----------------
1297 -- Mark_Blocks --
1298 -----------------
1299
1300 procedure Mark_Blocks is
1301 Tmp : System.Address := Pool.First_Used_Block;
1302 Previous : System.Address;
1303 Last : System.Address;
1304 Pointed : System.Address;
1305 Header : Allocation_Header_Access;
1306
1307 begin
1308 -- For each allocated block, check its contents. Things that look
1309 -- like a possible address are used to mark the blocks so that we try
1310 -- and keep them, for better detection in case of invalid access.
1311 -- This mechanism is far from being fool-proof: it doesn't check the
1312 -- stacks of the threads, doesn't check possible memory allocated not
1313 -- under control of this debug pool. But it should allow us to catch
1314 -- more cases.
1315
1316 while Tmp /= System.Null_Address loop
1317 Previous := Tmp;
1318 Last := Tmp + Header_Of (Tmp).Block_Size;
1319 while Previous < Last loop
1320 -- ??? Should we move byte-per-byte, or consider that addresses
1321 -- are always aligned on 4-bytes boundaries ? Let's use the
1322 -- fastest for now.
1323
1324 Pointed := To_Address_Access (Previous).all;
1325 if Is_Valid (Pointed) then
1326 Header := Header_Of (Pointed);
1327
1328 -- Do not even attempt to mark blocks in use. That would
1329 -- screw up the whole application, of course.
1330
1331 if Header.Block_Size < 0 then
1332 Mark (Header, Pointed, In_Use => True);
1333 end if;
1334 end if;
1335
1336 Previous := Previous + System.Address'Size;
1337 end loop;
1338
1339 Tmp := Header_Of (Tmp).Next;
1340 end loop;
1341 end Mark_Blocks;
1342
1343 ------------
1344 -- Marked --
1345 ------------
1346
1347 function Marked (A : System.Address) return Boolean is
1348 begin
1349 return To_Byte (A).all = In_Use_Mark;
1350 end Marked;
1351
1352 -----------------
1353 -- Reset_Marks --
1354 -----------------
1355
1356 procedure Reset_Marks is
1357 Current : System.Address := Pool.First_Free_Block;
1358 Header : Allocation_Header_Access;
1359
1360 begin
1361 while Current /= System.Null_Address loop
1362 Header := Header_Of (Current);
1363 Mark (Header, Current, False);
1364 Current := Header.Next;
1365 end loop;
1366 end Reset_Marks;
1367
1368 Lock : Scope_Lock;
1369 pragma Unreferenced (Lock);
1370
1371 -- Start of processing for Free_Physically
1372
1373 begin
1374 if Pool.Advanced_Scanning then
1375
1376 -- Reset the mark for each freed block
1377
1378 Reset_Marks;
1379
1380 Mark_Blocks;
1381 end if;
1382
1383 Free_Blocks (Ignore_Marks => not Pool.Advanced_Scanning);
1384
1385 -- The contract is that we need to free at least Minimum_To_Free bytes,
1386 -- even if this means freeing marked blocks in the advanced scheme.
1387
1388 if Total_Freed < Pool.Minimum_To_Free
1389 and then Pool.Advanced_Scanning
1390 then
1391 Pool.Marked_Blocks_Deallocated := True;
1392 Free_Blocks (Ignore_Marks => True);
1393 end if;
1394 end Free_Physically;
1395
1396 --------------
1397 -- Get_Size --
1398 --------------
1399
1400 procedure Get_Size
1401 (Storage_Address : Address;
1402 Size_In_Storage_Elements : out Storage_Count;
1403 Valid : out Boolean)
1404 is
1405 Lock : Scope_Lock;
1406 pragma Unreferenced (Lock);
1407
1408 begin
1409 Valid := Is_Valid (Storage_Address);
1410 Size_In_Storage_Elements := Storage_Count'First;
1411
1412 if Is_Valid (Storage_Address) then
1413 declare
1414 Header : constant Allocation_Header_Access :=
1415 Header_Of (Storage_Address);
1416
1417 begin
1418 if Header.Block_Size >= 0 then
1419 Valid := True;
1420 Size_In_Storage_Elements := Header.Block_Size;
1421 else
1422 Valid := False;
1423 end if;
1424 end;
1425 else
1426 Valid := False;
1427 end if;
1428 end Get_Size;
1429
1430 ---------------------
1431 -- Print_Traceback --
1432 ---------------------
1433
1434 procedure Print_Traceback
1435 (Output_File : File_Type;
1436 Prefix : String;
1437 Traceback : Traceback_Htable_Elem_Ptr)
1438 is
1439 begin
1440 if Traceback /= null then
1441 Put (Output_File, Prefix);
1442 Put_Line (Output_File, 0, Traceback.Traceback);
1443 end if;
1444 end Print_Traceback;
1445
1446 ----------------
1447 -- Deallocate --
1448 ----------------
1449
1450 procedure Deallocate
1451 (Pool : in out Debug_Pool;
1452 Storage_Address : Address;
1453 Size_In_Storage_Elements : Storage_Count;
1454 Alignment : Storage_Count)
1455 is
1456 pragma Unreferenced (Alignment);
1457
1458 Header : constant Allocation_Header_Access :=
1459 Header_Of (Storage_Address);
1460 Previous : System.Address;
1461 Valid : Boolean;
1462
1463 Header_Block_Size_Was_Less_Than_0 : Boolean := True;
1464
1465 begin
1466 declare
1467 Lock : Scope_Lock;
1468 pragma Unreferenced (Lock);
1469
1470 begin
1471 Valid := Is_Valid (Storage_Address);
1472
1473 if Valid and then not (Header.Block_Size < 0) then
1474 Header_Block_Size_Was_Less_Than_0 := False;
1475
1476 -- Some sort of codegen problem or heap corruption caused the
1477 -- Size_In_Storage_Elements to be wrongly computed. The code
1478 -- below is all based on the assumption that Header.all is not
1479 -- corrupted, such that the error is non-fatal.
1480
1481 if Header.Block_Size /= Size_In_Storage_Elements and then
1482 Size_In_Storage_Elements /= Storage_Count'Last
1483 then
1484 Put_Line (Output_File (Pool),
1485 "error: Deallocate size "
1486 & Storage_Count'Image (Size_In_Storage_Elements)
1487 & " does not match allocate size "
1488 & Storage_Count'Image (Header.Block_Size));
1489 end if;
1490
1491 if Pool.Low_Level_Traces then
1492 Put (Output_File (Pool),
1493 "info: Deallocated"
1494 & Storage_Count'Image (Header.Block_Size)
1495 & " bytes at ");
1496 Print_Address (Output_File (Pool), Storage_Address);
1497 Put (Output_File (Pool),
1498 " (physically"
1499 & Storage_Count'Image
1500 (Header.Block_Size + Extra_Allocation)
1501 & " bytes at ");
1502 Print_Address (Output_File (Pool), Header.Allocation_Address);
1503 Put (Output_File (Pool), "), at ");
1504
1505 Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null,
1506 Deallocate'Code_Address,
1507 Deallocate_End'Code_Address);
1508 Print_Traceback (Output_File (Pool),
1509 " Memory was allocated at ",
1510 Header.Alloc_Traceback);
1511 end if;
1512
1513 -- Remove this block from the list of used blocks
1514
1515 Previous :=
1516 To_Address (Header.Dealloc_Traceback);
1517
1518 if Previous = System.Null_Address then
1519 Pool.First_Used_Block := Header_Of (Pool.First_Used_Block).Next;
1520
1521 if Pool.First_Used_Block /= System.Null_Address then
1522 Header_Of (Pool.First_Used_Block).Dealloc_Traceback :=
1523 To_Traceback (null);
1524 end if;
1525
1526 else
1527 Header_Of (Previous).Next := Header.Next;
1528
1529 if Header.Next /= System.Null_Address then
1530 Header_Of
1531 (Header.Next).Dealloc_Traceback := To_Address (Previous);
1532 end if;
1533 end if;
1534
1535 -- Update the Alloc_Traceback Frees/Total_Frees members
1536 -- (if present)
1537
1538 if Header.Alloc_Traceback /= null then
1539 Header.Alloc_Traceback.Frees :=
1540 Header.Alloc_Traceback.Frees + 1;
1541 Header.Alloc_Traceback.Total_Frees :=
1542 Header.Alloc_Traceback.Total_Frees +
1543 Byte_Count (Header.Block_Size);
1544 end if;
1545
1546 Pool.Free_Count := Pool.Free_Count + 1;
1547
1548 -- Update the header
1549
1550 Header.all :=
1551 (Allocation_Address => Header.Allocation_Address,
1552 Alloc_Traceback => Header.Alloc_Traceback,
1553 Dealloc_Traceback => To_Traceback
1554 (Find_Or_Create_Traceback
1555 (Pool, Dealloc,
1556 Header.Block_Size,
1557 Deallocate'Code_Address,
1558 Deallocate_End'Code_Address)),
1559 Next => System.Null_Address,
1560 Block_Size => -Header.Block_Size);
1561
1562 if Pool.Reset_Content_On_Free then
1563 Set_Dead_Beef (Storage_Address, -Header.Block_Size);
1564 end if;
1565
1566 Pool.Logically_Deallocated :=
1567 Pool.Logically_Deallocated + Byte_Count (-Header.Block_Size);
1568
1569 -- Link this free block with the others (at the end of the list,
1570 -- so that we can start releasing the older blocks first later on)
1571
1572 if Pool.First_Free_Block = System.Null_Address then
1573 Pool.First_Free_Block := Storage_Address;
1574 Pool.Last_Free_Block := Storage_Address;
1575
1576 else
1577 Header_Of (Pool.Last_Free_Block).Next := Storage_Address;
1578 Pool.Last_Free_Block := Storage_Address;
1579 end if;
1580
1581 -- Do not physically release the memory here, but in Alloc.
1582 -- See comment there for details.
1583 end if;
1584 end;
1585
1586 if not Valid then
1587 if Storage_Address = System.Null_Address then
1588 if Pool.Raise_Exceptions and then
1589 Size_In_Storage_Elements /= Storage_Count'Last
1590 then
1591 raise Freeing_Not_Allocated_Storage;
1592 else
1593 Put (Output_File (Pool),
1594 "error: Freeing Null_Address, at ");
1595 Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null,
1596 Deallocate'Code_Address,
1597 Deallocate_End'Code_Address);
1598 return;
1599 end if;
1600 end if;
1601
1602 if Allow_Unhandled_Memory
1603 and then not Is_Handled (Storage_Address)
1604 then
1605 System.CRTL.free (Storage_Address);
1606 return;
1607 end if;
1608
1609 if Pool.Raise_Exceptions
1610 and then Size_In_Storage_Elements /= Storage_Count'Last
1611 then
1612 raise Freeing_Not_Allocated_Storage;
1613 else
1614 Put (Output_File (Pool),
1615 "error: Freeing not allocated storage, at ");
1616 Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null,
1617 Deallocate'Code_Address,
1618 Deallocate_End'Code_Address);
1619 end if;
1620
1621 elsif Header_Block_Size_Was_Less_Than_0 then
1622 if Pool.Raise_Exceptions then
1623 raise Freeing_Deallocated_Storage;
1624 else
1625 Put (Output_File (Pool),
1626 "error: Freeing already deallocated storage, at ");
1627 Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null,
1628 Deallocate'Code_Address,
1629 Deallocate_End'Code_Address);
1630 Print_Traceback (Output_File (Pool),
1631 " Memory already deallocated at ",
1632 To_Traceback (Header.Dealloc_Traceback));
1633 Print_Traceback (Output_File (Pool), " Memory was allocated at ",
1634 Header.Alloc_Traceback);
1635 end if;
1636 end if;
1637 end Deallocate;
1638
1639 --------------------
1640 -- Deallocate_End --
1641 --------------------
1642
1643 -- DO NOT MOVE, this must be right after Deallocate
1644
1645 -- See Allocate_End
1646
1647 -- This is making assumptions about code order that may be invalid ???
1648
1649 procedure Deallocate_End is null;
1650
1651 -----------------
1652 -- Dereference --
1653 -----------------
1654
1655 procedure Dereference
1656 (Pool : in out Debug_Pool;
1657 Storage_Address : Address;
1658 Size_In_Storage_Elements : Storage_Count;
1659 Alignment : Storage_Count)
1660 is
1661 pragma Unreferenced (Alignment, Size_In_Storage_Elements);
1662
1663 Valid : constant Boolean := Is_Valid (Storage_Address);
1664 Header : Allocation_Header_Access;
1665
1666 begin
1667 -- Locking policy: we do not do any locking in this procedure. The
1668 -- tables are only read, not written to, and although a problem might
1669 -- appear if someone else is modifying the tables at the same time, this
1670 -- race condition is not intended to be detected by this storage_pool (a
1671 -- now invalid pointer would appear as valid). Instead, we prefer
1672 -- optimum performance for dereferences.
1673
1674 if not Valid then
1675 if Pool.Raise_Exceptions then
1676 raise Accessing_Not_Allocated_Storage;
1677 else
1678 Put (Output_File (Pool),
1679 "error: Accessing not allocated storage, at ");
1680 Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null,
1681 Deallocate'Code_Address,
1682 Dereference_End'Code_Address);
1683 end if;
1684
1685 else
1686 Header := Header_Of (Storage_Address);
1687
1688 if Header.Block_Size < 0 then
1689 if Pool.Raise_Exceptions then
1690 raise Accessing_Deallocated_Storage;
1691 else
1692 Put (Output_File (Pool),
1693 "error: Accessing deallocated storage, at ");
1694 Put_Line
1695 (Output_File (Pool), Pool.Stack_Trace_Depth, null,
1696 Deallocate'Code_Address,
1697 Dereference_End'Code_Address);
1698 Print_Traceback (Output_File (Pool), " First deallocation at ",
1699 To_Traceback (Header.Dealloc_Traceback));
1700 Print_Traceback (Output_File (Pool), " Initial allocation at ",
1701 Header.Alloc_Traceback);
1702 end if;
1703 end if;
1704 end if;
1705 end Dereference;
1706
1707 ---------------------
1708 -- Dereference_End --
1709 ---------------------
1710
1711 -- DO NOT MOVE: this must be right after Dereference
1712
1713 -- See Allocate_End
1714
1715 -- This is making assumptions about code order that may be invalid ???
1716
1717 procedure Dereference_End is null;
1718
1719 ----------------
1720 -- Print_Info --
1721 ----------------
1722
1723 procedure Print_Info
1724 (Pool : Debug_Pool;
1725 Cumulate : Boolean := False;
1726 Display_Slots : Boolean := False;
1727 Display_Leaks : Boolean := False)
1728 is
1729 package Backtrace_Htable_Cumulate is new GNAT.HTable.Static_HTable
1730 (Header_Num => Header,
1731 Element => Traceback_Htable_Elem,
1732 Elmt_Ptr => Traceback_Htable_Elem_Ptr,
1733 Null_Ptr => null,
1734 Set_Next => Set_Next,
1735 Next => Next,
1736 Key => Tracebacks_Array_Access,
1737 Get_Key => Get_Key,
1738 Hash => Hash,
1739 Equal => Equal);
1740 -- This needs a comment ??? probably some of the ones below do too???
1741
1742 Current : System.Address;
1743 Data : Traceback_Htable_Elem_Ptr;
1744 Elem : Traceback_Htable_Elem_Ptr;
1745 Header : Allocation_Header_Access;
1746 K : Traceback_Kind;
1747
1748 begin
1749 Put_Line
1750 ("Total allocated bytes : " &
1751 Byte_Count'Image (Pool.Allocated));
1752
1753 Put_Line
1754 ("Total logically deallocated bytes : " &
1755 Byte_Count'Image (Pool.Logically_Deallocated));
1756
1757 Put_Line
1758 ("Total physically deallocated bytes : " &
1759 Byte_Count'Image (Pool.Physically_Deallocated));
1760
1761 if Pool.Marked_Blocks_Deallocated then
1762 Put_Line ("Marked blocks were physically deallocated. This is");
1763 Put_Line ("potentially dangerous, and you might want to run");
1764 Put_Line ("again with a lower value of Minimum_To_Free");
1765 end if;
1766
1767 Put_Line
1768 ("Current Water Mark: " &
1769 Byte_Count'Image (Pool.Current_Water_Mark));
1770
1771 Put_Line
1772 ("High Water Mark: " &
1773 Byte_Count'Image (Pool.High_Water));
1774
1775 Put_Line ("");
1776
1777 if Display_Slots then
1778 Data := Backtrace_Htable.Get_First;
1779 while Data /= null loop
1780 if Data.Kind in Alloc .. Dealloc then
1781 Elem :=
1782 new Traceback_Htable_Elem'
1783 (Traceback => new Tracebacks_Array'(Data.Traceback.all),
1784 Count => Data.Count,
1785 Kind => Data.Kind,
1786 Total => Data.Total,
1787 Frees => Data.Frees,
1788 Total_Frees => Data.Total_Frees,
1789 Next => null);
1790 Backtrace_Htable_Cumulate.Set (Elem);
1791
1792 if Cumulate then
1793 K := (if Data.Kind = Alloc then Indirect_Alloc
1794 else Indirect_Dealloc);
1795
1796 -- Propagate the direct call to all its parents
1797
1798 for T in Data.Traceback'First + 1 .. Data.Traceback'Last loop
1799 Elem := Backtrace_Htable_Cumulate.Get
1800 (Data.Traceback
1801 (T .. Data.Traceback'Last)'Unrestricted_Access);
1802
1803 -- If not, insert it
1804
1805 if Elem = null then
1806 Elem :=
1807 new Traceback_Htable_Elem'
1808 (Traceback =>
1809 new Tracebacks_Array'
1810 (Data.Traceback
1811 (T .. Data.Traceback'Last)),
1812 Count => Data.Count,
1813 Kind => K,
1814 Total => Data.Total,
1815 Frees => Data.Frees,
1816 Total_Frees => Data.Total_Frees,
1817 Next => null);
1818 Backtrace_Htable_Cumulate.Set (Elem);
1819
1820 -- Properly take into account that the subprograms
1821 -- indirectly called might be doing either allocations
1822 -- or deallocations. This needs to be reflected in the
1823 -- counts.
1824
1825 else
1826 Elem.Count := Elem.Count + Data.Count;
1827
1828 if K = Elem.Kind then
1829 Elem.Total := Elem.Total + Data.Total;
1830
1831 elsif Elem.Total > Data.Total then
1832 Elem.Total := Elem.Total - Data.Total;
1833
1834 else
1835 Elem.Kind := K;
1836 Elem.Total := Data.Total - Elem.Total;
1837 end if;
1838 end if;
1839 end loop;
1840 end if;
1841
1842 Data := Backtrace_Htable.Get_Next;
1843 end if;
1844 end loop;
1845
1846 Put_Line ("List of allocations/deallocations: ");
1847
1848 Data := Backtrace_Htable_Cumulate.Get_First;
1849 while Data /= null loop
1850 case Data.Kind is
1851 when Alloc => Put ("alloc (count:");
1852 when Indirect_Alloc => Put ("indirect alloc (count:");
1853 when Dealloc => Put ("free (count:");
1854 when Indirect_Dealloc => Put ("indirect free (count:");
1855 end case;
1856
1857 Put (Natural'Image (Data.Count) & ", total:" &
1858 Byte_Count'Image (Data.Total) & ") ");
1859
1860 for T in Data.Traceback'Range loop
1861 Put (Image_C (PC_For (Data.Traceback (T))) & ' ');
1862 end loop;
1863
1864 Put_Line ("");
1865
1866 Data := Backtrace_Htable_Cumulate.Get_Next;
1867 end loop;
1868
1869 Backtrace_Htable_Cumulate.Reset;
1870 end if;
1871
1872 if Display_Leaks then
1873 Put_Line ("");
1874 Put_Line ("List of not deallocated blocks:");
1875
1876 -- Do not try to group the blocks with the same stack traces
1877 -- together. This is done by the gnatmem output.
1878
1879 Current := Pool.First_Used_Block;
1880 while Current /= System.Null_Address loop
1881 Header := Header_Of (Current);
1882
1883 Put ("Size: " & Storage_Count'Image (Header.Block_Size) & " at: ");
1884
1885 if Header.Alloc_Traceback /= null then
1886 for T in Header.Alloc_Traceback.Traceback'Range loop
1887 Put (Image_C
1888 (PC_For (Header.Alloc_Traceback.Traceback (T))) & ' ');
1889 end loop;
1890 end if;
1891
1892 Put_Line ("");
1893 Current := Header.Next;
1894 end loop;
1895 end if;
1896 end Print_Info;
1897
1898 ----------
1899 -- Dump --
1900 ----------
1901
1902 procedure Dump
1903 (Pool : Debug_Pool;
1904 Size : Positive;
1905 Report : Report_Type := All_Reports)
1906 is
1907 procedure Do_Report (Sort : Report_Type);
1908 -- Do a specific type of report
1909
1910 ---------------
1911 -- Do_Report --
1912 ---------------
1913
1914 procedure Do_Report (Sort : Report_Type) is
1915 Elem : Traceback_Htable_Elem_Ptr;
1916 Bigger : Boolean;
1917 Grand_Total : Float;
1918
1919 Max : array (1 .. Size) of Traceback_Htable_Elem_Ptr :=
1920 [others => null];
1921 -- Sorted array for the biggest memory users
1922
1923 Allocated_In_Pool : Byte_Count;
1924 -- safe thread Pool.Allocated
1925
1926 Elem_Safe : Traceback_Htable_Elem;
1927 -- safe thread current elem.all;
1928
1929 Max_M_Safe : Traceback_Htable_Elem;
1930 -- safe thread Max(M).all
1931
1932 begin
1933 Put_Line ("");
1934
1935 case Sort is
1936 when All_Reports
1937 | Memory_Usage
1938 =>
1939 Put_Line (Size'Img & " biggest memory users at this time:");
1940 Put_Line ("Results include bytes and chunks still allocated");
1941 Grand_Total := Float (Pool.Current_Water_Mark);
1942
1943 when Allocations_Count =>
1944 Put_Line (Size'Img & " biggest number of live allocations:");
1945 Put_Line ("Results include bytes and chunks still allocated");
1946 Grand_Total := Float (Pool.Current_Water_Mark);
1947
1948 when Sort_Total_Allocs =>
1949 Put_Line (Size'Img & " biggest number of allocations:");
1950 Put_Line ("Results include total bytes and chunks allocated,");
1951 Put_Line ("even if no longer allocated - Deallocations are"
1952 & " ignored");
1953
1954 declare
1955 Lock : Scope_Lock;
1956 pragma Unreferenced (Lock);
1957 begin
1958 Allocated_In_Pool := Pool.Allocated;
1959 end;
1960
1961 Grand_Total := Float (Allocated_In_Pool);
1962
1963 when Marked_Blocks =>
1964 Put_Line ("Special blocks marked by Mark_Traceback");
1965 Grand_Total := 0.0;
1966 end case;
1967
1968 declare
1969 Lock : Scope_Lock;
1970 pragma Unreferenced (Lock);
1971 begin
1972 Elem := Backtrace_Htable.Get_First;
1973 end;
1974
1975 while Elem /= null loop
1976 declare
1977 Lock : Scope_Lock;
1978 pragma Unreferenced (Lock);
1979 begin
1980 Elem_Safe := Elem.all;
1981 end;
1982
1983 -- Handle only alloc elememts
1984 if Elem_Safe.Kind = Alloc then
1985 -- Ignore small blocks (depending on the sorting criteria) to
1986 -- gain speed.
1987
1988 if (Sort = Memory_Usage
1989 and then Elem_Safe.Total - Elem_Safe.Total_Frees >= 1_000)
1990 or else (Sort = Allocations_Count
1991 and then Elem_Safe.Count - Elem_Safe.Frees >= 1)
1992 or else (Sort = Sort_Total_Allocs
1993 and then Elem_Safe.Count > 1)
1994 or else (Sort = Marked_Blocks
1995 and then Elem_Safe.Total = 0)
1996 then
1997 if Sort = Marked_Blocks then
1998 Grand_Total := Grand_Total + Float (Elem_Safe.Count);
1999 end if;
2000
2001 for M in Max'Range loop
2002 Bigger := Max (M) = null;
2003 if not Bigger then
2004 declare
2005 Lock : Scope_Lock;
2006 pragma Unreferenced (Lock);
2007 begin
2008 Max_M_Safe := Max (M).all;
2009 end;
2010
2011 case Sort is
2012 when All_Reports
2013 | Memory_Usage
2014 =>
2015 Bigger :=
2016 Max_M_Safe.Total - Max_M_Safe.Total_Frees
2017 < Elem_Safe.Total - Elem_Safe.Total_Frees;
2018
2019 when Allocations_Count =>
2020 Bigger :=
2021 Max_M_Safe.Count - Max_M_Safe.Frees
2022 < Elem_Safe.Count - Elem_Safe.Frees;
2023
2024 when Marked_Blocks
2025 | Sort_Total_Allocs
2026 =>
2027 Bigger := Max_M_Safe.Count < Elem_Safe.Count;
2028 end case;
2029 end if;
2030
2031 if Bigger then
2032 Max (M + 1 .. Max'Last) := Max (M .. Max'Last - 1);
2033 Max (M) := Elem;
2034 exit;
2035 end if;
2036 end loop;
2037 end if;
2038 end if;
2039
2040 declare
2041 Lock : Scope_Lock;
2042 pragma Unreferenced (Lock);
2043 begin
2044 Elem := Backtrace_Htable.Get_Next;
2045 end;
2046 end loop;
2047
2048 if Grand_Total = 0.0 then
2049 Grand_Total := 1.0;
2050 end if;
2051
2052 for M in Max'Range loop
2053 exit when Max (M) = null;
2054 declare
2055 type Percent is delta 0.1 range 0.0 .. 100.0;
2056
2057 P : Percent;
2058 Total : Byte_Count;
2059
2060 begin
2061 declare
2062 Lock : Scope_Lock;
2063 pragma Unreferenced (Lock);
2064 begin
2065 Max_M_Safe := Max (M).all;
2066 end;
2067
2068 case Sort is
2069 when All_Reports
2070 | Allocations_Count
2071 | Memory_Usage
2072 =>
2073 Total := Max_M_Safe.Total - Max_M_Safe.Total_Frees;
2074
2075 when Sort_Total_Allocs =>
2076 Total := Max_M_Safe.Total;
2077
2078 when Marked_Blocks =>
2079 Total := Byte_Count (Max_M_Safe.Count);
2080 end case;
2081
2082 declare
2083 Normalized_Total : constant Float := Float (Total);
2084 -- In multi tasking configuration, memory deallocations
2085 -- during Do_Report processing can lead to Total >
2086 -- Grand_Total. As Percent requires Total <= Grand_Total
2087
2088 begin
2089 if Normalized_Total > Grand_Total then
2090 P := 100.0;
2091 else
2092 P := Percent (100.0 * Normalized_Total / Grand_Total);
2093 end if;
2094 end;
2095
2096 case Sort is
2097 when All_Reports
2098 | Allocations_Count
2099 | Memory_Usage
2100 =>
2101 declare
2102 Count : constant Natural :=
2103 Max_M_Safe.Count - Max_M_Safe.Frees;
2104 begin
2105 Put (P'Img & "%:" & Total'Img & " bytes in"
2106 & Count'Img & " chunks at");
2107 end;
2108
2109 when Sort_Total_Allocs =>
2110 Put (P'Img & "%:" & Total'Img & " bytes in"
2111 & Max_M_Safe.Count'Img & " chunks at");
2112
2113 when Marked_Blocks =>
2114 Put (P'Img & "%:"
2115 & Max_M_Safe.Count'Img & " chunks /"
2116 & Integer (Grand_Total)'Img & " at");
2117 end case;
2118 end;
2119
2120 for J in Max (M).Traceback'Range loop
2121 Put (" " & Image_C (PC_For (Max (M).Traceback (J))));
2122 end loop;
2123
2124 Put_Line ("");
2125 end loop;
2126 end Do_Report;
2127
2128 -- Local variables
2129
2130 Total_Freed : Byte_Count;
2131 -- safe thread pool logically & physically deallocated
2132
2133 Traceback_Elements_Allocated : Byte_Count;
2134 -- safe thread Traceback_Count
2135
2136 Validity_Elements_Allocated : Byte_Count;
2137 -- safe thread Validity_Count
2138
2139 Ada_Allocs_Bytes : Byte_Count;
2140 -- safe thread pool Allocated
2141
2142 Ada_Allocs_Chunks : Byte_Count;
2143 -- safe thread pool Alloc_Count
2144
2145 Ada_Free_Chunks : Byte_Count;
2146 -- safe thread pool Free_Count
2147
2148 -- Start of processing for Dump
2149
2150 begin
2151 declare
2152 Lock : Scope_Lock;
2153 pragma Unreferenced (Lock);
2154 begin
2155 Total_Freed :=
2156 Pool.Logically_Deallocated + Pool.Physically_Deallocated;
2157 Traceback_Elements_Allocated := Traceback_Count;
2158 Validity_Elements_Allocated := Validity_Count;
2159 Ada_Allocs_Bytes := Pool.Allocated;
2160 Ada_Allocs_Chunks := Pool.Alloc_Count;
2161 Ada_Free_Chunks := Pool.Free_Count;
2162 end;
2163
2164 Put_Line
2165 ("Traceback elements allocated: " & Traceback_Elements_Allocated'Img);
2166 Put_Line
2167 ("Validity elements allocated: " & Validity_Elements_Allocated'Img);
2168 Put_Line ("");
2169
2170 Put_Line ("Ada Allocs:" & Ada_Allocs_Bytes'Img
2171 & " bytes in" & Ada_Allocs_Chunks'Img & " chunks");
2172 Put_Line ("Ada Free:" & Total_Freed'Img & " bytes in" &
2173 Ada_Free_Chunks'Img
2174 & " chunks");
2175 Put_Line ("Ada Current watermark: "
2176 & Byte_Count'Image (Pool.Current_Water_Mark)
2177 & " in" & Byte_Count'Image (Ada_Allocs_Chunks -
2178 Ada_Free_Chunks) & " chunks");
2179 Put_Line ("Ada High watermark: " & Pool.High_Water_Mark'Img);
2180
2181 case Report is
2182 when All_Reports =>
2183 for Sort in Report_Type loop
2184 if Sort /= All_Reports then
2185 Do_Report (Sort);
2186 end if;
2187 end loop;
2188
2189 when others =>
2190 Do_Report (Report);
2191 end case;
2192 end Dump;
2193
2194 -----------------
2195 -- Dump_Stdout --
2196 -----------------
2197
2198 procedure Dump_Stdout
2199 (Pool : Debug_Pool;
2200 Size : Positive;
2201 Report : Report_Type := All_Reports)
2202 is
2203 procedure Internal is new Dump
2204 (Put_Line => Stdout_Put_Line,
2205 Put => Stdout_Put);
2206
2207 -- Start of processing for Dump_Stdout
2208
2209 begin
2210 Internal (Pool, Size, Report);
2211 end Dump_Stdout;
2212
2213 -----------
2214 -- Reset --
2215 -----------
2216
2217 procedure Reset is
2218 Elem : Traceback_Htable_Elem_Ptr;
2219 Lock : Scope_Lock;
2220 pragma Unreferenced (Lock);
2221 begin
2222 Elem := Backtrace_Htable.Get_First;
2223 while Elem /= null loop
2224 Elem.Count := 0;
2225 Elem.Frees := 0;
2226 Elem.Total := 0;
2227 Elem.Total_Frees := 0;
2228 Elem := Backtrace_Htable.Get_Next;
2229 end loop;
2230 end Reset;
2231
2232 ------------------
2233 -- Storage_Size --
2234 ------------------
2235
2236 function Storage_Size (Pool : Debug_Pool) return Storage_Count is
2237 pragma Unreferenced (Pool);
2238 begin
2239 return Storage_Count'Last;
2240 end Storage_Size;
2241
2242 ---------------------
2243 -- High_Water_Mark --
2244 ---------------------
2245
2246 function High_Water_Mark (Pool : Debug_Pool) return Byte_Count is
2247 Lock : Scope_Lock;
2248 pragma Unreferenced (Lock);
2249 begin
2250 return Pool.High_Water;
2251 end High_Water_Mark;
2252
2253 ------------------------
2254 -- Current_Water_Mark --
2255 ------------------------
2256
2257 function Current_Water_Mark (Pool : Debug_Pool) return Byte_Count is
2258 Lock : Scope_Lock;
2259 pragma Unreferenced (Lock);
2260 begin
2261 return Pool.Allocated - Pool.Logically_Deallocated -
2262 Pool.Physically_Deallocated;
2263 end Current_Water_Mark;
2264
2265 ------------------------------
2266 -- System_Memory_Debug_Pool --
2267 ------------------------------
2268
2269 procedure System_Memory_Debug_Pool
2270 (Has_Unhandled_Memory : Boolean := True)
2271 is
2272 Lock : Scope_Lock;
2273 pragma Unreferenced (Lock);
2274 begin
2275 System_Memory_Debug_Pool_Enabled := True;
2276 Allow_Unhandled_Memory := Has_Unhandled_Memory;
2277 end System_Memory_Debug_Pool;
2278
2279 ---------------
2280 -- Configure --
2281 ---------------
2282
2283 procedure Configure
2284 (Pool : in out Debug_Pool;
2285 Stack_Trace_Depth : Natural := Default_Stack_Trace_Depth;
2286 Maximum_Logically_Freed_Memory : SSC := Default_Max_Freed;
2287 Minimum_To_Free : SSC := Default_Min_Freed;
2288 Reset_Content_On_Free : Boolean := Default_Reset_Content;
2289 Raise_Exceptions : Boolean := Default_Raise_Exceptions;
2290 Advanced_Scanning : Boolean := Default_Advanced_Scanning;
2291 Errors_To_Stdout : Boolean := Default_Errors_To_Stdout;
2292 Low_Level_Traces : Boolean := Default_Low_Level_Traces)
2293 is
2294 Lock : Scope_Lock;
2295 pragma Unreferenced (Lock);
2296 begin
2297 Pool.Stack_Trace_Depth := Stack_Trace_Depth;
2298 Pool.Maximum_Logically_Freed_Memory := Maximum_Logically_Freed_Memory;
2299 Pool.Reset_Content_On_Free := Reset_Content_On_Free;
2300 Pool.Raise_Exceptions := Raise_Exceptions;
2301 Pool.Minimum_To_Free := Minimum_To_Free;
2302 Pool.Advanced_Scanning := Advanced_Scanning;
2303 Pool.Errors_To_Stdout := Errors_To_Stdout;
2304 Pool.Low_Level_Traces := Low_Level_Traces;
2305 end Configure;
2306
2307 ----------------
2308 -- Print_Pool --
2309 ----------------
2310
2311 procedure Print_Pool (A : System.Address) is
2312 Storage : constant Address := A;
2313 Valid : constant Boolean := Is_Valid (Storage);
2314 Header : Allocation_Header_Access;
2315
2316 begin
2317 -- We might get Null_Address if the call from gdb was done incorrectly.
2318 -- For instance, doing a "print_pool(my_var)" passes 0x0, instead of
2319 -- passing the value of my_var.
2320
2321 if A = System.Null_Address then
2322 Put_Line
2323 (Standard_Output, "Memory not under control of the storage pool");
2324 return;
2325 end if;
2326
2327 if not Valid then
2328 Put_Line
2329 (Standard_Output, "Memory not under control of the storage pool");
2330
2331 else
2332 Header := Header_Of (Storage);
2333 Print_Address (Standard_Output, A);
2334 Put_Line (Standard_Output, " allocated at:");
2335 Print_Traceback (Standard_Output, "", Header.Alloc_Traceback);
2336
2337 if To_Traceback (Header.Dealloc_Traceback) /= null then
2338 Print_Address (Standard_Output, A);
2339 Put_Line (Standard_Output,
2340 " logically freed memory, deallocated at:");
2341 Print_Traceback (Standard_Output, "",
2342 To_Traceback (Header.Dealloc_Traceback));
2343 end if;
2344 end if;
2345 end Print_Pool;
2346
2347 -----------------------
2348 -- Print_Info_Stdout --
2349 -----------------------
2350
2351 procedure Print_Info_Stdout
2352 (Pool : Debug_Pool;
2353 Cumulate : Boolean := False;
2354 Display_Slots : Boolean := False;
2355 Display_Leaks : Boolean := False)
2356 is
2357 procedure Internal is new Print_Info
2358 (Put_Line => Stdout_Put_Line,
2359 Put => Stdout_Put);
2360
2361 -- Start of processing for Print_Info_Stdout
2362
2363 begin
2364 Internal (Pool, Cumulate, Display_Slots, Display_Leaks);
2365 end Print_Info_Stdout;
2366
2367 ------------------
2368 -- Dump_Gnatmem --
2369 ------------------
2370
2371 procedure Dump_Gnatmem (Pool : Debug_Pool; File_Name : String) is
2372 type File_Ptr is new System.Address;
2373
2374 function fopen (Path : String; Mode : String) return File_Ptr;
2375 pragma Import (C, fopen);
2376
2377 procedure fwrite
2378 (Ptr : System.Address;
2379 Size : size_t;
2380 Nmemb : size_t;
2381 Stream : File_Ptr);
2382
2383 procedure fwrite
2384 (Str : String;
2385 Size : size_t;
2386 Nmemb : size_t;
2387 Stream : File_Ptr);
2388 pragma Import (C, fwrite);
2389
2390 procedure fputc (C : Integer; Stream : File_Ptr);
2391 pragma Import (C, fputc);
2392
2393 procedure fclose (Stream : File_Ptr);
2394 pragma Import (C, fclose);
2395
2396 Address_Size : constant size_t :=
2397 System.Address'Max_Size_In_Storage_Elements;
2398 -- Size in bytes of a pointer
2399
2400 File : File_Ptr;
2401 Current : System.Address;
2402 Header : Allocation_Header_Access;
2403 Actual_Size : size_t;
2404 Num_Calls : Integer;
2405 Tracebk : Tracebacks_Array_Access;
2406 Dummy_Time : Duration := 1.0;
2407
2408 begin
2409 File := fopen (File_Name & ASCII.NUL, "wb" & ASCII.NUL);
2410 fwrite ("GMEM DUMP" & ASCII.LF, 10, 1, File);
2411
2412 fwrite
2413 (Ptr => Dummy_Time'Address,
2414 Size => Duration'Max_Size_In_Storage_Elements,
2415 Nmemb => 1,
2416 Stream => File);
2417
2418 -- List of not deallocated blocks (see Print_Info)
2419
2420 Current := Pool.First_Used_Block;
2421 while Current /= System.Null_Address loop
2422 Header := Header_Of (Current);
2423
2424 Actual_Size := size_t (Header.Block_Size);
2425
2426 if Header.Alloc_Traceback /= null then
2427 Tracebk := Header.Alloc_Traceback.Traceback;
2428 Num_Calls := Tracebk'Length;
2429
2430 -- (Code taken from memtrack.adb in GNAT's sources)
2431
2432 -- Logs allocation call using the format:
2433
2434 -- 'A' <mem addr> <size chunk> <len backtrace> <addr1> ... <addrn>
2435
2436 fputc (Character'Pos ('A'), File);
2437 fwrite (Current'Address, Address_Size, 1, File);
2438
2439 fwrite
2440 (Ptr => Actual_Size'Address,
2441 Size => size_t'Max_Size_In_Storage_Elements,
2442 Nmemb => 1,
2443 Stream => File);
2444
2445 fwrite
2446 (Ptr => Dummy_Time'Address,
2447 Size => Duration'Max_Size_In_Storage_Elements,
2448 Nmemb => 1,
2449 Stream => File);
2450
2451 fwrite
2452 (Ptr => Num_Calls'Address,
2453 Size => Integer'Max_Size_In_Storage_Elements,
2454 Nmemb => 1,
2455 Stream => File);
2456
2457 for J in Tracebk'First .. Tracebk'First + Num_Calls - 1 loop
2458 declare
2459 Ptr : System.Address := PC_For (Tracebk (J));
2460 begin
2461 fwrite (Ptr'Address, Address_Size, 1, File);
2462 end;
2463 end loop;
2464 end if;
2465
2466 Current := Header.Next;
2467 end loop;
2468
2469 fclose (File);
2470 end Dump_Gnatmem;
2471
2472 ----------------
2473 -- Stdout_Put --
2474 ----------------
2475
2476 procedure Stdout_Put (S : String) is
2477 begin
2478 Put (Standard_Output, S);
2479 end Stdout_Put;
2480
2481 ---------------------
2482 -- Stdout_Put_Line --
2483 ---------------------
2484
2485 procedure Stdout_Put_Line (S : String) is
2486 begin
2487 Put_Line (Standard_Output, S);
2488 end Stdout_Put_Line;
2489
2490 end GNAT.Debug_Pools;