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