1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
5 -- G N A T . D E B U G _ P O O L S --
9 -- Copyright (C) 1992-2024, Free Software Foundation, Inc. --
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. --
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. --
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/>. --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
30 ------------------------------------------------------------------------------
32 -- This packages provides a special implementation of the Ada 95 storage pools
34 -- The goal of this debug pool is to detect incorrect uses of memory
35 -- (multiple deallocations, access to invalid memory,...). Errors are reported
36 -- in one of two ways: either by immediately raising an exception, or by
37 -- printing a message on standard output or standard error.
39 -- You need to instrument your code to use this package: for each access type
40 -- you want to monitor, you need to add a clause similar to:
42 -- type Integer_Access is access Integer;
43 -- for Integer_Access'Storage_Pool use Pool;
45 -- where Pool is a tagged object declared with
47 -- Pool : GNAT.Debug_Pools.Debug_Pool;
49 -- This package was designed to be as efficient as possible, but still has an
50 -- impact on the performance of your code, which depends on the number of
51 -- allocations, deallocations and, somewhat less, dereferences that your
52 -- application performs.
54 -- For each faulty memory use, this debug pool will print several lines
55 -- of information, including things like the location where the memory
56 -- was initially allocated, the location where it was freed etc.
58 -- Physical allocations and deallocations are done through the usual system
59 -- calls. However, in order to provide proper checks, the debug pool will not
60 -- release the memory immediately. It keeps released memory around (the amount
61 -- kept around is configurable) so that it can distinguish between memory that
62 -- has not been allocated and memory that has been allocated but freed. This
63 -- also means that this memory cannot be reallocated, preventing what would
64 -- otherwise be a false indication that freed memory is now allocated.
66 -- In addition, this package presents several subprograms that help analyze
67 -- the behavior of your program, by reporting memory leaks, the total amount
68 -- of memory that was allocated. The pool is also designed to work correctly
69 -- in conjunction with gnatmem.
71 -- Finally, a subprogram Print_Pool is provided for use from the debugger
76 -- Current limitation of this debug pool: if you use this debug pool for a
77 -- general access type ("access all"), the pool might report invalid
78 -- dereferences if the access object is pointing to another object on the
79 -- stack which was not allocated through a call to "new".
81 -- This debug pool will respect all alignments specified in your code, but
82 -- it does that by aligning all objects using Standard'Maximum_Alignment.
83 -- This allows faster checks, and limits the performance impact of using
86 with System
; use System
;
87 with System
.Storage_Elements
; use System
.Storage_Elements
;
88 with System
.Checked_Pools
;
90 package GNAT
.Debug_Pools
is
92 type Debug_Pool
is new System
.Checked_Pools
.Checked_Pool
with private;
95 subtype SSC
is System
.Storage_Elements
.Storage_Count
;
97 Default_Max_Freed
: constant SSC
:= 50_000_000
;
98 Default_Stack_Trace_Depth
: constant Natural := 20;
99 Default_Reset_Content
: constant Boolean := False;
100 Default_Raise_Exceptions
: constant Boolean := True;
101 Default_Advanced_Scanning
: constant Boolean := False;
102 Default_Min_Freed
: constant SSC
:= 0;
103 Default_Errors_To_Stdout
: constant Boolean := True;
104 Default_Low_Level_Traces
: constant Boolean := False;
105 -- The above values are constants used for the parameters to Configure
106 -- if not overridden in the call. See description of Configure for full
107 -- details on these parameters. If these defaults are not satisfactory,
108 -- then you need to call Configure to change the default values.
111 (Pool
: in out Debug_Pool
;
112 Stack_Trace_Depth
: Natural := Default_Stack_Trace_Depth
;
113 Maximum_Logically_Freed_Memory
: SSC
:= Default_Max_Freed
;
114 Minimum_To_Free
: SSC
:= Default_Min_Freed
;
115 Reset_Content_On_Free
: Boolean := Default_Reset_Content
;
116 Raise_Exceptions
: Boolean := Default_Raise_Exceptions
;
117 Advanced_Scanning
: Boolean := Default_Advanced_Scanning
;
118 Errors_To_Stdout
: Boolean := Default_Errors_To_Stdout
;
119 Low_Level_Traces
: Boolean := Default_Low_Level_Traces
);
120 -- Subprogram used to configure the debug pool.
122 -- Stack_Trace_Depth. This parameter controls the maximum depth of stack
123 -- traces that are output to indicate locations of actions for error
124 -- conditions such as bad allocations. If set to zero, the debug pool
125 -- will not try to compute backtraces. This is more efficient but gives
126 -- less information on problem locations (and in particular, this
127 -- disables the tracking of the biggest users of memory).
129 -- Maximum_Logically_Freed_Memory: maximum amount of memory (bytes)
130 -- that should be kept before starting to physically deallocate some.
131 -- This value should be non-zero, since having memory that is logically
132 -- but not physically freed helps to detect invalid memory accesses.
134 -- Minimum_To_Free is the minimum amount of memory that should be freed
135 -- every time the pool starts physically releasing memory. The algorithm
136 -- to compute which block should be physically released needs some
137 -- expensive initialization (see Advanced_Scanning below), and this
138 -- parameter can be used to limit the performance impact by ensuring
139 -- that a reasonable amount of memory is freed each time. Even in the
140 -- advanced scanning mode, marked blocks may be released to match this
141 -- Minimum_To_Free parameter.
143 -- Reset_Content_On_Free: If true, then the contents of the freed memory
144 -- is reset to the pattern 16#DEADBEEF#, following an old IBM convention.
145 -- This helps in detecting invalid memory references from the debugger.
147 -- Raise_Exceptions: If true, the exceptions below will be raised every
148 -- time an error is detected. If you set this to False, then the action
149 -- is to generate output on standard error or standard output, depending
150 -- on Errors_To_Stdout, noting the errors, but to
151 -- keep running if possible (of course if storage is badly damaged, this
152 -- attempt may fail. This helps to detect more than one error in a run.
154 -- Advanced_Scanning: If true, the pool will check the contents of all
155 -- allocated blocks before physically releasing memory. Any possible
156 -- reference to a logically free block will prevent its deallocation.
157 -- Note that this algorithm is approximate, and it is recommended
158 -- that you set Minimum_To_Free to a non-zero value to save time.
160 -- Errors_To_Stdout: Errors messages will be displayed on stdout if
161 -- this parameter is True, or to stderr otherwise.
163 -- Low_Level_Traces: Traces all allocation and deallocations on the
164 -- stream specified by Errors_To_Stdout. This can be used for
165 -- post-processing by your own application, or to debug the
166 -- debug_pool itself. The output indicates the size of the allocated
167 -- block both as requested by the application and as physically
168 -- allocated to fit the additional information needed by the debug
171 -- All instantiations of this pool use the same internal tables. However,
172 -- they do not store the same amount of information for the tracebacks,
173 -- and they have different counters for maximum logically freed memory.
175 Accessing_Not_Allocated_Storage
: exception;
176 -- Exception raised if Raise_Exception is True, and an attempt is made
177 -- to access storage that was never allocated.
179 Accessing_Deallocated_Storage
: exception;
180 -- Exception raised if Raise_Exception is True, and an attempt is made
181 -- to access storage that was allocated but has been deallocated.
183 Freeing_Not_Allocated_Storage
: exception;
184 -- Exception raised if Raise_Exception is True, and an attempt is made
185 -- to free storage that had not been previously allocated.
187 Freeing_Deallocated_Storage
: exception;
188 -- Exception raised if Raise_Exception is True, and an attempt is made
189 -- to free storage that had already been freed.
191 -- Note on the above exceptions. The distinction between not allocated
192 -- and deallocated storage is not guaranteed to be accurate in the case
193 -- where storage is allocated, and then physically freed. Larger values
194 -- of the parameter Maximum_Logically_Freed_Memory will help to guarantee
195 -- that this distinction is made more accurately.
198 with procedure Put_Line
(S
: String) is <>;
199 with procedure Put
(S
: String) is <>;
202 Cumulate
: Boolean := False;
203 Display_Slots
: Boolean := False;
204 Display_Leaks
: Boolean := False);
205 -- Print out information about the High Water Mark, the current and
206 -- total number of bytes allocated and the total number of bytes
209 -- If Display_Slots is true, this subprogram prints a list of all the
210 -- locations in the application that have done at least one allocation or
211 -- deallocation. The result might be used to detect places in the program
212 -- where lots of allocations are taking place. This output is not in any
215 -- If Cumulate if True, then each stack trace will display the number of
216 -- allocations that were done either directly, or by the subprograms called
217 -- at that location (e.g: if there were two physical allocations at a->b->c
218 -- and a->b->d, then a->b would be reported as performing two allocations).
220 -- If Display_Leaks is true, then each block that has not been deallocated
221 -- (often called a "memory leak") will be listed, along with the traceback
222 -- showing where it was allocated. Not that no grouping of the blocks is
223 -- done, you should use the Dump_Gnatmem procedure below in conjunction
224 -- with the gnatmem utility.
226 procedure Print_Info_Stdout
228 Cumulate
: Boolean := False;
229 Display_Slots
: Boolean := False;
230 Display_Leaks
: Boolean := False);
231 -- Standard instantiation of Print_Info to print on standard_output. More
232 -- convenient to use where this is the intended location, and in particular
233 -- easier to use from the debugger.
235 procedure Dump_Gnatmem
(Pool
: Debug_Pool
; File_Name
: String);
236 -- Create an external file on the disk, which can be processed by gnatmem
237 -- to display the location of memory leaks.
239 -- This provides a nicer output that Print_Info above, and groups similar
240 -- stack traces together. This also provides an easy way to save the memory
241 -- status of your program for post-mortem analysis.
243 -- To use this file, use the following command line:
244 -- gnatmem 5 -i <File_Name> <Executable_Name>
245 -- If you want all the stack traces to be displayed with 5 levels.
247 procedure Print_Pool
(A
: System
.Address
);
248 pragma Export
(C
, Print_Pool
, "print_pool");
249 -- This subprogram is meant to be used from a debugger. Given an address in
250 -- memory, it will print on standard output the known information about
251 -- this address (provided, of course, the matching pointer is handled by
254 -- The information includes the stacktrace for the allocation or
255 -- deallocation of that memory chunk, its current status (allocated or
256 -- logically freed), etc.
267 Allocations_Count
=> 2,
268 Sort_Total_Allocs
=> 3,
272 with procedure Put_Line
(S
: String) is <>;
273 with procedure Put
(S
: String) is <>;
277 Report
: Report_Type
:= All_Reports
);
278 -- Dump information about memory usage.
279 -- Size is the number of the biggest memory users we want to show
280 -- (requires that the Debug_Pool has been configured with Stack_Trace_Depth
281 -- greater than zero). Also, for efficiency reasons, tracebacks with
282 -- a memory allocation below 1_000 bytes are not shown in the "biggest
283 -- memory users" part of the report.
284 -- Report indicates which sorting order is used in the report.
286 procedure Dump_Stdout
289 Report
: Report_Type
:= All_Reports
);
290 -- Standard instantiation of Dump to print on standard_output. More
291 -- convenient to use where this is the intended location, and in particular
292 -- easier to use from the debugger.
295 -- Reset all internal data. This is in general not needed, unless you want
296 -- to know what memory is used by specific parts of your application
299 (Storage_Address
: Address
;
300 Size_In_Storage_Elements
: out Storage_Count
;
301 Valid
: out Boolean);
302 -- Set Valid if Storage_Address is the address of a chunk of memory
303 -- currently allocated by any pool.
304 -- If Valid is True, Size_In_Storage_Elements is set to the size of this
307 type Byte_Count
is mod 2 ** Long_Long_Integer'Size;
308 -- Type used for maintaining byte counts, needs to be large enough to
309 -- to accommodate counts allowing for repeated use of the same memory.
311 function High_Water_Mark
312 (Pool
: Debug_Pool
) return Byte_Count
;
313 -- Return the highest size of the memory allocated by the pool.
314 -- Memory used internally by the pool is not taken into account.
316 function Current_Water_Mark
317 (Pool
: Debug_Pool
) return Byte_Count
;
318 -- Return the size of the memory currently allocated by the pool.
319 -- Memory used internally by the pool is not taken into account.
321 procedure System_Memory_Debug_Pool
322 (Has_Unhandled_Memory
: Boolean := True);
323 -- Let the package know the System.Memory is using it.
324 -- If Has_Unhandled_Memory is true, some deallocation can be done for
325 -- memory not allocated with Allocate.
328 -- The following are the standard primitive subprograms for a pool
331 (Pool
: in out Debug_Pool
;
332 Storage_Address
: out Address
;
333 Size_In_Storage_Elements
: Storage_Count
;
334 Alignment
: Storage_Count
);
335 -- Allocate a new chunk of memory, and set it up so that the debug pool
336 -- can check accesses to its data, and report incorrect access later on.
337 -- The parameters have the same semantics as defined in the ARM95.
340 (Pool
: in out Debug_Pool
;
341 Storage_Address
: Address
;
342 Size_In_Storage_Elements
: Storage_Count
;
343 Alignment
: Storage_Count
);
344 -- Mark a block of memory as invalid. It might not be physically removed
345 -- immediately, depending on the setup of the debug pool, so that checks
346 -- are still possible. The parameters have the same semantics as defined
349 function Storage_Size
(Pool
: Debug_Pool
) return SSC
;
350 -- Return the maximal size of data that can be allocated through Pool.
351 -- Since Pool uses the malloc() system call, all the memory is accessible
354 procedure Dereference
355 (Pool
: in out Debug_Pool
;
356 Storage_Address
: System
.Address
;
357 Size_In_Storage_Elements
: Storage_Count
;
358 Alignment
: Storage_Count
);
359 -- Check whether a dereference statement is valid, i.e. whether the pointer
360 -- was allocated through Pool. As documented above, errors will be
361 -- reported either by a special error message or an exception, depending
362 -- on the setup of the storage pool.
363 -- The parameters have the same semantics as defined in the ARM95.
365 type Debug_Pool
is new System
.Checked_Pools
.Checked_Pool
with record
366 Stack_Trace_Depth
: Natural := Default_Stack_Trace_Depth
;
367 Maximum_Logically_Freed_Memory
: SSC
:= Default_Max_Freed
;
368 Reset_Content_On_Free
: Boolean := Default_Reset_Content
;
369 Raise_Exceptions
: Boolean := Default_Raise_Exceptions
;
370 Minimum_To_Free
: SSC
:= Default_Min_Freed
;
371 Advanced_Scanning
: Boolean := Default_Advanced_Scanning
;
372 Errors_To_Stdout
: Boolean := Default_Errors_To_Stdout
;
373 Low_Level_Traces
: Boolean := Default_Low_Level_Traces
;
375 Alloc_Count
: Byte_Count
:= 0;
376 -- Total number of allocation
378 Free_Count
: Byte_Count
:= 0;
379 -- Total number of deallocation
381 Allocated
: Byte_Count
:= 0;
382 -- Total number of bytes allocated in this pool
384 Logically_Deallocated
: Byte_Count
:= 0;
385 -- Total number of bytes logically deallocated in this pool. This is the
386 -- memory that the application has released, but that the pool has not
387 -- yet physically released through a call to free(), to detect later
388 -- accessed to deallocated memory.
390 Physically_Deallocated
: Byte_Count
:= 0;
391 -- Total number of bytes that were free()-ed
393 Marked_Blocks_Deallocated
: Boolean := False;
394 -- Set to true if some mark blocks had to be deallocated in the advanced
395 -- scanning scheme. Since this is potentially dangerous, this is
396 -- reported to the user, who might want to rerun his program with a
397 -- lower Minimum_To_Free value.
399 High_Water
: Byte_Count
:= 0;
400 -- Maximum of Allocated - Logically_Deallocated - Physically_Deallocated
402 First_Free_Block
: System
.Address
:= System
.Null_Address
;
403 Last_Free_Block
: System
.Address
:= System
.Null_Address
;
404 -- Pointers to the first and last logically freed blocks
406 First_Used_Block
: System
.Address
:= System
.Null_Address
;
407 -- Pointer to the list of currently allocated blocks. This list is
408 -- used to list the memory leaks in the application on exit, as well as
409 -- for the advanced freeing algorithms that needs to traverse all these
410 -- blocks to find possible references to the block being physically
414 end GNAT
.Debug_Pools
;