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