gmem: Clarify that a NULL check is not needed before calling g_free()
[platform/upstream/glib.git] / glib / gmem.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GLib Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
23  */
24
25 /* 
26  * MT safe
27  */
28
29 #include "config.h"
30
31 #include "gmem.h"
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <signal.h>
36
37 #include "gslice.h"
38 #include "gbacktrace.h"
39 #include "gtestutils.h"
40 #include "gthread.h"
41 #include "glib_trace.h"
42
43 #define MEM_PROFILE_TABLE_SIZE 4096
44
45
46 /* notes on macros:
47  * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
48  * g_mem_profile().
49  * If g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
50  */
51
52 /* --- variables --- */
53 static GMemVTable glib_mem_vtable = {
54   malloc,
55   realloc,
56   free,
57   calloc,
58   malloc,
59   realloc,
60 };
61
62 /**
63  * SECTION:memory
64  * @Short_Description: general memory-handling
65  * @Title: Memory Allocation
66  * 
67  * These functions provide support for allocating and freeing memory.
68  * 
69  * If any call to allocate memory fails, the application is terminated.
70  * This also means that there is no need to check if the call succeeded.
71  * 
72  * It's important to match g_malloc() (and wrappers such as g_new()) with
73  * g_free(), g_slice_alloc() (and wrappers such as g_slice_new()) with
74  * g_slice_free(), plain malloc() with free(), and (if you're using C++)
75  * new with delete and new[] with delete[]. Otherwise bad things can happen,
76  * since these allocators may use different memory pools (and new/delete call
77  * constructors and destructors). See also g_mem_set_vtable().
78  */
79
80 /* --- functions --- */
81 /**
82  * g_malloc:
83  * @n_bytes: the number of bytes to allocate
84  * 
85  * Allocates @n_bytes bytes of memory.
86  * If @n_bytes is 0 it returns %NULL.
87  * 
88  * Returns: a pointer to the allocated memory
89  */
90 gpointer
91 g_malloc (gsize n_bytes)
92 {
93   if (G_LIKELY (n_bytes))
94     {
95       gpointer mem;
96
97       mem = glib_mem_vtable.malloc (n_bytes);
98       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
99       if (mem)
100         return mem;
101
102       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
103                G_STRLOC, n_bytes);
104     }
105
106   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
107
108   return NULL;
109 }
110
111 /**
112  * g_malloc0:
113  * @n_bytes: the number of bytes to allocate
114  * 
115  * Allocates @n_bytes bytes of memory, initialized to 0's.
116  * If @n_bytes is 0 it returns %NULL.
117  * 
118  * Returns: a pointer to the allocated memory
119  */
120 gpointer
121 g_malloc0 (gsize n_bytes)
122 {
123   if (G_LIKELY (n_bytes))
124     {
125       gpointer mem;
126
127       mem = glib_mem_vtable.calloc (1, n_bytes);
128       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
129       if (mem)
130         return mem;
131
132       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
133                G_STRLOC, n_bytes);
134     }
135
136   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
137
138   return NULL;
139 }
140
141 /**
142  * g_realloc:
143  * @mem: (allow-none): the memory to reallocate
144  * @n_bytes: new size of the memory in bytes
145  * 
146  * Reallocates the memory pointed to by @mem, so that it now has space for
147  * @n_bytes bytes of memory. It returns the new address of the memory, which may
148  * have been moved. @mem may be %NULL, in which case it's considered to
149  * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
150  * and @mem will be freed unless it is %NULL.
151  * 
152  * Returns: the new address of the allocated memory
153  */
154 gpointer
155 g_realloc (gpointer mem,
156            gsize    n_bytes)
157 {
158   gpointer newmem;
159
160   if (G_LIKELY (n_bytes))
161     {
162       newmem = glib_mem_vtable.realloc (mem, n_bytes);
163       TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
164       if (newmem)
165         return newmem;
166
167       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
168                G_STRLOC, n_bytes);
169     }
170
171   if (mem)
172     glib_mem_vtable.free (mem);
173
174   TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
175
176   return NULL;
177 }
178
179 /**
180  * g_free:
181  * @mem: (allow-none): the memory to free
182  * 
183  * Frees the memory pointed to by @mem.
184  *
185  * If @mem is %NULL it simply returns, so there is no need to check @mem
186  * against %NULL before calling this function.
187  */
188 void
189 g_free (gpointer mem)
190 {
191   if (G_LIKELY (mem))
192     glib_mem_vtable.free (mem);
193   TRACE(GLIB_MEM_FREE((void*) mem));
194 }
195
196 /**
197  * g_clear_pointer: (skip)
198  * @pp: a pointer to a variable, struct member etc. holding a pointer
199  * @destroy: a function to which a gpointer can be passed, to destroy *@pp
200  *
201  * Clears a reference to a variable.
202  *
203  * @pp must not be %NULL.
204  *
205  * If the reference is %NULL then this function does nothing.
206  * Otherwise, the variable is destroyed using @destroy and the
207  * pointer is set to %NULL.
208  *
209  * A macro is also included that allows this function to be used without
210  * pointer casts.
211  *
212  * Since: 2.34
213  **/
214 #undef g_clear_pointer
215 void
216 g_clear_pointer (gpointer      *pp,
217                  GDestroyNotify destroy)
218 {
219   gpointer _p;
220
221   _p = *pp;
222   if (_p)
223     {
224       *pp = NULL;
225       destroy (_p);
226     }
227 }
228
229 /**
230  * g_try_malloc:
231  * @n_bytes: number of bytes to allocate.
232  * 
233  * Attempts to allocate @n_bytes, and returns %NULL on failure.
234  * Contrast with g_malloc(), which aborts the program on failure.
235  * 
236  * Returns: the allocated memory, or %NULL.
237  */
238 gpointer
239 g_try_malloc (gsize n_bytes)
240 {
241   gpointer mem;
242
243   if (G_LIKELY (n_bytes))
244     mem = glib_mem_vtable.try_malloc (n_bytes);
245   else
246     mem = NULL;
247
248   TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
249
250   return mem;
251 }
252
253 /**
254  * g_try_malloc0:
255  * @n_bytes: number of bytes to allocate
256  * 
257  * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
258  * failure. Contrast with g_malloc0(), which aborts the program on failure.
259  * 
260  * Since: 2.8
261  * Returns: the allocated memory, or %NULL
262  */
263 gpointer
264 g_try_malloc0 (gsize n_bytes)
265 {
266   gpointer mem;
267
268   if (G_LIKELY (n_bytes))
269     mem = glib_mem_vtable.try_malloc (n_bytes);
270   else
271     mem = NULL;
272
273   if (mem)
274     memset (mem, 0, n_bytes);
275
276   return mem;
277 }
278
279 /**
280  * g_try_realloc:
281  * @mem: (allow-none): previously-allocated memory, or %NULL.
282  * @n_bytes: number of bytes to allocate.
283  * 
284  * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
285  * on failure. Contrast with g_realloc(), which aborts the program
286  * on failure.
287  *
288  * If @mem is %NULL, behaves the same as g_try_malloc().
289  * 
290  * Returns: the allocated memory, or %NULL.
291  */
292 gpointer
293 g_try_realloc (gpointer mem,
294                gsize    n_bytes)
295 {
296   gpointer newmem;
297
298   if (G_LIKELY (n_bytes))
299     newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
300   else
301     {
302       newmem = NULL;
303       if (mem)
304         glib_mem_vtable.free (mem);
305     }
306
307   TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
308
309   return newmem;
310 }
311
312
313 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
314
315 /**
316  * g_malloc_n:
317  * @n_blocks: the number of blocks to allocate
318  * @n_block_bytes: the size of each block in bytes
319  * 
320  * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
321  * but care is taken to detect possible overflow during multiplication.
322  * 
323  * Since: 2.24
324  * Returns: a pointer to the allocated memory
325  */
326 gpointer
327 g_malloc_n (gsize n_blocks,
328             gsize n_block_bytes)
329 {
330   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
331     {
332       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
333                G_STRLOC, n_blocks, n_block_bytes);
334     }
335
336   return g_malloc (n_blocks * n_block_bytes);
337 }
338
339 /**
340  * g_malloc0_n:
341  * @n_blocks: the number of blocks to allocate
342  * @n_block_bytes: the size of each block in bytes
343  * 
344  * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
345  * but care is taken to detect possible overflow during multiplication.
346  * 
347  * Since: 2.24
348  * Returns: a pointer to the allocated memory
349  */
350 gpointer
351 g_malloc0_n (gsize n_blocks,
352              gsize n_block_bytes)
353 {
354   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
355     {
356       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
357                G_STRLOC, n_blocks, n_block_bytes);
358     }
359
360   return g_malloc0 (n_blocks * n_block_bytes);
361 }
362
363 /**
364  * g_realloc_n:
365  * @mem: (allow-none): the memory to reallocate
366  * @n_blocks: the number of blocks to allocate
367  * @n_block_bytes: the size of each block in bytes
368  * 
369  * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
370  * but care is taken to detect possible overflow during multiplication.
371  * 
372  * Since: 2.24
373  * Returns: the new address of the allocated memory
374  */
375 gpointer
376 g_realloc_n (gpointer mem,
377              gsize    n_blocks,
378              gsize    n_block_bytes)
379 {
380   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
381     {
382       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
383                G_STRLOC, n_blocks, n_block_bytes);
384     }
385
386   return g_realloc (mem, n_blocks * n_block_bytes);
387 }
388
389 /**
390  * g_try_malloc_n:
391  * @n_blocks: the number of blocks to allocate
392  * @n_block_bytes: the size of each block in bytes
393  * 
394  * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
395  * but care is taken to detect possible overflow during multiplication.
396  * 
397  * Since: 2.24
398  * Returns: the allocated memory, or %NULL.
399  */
400 gpointer
401 g_try_malloc_n (gsize n_blocks,
402                 gsize n_block_bytes)
403 {
404   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
405     return NULL;
406
407   return g_try_malloc (n_blocks * n_block_bytes);
408 }
409
410 /**
411  * g_try_malloc0_n:
412  * @n_blocks: the number of blocks to allocate
413  * @n_block_bytes: the size of each block in bytes
414  * 
415  * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
416  * but care is taken to detect possible overflow during multiplication.
417  * 
418  * Since: 2.24
419  * Returns: the allocated memory, or %NULL
420  */
421 gpointer
422 g_try_malloc0_n (gsize n_blocks,
423                  gsize n_block_bytes)
424 {
425   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
426     return NULL;
427
428   return g_try_malloc0 (n_blocks * n_block_bytes);
429 }
430
431 /**
432  * g_try_realloc_n:
433  * @mem: (allow-none): previously-allocated memory, or %NULL.
434  * @n_blocks: the number of blocks to allocate
435  * @n_block_bytes: the size of each block in bytes
436  * 
437  * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
438  * but care is taken to detect possible overflow during multiplication.
439  * 
440  * Since: 2.24
441  * Returns: the allocated memory, or %NULL.
442  */
443 gpointer
444 g_try_realloc_n (gpointer mem,
445                  gsize    n_blocks,
446                  gsize    n_block_bytes)
447 {
448   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
449     return NULL;
450
451   return g_try_realloc (mem, n_blocks * n_block_bytes);
452 }
453
454
455
456 static gpointer
457 fallback_calloc (gsize n_blocks,
458                  gsize n_block_bytes)
459 {
460   gsize l = n_blocks * n_block_bytes;
461   gpointer mem = glib_mem_vtable.malloc (l);
462
463   if (mem)
464     memset (mem, 0, l);
465
466   return mem;
467 }
468
469 static gboolean vtable_set = FALSE;
470
471 /**
472  * g_mem_is_system_malloc:
473  * 
474  * Checks whether the allocator used by g_malloc() is the system's
475  * malloc implementation. If it returns %TRUE memory allocated with
476  * malloc() can be used interchangeable with memory allocated using g_malloc().
477  * This function is useful for avoiding an extra copy of allocated memory returned
478  * by a non-GLib-based API.
479  *
480  * A different allocator can be set using g_mem_set_vtable().
481  *
482  * Returns: if %TRUE, malloc() and g_malloc() can be mixed.
483  **/
484 gboolean
485 g_mem_is_system_malloc (void)
486 {
487   return !vtable_set;
488 }
489
490 /**
491  * g_mem_set_vtable:
492  * @vtable: table of memory allocation routines.
493  * 
494  * Sets the #GMemVTable to use for memory allocation. You can use this
495  * to provide custom memory allocation routines.
496  *
497  * The @vtable only needs to provide malloc(), realloc(), and free()
498  * functions; GLib can provide default implementations of the others.
499  * The malloc() and realloc() implementations should return %NULL on
500  * failure, GLib will handle error-checking for you. @vtable is copied,
501  * so need not persist after this function has been called.
502  *
503  * Note that this function must be called before using any other GLib
504  * functions.
505  */
506 void
507 g_mem_set_vtable (GMemVTable *vtable)
508 {
509   if (!vtable_set)
510     {
511       if (vtable->malloc && vtable->realloc && vtable->free)
512         {
513           glib_mem_vtable.malloc = vtable->malloc;
514           glib_mem_vtable.realloc = vtable->realloc;
515           glib_mem_vtable.free = vtable->free;
516           glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
517           glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
518           glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
519           vtable_set = TRUE;
520         }
521       else
522         g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
523     }
524   else
525     g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
526 }
527
528
529 /* --- memory profiling and checking --- */
530 #ifdef  G_DISABLE_CHECKS
531 /**
532  * glib_mem_profiler_table:
533  * 
534  * A #GMemVTable containing profiling variants of the memory
535  * allocation functions. Use them together with g_mem_profile()
536  * in order to get information about the memory allocation pattern
537  * of your program.
538  */
539 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
540 void
541 g_mem_profile (void)
542 {
543 }
544 #else   /* !G_DISABLE_CHECKS */
545 typedef enum {
546   PROFILER_FREE         = 0,
547   PROFILER_ALLOC        = 1,
548   PROFILER_RELOC        = 2,
549   PROFILER_ZINIT        = 4
550 } ProfilerJob;
551 static guint *profile_data = NULL;
552 static gsize profile_allocs = 0;
553 static gsize profile_zinit = 0;
554 static gsize profile_frees = 0;
555 static GMutex gmem_profile_mutex;
556
557 #define PROFILE_TABLE(f1,f2,f3)   ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
558
559 static void
560 profiler_log (ProfilerJob job,
561               gsize       n_bytes,
562               gboolean    success)
563 {
564   g_mutex_lock (&gmem_profile_mutex);
565   if (!profile_data)
566     {
567       profile_data = calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8, 
568                              sizeof (profile_data[0]));
569       if (!profile_data)        /* memory system kiddin' me, eh? */
570         {
571           g_mutex_unlock (&gmem_profile_mutex);
572           return;
573         }
574     }
575
576   if (n_bytes < MEM_PROFILE_TABLE_SIZE)
577     profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
578                                           (job & PROFILER_RELOC) != 0,
579                                           success != 0)] += 1;
580   else
581     profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
582                                                          (job & PROFILER_RELOC) != 0,
583                                                          success != 0)] += 1;
584   if (success)
585     {
586       if (job & PROFILER_ALLOC)
587         {
588           profile_allocs += n_bytes;
589           if (job & PROFILER_ZINIT)
590             profile_zinit += n_bytes;
591         }
592       else
593         profile_frees += n_bytes;
594     }
595   g_mutex_unlock (&gmem_profile_mutex);
596 }
597
598 static void
599 profile_print_locked (guint   *local_data,
600                       gboolean success)
601 {
602   gboolean need_header = TRUE;
603   guint i;
604
605   for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
606     {
607       glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
608       glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
609       glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
610       glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
611       
612       if (!t_malloc && !t_realloc && !t_free && !t_refree)
613         continue;
614       else if (need_header)
615         {
616           need_header = FALSE;
617           g_print (" blocks of | allocated  | freed      | allocated  | freed      | n_bytes   \n");
618           g_print ("  n_bytes  | n_times by | n_times by | n_times by | n_times by | remaining \n");
619           g_print ("           | malloc()   | free()     | realloc()  | realloc()  |           \n");
620           g_print ("===========|============|============|============|============|===========\n");
621         }
622       if (i < MEM_PROFILE_TABLE_SIZE)
623         g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
624                  i, t_malloc, t_free, t_realloc, t_refree,
625                  (t_malloc - t_free + t_realloc - t_refree) * i);
626       else if (i >= MEM_PROFILE_TABLE_SIZE)
627         g_print ("   >%6u | %10ld | %10ld | %10ld | %10ld |        ***\n",
628                  i, t_malloc, t_free, t_realloc, t_refree);
629     }
630   if (need_header)
631     g_print (" --- none ---\n");
632 }
633
634 /**
635  * g_mem_profile:
636  * 
637  * Outputs a summary of memory usage.
638  * 
639  * It outputs the frequency of allocations of different sizes,
640  * the total number of bytes which have been allocated,
641  * the total number of bytes which have been freed,
642  * and the difference between the previous two values, i.e. the number of bytes
643  * still in use.
644  * 
645  * Note that this function will not output anything unless you have
646  * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
647  */
648
649 void
650 g_mem_profile (void)
651 {
652   guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8];
653   gsize local_allocs;
654   gsize local_zinit;
655   gsize local_frees;
656
657   g_mutex_lock (&gmem_profile_mutex);
658
659   local_allocs = profile_allocs;
660   local_zinit = profile_zinit;
661   local_frees = profile_frees;
662
663   if (!profile_data)
664     {
665       g_mutex_unlock (&gmem_profile_mutex);
666       return;
667     }
668
669   memcpy (local_data, profile_data, 
670           (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
671   
672   g_mutex_unlock (&gmem_profile_mutex);
673
674   g_print ("GLib Memory statistics (successful operations):\n");
675   profile_print_locked (local_data, TRUE);
676   g_print ("GLib Memory statistics (failing operations):\n");
677   profile_print_locked (local_data, FALSE);
678   g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
679            "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
680            "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
681            "remaining=%"G_GSIZE_FORMAT"\n",
682            local_allocs,
683            local_zinit,
684            ((gdouble) local_zinit) / local_allocs * 100.0,
685            local_frees,
686            ((gdouble) local_frees) / local_allocs * 100.0,
687            local_allocs - local_frees);
688 }
689
690 static gpointer
691 profiler_try_malloc (gsize n_bytes)
692 {
693   gsize *p;
694
695   p = malloc (sizeof (gsize) * 2 + n_bytes);
696
697   if (p)
698     {
699       p[0] = 0;         /* free count */
700       p[1] = n_bytes;   /* length */
701       profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
702       p += 2;
703     }
704   else
705     profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
706   
707   return p;
708 }
709
710 static gpointer
711 profiler_malloc (gsize n_bytes)
712 {
713   gpointer mem = profiler_try_malloc (n_bytes);
714
715   if (!mem)
716     g_mem_profile ();
717
718   return mem;
719 }
720
721 static gpointer
722 profiler_calloc (gsize n_blocks,
723                  gsize n_block_bytes)
724 {
725   gsize l = n_blocks * n_block_bytes;
726   gsize *p;
727
728   p = calloc (1, sizeof (gsize) * 2 + l);
729
730   if (p)
731     {
732       p[0] = 0;         /* free count */
733       p[1] = l;         /* length */
734       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
735       p += 2;
736     }
737   else
738     {
739       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
740       g_mem_profile ();
741     }
742
743   return p;
744 }
745
746 static void
747 profiler_free (gpointer mem)
748 {
749   gsize *p = mem;
750
751   p -= 2;
752   if (p[0])     /* free count */
753     {
754       g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
755                  p + 2, p[0]);
756       profiler_log (PROFILER_FREE,
757                     p[1],       /* length */
758                     FALSE);
759     }
760   else
761     {
762       profiler_log (PROFILER_FREE,
763                     p[1],       /* length */
764                     TRUE);
765       memset (p + 2, 0xaa, p[1]);
766
767       /* for all those that miss free (p); in this place, yes,
768        * we do leak all memory when profiling, and that is intentional
769        * to catch double frees. patch submissions are futile.
770        */
771     }
772   p[0] += 1;
773 }
774
775 static gpointer
776 profiler_try_realloc (gpointer mem,
777                       gsize    n_bytes)
778 {
779   gsize *p = mem;
780
781   p -= 2;
782   
783   if (mem && p[0])      /* free count */
784     {
785       g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
786                  "memory has been freed %"G_GSIZE_FORMAT" times already",
787                  p + 2, (gsize) n_bytes, p[0]);
788       profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
789
790       return NULL;
791     }
792   else
793     {
794       p = realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
795
796       if (p)
797         {
798           if (mem)
799             profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
800           p[0] = 0;
801           p[1] = n_bytes;
802           profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
803           p += 2;
804         }
805       else
806         profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
807
808       return p;
809     }
810 }
811
812 static gpointer
813 profiler_realloc (gpointer mem,
814                   gsize    n_bytes)
815 {
816   mem = profiler_try_realloc (mem, n_bytes);
817
818   if (!mem)
819     g_mem_profile ();
820
821   return mem;
822 }
823
824 static GMemVTable profiler_table = {
825   profiler_malloc,
826   profiler_realloc,
827   profiler_free,
828   profiler_calloc,
829   profiler_try_malloc,
830   profiler_try_realloc,
831 };
832 GMemVTable *glib_mem_profiler_table = &profiler_table;
833
834 #endif  /* !G_DISABLE_CHECKS */