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