2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2010 Free Software Foundation Europe e.V.
6 The main author of Bacula is Kern Sibbald, with contributions from
7 many others, a complete list can be found in the file AUTHORS.
8 This program is Free Software; you can redistribute it and/or
9 modify it under the terms of version three of the GNU Affero General Public
10 License as published by the Free Software Foundation and included
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU Affero General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 Bacula® is a registered trademark of Kern Sibbald.
24 The licensor of Bacula is the Free Software Foundation Europe
25 (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26 Switzerland, email:ftf@fsfeurope.org.
31 Smart Memory Allocator
33 Evolved over several years, starting with the initial
34 SMARTALLOC code for AutoSketch in 1986, guided by the Blind
35 Watchbreaker, John Walker. Isolated in this general-purpose
36 form in September of 1989. Updated with be more POSIX
37 compliant and to include Web-friendly HTML documentation in
38 October of 1998 by the same culprit. For additional
39 information and the current version visit the Web page:
41 http://www.fourmilab.ch/smartall/
45 #define _LOCKMGR_COMPLIANT
48 /* Use the real routines here */
54 /* We normally turn off debugging here.
55 * If you want it, simply #ifdef all the
64 #define Dmsg2(l,f,a1,a2)
65 #define Dmsg3(l,f,a1,a2,a3)
66 #define Dmsg4(l,f,a1,a2,a3,a4)
70 uint64_t sm_max_bytes = 0;
71 uint64_t sm_bytes = 0;
72 uint32_t sm_max_buffers = 0;
73 uint32_t sm_buffers = 0;
77 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
79 extern char my_name[]; /* daemon name */
81 #define EOS '\0' /* End of string sentinel */
82 #define sm_min(a, b) ((a) < (b) ? (a) : (b))
84 /* Queue data structures */
86 /* Memory allocation control structures and storage. */
89 struct b_queue abq; /* Links on allocated queue */
90 uint32_t ablen; /* Buffer length in bytes */
91 const char *abfname; /* File name pointer */
92 uint32_t ablineno; /* Line number of allocation */
93 bool abin_use; /* set when malloced and cleared when free */
96 static struct b_queue abqueue = { /* Allocated buffer queue */
101 static bool bufimode = false; /* Buffers not tracked when True */
103 #define HEAD_SIZE BALIGN(sizeof(struct abufhead))
106 /* SMALLOC -- Allocate buffer, enqueing on the orphaned buffer
109 static void *smalloc(const char *fname, int lineno, unsigned int nbytes)
113 /* Note: Unix MALLOC actually permits a zero length to be
114 passed and allocates a valid block with zero user bytes.
115 Such a block can later be expanded with realloc(). We
116 disallow this based on the belief that it's better to make
117 a special case and allocate one byte in the rare case this
118 is desired than to miss all the erroneous occurrences where
119 buffer length calculation code results in a zero. */
123 nbytes += HEAD_SIZE + 1;
124 if ((buf = (char *)malloc(nbytes)) != NULL) {
125 struct abufhead *head = (struct abufhead *)buf;
127 /* Enqueue buffer on allocated list */
128 qinsert(&abqueue, (struct b_queue *) buf);
129 head->ablen = nbytes;
130 head->abfname = bufimode ? NULL : fname;
131 head->ablineno = (uint32_t)lineno;
132 head->abin_use = true;
133 /* Emplace end-clobber detector at end of buffer */
134 buf[nbytes - 1] = (uint8_t)((((intptr_t) buf) & 0xFF) ^ 0xC5);
135 buf += HEAD_SIZE; /* Increment to user data start */
136 if (++sm_buffers > sm_max_buffers) {
137 sm_max_buffers = sm_buffers;
140 if (sm_bytes > sm_max_bytes) {
141 sm_max_bytes = sm_bytes;
145 Emsg0(M_ABORT, 0, _("Out of memory\n"));
147 Dmsg4(1150, "smalloc %d at %p from %s:%d\n", nbytes, buf, fname, lineno);
148 #if SMALLOC_SANITY_CHECK > 0
149 if (sm_bytes > SMALLOC_SANITY_CHECK) {
150 Emsg0(M_ABORT, 0, _("Too much memory used."));
156 /* SM_NEW_OWNER -- Update the File and line number for a buffer
157 This is to accomodate mem_pool. */
159 void sm_new_owner(const char *fname, int lineno, char *buf)
161 buf -= HEAD_SIZE; /* Decrement to header */
162 ((struct abufhead *)buf)->abfname = bufimode ? NULL : fname;
163 ((struct abufhead *)buf)->ablineno = (uint32_t) lineno;
164 ((struct abufhead *)buf)->abin_use = true;
168 /* SM_FREE -- Update free pool availability. FREE is never called
169 except through this interface or by actuallyfree().
170 free(x) is defined to generate a call to this
173 void sm_free(const char *file, int line, void *fp)
175 char *cp = (char *) fp;
177 uint32_t lineno = line;
180 Emsg2(M_ABORT, 0, _("Attempt to free NULL called from %s:%d\n"), file, lineno);
184 qp = (struct b_queue *)cp;
185 struct abufhead *head = (struct abufhead *)cp;
188 Dmsg4(1150, "sm_free %d at %p from %s:%d\n",
190 head->abfname, head->ablineno);
192 if (!head->abin_use) {
194 Emsg2(M_ABORT, 0, _("double free from %s:%d\n"), file, lineno);
196 head->abin_use = false;
198 /* The following assertions will catch virtually every release
199 of an address which isn't an allocated buffer. */
200 if (qp->qnext->qprev != qp) {
202 Emsg2(M_ABORT, 0, _("qp->qnext->qprev != qp called from %s:%d\n"), file, lineno);
204 if (qp->qprev->qnext != qp) {
206 Emsg2(M_ABORT, 0, _("qp->qprev->qnext != qp called from %s:%d\n"), file, lineno);
209 /* The following assertion detects storing off the end of the
210 allocated space in the buffer by comparing the end of buffer
211 checksum with the address of the buffer. */
213 if (((unsigned char *)cp)[head->ablen - 1] != ((((intptr_t) cp) & 0xFF) ^ 0xC5)) {
215 Emsg2(M_ABORT, 0, _("Buffer overrun called from %s:%d\n"), file, line);
217 if (sm_buffers > 0) {
219 sm_bytes -= head->ablen;
225 /* Now we wipe the contents of the just-released buffer with
226 "designer garbage" (Duff Kurland's phrase) of alternating
227 bits. This is intended to ruin the day for any miscreant who
228 attempts to access data through a pointer into storage that's
229 been previously released.
231 Modified, kes May, 2007 to not zap the header. This allows us
232 to check the in_use bit and detect doubly freed buffers.
235 memset(cp+HEAD_SIZE, 0xAA, (int)(head->ablen - HEAD_SIZE));
240 /* SM_MALLOC -- Allocate buffer. NULL is returned if no memory
243 void *sm_malloc(const char *fname, int lineno, unsigned int nbytes)
247 if ((buf = smalloc(fname, lineno, nbytes)) != NULL) {
249 /* To catch sloppy code that assumes buffers obtained from
250 malloc() are zeroed, we preset the buffer contents to
251 "designer garbage" consisting of alternating bits. */
253 memset(buf, 0x55, (int) nbytes);
255 Emsg0(M_ABORT, 0, _("Out of memory\n"));
260 /* SM_CALLOC -- Allocate an array and clear it to zero. */
262 void *sm_calloc(const char *fname, int lineno,
263 unsigned int nelem, unsigned int elsize)
267 if ((buf = smalloc(fname, lineno, nelem * elsize)) != NULL) {
268 memset(buf, 0, (int) (nelem * elsize));
270 Emsg0(M_ABORT, 0, _("Out of memory\n"));
275 /* SM_REALLOC -- Adjust the size of a previously allocated buffer.
276 Note that the trick of "resurrecting" a previously
277 freed buffer with realloc() is NOT supported by this
278 function. Further, because of the need to maintain
279 our control storage, SM_REALLOC must always allocate
280 a new block and copy the data in the old block.
281 This may result in programs which make heavy use of
282 realloc() running much slower than normally. */
284 void *sm_realloc(const char *fname, int lineno, void *ptr, unsigned int size)
288 char *cp = (char *) ptr;
290 Dmsg4(1400, "sm_realloc %s:%d %p %d\n", fname, (uint32_t)lineno, ptr, size);
292 e_msg(fname, lineno, M_ABORT, 0, _("sm_realloc size: %d\n"), size);
295 /* If the old block pointer is NULL, treat realloc() as a
296 malloc(). SVID is silent on this, but many C libraries
299 return sm_malloc(fname, lineno, size);
302 /* If the old and new sizes are the same, be a nice guy and just
303 return the buffer passed in. */
305 struct abufhead *head = (struct abufhead *)cp;
306 osize = head->ablen - (HEAD_SIZE + 1);
311 /* Sizes differ. Allocate a new buffer of the requested size.
312 If we can't obtain such a buffer, act as defined in SVID:
313 return NULL from realloc() and leave the buffer in PTR
317 // sm_bytes -= head->ablen;
319 if ((buf = smalloc(fname, lineno, size)) != NULL) {
320 memcpy(buf, ptr, (int)sm_min(size, osize));
321 /* If the new buffer is larger than the old, fill the balance
322 of it with "designer garbage". */
324 memset(((char *) buf) + osize, 0x55, (int) (size - osize));
327 /* All done. Free and dechain the original buffer. */
328 sm_free(fname, lineno, ptr);
330 Dmsg4(4150, _("sm_realloc %d at %p from %s:%d\n"), size, buf, fname, (uint32_t)lineno);
334 /* ACTUALLYMALLOC -- Call the system malloc() function to obtain
335 storage which will eventually be released
336 by system or library routines not compiled
339 void *actuallymalloc(unsigned int size)
344 /* ACTUALLYCALLOC -- Call the system calloc() function to obtain
345 storage which will eventually be released
346 by system or library routines not compiled
349 void *actuallycalloc(unsigned int nelem, unsigned int elsize)
351 return calloc(nelem, elsize);
354 /* ACTUALLYREALLOC -- Call the system realloc() function to obtain
355 storage which will eventually be released
356 by system or library routines not compiled
359 void *actuallyrealloc(void *ptr, unsigned int size)
361 Dmsg2(1400, "Actuallyrealloc %p %d\n", ptr, size);
362 return realloc(ptr, size);
365 /* ACTUALLYFREE -- Interface to system free() function to release
366 buffers allocated by low-level routines. */
368 void actuallyfree(void *cp)
373 /* SM_DUMP -- Print orphaned buffers (and dump them if BUFDUMP is
376 void sm_dump(bool bufdump, bool in_use)
382 ap = (struct abufhead *)abqueue.qnext;
384 while (ap != (struct abufhead *) &abqueue) {
387 (ap->abq.qnext->qprev != (struct b_queue *) ap) ||
388 (ap->abq.qprev->qnext != (struct b_queue *) ap)) {
390 "\nOrphaned buffers exist. Dump terminated following\n"
391 " discovery of bad links in chain of orphaned buffers.\n"
392 " Buffer address with bad links: %p\n"), ap);
396 if (ap->abfname != NULL) {
398 uint32_t memsize = ap->ablen - (HEAD_SIZE + 1);
399 char *cp = ((char *)ap) + HEAD_SIZE;
401 Pmsg6(0, "%s buffer: %s %d bytes at %p from %s:%d\n",
402 in_use?"In use":"Orphaned",
403 my_name, memsize, cp, ap->abfname, ap->ablineno);
411 bstrncat(errmsg, "\n", sizeof(errmsg));
413 Pmsg1(0, "%s", errmsg);
416 bsnprintf(buf, sizeof(buf), " %02X",
418 bstrncat(errmsg, buf, sizeof(errmsg));
422 Pmsg1(0, "%s\n", errmsg);
425 ap = (struct abufhead *) ap->abq.qnext;
431 /* SM_CHECK -- Check the buffers and dump if any damage exists. */
432 void sm_check(const char *fname, int lineno, bool bufdump)
434 if (!sm_check_rtn(fname, lineno, bufdump)) {
435 Emsg2(M_ABORT, 0, _("Damaged buffer found. Called from %s:%d\n"),
436 fname, (uint32_t)lineno);
441 /* SM_CHECK_RTN -- Check the buffers and return 1 if OK otherwise 0 */
442 int sm_check_rtn(const char *fname, int lineno, bool bufdump)
448 ap = (struct abufhead *) abqueue.qnext;
449 while (ap != (struct abufhead *)&abqueue) {
452 if (ap->abq.qnext->qprev != (struct b_queue *)ap) {
455 if (ap->abq.qprev->qnext != (struct b_queue *)ap) {
458 if (((unsigned char *) ap)[((struct abufhead *)ap)->ablen - 1] !=
459 ((((intptr_t) ap) & 0xFF) ^ 0xC5)) {
468 _("\nDamaged buffers found at %s:%d\n"), fname, (uint32_t)lineno);
471 Pmsg0(0, _(" discovery of bad prev link.\n"));
474 Pmsg0(0, _(" discovery of bad next link.\n"));
477 Pmsg0(0, _(" discovery of data overrun.\n"));
480 Pmsg0(0, _(" NULL pointer.\n"));
486 Pmsg1(0, _(" Buffer address: %p\n"), ap);
488 if (ap->abfname != NULL) {
489 uint32_t memsize = ap->ablen - (HEAD_SIZE + 1);
493 _("Damaged buffer: %6u bytes allocated at line %d of %s %s\n"),
494 memsize, ap->ablineno, my_name, ap->abfname
498 char *cp = ((char *) ap) + HEAD_SIZE;
503 strcat(errmsg, "\n");
505 Pmsg1(0, "%s", errmsg);
509 sprintf(errmsg + strlen(errmsg), " %02X",
512 sprintf(errmsg + strlen(errmsg), " %c ",
518 Pmsg1(0, "%s\n", errmsg);
522 ap = (struct abufhead *)ap->abq.qnext;
526 return badbuf ? 0 : 1;
530 /* SM_STATIC -- Orphaned buffer detection can be disabled (for such
531 items as buffers allocated during initialisation) by
532 calling sm_static(1). Normal orphaned buffer
533 detection can be re-enabled with sm_static(0). Note
534 that all the other safeguards still apply to buffers
535 allocated when sm_static(1) mode is in effect. */
537 void sm_static(bool mode)
543 * Here we overload C++'s global new and delete operators
544 * so that the memory is allocated through smartalloc.
548 void * operator new(size_t size)
550 // Dmsg1(000, "new called %d\n", size);
551 return sm_malloc(__FILE__, __LINE__, size);
554 void operator delete(void *buf)
556 // Dmsg1(000, "free called %p\n", buf);
557 sm_free(__FILE__, __LINE__, buf);