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