1e92ffd19f10c6905afa68dcb9f7180d40565393
[platform/upstream/glib.git] / glib / gmem.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe
29  */
30
31 #include "config.h"
32
33 #include "gmem.h"
34
35 #include <stdlib.h>
36 #include <string.h>
37 #include <signal.h>
38
39 #include "gbacktrace.h"
40 #include "gtestutils.h"
41 #include "gthread.h"
42 #include "glib_trace.h"
43
44
45 #define MEM_PROFILE_TABLE_SIZE 4096
46
47
48 /* notes on macros:
49  * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
50  * g_mem_profile().
51  * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
52  * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
53  * match the corresponding GLib prototypes, keep configure.ac and gmem.h in sync here.
54  * g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
55  */
56
57 /* --- prototypes --- */
58 static gboolean g_mem_initialized = FALSE;
59 static void     g_mem_init_nomessage (void);
60
61
62 /* --- malloc wrappers --- */
63 #ifndef REALLOC_0_WORKS
64 static gpointer
65 standard_realloc (gpointer mem,
66                   gsize    n_bytes)
67 {
68   if (!mem)
69     return malloc (n_bytes);
70   else
71     return realloc (mem, n_bytes);
72 }
73 #endif  /* !REALLOC_0_WORKS */
74
75 #ifdef SANE_MALLOC_PROTOS
76 #  define standard_malloc       malloc
77 #  ifdef REALLOC_0_WORKS
78 #    define standard_realloc    realloc
79 #  endif /* REALLOC_0_WORKS */
80 #  define standard_free         free
81 #  define standard_calloc       calloc
82 #  define standard_try_malloc   malloc
83 #  define standard_try_realloc  realloc
84 #else   /* !SANE_MALLOC_PROTOS */
85 static gpointer
86 standard_malloc (gsize n_bytes)
87 {
88   return malloc (n_bytes);
89 }
90 #  ifdef REALLOC_0_WORKS
91 static gpointer
92 standard_realloc (gpointer mem,
93                   gsize    n_bytes)
94 {
95   return realloc (mem, n_bytes);
96 }
97 #  endif /* REALLOC_0_WORKS */
98 static void
99 standard_free (gpointer mem)
100 {
101   free (mem);
102 }
103 static gpointer
104 standard_calloc (gsize n_blocks,
105                  gsize n_bytes)
106 {
107   return calloc (n_blocks, n_bytes);
108 }
109 #define standard_try_malloc     standard_malloc
110 #define standard_try_realloc    standard_realloc
111 #endif  /* !SANE_MALLOC_PROTOS */
112
113
114 /* --- variables --- */
115 static GMemVTable glib_mem_vtable = {
116   standard_malloc,
117   standard_realloc,
118   standard_free,
119   standard_calloc,
120   standard_try_malloc,
121   standard_try_realloc,
122 };
123
124 /* --- functions --- */
125 gpointer
126 g_malloc (gsize n_bytes)
127 {
128   if (G_UNLIKELY (!g_mem_initialized))
129     g_mem_init_nomessage();
130   if (G_LIKELY (n_bytes))
131     {
132       gpointer mem;
133
134       mem = glib_mem_vtable.malloc (n_bytes);
135       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
136       if (mem)
137         return mem;
138
139       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
140                G_STRLOC, n_bytes);
141     }
142
143   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
144
145   return NULL;
146 }
147
148 gpointer
149 g_malloc0 (gsize n_bytes)
150 {
151   if (G_UNLIKELY (!g_mem_initialized))
152     g_mem_init_nomessage();
153   if (G_LIKELY (n_bytes))
154     {
155       gpointer mem;
156
157       mem = glib_mem_vtable.calloc (1, n_bytes);
158       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
159       if (mem)
160         return mem;
161
162       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
163                G_STRLOC, n_bytes);
164     }
165
166   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
167
168   return NULL;
169 }
170
171 gpointer
172 g_realloc (gpointer mem,
173            gsize    n_bytes)
174 {
175   gpointer newmem;
176
177   if (G_UNLIKELY (!g_mem_initialized))
178     g_mem_init_nomessage();
179   if (G_LIKELY (n_bytes))
180     {
181       newmem = glib_mem_vtable.realloc (mem, n_bytes);
182       TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
183       if (newmem)
184         return newmem;
185
186       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
187                G_STRLOC, n_bytes);
188     }
189
190   if (mem)
191     glib_mem_vtable.free (mem);
192
193   TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
194
195   return NULL;
196 }
197
198 void
199 g_free (gpointer mem)
200 {
201   if (G_UNLIKELY (!g_mem_initialized))
202     g_mem_init_nomessage();
203   if (G_LIKELY (mem))
204     glib_mem_vtable.free (mem);
205   TRACE(GLIB_MEM_FREE((void*) mem));
206 }
207
208 gpointer
209 g_try_malloc (gsize n_bytes)
210 {
211   gpointer mem;
212
213   if (G_UNLIKELY (!g_mem_initialized))
214     g_mem_init_nomessage();
215   if (G_LIKELY (n_bytes))
216     mem = glib_mem_vtable.try_malloc (n_bytes);
217   else
218     mem = NULL;
219
220   TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
221
222   return mem;
223 }
224
225 gpointer
226 g_try_malloc0 (gsize n_bytes)
227 {
228   gpointer mem;
229
230   if (G_UNLIKELY (!g_mem_initialized))
231     g_mem_init_nomessage();
232   if (G_LIKELY (n_bytes))
233     mem = glib_mem_vtable.try_malloc (n_bytes);
234   else
235     mem = NULL;
236
237   if (mem)
238     memset (mem, 0, n_bytes);
239
240   return mem;
241 }
242
243 gpointer
244 g_try_realloc (gpointer mem,
245                gsize    n_bytes)
246 {
247   gpointer newmem;
248
249   if (G_UNLIKELY (!g_mem_initialized))
250     g_mem_init_nomessage();
251   if (G_LIKELY (n_bytes))
252     newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
253   else
254     {
255       newmem = NULL;
256       if (mem)
257         glib_mem_vtable.free (mem);
258     }
259
260   TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
261
262   return newmem;
263 }
264
265
266 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((a) > G_MAXSIZE / (b)))
267
268 gpointer
269 g_malloc_n (gsize n_blocks,
270             gsize n_block_bytes)
271 {
272   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
273     {
274       if (G_UNLIKELY (!g_mem_initialized))
275         g_mem_init_nomessage();
276
277       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
278                G_STRLOC, n_blocks, n_block_bytes);
279     }
280
281   return g_malloc (n_blocks * n_block_bytes);
282 }
283
284 gpointer
285 g_malloc0_n (gsize n_blocks,
286              gsize n_block_bytes)
287 {
288   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
289     {
290       if (G_UNLIKELY (!g_mem_initialized))
291         g_mem_init_nomessage();
292
293       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
294                G_STRLOC, n_blocks, n_block_bytes);
295     }
296
297   return g_malloc0 (n_blocks * n_block_bytes);
298 }
299
300 gpointer
301 g_realloc_n (gpointer mem,
302              gsize    n_blocks,
303              gsize    n_block_bytes)
304 {
305   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
306     {
307       if (G_UNLIKELY (!g_mem_initialized))
308         g_mem_init_nomessage();
309
310       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
311                G_STRLOC, n_blocks, n_block_bytes);
312     }
313
314   return g_realloc (mem, n_blocks * n_block_bytes);
315 }
316
317 gpointer
318 g_try_malloc_n (gsize n_blocks,
319                 gsize n_block_bytes)
320 {
321   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
322     return NULL;
323
324   return g_try_malloc (n_blocks * n_block_bytes);
325 }
326
327 gpointer
328 g_try_malloc0_n (gsize n_blocks,
329                  gsize n_block_bytes)
330 {
331   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
332     return NULL;
333
334   return g_try_malloc0 (n_blocks * n_block_bytes);
335 }
336
337 gpointer
338 g_try_realloc_n (gpointer mem,
339                  gsize    n_blocks,
340                  gsize    n_block_bytes)
341 {
342   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
343     return NULL;
344
345   return g_try_realloc (mem, n_blocks * n_block_bytes);
346 }
347
348
349
350 static gpointer
351 fallback_calloc (gsize n_blocks,
352                  gsize n_block_bytes)
353 {
354   gsize l = n_blocks * n_block_bytes;
355   gpointer mem = glib_mem_vtable.malloc (l);
356
357   if (mem)
358     memset (mem, 0, l);
359
360   return mem;
361 }
362
363 static gboolean vtable_set = FALSE;
364
365 /**
366  * g_mem_is_system_malloc
367  * 
368  * Checks whether the allocator used by g_malloc() is the system's
369  * malloc implementation. If it returns %TRUE memory allocated with
370  * malloc() can be used interchangeable with memory allocated using g_malloc(). 
371  * This function is useful for avoiding an extra copy of allocated memory returned
372  * by a non-GLib-based API.
373  *
374  * A different allocator can be set using g_mem_set_vtable().
375  *
376  * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
377  **/
378 gboolean
379 g_mem_is_system_malloc (void)
380 {
381   return !vtable_set;
382 }
383
384 void
385 g_mem_set_vtable (GMemVTable *vtable)
386 {
387   if (!vtable_set)
388     {
389       if (vtable->malloc && vtable->realloc && vtable->free)
390         {
391           glib_mem_vtable.malloc = vtable->malloc;
392           glib_mem_vtable.realloc = vtable->realloc;
393           glib_mem_vtable.free = vtable->free;
394           glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
395           glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
396           glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
397           vtable_set = TRUE;
398         }
399       else
400         g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
401     }
402   else
403     g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
404 }
405
406
407 /* --- memory profiling and checking --- */
408 #ifdef  G_DISABLE_CHECKS
409 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
410 void
411 g_mem_profile (void)
412 {
413 }
414 #else   /* !G_DISABLE_CHECKS */
415 typedef enum {
416   PROFILER_FREE         = 0,
417   PROFILER_ALLOC        = 1,
418   PROFILER_RELOC        = 2,
419   PROFILER_ZINIT        = 4
420 } ProfilerJob;
421 static guint *profile_data = NULL;
422 static gsize profile_allocs = 0;
423 static gsize profile_zinit = 0;
424 static gsize profile_frees = 0;
425 static GMutex *gmem_profile_mutex = NULL;
426 #ifdef  G_ENABLE_DEBUG
427 static volatile gsize g_trap_free_size = 0;
428 static volatile gsize g_trap_realloc_size = 0;
429 static volatile gsize g_trap_malloc_size = 0;
430 #endif  /* G_ENABLE_DEBUG */
431
432 #define PROFILE_TABLE(f1,f2,f3)   ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
433
434 static void
435 profiler_log (ProfilerJob job,
436               gsize       n_bytes,
437               gboolean    success)
438 {
439   g_mutex_lock (gmem_profile_mutex);
440   if (!profile_data)
441     {
442       profile_data = standard_calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8, 
443                                       sizeof (profile_data[0]));
444       if (!profile_data)        /* memory system kiddin' me, eh? */
445         {
446           g_mutex_unlock (gmem_profile_mutex);
447           return;
448         }
449     }
450
451   if (n_bytes < MEM_PROFILE_TABLE_SIZE)
452     profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
453                                           (job & PROFILER_RELOC) != 0,
454                                           success != 0)] += 1;
455   else
456     profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
457                                                          (job & PROFILER_RELOC) != 0,
458                                                          success != 0)] += 1;
459   if (success)
460     {
461       if (job & PROFILER_ALLOC)
462         {
463           profile_allocs += n_bytes;
464           if (job & PROFILER_ZINIT)
465             profile_zinit += n_bytes;
466         }
467       else
468         profile_frees += n_bytes;
469     }
470   g_mutex_unlock (gmem_profile_mutex);
471 }
472
473 static void
474 profile_print_locked (guint   *local_data,
475                       gboolean success)
476 {
477   gboolean need_header = TRUE;
478   guint i;
479
480   for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
481     {
482       glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
483       glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
484       glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
485       glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
486       
487       if (!t_malloc && !t_realloc && !t_free && !t_refree)
488         continue;
489       else if (need_header)
490         {
491           need_header = FALSE;
492           g_print (" blocks of | allocated  | freed      | allocated  | freed      | n_bytes   \n");
493           g_print ("  n_bytes  | n_times by | n_times by | n_times by | n_times by | remaining \n");
494           g_print ("           | malloc()   | free()     | realloc()  | realloc()  |           \n");
495           g_print ("===========|============|============|============|============|===========\n");
496         }
497       if (i < MEM_PROFILE_TABLE_SIZE)
498         g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
499                  i, t_malloc, t_free, t_realloc, t_refree,
500                  (t_malloc - t_free + t_realloc - t_refree) * i);
501       else if (i >= MEM_PROFILE_TABLE_SIZE)
502         g_print ("   >%6u | %10ld | %10ld | %10ld | %10ld |        ***\n",
503                  i, t_malloc, t_free, t_realloc, t_refree);
504     }
505   if (need_header)
506     g_print (" --- none ---\n");
507 }
508
509 void
510 g_mem_profile (void)
511 {
512   guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
513   gsize local_allocs;
514   gsize local_zinit;
515   gsize local_frees;
516
517   if (G_UNLIKELY (!g_mem_initialized))
518     g_mem_init_nomessage();
519
520   g_mutex_lock (gmem_profile_mutex);
521
522   local_allocs = profile_allocs;
523   local_zinit = profile_zinit;
524   local_frees = profile_frees;
525
526   if (!profile_data)
527     {
528       g_mutex_unlock (gmem_profile_mutex);
529       return;
530     }
531
532   memcpy (local_data, profile_data, 
533           (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
534   
535   g_mutex_unlock (gmem_profile_mutex);
536
537   g_print ("GLib Memory statistics (successful operations):\n");
538   profile_print_locked (local_data, TRUE);
539   g_print ("GLib Memory statistics (failing operations):\n");
540   profile_print_locked (local_data, FALSE);
541   g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
542            "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
543            "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
544            "remaining=%"G_GSIZE_FORMAT"\n",
545            local_allocs,
546            local_zinit,
547            ((gdouble) local_zinit) / local_allocs * 100.0,
548            local_frees,
549            ((gdouble) local_frees) / local_allocs * 100.0,
550            local_allocs - local_frees);
551 }
552
553 static gpointer
554 profiler_try_malloc (gsize n_bytes)
555 {
556   gsize *p;
557
558 #ifdef  G_ENABLE_DEBUG
559   if (g_trap_malloc_size == n_bytes)
560     G_BREAKPOINT ();
561 #endif  /* G_ENABLE_DEBUG */
562
563   p = standard_malloc (sizeof (gsize) * 2 + n_bytes);
564
565   if (p)
566     {
567       p[0] = 0;         /* free count */
568       p[1] = n_bytes;   /* length */
569       profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
570       p += 2;
571     }
572   else
573     profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
574   
575   return p;
576 }
577
578 static gpointer
579 profiler_malloc (gsize n_bytes)
580 {
581   gpointer mem = profiler_try_malloc (n_bytes);
582
583   if (!mem)
584     g_mem_profile ();
585
586   return mem;
587 }
588
589 static gpointer
590 profiler_calloc (gsize n_blocks,
591                  gsize n_block_bytes)
592 {
593   gsize l = n_blocks * n_block_bytes;
594   gsize *p;
595
596 #ifdef  G_ENABLE_DEBUG
597   if (g_trap_malloc_size == l)
598     G_BREAKPOINT ();
599 #endif  /* G_ENABLE_DEBUG */
600   
601   p = standard_calloc (1, sizeof (gsize) * 2 + l);
602
603   if (p)
604     {
605       p[0] = 0;         /* free count */
606       p[1] = l;         /* length */
607       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
608       p += 2;
609     }
610   else
611     {
612       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
613       g_mem_profile ();
614     }
615
616   return p;
617 }
618
619 static void
620 profiler_free (gpointer mem)
621 {
622   gsize *p = mem;
623
624   p -= 2;
625   if (p[0])     /* free count */
626     {
627       g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
628                  p + 2, p[0]);
629       profiler_log (PROFILER_FREE,
630                     p[1],       /* length */
631                     FALSE);
632     }
633   else
634     {
635 #ifdef  G_ENABLE_DEBUG
636       if (g_trap_free_size == p[1])
637         G_BREAKPOINT ();
638 #endif  /* G_ENABLE_DEBUG */
639
640       profiler_log (PROFILER_FREE,
641                     p[1],       /* length */
642                     TRUE);
643       memset (p + 2, 0xaa, p[1]);
644
645       /* for all those that miss standard_free (p); in this place, yes,
646        * we do leak all memory when profiling, and that is intentional
647        * to catch double frees. patch submissions are futile.
648        */
649     }
650   p[0] += 1;
651 }
652
653 static gpointer
654 profiler_try_realloc (gpointer mem,
655                       gsize    n_bytes)
656 {
657   gsize *p = mem;
658
659   p -= 2;
660
661 #ifdef  G_ENABLE_DEBUG
662   if (g_trap_realloc_size == n_bytes)
663     G_BREAKPOINT ();
664 #endif  /* G_ENABLE_DEBUG */
665   
666   if (mem && p[0])      /* free count */
667     {
668       g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
669                  "memory has been freed %"G_GSIZE_FORMAT" times already",
670                  p + 2, (gsize) n_bytes, p[0]);
671       profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
672
673       return NULL;
674     }
675   else
676     {
677       p = standard_realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
678
679       if (p)
680         {
681           if (mem)
682             profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
683           p[0] = 0;
684           p[1] = n_bytes;
685           profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
686           p += 2;
687         }
688       else
689         profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
690
691       return p;
692     }
693 }
694
695 static gpointer
696 profiler_realloc (gpointer mem,
697                   gsize    n_bytes)
698 {
699   mem = profiler_try_realloc (mem, n_bytes);
700
701   if (!mem)
702     g_mem_profile ();
703
704   return mem;
705 }
706
707 static GMemVTable profiler_table = {
708   profiler_malloc,
709   profiler_realloc,
710   profiler_free,
711   profiler_calloc,
712   profiler_try_malloc,
713   profiler_try_realloc,
714 };
715 GMemVTable *glib_mem_profiler_table = &profiler_table;
716
717 #endif  /* !G_DISABLE_CHECKS */
718
719 /* --- MemChunks --- */
720 /**
721  * SECTION: allocators
722  * @title: Memory Allocators
723  * @short_description: deprecated way to allocate chunks of memory for
724  *                     GList, GSList and GNode
725  *
726  * Prior to 2.10, #GAllocator was used as an efficient way to allocate
727  * small pieces of memory for use with the #GList, #GSList and #GNode
728  * data structures. Since 2.10, it has been completely replaced by the
729  * <link linkend="glib-Memory-Slices">slice allocator</link> and
730  * deprecated.
731  **/
732
733 /**
734  * SECTION: memory_chunks
735  * @title: Memory Chunks
736  * @short_description: deprecated way to allocate groups of equal-sized
737  *                     chunks of memory
738  *
739  * Memory chunks provide an space-efficient way to allocate equal-sized
740  * pieces of memory, called atoms. However, due to the administrative
741  * overhead (in particular for #G_ALLOC_AND_FREE, and when used from
742  * multiple threads), they are in practise often slower than direct use
743  * of g_malloc(). Therefore, memory chunks have been deprecated in
744  * favor of the <link linkend="glib-Memory-Slices">slice
745  * allocator</link>, which has been added in 2.10. All internal uses of
746  * memory chunks in GLib have been converted to the
747  * <literal>g_slice</literal> API.
748  *
749  * There are two types of memory chunks, #G_ALLOC_ONLY, and
750  * #G_ALLOC_AND_FREE. <itemizedlist> <listitem><para> #G_ALLOC_ONLY
751  * chunks only allow allocation of atoms. The atoms can never be freed
752  * individually. The memory chunk can only be free in its entirety.
753  * </para></listitem> <listitem><para> #G_ALLOC_AND_FREE chunks do
754  * allow atoms to be freed individually. The disadvantage of this is
755  * that the memory chunk has to keep track of which atoms have been
756  * freed. This results in more memory being used and a slight
757  * degradation in performance. </para></listitem> </itemizedlist>
758  *
759  * To create a memory chunk use g_mem_chunk_new() or the convenience
760  * macro g_mem_chunk_create().
761  *
762  * To allocate a new atom use g_mem_chunk_alloc(),
763  * g_mem_chunk_alloc0(), or the convenience macros g_chunk_new() or
764  * g_chunk_new0().
765  *
766  * To free an atom use g_mem_chunk_free(), or the convenience macro
767  * g_chunk_free(). (Atoms can only be freed if the memory chunk is
768  * created with the type set to #G_ALLOC_AND_FREE.)
769  *
770  * To free any blocks of memory which are no longer being used, use
771  * g_mem_chunk_clean(). To clean all memory chunks, use g_blow_chunks().
772  *
773  * To reset the memory chunk, freeing all of the atoms, use
774  * g_mem_chunk_reset().
775  *
776  * To destroy a memory chunk, use g_mem_chunk_destroy().
777  *
778  * To help debug memory chunks, use g_mem_chunk_info() and
779  * g_mem_chunk_print().
780  *
781  * <example>
782  *  <title>Using a #GMemChunk</title>
783  *  <programlisting>
784  *   GMemChunk *mem_chunk;
785  *   gchar *mem[10000];
786  *   gint i;
787  *
788  *   /<!-- -->* Create a GMemChunk with atoms 50 bytes long, and memory
789  *      blocks holding 100 bytes. Note that this means that only 2 atoms
790  *      fit into each memory block and so isn't very efficient. *<!-- -->/
791  *   mem_chunk = g_mem_chunk_new ("test mem chunk", 50, 100, G_ALLOC_AND_FREE);
792  *   /<!-- -->* Now allocate 10000 atoms. *<!-- -->/
793  *   for (i = 0; i &lt; 10000; i++)
794  *     {
795  *       mem[i] = g_chunk_new (gchar, mem_chunk);
796  *       /<!-- -->* Fill in the atom memory with some junk. *<!-- -->/
797  *       for (j = 0; j &lt; 50; j++)
798  *         mem[i][j] = i * j;
799  *     }
800  *   /<!-- -->* Now free all of the atoms. Note that since we are going to
801  *      destroy the GMemChunk, this wouldn't normally be used. *<!-- -->/
802  *   for (i = 0; i &lt; 10000; i++)
803  *     {
804  *       g_mem_chunk_free (mem_chunk, mem[i]);
805  *     }
806  *   /<!-- -->* We are finished with the GMemChunk, so we destroy it. *<!-- -->/
807  *   g_mem_chunk_destroy (mem_chunk);
808  *  </programlisting>
809  * </example>
810  *
811  * <example>
812  *  <title>Using a #GMemChunk with data structures</title>
813  *  <programlisting>
814  *    GMemChunk *array_mem_chunk;
815  *    GRealArray *array;
816  *    /<!-- -->* Create a GMemChunk to hold GRealArray structures, using
817  *       the g_mem_chunk_create(<!-- -->) convenience macro. We want 1024 atoms in each
818  *       memory block, and we want to be able to free individual atoms. *<!-- -->/
819  *    array_mem_chunk = g_mem_chunk_create (GRealArray, 1024, G_ALLOC_AND_FREE);
820  *    /<!-- -->* Allocate one atom, using the g_chunk_new(<!-- -->) convenience macro. *<!-- -->/
821  *    array = g_chunk_new (GRealArray, array_mem_chunk);
822  *    /<!-- -->* We can now use array just like a normal pointer to a structure. *<!-- -->/
823  *    array->data            = NULL;
824  *    array->len             = 0;
825  *    array->alloc           = 0;
826  *    array->zero_terminated = (zero_terminated ? 1 : 0);
827  *    array->clear           = (clear ? 1 : 0);
828  *    array->elt_size        = elt_size;
829  *    /<!-- -->* We can free the element, so it can be reused. *<!-- -->/
830  *    g_chunk_free (array, array_mem_chunk);
831  *    /<!-- -->* We destroy the GMemChunk when we are finished with it. *<!-- -->/
832  *    g_mem_chunk_destroy (array_mem_chunk);
833  *  </programlisting>
834  * </example>
835  **/
836
837 #ifndef G_ALLOC_AND_FREE
838
839 /**
840  * GAllocator:
841  *
842  * The #GAllocator struct contains private data. and should only be
843  * accessed using the following functions.
844  **/
845 typedef struct _GAllocator GAllocator;
846
847 /**
848  * GMemChunk:
849  *
850  * The #GMemChunk struct is an opaque data structure representing a
851  * memory chunk. It should be accessed only through the use of the
852  * following functions.
853  **/
854 typedef struct _GMemChunk  GMemChunk;
855
856 /**
857  * G_ALLOC_ONLY:
858  *
859  * Specifies the type of a #GMemChunk. Used in g_mem_chunk_new() and
860  * g_mem_chunk_create() to specify that atoms will never be freed
861  * individually.
862  **/
863 #define G_ALLOC_ONLY      1
864
865 /**
866  * G_ALLOC_AND_FREE:
867  *
868  * Specifies the type of a #GMemChunk. Used in g_mem_chunk_new() and
869  * g_mem_chunk_create() to specify that atoms will be freed
870  * individually.
871  **/
872 #define G_ALLOC_AND_FREE  2
873 #endif
874
875 struct _GMemChunk {
876   guint alloc_size;           /* the size of an atom */
877 };
878
879 /**
880  * g_mem_chunk_new:
881  * @name: a string to identify the #GMemChunk. It is not copied so it
882  *        should be valid for the lifetime of the #GMemChunk. It is
883  *        only used in g_mem_chunk_print(), which is used for debugging.
884  * @atom_size: the size, in bytes, of each element in the #GMemChunk.
885  * @area_size: the size, in bytes, of each block of memory allocated to
886  *             contain the atoms.
887  * @type: the type of the #GMemChunk.  #G_ALLOC_AND_FREE is used if the
888  *        atoms will be freed individually.  #G_ALLOC_ONLY should be
889  *        used if atoms will never be freed individually.
890  *        #G_ALLOC_ONLY is quicker, since it does not need to track
891  *        free atoms, but it obviously wastes memory if you no longer
892  *        need many of the atoms.
893  * @Returns: the new #GMemChunk.
894  *
895  * Creates a new #GMemChunk.
896  *
897  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
898  *                  allocator</link> instead
899  **/
900 GMemChunk*
901 g_mem_chunk_new (const gchar  *name,
902                  gint          atom_size,
903                  gsize         area_size,
904                  gint          type)
905 {
906   GMemChunk *mem_chunk;
907   g_return_val_if_fail (atom_size > 0, NULL);
908
909   mem_chunk = g_slice_new (GMemChunk);
910   mem_chunk->alloc_size = atom_size;
911   return mem_chunk;
912 }
913
914 /**
915  * g_mem_chunk_destroy:
916  * @mem_chunk: a #GMemChunk.
917  *
918  * Frees all of the memory allocated for a #GMemChunk.
919  *
920  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
921  *                  allocator</link> instead
922  **/
923 void
924 g_mem_chunk_destroy (GMemChunk *mem_chunk)
925 {
926   g_return_if_fail (mem_chunk != NULL);
927   
928   g_slice_free (GMemChunk, mem_chunk);
929 }
930
931 /**
932  * g_mem_chunk_alloc:
933  * @mem_chunk: a #GMemChunk.
934  * @Returns: a pointer to the allocated atom.
935  *
936  * Allocates an atom of memory from a #GMemChunk.
937  *
938  * Deprecated:2.10: Use g_slice_alloc() instead
939  **/
940 gpointer
941 g_mem_chunk_alloc (GMemChunk *mem_chunk)
942 {
943   g_return_val_if_fail (mem_chunk != NULL, NULL);
944   
945   return g_slice_alloc (mem_chunk->alloc_size);
946 }
947
948 /**
949  * g_mem_chunk_alloc0:
950  * @mem_chunk: a #GMemChunk.
951  * @Returns: a pointer to the allocated atom.
952  *
953  * Allocates an atom of memory from a #GMemChunk, setting the memory to
954  * 0.
955  *
956  * Deprecated:2.10: Use g_slice_alloc0() instead
957  **/
958 gpointer
959 g_mem_chunk_alloc0 (GMemChunk *mem_chunk)
960 {
961   g_return_val_if_fail (mem_chunk != NULL, NULL);
962   
963   return g_slice_alloc0 (mem_chunk->alloc_size);
964 }
965
966 /**
967  * g_mem_chunk_free:
968  * @mem_chunk: a #GMemChunk.
969  * @mem: a pointer to the atom to free.
970  *
971  * Frees an atom in a #GMemChunk. This should only be called if the
972  * #GMemChunk was created with #G_ALLOC_AND_FREE. Otherwise it will
973  * simply return.
974  *
975  * Deprecated:2.10: Use g_slice_free1() instead
976  **/
977 void
978 g_mem_chunk_free (GMemChunk *mem_chunk,
979                   gpointer   mem)
980 {
981   g_return_if_fail (mem_chunk != NULL);
982   
983   g_slice_free1 (mem_chunk->alloc_size, mem);
984 }
985
986 /**
987  * g_mem_chunk_clean:
988  * @mem_chunk: a #GMemChunk.
989  *
990  * Frees any blocks in a #GMemChunk which are no longer being used.
991  *
992  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
993  *                  allocator</link> instead
994  **/
995 void    g_mem_chunk_clean       (GMemChunk *mem_chunk)  {}
996
997 /**
998  * g_mem_chunk_reset:
999  * @mem_chunk: a #GMemChunk.
1000  *
1001  * Resets a GMemChunk to its initial state. It frees all of the
1002  * currently allocated blocks of memory.
1003  *
1004  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1005  *                  allocator</link> instead
1006  **/
1007 void    g_mem_chunk_reset       (GMemChunk *mem_chunk)  {}
1008
1009
1010 /**
1011  * g_mem_chunk_print:
1012  * @mem_chunk: a #GMemChunk.
1013  *
1014  * Outputs debugging information for a #GMemChunk. It outputs the name
1015  * of the #GMemChunk (set with g_mem_chunk_new()), the number of bytes
1016  * used, and the number of blocks of memory allocated.
1017  *
1018  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1019  *                  allocator</link> instead
1020  **/
1021 void    g_mem_chunk_print       (GMemChunk *mem_chunk)  {}
1022
1023
1024 /**
1025  * g_mem_chunk_info:
1026  *
1027  * Outputs debugging information for all #GMemChunk objects currently
1028  * in use. It outputs the number of #GMemChunk objects currently
1029  * allocated, and calls g_mem_chunk_print() to output information on
1030  * each one.
1031  *
1032  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1033  *                  allocator</link> instead
1034  **/
1035 void    g_mem_chunk_info        (void)                  {}
1036
1037 /**
1038  * g_blow_chunks:
1039  *
1040  * Calls g_mem_chunk_clean() on all #GMemChunk objects.
1041  *
1042  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1043  *                  allocator</link> instead
1044  **/
1045 void    g_blow_chunks           (void)                  {}
1046
1047 /**
1048  * g_chunk_new0:
1049  * @type: the type of the #GMemChunk atoms, typically a structure name.
1050  * @chunk: a #GMemChunk.
1051  * @Returns: a pointer to the allocated atom, cast to a pointer to
1052  *           @type.
1053  *
1054  * A convenience macro to allocate an atom of memory from a #GMemChunk.
1055  * It calls g_mem_chunk_alloc0() and casts the returned atom to a
1056  * pointer to the given type, avoiding a type cast in the source code.
1057  *
1058  * Deprecated:2.10: Use g_slice_new0() instead
1059  **/
1060
1061 /**
1062  * g_chunk_free:
1063  * @mem: a pointer to the atom to be freed.
1064  * @mem_chunk: a #GMemChunk.
1065  *
1066  * A convenience macro to free an atom of memory from a #GMemChunk. It
1067  * simply switches the arguments and calls g_mem_chunk_free() It is
1068  * included simply to complement the other convenience macros,
1069  * g_chunk_new() and g_chunk_new0().
1070  *
1071  * Deprecated:2.10: Use g_slice_free() instead
1072  **/
1073
1074 /**
1075  * g_chunk_new:
1076  * @type: the type of the #GMemChunk atoms, typically a structure name.
1077  * @chunk: a #GMemChunk.
1078  * @Returns: a pointer to the allocated atom, cast to a pointer to
1079  *           @type.
1080  *
1081  * A convenience macro to allocate an atom of memory from a #GMemChunk.
1082  * It calls g_mem_chunk_alloc() and casts the returned atom to a
1083  * pointer to the given type, avoiding a type cast in the source code.
1084  *
1085  * Deprecated:2.10: Use g_slice_new() instead
1086  **/
1087
1088 /**
1089  * g_mem_chunk_create:
1090  * @type: the type of the atoms, typically a structure name.
1091  * @pre_alloc: the number of atoms to store in each block of memory.
1092  * @alloc_type: the type of the #GMemChunk.  #G_ALLOC_AND_FREE is used
1093  *              if the atoms will be freed individually.  #G_ALLOC_ONLY
1094  *              should be used if atoms will never be freed
1095  *              individually.  #G_ALLOC_ONLY is quicker, since it does
1096  *              not need to track free atoms, but it obviously wastes
1097  *              memory if you no longer need many of the atoms.
1098  * @Returns: the new #GMemChunk.
1099  *
1100  * A convenience macro for creating a new #GMemChunk. It calls
1101  * g_mem_chunk_new(), using the given type to create the #GMemChunk
1102  * name. The atom size is determined using
1103  * <function>sizeof()</function>, and the area size is calculated by
1104  * multiplying the @pre_alloc parameter with the atom size.
1105  *
1106  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1107  *                  allocator</link> instead
1108  **/
1109
1110
1111 /**
1112  * g_allocator_new:
1113  * @name: the name of the #GAllocator. This name is used to set the
1114  *        name of the #GMemChunk used by the #GAllocator, and is only
1115  *        used for debugging.
1116  * @n_preallocs: the number of elements in each block of memory
1117  *               allocated.  Larger blocks mean less calls to
1118  *               g_malloc(), but some memory may be wasted.  (GLib uses
1119  *               128 elements per block by default.) The value must be
1120  *               between 1 and 65535.
1121  * @Returns: a new #GAllocator.
1122  *
1123  * Creates a new #GAllocator.
1124  *
1125  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1126  *                  allocator</link> instead
1127  **/
1128 GAllocator*
1129 g_allocator_new (const gchar *name,
1130                  guint        n_preallocs)
1131 {
1132   static struct _GAllocator {
1133     gchar      *name;
1134     guint16     n_preallocs;
1135     guint       is_unused : 1;
1136     guint       type : 4;
1137     GAllocator *last;
1138     GMemChunk  *mem_chunk;
1139     gpointer    free_list;
1140   } dummy = {
1141     "GAllocator is deprecated", 1, TRUE, 0, NULL, NULL, NULL,
1142   };
1143   /* some (broken) GAllocator uses depend on non-NULL allocators */
1144   return (void*) &dummy;
1145 }
1146
1147 /**
1148  * g_allocator_free:
1149  * @allocator: a #GAllocator.
1150  *
1151  * Frees all of the memory allocated by the #GAllocator.
1152  *
1153  * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1154  *                  allocator</link> instead
1155  **/
1156 void
1157 g_allocator_free (GAllocator *allocator)
1158 {
1159 }
1160
1161 #ifdef ENABLE_GC_FRIENDLY_DEFAULT
1162 gboolean g_mem_gc_friendly = TRUE;
1163 #else
1164 gboolean g_mem_gc_friendly = FALSE;
1165 #endif
1166
1167 static void
1168 g_mem_init_nomessage (void)
1169 {
1170   gchar buffer[1024];
1171   const gchar *val;
1172   const GDebugKey keys[] = {
1173     { "gc-friendly", 1 },
1174   };
1175   gint flags;
1176   if (g_mem_initialized)
1177     return;
1178   /* don't use g_malloc/g_message here */
1179   val = _g_getenv_nomalloc ("G_DEBUG", buffer);
1180   flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1181   if (flags & 1)        /* gc-friendly */
1182     {
1183       g_mem_gc_friendly = TRUE;
1184     }
1185   g_mem_initialized = TRUE;
1186 }
1187
1188 void
1189 _g_mem_thread_init_noprivate_nomessage (void)
1190 {
1191   /* we may only create mutexes here, locking/
1192    * unlocking a mutex does not yet work.
1193    */
1194   g_mem_init_nomessage();
1195 #ifndef G_DISABLE_CHECKS
1196   gmem_profile_mutex = g_mutex_new ();
1197 #endif
1198 }