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