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