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