blob: b7f0a4a59076c96a0e5f7474a28a42ae11e850d7 [file] [log] [blame]
sewardjde4a1d02002-03-22 01:27:54 +00001
2/*--------------------------------------------------------------------*/
3/*--- An implementation of malloc/free which doesn't use sbrk. ---*/
njn717cde52005-05-10 02:47:21 +00004/*--- m_mallocfree.c ---*/
sewardjde4a1d02002-03-22 01:27:54 +00005/*--------------------------------------------------------------------*/
6
7/*
njnb9c427c2004-12-01 14:14:42 +00008 This file is part of Valgrind, a dynamic binary instrumentation
9 framework.
sewardjde4a1d02002-03-22 01:27:54 +000010
sewardj03f8d3f2012-08-05 15:46:46 +000011 Copyright (C) 2000-2012 Julian Seward
sewardjde4a1d02002-03-22 01:27:54 +000012 jseward@acm.org
sewardjde4a1d02002-03-22 01:27:54 +000013
14 This program is free software; you can redistribute it and/or
15 modify it under the terms of the GNU General Public License as
16 published by the Free Software Foundation; either version 2 of the
17 License, or (at your option) any later version.
18
19 This program is distributed in the hope that it will be useful, but
20 WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 General Public License for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
27 02111-1307, USA.
28
njn25e49d8e72002-09-23 09:36:25 +000029 The GNU General Public License is contained in the file COPYING.
sewardjde4a1d02002-03-22 01:27:54 +000030*/
31
njnc7561b92005-06-19 01:24:32 +000032#include "pub_core_basics.h"
sewardj4cfea4f2006-10-14 19:26:10 +000033#include "pub_core_vki.h"
sewardj45f4e7c2005-09-27 19:20:21 +000034#include "pub_core_debuglog.h"
njn97405b22005-06-02 03:39:33 +000035#include "pub_core_libcbase.h"
sewardj45f4e7c2005-09-27 19:20:21 +000036#include "pub_core_aspacemgr.h"
njn132bfcc2005-06-04 19:16:06 +000037#include "pub_core_libcassert.h"
njn36a20fa2005-06-03 03:08:39 +000038#include "pub_core_libcprint.h"
njnaf1d7df2005-06-11 01:31:52 +000039#include "pub_core_mallocfree.h"
njn20242342005-05-16 23:31:24 +000040#include "pub_core_options.h"
sewardj6c591e12011-04-11 16:17:51 +000041#include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy
njn32397c02007-11-10 04:08:08 +000042#include "pub_core_threadstate.h" // For VG_INVALID_THREADID
sewardjd043de92011-09-26 11:28:20 +000043#include "pub_core_transtab.h"
njnfc51f8d2005-06-21 03:20:17 +000044#include "pub_core_tooliface.h"
sewardj55f9d1a2005-04-25 11:11:44 +000045
philippe72faf102012-03-11 22:24:03 +000046#include "pub_tool_inner.h"
47#if defined(ENABLE_INNER_CLIENT_REQUEST)
48#include "memcheck/memcheck.h"
49#endif
sewardjde4a1d02002-03-22 01:27:54 +000050
sewardj0b3fd2d2007-08-21 10:55:26 +000051// #define DEBUG_MALLOC // turn on heavyweight debugging machinery
52// #define VERBOSE_MALLOC // make verbose, esp. in debugging machinery
nethercote2d5b8162004-08-11 09:40:52 +000053
bart545380e2008-04-21 17:28:50 +000054/* Number and total size of blocks in free queue. Used by mallinfo(). */
55Long VG_(free_queue_volume) = 0;
56Long VG_(free_queue_length) = 0;
57
sewardj9c606bd2008-09-18 18:12:50 +000058static void cc_analyse_alloc_arena ( ArenaId aid ); /* fwds */
59
nethercote2d5b8162004-08-11 09:40:52 +000060/*------------------------------------------------------------*/
61/*--- Main types ---*/
62/*------------------------------------------------------------*/
63
sewardjc1ac9772007-08-20 22:57:56 +000064#define N_MALLOC_LISTS 112 // do not change this
nethercote2d5b8162004-08-11 09:40:52 +000065
nethercote7ac7f7b2004-11-02 12:36:02 +000066// The amount you can ask for is limited only by sizeof(SizeT)...
67#define MAX_PSZB (~((SizeT)0x0))
nethercote2d5b8162004-08-11 09:40:52 +000068
sewardj0b3fd2d2007-08-21 10:55:26 +000069// Each arena has a sorted array of superblocks, which expands
70// dynamically. This is its initial size.
71#define SBLOCKS_SIZE_INITIAL 50
72
nethercote2d5b8162004-08-11 09:40:52 +000073typedef UChar UByte;
74
njn8d3f8452005-07-20 04:12:41 +000075/* Layout of an in-use block:
nethercote2d5b8162004-08-11 09:40:52 +000076
njn341a6642009-05-24 23:36:50 +000077 cost center (OPTIONAL) (VG_MIN_MALLOC_SZB bytes, only when h-p enabled)
njn8d3f8452005-07-20 04:12:41 +000078 this block total szB (sizeof(SizeT) bytes)
njn7ce83112005-08-24 22:38:00 +000079 red zone bytes (depends on Arena.rz_szB, but >= sizeof(void*))
njn8d3f8452005-07-20 04:12:41 +000080 (payload bytes)
njn7ce83112005-08-24 22:38:00 +000081 red zone bytes (depends on Arena.rz_szB, but >= sizeof(void*))
njn8d3f8452005-07-20 04:12:41 +000082 this block total szB (sizeof(SizeT) bytes)
nethercote2d5b8162004-08-11 09:40:52 +000083
njn8d3f8452005-07-20 04:12:41 +000084 Layout of a block on the free list:
nethercote2d5b8162004-08-11 09:40:52 +000085
njn341a6642009-05-24 23:36:50 +000086 cost center (OPTIONAL) (VG_MIN_MALLOC_SZB bytes, only when h-p enabled)
njn8d3f8452005-07-20 04:12:41 +000087 this block total szB (sizeof(SizeT) bytes)
88 freelist previous ptr (sizeof(void*) bytes)
89 excess red zone bytes (if Arena.rz_szB > sizeof(void*))
90 (payload bytes)
91 excess red zone bytes (if Arena.rz_szB > sizeof(void*))
92 freelist next ptr (sizeof(void*) bytes)
93 this block total szB (sizeof(SizeT) bytes)
nethercote2d5b8162004-08-11 09:40:52 +000094
njn8d3f8452005-07-20 04:12:41 +000095 Total size in bytes (bszB) and payload size in bytes (pszB)
96 are related by:
nethercote2d5b8162004-08-11 09:40:52 +000097
sewardj94c8eb42008-09-19 20:13:39 +000098 bszB == pszB + 2*sizeof(SizeT) + 2*a->rz_szB
99
100 when heap profiling is not enabled, and
101
njn341a6642009-05-24 23:36:50 +0000102 bszB == pszB + 2*sizeof(SizeT) + 2*a->rz_szB + VG_MIN_MALLOC_SZB
njn8d3f8452005-07-20 04:12:41 +0000103
sewardj94c8eb42008-09-19 20:13:39 +0000104 when it is enabled. It follows that the minimum overhead per heap
105 block for arenas used by the core is:
106
107 32-bit platforms: 2*4 + 2*4 == 16 bytes
108 64-bit platforms: 2*8 + 2*8 == 32 bytes
109
110 when heap profiling is not enabled, and
njna527a492005-12-16 17:06:37 +0000111
njn341a6642009-05-24 23:36:50 +0000112 32-bit platforms: 2*4 + 2*4 + 8 == 24 bytes
113 64-bit platforms: 2*8 + 2*8 + 16 == 48 bytes
njna527a492005-12-16 17:06:37 +0000114
sewardj94c8eb42008-09-19 20:13:39 +0000115 when it is enabled. In all cases, extra overhead may be incurred
116 when rounding the payload size up to VG_MIN_MALLOC_SZB.
njna527a492005-12-16 17:06:37 +0000117
njn8d3f8452005-07-20 04:12:41 +0000118 Furthermore, both size fields in the block have their least-significant
119 bit set if the block is not in use, and unset if it is in use.
120 (The bottom 3 or so bits are always free for this because of alignment.)
121 A block size of zero is not possible, because a block always has at
122 least two SizeTs and two pointers of overhead.
123
124 Nb: All Block payloads must be VG_MIN_MALLOC_SZB-aligned. This is
125 achieved by ensuring that Superblocks are VG_MIN_MALLOC_SZB-aligned
126 (see newSuperblock() for how), and that the lengths of the following
127 things are a multiple of VG_MIN_MALLOC_SZB:
128 - Superblock admin section lengths (due to elastic padding)
129 - Block admin section (low and high) lengths (due to elastic redzones)
130 - Block payload lengths (due to req_pszB rounding up)
sewardj9c606bd2008-09-18 18:12:50 +0000131
132 The heap-profile cost-center field is 8 bytes even on 32 bit
133 platforms. This is so as to keep the payload field 8-aligned. On
134 a 64-bit platform, this cc-field contains a pointer to a const
135 HChar*, which is the cost center name. On 32-bit platforms, the
136 pointer lives in the lower-addressed half of the field, regardless
137 of the endianness of the host.
nethercote2d5b8162004-08-11 09:40:52 +0000138*/
139typedef
140 struct {
141 // No fields are actually used in this struct, because a Block has
njn37517e82005-05-25 15:52:39 +0000142 // many variable sized fields and so can't be accessed
nethercote2d5b8162004-08-11 09:40:52 +0000143 // meaningfully with normal fields. So we use access functions all
144 // the time. This struct gives us a type to use, though. Also, we
145 // make sizeof(Block) 1 byte so that we can do arithmetic with the
146 // Block* type in increments of 1!
147 UByte dummy;
148 }
149 Block;
150
151// A superblock. 'padding' is never used, it just ensures that if the
152// entire Superblock is aligned to VG_MIN_MALLOC_SZB, then payload_bytes[]
153// will be too. It can add small amounts of padding unnecessarily -- eg.
154// 8-bytes on 32-bit machines with an 8-byte VG_MIN_MALLOC_SZB -- because
155// it's too hard to make a constant expression that works perfectly in all
156// cases.
sewardjd043de92011-09-26 11:28:20 +0000157// 'unsplittable' is set to NULL if superblock can be splitted, otherwise
158// it is set to the address of the superblock. An unsplittable superblock
159// will contain only one allocated block. An unsplittable superblock will
160// be unmapped when its (only) allocated block is freed.
161// The free space at the end of an unsplittable superblock is not used to
162// make a free block. Note that this means that an unsplittable superblock can
sewardjd8b93462011-09-10 10:17:35 +0000163// have up to slightly less than 1 page of unused bytes at the end of the
164// superblock.
sewardjd043de92011-09-26 11:28:20 +0000165// 'unsplittable' is used to avoid quadratic memory usage for linear
166// reallocation of big structures
167// (see http://bugs.kde.org/show_bug.cgi?id=250101).
168// ??? unsplittable replaces 'void *padding2'. Choosed this
sewardjd8b93462011-09-10 10:17:35 +0000169// ??? to avoid changing the alignment logic. Maybe something cleaner
170// ??? can be done.
sewardjd043de92011-09-26 11:28:20 +0000171// A splittable block can be reclaimed when all its blocks are freed :
172// the reclaim of such a block is deferred till either another superblock
173// of the same arena can be reclaimed or till a new superblock is needed
174// in any arena.
nethercote2d5b8162004-08-11 09:40:52 +0000175// payload_bytes[] is made a single big Block when the Superblock is
176// created, and then can be split and the splittings remerged, but Blocks
177// always cover its entire length -- there's never any unused bytes at the
178// end, for example.
sewardj0b3fd2d2007-08-21 10:55:26 +0000179typedef
nethercote2d5b8162004-08-11 09:40:52 +0000180 struct _Superblock {
nethercote7ac7f7b2004-11-02 12:36:02 +0000181 SizeT n_payload_bytes;
sewardjd043de92011-09-26 11:28:20 +0000182 struct _Superblock* unsplittable;
sewardj0b3fd2d2007-08-21 10:55:26 +0000183 UByte padding[ VG_MIN_MALLOC_SZB -
184 ((sizeof(struct _Superblock*) + sizeof(SizeT)) %
nethercote7ac7f7b2004-11-02 12:36:02 +0000185 VG_MIN_MALLOC_SZB) ];
nethercote2d5b8162004-08-11 09:40:52 +0000186 UByte payload_bytes[0];
187 }
188 Superblock;
189
190// An arena. 'freelist' is a circular, doubly-linked list. 'rz_szB' is
191// elastic, in that it can be bigger than asked-for to ensure alignment.
sewardj0b3fd2d2007-08-21 10:55:26 +0000192typedef
nethercote2d5b8162004-08-11 09:40:52 +0000193 struct {
sewardj0b3fd2d2007-08-21 10:55:26 +0000194 Char* name;
195 Bool clientmem; // Allocates in the client address space?
196 SizeT rz_szB; // Red zone size in bytes
197 SizeT min_sblock_szB; // Minimum superblock size in bytes
sewardjd043de92011-09-26 11:28:20 +0000198 SizeT min_unsplittable_sblock_szB;
199 // Minimum unsplittable superblock size in bytes. To be marked as
200 // unsplittable, a superblock must have a
201 // size >= min_unsplittable_sblock_szB and cannot be splitted.
202 // So, to avoid big overhead, superblocks used to provide aligned
203 // blocks on big alignments are splittable.
204 // Unsplittable superblocks will be reclaimed when their (only)
sewardjd8b93462011-09-10 10:17:35 +0000205 // allocated block is freed.
sewardjd043de92011-09-26 11:28:20 +0000206 // Smaller size superblocks are splittable and can be reclaimed when all
207 // their blocks are freed.
sewardj0b3fd2d2007-08-21 10:55:26 +0000208 Block* freelist[N_MALLOC_LISTS];
209 // A dynamically expanding, ordered array of (pointers to)
210 // superblocks in the arena. If this array is expanded, which
211 // is rare, the previous space it occupies is simply abandoned.
212 // To avoid having to get yet another block from m_aspacemgr for
213 // the first incarnation of this array, the first allocation of
214 // it is within this struct. If it has to be expanded then the
215 // new space is acquired from m_aspacemgr as you would expect.
216 Superblock** sblocks;
217 SizeT sblocks_size;
218 SizeT sblocks_used;
219 Superblock* sblocks_initial[SBLOCKS_SIZE_INITIAL];
sewardjd043de92011-09-26 11:28:20 +0000220 Superblock* deferred_reclaimed_sb;
221
nethercote2d5b8162004-08-11 09:40:52 +0000222 // Stats only.
sewardjd043de92011-09-26 11:28:20 +0000223 ULong stats__nreclaim_unsplit;
224 ULong stats__nreclaim_split;
225 /* total # of reclaim executed for unsplittable/splittable superblocks */
sewardj7d1064a2011-02-23 13:18:56 +0000226 SizeT stats__bytes_on_loan;
227 SizeT stats__bytes_mmaped;
228 SizeT stats__bytes_on_loan_max;
229 ULong stats__tot_blocks; /* total # blocks alloc'd */
230 ULong stats__tot_bytes; /* total # bytes alloc'd */
231 ULong stats__nsearches; /* total # freelist checks */
232 // If profiling, when should the next profile happen at
233 // (in terms of stats__bytes_on_loan_max) ?
sewardj9c606bd2008-09-18 18:12:50 +0000234 SizeT next_profile_at;
sewardjd8b93462011-09-10 10:17:35 +0000235 SizeT stats__bytes_mmaped_max;
sewardj0b3fd2d2007-08-21 10:55:26 +0000236 }
nethercote2d5b8162004-08-11 09:40:52 +0000237 Arena;
238
239
240/*------------------------------------------------------------*/
241/*--- Low-level functions for working with Blocks. ---*/
242/*------------------------------------------------------------*/
243
nethercote7ac7f7b2004-11-02 12:36:02 +0000244#define SIZE_T_0x1 ((SizeT)0x1)
245
njnb8329f02009-04-16 00:33:20 +0000246static char* probably_your_fault =
247 "This is probably caused by your program erroneously writing past the\n"
248 "end of a heap block and corrupting heap metadata. If you fix any\n"
249 "invalid writes reported by Memcheck, this assertion failure will\n"
250 "probably go away. Please try that before reporting this as a bug.\n";
251
njn8d3f8452005-07-20 04:12:41 +0000252// Mark a bszB as in-use, and not in-use, and remove the in-use attribute.
nethercote2d5b8162004-08-11 09:40:52 +0000253static __inline__
nethercote7ac7f7b2004-11-02 12:36:02 +0000254SizeT mk_inuse_bszB ( SizeT bszB )
nethercote2d5b8162004-08-11 09:40:52 +0000255{
njnb8329f02009-04-16 00:33:20 +0000256 vg_assert2(bszB != 0, probably_your_fault);
nethercote7ac7f7b2004-11-02 12:36:02 +0000257 return bszB & (~SIZE_T_0x1);
nethercote2d5b8162004-08-11 09:40:52 +0000258}
259static __inline__
nethercote7ac7f7b2004-11-02 12:36:02 +0000260SizeT mk_free_bszB ( SizeT bszB )
nethercote2d5b8162004-08-11 09:40:52 +0000261{
njnb8329f02009-04-16 00:33:20 +0000262 vg_assert2(bszB != 0, probably_your_fault);
nethercote7ac7f7b2004-11-02 12:36:02 +0000263 return bszB | SIZE_T_0x1;
nethercote2d5b8162004-08-11 09:40:52 +0000264}
nethercote2d5b8162004-08-11 09:40:52 +0000265static __inline__
nethercote7ac7f7b2004-11-02 12:36:02 +0000266SizeT mk_plain_bszB ( SizeT bszB )
nethercote2d5b8162004-08-11 09:40:52 +0000267{
njnb8329f02009-04-16 00:33:20 +0000268 vg_assert2(bszB != 0, probably_your_fault);
nethercote7ac7f7b2004-11-02 12:36:02 +0000269 return bszB & (~SIZE_T_0x1);
nethercote2d5b8162004-08-11 09:40:52 +0000270}
271
philipped99c26a2012-07-31 22:17:28 +0000272// Forward definition.
273static
274void ensure_mm_init ( ArenaId aid );
275
sewardj94c8eb42008-09-19 20:13:39 +0000276// return either 0 or sizeof(ULong) depending on whether or not
277// heap profiling is engaged
sewardjd043de92011-09-26 11:28:20 +0000278#define hp_overhead_szB() set_at_init_hp_overhead_szB
279static SizeT set_at_init_hp_overhead_szB = -1000000;
280// startup value chosen to very likely cause a problem if used before
281// a proper value is given by ensure_mm_init.
sewardj94c8eb42008-09-19 20:13:39 +0000282
njn402c8612005-08-23 22:11:20 +0000283//---------------------------------------------------------------------------
284
285// Get a block's size as stored, ie with the in-use/free attribute.
nethercote2d5b8162004-08-11 09:40:52 +0000286static __inline__
njn402c8612005-08-23 22:11:20 +0000287SizeT get_bszB_as_is ( Block* b )
nethercote2d5b8162004-08-11 09:40:52 +0000288{
njn402c8612005-08-23 22:11:20 +0000289 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000290 SizeT bszB_lo = *(SizeT*)&b2[0 + hp_overhead_szB()];
njn402c8612005-08-23 22:11:20 +0000291 SizeT bszB_hi = *(SizeT*)&b2[mk_plain_bszB(bszB_lo) - sizeof(SizeT)];
292 vg_assert2(bszB_lo == bszB_hi,
njnb8329f02009-04-16 00:33:20 +0000293 "Heap block lo/hi size mismatch: lo = %llu, hi = %llu.\n%s",
294 (ULong)bszB_lo, (ULong)bszB_hi, probably_your_fault);
njn402c8612005-08-23 22:11:20 +0000295 return bszB_lo;
nethercote2d5b8162004-08-11 09:40:52 +0000296}
297
njn402c8612005-08-23 22:11:20 +0000298// Get a block's plain size, ie. remove the in-use/free attribute.
299static __inline__
300SizeT get_bszB ( Block* b )
301{
302 return mk_plain_bszB(get_bszB_as_is(b));
303}
304
305// Set the size fields of a block. bszB may have the in-use/free attribute.
306static __inline__
307void set_bszB ( Block* b, SizeT bszB )
308{
309 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000310 *(SizeT*)&b2[0 + hp_overhead_szB()] = bszB;
njn402c8612005-08-23 22:11:20 +0000311 *(SizeT*)&b2[mk_plain_bszB(bszB) - sizeof(SizeT)] = bszB;
312}
313
314//---------------------------------------------------------------------------
315
njn472cc7c2005-07-17 17:20:30 +0000316// Does this block have the in-use attribute?
317static __inline__
318Bool is_inuse_block ( Block* b )
319{
njn402c8612005-08-23 22:11:20 +0000320 SizeT bszB = get_bszB_as_is(b);
njnb8329f02009-04-16 00:33:20 +0000321 vg_assert2(bszB != 0, probably_your_fault);
njn472cc7c2005-07-17 17:20:30 +0000322 return (0 != (bszB & SIZE_T_0x1)) ? False : True;
323}
324
njn402c8612005-08-23 22:11:20 +0000325//---------------------------------------------------------------------------
njn8d3f8452005-07-20 04:12:41 +0000326
njn089f51f2005-07-17 18:12:00 +0000327// Return the lower, upper and total overhead in bytes for a block.
328// These are determined purely by which arena the block lives in.
329static __inline__
330SizeT overhead_szB_lo ( Arena* a )
331{
sewardj94c8eb42008-09-19 20:13:39 +0000332 return hp_overhead_szB() + sizeof(SizeT) + a->rz_szB;
njn089f51f2005-07-17 18:12:00 +0000333}
334static __inline__
335SizeT overhead_szB_hi ( Arena* a )
336{
njn8d3f8452005-07-20 04:12:41 +0000337 return a->rz_szB + sizeof(SizeT);
njn089f51f2005-07-17 18:12:00 +0000338}
339static __inline__
340SizeT overhead_szB ( Arena* a )
341{
342 return overhead_szB_lo(a) + overhead_szB_hi(a);
343}
344
njn402c8612005-08-23 22:11:20 +0000345//---------------------------------------------------------------------------
346
njn089f51f2005-07-17 18:12:00 +0000347// Return the minimum bszB for a block in this arena. Can have zero-length
348// payloads, so it's the size of the admin bytes.
349static __inline__
350SizeT min_useful_bszB ( Arena* a )
351{
352 return overhead_szB(a);
353}
354
njn402c8612005-08-23 22:11:20 +0000355//---------------------------------------------------------------------------
356
njn089f51f2005-07-17 18:12:00 +0000357// Convert payload size <--> block size (both in bytes).
358static __inline__
359SizeT pszB_to_bszB ( Arena* a, SizeT pszB )
360{
361 return pszB + overhead_szB(a);
362}
363static __inline__
364SizeT bszB_to_pszB ( Arena* a, SizeT bszB )
365{
njnb8329f02009-04-16 00:33:20 +0000366 vg_assert2(bszB >= overhead_szB(a), probably_your_fault);
njn089f51f2005-07-17 18:12:00 +0000367 return bszB - overhead_szB(a);
368}
369
njn402c8612005-08-23 22:11:20 +0000370//---------------------------------------------------------------------------
nethercote2d5b8162004-08-11 09:40:52 +0000371
njn089f51f2005-07-17 18:12:00 +0000372// Get a block's payload size.
nethercote7ac7f7b2004-11-02 12:36:02 +0000373static __inline__
njn089f51f2005-07-17 18:12:00 +0000374SizeT get_pszB ( Arena* a, Block* b )
nethercote7ac7f7b2004-11-02 12:36:02 +0000375{
njn089f51f2005-07-17 18:12:00 +0000376 return bszB_to_pszB(a, get_bszB(b));
nethercote7ac7f7b2004-11-02 12:36:02 +0000377}
378
njn402c8612005-08-23 22:11:20 +0000379//---------------------------------------------------------------------------
380
381// Given the addr of a block, return the addr of its payload, and vice versa.
nethercote2d5b8162004-08-11 09:40:52 +0000382static __inline__
383UByte* get_block_payload ( Arena* a, Block* b )
384{
385 UByte* b2 = (UByte*)b;
nethercote7ac7f7b2004-11-02 12:36:02 +0000386 return & b2[ overhead_szB_lo(a) ];
nethercote2d5b8162004-08-11 09:40:52 +0000387}
388// Given the addr of a block's payload, return the addr of the block itself.
389static __inline__
390Block* get_payload_block ( Arena* a, UByte* payload )
391{
nethercote7ac7f7b2004-11-02 12:36:02 +0000392 return (Block*)&payload[ -overhead_szB_lo(a) ];
nethercote2d5b8162004-08-11 09:40:52 +0000393}
394
njn402c8612005-08-23 22:11:20 +0000395//---------------------------------------------------------------------------
nethercote2d5b8162004-08-11 09:40:52 +0000396
397// Set and get the next and previous link fields of a block.
398static __inline__
399void set_prev_b ( Block* b, Block* prev_p )
400{
401 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000402 *(Block**)&b2[hp_overhead_szB() + sizeof(SizeT)] = prev_p;
nethercote2d5b8162004-08-11 09:40:52 +0000403}
404static __inline__
405void set_next_b ( Block* b, Block* next_p )
406{
njn402c8612005-08-23 22:11:20 +0000407 UByte* b2 = (UByte*)b;
408 *(Block**)&b2[get_bszB(b) - sizeof(SizeT) - sizeof(void*)] = next_p;
nethercote2d5b8162004-08-11 09:40:52 +0000409}
410static __inline__
411Block* get_prev_b ( Block* b )
412{
413 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000414 return *(Block**)&b2[hp_overhead_szB() + sizeof(SizeT)];
nethercote2d5b8162004-08-11 09:40:52 +0000415}
416static __inline__
417Block* get_next_b ( Block* b )
418{
njn402c8612005-08-23 22:11:20 +0000419 UByte* b2 = (UByte*)b;
420 return *(Block**)&b2[get_bszB(b) - sizeof(SizeT) - sizeof(void*)];
nethercote2d5b8162004-08-11 09:40:52 +0000421}
422
njn402c8612005-08-23 22:11:20 +0000423//---------------------------------------------------------------------------
nethercote2d5b8162004-08-11 09:40:52 +0000424
sewardj9c606bd2008-09-18 18:12:50 +0000425// Set and get the cost-center field of a block.
426static __inline__
427void set_cc ( Block* b, HChar* cc )
428{
429 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000430 vg_assert( VG_(clo_profile_heap) );
sewardj9c606bd2008-09-18 18:12:50 +0000431 *(HChar**)&b2[0] = cc;
432}
433static __inline__
434HChar* get_cc ( Block* b )
435{
436 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000437 vg_assert( VG_(clo_profile_heap) );
sewardj9c606bd2008-09-18 18:12:50 +0000438 return *(HChar**)&b2[0];
439}
440
441//---------------------------------------------------------------------------
442
nethercote2d5b8162004-08-11 09:40:52 +0000443// Get the block immediately preceding this one in the Superblock.
444static __inline__
445Block* get_predecessor_block ( Block* b )
446{
447 UByte* b2 = (UByte*)b;
nethercote7ac7f7b2004-11-02 12:36:02 +0000448 SizeT bszB = mk_plain_bszB( (*(SizeT*)&b2[-sizeof(SizeT)]) );
nethercote2d5b8162004-08-11 09:40:52 +0000449 return (Block*)&b2[-bszB];
450}
451
njn402c8612005-08-23 22:11:20 +0000452//---------------------------------------------------------------------------
453
nethercote2d5b8162004-08-11 09:40:52 +0000454// Read and write the lower and upper red-zone bytes of a block.
455static __inline__
njn1dcee092009-02-24 03:07:37 +0000456void set_rz_lo_byte ( Block* b, UInt rz_byteno, UByte v )
nethercote2d5b8162004-08-11 09:40:52 +0000457{
458 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000459 b2[hp_overhead_szB() + sizeof(SizeT) + rz_byteno] = v;
nethercote2d5b8162004-08-11 09:40:52 +0000460}
461static __inline__
njn1dcee092009-02-24 03:07:37 +0000462void set_rz_hi_byte ( Block* b, UInt rz_byteno, UByte v )
nethercote2d5b8162004-08-11 09:40:52 +0000463{
njn402c8612005-08-23 22:11:20 +0000464 UByte* b2 = (UByte*)b;
465 b2[get_bszB(b) - sizeof(SizeT) - rz_byteno - 1] = v;
nethercote2d5b8162004-08-11 09:40:52 +0000466}
467static __inline__
njn1dcee092009-02-24 03:07:37 +0000468UByte get_rz_lo_byte ( Block* b, UInt rz_byteno )
nethercote2d5b8162004-08-11 09:40:52 +0000469{
470 UByte* b2 = (UByte*)b;
sewardj94c8eb42008-09-19 20:13:39 +0000471 return b2[hp_overhead_szB() + sizeof(SizeT) + rz_byteno];
nethercote2d5b8162004-08-11 09:40:52 +0000472}
473static __inline__
njn1dcee092009-02-24 03:07:37 +0000474UByte get_rz_hi_byte ( Block* b, UInt rz_byteno )
nethercote2d5b8162004-08-11 09:40:52 +0000475{
njn402c8612005-08-23 22:11:20 +0000476 UByte* b2 = (UByte*)b;
477 return b2[get_bszB(b) - sizeof(SizeT) - rz_byteno - 1];
nethercote2d5b8162004-08-11 09:40:52 +0000478}
479
480
nethercote2d5b8162004-08-11 09:40:52 +0000481/*------------------------------------------------------------*/
482/*--- Arena management ---*/
483/*------------------------------------------------------------*/
484
485#define CORE_ARENA_MIN_SZB 1048576
486
487// The arena structures themselves.
488static Arena vg_arena[VG_N_ARENAS];
489
490// Functions external to this module identify arenas using ArenaIds,
491// not Arena*s. This fn converts the former to the latter.
492static Arena* arenaId_to_ArenaP ( ArenaId arena )
493{
494 vg_assert(arena >= 0 && arena < VG_N_ARENAS);
495 return & vg_arena[arena];
496}
497
philipped99c26a2012-07-31 22:17:28 +0000498SizeT VG_(malloc_effective_client_redzone_size)(void)
499{
500 vg_assert(VG_(needs).malloc_replacement);
501 ensure_mm_init (VG_AR_CLIENT);
502 /* ensure_mm_init will call arena_init if not yet done.
503 This then ensures that the arena redzone size is properly
504 initialised. */
505 return arenaId_to_ArenaP(VG_AR_CLIENT)->rz_szB;
506}
507
508// Initialise an arena. rz_szB is the (default) minimum redzone size;
509// It might be overriden by VG_(clo_redzone_size) or VG_(clo_core_redzone_size).
510// it might be made bigger to ensure that VG_MIN_MALLOC_SZB is observed.
nethercote2d5b8162004-08-11 09:40:52 +0000511static
sewardjd8b93462011-09-10 10:17:35 +0000512void arena_init ( ArenaId aid, Char* name, SizeT rz_szB,
sewardjd043de92011-09-26 11:28:20 +0000513 SizeT min_sblock_szB, SizeT min_unsplittable_sblock_szB )
nethercote2d5b8162004-08-11 09:40:52 +0000514{
sewardj0b3fd2d2007-08-21 10:55:26 +0000515 SizeT i;
nethercote2d5b8162004-08-11 09:40:52 +0000516 Arena* a = arenaId_to_ArenaP(aid);
philipped99c26a2012-07-31 22:17:28 +0000517
518 // Ensure default redzones are a reasonable size.
519 vg_assert(rz_szB <= MAX_REDZONE_SZB);
nethercote2d5b8162004-08-11 09:40:52 +0000520
philipped99c26a2012-07-31 22:17:28 +0000521 /* Override the default redzone size if a clo value was given.
522 Note that the clo value can be significantly bigger than MAX_REDZONE_SZB
523 to allow the user to chase horrible bugs using up to 1 page
524 of protection. */
525 if (VG_AR_CLIENT == aid) {
526 if (VG_(clo_redzone_size) != -1)
527 rz_szB = VG_(clo_redzone_size);
528 } else {
529 if (VG_(clo_core_redzone_size) != rz_szB)
530 rz_szB = VG_(clo_core_redzone_size);
531 }
532
533 // Redzones must always be at least the size of a pointer, for holding the
534 // prev/next pointer (see the layout details at the top of this file).
njn7ce83112005-08-24 22:38:00 +0000535 if (rz_szB < sizeof(void*)) rz_szB = sizeof(void*);
nethercote2d5b8162004-08-11 09:40:52 +0000536
537 // The size of the low and high admin sections in a block must be a
njn30490552005-03-13 06:30:42 +0000538 // multiple of VG_MIN_MALLOC_SZB. So we round up the asked-for
nethercote2d5b8162004-08-11 09:40:52 +0000539 // redzone size if necessary to achieve this.
540 a->rz_szB = rz_szB;
541 while (0 != overhead_szB_lo(a) % VG_MIN_MALLOC_SZB) a->rz_szB++;
njn341a6642009-05-24 23:36:50 +0000542 vg_assert(overhead_szB_lo(a) - hp_overhead_szB() == overhead_szB_hi(a));
nethercote2d5b8162004-08-11 09:40:52 +0000543
philipped99c26a2012-07-31 22:17:28 +0000544 // Here we have established the effective redzone size.
545
546
547 vg_assert((min_sblock_szB % VKI_PAGE_SIZE) == 0);
548 a->name = name;
549 a->clientmem = ( VG_AR_CLIENT == aid ? True : False );
550
nethercote2d5b8162004-08-11 09:40:52 +0000551 a->min_sblock_szB = min_sblock_szB;
sewardjd043de92011-09-26 11:28:20 +0000552 a->min_unsplittable_sblock_szB = min_unsplittable_sblock_szB;
njn6e6588c2005-03-13 18:52:48 +0000553 for (i = 0; i < N_MALLOC_LISTS; i++) a->freelist[i] = NULL;
sewardj0b3fd2d2007-08-21 10:55:26 +0000554
sewardj7d1064a2011-02-23 13:18:56 +0000555 a->sblocks = & a->sblocks_initial[0];
556 a->sblocks_size = SBLOCKS_SIZE_INITIAL;
557 a->sblocks_used = 0;
sewardjd043de92011-09-26 11:28:20 +0000558 a->stats__nreclaim_unsplit = 0;
559 a->stats__nreclaim_split = 0;
sewardj7d1064a2011-02-23 13:18:56 +0000560 a->stats__bytes_on_loan = 0;
561 a->stats__bytes_mmaped = 0;
562 a->stats__bytes_on_loan_max = 0;
sewardjd8b93462011-09-10 10:17:35 +0000563 a->stats__bytes_mmaped_max = 0;
sewardj7d1064a2011-02-23 13:18:56 +0000564 a->stats__tot_blocks = 0;
565 a->stats__tot_bytes = 0;
566 a->stats__nsearches = 0;
567 a->next_profile_at = 25 * 1000 * 1000;
sewardj0b3fd2d2007-08-21 10:55:26 +0000568 vg_assert(sizeof(a->sblocks_initial)
569 == SBLOCKS_SIZE_INITIAL * sizeof(Superblock*));
nethercote2d5b8162004-08-11 09:40:52 +0000570}
571
572/* Print vital stats for an arena. */
573void VG_(print_all_arena_stats) ( void )
574{
nethercote7ac7f7b2004-11-02 12:36:02 +0000575 UInt i;
nethercote2d5b8162004-08-11 09:40:52 +0000576 for (i = 0; i < VG_N_ARENAS; i++) {
577 Arena* a = arenaId_to_ArenaP(i);
578 VG_(message)(Vg_DebugMsg,
sewardjd043de92011-09-26 11:28:20 +0000579 "%8s: %8ld/%8ld max/curr mmap'd, "
580 "%llu/%llu unsplit/split sb unmmap'd, "
581 "%8ld/%8ld max/curr, "
sewardj7d1064a2011-02-23 13:18:56 +0000582 "%10llu/%10llu totalloc-blocks/bytes,"
philipped99c26a2012-07-31 22:17:28 +0000583 " %10llu searches %lu rzB\n",
sewardjd8b93462011-09-10 10:17:35 +0000584 a->name,
585 a->stats__bytes_mmaped_max, a->stats__bytes_mmaped,
sewardjd043de92011-09-26 11:28:20 +0000586 a->stats__nreclaim_unsplit, a->stats__nreclaim_split,
sewardj7d1064a2011-02-23 13:18:56 +0000587 a->stats__bytes_on_loan_max,
588 a->stats__bytes_on_loan,
589 a->stats__tot_blocks, a->stats__tot_bytes,
philipped99c26a2012-07-31 22:17:28 +0000590 a->stats__nsearches,
591 a->rz_szB
nethercote2d5b8162004-08-11 09:40:52 +0000592 );
593 }
594}
595
sewardj9c606bd2008-09-18 18:12:50 +0000596void VG_(print_arena_cc_analysis) ( void )
597{
598 UInt i;
599 vg_assert( VG_(clo_profile_heap) );
600 for (i = 0; i < VG_N_ARENAS; i++) {
601 cc_analyse_alloc_arena(i);
602 }
603}
604
605
nethercote2d5b8162004-08-11 09:40:52 +0000606/* This library is self-initialising, as it makes this more self-contained,
607 less coupled with the outside world. Hence VG_(arena_malloc)() and
608 VG_(arena_free)() below always call ensure_mm_init() to ensure things are
sewardj45f4e7c2005-09-27 19:20:21 +0000609 correctly initialised.
610
611 We initialise the client arena separately (and later) because the core
612 must do non-client allocation before the tool has a chance to set the
613 client arena's redzone size.
614*/
sewardj0b3fd2d2007-08-21 10:55:26 +0000615static Bool client_inited = False;
616static Bool nonclient_inited = False;
617
nethercote2d5b8162004-08-11 09:40:52 +0000618static
sewardj45f4e7c2005-09-27 19:20:21 +0000619void ensure_mm_init ( ArenaId aid )
nethercote2d5b8162004-08-11 09:40:52 +0000620{
njn95c23292005-12-26 17:50:22 +0000621 static SizeT client_rz_szB = 8; // default: be paranoid
njnfc51f8d2005-06-21 03:20:17 +0000622
sewardj45f4e7c2005-09-27 19:20:21 +0000623 /* We use checked red zones (of various sizes) for our internal stuff,
nethercote2d5b8162004-08-11 09:40:52 +0000624 and an unchecked zone of arbitrary size for the client. Of
625 course the client's red zone can be checked by the tool, eg.
626 by using addressibility maps, but not by the mechanism implemented
627 here, which merely checks at the time of freeing that the red
628 zone bytes are unchanged.
629
630 Nb: redzone sizes are *minimums*; they could be made bigger to ensure
njn8d3f8452005-07-20 04:12:41 +0000631 alignment. Eg. with 8 byte alignment, on 32-bit machines 4 stays as
632 4, but 16 becomes 20; but on 64-bit machines 4 becomes 8, and 16
633 stays as 16 --- the extra 4 bytes in both are accounted for by the
634 larger prev/next ptr.
nethercote2d5b8162004-08-11 09:40:52 +0000635 */
sewardj45f4e7c2005-09-27 19:20:21 +0000636 if (VG_AR_CLIENT == aid) {
sewardj5600ab32006-10-17 01:42:40 +0000637 Int ar_client_sbszB;
sewardj45f4e7c2005-09-27 19:20:21 +0000638 if (client_inited) {
639 // This assertion ensures that a tool cannot try to change the client
640 // redzone size with VG_(needs_malloc_replacement)() after this module
641 // has done its first allocation from the client arena.
642 if (VG_(needs).malloc_replacement)
njn95c23292005-12-26 17:50:22 +0000643 vg_assert(client_rz_szB == VG_(tdict).tool_client_redzone_szB);
sewardj45f4e7c2005-09-27 19:20:21 +0000644 return;
645 }
nethercote2d5b8162004-08-11 09:40:52 +0000646
sewardj45f4e7c2005-09-27 19:20:21 +0000647 // Check and set the client arena redzone size
648 if (VG_(needs).malloc_replacement) {
njn95c23292005-12-26 17:50:22 +0000649 client_rz_szB = VG_(tdict).tool_client_redzone_szB;
philipped99c26a2012-07-31 22:17:28 +0000650 if (client_rz_szB > MAX_REDZONE_SZB) {
sewardj45f4e7c2005-09-27 19:20:21 +0000651 VG_(printf)( "\nTool error:\n"
652 " specified redzone size is too big (%llu)\n",
njn95c23292005-12-26 17:50:22 +0000653 (ULong)client_rz_szB);
sewardj45f4e7c2005-09-27 19:20:21 +0000654 VG_(exit)(1);
655 }
656 }
sewardj6e9de462011-06-28 07:25:29 +0000657 // Initialise the client arena. On all platforms,
sewardjc1ac9772007-08-20 22:57:56 +0000658 // increasing the superblock size reduces the number of superblocks
659 // in the client arena, which makes findSb cheaper.
sewardjc1ac9772007-08-20 22:57:56 +0000660 ar_client_sbszB = 4194304;
sewardjd043de92011-09-26 11:28:20 +0000661 // superblocks with a size > ar_client_sbszB will be unsplittable
662 // (unless used for providing memalign-ed blocks).
sewardjd8b93462011-09-10 10:17:35 +0000663 arena_init ( VG_AR_CLIENT, "client", client_rz_szB,
664 ar_client_sbszB, ar_client_sbszB+1);
sewardj45f4e7c2005-09-27 19:20:21 +0000665 client_inited = True;
666
667 } else {
668 if (nonclient_inited) {
669 return;
670 }
sewardjd043de92011-09-26 11:28:20 +0000671 set_at_init_hp_overhead_szB =
672 VG_(clo_profile_heap) ? VG_MIN_MALLOC_SZB : 0;
sewardj45f4e7c2005-09-27 19:20:21 +0000673 // Initialise the non-client arenas
sewardjd043de92011-09-26 11:28:20 +0000674 // Similarly to client arena, big allocations will be unsplittable.
philipped99c26a2012-07-31 22:17:28 +0000675 arena_init ( VG_AR_CORE, "core", CORE_REDZONE_DEFAULT_SZB,
676 1048576, 1048576+1 );
677 arena_init ( VG_AR_TOOL, "tool", CORE_REDZONE_DEFAULT_SZB,
678 4194304, 4194304+1 );
679 arena_init ( VG_AR_DINFO, "dinfo", CORE_REDZONE_DEFAULT_SZB,
680 1048576, 1048576+1 );
681 arena_init ( VG_AR_DEMANGLE, "demangle", CORE_REDZONE_DEFAULT_SZB,
682 65536, 65536+1 );
683 arena_init ( VG_AR_EXECTXT, "exectxt", CORE_REDZONE_DEFAULT_SZB,
684 1048576, 1048576+1 );
685 arena_init ( VG_AR_ERRORS, "errors", CORE_REDZONE_DEFAULT_SZB,
686 65536, 65536+1 );
687 arena_init ( VG_AR_TTAUX, "ttaux", CORE_REDZONE_DEFAULT_SZB,
688 65536, 65536+1 );
sewardj45f4e7c2005-09-27 19:20:21 +0000689 nonclient_inited = True;
690 }
691
nethercote2d5b8162004-08-11 09:40:52 +0000692# ifdef DEBUG_MALLOC
sewardj0b3fd2d2007-08-21 10:55:26 +0000693 VG_(printf)("ZZZ1\n");
nethercote2d5b8162004-08-11 09:40:52 +0000694 VG_(sanity_check_malloc_all)();
sewardj0b3fd2d2007-08-21 10:55:26 +0000695 VG_(printf)("ZZZ2\n");
nethercote2d5b8162004-08-11 09:40:52 +0000696# endif
697}
698
699
700/*------------------------------------------------------------*/
701/*--- Superblock management ---*/
702/*------------------------------------------------------------*/
703
njn4c245e52009-03-15 23:25:38 +0000704__attribute__((noreturn))
sewardj45f4e7c2005-09-27 19:20:21 +0000705void VG_(out_of_memory_NORETURN) ( HChar* who, SizeT szB )
706{
707 static Bool alreadyCrashing = False;
708 ULong tot_alloc = VG_(am_get_anonsize_total)();
njnb81c7952007-03-22 03:36:55 +0000709 Char* s1 =
710 "\n"
711 " Valgrind's memory management: out of memory:\n"
712 " %s's request for %llu bytes failed.\n"
713 " %llu bytes have already been allocated.\n"
714 " Valgrind cannot continue. Sorry.\n\n"
715 " There are several possible reasons for this.\n"
716 " - You have some kind of memory limit in place. Look at the\n"
717 " output of 'ulimit -a'. Is there a limit on the size of\n"
718 " virtual memory or address space?\n"
719 " - You have run out of swap space.\n"
720 " - Valgrind has a bug. If you think this is the case or you are\n"
721 " not sure, please let us know and we'll try to fix it.\n"
722 " Please note that programs can take substantially more memory than\n"
723 " normal when running under Valgrind tools, eg. up to twice or\n"
724 " more, depending on the tool. On a 64-bit machine, Valgrind\n"
725 " should be able to make use of up 32GB memory. On a 32-bit\n"
726 " machine, Valgrind should be able to use all the memory available\n"
727 " to a single process, up to 4GB if that's how you have your\n"
728 " kernel configured. Most 32-bit Linux setups allow a maximum of\n"
729 " 3GB per process.\n\n"
730 " Whatever the reason, Valgrind cannot continue. Sorry.\n";
731
sewardj45f4e7c2005-09-27 19:20:21 +0000732 if (!alreadyCrashing) {
733 alreadyCrashing = True;
njnb81c7952007-03-22 03:36:55 +0000734 VG_(message)(Vg_UserMsg, s1, who, (ULong)szB, tot_alloc);
sewardj45f4e7c2005-09-27 19:20:21 +0000735 } else {
njnb81c7952007-03-22 03:36:55 +0000736 VG_(debugLog)(0,"mallocfree", s1, who, (ULong)szB, tot_alloc);
sewardj45f4e7c2005-09-27 19:20:21 +0000737 }
njncda2f0f2009-05-18 02:12:08 +0000738
sewardj45f4e7c2005-09-27 19:20:21 +0000739 VG_(exit)(1);
740}
741
742
nethercote2d5b8162004-08-11 09:40:52 +0000743// Align ptr p upwards to an align-sized boundary.
744static
nethercote7ac7f7b2004-11-02 12:36:02 +0000745void* align_upwards ( void* p, SizeT align )
nethercote2d5b8162004-08-11 09:40:52 +0000746{
747 Addr a = (Addr)p;
748 if ((a % align) == 0) return (void*)a;
749 return (void*)(a - (a % align) + align);
750}
751
sewardjd043de92011-09-26 11:28:20 +0000752// Forward definition.
753static
754void deferred_reclaimSuperblock ( Arena* a, Superblock* sb);
755
nethercote2d5b8162004-08-11 09:40:52 +0000756// If not enough memory available, either aborts (for non-client memory)
757// or returns 0 (for client memory).
758static
nethercote7ac7f7b2004-11-02 12:36:02 +0000759Superblock* newSuperblock ( Arena* a, SizeT cszB )
nethercote2d5b8162004-08-11 09:40:52 +0000760{
nethercote2d5b8162004-08-11 09:40:52 +0000761 Superblock* sb;
sewardj45f4e7c2005-09-27 19:20:21 +0000762 SysRes sres;
sewardjd043de92011-09-26 11:28:20 +0000763 Bool unsplittable;
764 ArenaId aid;
765
766 // A new superblock is needed for arena a. We will execute the deferred
767 // reclaim in all arenas in order to minimise fragmentation and
768 // peak memory usage.
769 for (aid = 0; aid < VG_N_ARENAS; aid++) {
770 Arena* arena = arenaId_to_ArenaP(aid);
771 if (arena->deferred_reclaimed_sb != NULL)
772 deferred_reclaimSuperblock (arena, NULL);
773 }
nethercote2d5b8162004-08-11 09:40:52 +0000774
775 // Take into account admin bytes in the Superblock.
776 cszB += sizeof(Superblock);
777
778 if (cszB < a->min_sblock_szB) cszB = a->min_sblock_szB;
bartc3c98392008-04-19 14:43:30 +0000779 cszB = VG_PGROUNDUP(cszB);
nethercote2d5b8162004-08-11 09:40:52 +0000780
sewardjd043de92011-09-26 11:28:20 +0000781 if (cszB >= a->min_unsplittable_sblock_szB)
782 unsplittable = True;
sewardjd8b93462011-09-10 10:17:35 +0000783 else
sewardjd043de92011-09-26 11:28:20 +0000784 unsplittable = False;
sewardjd8b93462011-09-10 10:17:35 +0000785
786
sewardj45f4e7c2005-09-27 19:20:21 +0000787 if (a->clientmem) {
nethercote2d5b8162004-08-11 09:40:52 +0000788 // client allocation -- return 0 to client if it fails
sewardjd043de92011-09-26 11:28:20 +0000789 if (unsplittable)
sewardjd8b93462011-09-10 10:17:35 +0000790 sres = VG_(am_mmap_anon_float_client)
791 ( cszB, VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC );
792 else
793 sres = VG_(am_sbrk_anon_float_client)
794 ( cszB, VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC );
njncda2f0f2009-05-18 02:12:08 +0000795 if (sr_isError(sres))
nethercote2d5b8162004-08-11 09:40:52 +0000796 return 0;
njncda2f0f2009-05-18 02:12:08 +0000797 sb = (Superblock*)(AddrH)sr_Res(sres);
sewardj45f4e7c2005-09-27 19:20:21 +0000798 // Mark this segment as containing client heap. The leak
799 // checker needs to be able to identify such segments so as not
800 // to use them as sources of roots during leak checks.
sewardj5600ab32006-10-17 01:42:40 +0000801 VG_(am_set_segment_isCH_if_SkAnonC)(
802 (NSegment*) VG_(am_find_nsegment)( (Addr)sb )
803 );
nethercote2d5b8162004-08-11 09:40:52 +0000804 } else {
sewardj45f4e7c2005-09-27 19:20:21 +0000805 // non-client allocation -- abort if it fails
sewardjd043de92011-09-26 11:28:20 +0000806 if (unsplittable)
sewardjd8b93462011-09-10 10:17:35 +0000807 sres = VG_(am_mmap_anon_float_valgrind)( cszB );
808 else
809 sres = VG_(am_sbrk_anon_float_valgrind)( cszB );
njncda2f0f2009-05-18 02:12:08 +0000810 if (sr_isError(sres)) {
sewardj45f4e7c2005-09-27 19:20:21 +0000811 VG_(out_of_memory_NORETURN)("newSuperblock", cszB);
812 /* NOTREACHED */
813 sb = NULL; /* keep gcc happy */
814 } else {
njncda2f0f2009-05-18 02:12:08 +0000815 sb = (Superblock*)(AddrH)sr_Res(sres);
sewardj45f4e7c2005-09-27 19:20:21 +0000816 }
nethercote2d5b8162004-08-11 09:40:52 +0000817 }
818 vg_assert(NULL != sb);
philippe72faf102012-03-11 22:24:03 +0000819 INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(sb, cszB));
nethercote2d5b8162004-08-11 09:40:52 +0000820 vg_assert(0 == (Addr)sb % VG_MIN_MALLOC_SZB);
821 sb->n_payload_bytes = cszB - sizeof(Superblock);
sewardjd043de92011-09-26 11:28:20 +0000822 sb->unsplittable = (unsplittable ? sb : NULL);
sewardj7d1064a2011-02-23 13:18:56 +0000823 a->stats__bytes_mmaped += cszB;
sewardjd8b93462011-09-10 10:17:35 +0000824 if (a->stats__bytes_mmaped > a->stats__bytes_mmaped_max)
825 a->stats__bytes_mmaped_max = a->stats__bytes_mmaped;
sewardj45f4e7c2005-09-27 19:20:21 +0000826 VG_(debugLog)(1, "mallocfree",
sewardjd8b93462011-09-10 10:17:35 +0000827 "newSuperblock at %p (pszB %7ld) %s owner %s/%s\n",
sewardjd043de92011-09-26 11:28:20 +0000828 sb, sb->n_payload_bytes,
829 (unsplittable ? "unsplittable" : ""),
sewardj45264af2011-07-24 17:39:10 +0000830 a->clientmem ? "CLIENT" : "VALGRIND", a->name );
sewardj4c89b2f2011-08-17 22:13:14 +0000831 return sb;
sewardj45264af2011-07-24 17:39:10 +0000832}
833
sewardjd043de92011-09-26 11:28:20 +0000834// Reclaims the given superblock:
sewardjd8b93462011-09-10 10:17:35 +0000835// * removes sb from arena sblocks list.
836// * munmap the superblock segment.
837static
838void reclaimSuperblock ( Arena* a, Superblock* sb)
839{
840 SysRes sres;
841 SizeT cszB;
842 UInt i, j;
843
844 VG_(debugLog)(1, "mallocfree",
sewardjd043de92011-09-26 11:28:20 +0000845 "reclaimSuperblock at %p (pszB %7ld) %s owner %s/%s\n",
846 sb, sb->n_payload_bytes,
847 (sb->unsplittable ? "unsplittable" : ""),
sewardjd8b93462011-09-10 10:17:35 +0000848 a->clientmem ? "CLIENT" : "VALGRIND", a->name );
849
sewardjd8b93462011-09-10 10:17:35 +0000850 // Take into account admin bytes in the Superblock.
851 cszB = sizeof(Superblock) + sb->n_payload_bytes;
sewardjd8b93462011-09-10 10:17:35 +0000852
853 // removes sb from superblock list.
854 for (i = 0; i < a->sblocks_used; i++) {
855 if (a->sblocks[i] == sb)
856 break;
857 }
858 vg_assert(i >= 0 && i < a->sblocks_used);
859 for (j = i; j < a->sblocks_used; j++)
860 a->sblocks[j] = a->sblocks[j+1];
861 a->sblocks_used--;
862 a->sblocks[a->sblocks_used] = NULL;
863 // paranoia: NULLify ptr to reclaimed sb or NULLify copy of ptr to last sb.
864
sewardjd043de92011-09-26 11:28:20 +0000865 a->stats__bytes_mmaped -= cszB;
866 if (sb->unsplittable)
867 a->stats__nreclaim_unsplit++;
868 else
869 a->stats__nreclaim_split++;
870
sewardjd8b93462011-09-10 10:17:35 +0000871 // Now that the sb is removed from the list, mnumap its space.
872 if (a->clientmem) {
873 // reclaimable client allocation
874 Bool need_discard = False;
875 sres = VG_(am_munmap_client)(&need_discard, (Addr) sb, cszB);
sewardjd8b93462011-09-10 10:17:35 +0000876 vg_assert2(! sr_isError(sres), "superblock client munmap failure\n");
sewardjd043de92011-09-26 11:28:20 +0000877 /* We somewhat help the client by discarding the range.
878 Note however that if the client has JITted some code in
879 a small block that was freed, we do not provide this
880 'discard support' */
881 /* JRS 2011-Sept-26: it would be nice to move the discard
882 outwards somewhat (in terms of calls) so as to make it easier
883 to verify that there will be no nonterminating recursive set
884 of calls a result of calling VG_(discard_translations).
885 Another day, perhaps. */
886 if (need_discard)
887 VG_(discard_translations) ((Addr) sb, cszB, "reclaimSuperblock");
sewardjd8b93462011-09-10 10:17:35 +0000888 } else {
889 // reclaimable non-client allocation
890 sres = VG_(am_munmap_valgrind)((Addr) sb, cszB);
891 vg_assert2(! sr_isError(sres), "superblock valgrind munmap failure\n");
892 }
sewardjd043de92011-09-26 11:28:20 +0000893
sewardjd8b93462011-09-10 10:17:35 +0000894}
895
nethercote2d5b8162004-08-11 09:40:52 +0000896// Find the superblock containing the given chunk.
897static
898Superblock* findSb ( Arena* a, Block* b )
899{
sewardj0b3fd2d2007-08-21 10:55:26 +0000900 SizeT min = 0;
901 SizeT max = a->sblocks_used;
sewardj49bdd7a2005-12-17 20:37:36 +0000902
sewardj0b3fd2d2007-08-21 10:55:26 +0000903 while (min <= max) {
904 Superblock * sb;
905 SizeT pos = min + (max - min)/2;
906
907 vg_assert(pos >= 0 && pos < a->sblocks_used);
908 sb = a->sblocks[pos];
909 if ((Block*)&sb->payload_bytes[0] <= b
910 && b < (Block*)&sb->payload_bytes[sb->n_payload_bytes])
911 {
912 return sb;
913 } else if ((Block*)&sb->payload_bytes[0] <= b) {
914 min = pos + 1;
915 } else {
916 max = pos - 1;
sewardj49bdd7a2005-12-17 20:37:36 +0000917 }
918 }
sewardj0b3fd2d2007-08-21 10:55:26 +0000919 VG_(printf)("findSb: can't find pointer %p in arena '%s'\n",
920 b, a->name );
921 VG_(core_panic)("findSb: VG_(arena_free)() in wrong arena?");
922 return NULL; /*NOTREACHED*/
nethercote2d5b8162004-08-11 09:40:52 +0000923}
924
sewardjde4a1d02002-03-22 01:27:54 +0000925
fitzhardinge98abfc72003-12-16 02:05:15 +0000926/*------------------------------------------------------------*/
sewardjde4a1d02002-03-22 01:27:54 +0000927/*--- Functions for working with freelists. ---*/
928/*------------------------------------------------------------*/
929
nethercote2d5b8162004-08-11 09:40:52 +0000930// Nb: Determination of which freelist a block lives on is based on the
931// payload size, not block size.
sewardjde4a1d02002-03-22 01:27:54 +0000932
nethercote2d5b8162004-08-11 09:40:52 +0000933// Convert a payload size in bytes to a freelist number.
sewardjde4a1d02002-03-22 01:27:54 +0000934static
nethercote7ac7f7b2004-11-02 12:36:02 +0000935UInt pszB_to_listNo ( SizeT pszB )
sewardjde4a1d02002-03-22 01:27:54 +0000936{
njndb247dc2005-07-17 23:12:33 +0000937 SizeT n = pszB / VG_MIN_MALLOC_SZB;
tom60a4b0b2005-10-12 10:45:27 +0000938 vg_assert(0 == pszB % VG_MIN_MALLOC_SZB);
njn61dcab82005-05-21 19:36:45 +0000939
sewardjc1ac9772007-08-20 22:57:56 +0000940 // The first 64 lists hold blocks of size VG_MIN_MALLOC_SZB * list_num.
941 // The final 48 hold bigger blocks.
942 if (n < 64) return (UInt)n;
943 /* Exponential slope up, factor 1.05 */
944 if (n < 67) return 64;
945 if (n < 70) return 65;
946 if (n < 74) return 66;
947 if (n < 77) return 67;
948 if (n < 81) return 68;
949 if (n < 85) return 69;
950 if (n < 90) return 70;
951 if (n < 94) return 71;
952 if (n < 99) return 72;
953 if (n < 104) return 73;
954 if (n < 109) return 74;
955 if (n < 114) return 75;
956 if (n < 120) return 76;
957 if (n < 126) return 77;
958 if (n < 133) return 78;
959 if (n < 139) return 79;
960 /* Exponential slope up, factor 1.10 */
961 if (n < 153) return 80;
962 if (n < 169) return 81;
963 if (n < 185) return 82;
964 if (n < 204) return 83;
965 if (n < 224) return 84;
966 if (n < 247) return 85;
967 if (n < 272) return 86;
968 if (n < 299) return 87;
969 if (n < 329) return 88;
970 if (n < 362) return 89;
971 if (n < 398) return 90;
972 if (n < 438) return 91;
973 if (n < 482) return 92;
974 if (n < 530) return 93;
975 if (n < 583) return 94;
976 if (n < 641) return 95;
977 /* Exponential slope up, factor 1.20 */
978 if (n < 770) return 96;
979 if (n < 924) return 97;
980 if (n < 1109) return 98;
981 if (n < 1331) return 99;
982 if (n < 1597) return 100;
983 if (n < 1916) return 101;
984 if (n < 2300) return 102;
985 if (n < 2760) return 103;
986 if (n < 3312) return 104;
987 if (n < 3974) return 105;
988 if (n < 4769) return 106;
989 if (n < 5723) return 107;
990 if (n < 6868) return 108;
991 if (n < 8241) return 109;
992 if (n < 9890) return 110;
993 return 111;
sewardjde4a1d02002-03-22 01:27:54 +0000994}
995
nethercote2d5b8162004-08-11 09:40:52 +0000996// What is the minimum payload size for a given list?
sewardjde4a1d02002-03-22 01:27:54 +0000997static
nethercote7ac7f7b2004-11-02 12:36:02 +0000998SizeT listNo_to_pszB_min ( UInt listNo )
sewardjde4a1d02002-03-22 01:27:54 +0000999{
sewardj1d2e2e62007-08-23 10:22:44 +00001000 /* Repeatedly computing this function at every request is
1001 expensive. Hence at the first call just cache the result for
1002 every possible argument. */
1003 static SizeT cache[N_MALLOC_LISTS];
1004 static Bool cache_valid = False;
1005 if (!cache_valid) {
1006 UInt i;
1007 for (i = 0; i < N_MALLOC_LISTS; i++) {
1008 SizeT pszB = 0;
1009 while (pszB_to_listNo(pszB) < i)
1010 pszB += VG_MIN_MALLOC_SZB;
1011 cache[i] = pszB;
1012 }
1013 cache_valid = True;
1014 }
1015 /* Returned cached answer. */
njn6e6588c2005-03-13 18:52:48 +00001016 vg_assert(listNo <= N_MALLOC_LISTS);
sewardj1d2e2e62007-08-23 10:22:44 +00001017 return cache[listNo];
sewardjde4a1d02002-03-22 01:27:54 +00001018}
1019
nethercote2d5b8162004-08-11 09:40:52 +00001020// What is the maximum payload size for a given list?
sewardjde4a1d02002-03-22 01:27:54 +00001021static
nethercote7ac7f7b2004-11-02 12:36:02 +00001022SizeT listNo_to_pszB_max ( UInt listNo )
sewardjde4a1d02002-03-22 01:27:54 +00001023{
njn6e6588c2005-03-13 18:52:48 +00001024 vg_assert(listNo <= N_MALLOC_LISTS);
1025 if (listNo == N_MALLOC_LISTS-1) {
nethercote2d5b8162004-08-11 09:40:52 +00001026 return MAX_PSZB;
sewardjde4a1d02002-03-22 01:27:54 +00001027 } else {
nethercote2d5b8162004-08-11 09:40:52 +00001028 return listNo_to_pszB_min(listNo+1) - 1;
sewardjde4a1d02002-03-22 01:27:54 +00001029 }
1030}
1031
1032
1033/* A nasty hack to try and reduce fragmentation. Try and replace
1034 a->freelist[lno] with another block on the same list but with a
1035 lower address, with the idea of attempting to recycle the same
1036 blocks rather than cruise through the address space. */
sewardjde4a1d02002-03-22 01:27:54 +00001037static
nethercote7ac7f7b2004-11-02 12:36:02 +00001038void swizzle ( Arena* a, UInt lno )
sewardjde4a1d02002-03-22 01:27:54 +00001039{
nethercote2d5b8162004-08-11 09:40:52 +00001040 Block* p_best;
1041 Block* pp;
1042 Block* pn;
nethercote7ac7f7b2004-11-02 12:36:02 +00001043 UInt i;
sewardjde4a1d02002-03-22 01:27:54 +00001044
1045 p_best = a->freelist[lno];
1046 if (p_best == NULL) return;
1047
1048 pn = pp = p_best;
njn2bf9ba62005-12-25 02:47:12 +00001049
1050 // This loop bound was 20 for a long time, but experiments showed that
1051 // reducing it to 10 gave the same result in all the tests, and 5 got the
1052 // same result in 85--100% of cases. And it's called often enough to be
1053 // noticeable in programs that allocated a lot.
1054 for (i = 0; i < 5; i++) {
nethercote2d5b8162004-08-11 09:40:52 +00001055 pn = get_next_b(pn);
1056 pp = get_prev_b(pp);
sewardjde4a1d02002-03-22 01:27:54 +00001057 if (pn < p_best) p_best = pn;
1058 if (pp < p_best) p_best = pp;
1059 }
1060 if (p_best < a->freelist[lno]) {
nethercote2d5b8162004-08-11 09:40:52 +00001061# ifdef VERBOSE_MALLOC
sewardj9c606bd2008-09-18 18:12:50 +00001062 VG_(printf)("retreat by %ld\n", (Word)(a->freelist[lno] - p_best));
sewardjde4a1d02002-03-22 01:27:54 +00001063# endif
1064 a->freelist[lno] = p_best;
1065 }
1066}
1067
1068
1069/*------------------------------------------------------------*/
sewardjde4a1d02002-03-22 01:27:54 +00001070/*--- Sanity-check/debugging machinery. ---*/
1071/*------------------------------------------------------------*/
1072
njn6e6588c2005-03-13 18:52:48 +00001073#define REDZONE_LO_MASK 0x31
1074#define REDZONE_HI_MASK 0x7c
nethercote2d5b8162004-08-11 09:40:52 +00001075
nethercote7ac7f7b2004-11-02 12:36:02 +00001076// Do some crude sanity checks on a Block.
sewardjde4a1d02002-03-22 01:27:54 +00001077static
nethercote2d5b8162004-08-11 09:40:52 +00001078Bool blockSane ( Arena* a, Block* b )
sewardjde4a1d02002-03-22 01:27:54 +00001079{
1080# define BLEAT(str) VG_(printf)("blockSane: fail -- %s\n",str)
nethercote7ac7f7b2004-11-02 12:36:02 +00001081 UInt i;
njn402c8612005-08-23 22:11:20 +00001082 // The lo and hi size fields will be checked (indirectly) by the call
1083 // to get_rz_hi_byte().
njn472cc7c2005-07-17 17:20:30 +00001084 if (!a->clientmem && is_inuse_block(b)) {
philippe72faf102012-03-11 22:24:03 +00001085 // In the inner, for memcheck sake, temporarily mark redzone accessible.
1086 INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED
1087 (b + hp_overhead_szB() + sizeof(SizeT), a->rz_szB));
1088 INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED
1089 (b + get_bszB(b)
1090 - sizeof(SizeT) - a->rz_szB, a->rz_szB));
nethercote2d5b8162004-08-11 09:40:52 +00001091 for (i = 0; i < a->rz_szB; i++) {
njn1dcee092009-02-24 03:07:37 +00001092 if (get_rz_lo_byte(b, i) !=
njn6e6588c2005-03-13 18:52:48 +00001093 (UByte)(((Addr)b&0xff) ^ REDZONE_LO_MASK))
nethercote2d5b8162004-08-11 09:40:52 +00001094 {BLEAT("redzone-lo");return False;}
njn1dcee092009-02-24 03:07:37 +00001095 if (get_rz_hi_byte(b, i) !=
njn6e6588c2005-03-13 18:52:48 +00001096 (UByte)(((Addr)b&0xff) ^ REDZONE_HI_MASK))
nethercote2d5b8162004-08-11 09:40:52 +00001097 {BLEAT("redzone-hi");return False;}
sewardjde4a1d02002-03-22 01:27:54 +00001098 }
philippe72faf102012-03-11 22:24:03 +00001099 INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS
1100 (b + hp_overhead_szB() + sizeof(SizeT), a->rz_szB));
1101 INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS
1102 (b + get_bszB(b)
1103 - sizeof(SizeT) - a->rz_szB, a->rz_szB));
sewardjde4a1d02002-03-22 01:27:54 +00001104 }
1105 return True;
1106# undef BLEAT
1107}
1108
nethercote2d5b8162004-08-11 09:40:52 +00001109// Print superblocks (only for debugging).
sewardjde4a1d02002-03-22 01:27:54 +00001110static
1111void ppSuperblocks ( Arena* a )
1112{
sewardj0b3fd2d2007-08-21 10:55:26 +00001113 UInt i, j, blockno = 1;
njnd0e685c2005-07-17 17:55:42 +00001114 SizeT b_bszB;
sewardjde4a1d02002-03-22 01:27:54 +00001115
sewardj0b3fd2d2007-08-21 10:55:26 +00001116 for (j = 0; j < a->sblocks_used; ++j) {
1117 Superblock * sb = a->sblocks[j];
1118
sewardjde4a1d02002-03-22 01:27:54 +00001119 VG_(printf)( "\n" );
sewardjd8b93462011-09-10 10:17:35 +00001120 VG_(printf)( "superblock %d at %p %s, sb->n_pl_bs = %lu\n",
sewardjd043de92011-09-26 11:28:20 +00001121 blockno++, sb, (sb->unsplittable ? "unsplittable" : ""),
sewardjd8b93462011-09-10 10:17:35 +00001122 sb->n_payload_bytes);
njnd0e685c2005-07-17 17:55:42 +00001123 for (i = 0; i < sb->n_payload_bytes; i += b_bszB) {
1124 Block* b = (Block*)&sb->payload_bytes[i];
1125 b_bszB = get_bszB(b);
njn8a7b41b2007-09-23 00:51:24 +00001126 VG_(printf)( " block at %d, bszB %lu: ", i, b_bszB );
njn472cc7c2005-07-17 17:20:30 +00001127 VG_(printf)( "%s, ", is_inuse_block(b) ? "inuse" : "free");
nethercote2d5b8162004-08-11 09:40:52 +00001128 VG_(printf)( "%s\n", blockSane(a, b) ? "ok" : "BAD" );
sewardjde4a1d02002-03-22 01:27:54 +00001129 }
nethercote2d5b8162004-08-11 09:40:52 +00001130 vg_assert(i == sb->n_payload_bytes); // no overshoot at end of Sb
sewardjde4a1d02002-03-22 01:27:54 +00001131 }
1132 VG_(printf)( "end of superblocks\n\n" );
1133}
1134
nethercote2d5b8162004-08-11 09:40:52 +00001135// Sanity check both the superblocks and the chains.
nethercote885dd912004-08-03 23:14:00 +00001136static void sanity_check_malloc_arena ( ArenaId aid )
sewardjde4a1d02002-03-22 01:27:54 +00001137{
sewardj0b3fd2d2007-08-21 10:55:26 +00001138 UInt i, j, superblockctr, blockctr_sb, blockctr_li;
nethercote7ac7f7b2004-11-02 12:36:02 +00001139 UInt blockctr_sb_free, listno;
1140 SizeT b_bszB, b_pszB, list_min_pszB, list_max_pszB;
sewardj0b3fd2d2007-08-21 10:55:26 +00001141 Bool thisFree, lastWasFree, sblockarrOK;
nethercote2d5b8162004-08-11 09:40:52 +00001142 Block* b;
1143 Block* b_prev;
nethercote7ac7f7b2004-11-02 12:36:02 +00001144 SizeT arena_bytes_on_loan;
sewardjde4a1d02002-03-22 01:27:54 +00001145 Arena* a;
1146
nethercote885dd912004-08-03 23:14:00 +00001147# define BOMB VG_(core_panic)("sanity_check_malloc_arena")
sewardjde4a1d02002-03-22 01:27:54 +00001148
1149 a = arenaId_to_ArenaP(aid);
sewardj0b3fd2d2007-08-21 10:55:26 +00001150
1151 // Check the superblock array.
1152 sblockarrOK
1153 = a->sblocks != NULL
1154 && a->sblocks_size >= SBLOCKS_SIZE_INITIAL
1155 && a->sblocks_used <= a->sblocks_size
1156 && (a->sblocks_size == SBLOCKS_SIZE_INITIAL
1157 ? (a->sblocks == &a->sblocks_initial[0])
1158 : (a->sblocks != &a->sblocks_initial[0]));
1159 if (!sblockarrOK) {
1160 VG_(printf)("sanity_check_malloc_arena: sblock array BAD\n");
1161 BOMB;
1162 }
1163
nethercote2d5b8162004-08-11 09:40:52 +00001164 // First, traverse all the superblocks, inspecting the Blocks in each.
sewardjde4a1d02002-03-22 01:27:54 +00001165 superblockctr = blockctr_sb = blockctr_sb_free = 0;
1166 arena_bytes_on_loan = 0;
sewardj0b3fd2d2007-08-21 10:55:26 +00001167 for (j = 0; j < a->sblocks_used; ++j) {
1168 Superblock * sb = a->sblocks[j];
sewardjde4a1d02002-03-22 01:27:54 +00001169 lastWasFree = False;
1170 superblockctr++;
nethercote2d5b8162004-08-11 09:40:52 +00001171 for (i = 0; i < sb->n_payload_bytes; i += mk_plain_bszB(b_bszB)) {
sewardjde4a1d02002-03-22 01:27:54 +00001172 blockctr_sb++;
nethercote2d5b8162004-08-11 09:40:52 +00001173 b = (Block*)&sb->payload_bytes[i];
njnd0e685c2005-07-17 17:55:42 +00001174 b_bszB = get_bszB_as_is(b);
sewardjde4a1d02002-03-22 01:27:54 +00001175 if (!blockSane(a, b)) {
njn8a7b41b2007-09-23 00:51:24 +00001176 VG_(printf)("sanity_check_malloc_arena: sb %p, block %d "
1177 "(bszB %lu): BAD\n", sb, i, b_bszB );
sewardjde4a1d02002-03-22 01:27:54 +00001178 BOMB;
1179 }
njn472cc7c2005-07-17 17:20:30 +00001180 thisFree = !is_inuse_block(b);
sewardjde4a1d02002-03-22 01:27:54 +00001181 if (thisFree && lastWasFree) {
njn8a7b41b2007-09-23 00:51:24 +00001182 VG_(printf)("sanity_check_malloc_arena: sb %p, block %d "
1183 "(bszB %lu): UNMERGED FREES\n", sb, i, b_bszB );
sewardjde4a1d02002-03-22 01:27:54 +00001184 BOMB;
1185 }
sewardjde4a1d02002-03-22 01:27:54 +00001186 if (thisFree) blockctr_sb_free++;
sewardj0b3fd2d2007-08-21 10:55:26 +00001187 if (!thisFree)
nethercote2d5b8162004-08-11 09:40:52 +00001188 arena_bytes_on_loan += bszB_to_pszB(a, b_bszB);
1189 lastWasFree = thisFree;
sewardjde4a1d02002-03-22 01:27:54 +00001190 }
nethercote2d5b8162004-08-11 09:40:52 +00001191 if (i > sb->n_payload_bytes) {
nethercote885dd912004-08-03 23:14:00 +00001192 VG_(printf)( "sanity_check_malloc_arena: sb %p: last block "
sewardjde4a1d02002-03-22 01:27:54 +00001193 "overshoots end\n", sb);
1194 BOMB;
1195 }
sewardjde4a1d02002-03-22 01:27:54 +00001196 }
1197
sewardj7d1064a2011-02-23 13:18:56 +00001198 if (arena_bytes_on_loan != a->stats__bytes_on_loan) {
nethercote2d5b8162004-08-11 09:40:52 +00001199# ifdef VERBOSE_MALLOC
sewardjd8b93462011-09-10 10:17:35 +00001200 VG_(printf)( "sanity_check_malloc_arena: a->bytes_on_loan %lu, "
1201 "arena_bytes_on_loan %lu: "
nethercote2d5b8162004-08-11 09:40:52 +00001202 "MISMATCH\n", a->bytes_on_loan, arena_bytes_on_loan);
1203# endif
sewardjde4a1d02002-03-22 01:27:54 +00001204 ppSuperblocks(a);
1205 BOMB;
1206 }
1207
1208 /* Second, traverse each list, checking that the back pointers make
1209 sense, counting blocks encountered, and checking that each block
1210 is an appropriate size for this list. */
1211 blockctr_li = 0;
njn6e6588c2005-03-13 18:52:48 +00001212 for (listno = 0; listno < N_MALLOC_LISTS; listno++) {
nethercote2d5b8162004-08-11 09:40:52 +00001213 list_min_pszB = listNo_to_pszB_min(listno);
1214 list_max_pszB = listNo_to_pszB_max(listno);
sewardjde4a1d02002-03-22 01:27:54 +00001215 b = a->freelist[listno];
1216 if (b == NULL) continue;
1217 while (True) {
1218 b_prev = b;
nethercote2d5b8162004-08-11 09:40:52 +00001219 b = get_next_b(b);
1220 if (get_prev_b(b) != b_prev) {
nethercote885dd912004-08-03 23:14:00 +00001221 VG_(printf)( "sanity_check_malloc_arena: list %d at %p: "
sewardj0b3fd2d2007-08-21 10:55:26 +00001222 "BAD LINKAGE\n",
sewardjde4a1d02002-03-22 01:27:54 +00001223 listno, b );
1224 BOMB;
1225 }
njn089f51f2005-07-17 18:12:00 +00001226 b_pszB = get_pszB(a, b);
nethercote2d5b8162004-08-11 09:40:52 +00001227 if (b_pszB < list_min_pszB || b_pszB > list_max_pszB) {
sewardj0b3fd2d2007-08-21 10:55:26 +00001228 VG_(printf)(
nethercote885dd912004-08-03 23:14:00 +00001229 "sanity_check_malloc_arena: list %d at %p: "
njn8a7b41b2007-09-23 00:51:24 +00001230 "WRONG CHAIN SIZE %luB (%luB, %luB)\n",
nethercote2d5b8162004-08-11 09:40:52 +00001231 listno, b, b_pszB, list_min_pszB, list_max_pszB );
sewardjde4a1d02002-03-22 01:27:54 +00001232 BOMB;
1233 }
1234 blockctr_li++;
1235 if (b == a->freelist[listno]) break;
1236 }
1237 }
1238
1239 if (blockctr_sb_free != blockctr_li) {
nethercote2d5b8162004-08-11 09:40:52 +00001240# ifdef VERBOSE_MALLOC
1241 VG_(printf)( "sanity_check_malloc_arena: BLOCK COUNT MISMATCH "
1242 "(via sbs %d, via lists %d)\n",
1243 blockctr_sb_free, blockctr_li );
1244# endif
sewardjde4a1d02002-03-22 01:27:54 +00001245 ppSuperblocks(a);
1246 BOMB;
1247 }
1248
nethercote885dd912004-08-03 23:14:00 +00001249 if (VG_(clo_verbosity) > 2)
1250 VG_(message)(Vg_DebugMsg,
njn669ef072005-03-13 05:46:57 +00001251 "%8s: %2d sbs, %5d bs, %2d/%-2d free bs, "
sewardj738856f2009-07-15 14:48:32 +00001252 "%7ld mmap, %7ld loan\n",
nethercote885dd912004-08-03 23:14:00 +00001253 a->name,
1254 superblockctr,
1255 blockctr_sb, blockctr_sb_free, blockctr_li,
sewardj7d1064a2011-02-23 13:18:56 +00001256 a->stats__bytes_mmaped, a->stats__bytes_on_loan);
sewardjde4a1d02002-03-22 01:27:54 +00001257# undef BOMB
1258}
1259
1260
sewardj9c606bd2008-09-18 18:12:50 +00001261#define N_AN_CCS 1000
1262
1263typedef struct { ULong nBytes; ULong nBlocks; HChar* cc; } AnCC;
1264
1265static AnCC anCCs[N_AN_CCS];
1266
1267static Int cmp_AnCC_by_vol ( void* v1, void* v2 ) {
1268 AnCC* ancc1 = (AnCC*)v1;
1269 AnCC* ancc2 = (AnCC*)v2;
1270 if (ancc1->nBytes < ancc2->nBytes) return -1;
1271 if (ancc1->nBytes > ancc2->nBytes) return 1;
1272 return 0;
1273}
1274
1275static void cc_analyse_alloc_arena ( ArenaId aid )
1276{
1277 Word i, j, k;
1278 Arena* a;
1279 Block* b;
1280 Bool thisFree, lastWasFree;
1281 SizeT b_bszB;
1282
1283 HChar* cc;
1284 UInt n_ccs = 0;
1285 //return;
1286 a = arenaId_to_ArenaP(aid);
1287 if (a->name == NULL) {
1288 /* arena is not in use, is not initialised and will fail the
1289 sanity check that follows. */
1290 return;
1291 }
1292
1293 sanity_check_malloc_arena(aid);
1294
1295 VG_(printf)(
sewardjd8b93462011-09-10 10:17:35 +00001296 "-------- Arena \"%s\": %lu/%lu max/curr mmap'd, "
sewardjd043de92011-09-26 11:28:20 +00001297 "%llu/%llu unsplit/split sb unmmap'd, "
philipped99c26a2012-07-31 22:17:28 +00001298 "%lu/%lu max/curr on_loan %lu rzB --------\n",
sewardjd8b93462011-09-10 10:17:35 +00001299 a->name, a->stats__bytes_mmaped_max, a->stats__bytes_mmaped,
sewardjd043de92011-09-26 11:28:20 +00001300 a->stats__nreclaim_unsplit, a->stats__nreclaim_split,
philipped99c26a2012-07-31 22:17:28 +00001301 a->stats__bytes_on_loan_max, a->stats__bytes_on_loan,
1302 a->rz_szB
sewardj9c606bd2008-09-18 18:12:50 +00001303 );
1304
1305 for (j = 0; j < a->sblocks_used; ++j) {
1306 Superblock * sb = a->sblocks[j];
1307 lastWasFree = False;
1308 for (i = 0; i < sb->n_payload_bytes; i += mk_plain_bszB(b_bszB)) {
1309 b = (Block*)&sb->payload_bytes[i];
1310 b_bszB = get_bszB_as_is(b);
1311 if (!blockSane(a, b)) {
1312 VG_(printf)("sanity_check_malloc_arena: sb %p, block %ld "
1313 "(bszB %lu): BAD\n", sb, i, b_bszB );
1314 tl_assert(0);
1315 }
1316 thisFree = !is_inuse_block(b);
1317 if (thisFree && lastWasFree) {
1318 VG_(printf)("sanity_check_malloc_arena: sb %p, block %ld "
1319 "(bszB %lu): UNMERGED FREES\n", sb, i, b_bszB );
1320 tl_assert(0);
1321 }
1322 lastWasFree = thisFree;
1323
1324 if (thisFree) continue;
1325
1326 if (0)
1327 VG_(printf)("block: inUse=%d pszB=%d cc=%s\n",
1328 (Int)(!thisFree),
1329 (Int)bszB_to_pszB(a, b_bszB),
1330 get_cc(b));
1331 cc = get_cc(b);
1332 tl_assert(cc);
1333 for (k = 0; k < n_ccs; k++) {
1334 tl_assert(anCCs[k].cc);
1335 if (0 == VG_(strcmp)(cc, anCCs[k].cc))
1336 break;
1337 }
1338 tl_assert(k >= 0 && k <= n_ccs);
1339
1340 if (k == n_ccs) {
1341 tl_assert(n_ccs < N_AN_CCS-1);
1342 n_ccs++;
1343 anCCs[k].nBytes = 0;
1344 anCCs[k].nBlocks = 0;
1345 anCCs[k].cc = cc;
1346 }
1347
1348 tl_assert(k >= 0 && k < n_ccs && k < N_AN_CCS);
1349 anCCs[k].nBytes += (ULong)bszB_to_pszB(a, b_bszB);
1350 anCCs[k].nBlocks++;
1351 }
1352 if (i > sb->n_payload_bytes) {
1353 VG_(printf)( "sanity_check_malloc_arena: sb %p: last block "
1354 "overshoots end\n", sb);
1355 tl_assert(0);
1356 }
1357 }
1358
1359 VG_(ssort)( &anCCs[0], n_ccs, sizeof(anCCs[0]), cmp_AnCC_by_vol );
1360
1361 for (k = 0; k < n_ccs; k++) {
1362 VG_(printf)("%'13llu in %'9llu: %s\n",
1363 anCCs[k].nBytes, anCCs[k].nBlocks, anCCs[k].cc );
1364 }
1365
1366 VG_(printf)("\n");
1367}
1368
1369
nethercote885dd912004-08-03 23:14:00 +00001370void VG_(sanity_check_malloc_all) ( void )
sewardjde4a1d02002-03-22 01:27:54 +00001371{
nethercote7ac7f7b2004-11-02 12:36:02 +00001372 UInt i;
sewardj0b3fd2d2007-08-21 10:55:26 +00001373 for (i = 0; i < VG_N_ARENAS; i++) {
1374 if (i == VG_AR_CLIENT && !client_inited)
1375 continue;
nethercote885dd912004-08-03 23:14:00 +00001376 sanity_check_malloc_arena ( i );
sewardj0b3fd2d2007-08-21 10:55:26 +00001377 }
sewardjde4a1d02002-03-22 01:27:54 +00001378}
1379
sewardjde4a1d02002-03-22 01:27:54 +00001380
nethercote2d5b8162004-08-11 09:40:52 +00001381/*------------------------------------------------------------*/
1382/*--- Creating and deleting blocks. ---*/
1383/*------------------------------------------------------------*/
1384
1385// Mark the bytes at b .. b+bszB-1 as not in use, and add them to the
1386// relevant free list.
1387
1388static
nethercote7ac7f7b2004-11-02 12:36:02 +00001389void mkFreeBlock ( Arena* a, Block* b, SizeT bszB, UInt b_lno )
jsewardb1a26ae2004-03-14 03:06:37 +00001390{
nethercote7ac7f7b2004-11-02 12:36:02 +00001391 SizeT pszB = bszB_to_pszB(a, bszB);
nethercote2d5b8162004-08-11 09:40:52 +00001392 vg_assert(b_lno == pszB_to_listNo(pszB));
philippe72faf102012-03-11 22:24:03 +00001393 INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(b, bszB));
nethercote2d5b8162004-08-11 09:40:52 +00001394 // Set the size fields and indicate not-in-use.
njn8d3f8452005-07-20 04:12:41 +00001395 set_bszB(b, mk_free_bszB(bszB));
nethercote2d5b8162004-08-11 09:40:52 +00001396
1397 // Add to the relevant list.
1398 if (a->freelist[b_lno] == NULL) {
1399 set_prev_b(b, b);
1400 set_next_b(b, b);
1401 a->freelist[b_lno] = b;
1402 } else {
1403 Block* b_prev = get_prev_b(a->freelist[b_lno]);
1404 Block* b_next = a->freelist[b_lno];
1405 set_next_b(b_prev, b);
1406 set_prev_b(b_next, b);
1407 set_next_b(b, b_next);
1408 set_prev_b(b, b_prev);
1409 }
1410# ifdef DEBUG_MALLOC
1411 (void)blockSane(a,b);
1412# endif
1413}
1414
1415// Mark the bytes at b .. b+bszB-1 as in use, and set up the block
1416// appropriately.
1417static
nethercote7ac7f7b2004-11-02 12:36:02 +00001418void mkInuseBlock ( Arena* a, Block* b, SizeT bszB )
nethercote2d5b8162004-08-11 09:40:52 +00001419{
nethercote7ac7f7b2004-11-02 12:36:02 +00001420 UInt i;
nethercote2d5b8162004-08-11 09:40:52 +00001421 vg_assert(bszB >= min_useful_bszB(a));
philippe72faf102012-03-11 22:24:03 +00001422 INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(b, bszB));
njn8d3f8452005-07-20 04:12:41 +00001423 set_bszB(b, mk_inuse_bszB(bszB));
nethercote2d5b8162004-08-11 09:40:52 +00001424 set_prev_b(b, NULL); // Take off freelist
1425 set_next_b(b, NULL); // ditto
1426 if (!a->clientmem) {
1427 for (i = 0; i < a->rz_szB; i++) {
njn1dcee092009-02-24 03:07:37 +00001428 set_rz_lo_byte(b, i, (UByte)(((Addr)b&0xff) ^ REDZONE_LO_MASK));
1429 set_rz_hi_byte(b, i, (UByte)(((Addr)b&0xff) ^ REDZONE_HI_MASK));
nethercote2d5b8162004-08-11 09:40:52 +00001430 }
1431 }
1432# ifdef DEBUG_MALLOC
1433 (void)blockSane(a,b);
1434# endif
1435}
1436
1437// Remove a block from a given list. Does no sanity checking.
1438static
nethercote7ac7f7b2004-11-02 12:36:02 +00001439void unlinkBlock ( Arena* a, Block* b, UInt listno )
nethercote2d5b8162004-08-11 09:40:52 +00001440{
njn6e6588c2005-03-13 18:52:48 +00001441 vg_assert(listno < N_MALLOC_LISTS);
nethercote2d5b8162004-08-11 09:40:52 +00001442 if (get_prev_b(b) == b) {
1443 // Only one element in the list; treat it specially.
1444 vg_assert(get_next_b(b) == b);
1445 a->freelist[listno] = NULL;
1446 } else {
1447 Block* b_prev = get_prev_b(b);
1448 Block* b_next = get_next_b(b);
1449 a->freelist[listno] = b_prev;
1450 set_next_b(b_prev, b_next);
1451 set_prev_b(b_next, b_prev);
1452 swizzle ( a, listno );
1453 }
1454 set_prev_b(b, NULL);
1455 set_next_b(b, NULL);
jsewardb1a26ae2004-03-14 03:06:37 +00001456}
1457
1458
sewardjde4a1d02002-03-22 01:27:54 +00001459/*------------------------------------------------------------*/
njn25e49d8e72002-09-23 09:36:25 +00001460/*--- Core-visible functions. ---*/
sewardjde4a1d02002-03-22 01:27:54 +00001461/*------------------------------------------------------------*/
1462
nethercote2d5b8162004-08-11 09:40:52 +00001463// Align the request size.
1464static __inline__
nethercote7ac7f7b2004-11-02 12:36:02 +00001465SizeT align_req_pszB ( SizeT req_pszB )
nethercote2d5b8162004-08-11 09:40:52 +00001466{
nethercote7ac7f7b2004-11-02 12:36:02 +00001467 SizeT n = VG_MIN_MALLOC_SZB-1;
nethercote2d5b8162004-08-11 09:40:52 +00001468 return ((req_pszB + n) & (~n));
1469}
1470
sewardj9c606bd2008-09-18 18:12:50 +00001471void* VG_(arena_malloc) ( ArenaId aid, HChar* cc, SizeT req_pszB )
sewardjde4a1d02002-03-22 01:27:54 +00001472{
nethercote7ac7f7b2004-11-02 12:36:02 +00001473 SizeT req_bszB, frag_bszB, b_bszB;
sewardj0b3fd2d2007-08-21 10:55:26 +00001474 UInt lno, i;
sewardjd8b93462011-09-10 10:17:35 +00001475 Superblock* new_sb = NULL;
nethercote2d5b8162004-08-11 09:40:52 +00001476 Block* b = NULL;
sewardjde4a1d02002-03-22 01:27:54 +00001477 Arena* a;
jsewardb1a26ae2004-03-14 03:06:37 +00001478 void* v;
sewardj7d1064a2011-02-23 13:18:56 +00001479 UWord stats__nsearches = 0;
sewardjde4a1d02002-03-22 01:27:54 +00001480
sewardj45f4e7c2005-09-27 19:20:21 +00001481 ensure_mm_init(aid);
sewardjde4a1d02002-03-22 01:27:54 +00001482 a = arenaId_to_ArenaP(aid);
1483
nethercote7ac7f7b2004-11-02 12:36:02 +00001484 vg_assert(req_pszB < MAX_PSZB);
nethercote2d5b8162004-08-11 09:40:52 +00001485 req_pszB = align_req_pszB(req_pszB);
1486 req_bszB = pszB_to_bszB(a, req_pszB);
sewardjde4a1d02002-03-22 01:27:54 +00001487
sewardj9c606bd2008-09-18 18:12:50 +00001488 // You must provide a cost-center name against which to charge
1489 // this allocation; it isn't optional.
1490 vg_assert(cc);
1491
nethercote2d5b8162004-08-11 09:40:52 +00001492 // Scan through all the big-enough freelists for a block.
njn4ab6d532007-10-16 23:18:06 +00001493 //
1494 // Nb: this scanning might be expensive in some cases. Eg. if you
1495 // allocate lots of small objects without freeing them, but no
1496 // medium-sized objects, it will repeatedly scanning through the whole
1497 // list, and each time not find any free blocks until the last element.
1498 //
1499 // If this becomes a noticeable problem... the loop answers the question
1500 // "where is the first nonempty list above me?" And most of the time,
1501 // you ask the same question and get the same answer. So it would be
1502 // good to somehow cache the results of previous searches.
1503 // One possibility is an array (with N_MALLOC_LISTS elements) of
1504 // shortcuts. shortcut[i] would give the index number of the nearest
1505 // larger list above list i which is non-empty. Then this loop isn't
1506 // necessary. However, we'd have to modify some section [ .. i-1] of the
1507 // shortcut array every time a list [i] changes from empty to nonempty or
1508 // back. This would require care to avoid pathological worst-case
1509 // behaviour.
1510 //
njn6e6588c2005-03-13 18:52:48 +00001511 for (lno = pszB_to_listNo(req_pszB); lno < N_MALLOC_LISTS; lno++) {
sewardj7d1064a2011-02-23 13:18:56 +00001512 UWord nsearches_this_level = 0;
sewardjde4a1d02002-03-22 01:27:54 +00001513 b = a->freelist[lno];
nethercote2d5b8162004-08-11 09:40:52 +00001514 if (NULL == b) continue; // If this list is empty, try the next one.
sewardjde4a1d02002-03-22 01:27:54 +00001515 while (True) {
sewardj7d1064a2011-02-23 13:18:56 +00001516 stats__nsearches++;
1517 nsearches_this_level++;
1518 if (UNLIKELY(nsearches_this_level >= 100)
1519 && lno < N_MALLOC_LISTS-1) {
1520 /* Avoid excessive scanning on this freelist, and instead
1521 try the next one up. But first, move this freelist's
1522 start pointer one element along, so as to ensure that
1523 subsequent searches of this list don't endlessly
1524 revisit only these 100 elements, but in fact slowly
1525 progress through the entire list. */
1526 b = a->freelist[lno];
1527 vg_assert(b); // this list must be nonempty!
1528 a->freelist[lno] = get_next_b(b); // step one along
1529 break;
1530 }
njnd0e685c2005-07-17 17:55:42 +00001531 b_bszB = get_bszB(b);
nethercote2d5b8162004-08-11 09:40:52 +00001532 if (b_bszB >= req_bszB) goto obtained_block; // success!
1533 b = get_next_b(b);
1534 if (b == a->freelist[lno]) break; // traversed entire freelist
sewardjde4a1d02002-03-22 01:27:54 +00001535 }
sewardjde4a1d02002-03-22 01:27:54 +00001536 }
1537
nethercote2d5b8162004-08-11 09:40:52 +00001538 // If we reach here, no suitable block found, allocate a new superblock
njn6e6588c2005-03-13 18:52:48 +00001539 vg_assert(lno == N_MALLOC_LISTS);
nethercote2d5b8162004-08-11 09:40:52 +00001540 new_sb = newSuperblock(a, req_bszB);
1541 if (NULL == new_sb) {
1542 // Should only fail if for client, otherwise, should have aborted
1543 // already.
1544 vg_assert(VG_AR_CLIENT == aid);
1545 return NULL;
sewardjde4a1d02002-03-22 01:27:54 +00001546 }
sewardj0b3fd2d2007-08-21 10:55:26 +00001547
1548 vg_assert(a->sblocks_used <= a->sblocks_size);
1549 if (a->sblocks_used == a->sblocks_size) {
1550 Superblock ** array;
1551 SysRes sres = VG_(am_sbrk_anon_float_valgrind)(sizeof(Superblock *) *
1552 a->sblocks_size * 2);
njncda2f0f2009-05-18 02:12:08 +00001553 if (sr_isError(sres)) {
sewardj0b3fd2d2007-08-21 10:55:26 +00001554 VG_(out_of_memory_NORETURN)("arena_init", sizeof(Superblock *) *
1555 a->sblocks_size * 2);
1556 /* NOTREACHED */
1557 }
njncda2f0f2009-05-18 02:12:08 +00001558 array = (Superblock**)(AddrH)sr_Res(sres);
sewardj0b3fd2d2007-08-21 10:55:26 +00001559 for (i = 0; i < a->sblocks_used; ++i) array[i] = a->sblocks[i];
1560
1561 a->sblocks_size *= 2;
1562 a->sblocks = array;
1563 VG_(debugLog)(1, "mallocfree",
1564 "sblock array for arena `%s' resized to %ld\n",
1565 a->name, a->sblocks_size);
1566 }
1567
1568 vg_assert(a->sblocks_used < a->sblocks_size);
1569
1570 i = a->sblocks_used;
1571 while (i > 0) {
1572 if (a->sblocks[i-1] > new_sb) {
1573 a->sblocks[i] = a->sblocks[i-1];
1574 } else {
1575 break;
1576 }
1577 --i;
1578 }
1579 a->sblocks[i] = new_sb;
1580 a->sblocks_used++;
1581
nethercote2d5b8162004-08-11 09:40:52 +00001582 b = (Block*)&new_sb->payload_bytes[0];
1583 lno = pszB_to_listNo(bszB_to_pszB(a, new_sb->n_payload_bytes));
1584 mkFreeBlock ( a, b, new_sb->n_payload_bytes, lno);
sewardj94c8eb42008-09-19 20:13:39 +00001585 if (VG_(clo_profile_heap))
1586 set_cc(b, "admin.free-new-sb-1");
nethercote2d5b8162004-08-11 09:40:52 +00001587 // fall through
sewardjde4a1d02002-03-22 01:27:54 +00001588
nethercote2d5b8162004-08-11 09:40:52 +00001589 obtained_block:
1590 // Ok, we can allocate from b, which lives in list lno.
sewardjde4a1d02002-03-22 01:27:54 +00001591 vg_assert(b != NULL);
njn6e6588c2005-03-13 18:52:48 +00001592 vg_assert(lno < N_MALLOC_LISTS);
sewardjde4a1d02002-03-22 01:27:54 +00001593 vg_assert(a->freelist[lno] != NULL);
njnd0e685c2005-07-17 17:55:42 +00001594 b_bszB = get_bszB(b);
nethercote2d5b8162004-08-11 09:40:52 +00001595 // req_bszB is the size of the block we are after. b_bszB is the
1596 // size of what we've actually got. */
1597 vg_assert(b_bszB >= req_bszB);
sewardjde4a1d02002-03-22 01:27:54 +00001598
nethercote2d5b8162004-08-11 09:40:52 +00001599 // Could we split this block and still get a useful fragment?
sewardjd043de92011-09-26 11:28:20 +00001600 // A block in an unsplittable superblock can never be splitted.
nethercote2d5b8162004-08-11 09:40:52 +00001601 frag_bszB = b_bszB - req_bszB;
sewardjd8b93462011-09-10 10:17:35 +00001602 if (frag_bszB >= min_useful_bszB(a)
sewardjd043de92011-09-26 11:28:20 +00001603 && (NULL == new_sb || ! new_sb->unsplittable)) {
nethercote2d5b8162004-08-11 09:40:52 +00001604 // Yes, split block in two, put the fragment on the appropriate free
1605 // list, and update b_bszB accordingly.
1606 // printf( "split %dB into %dB and %dB\n", b_bszB, req_bszB, frag_bszB );
sewardjde4a1d02002-03-22 01:27:54 +00001607 unlinkBlock(a, b, lno);
nethercote2d5b8162004-08-11 09:40:52 +00001608 mkInuseBlock(a, b, req_bszB);
sewardj94c8eb42008-09-19 20:13:39 +00001609 if (VG_(clo_profile_heap))
1610 set_cc(b, cc);
nethercote2d5b8162004-08-11 09:40:52 +00001611 mkFreeBlock(a, &b[req_bszB], frag_bszB,
1612 pszB_to_listNo(bszB_to_pszB(a, frag_bszB)));
sewardj94c8eb42008-09-19 20:13:39 +00001613 if (VG_(clo_profile_heap))
1614 set_cc(&b[req_bszB], "admin.fragmentation-1");
njnd0e685c2005-07-17 17:55:42 +00001615 b_bszB = get_bszB(b);
nethercote2d5b8162004-08-11 09:40:52 +00001616 } else {
1617 // No, mark as in use and use as-is.
1618 unlinkBlock(a, b, lno);
1619 mkInuseBlock(a, b, b_bszB);
sewardj94c8eb42008-09-19 20:13:39 +00001620 if (VG_(clo_profile_heap))
1621 set_cc(b, cc);
sewardjde4a1d02002-03-22 01:27:54 +00001622 }
sewardjde4a1d02002-03-22 01:27:54 +00001623
nethercote2d5b8162004-08-11 09:40:52 +00001624 // Update stats
sewardj7d1064a2011-02-23 13:18:56 +00001625 SizeT loaned = bszB_to_pszB(a, b_bszB);
1626 a->stats__bytes_on_loan += loaned;
1627 if (a->stats__bytes_on_loan > a->stats__bytes_on_loan_max) {
1628 a->stats__bytes_on_loan_max = a->stats__bytes_on_loan;
1629 if (a->stats__bytes_on_loan_max >= a->next_profile_at) {
sewardj9c606bd2008-09-18 18:12:50 +00001630 /* next profile after 10% more growth */
1631 a->next_profile_at
1632 = (SizeT)(
sewardj75f107f2011-09-26 20:17:41 +00001633 (((ULong)a->stats__bytes_on_loan_max) * 105ULL) / 100ULL );
sewardj9c606bd2008-09-18 18:12:50 +00001634 if (VG_(clo_profile_heap))
1635 cc_analyse_alloc_arena(aid);
1636 }
1637 }
sewardj7d1064a2011-02-23 13:18:56 +00001638 a->stats__tot_blocks += (ULong)1;
1639 a->stats__tot_bytes += (ULong)loaned;
1640 a->stats__nsearches += (ULong)stats__nsearches;
sewardjde4a1d02002-03-22 01:27:54 +00001641
1642# ifdef DEBUG_MALLOC
nethercote885dd912004-08-03 23:14:00 +00001643 sanity_check_malloc_arena(aid);
sewardjde4a1d02002-03-22 01:27:54 +00001644# endif
1645
nethercote2d5b8162004-08-11 09:40:52 +00001646 v = get_block_payload(a, b);
1647 vg_assert( (((Addr)v) & (VG_MIN_MALLOC_SZB-1)) == 0 );
sewardjb5f6f512005-03-10 23:59:00 +00001648
philippe72faf102012-03-11 22:24:03 +00001649 // Which size should we pass to VALGRIND_MALLOCLIKE_BLOCK ?
1650 // We have 2 possible options:
1651 // 1. The final resulting usable size.
1652 // 2. The initial (non-aligned) req_pszB.
1653 // Memcheck implements option 2 easily, as the initial requested size
1654 // is maintained in the mc_chunk data structure.
1655 // This is not as easy in the core, as there is no such structure.
1656 // (note: using the aligned req_pszB is not simpler than 2, as
1657 // requesting an aligned req_pszB might still be satisfied by returning
1658 // a (slightly) bigger block than requested if the remaining part of
1659 // of a free block is not big enough to make a free block by itself).
1660 // Implement Sol 2 can be done the following way:
1661 // After having called VALGRIND_MALLOCLIKE_BLOCK, the non accessible
1662 // redzone just after the block can be used to determine the
1663 // initial requested size.
1664 // Currently, not implemented => we use Option 1.
1665 INNER_REQUEST
1666 (VALGRIND_MALLOCLIKE_BLOCK(v,
1667 VG_(arena_malloc_usable_size)(aid, v),
1668 a->rz_szB, False));
sewardja53462a2007-11-24 23:37:07 +00001669
1670 /* For debugging/testing purposes, fill the newly allocated area
1671 with a definite value in an attempt to shake out any
1672 uninitialised uses of the data (by V core / V tools, not by the
1673 client). Testing on 25 Nov 07 with the values 0x00, 0xFF, 0x55,
1674 0xAA showed no differences in the regression tests on
1675 amd64-linux. Note, is disabled by default. */
1676 if (0 && aid != VG_AR_CLIENT)
1677 VG_(memset)(v, 0xAA, (SizeT)req_pszB);
1678
jsewardb1a26ae2004-03-14 03:06:37 +00001679 return v;
sewardjde4a1d02002-03-22 01:27:54 +00001680}
1681
sewardjd043de92011-09-26 11:28:20 +00001682// If arena has already a deferred reclaimed superblock and
1683// this superblock is still reclaimable, then this superblock is first
1684// reclaimed.
1685// sb becomes then the new arena deferred superblock.
1686// Passing NULL as sb allows to reclaim a deferred sb without setting a new
1687// deferred reclaim.
1688static
1689void deferred_reclaimSuperblock ( Arena* a, Superblock* sb)
1690{
1691
1692 if (sb == NULL) {
1693 if (!a->deferred_reclaimed_sb)
1694 // no deferred sb to reclaim now, nothing to do in the future =>
1695 // return directly.
1696 return;
1697
1698 VG_(debugLog)(1, "mallocfree",
1699 "deferred_reclaimSuperblock NULL "
1700 "(prev %p) owner %s/%s\n",
1701 a->deferred_reclaimed_sb,
1702 a->clientmem ? "CLIENT" : "VALGRIND", a->name );
1703 } else
1704 VG_(debugLog)(1, "mallocfree",
1705 "deferred_reclaimSuperblock at %p (pszB %7ld) %s "
1706 "(prev %p) owner %s/%s\n",
1707 sb, sb->n_payload_bytes,
1708 (sb->unsplittable ? "unsplittable" : ""),
1709 a->deferred_reclaimed_sb,
1710 a->clientmem ? "CLIENT" : "VALGRIND", a->name );
1711
1712 if (a->deferred_reclaimed_sb && a->deferred_reclaimed_sb != sb) {
1713 // If we are deferring another block that the current block deferred,
1714 // then if this block can stil be reclaimed, reclaim it now.
1715 // Note that we might have a re-deferred reclaim of the same block
1716 // with a sequence: free (causing a deferred reclaim of sb)
1717 // alloc (using a piece of memory of the deferred sb)
1718 // free of the just alloc-ed block (causing a re-defer).
1719 UByte* def_sb_start;
1720 UByte* def_sb_end;
1721 Superblock* def_sb;
1722 Block* b;
1723
1724 def_sb = a->deferred_reclaimed_sb;
1725 def_sb_start = &def_sb->payload_bytes[0];
1726 def_sb_end = &def_sb->payload_bytes[def_sb->n_payload_bytes - 1];
1727 b = (Block *)def_sb_start;
1728 vg_assert (blockSane(a, b));
1729
1730 // Check if the deferred_reclaimed_sb is still reclaimable.
1731 // If yes, we will execute the reclaim.
1732 if (!is_inuse_block(b)) {
1733 // b (at the beginning of def_sb) is not in use.
1734 UInt b_listno;
1735 SizeT b_bszB, b_pszB;
1736 b_bszB = get_bszB(b);
1737 b_pszB = bszB_to_pszB(a, b_bszB);
1738 if (b + b_bszB-1 == (Block*)def_sb_end) {
1739 // b (not in use) covers the full superblock.
1740 // => def_sb is still reclaimable
1741 // => execute now the reclaim of this def_sb.
1742 b_listno = pszB_to_listNo(b_pszB);
1743 unlinkBlock( a, b, b_listno );
1744 reclaimSuperblock (a, def_sb);
1745 a->deferred_reclaimed_sb = NULL;
1746 }
1747 }
1748 }
1749
1750 // sb (possibly NULL) becomes the new deferred reclaimed superblock.
1751 a->deferred_reclaimed_sb = sb;
1752}
1753
sewardjde4a1d02002-03-22 01:27:54 +00001754
njn25e49d8e72002-09-23 09:36:25 +00001755void VG_(arena_free) ( ArenaId aid, void* ptr )
sewardjde4a1d02002-03-22 01:27:54 +00001756{
1757 Superblock* sb;
nethercote2d5b8162004-08-11 09:40:52 +00001758 UByte* sb_start;
1759 UByte* sb_end;
njna2578652005-07-17 17:12:24 +00001760 Block* other_b;
nethercote2d5b8162004-08-11 09:40:52 +00001761 Block* b;
nethercote7ac7f7b2004-11-02 12:36:02 +00001762 SizeT b_bszB, b_pszB, other_bszB;
1763 UInt b_listno;
sewardjde4a1d02002-03-22 01:27:54 +00001764 Arena* a;
1765
sewardj45f4e7c2005-09-27 19:20:21 +00001766 ensure_mm_init(aid);
sewardjde4a1d02002-03-22 01:27:54 +00001767 a = arenaId_to_ArenaP(aid);
1768
njn25e49d8e72002-09-23 09:36:25 +00001769 if (ptr == NULL) {
njn25e49d8e72002-09-23 09:36:25 +00001770 return;
1771 }
1772
nethercote2d5b8162004-08-11 09:40:52 +00001773 b = get_payload_block(a, ptr);
sewardjde4a1d02002-03-22 01:27:54 +00001774
sewardj3187a4e2005-12-04 23:27:14 +00001775 /* If this is one of V's areas, check carefully the block we're
1776 getting back. This picks up simple block-end overruns. */
1777 if (aid != VG_AR_CLIENT)
1778 vg_assert(blockSane(a, b));
sewardjde4a1d02002-03-22 01:27:54 +00001779
njne6f9e3b2005-07-17 18:00:57 +00001780 b_bszB = get_bszB(b);
1781 b_pszB = bszB_to_pszB(a, b_bszB);
nethercote2d5b8162004-08-11 09:40:52 +00001782 sb = findSb( a, b );
1783 sb_start = &sb->payload_bytes[0];
1784 sb_end = &sb->payload_bytes[sb->n_payload_bytes - 1];
sewardjde4a1d02002-03-22 01:27:54 +00001785
sewardj7d1064a2011-02-23 13:18:56 +00001786 a->stats__bytes_on_loan -= b_pszB;
njne6f9e3b2005-07-17 18:00:57 +00001787
sewardj3187a4e2005-12-04 23:27:14 +00001788 /* If this is one of V's areas, fill it up with junk to enhance the
1789 chances of catching any later reads of it. Note, 0xDD is
1790 carefully chosen junk :-), in that: (1) 0xDDDDDDDD is an invalid
1791 and non-word-aligned address on most systems, and (2) 0xDD is a
1792 value which is unlikely to be generated by the new compressed
1793 Vbits representation for memcheck. */
1794 if (aid != VG_AR_CLIENT)
1795 VG_(memset)(ptr, 0xDD, (SizeT)b_pszB);
1796
sewardjd043de92011-09-26 11:28:20 +00001797 if (! sb->unsplittable) {
sewardjd8b93462011-09-10 10:17:35 +00001798 // Put this chunk back on a list somewhere.
1799 b_listno = pszB_to_listNo(b_pszB);
1800 mkFreeBlock( a, b, b_bszB, b_listno );
1801 if (VG_(clo_profile_heap))
1802 set_cc(b, "admin.free-1");
sewardjde4a1d02002-03-22 01:27:54 +00001803
sewardjd8b93462011-09-10 10:17:35 +00001804 // See if this block can be merged with its successor.
1805 // First test if we're far enough before the superblock's end to possibly
1806 // have a successor.
1807 other_b = b + b_bszB;
1808 if (other_b+min_useful_bszB(a)-1 <= (Block*)sb_end) {
1809 // Ok, we have a successor, merge if it's not in use.
1810 other_bszB = get_bszB(other_b);
1811 if (!is_inuse_block(other_b)) {
1812 // VG_(printf)( "merge-successor\n");
1813# ifdef DEBUG_MALLOC
1814 vg_assert(blockSane(a, other_b));
1815# endif
1816 unlinkBlock( a, b, b_listno );
1817 unlinkBlock( a, other_b,
1818 pszB_to_listNo(bszB_to_pszB(a,other_bszB)) );
1819 b_bszB += other_bszB;
1820 b_listno = pszB_to_listNo(bszB_to_pszB(a, b_bszB));
1821 mkFreeBlock( a, b, b_bszB, b_listno );
1822 if (VG_(clo_profile_heap))
1823 set_cc(b, "admin.free-2");
1824 }
1825 } else {
1826 // Not enough space for successor: check that b is the last block
1827 // ie. there are no unused bytes at the end of the Superblock.
1828 vg_assert(other_b-1 == (Block*)sb_end);
1829 }
1830
1831 // Then see if this block can be merged with its predecessor.
1832 // First test if we're far enough after the superblock's start to possibly
1833 // have a predecessor.
1834 if (b >= (Block*)sb_start + min_useful_bszB(a)) {
1835 // Ok, we have a predecessor, merge if it's not in use.
1836 other_b = get_predecessor_block( b );
1837 other_bszB = get_bszB(other_b);
1838 if (!is_inuse_block(other_b)) {
1839 // VG_(printf)( "merge-predecessor\n");
1840 unlinkBlock( a, b, b_listno );
1841 unlinkBlock( a, other_b,
1842 pszB_to_listNo(bszB_to_pszB(a, other_bszB)) );
1843 b = other_b;
1844 b_bszB += other_bszB;
1845 b_listno = pszB_to_listNo(bszB_to_pszB(a, b_bszB));
1846 mkFreeBlock( a, b, b_bszB, b_listno );
1847 if (VG_(clo_profile_heap))
1848 set_cc(b, "admin.free-3");
1849 }
1850 } else {
1851 // Not enough space for predecessor: check that b is the first block,
1852 // ie. there are no unused bytes at the start of the Superblock.
1853 vg_assert((Block*)sb_start == b);
sewardjde4a1d02002-03-22 01:27:54 +00001854 }
sewardjd043de92011-09-26 11:28:20 +00001855
1856 /* If the block b just merged is the only block of the superblock sb,
1857 then we defer reclaim sb. */
1858 if ( ((Block*)sb_start == b) && (b + b_bszB-1 == (Block*)sb_end) ) {
1859 deferred_reclaimSuperblock (a, sb);
1860 }
1861
philippe72faf102012-03-11 22:24:03 +00001862 // Inform that ptr has been released. We give redzone size
1863 // 0 instead of a->rz_szB as proper accessibility is done just after.
1864 INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(ptr, 0));
1865
1866 // We need to (re-)establish the minimum accessibility needed
1867 // for free list management. E.g. if block ptr has been put in a free
1868 // list and a neighbour block is released afterwards, the
1869 // "lo" and "hi" portions of the block ptr will be accessed to
1870 // glue the 2 blocks together.
1871 // We could mark the whole block as not accessible, and each time
1872 // transiently mark accessible the needed lo/hi parts. Not done as this
1873 // is quite complex, for very little expected additional bug detection.
1874 // fully unaccessible. Note that the below marks the (possibly) merged
1875 // block, not the block corresponding to the ptr argument.
1876
1877 // First mark the whole block unaccessible.
1878 INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS(b, b_bszB));
1879 // Then mark the relevant administrative headers as defined.
1880 // No need to mark the heap profile portion as defined, this is not
1881 // used for free blocks.
1882 INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED(b + hp_overhead_szB(),
1883 sizeof(SizeT) + sizeof(void*)));
1884 INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED(b + b_bszB
1885 - sizeof(SizeT) - sizeof(void*),
1886 sizeof(SizeT) + sizeof(void*)));
nethercote2d5b8162004-08-11 09:40:52 +00001887 } else {
sewardjd8b93462011-09-10 10:17:35 +00001888 // b must be first block (i.e. no unused bytes at the beginning)
sewardj4c89b2f2011-08-17 22:13:14 +00001889 vg_assert((Block*)sb_start == b);
sewardjd8b93462011-09-10 10:17:35 +00001890
1891 // b must be last block (i.e. no unused bytes at the end)
1892 other_b = b + b_bszB;
1893 vg_assert(other_b-1 == (Block*)sb_end);
1894
philippe72faf102012-03-11 22:24:03 +00001895 // Inform that ptr has been released. Redzone size value
1896 // is not relevant (so we give 0 instead of a->rz_szB)
1897 // as it is expected that the aspacemgr munmap will be used by
1898 // outer to mark the whole superblock as unaccessible.
1899 INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(ptr, 0));
1900
sewardjd043de92011-09-26 11:28:20 +00001901 // Reclaim immediately the unsplittable superblock sb.
sewardjd8b93462011-09-10 10:17:35 +00001902 reclaimSuperblock (a, sb);
sewardjde4a1d02002-03-22 01:27:54 +00001903 }
1904
1905# ifdef DEBUG_MALLOC
nethercote885dd912004-08-03 23:14:00 +00001906 sanity_check_malloc_arena(aid);
sewardjde4a1d02002-03-22 01:27:54 +00001907# endif
1908
sewardjde4a1d02002-03-22 01:27:54 +00001909}
1910
1911
1912/*
1913 The idea for malloc_aligned() is to allocate a big block, base, and
1914 then split it into two parts: frag, which is returned to the the
1915 free pool, and align, which is the bit we're really after. Here's
1916 a picture. L and H denote the block lower and upper overheads, in
nethercote2d5b8162004-08-11 09:40:52 +00001917 bytes. The details are gruesome. Note it is slightly complicated
sewardjde4a1d02002-03-22 01:27:54 +00001918 because the initial request to generate base may return a bigger
1919 block than we asked for, so it is important to distinguish the base
1920 request size and the base actual size.
1921
1922 frag_b align_b
1923 | |
1924 | frag_p | align_p
1925 | | | |
1926 v v v v
1927
1928 +---+ +---+---+ +---+
1929 | L |----------------| H | L |---------------| H |
1930 +---+ +---+---+ +---+
1931
1932 ^ ^ ^
1933 | | :
1934 | base_p this addr must be aligned
1935 |
1936 base_b
1937
1938 . . . . . . .
nethercote2d5b8162004-08-11 09:40:52 +00001939 <------ frag_bszB -------> . . .
1940 . <------------- base_pszB_act -----------> .
sewardjde4a1d02002-03-22 01:27:54 +00001941 . . . . . . .
1942
1943*/
sewardj9c606bd2008-09-18 18:12:50 +00001944void* VG_(arena_memalign) ( ArenaId aid, HChar* cc,
1945 SizeT req_alignB, SizeT req_pszB )
sewardjde4a1d02002-03-22 01:27:54 +00001946{
nethercote7ac7f7b2004-11-02 12:36:02 +00001947 SizeT base_pszB_req, base_pszB_act, frag_bszB;
nethercote2d5b8162004-08-11 09:40:52 +00001948 Block *base_b, *align_b;
1949 UByte *base_p, *align_p;
nethercote7ac7f7b2004-11-02 12:36:02 +00001950 SizeT saved_bytes_on_loan;
sewardjde4a1d02002-03-22 01:27:54 +00001951 Arena* a;
1952
sewardj45f4e7c2005-09-27 19:20:21 +00001953 ensure_mm_init(aid);
sewardjde4a1d02002-03-22 01:27:54 +00001954 a = arenaId_to_ArenaP(aid);
1955
nethercote7ac7f7b2004-11-02 12:36:02 +00001956 vg_assert(req_pszB < MAX_PSZB);
sewardjde4a1d02002-03-22 01:27:54 +00001957
sewardj9c606bd2008-09-18 18:12:50 +00001958 // You must provide a cost-center name against which to charge
1959 // this allocation; it isn't optional.
1960 vg_assert(cc);
1961
philippef5f6ed12012-06-15 22:19:59 +00001962 // Check that the requested alignment has a plausible size.
nethercote2d5b8162004-08-11 09:40:52 +00001963 // Check that the requested alignment seems reasonable; that is, is
1964 // a power of 2.
1965 if (req_alignB < VG_MIN_MALLOC_SZB
philippef5f6ed12012-06-15 22:19:59 +00001966 || req_alignB > 16 * 1024 * 1024
njn717cde52005-05-10 02:47:21 +00001967 || VG_(log2)( req_alignB ) == -1 /* not a power of 2 */) {
njn36b65172009-04-14 23:43:15 +00001968 VG_(printf)("VG_(arena_memalign)(%p, %lu, %lu)\n"
1969 "bad alignment value %lu\n"
1970 "(it is too small, too big, or not a power of two)",
1971 a, req_alignB, req_pszB, req_alignB );
njn717cde52005-05-10 02:47:21 +00001972 VG_(core_panic)("VG_(arena_memalign)");
nethercote2d5b8162004-08-11 09:40:52 +00001973 /*NOTREACHED*/
sewardjde4a1d02002-03-22 01:27:54 +00001974 }
nethercote2d5b8162004-08-11 09:40:52 +00001975 // Paranoid
1976 vg_assert(req_alignB % VG_MIN_MALLOC_SZB == 0);
sewardjde4a1d02002-03-22 01:27:54 +00001977
1978 /* Required payload size for the aligned chunk. */
nethercote2d5b8162004-08-11 09:40:52 +00001979 req_pszB = align_req_pszB(req_pszB);
sewardjde4a1d02002-03-22 01:27:54 +00001980
nethercote2d5b8162004-08-11 09:40:52 +00001981 /* Payload size to request for the big block that we will split up. */
1982 base_pszB_req = req_pszB + min_useful_bszB(a) + req_alignB;
sewardjde4a1d02002-03-22 01:27:54 +00001983
1984 /* Payload ptr for the block we are going to split. Note this
1985 changes a->bytes_on_loan; we save and restore it ourselves. */
sewardj7d1064a2011-02-23 13:18:56 +00001986 saved_bytes_on_loan = a->stats__bytes_on_loan;
sewardjd8b93462011-09-10 10:17:35 +00001987 {
1988 /* As we will split the block given back by VG_(arena_malloc),
sewardjd043de92011-09-26 11:28:20 +00001989 we have to (temporarily) disable unsplittable for this arena,
1990 as unsplittable superblocks cannot be splitted. */
1991 const SizeT save_min_unsplittable_sblock_szB
1992 = a->min_unsplittable_sblock_szB;
1993 a->min_unsplittable_sblock_szB = MAX_PSZB;
sewardjd8b93462011-09-10 10:17:35 +00001994 base_p = VG_(arena_malloc) ( aid, cc, base_pszB_req );
sewardjd043de92011-09-26 11:28:20 +00001995 a->min_unsplittable_sblock_szB = save_min_unsplittable_sblock_szB;
sewardjd8b93462011-09-10 10:17:35 +00001996 }
sewardj7d1064a2011-02-23 13:18:56 +00001997 a->stats__bytes_on_loan = saved_bytes_on_loan;
sewardjde4a1d02002-03-22 01:27:54 +00001998
tom8af1a172005-10-06 12:04:26 +00001999 /* Give up if we couldn't allocate enough space */
2000 if (base_p == 0)
2001 return 0;
philippe72faf102012-03-11 22:24:03 +00002002 /* base_p was marked as allocated by VALGRIND_MALLOCLIKE_BLOCK
2003 inside VG_(arena_malloc). We need to indicate it is free, then
2004 we need to mark it undefined to allow the below code to access is. */
2005 INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(base_p, a->rz_szB));
2006 INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(base_p, base_pszB_req));
tom8af1a172005-10-06 12:04:26 +00002007
sewardjde4a1d02002-03-22 01:27:54 +00002008 /* Block ptr for the block we are going to split. */
nethercote2d5b8162004-08-11 09:40:52 +00002009 base_b = get_payload_block ( a, base_p );
sewardjde4a1d02002-03-22 01:27:54 +00002010
2011 /* Pointer to the payload of the aligned block we are going to
2012 return. This has to be suitably aligned. */
nethercote2d5b8162004-08-11 09:40:52 +00002013 align_p = align_upwards ( base_b + 2 * overhead_szB_lo(a)
2014 + overhead_szB_hi(a),
sewardjde4a1d02002-03-22 01:27:54 +00002015 req_alignB );
nethercote2d5b8162004-08-11 09:40:52 +00002016 align_b = get_payload_block(a, align_p);
sewardjde4a1d02002-03-22 01:27:54 +00002017
2018 /* The block size of the fragment we will create. This must be big
2019 enough to actually create a fragment. */
nethercote2d5b8162004-08-11 09:40:52 +00002020 frag_bszB = align_b - base_b;
2021
2022 vg_assert(frag_bszB >= min_useful_bszB(a));
sewardjde4a1d02002-03-22 01:27:54 +00002023
2024 /* The actual payload size of the block we are going to split. */
njn089f51f2005-07-17 18:12:00 +00002025 base_pszB_act = get_pszB(a, base_b);
sewardjde4a1d02002-03-22 01:27:54 +00002026
nethercote2d5b8162004-08-11 09:40:52 +00002027 /* Create the fragment block, and put it back on the relevant free list. */
2028 mkFreeBlock ( a, base_b, frag_bszB,
2029 pszB_to_listNo(bszB_to_pszB(a, frag_bszB)) );
sewardj94c8eb42008-09-19 20:13:39 +00002030 if (VG_(clo_profile_heap))
2031 set_cc(base_b, "admin.frag-memalign-1");
sewardjde4a1d02002-03-22 01:27:54 +00002032
2033 /* Create the aligned block. */
nethercote2d5b8162004-08-11 09:40:52 +00002034 mkInuseBlock ( a, align_b,
2035 base_p + base_pszB_act
2036 + overhead_szB_hi(a) - (UByte*)align_b );
sewardj94c8eb42008-09-19 20:13:39 +00002037 if (VG_(clo_profile_heap))
2038 set_cc(align_b, cc);
sewardjde4a1d02002-03-22 01:27:54 +00002039
2040 /* Final sanity checks. */
njn472cc7c2005-07-17 17:20:30 +00002041 vg_assert( is_inuse_block(get_payload_block(a, align_p)) );
sewardjde4a1d02002-03-22 01:27:54 +00002042
njn089f51f2005-07-17 18:12:00 +00002043 vg_assert(req_pszB <= get_pszB(a, get_payload_block(a, align_p)));
sewardjde4a1d02002-03-22 01:27:54 +00002044
sewardj7d1064a2011-02-23 13:18:56 +00002045 a->stats__bytes_on_loan += get_pszB(a, get_payload_block(a, align_p));
2046 if (a->stats__bytes_on_loan > a->stats__bytes_on_loan_max) {
2047 a->stats__bytes_on_loan_max = a->stats__bytes_on_loan;
2048 }
2049 /* a->stats__tot_blocks, a->stats__tot_bytes, a->stats__nsearches
2050 are updated by the call to VG_(arena_malloc) just a few lines
2051 above. So we don't need to update them here. */
sewardjde4a1d02002-03-22 01:27:54 +00002052
2053# ifdef DEBUG_MALLOC
nethercote885dd912004-08-03 23:14:00 +00002054 sanity_check_malloc_arena(aid);
sewardjde4a1d02002-03-22 01:27:54 +00002055# endif
2056
nethercote2d5b8162004-08-11 09:40:52 +00002057 vg_assert( (((Addr)align_p) % req_alignB) == 0 );
sewardjb5f6f512005-03-10 23:59:00 +00002058
philippe72faf102012-03-11 22:24:03 +00002059 INNER_REQUEST(VALGRIND_MALLOCLIKE_BLOCK(align_p,
2060 req_pszB, a->rz_szB, False));
sewardjb5f6f512005-03-10 23:59:00 +00002061
nethercote2d5b8162004-08-11 09:40:52 +00002062 return align_p;
2063}
2064
2065
njn8b140de2009-02-17 04:31:18 +00002066SizeT VG_(arena_malloc_usable_size) ( ArenaId aid, void* ptr )
nethercote2d5b8162004-08-11 09:40:52 +00002067{
2068 Arena* a = arenaId_to_ArenaP(aid);
2069 Block* b = get_payload_block(a, ptr);
njn089f51f2005-07-17 18:12:00 +00002070 return get_pszB(a, b);
sewardjde4a1d02002-03-22 01:27:54 +00002071}
2072
bart545380e2008-04-21 17:28:50 +00002073
2074// Implementation of mallinfo(). There is no recent standard that defines
2075// the behavior of mallinfo(). The meaning of the fields in struct mallinfo
2076// is as follows:
2077//
2078// struct mallinfo {
2079// int arena; /* total space in arena */
2080// int ordblks; /* number of ordinary blocks */
2081// int smblks; /* number of small blocks */
2082// int hblks; /* number of holding blocks */
2083// int hblkhd; /* space in holding block headers */
2084// int usmblks; /* space in small blocks in use */
2085// int fsmblks; /* space in free small blocks */
2086// int uordblks; /* space in ordinary blocks in use */
2087// int fordblks; /* space in free ordinary blocks */
2088// int keepcost; /* space penalty if keep option */
2089// /* is used */
2090// };
2091//
2092// The glibc documentation about mallinfo (which is somewhat outdated) can
2093// be found here:
2094// http://www.gnu.org/software/libtool/manual/libc/Statistics-of-Malloc.html
2095//
2096// See also http://bugs.kde.org/show_bug.cgi?id=160956.
2097//
2098// Regarding the implementation of VG_(mallinfo)(): we cannot return the
2099// whole struct as the library function does, because this is called by a
2100// client request. So instead we use a pointer to do call by reference.
njn088bfb42005-08-17 05:01:37 +00002101void VG_(mallinfo) ( ThreadId tid, struct vg_mallinfo* mi )
2102{
sewardj76dda8f2008-05-29 13:45:49 +00002103 UWord i, free_blocks, free_blocks_size;
bartc3c98392008-04-19 14:43:30 +00002104 Arena* a = arenaId_to_ArenaP(VG_AR_CLIENT);
2105
2106 // Traverse free list and calculate free blocks statistics.
2107 // This may seem slow but glibc works the same way.
2108 free_blocks_size = free_blocks = 0;
2109 for (i = 0; i < N_MALLOC_LISTS; i++) {
2110 Block* b = a->freelist[i];
2111 if (b == NULL) continue;
2112 for (;;) {
2113 free_blocks++;
sewardj76dda8f2008-05-29 13:45:49 +00002114 free_blocks_size += (UWord)get_pszB(a, b);
bartc3c98392008-04-19 14:43:30 +00002115 b = get_next_b(b);
2116 if (b == a->freelist[i]) break;
2117 }
2118 }
2119
2120 // We don't have fastbins so smblks & fsmblks are always 0. Also we don't
bart545380e2008-04-21 17:28:50 +00002121 // have a separate mmap allocator so set hblks & hblkhd to 0.
sewardj7d1064a2011-02-23 13:18:56 +00002122 mi->arena = a->stats__bytes_mmaped;
bart545380e2008-04-21 17:28:50 +00002123 mi->ordblks = free_blocks + VG_(free_queue_length);
bartc3c98392008-04-19 14:43:30 +00002124 mi->smblks = 0;
2125 mi->hblks = 0;
2126 mi->hblkhd = 0;
2127 mi->usmblks = 0;
2128 mi->fsmblks = 0;
sewardj7d1064a2011-02-23 13:18:56 +00002129 mi->uordblks = a->stats__bytes_on_loan - VG_(free_queue_volume);
bart545380e2008-04-21 17:28:50 +00002130 mi->fordblks = free_blocks_size + VG_(free_queue_volume);
bartc3c98392008-04-19 14:43:30 +00002131 mi->keepcost = 0; // may want some value in here
njn088bfb42005-08-17 05:01:37 +00002132}
sewardjde4a1d02002-03-22 01:27:54 +00002133
sewardj45f4e7c2005-09-27 19:20:21 +00002134
sewardjde4a1d02002-03-22 01:27:54 +00002135/*------------------------------------------------------------*/
2136/*--- Services layered on top of malloc/free. ---*/
2137/*------------------------------------------------------------*/
2138
sewardj9c606bd2008-09-18 18:12:50 +00002139void* VG_(arena_calloc) ( ArenaId aid, HChar* cc,
2140 SizeT nmemb, SizeT bytes_per_memb )
sewardjde4a1d02002-03-22 01:27:54 +00002141{
nethercote7ac7f7b2004-11-02 12:36:02 +00002142 SizeT size;
sewardjde4a1d02002-03-22 01:27:54 +00002143 UChar* p;
njn25e49d8e72002-09-23 09:36:25 +00002144
njn926ed472005-03-11 04:44:10 +00002145 size = nmemb * bytes_per_memb;
2146 vg_assert(size >= nmemb && size >= bytes_per_memb);// check against overflow
njn3e884182003-04-15 13:03:23 +00002147
sewardj9c606bd2008-09-18 18:12:50 +00002148 p = VG_(arena_malloc) ( aid, cc, size );
njn3e884182003-04-15 13:03:23 +00002149
njn926ed472005-03-11 04:44:10 +00002150 VG_(memset)(p, 0, size);
sewardjb5f6f512005-03-10 23:59:00 +00002151
sewardjde4a1d02002-03-22 01:27:54 +00002152 return p;
2153}
2154
2155
sewardj9c606bd2008-09-18 18:12:50 +00002156void* VG_(arena_realloc) ( ArenaId aid, HChar* cc,
2157 void* ptr, SizeT req_pszB )
sewardjde4a1d02002-03-22 01:27:54 +00002158{
2159 Arena* a;
njn089f51f2005-07-17 18:12:00 +00002160 SizeT old_pszB;
sewardjb5f6f512005-03-10 23:59:00 +00002161 UChar *p_new;
nethercote2d5b8162004-08-11 09:40:52 +00002162 Block* b;
sewardjde4a1d02002-03-22 01:27:54 +00002163
sewardj45f4e7c2005-09-27 19:20:21 +00002164 ensure_mm_init(aid);
sewardjde4a1d02002-03-22 01:27:54 +00002165 a = arenaId_to_ArenaP(aid);
2166
nethercote7ac7f7b2004-11-02 12:36:02 +00002167 vg_assert(req_pszB < MAX_PSZB);
sewardjde4a1d02002-03-22 01:27:54 +00002168
njn180f6982008-10-12 19:51:41 +00002169 if (NULL == ptr) {
2170 return VG_(arena_malloc)(aid, cc, req_pszB);
2171 }
2172
2173 if (req_pszB == 0) {
2174 VG_(arena_free)(aid, ptr);
2175 return NULL;
2176 }
2177
nethercote2d5b8162004-08-11 09:40:52 +00002178 b = get_payload_block(a, ptr);
2179 vg_assert(blockSane(a, b));
sewardjde4a1d02002-03-22 01:27:54 +00002180
njn472cc7c2005-07-17 17:20:30 +00002181 vg_assert(is_inuse_block(b));
njn089f51f2005-07-17 18:12:00 +00002182 old_pszB = get_pszB(a, b);
sewardjde4a1d02002-03-22 01:27:54 +00002183
njn25e49d8e72002-09-23 09:36:25 +00002184 if (req_pszB <= old_pszB) {
njn25e49d8e72002-09-23 09:36:25 +00002185 return ptr;
2186 }
sewardjde4a1d02002-03-22 01:27:54 +00002187
sewardj9c606bd2008-09-18 18:12:50 +00002188 p_new = VG_(arena_malloc) ( aid, cc, req_pszB );
njn828022a2005-03-13 14:56:31 +00002189
sewardjb5f6f512005-03-10 23:59:00 +00002190 VG_(memcpy)(p_new, ptr, old_pszB);
sewardjde4a1d02002-03-22 01:27:54 +00002191
sewardjb5f6f512005-03-10 23:59:00 +00002192 VG_(arena_free)(aid, ptr);
njn25e49d8e72002-09-23 09:36:25 +00002193
sewardjde4a1d02002-03-22 01:27:54 +00002194 return p_new;
2195}
2196
2197
njn6ba622c2005-06-11 01:12:08 +00002198/* Inline just for the wrapper VG_(strdup) below */
sewardj9c606bd2008-09-18 18:12:50 +00002199__inline__ Char* VG_(arena_strdup) ( ArenaId aid, HChar* cc,
2200 const Char* s )
njn6ba622c2005-06-11 01:12:08 +00002201{
2202 Int i;
2203 Int len;
2204 Char* res;
2205
2206 if (s == NULL)
2207 return NULL;
2208
2209 len = VG_(strlen)(s) + 1;
sewardj9c606bd2008-09-18 18:12:50 +00002210 res = VG_(arena_malloc) (aid, cc, len);
njn6ba622c2005-06-11 01:12:08 +00002211
2212 for (i = 0; i < len; i++)
2213 res[i] = s[i];
2214 return res;
2215}
2216
2217
sewardjde4a1d02002-03-22 01:27:54 +00002218/*------------------------------------------------------------*/
nethercote996901a2004-08-03 13:29:09 +00002219/*--- Tool-visible functions. ---*/
njn25e49d8e72002-09-23 09:36:25 +00002220/*------------------------------------------------------------*/
2221
nethercote2d5b8162004-08-11 09:40:52 +00002222// All just wrappers to avoid exposing arenas to tools.
njn25e49d8e72002-09-23 09:36:25 +00002223
sewardj9c606bd2008-09-18 18:12:50 +00002224void* VG_(malloc) ( HChar* cc, SizeT nbytes )
njn25e49d8e72002-09-23 09:36:25 +00002225{
sewardj9c606bd2008-09-18 18:12:50 +00002226 return VG_(arena_malloc) ( VG_AR_TOOL, cc, nbytes );
njn25e49d8e72002-09-23 09:36:25 +00002227}
2228
2229void VG_(free) ( void* ptr )
2230{
nethercote60f5b822004-01-26 17:24:42 +00002231 VG_(arena_free) ( VG_AR_TOOL, ptr );
njn25e49d8e72002-09-23 09:36:25 +00002232}
2233
sewardj9c606bd2008-09-18 18:12:50 +00002234void* VG_(calloc) ( HChar* cc, SizeT nmemb, SizeT bytes_per_memb )
njn25e49d8e72002-09-23 09:36:25 +00002235{
sewardj9c606bd2008-09-18 18:12:50 +00002236 return VG_(arena_calloc) ( VG_AR_TOOL, cc, nmemb, bytes_per_memb );
njn25e49d8e72002-09-23 09:36:25 +00002237}
2238
sewardj9c606bd2008-09-18 18:12:50 +00002239void* VG_(realloc) ( HChar* cc, void* ptr, SizeT size )
njn25e49d8e72002-09-23 09:36:25 +00002240{
sewardj9c606bd2008-09-18 18:12:50 +00002241 return VG_(arena_realloc) ( VG_AR_TOOL, cc, ptr, size );
njn25e49d8e72002-09-23 09:36:25 +00002242}
2243
sewardj9c606bd2008-09-18 18:12:50 +00002244Char* VG_(strdup) ( HChar* cc, const Char* s )
njn6ba622c2005-06-11 01:12:08 +00002245{
sewardj9c606bd2008-09-18 18:12:50 +00002246 return VG_(arena_strdup) ( VG_AR_TOOL, cc, s );
njn6ba622c2005-06-11 01:12:08 +00002247}
2248
njn32397c02007-11-10 04:08:08 +00002249// Useful for querying user blocks.
2250SizeT VG_(malloc_usable_size) ( void* p )
2251{
njn00556da2009-03-17 04:51:19 +00002252 return VG_(arena_malloc_usable_size)(VG_AR_CLIENT, p);
njn32397c02007-11-10 04:08:08 +00002253}
2254
2255
sewardjde4a1d02002-03-22 01:27:54 +00002256/*--------------------------------------------------------------------*/
njn717cde52005-05-10 02:47:21 +00002257/*--- end ---*/
sewardjde4a1d02002-03-22 01:27:54 +00002258/*--------------------------------------------------------------------*/