002ddd8f58bbfc586eaf23a35c28cffef9520daa
[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 <stdlib.h>
34 #include <string.h>
35 #include <signal.h>
36
37 #include "glib.h"
38 #include "gthreadinit.h"
39 #include "galias.h"
40
41 #define MEM_PROFILE_TABLE_SIZE 4096
42
43
44 /* notes on macros:
45  * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
46  * g_mem_profile().
47  * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
48  * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
49  * match the corresponding GLib prototypes, keep configure.in and gmem.h in sync here.
50  * g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
51  */
52
53 /* --- prototypes --- */
54 static gboolean g_mem_initialized = FALSE;
55 static void     g_mem_init_nomessage (void);
56
57
58 /* --- malloc wrappers --- */
59 #ifndef REALLOC_0_WORKS
60 static gpointer
61 standard_realloc (gpointer mem,
62                   gsize    n_bytes)
63 {
64   if (!mem)
65     return malloc (n_bytes);
66   else
67     return realloc (mem, n_bytes);
68 }
69 #endif  /* !REALLOC_0_WORKS */
70
71 #ifdef SANE_MALLOC_PROTOS
72 #  define standard_malloc       malloc
73 #  ifdef REALLOC_0_WORKS
74 #    define standard_realloc    realloc
75 #  endif /* REALLOC_0_WORKS */
76 #  define standard_free         free
77 #  define standard_calloc       calloc
78 #  define standard_try_malloc   malloc
79 #  define standard_try_realloc  realloc
80 #else   /* !SANE_MALLOC_PROTOS */
81 static gpointer
82 standard_malloc (gsize n_bytes)
83 {
84   return malloc (n_bytes);
85 }
86 #  ifdef REALLOC_0_WORKS
87 static gpointer
88 standard_realloc (gpointer mem,
89                   gsize    n_bytes)
90 {
91   return realloc (mem, n_bytes);
92 }
93 #  endif /* REALLOC_0_WORKS */
94 static void
95 standard_free (gpointer mem)
96 {
97   free (mem);
98 }
99 static gpointer
100 standard_calloc (gsize n_blocks,
101                  gsize n_bytes)
102 {
103   return calloc (n_blocks, n_bytes);
104 }
105 #define standard_try_malloc     standard_malloc
106 #define standard_try_realloc    standard_realloc
107 #endif  /* !SANE_MALLOC_PROTOS */
108
109
110 /* --- variables --- */
111 static GMemVTable glib_mem_vtable = {
112   standard_malloc,
113   standard_realloc,
114   standard_free,
115   standard_calloc,
116   standard_try_malloc,
117   standard_try_realloc,
118 };
119
120
121 /* --- functions --- */
122 gpointer
123 g_malloc (gulong n_bytes)
124 {
125   if (G_UNLIKELY (!g_mem_initialized))
126     g_mem_init_nomessage();
127   if (G_LIKELY (n_bytes))
128     {
129       gpointer mem;
130
131       mem = glib_mem_vtable.malloc (n_bytes);
132       if (mem)
133         return mem;
134
135       g_error ("%s: failed to allocate %lu bytes", G_STRLOC, n_bytes);
136     }
137
138   return NULL;
139 }
140
141 gpointer
142 g_malloc0 (gulong n_bytes)
143 {
144   if (G_UNLIKELY (!g_mem_initialized))
145     g_mem_init_nomessage();
146   if (G_LIKELY (n_bytes))
147     {
148       gpointer mem;
149
150       mem = glib_mem_vtable.calloc (1, n_bytes);
151       if (mem)
152         return mem;
153
154       g_error ("%s: failed to allocate %lu bytes", G_STRLOC, n_bytes);
155     }
156
157   return NULL;
158 }
159
160 gpointer
161 g_realloc (gpointer mem,
162            gulong   n_bytes)
163 {
164   if (G_UNLIKELY (!g_mem_initialized))
165     g_mem_init_nomessage();
166   if (G_LIKELY (n_bytes))
167     {
168       mem = glib_mem_vtable.realloc (mem, n_bytes);
169       if (mem)
170         return mem;
171
172       g_error ("%s: failed to allocate %lu bytes", G_STRLOC, n_bytes);
173     }
174
175   if (mem)
176     glib_mem_vtable.free (mem);
177
178   return NULL;
179 }
180
181 void
182 g_free (gpointer mem)
183 {
184   if (G_UNLIKELY (!g_mem_initialized))
185     g_mem_init_nomessage();
186   if (G_LIKELY (mem))
187     glib_mem_vtable.free (mem);
188 }
189
190 gpointer
191 g_try_malloc (gulong n_bytes)
192 {
193   if (G_UNLIKELY (!g_mem_initialized))
194     g_mem_init_nomessage();
195   if (G_LIKELY (n_bytes))
196     return glib_mem_vtable.try_malloc (n_bytes);
197   else
198     return NULL;
199 }
200
201 gpointer
202 g_try_malloc0 (gulong n_bytes)
203
204   gpointer mem;
205
206   mem = g_try_malloc (n_bytes);
207   
208   if (mem)
209     memset (mem, 0, n_bytes);
210
211   return mem;
212 }
213
214 gpointer
215 g_try_realloc (gpointer mem,
216                gulong   n_bytes)
217 {
218   if (G_UNLIKELY (!g_mem_initialized))
219     g_mem_init_nomessage();
220   if (G_LIKELY (n_bytes))
221     return glib_mem_vtable.try_realloc (mem, n_bytes);
222
223   if (mem)
224     glib_mem_vtable.free (mem);
225
226   return NULL;
227 }
228
229 static gpointer
230 fallback_calloc (gsize n_blocks,
231                  gsize n_block_bytes)
232 {
233   gsize l = n_blocks * n_block_bytes;
234   gpointer mem = glib_mem_vtable.malloc (l);
235
236   if (mem)
237     memset (mem, 0, l);
238
239   return mem;
240 }
241
242 static gboolean vtable_set = FALSE;
243
244 /**
245  * g_mem_is_system_malloc
246  * 
247  * Checks whether the allocator used by g_malloc() is the system's
248  * malloc implementation. If it returns %TRUE memory allocated with
249  * malloc() can be used interchangeable with memory allocated using g_malloc(). 
250  * This function is useful for avoiding an extra copy of allocated memory returned
251  * by a non-GLib-based API.
252  *
253  * A different allocator can be set using g_mem_set_vtable().
254  *
255  * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
256  **/
257 gboolean
258 g_mem_is_system_malloc (void)
259 {
260   return !vtable_set;
261 }
262
263 void
264 g_mem_set_vtable (GMemVTable *vtable)
265 {
266   if (!vtable_set)
267     {
268       if (vtable->malloc && vtable->realloc && vtable->free)
269         {
270           glib_mem_vtable.malloc = vtable->malloc;
271           glib_mem_vtable.realloc = vtable->realloc;
272           glib_mem_vtable.free = vtable->free;
273           glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
274           glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
275           glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
276           vtable_set = TRUE;
277         }
278       else
279         g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
280     }
281   else
282     g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
283 }
284
285
286 /* --- memory profiling and checking --- */
287 #ifdef  G_DISABLE_CHECKS
288 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
289 void
290 g_mem_profile (void)
291 {
292 }
293 #else   /* !G_DISABLE_CHECKS */
294 typedef enum {
295   PROFILER_FREE         = 0,
296   PROFILER_ALLOC        = 1,
297   PROFILER_RELOC        = 2,
298   PROFILER_ZINIT        = 4
299 } ProfilerJob;
300 static guint *profile_data = NULL;
301 static gulong profile_allocs = 0;
302 static gulong profile_zinit = 0;
303 static gulong profile_frees = 0;
304 static GMutex *gmem_profile_mutex = NULL;
305 #ifdef  G_ENABLE_DEBUG
306 static volatile gulong g_trap_free_size = 0;
307 static volatile gulong g_trap_realloc_size = 0;
308 static volatile gulong g_trap_malloc_size = 0;
309 #endif  /* G_ENABLE_DEBUG */
310
311 #define PROFILE_TABLE(f1,f2,f3)   ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
312
313 static void
314 profiler_log (ProfilerJob job,
315               gulong      n_bytes,
316               gboolean    success)
317 {
318   g_mutex_lock (gmem_profile_mutex);
319   if (!profile_data)
320     {
321       profile_data = standard_malloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
322       if (!profile_data)        /* memory system kiddin' me, eh? */
323         {
324           g_mutex_unlock (gmem_profile_mutex);
325           return;
326         }
327     }
328
329   if (n_bytes < MEM_PROFILE_TABLE_SIZE)
330     profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
331                                           (job & PROFILER_RELOC) != 0,
332                                           success != 0)] += 1;
333   else
334     profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
335                                                          (job & PROFILER_RELOC) != 0,
336                                                          success != 0)] += 1;
337   if (success)
338     {
339       if (job & PROFILER_ALLOC)
340         {
341           profile_allocs += n_bytes;
342           if (job & PROFILER_ZINIT)
343             profile_zinit += n_bytes;
344         }
345       else
346         profile_frees += n_bytes;
347     }
348   g_mutex_unlock (gmem_profile_mutex);
349 }
350
351 static void
352 profile_print_locked (guint   *local_data,
353                       gboolean success)
354 {
355   gboolean need_header = TRUE;
356   guint i;
357
358   for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
359     {
360       glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
361       glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
362       glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
363       glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
364       
365       if (!t_malloc && !t_realloc && !t_free && !t_refree)
366         continue;
367       else if (need_header)
368         {
369           need_header = FALSE;
370           g_print (" blocks of | allocated  | freed      | allocated  | freed      | n_bytes   \n");
371           g_print ("  n_bytes  | n_times by | n_times by | n_times by | n_times by | remaining \n");
372           g_print ("           | malloc()   | free()     | realloc()  | realloc()  |           \n");
373           g_print ("===========|============|============|============|============|===========\n");
374         }
375       if (i < MEM_PROFILE_TABLE_SIZE)
376         g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
377                  i, t_malloc, t_free, t_realloc, t_refree,
378                  (t_malloc - t_free + t_realloc - t_refree) * i);
379       else if (i >= MEM_PROFILE_TABLE_SIZE)
380         g_print ("   >%6u | %10ld | %10ld | %10ld | %10ld |        ***\n",
381                  i, t_malloc, t_free, t_realloc, t_refree);
382     }
383   if (need_header)
384     g_print (" --- none ---\n");
385 }
386
387 void
388 g_mem_profile (void)
389 {
390   guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
391   gulong local_allocs;
392   gulong local_zinit;
393   gulong local_frees;
394
395   if (G_UNLIKELY (!g_mem_initialized))
396     g_mem_init_nomessage();
397
398   g_mutex_lock (gmem_profile_mutex);
399
400   local_allocs = profile_allocs;
401   local_zinit = profile_zinit;
402   local_frees = profile_frees;
403
404   if (!profile_data)
405     {
406       g_mutex_unlock (gmem_profile_mutex);
407       return;
408     }
409
410   memcpy (local_data, profile_data, 
411           (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
412   
413   g_mutex_unlock (gmem_profile_mutex);
414
415   g_print ("GLib Memory statistics (successful operations):\n");
416   profile_print_locked (local_data, TRUE);
417   g_print ("GLib Memory statistics (failing operations):\n");
418   profile_print_locked (local_data, FALSE);
419   g_print ("Total bytes: allocated=%lu, zero-initialized=%lu (%.2f%%), freed=%lu (%.2f%%), remaining=%lu\n",
420            local_allocs,
421            local_zinit,
422            ((gdouble) local_zinit) / local_allocs * 100.0,
423            local_frees,
424            ((gdouble) local_frees) / local_allocs * 100.0,
425            local_allocs - local_frees);
426 }
427
428 static gpointer
429 profiler_try_malloc (gsize n_bytes)
430 {
431   gulong *p;
432
433 #ifdef  G_ENABLE_DEBUG
434   if (g_trap_malloc_size == n_bytes)
435     G_BREAKPOINT ();
436 #endif  /* G_ENABLE_DEBUG */
437
438   p = standard_malloc (sizeof (gulong) * 2 + n_bytes);
439
440   if (p)
441     {
442       p[0] = 0;         /* free count */
443       p[1] = n_bytes;   /* length */
444       profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
445       p += 2;
446     }
447   else
448     profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
449   
450   return p;
451 }
452
453 static gpointer
454 profiler_malloc (gsize n_bytes)
455 {
456   gpointer mem = profiler_try_malloc (n_bytes);
457
458   if (!mem)
459     g_mem_profile ();
460
461   return mem;
462 }
463
464 static gpointer
465 profiler_calloc (gsize n_blocks,
466                  gsize n_block_bytes)
467 {
468   gsize l = n_blocks * n_block_bytes;
469   gulong *p;
470
471 #ifdef  G_ENABLE_DEBUG
472   if (g_trap_malloc_size == l)
473     G_BREAKPOINT ();
474 #endif  /* G_ENABLE_DEBUG */
475   
476   p = standard_calloc (1, sizeof (gulong) * 2 + l);
477
478   if (p)
479     {
480       p[0] = 0;         /* free count */
481       p[1] = l;         /* length */
482       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
483       p += 2;
484     }
485   else
486     {
487       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
488       g_mem_profile ();
489     }
490
491   return p;
492 }
493
494 static void
495 profiler_free (gpointer mem)
496 {
497   gulong *p = mem;
498
499   p -= 2;
500   if (p[0])     /* free count */
501     {
502       g_warning ("free(%p): memory has been freed %lu times already", p + 2, p[0]);
503       profiler_log (PROFILER_FREE,
504                     p[1],       /* length */
505                     FALSE);
506     }
507   else
508     {
509 #ifdef  G_ENABLE_DEBUG
510       if (g_trap_free_size == p[1])
511         G_BREAKPOINT ();
512 #endif  /* G_ENABLE_DEBUG */
513
514       profiler_log (PROFILER_FREE,
515                     p[1],       /* length */
516                     TRUE);
517       memset (p + 2, 0xaa, p[1]);
518
519       /* for all those that miss standard_free (p); in this place, yes,
520        * we do leak all memory when profiling, and that is intentional
521        * to catch double frees. patch submissions are futile.
522        */
523     }
524   p[0] += 1;
525 }
526
527 static gpointer
528 profiler_try_realloc (gpointer mem,
529                       gsize    n_bytes)
530 {
531   gulong *p = mem;
532
533   p -= 2;
534
535 #ifdef  G_ENABLE_DEBUG
536   if (g_trap_realloc_size == n_bytes)
537     G_BREAKPOINT ();
538 #endif  /* G_ENABLE_DEBUG */
539   
540   if (mem && p[0])      /* free count */
541     {
542       g_warning ("realloc(%p, %lu): memory has been freed %lu times already", p + 2, (gulong)n_bytes, p[0]);
543       profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
544
545       return NULL;
546     }
547   else
548     {
549       p = standard_realloc (mem ? p : NULL, sizeof (gulong) * 2 + n_bytes);
550
551       if (p)
552         {
553           if (mem)
554             profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
555           p[0] = 0;
556           p[1] = n_bytes;
557           profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
558           p += 2;
559         }
560       else
561         profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
562
563       return p;
564     }
565 }
566
567 static gpointer
568 profiler_realloc (gpointer mem,
569                   gsize    n_bytes)
570 {
571   mem = profiler_try_realloc (mem, n_bytes);
572
573   if (!mem)
574     g_mem_profile ();
575
576   return mem;
577 }
578
579 static GMemVTable profiler_table = {
580   profiler_malloc,
581   profiler_realloc,
582   profiler_free,
583   profiler_calloc,
584   profiler_try_malloc,
585   profiler_try_realloc,
586 };
587 GMemVTable *glib_mem_profiler_table = &profiler_table;
588
589 #endif  /* !G_DISABLE_CHECKS */
590
591 /* --- MemChunks --- */
592 #ifndef G_ALLOC_AND_FREE
593 typedef struct _GAllocator GAllocator;
594 typedef struct _GMemChunk  GMemChunk;
595 #define G_ALLOC_ONLY      1
596 #define G_ALLOC_AND_FREE  2
597 #endif
598
599 struct _GMemChunk {
600   guint alloc_size;           /* the size of an atom */
601 };
602
603 GMemChunk*
604 g_mem_chunk_new (const gchar  *name,
605                  gint          atom_size,
606                  gulong        area_size,
607                  gint          type)
608 {
609   GMemChunk *mem_chunk;
610   g_return_val_if_fail (atom_size > 0, NULL);
611
612   mem_chunk = g_slice_new (GMemChunk);
613   mem_chunk->alloc_size = atom_size;
614   return mem_chunk;
615 }
616
617 void
618 g_mem_chunk_destroy (GMemChunk *mem_chunk)
619 {
620   g_return_if_fail (mem_chunk != NULL);
621   
622   g_slice_free (GMemChunk, mem_chunk);
623 }
624
625 gpointer
626 g_mem_chunk_alloc (GMemChunk *mem_chunk)
627 {
628   g_return_val_if_fail (mem_chunk != NULL, NULL);
629   
630   return g_slice_alloc (mem_chunk->alloc_size);
631 }
632
633 gpointer
634 g_mem_chunk_alloc0 (GMemChunk *mem_chunk)
635 {
636   g_return_val_if_fail (mem_chunk != NULL, NULL);
637   
638   return g_slice_alloc0 (mem_chunk->alloc_size);
639 }
640
641 void
642 g_mem_chunk_free (GMemChunk *mem_chunk,
643                   gpointer   mem)
644 {
645   g_return_if_fail (mem_chunk != NULL);
646   
647   g_slice_free1 (mem_chunk->alloc_size, mem);
648 }
649
650 void    g_mem_chunk_clean       (GMemChunk *mem_chunk)  {}
651 void    g_mem_chunk_reset       (GMemChunk *mem_chunk)  {}
652 void    g_mem_chunk_print       (GMemChunk *mem_chunk)  {}
653 void    g_mem_chunk_info        (void)                  {}
654 void    g_blow_chunks           (void)                  {}
655
656 GAllocator*
657 g_allocator_new (const gchar *name,
658                  guint        n_preallocs)
659 {
660   static struct _GAllocator {
661     gchar      *name;
662     guint16     n_preallocs;
663     guint       is_unused : 1;
664     guint       type : 4;
665     GAllocator *last;
666     GMemChunk  *mem_chunk;
667     gpointer    free_list;
668   } dummy = {
669     "GAllocator is deprecated", 1, TRUE, 0, NULL, NULL, NULL,
670   };
671   /* some (broken) GAllocator uses depend on non-NULL allocators */
672   return (void*) &dummy;
673 }
674
675 void
676 g_allocator_free (GAllocator *allocator)
677 {
678 }
679
680 #ifdef ENABLE_GC_FRIENDLY_DEFAULT
681 gboolean g_mem_gc_friendly = TRUE;
682 #else
683 gboolean g_mem_gc_friendly = FALSE;
684 #endif
685
686 static void
687 g_mem_init_nomessage (void)
688 {
689   gchar buffer[1024];
690   const gchar *val;
691   static const GDebugKey keys[] = {
692     { "gc-friendly", 1 },
693   };
694   gint flags;
695   if (g_mem_initialized)
696     return;
697   /* don't use g_malloc/g_message here */
698   val = _g_getenv_nomalloc ("G_DEBUG", buffer);
699   flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
700   if (flags & 1)        /* gc-friendly */
701     {
702       g_mem_gc_friendly = TRUE;
703     }
704   g_mem_initialized = TRUE;
705 }
706
707 void
708 _g_mem_thread_init_noprivate_nomessage (void)
709 {
710   /* we may only create mutexes here, locking/
711    * unlocking a mutex does not yet work.
712    */
713   g_mem_init_nomessage();
714 #ifndef G_DISABLE_CHECKS
715   gmem_profile_mutex = g_mutex_new ();
716 #endif
717 }
718
719 #define __G_MEM_C__
720 #include "galiasdef.c"