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