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