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