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