]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/smartall.c
Add jcr to DB arguments
[bacula/bacula] / bacula / src / lib / smartall.c
1 /*
2
3                          S M A R T A L L O C
4                         Smart Memory Allocator
5
6         Evolved   over   several  years,  starting  with  the  initial
7         SMARTALLOC code for AutoSketch in 1986, guided  by  the  Blind
8         Watchbreaker,  John  Walker.  Isolated in this general-purpose
9         form in  September  of  1989.   Updated  with  be  more  POSIX
10         compliant  and  to  include Web-friendly HTML documentation in
11         October  of  1998  by  the  same  culprit.    For   additional
12         information and the current version visit the Web page:
13
14                   http://www.fourmilab.ch/smartall/
15
16   
17          Version $Id$
18
19 */
20
21 /*
22    Copyright (C) 2000-2003 Kern Sibbald and John Walker
23
24    This program is free software; you can redistribute it and/or
25    modify it under the terms of the GNU General Public License as
26    published by the Free Software Foundation; either version 2 of
27    the License, or (at your option) any later version.
28
29    This program is distributed in the hope that it will be useful,
30    but WITHOUT ANY WARRANTY; without even the implied warranty of
31    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
32    General Public License for more details.
33
34    You should have received a copy of the GNU General Public
35    License along with this program; if not, write to the Free
36    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
37    MA 02111-1307, USA.
38
39  */
40
41 #include "bacula.h"
42 /* Use the real routines here */
43 #undef realloc
44 #undef calloc
45 #undef malloc
46 #undef free
47       
48
49
50 #ifdef SMARTALLOC
51
52 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
53
54 extern char my_name[];                /* daemon name */
55
56 typedef unsigned short sm_ushort;
57
58 #define EOS      '\0'              /* End of string sentinel */
59 #define sm_min(a, b) ((a) < (b) ? (a) : (b))
60
61 /*  Queue data structures  */
62
63 /*  Memory allocation control structures and storage.  */
64
65 struct abufhead {
66         struct b_queue abq;          /* Links on allocated queue */
67         unsigned ablen;            /* Buffer length in bytes */
68         char *abfname;             /* File name pointer */
69         sm_ushort ablineno;        /* Line number of allocation */ 
70 };
71
72 static struct b_queue abqueue = {    /* Allocated buffer queue */
73         &abqueue, &abqueue
74 };
75
76 static Boolean bufimode = False;   /* Buffers not tracked when True */
77
78 #define HEAD_SIZE BALIGN(sizeof(struct abufhead))
79
80
81 /*  SMALLOC  --  Allocate buffer, enqueing on the orphaned buffer
82                  tracking list.  */
83
84 static void *smalloc(char *fname, int lineno, unsigned int nbytes)
85 {
86         char *buf;
87
88         /* Note:  Unix  MALLOC  actually  permits  a zero length to be
89            passed and allocates a valid block with  zero  user  bytes.
90            Such  a  block  can  later  be expanded with realloc().  We
91            disallow this based on the belief that it's better to  make
92            a  special case and allocate one byte in the rare case this
93            is desired than to miss all the erroneous occurrences where
94            buffer length calculation code results in a zero.  */
95
96         ASSERT(nbytes > 0);
97
98         nbytes += HEAD_SIZE + 1;
99         if ((buf = (char *)malloc(nbytes)) != NULL) {
100            P(mutex);
101            /* Enqueue buffer on allocated list */
102            qinsert(&abqueue, (struct b_queue *) buf);
103            ((struct abufhead *) buf)->ablen = nbytes;
104            ((struct abufhead *) buf)->abfname = bufimode ? NULL : fname;
105            ((struct abufhead *) buf)->ablineno = (sm_ushort) lineno;
106            /* Emplace end-clobber detector at end of buffer */
107            buf[nbytes - 1] = (((long) buf) & 0xFF) ^ 0xC5;
108            buf += HEAD_SIZE;  /* Increment to user data start */
109            V(mutex);
110         }
111         Dmsg4(1150, "smalloc %d at %x from %s:%d\n", nbytes, buf, fname, lineno);
112         return (void *)buf;
113 }
114
115 /*  SM_NEW_OWNER -- Update the File and line number for a buffer
116                     This is to accomodate mem_pool. */
117
118 void sm_new_owner(char *fname, int lineno, char *buf)
119 {
120         buf -= HEAD_SIZE;  /* Decrement to header */
121         ((struct abufhead *)buf)->abfname = bufimode ? NULL : fname;
122         ((struct abufhead *)buf)->ablineno = (sm_ushort) lineno;
123         return;
124 }
125
126 /*  SM_FREE  --  Update free pool availability.  FREE is never called
127                  except  through  this interface or by actuallyfree().
128                  free(x)  is  defined  to  generate  a  call  to  this
129                  routine.  */
130
131 void sm_free(char *file, int line, void *fp)
132 {
133         char *cp = (char *) fp;
134         struct b_queue *qp;
135
136         if (cp == NULL) {
137            Emsg2(M_ABORT, 0, "Attempt to free NULL called from %s:%d\n", file, line);
138         }
139
140         cp -= HEAD_SIZE;
141         qp = (struct b_queue *) cp;
142
143         P(mutex);
144         Dmsg4(1150, "sm_free %d at %x from %s:%d\n", 
145               ((struct abufhead *)cp)->ablen, fp, 
146               ((struct abufhead *)cp)->abfname, ((struct abufhead *)cp)->ablineno);
147
148         /* The following assertions will catch virtually every release
149            of an address which isn't an allocated buffer. */
150         if (qp->qnext->qprev != qp) {
151            V(mutex);
152            Emsg2(M_ABORT, 0, "qp->qnext->qprev != qp called from %s:%d\n", file, line);
153         }
154         if (qp->qprev->qnext != qp) {
155            V(mutex);
156            Emsg2(M_ABORT, 0, "qp->qprev->qnext != qp called from %s:%d\n", file, line);
157         }
158
159         /* The following assertion detects storing off the  end  of  the
160            allocated  space in the buffer by comparing the end of buffer
161            checksum with the address of the buffer.  */
162
163         if (((unsigned char *) cp)[((struct abufhead *) cp)->ablen - 1] !=
164                  ((((long) cp) & 0xFF) ^ 0xC5)) {
165            V(mutex);
166            Emsg2(M_ABORT, 0, "Buffer overrun called from %s:%d\n", file, line);
167         }
168
169
170         qdchain(qp);
171         V(mutex);
172
173         /* Now we wipe the contents of  the  just-released  buffer  with
174            "designer  garbage"  (Duff  Kurland's  phrase) of alternating
175            bits.  This is intended to ruin the day for any miscreant who
176            attempts to access data through a pointer into storage that's
177            been previously released. */
178
179         memset(cp, 0xAA, (int) ((struct abufhead *) cp)->ablen);
180
181         free(cp);
182 }
183
184 /*  SM_MALLOC  --  Allocate buffer.  NULL is returned if no memory
185                    was available.  */
186
187 void *sm_malloc(char *fname, int lineno, unsigned int nbytes)
188 {
189         void *buf;
190
191         if ((buf = smalloc(fname, lineno, nbytes)) != NULL) {
192
193            /* To catch sloppy code that assumes  buffers  obtained  from
194               malloc()  are  zeroed,  we  preset  the buffer contents to
195               "designer garbage" consisting of alternating bits.  */
196
197            memset(buf, 0x55, (int) nbytes);
198         }
199         return buf;
200 }
201
202 /*  SM_CALLOC  --  Allocate an array and clear it to zero.  */
203
204 void *sm_calloc(char *fname, int lineno,
205                 unsigned int nelem, unsigned int elsize)
206 {
207         void *buf;
208
209         if ((buf = smalloc(fname, lineno, nelem * elsize)) != NULL) {
210            memset(buf, 0, (int) (nelem * elsize));
211         }
212         return buf;
213 }
214
215 /*  SM_REALLOC  --  Adjust the size of a  previously  allocated  buffer.
216                     Note  that  the trick of "resurrecting" a previously
217                     freed buffer with realloc() is NOT supported by this
218                     function.   Further, because of the need to maintain
219                     our control storage, SM_REALLOC must always allocate
220                     a  new  block  and  copy  the data in the old block.
221                     This may result in programs which make heavy use  of
222                     realloc() running much slower than normally.  */
223
224 void *sm_realloc(char *fname, int lineno, void *ptr, unsigned int size)
225 {
226         unsigned osize;
227         void *buf;
228         char *cp = (char *) ptr;
229
230         Dmsg4(400, "sm_realloc %s:%d 0x%x %d\n", fname, lineno, ptr, size);
231         if (size <= 0) {
232            e_msg(fname, lineno, M_ABORT, 0, "sm_realloc size: %d\n", size);
233         }
234
235         /*  If  the  old  block  pointer  is  NULL, treat realloc() as a
236            malloc().  SVID is silent  on  this,  but  many  C  libraries
237            permit this.  */
238
239         if (ptr == NULL)
240            return sm_malloc(fname, lineno, size);
241
242         /* If the old and new sizes are the same, be a nice guy and just
243            return the buffer passed in.  */
244
245         cp -= HEAD_SIZE;
246         osize = ((struct abufhead *) cp)->ablen - (HEAD_SIZE + 1);
247         if (size == osize) {
248            return ptr;
249         }
250
251         /* Sizes differ.  Allocate a new buffer of the  requested  size.
252            If  we  can't  obtain  such a buffer, act as defined in SVID:
253            return NULL from  realloc()  and  leave  the  buffer  in  PTR
254            intact.  */
255
256         if ((buf = smalloc(fname, lineno, size)) != NULL) {
257            memcpy(buf, ptr, (int) sm_min(size, osize));
258            /* If the new buffer is larger than the old, fill the balance
259               of it with "designer garbage". */
260            if (size > osize) {
261               memset(((char *) buf) + osize, 0x55, (int) (size - osize));
262            }
263
264            /* All done.  Free and dechain the original buffer. */
265
266            sm_free(__FILE__, __LINE__, ptr);
267         }
268         Dmsg4(150, "sm_realloc %d at %x from %s:%d\n", size, buf, fname, lineno);
269         return buf;
270 }
271
272 /*  ACTUALLYMALLOC  --  Call the system malloc() function to obtain
273                         storage which will eventually be released
274                         by system or library routines not compiled
275                         using SMARTALLOC.  */
276
277 void *actuallymalloc(unsigned int size)
278 {
279         return malloc(size);
280 }
281
282 /*  ACTUALLYCALLOC  --  Call the system calloc() function to obtain
283                         storage which will eventually be released
284                         by system or library routines not compiled
285                         using SMARTALLOC.  */
286
287 void *actuallycalloc(unsigned int nelem, unsigned int elsize)
288 {
289         return calloc(nelem, elsize);
290 }
291
292 /*  ACTUALLYREALLOC  --  Call the system realloc() function to obtain
293                          storage which will eventually be released
294                          by system or library routines not compiled
295                          using SMARTALLOC.  */
296
297 void *actuallyrealloc(void *ptr, unsigned int size)
298 {
299         Dmsg2(400, "Actuallyrealloc 0x%x %d\n", ptr, size);
300         return realloc(ptr, size);
301 }
302
303 /*  ACTUALLYFREE  --  Interface to system free() function to release
304                       buffers allocated by low-level routines. */
305
306 void actuallyfree(void *cp)
307 {
308         free(cp);
309 }
310
311 /*  SM_DUMP  --  Print orphaned buffers (and dump them if BUFDUMP is
312  *               True).
313  *  N.B. DO NOT USE any Bacula print routines (Dmsg, Jmsg, Emsg, ...)
314  *    as they have all been shut down at this point.
315  */
316 void sm_dump(Boolean bufdump)
317 {
318         struct abufhead *ap;
319
320         P(mutex);
321
322         ap = (struct abufhead *)abqueue.qnext;
323
324         while (ap != (struct abufhead *) &abqueue) {
325
326            if ((ap == NULL) ||
327                (ap->abq.qnext->qprev != (struct b_queue *) ap) || 
328                (ap->abq.qprev->qnext != (struct b_queue *) ap)) {
329               fprintf(stderr,
330                  "\nOrphaned buffers exist.  Dump terminated following\n");
331               fprintf(stderr,
332                  "  discovery of bad links in chain of orphaned buffers.\n");
333               fprintf(stderr,
334                  "  Buffer address with bad links: %lx\n", (long) ap);
335               break;
336            }
337
338            if (ap->abfname != NULL) {
339               unsigned memsize = ap->ablen - (HEAD_SIZE + 1);
340               char errmsg[80];
341
342               sprintf(errmsg,
343                 "Orphaned buffer:  %6u bytes allocated at line %d of %s %s\n",
344                  memsize, ap->ablineno, my_name, ap->abfname
345               );
346               fprintf(stderr, "%s", errmsg);
347               if (bufdump) {
348                  unsigned llen = 0;
349                  char *cp = ((char *) ap) + HEAD_SIZE;
350
351                  errmsg[0] = EOS;
352                  while (memsize) {
353                     if (llen >= 16) {
354                        strcat(errmsg, "\n");
355                        llen = 0;
356                        fprintf(stderr, "%s", errmsg);
357                        errmsg[0] = EOS;
358                     }
359                     sprintf(errmsg + strlen(errmsg), " %02X",
360                        (*cp++) & 0xFF);
361                     llen++;
362                     memsize--;
363                  }
364                  fprintf(stderr, "%s\n", errmsg);
365               }
366            }
367            ap = (struct abufhead *) ap->abq.qnext;
368         }
369         V(mutex);
370 }
371
372 #undef sm_check
373 /*  SM_CHECK --  Check the buffers and dump if any damage exists. */
374 void sm_check(char *fname, int lineno, Boolean bufdump)
375 {
376         if (!sm_check_rtn(fname, lineno, bufdump)) {
377            Emsg2(M_ABORT, 0, "Damaged buffer found. Called from %s:%d\n",
378               fname, lineno);
379         }
380 }
381
382 #undef sm_check_rtn
383 /*  SM_CHECK_RTN -- Check the buffers and return 1 if OK otherwise 0 */
384 int sm_check_rtn(char *fname, int lineno, Boolean bufdump)
385 {
386         struct abufhead *ap;
387         int bad, badbuf = 0;
388
389         P(mutex);
390         ap = (struct abufhead *) abqueue.qnext;
391         while (ap != (struct abufhead *) &abqueue) {
392            bad = 0;
393            if ((ap == NULL) ||
394                (ap->abq.qnext->qprev != (struct b_queue *) ap)) {
395               bad = 0x1;
396            }
397            if (ap->abq.qprev->qnext != (struct b_queue *) ap) { 
398               bad |= 0x2;
399            }
400            if (((unsigned char *) ap)[((struct abufhead *) ap)->ablen - 1] !=
401                 ((((long) ap) & 0xFF) ^ 0xC5)) {
402               bad |= 0x4;
403            }
404            badbuf |= bad;
405            if (bad) {
406               fprintf(stderr,
407                  "\nDamaged buffers found at %s:%d\n", fname, lineno);
408
409               if (bad & 0x1) {
410                  fprintf(stderr, "  discovery of bad prev link.\n");
411               }
412               if (bad & 0x2) {
413                  fprintf(stderr, "  discovery of bad next link.\n");
414               }
415               if (bad & 0x4) {
416                  fprintf(stderr, "  discovery of data overrun.\n");
417               }
418
419               fprintf(stderr, "  Buffer address: %lx\n", (long) ap);
420
421               if (ap->abfname != NULL) {
422                  unsigned memsize = ap->ablen - (HEAD_SIZE + 1);
423                  char errmsg[80];
424
425                  fprintf(stderr,
426                    "Damaged buffer:  %6u bytes allocated at line %d of %s %s\n",
427                     memsize, ap->ablineno, my_name, ap->abfname
428                  );
429                  if (bufdump) {
430                     unsigned llen = 0;
431                     char *cp = ((char *) ap) + HEAD_SIZE;
432
433                     errmsg[0] = EOS;
434                     while (memsize) {
435                        if (llen >= 16) {
436                           strcat(errmsg, "\n");
437                           llen = 0;
438                           fprintf(stderr, "%s", errmsg);
439                           errmsg[0] = EOS;
440                        }
441                        if (*cp < 0x20) {
442                           sprintf(errmsg + strlen(errmsg), " %02X",
443                              (*cp++) & 0xFF);
444                        } else {
445                           sprintf(errmsg + strlen(errmsg), " %c ",
446                              (*cp++) & 0xFF);
447                        }
448                        llen++;
449                        memsize--;
450                     }
451                     fprintf(stderr, "%s\n", errmsg);
452                  }
453               }
454            }
455            ap = (struct abufhead *) ap->abq.qnext;
456         }
457         V(mutex);
458         return badbuf ? 0 : 1;
459 }
460
461
462 /*  SM_STATIC  --  Orphaned buffer detection can be disabled  (for  such
463                    items  as buffers allocated during initialisation) by
464                    calling   sm_static(1).    Normal   orphaned   buffer
465                    detection  can be re-enabled with sm_static(0).  Note
466                    that all the other safeguards still apply to  buffers
467                    allocated  when  sm_static(1)  mode is in effect.  */
468
469 void sm_static(int mode)
470 {
471         bufimode = (Boolean) (mode != 0);
472 }
473
474 #endif