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