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