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