Add g_try_new, g_try_new0, g_try_renew and g_try_malloc0. (#169611, Stefan
[platform/upstream/glib.git] / glib / gmem.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe
29  */
30
31 #include "config.h"
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <signal.h>
36
37 #include "glib.h"
38 #include "gthreadinit.h"
39 #include "galias.h"
40
41 /* notes on macros:
42  * having DISABLE_MEM_POOLS defined, disables mem_chunks alltogether, their
43  * allocations are performed through ordinary g_malloc/g_free.
44  * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
45  * g_mem_profile().
46  * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
47  * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
48  * match the corresponding GLib prototypes, keep configure.in and gmem.h in sync here.
49  * if ENABLE_GC_FRIENDLY is defined, freed memory should be 0-wiped.
50  */
51
52 #define MEM_PROFILE_TABLE_SIZE 4096
53
54 #define MEM_AREA_SIZE 4L
55
56 #ifdef  G_DISABLE_CHECKS
57 #  define ENTER_MEM_CHUNK_ROUTINE()
58 #  define LEAVE_MEM_CHUNK_ROUTINE()
59 #  define IN_MEM_CHUNK_ROUTINE()        FALSE
60 #else   /* !G_DISABLE_CHECKS */
61 static GPrivate* mem_chunk_recursion = NULL;
62 #  define MEM_CHUNK_ROUTINE_COUNT()     GPOINTER_TO_UINT (g_private_get (mem_chunk_recursion))
63 #  define ENTER_MEM_CHUNK_ROUTINE()     g_private_set (mem_chunk_recursion, GUINT_TO_POINTER (MEM_CHUNK_ROUTINE_COUNT () + 1))
64 #  define LEAVE_MEM_CHUNK_ROUTINE()     g_private_set (mem_chunk_recursion, GUINT_TO_POINTER (MEM_CHUNK_ROUTINE_COUNT () - 1))
65 #endif  /* !G_DISABLE_CHECKS */
66
67 #ifndef REALLOC_0_WORKS
68 static gpointer
69 standard_realloc (gpointer mem,
70                   gsize    n_bytes)
71 {
72   if (!mem)
73     return malloc (n_bytes);
74   else
75     return realloc (mem, n_bytes);
76 }
77 #endif  /* !REALLOC_0_WORKS */
78
79 #ifdef SANE_MALLOC_PROTOS
80 #  define standard_malloc       malloc
81 #  ifdef REALLOC_0_WORKS
82 #    define standard_realloc    realloc
83 #  endif /* REALLOC_0_WORKS */
84 #  define standard_free         free
85 #  define standard_calloc       calloc
86 #  define standard_try_malloc   malloc
87 #  define standard_try_realloc  realloc
88 #else   /* !SANE_MALLOC_PROTOS */
89 static gpointer
90 standard_malloc (gsize n_bytes)
91 {
92   return malloc (n_bytes);
93 }
94 #  ifdef REALLOC_0_WORKS
95 static gpointer
96 standard_realloc (gpointer mem,
97                   gsize    n_bytes)
98 {
99   return realloc (mem, n_bytes);
100 }
101 #  endif /* REALLOC_0_WORKS */
102 static void
103 standard_free (gpointer mem)
104 {
105   free (mem);
106 }
107 static gpointer
108 standard_calloc (gsize n_blocks,
109                  gsize n_bytes)
110 {
111   return calloc (n_blocks, n_bytes);
112 }
113 #define standard_try_malloc     standard_malloc
114 #define standard_try_realloc    standard_realloc
115 #endif  /* !SANE_MALLOC_PROTOS */
116
117
118 /* --- variables --- */
119 static GMemVTable glib_mem_vtable = {
120   standard_malloc,
121   standard_realloc,
122   standard_free,
123   standard_calloc,
124   standard_try_malloc,
125   standard_try_realloc,
126 };
127
128
129 /* --- functions --- */
130 gpointer
131 g_malloc (gulong n_bytes)
132 {
133   if (n_bytes)
134     {
135       gpointer mem;
136
137       mem = glib_mem_vtable.malloc (n_bytes);
138       if (mem)
139         return mem;
140
141       g_error ("%s: failed to allocate %lu bytes", G_STRLOC, n_bytes);
142     }
143
144   return NULL;
145 }
146
147 gpointer
148 g_malloc0 (gulong n_bytes)
149 {
150   if (n_bytes)
151     {
152       gpointer mem;
153
154       mem = glib_mem_vtable.calloc (1, n_bytes);
155       if (mem)
156         return mem;
157
158       g_error ("%s: failed to allocate %lu bytes", G_STRLOC, n_bytes);
159     }
160
161   return NULL;
162 }
163
164 gpointer
165 g_realloc (gpointer mem,
166            gulong   n_bytes)
167 {
168   if (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 %lu bytes", G_STRLOC, n_bytes);
175     }
176
177   if (mem)
178     glib_mem_vtable.free (mem);
179
180   return NULL;
181 }
182
183 void
184 g_free (gpointer mem)
185 {
186   if (mem)
187     glib_mem_vtable.free (mem);
188 }
189
190 gpointer
191 g_try_malloc (gulong n_bytes)
192 {
193   if (n_bytes)
194     return glib_mem_vtable.try_malloc (n_bytes);
195   else
196     return NULL;
197 }
198
199 gpointer
200 g_try_malloc0 (gulong n_bytes)
201
202   gpointer mem;
203
204   mem = g_try_malloc (n_bytes);
205   
206   if (mem)
207     memset (mem, 0, n_bytes);
208
209   return mem;
210 }
211
212 gpointer
213 g_try_realloc (gpointer mem,
214                gulong   n_bytes)
215 {
216   if (n_bytes)
217     return glib_mem_vtable.try_realloc (mem, n_bytes);
218
219   if (mem)
220     glib_mem_vtable.free (mem);
221
222   return NULL;
223 }
224
225 static gpointer
226 fallback_calloc (gsize n_blocks,
227                  gsize n_block_bytes)
228 {
229   gsize l = n_blocks * n_block_bytes;
230   gpointer mem = glib_mem_vtable.malloc (l);
231
232   if (mem)
233     memset (mem, 0, l);
234
235   return mem;
236 }
237
238 static gboolean vtable_set = FALSE;
239
240 /**
241  * g_mem_is_system_malloc
242  * 
243  * Checks whether the allocator used by g_malloc() is the system's
244  * malloc implementation. If it returns %TRUE memory allocated with
245  * malloc() can be used interchangeable with memory allocated using g_malloc(). 
246  * This function is useful for avoiding an extra copy of allocated memory returned
247  * by a non-GLib-based API.
248  *
249  * A different allocator can be set using g_mem_set_vtable().
250  *
251  * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
252  **/
253 gboolean
254 g_mem_is_system_malloc (void)
255 {
256   return !vtable_set;
257 }
258
259 void
260 g_mem_set_vtable (GMemVTable *vtable)
261 {
262   if (!vtable_set)
263     {
264       if (vtable->malloc && vtable->realloc && vtable->free)
265         {
266           glib_mem_vtable.malloc = vtable->malloc;
267           glib_mem_vtable.realloc = vtable->realloc;
268           glib_mem_vtable.free = vtable->free;
269           glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
270           glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
271           glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
272           vtable_set = TRUE;
273         }
274       else
275         g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
276     }
277   else
278     g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
279 }
280
281
282 /* --- memory profiling and checking --- */
283 #ifdef  G_DISABLE_CHECKS
284 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
285 void
286 g_mem_profile (void)
287 {
288 }
289 #else   /* !G_DISABLE_CHECKS */
290 typedef enum {
291   PROFILER_FREE         = 0,
292   PROFILER_ALLOC        = 1,
293   PROFILER_RELOC        = 2,
294   PROFILER_ZINIT        = 4
295 } ProfilerJob;
296 static guint *profile_data = NULL;
297 static gulong profile_allocs = 0;
298 static gulong profile_mc_allocs = 0;
299 static gulong profile_zinit = 0;
300 static gulong profile_frees = 0;
301 static gulong profile_mc_frees = 0;
302 static GMutex *g_profile_mutex = NULL;
303 #ifdef  G_ENABLE_DEBUG
304 static volatile gulong g_trap_free_size = 0;
305 static volatile gulong g_trap_realloc_size = 0;
306 static volatile gulong g_trap_malloc_size = 0;
307 #endif  /* G_ENABLE_DEBUG */
308
309 #define PROFILE_TABLE(f1,f2,f3)   ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
310
311 static void
312 profiler_log (ProfilerJob job,
313               gulong      n_bytes,
314               gboolean    success)
315 {
316   g_mutex_lock (g_profile_mutex);
317   if (!profile_data)
318     {
319       profile_data = standard_malloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
320       if (!profile_data)        /* memory system kiddin' me, eh? */
321         {
322           g_mutex_unlock (g_profile_mutex);
323           return;
324         }
325     }
326
327   if (MEM_CHUNK_ROUTINE_COUNT () == 0)
328     {
329       if (n_bytes < MEM_PROFILE_TABLE_SIZE)
330         profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
331                                               (job & PROFILER_RELOC) != 0,
332                                               success != 0)] += 1;
333       else
334         profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
335                                                              (job & PROFILER_RELOC) != 0,
336                                                              success != 0)] += 1;
337       if (success)
338         {
339           if (job & PROFILER_ALLOC)
340             {
341               profile_allocs += n_bytes;
342               if (job & PROFILER_ZINIT)
343                 profile_zinit += n_bytes;
344             }
345           else
346             profile_frees += n_bytes;
347         }
348     }
349   else if (success)
350     {
351       if (job & PROFILER_ALLOC)
352         profile_mc_allocs += n_bytes;
353       else
354         profile_mc_frees += n_bytes;
355     }
356   g_mutex_unlock (g_profile_mutex);
357 }
358
359 static void
360 profile_print_locked (guint   *local_data,
361                       gboolean success)
362 {
363   gboolean need_header = TRUE;
364   guint i;
365
366   for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
367     {
368       glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
369       glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
370       glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
371       glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
372       
373       if (!t_malloc && !t_realloc && !t_free && !t_refree)
374         continue;
375       else if (need_header)
376         {
377           need_header = FALSE;
378           g_print (" blocks of | allocated  | freed      | allocated  | freed      | n_bytes   \n");
379           g_print ("  n_bytes  | n_times by | n_times by | n_times by | n_times by | remaining \n");
380           g_print ("           | malloc()   | free()     | realloc()  | realloc()  |           \n");
381           g_print ("===========|============|============|============|============|===========\n");
382         }
383       if (i < MEM_PROFILE_TABLE_SIZE)
384         g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
385                  i, t_malloc, t_free, t_realloc, t_refree,
386                  (t_malloc - t_free + t_realloc - t_refree) * i);
387       else if (i >= MEM_PROFILE_TABLE_SIZE)
388         g_print ("   >%6u | %10ld | %10ld | %10ld | %10ld |        ***\n",
389                  i, t_malloc, t_free, t_realloc, t_refree);
390     }
391   if (need_header)
392     g_print (" --- none ---\n");
393 }
394
395 void
396 g_mem_profile (void)
397 {
398   guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
399   gulong local_allocs;
400   gulong local_zinit;
401   gulong local_frees;
402   gulong local_mc_allocs;
403   gulong local_mc_frees;
404
405   g_mutex_lock (g_profile_mutex);
406
407   local_allocs = profile_allocs;
408   local_zinit = profile_zinit;
409   local_frees = profile_frees;
410   local_mc_allocs = profile_mc_allocs;
411   local_mc_frees = profile_mc_frees;
412
413   if (!profile_data)
414     {
415       g_mutex_unlock (g_profile_mutex);
416       return;
417     }
418
419   memcpy (local_data, profile_data, 
420           (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
421   
422   g_mutex_unlock (g_profile_mutex);
423
424   g_print ("GLib Memory statistics (successful operations):\n");
425   profile_print_locked (local_data, TRUE);
426   g_print ("GLib Memory statistics (failing operations):\n");
427   profile_print_locked (local_data, FALSE);
428   g_print ("Total bytes: allocated=%lu, zero-initialized=%lu (%.2f%%), freed=%lu (%.2f%%), remaining=%lu\n",
429            local_allocs,
430            local_zinit,
431            ((gdouble) local_zinit) / local_allocs * 100.0,
432            local_frees,
433            ((gdouble) local_frees) / local_allocs * 100.0,
434            local_allocs - local_frees);
435   g_print ("MemChunk bytes: allocated=%lu, freed=%lu (%.2f%%), remaining=%lu\n",
436            local_mc_allocs,
437            local_mc_frees,
438            ((gdouble) local_mc_frees) / local_mc_allocs * 100.0,
439            local_mc_allocs - local_mc_frees);
440 }
441
442 static gpointer
443 profiler_try_malloc (gsize n_bytes)
444 {
445   gulong *p;
446
447 #ifdef  G_ENABLE_DEBUG
448   if (g_trap_malloc_size == n_bytes)
449     G_BREAKPOINT ();
450 #endif  /* G_ENABLE_DEBUG */
451
452   p = standard_malloc (sizeof (gulong) * 2 + n_bytes);
453
454   if (p)
455     {
456       p[0] = 0;         /* free count */
457       p[1] = n_bytes;   /* length */
458       profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
459       p += 2;
460     }
461   else
462     profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
463   
464   return p;
465 }
466
467 static gpointer
468 profiler_malloc (gsize n_bytes)
469 {
470   gpointer mem = profiler_try_malloc (n_bytes);
471
472   if (!mem)
473     g_mem_profile ();
474
475   return mem;
476 }
477
478 static gpointer
479 profiler_calloc (gsize n_blocks,
480                  gsize n_block_bytes)
481 {
482   gsize l = n_blocks * n_block_bytes;
483   gulong *p;
484
485 #ifdef  G_ENABLE_DEBUG
486   if (g_trap_malloc_size == l)
487     G_BREAKPOINT ();
488 #endif  /* G_ENABLE_DEBUG */
489   
490   p = standard_calloc (1, sizeof (gulong) * 2 + l);
491
492   if (p)
493     {
494       p[0] = 0;         /* free count */
495       p[1] = l;         /* length */
496       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
497       p += 2;
498     }
499   else
500     {
501       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
502       g_mem_profile ();
503     }
504
505   return p;
506 }
507
508 static void
509 profiler_free (gpointer mem)
510 {
511   gulong *p = mem;
512
513   p -= 2;
514   if (p[0])     /* free count */
515     {
516       g_warning ("free(%p): memory has been freed %lu times already", p + 2, p[0]);
517       profiler_log (PROFILER_FREE,
518                     p[1],       /* length */
519                     FALSE);
520     }
521   else
522     {
523 #ifdef  G_ENABLE_DEBUG
524       if (g_trap_free_size == p[1])
525         G_BREAKPOINT ();
526 #endif  /* G_ENABLE_DEBUG */
527
528       profiler_log (PROFILER_FREE,
529                     p[1],       /* length */
530                     TRUE);
531       memset (p + 2, 0xaa, p[1]);
532
533       /* for all those that miss standard_free (p); in this place, yes,
534        * we do leak all memory when profiling, and that is intentional
535        * to catch double frees. patch submissions are futile.
536        */
537     }
538   p[0] += 1;
539 }
540
541 static gpointer
542 profiler_try_realloc (gpointer mem,
543                       gsize    n_bytes)
544 {
545   gulong *p = mem;
546
547   p -= 2;
548
549 #ifdef  G_ENABLE_DEBUG
550   if (g_trap_realloc_size == n_bytes)
551     G_BREAKPOINT ();
552 #endif  /* G_ENABLE_DEBUG */
553   
554   if (mem && p[0])      /* free count */
555     {
556       g_warning ("realloc(%p, %lu): memory has been freed %lu times already", p + 2, (gulong)n_bytes, p[0]);
557       profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
558
559       return NULL;
560     }
561   else
562     {
563       p = standard_realloc (mem ? p : NULL, sizeof (gulong) * 2 + n_bytes);
564
565       if (p)
566         {
567           if (mem)
568             profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
569           p[0] = 0;
570           p[1] = n_bytes;
571           profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
572           p += 2;
573         }
574       else
575         profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
576
577       return p;
578     }
579 }
580
581 static gpointer
582 profiler_realloc (gpointer mem,
583                   gsize    n_bytes)
584 {
585   mem = profiler_try_realloc (mem, n_bytes);
586
587   if (!mem)
588     g_mem_profile ();
589
590   return mem;
591 }
592
593 static GMemVTable profiler_table = {
594   profiler_malloc,
595   profiler_realloc,
596   profiler_free,
597   profiler_calloc,
598   profiler_try_malloc,
599   profiler_try_realloc,
600 };
601 GMemVTable *glib_mem_profiler_table = &profiler_table;
602
603 #endif  /* !G_DISABLE_CHECKS */
604
605
606 /* --- MemChunks --- */
607 typedef struct _GFreeAtom      GFreeAtom;
608 typedef struct _GMemArea       GMemArea;
609
610 struct _GFreeAtom
611 {
612   GFreeAtom *next;
613 };
614
615 struct _GMemArea
616 {
617   GMemArea *next;            /* the next mem area */
618   GMemArea *prev;            /* the previous mem area */
619   gulong index;              /* the current index into the "mem" array */
620   gulong free;               /* the number of free bytes in this mem area */
621   gulong allocated;          /* the number of atoms allocated from this area */
622   gulong mark;               /* is this mem area marked for deletion */
623   gchar mem[MEM_AREA_SIZE];  /* the mem array from which atoms get allocated
624                               * the actual size of this array is determined by
625                               *  the mem chunk "area_size". ANSI says that it
626                               *  must be declared to be the maximum size it
627                               *  can possibly be (even though the actual size
628                               *  may be less).
629                               */
630 };
631
632 struct _GMemChunk
633 {
634   const gchar *name;         /* name of this MemChunk...used for debugging output */
635   gint type;                 /* the type of MemChunk: ALLOC_ONLY or ALLOC_AND_FREE */
636   gint num_mem_areas;        /* the number of memory areas */
637   gint num_marked_areas;     /* the number of areas marked for deletion */
638   guint atom_size;           /* the size of an atom */
639   gulong area_size;          /* the size of a memory area */
640   GMemArea *mem_area;        /* the current memory area */
641   GMemArea *mem_areas;       /* a list of all the mem areas owned by this chunk */
642   GMemArea *free_mem_area;   /* the free area...which is about to be destroyed */
643   GFreeAtom *free_atoms;     /* the free atoms list */
644   GTree *mem_tree;           /* tree of mem areas sorted by memory address */
645   GMemChunk *next;           /* pointer to the next chunk */
646   GMemChunk *prev;           /* pointer to the previous chunk */
647 };
648
649
650 #ifndef DISABLE_MEM_POOLS
651 static gulong g_mem_chunk_compute_size (gulong    size,
652                                         gulong    min_size) G_GNUC_CONST;
653 static gint   g_mem_chunk_area_compare (GMemArea *a,
654                                         GMemArea *b);
655 static gint   g_mem_chunk_area_search  (GMemArea *a,
656                                         gchar    *addr);
657
658 /* here we can't use StaticMutexes, as they depend upon a working
659  * g_malloc, the same holds true for StaticPrivate
660  */
661 static GMutex        *mem_chunks_lock = NULL;
662 static GMemChunk     *mem_chunks = NULL;
663
664 GMemChunk*
665 g_mem_chunk_new (const gchar  *name,
666                  gint          atom_size,
667                  gulong        area_size,
668                  gint          type)
669 {
670   GMemChunk *mem_chunk;
671   gulong rarea_size;
672
673   g_return_val_if_fail (atom_size > 0, NULL);
674   g_return_val_if_fail (area_size >= atom_size, NULL);
675
676   ENTER_MEM_CHUNK_ROUTINE ();
677
678   area_size = (area_size + atom_size - 1) / atom_size;
679   area_size *= atom_size;
680
681   mem_chunk = g_new (GMemChunk, 1);
682   mem_chunk->name = name;
683   mem_chunk->type = type;
684   mem_chunk->num_mem_areas = 0;
685   mem_chunk->num_marked_areas = 0;
686   mem_chunk->mem_area = NULL;
687   mem_chunk->free_mem_area = NULL;
688   mem_chunk->free_atoms = NULL;
689   mem_chunk->mem_tree = NULL;
690   mem_chunk->mem_areas = NULL;
691   mem_chunk->atom_size = atom_size;
692   
693   if (mem_chunk->type == G_ALLOC_AND_FREE)
694     mem_chunk->mem_tree = g_tree_new ((GCompareFunc) g_mem_chunk_area_compare);
695   
696   if (mem_chunk->atom_size % G_MEM_ALIGN)
697     mem_chunk->atom_size += G_MEM_ALIGN - (mem_chunk->atom_size % G_MEM_ALIGN);
698
699   rarea_size = area_size + sizeof (GMemArea) - MEM_AREA_SIZE;
700   rarea_size = g_mem_chunk_compute_size (rarea_size, atom_size + sizeof (GMemArea) - MEM_AREA_SIZE);
701   mem_chunk->area_size = rarea_size - (sizeof (GMemArea) - MEM_AREA_SIZE);
702
703   g_mutex_lock (mem_chunks_lock);
704   mem_chunk->next = mem_chunks;
705   mem_chunk->prev = NULL;
706   if (mem_chunks)
707     mem_chunks->prev = mem_chunk;
708   mem_chunks = mem_chunk;
709   g_mutex_unlock (mem_chunks_lock);
710
711   LEAVE_MEM_CHUNK_ROUTINE ();
712
713   return mem_chunk;
714 }
715
716 void
717 g_mem_chunk_destroy (GMemChunk *mem_chunk)
718 {
719   GMemArea *mem_areas;
720   GMemArea *temp_area;
721   
722   g_return_if_fail (mem_chunk != NULL);
723
724   ENTER_MEM_CHUNK_ROUTINE ();
725
726   mem_areas = mem_chunk->mem_areas;
727   while (mem_areas)
728     {
729       temp_area = mem_areas;
730       mem_areas = mem_areas->next;
731       g_free (temp_area);
732     }
733   
734   g_mutex_lock (mem_chunks_lock);
735   if (mem_chunk->next)
736     mem_chunk->next->prev = mem_chunk->prev;
737   if (mem_chunk->prev)
738     mem_chunk->prev->next = mem_chunk->next;
739   
740   if (mem_chunk == mem_chunks)
741     mem_chunks = mem_chunks->next;
742   g_mutex_unlock (mem_chunks_lock);
743   
744   if (mem_chunk->type == G_ALLOC_AND_FREE)
745     g_tree_destroy (mem_chunk->mem_tree);  
746
747   g_free (mem_chunk);
748
749   LEAVE_MEM_CHUNK_ROUTINE ();
750 }
751
752 gpointer
753 g_mem_chunk_alloc (GMemChunk *mem_chunk)
754 {
755   GMemArea *temp_area;
756   gpointer mem;
757
758   ENTER_MEM_CHUNK_ROUTINE ();
759
760   g_return_val_if_fail (mem_chunk != NULL, NULL);
761   
762   while (mem_chunk->free_atoms)
763     {
764       /* Get the first piece of memory on the "free_atoms" list.
765        * We can go ahead and destroy the list node we used to keep
766        *  track of it with and to update the "free_atoms" list to
767        *  point to its next element.
768        */
769       mem = mem_chunk->free_atoms;
770       mem_chunk->free_atoms = mem_chunk->free_atoms->next;
771       
772       /* Determine which area this piece of memory is allocated from */
773       temp_area = g_tree_search (mem_chunk->mem_tree,
774                                  (GCompareFunc) g_mem_chunk_area_search,
775                                  mem);
776       
777       /* If the area has been marked, then it is being destroyed.
778        *  (ie marked to be destroyed).
779        * We check to see if all of the segments on the free list that
780        *  reference this area have been removed. This occurs when
781        *  the ammount of free memory is less than the allocatable size.
782        * If the chunk should be freed, then we place it in the "free_mem_area".
783        * This is so we make sure not to free the mem area here and then
784        *  allocate it again a few lines down.
785        * If we don't allocate a chunk a few lines down then the "free_mem_area"
786        *  will be freed.
787        * If there is already a "free_mem_area" then we'll just free this mem area.
788        */
789       if (temp_area->mark)
790         {
791           /* Update the "free" memory available in that area */
792           temp_area->free += mem_chunk->atom_size;
793           
794           if (temp_area->free == mem_chunk->area_size)
795             {
796               if (temp_area == mem_chunk->mem_area)
797                 mem_chunk->mem_area = NULL;
798               
799               if (mem_chunk->free_mem_area)
800                 {
801                   mem_chunk->num_mem_areas -= 1;
802                   
803                   if (temp_area->next)
804                     temp_area->next->prev = temp_area->prev;
805                   if (temp_area->prev)
806                     temp_area->prev->next = temp_area->next;
807                   if (temp_area == mem_chunk->mem_areas)
808                     mem_chunk->mem_areas = mem_chunk->mem_areas->next;
809                   
810                   if (mem_chunk->type == G_ALLOC_AND_FREE)
811                     g_tree_remove (mem_chunk->mem_tree, temp_area);
812                   g_free (temp_area);
813                 }
814               else
815                 mem_chunk->free_mem_area = temp_area;
816               
817               mem_chunk->num_marked_areas -= 1;
818             }
819         }
820       else
821         {
822           /* Update the number of allocated atoms count.
823            */
824           temp_area->allocated += 1;
825           
826           /* The area wasn't marked...return the memory
827            */
828           goto outa_here;
829         }
830     }
831   
832   /* If there isn't a current mem area or the current mem area is out of space
833    *  then allocate a new mem area. We'll first check and see if we can use
834    *  the "free_mem_area". Otherwise we'll just malloc the mem area.
835    */
836   if ((!mem_chunk->mem_area) ||
837       ((mem_chunk->mem_area->index + mem_chunk->atom_size) > mem_chunk->area_size))
838     {
839       if (mem_chunk->free_mem_area)
840         {
841           mem_chunk->mem_area = mem_chunk->free_mem_area;
842           mem_chunk->free_mem_area = NULL;
843         }
844       else
845         {
846 #ifdef ENABLE_GC_FRIENDLY
847           mem_chunk->mem_area = (GMemArea*) g_malloc0 (sizeof (GMemArea) -
848                                                        MEM_AREA_SIZE +
849                                                        mem_chunk->area_size); 
850 #else /* !ENABLE_GC_FRIENDLY */
851           mem_chunk->mem_area = (GMemArea*) g_malloc (sizeof (GMemArea) -
852                                                       MEM_AREA_SIZE +
853                                                       mem_chunk->area_size);
854 #endif /* ENABLE_GC_FRIENDLY */
855           
856           mem_chunk->num_mem_areas += 1;
857           mem_chunk->mem_area->next = mem_chunk->mem_areas;
858           mem_chunk->mem_area->prev = NULL;
859           
860           if (mem_chunk->mem_areas)
861             mem_chunk->mem_areas->prev = mem_chunk->mem_area;
862           mem_chunk->mem_areas = mem_chunk->mem_area;
863           
864           if (mem_chunk->type == G_ALLOC_AND_FREE)
865             g_tree_insert (mem_chunk->mem_tree, mem_chunk->mem_area, mem_chunk->mem_area);
866         }
867       
868       mem_chunk->mem_area->index = 0;
869       mem_chunk->mem_area->free = mem_chunk->area_size;
870       mem_chunk->mem_area->allocated = 0;
871       mem_chunk->mem_area->mark = 0;
872     }
873   
874   /* Get the memory and modify the state variables appropriately.
875    */
876   mem = (gpointer) &mem_chunk->mem_area->mem[mem_chunk->mem_area->index];
877   mem_chunk->mem_area->index += mem_chunk->atom_size;
878   mem_chunk->mem_area->free -= mem_chunk->atom_size;
879   mem_chunk->mem_area->allocated += 1;
880
881 outa_here:
882
883   LEAVE_MEM_CHUNK_ROUTINE ();
884
885   return mem;
886 }
887
888 gpointer
889 g_mem_chunk_alloc0 (GMemChunk *mem_chunk)
890 {
891   gpointer mem;
892
893   mem = g_mem_chunk_alloc (mem_chunk);
894   if (mem)
895     {
896       memset (mem, 0, mem_chunk->atom_size);
897     }
898
899   return mem;
900 }
901
902 void
903 g_mem_chunk_free (GMemChunk *mem_chunk,
904                   gpointer   mem)
905 {
906   GMemArea *temp_area;
907   GFreeAtom *free_atom;
908   
909   g_return_if_fail (mem_chunk != NULL);
910   g_return_if_fail (mem != NULL);
911
912   ENTER_MEM_CHUNK_ROUTINE ();
913
914 #ifdef ENABLE_GC_FRIENDLY
915   memset (mem, 0, mem_chunk->atom_size);
916 #endif /* ENABLE_GC_FRIENDLY */
917
918   /* Don't do anything if this is an ALLOC_ONLY chunk
919    */
920   if (mem_chunk->type == G_ALLOC_AND_FREE)
921     {
922       /* Place the memory on the "free_atoms" list
923        */
924       free_atom = (GFreeAtom*) mem;
925       free_atom->next = mem_chunk->free_atoms;
926       mem_chunk->free_atoms = free_atom;
927       
928       temp_area = g_tree_search (mem_chunk->mem_tree,
929                                  (GCompareFunc) g_mem_chunk_area_search,
930                                  mem);
931       
932       temp_area->allocated -= 1;
933       
934       if (temp_area->allocated == 0)
935         {
936           temp_area->mark = 1;
937           mem_chunk->num_marked_areas += 1;
938         }
939     }
940
941   LEAVE_MEM_CHUNK_ROUTINE ();
942 }
943
944 /* This doesn't free the free_area if there is one */
945 void
946 g_mem_chunk_clean (GMemChunk *mem_chunk)
947 {
948   GMemArea *mem_area;
949   GFreeAtom *prev_free_atom;
950   GFreeAtom *temp_free_atom;
951   gpointer mem;
952   
953   g_return_if_fail (mem_chunk != NULL);
954   
955   ENTER_MEM_CHUNK_ROUTINE ();
956
957   if (mem_chunk->type == G_ALLOC_AND_FREE)
958     {
959       prev_free_atom = NULL;
960       temp_free_atom = mem_chunk->free_atoms;
961       
962       while (temp_free_atom)
963         {
964           mem = (gpointer) temp_free_atom;
965           
966           mem_area = g_tree_search (mem_chunk->mem_tree,
967                                     (GCompareFunc) g_mem_chunk_area_search,
968                                     mem);
969           
970           /* If this mem area is marked for destruction then delete the
971            *  area and list node and decrement the free mem.
972            */
973           if (mem_area->mark)
974             {
975               if (prev_free_atom)
976                 prev_free_atom->next = temp_free_atom->next;
977               else
978                 mem_chunk->free_atoms = temp_free_atom->next;
979               temp_free_atom = temp_free_atom->next;
980               
981               mem_area->free += mem_chunk->atom_size;
982               if (mem_area->free == mem_chunk->area_size)
983                 {
984                   mem_chunk->num_mem_areas -= 1;
985                   mem_chunk->num_marked_areas -= 1;
986                   
987                   if (mem_area->next)
988                     mem_area->next->prev = mem_area->prev;
989                   if (mem_area->prev)
990                     mem_area->prev->next = mem_area->next;
991                   if (mem_area == mem_chunk->mem_areas)
992                     mem_chunk->mem_areas = mem_chunk->mem_areas->next;
993                   if (mem_area == mem_chunk->mem_area)
994                     mem_chunk->mem_area = NULL;
995                   
996                   if (mem_chunk->type == G_ALLOC_AND_FREE)
997                     g_tree_remove (mem_chunk->mem_tree, mem_area);
998                   g_free (mem_area);
999                 }
1000             }
1001           else
1002             {
1003               prev_free_atom = temp_free_atom;
1004               temp_free_atom = temp_free_atom->next;
1005             }
1006         }
1007     }
1008   LEAVE_MEM_CHUNK_ROUTINE ();
1009 }
1010
1011 void
1012 g_mem_chunk_reset (GMemChunk *mem_chunk)
1013 {
1014   GMemArea *mem_areas;
1015   GMemArea *temp_area;
1016   
1017   g_return_if_fail (mem_chunk != NULL);
1018   
1019   ENTER_MEM_CHUNK_ROUTINE ();
1020
1021   mem_areas = mem_chunk->mem_areas;
1022   mem_chunk->num_mem_areas = 0;
1023   mem_chunk->mem_areas = NULL;
1024   mem_chunk->mem_area = NULL;
1025   
1026   while (mem_areas)
1027     {
1028       temp_area = mem_areas;
1029       mem_areas = mem_areas->next;
1030       g_free (temp_area);
1031     }
1032   
1033   mem_chunk->free_atoms = NULL;
1034   
1035   if (mem_chunk->mem_tree)
1036     {
1037       g_tree_destroy (mem_chunk->mem_tree);
1038       mem_chunk->mem_tree = g_tree_new ((GCompareFunc) g_mem_chunk_area_compare);
1039     }
1040
1041   LEAVE_MEM_CHUNK_ROUTINE ();
1042 }
1043
1044 void
1045 g_mem_chunk_print (GMemChunk *mem_chunk)
1046 {
1047   GMemArea *mem_areas;
1048   gulong mem;
1049   
1050   g_return_if_fail (mem_chunk != NULL);
1051   
1052   mem_areas = mem_chunk->mem_areas;
1053   mem = 0;
1054   
1055   while (mem_areas)
1056     {
1057       mem += mem_chunk->area_size - mem_areas->free;
1058       mem_areas = mem_areas->next;
1059     }
1060
1061   g_log (G_LOG_DOMAIN, G_LOG_LEVEL_INFO,
1062          "%s: %ld bytes using %d mem areas",
1063          mem_chunk->name, mem, mem_chunk->num_mem_areas);
1064 }
1065
1066 void
1067 g_mem_chunk_info (void)
1068 {
1069   GMemChunk *mem_chunk;
1070   gint count;
1071   
1072   count = 0;
1073   g_mutex_lock (mem_chunks_lock);
1074   mem_chunk = mem_chunks;
1075   while (mem_chunk)
1076     {
1077       count += 1;
1078       mem_chunk = mem_chunk->next;
1079     }
1080   g_mutex_unlock (mem_chunks_lock);
1081   
1082   g_log (G_LOG_DOMAIN, G_LOG_LEVEL_INFO, "%d mem chunks", count);
1083   
1084   g_mutex_lock (mem_chunks_lock);
1085   mem_chunk = mem_chunks;
1086   g_mutex_unlock (mem_chunks_lock);
1087
1088   while (mem_chunk)
1089     {
1090       g_mem_chunk_print ((GMemChunk*) mem_chunk);
1091       mem_chunk = mem_chunk->next;
1092     }  
1093 }
1094
1095 void
1096 g_blow_chunks (void)
1097 {
1098   GMemChunk *mem_chunk;
1099   
1100   g_mutex_lock (mem_chunks_lock);
1101   mem_chunk = mem_chunks;
1102   g_mutex_unlock (mem_chunks_lock);
1103   while (mem_chunk)
1104     {
1105       g_mem_chunk_clean ((GMemChunk*) mem_chunk);
1106       mem_chunk = mem_chunk->next;
1107     }
1108 }
1109
1110 static gulong
1111 g_mem_chunk_compute_size (gulong size,
1112                           gulong min_size)
1113 {
1114   gulong power_of_2;
1115   gulong lower, upper;
1116   
1117   power_of_2 = 16;
1118   while (power_of_2 < size)
1119     power_of_2 <<= 1;
1120   
1121   lower = power_of_2 >> 1;
1122   upper = power_of_2;
1123   
1124   if (size - lower < upper - size && lower >= min_size)
1125     return lower;
1126   else
1127     return upper;
1128 }
1129
1130 static gint
1131 g_mem_chunk_area_compare (GMemArea *a,
1132                           GMemArea *b)
1133 {
1134   if (a->mem > b->mem)
1135     return 1;
1136   else if (a->mem < b->mem)
1137     return -1;
1138   return 0;
1139 }
1140
1141 static gint
1142 g_mem_chunk_area_search (GMemArea *a,
1143                          gchar    *addr)
1144 {
1145   if (a->mem <= addr)
1146     {
1147       if (addr < &a->mem[a->index])
1148         return 0;
1149       return 1;
1150     }
1151   return -1;
1152 }
1153
1154 #else /* DISABLE_MEM_POOLS */
1155
1156 typedef struct {
1157   guint alloc_size;           /* the size of an atom */
1158 }  GMinimalMemChunk;
1159
1160 GMemChunk*
1161 g_mem_chunk_new (const gchar  *name,
1162                  gint          atom_size,
1163                  gulong        area_size,
1164                  gint          type)
1165 {
1166   GMinimalMemChunk *mem_chunk;
1167
1168   g_return_val_if_fail (atom_size > 0, NULL);
1169
1170   mem_chunk = g_new (GMinimalMemChunk, 1);
1171   mem_chunk->alloc_size = atom_size;
1172
1173   return ((GMemChunk*) mem_chunk);
1174 }
1175
1176 void
1177 g_mem_chunk_destroy (GMemChunk *mem_chunk)
1178 {
1179   g_return_if_fail (mem_chunk != NULL);
1180   
1181   g_free (mem_chunk);
1182 }
1183
1184 gpointer
1185 g_mem_chunk_alloc (GMemChunk *mem_chunk)
1186 {
1187   GMinimalMemChunk *minimal = (GMinimalMemChunk *)mem_chunk;
1188   
1189   g_return_val_if_fail (mem_chunk != NULL, NULL);
1190   
1191   return g_malloc (minimal->alloc_size);
1192 }
1193
1194 gpointer
1195 g_mem_chunk_alloc0 (GMemChunk *mem_chunk)
1196 {
1197   GMinimalMemChunk *minimal = (GMinimalMemChunk *)mem_chunk;
1198   
1199   g_return_val_if_fail (mem_chunk != NULL, NULL);
1200   
1201   return g_malloc0 (minimal->alloc_size);
1202 }
1203
1204 void
1205 g_mem_chunk_free (GMemChunk *mem_chunk,
1206                   gpointer   mem)
1207 {
1208   g_return_if_fail (mem_chunk != NULL);
1209   
1210   g_free (mem);
1211 }
1212
1213 void    g_mem_chunk_clean       (GMemChunk *mem_chunk)  {}
1214 void    g_mem_chunk_reset       (GMemChunk *mem_chunk)  {}
1215 void    g_mem_chunk_print       (GMemChunk *mem_chunk)  {}
1216 void    g_mem_chunk_info        (void)                  {}
1217 void    g_blow_chunks           (void)                  {}
1218
1219 #endif /* DISABLE_MEM_POOLS */
1220
1221
1222 /* generic allocators
1223  */
1224 struct _GAllocator /* from gmem.c */
1225 {
1226   gchar         *name;
1227   guint16        n_preallocs;
1228   guint          is_unused : 1;
1229   guint          type : 4;
1230   GAllocator    *last;
1231   GMemChunk     *mem_chunk;
1232   gpointer       dummy; /* implementation specific */
1233 };
1234
1235 GAllocator*
1236 g_allocator_new (const gchar *name,
1237                  guint        n_preallocs)
1238 {
1239   GAllocator *allocator;
1240
1241   g_return_val_if_fail (name != NULL, NULL);
1242
1243   allocator = g_new0 (GAllocator, 1);
1244   allocator->name = g_strdup (name);
1245   allocator->n_preallocs = CLAMP (n_preallocs, 1, 65535);
1246   allocator->is_unused = TRUE;
1247   allocator->type = 0;
1248   allocator->last = NULL;
1249   allocator->mem_chunk = NULL;
1250   allocator->dummy = NULL;
1251
1252   return allocator;
1253 }
1254
1255 void
1256 g_allocator_free (GAllocator *allocator)
1257 {
1258   g_return_if_fail (allocator != NULL);
1259   g_return_if_fail (allocator->is_unused == TRUE);
1260
1261   g_free (allocator->name);
1262   if (allocator->mem_chunk)
1263     g_mem_chunk_destroy (allocator->mem_chunk);
1264
1265   g_free (allocator);
1266 }
1267
1268 void
1269 _g_mem_thread_init (void)
1270 {
1271 #ifndef DISABLE_MEM_POOLS
1272   mem_chunks_lock = g_mutex_new ();
1273 #endif
1274 #ifndef G_DISABLE_CHECKS
1275   g_profile_mutex = g_mutex_new ();
1276 #endif
1277 }
1278
1279 void
1280 _g_mem_thread_private_init (void)
1281 {
1282 #ifndef G_DISABLE_CHECKS
1283   g_assert (mem_chunk_recursion == NULL);
1284   mem_chunk_recursion = g_private_new (NULL);
1285 #endif
1286 }
1287
1288 #define __G_MEM_C__
1289 #include "galiasdef.c"