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