gfileutils: Add missing g_free() in error path
[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, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GLib Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
23  */
24
25 /* 
26  * MT safe
27  */
28
29 #include "config.h"
30
31 #include "gmem.h"
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <signal.h>
36
37 #include "gslice.h"
38 #include "gbacktrace.h"
39 #include "gtestutils.h"
40 #include "gthread.h"
41 #include "glib_trace.h"
42
43 #define MEM_PROFILE_TABLE_SIZE 4096
44
45
46 /* notes on macros:
47  * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
48  * g_mem_profile().
49  * If g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
50  */
51
52 /* --- variables --- */
53 static GMemVTable glib_mem_vtable = {
54   malloc,
55   realloc,
56   free,
57   calloc,
58   malloc,
59   realloc,
60 };
61
62 /**
63  * SECTION:memory
64  * @Short_Description: general memory-handling
65  * @Title: Memory Allocation
66  * 
67  * These functions provide support for allocating and freeing memory.
68  * 
69  * If any call to allocate memory fails, the application is terminated.
70  * This also means that there is no need to check if the call succeeded.
71  * 
72  * It's important to match g_malloc() (and wrappers such as g_new()) with
73  * g_free(), g_slice_alloc() and wrappers such as g_slice_new()) with
74  * g_slice_free(), plain malloc() with free(), and (if you're using C++)
75  * new with delete and new[] with delete[]. Otherwise bad things can happen,
76  * since these allocators may use different memory pools (and new/delete call
77  * constructors and destructors). See also g_mem_set_vtable().
78  */
79
80 /* --- functions --- */
81 /**
82  * g_malloc:
83  * @n_bytes: the number of bytes to allocate
84  * 
85  * Allocates @n_bytes bytes of memory.
86  * If @n_bytes is 0 it returns %NULL.
87  * 
88  * Returns: a pointer to the allocated memory
89  */
90 gpointer
91 g_malloc (gsize n_bytes)
92 {
93   if (G_LIKELY (n_bytes))
94     {
95       gpointer mem;
96
97       mem = glib_mem_vtable.malloc (n_bytes);
98       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
99       if (mem)
100         return mem;
101
102       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
103                G_STRLOC, n_bytes);
104     }
105
106   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
107
108   return NULL;
109 }
110
111 /**
112  * g_malloc0:
113  * @n_bytes: the number of bytes to allocate
114  * 
115  * Allocates @n_bytes bytes of memory, initialized to 0's.
116  * If @n_bytes is 0 it returns %NULL.
117  * 
118  * Returns: a pointer to the allocated memory
119  */
120 gpointer
121 g_malloc0 (gsize n_bytes)
122 {
123   if (G_LIKELY (n_bytes))
124     {
125       gpointer mem;
126
127       mem = glib_mem_vtable.calloc (1, n_bytes);
128       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
129       if (mem)
130         return mem;
131
132       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
133                G_STRLOC, n_bytes);
134     }
135
136   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
137
138   return NULL;
139 }
140
141 /**
142  * g_realloc:
143  * @mem: (allow-none): the memory to reallocate
144  * @n_bytes: new size of the memory in bytes
145  * 
146  * Reallocates the memory pointed to by @mem, so that it now has space for
147  * @n_bytes bytes of memory. It returns the new address of the memory, which may
148  * have been moved. @mem may be %NULL, in which case it's considered to
149  * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
150  * and @mem will be freed unless it is %NULL.
151  * 
152  * Returns: the new address of the allocated memory
153  */
154 gpointer
155 g_realloc (gpointer mem,
156            gsize    n_bytes)
157 {
158   gpointer newmem;
159
160   if (G_LIKELY (n_bytes))
161     {
162       newmem = glib_mem_vtable.realloc (mem, n_bytes);
163       TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
164       if (newmem)
165         return newmem;
166
167       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
168                G_STRLOC, n_bytes);
169     }
170
171   if (mem)
172     glib_mem_vtable.free (mem);
173
174   TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
175
176   return NULL;
177 }
178
179 /**
180  * g_free:
181  * @mem: (allow-none): the memory to free
182  * 
183  * Frees the memory pointed to by @mem.
184  * If @mem is %NULL it simply returns.
185  */
186 void
187 g_free (gpointer mem)
188 {
189   if (G_LIKELY (mem))
190     glib_mem_vtable.free (mem);
191   TRACE(GLIB_MEM_FREE((void*) mem));
192 }
193
194 /**
195  * g_clear_pointer: (skip)
196  * @pp: a pointer to a variable, struct member etc. holding a pointer
197  * @destroy: a function to which a gpointer can be passed, to destroy *@pp
198  *
199  * Clears a reference to a variable.
200  *
201  * @pp must not be %NULL.
202  *
203  * If the reference is %NULL then this function does nothing.
204  * Otherwise, the variable is destroyed using @destroy and the
205  * pointer is set to %NULL.
206  *
207  * This function is threadsafe and modifies the pointer atomically,
208  * using memory barriers where needed.
209  *
210  * A macro is also included that allows this function to be used without
211  * pointer casts.
212  *
213  * Since: 2.34
214  **/
215 #undef g_clear_pointer
216 void
217 g_clear_pointer (gpointer      *pp,
218                  GDestroyNotify destroy)
219 {
220   gpointer _p;
221
222   /* This is a little frustrating.
223    * Would be nice to have an atomic exchange (with no compare).
224    */
225   do
226     _p = g_atomic_pointer_get (pp);
227   while G_UNLIKELY (!g_atomic_pointer_compare_and_exchange (pp, _p, NULL));
228
229   if (_p)
230     destroy (_p);
231 }
232
233 /**
234  * g_try_malloc:
235  * @n_bytes: number of bytes to allocate.
236  * 
237  * Attempts to allocate @n_bytes, and returns %NULL on failure.
238  * Contrast with g_malloc(), which aborts the program on failure.
239  * 
240  * Returns: the allocated memory, or %NULL.
241  */
242 gpointer
243 g_try_malloc (gsize n_bytes)
244 {
245   gpointer mem;
246
247   if (G_LIKELY (n_bytes))
248     mem = glib_mem_vtable.try_malloc (n_bytes);
249   else
250     mem = NULL;
251
252   TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
253
254   return mem;
255 }
256
257 /**
258  * g_try_malloc0:
259  * @n_bytes: number of bytes to allocate
260  * 
261  * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
262  * failure. Contrast with g_malloc0(), which aborts the program on failure.
263  * 
264  * Since: 2.8
265  * Returns: the allocated memory, or %NULL
266  */
267 gpointer
268 g_try_malloc0 (gsize n_bytes)
269 {
270   gpointer mem;
271
272   if (G_LIKELY (n_bytes))
273     mem = glib_mem_vtable.try_malloc (n_bytes);
274   else
275     mem = NULL;
276
277   if (mem)
278     memset (mem, 0, n_bytes);
279
280   return mem;
281 }
282
283 /**
284  * g_try_realloc:
285  * @mem: (allow-none): previously-allocated memory, or %NULL.
286  * @n_bytes: number of bytes to allocate.
287  * 
288  * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
289  * on failure. Contrast with g_realloc(), which aborts the program
290  * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
291  * 
292  * Returns: the allocated memory, or %NULL.
293  */
294 gpointer
295 g_try_realloc (gpointer mem,
296                gsize    n_bytes)
297 {
298   gpointer newmem;
299
300   if (G_LIKELY (n_bytes))
301     newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
302   else
303     {
304       newmem = NULL;
305       if (mem)
306         glib_mem_vtable.free (mem);
307     }
308
309   TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
310
311   return newmem;
312 }
313
314
315 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
316
317 /**
318  * g_malloc_n:
319  * @n_blocks: the number of blocks to allocate
320  * @n_block_bytes: the size of each block in bytes
321  * 
322  * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
323  * but care is taken to detect possible overflow during multiplication.
324  * 
325  * Since: 2.24
326  * Returns: a pointer to the allocated memory
327  */
328 gpointer
329 g_malloc_n (gsize n_blocks,
330             gsize n_block_bytes)
331 {
332   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
333     {
334       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
335                G_STRLOC, n_blocks, n_block_bytes);
336     }
337
338   return g_malloc (n_blocks * n_block_bytes);
339 }
340
341 /**
342  * g_malloc0_n:
343  * @n_blocks: the number of blocks to allocate
344  * @n_block_bytes: the size of each block in bytes
345  * 
346  * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
347  * but care is taken to detect possible overflow during multiplication.
348  * 
349  * Since: 2.24
350  * Returns: a pointer to the allocated memory
351  */
352 gpointer
353 g_malloc0_n (gsize n_blocks,
354              gsize n_block_bytes)
355 {
356   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
357     {
358       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
359                G_STRLOC, n_blocks, n_block_bytes);
360     }
361
362   return g_malloc0 (n_blocks * n_block_bytes);
363 }
364
365 /**
366  * g_realloc_n:
367  * @mem: (allow-none): the memory to reallocate
368  * @n_blocks: the number of blocks to allocate
369  * @n_block_bytes: the size of each block in bytes
370  * 
371  * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
372  * but care is taken to detect possible overflow during multiplication.
373  * 
374  * Since: 2.24
375  * Returns: the new address of the allocated memory
376  */
377 gpointer
378 g_realloc_n (gpointer mem,
379              gsize    n_blocks,
380              gsize    n_block_bytes)
381 {
382   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
383     {
384       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
385                G_STRLOC, n_blocks, n_block_bytes);
386     }
387
388   return g_realloc (mem, n_blocks * n_block_bytes);
389 }
390
391 /**
392  * g_try_malloc_n:
393  * @n_blocks: the number of blocks to allocate
394  * @n_block_bytes: the size of each block in bytes
395  * 
396  * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
397  * but care is taken to detect possible overflow during multiplication.
398  * 
399  * Since: 2.24
400  * Returns: the allocated memory, or %NULL.
401  */
402 gpointer
403 g_try_malloc_n (gsize n_blocks,
404                 gsize n_block_bytes)
405 {
406   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
407     return NULL;
408
409   return g_try_malloc (n_blocks * n_block_bytes);
410 }
411
412 /**
413  * g_try_malloc0_n:
414  * @n_blocks: the number of blocks to allocate
415  * @n_block_bytes: the size of each block in bytes
416  * 
417  * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
418  * but care is taken to detect possible overflow during multiplication.
419  * 
420  * Since: 2.24
421  * Returns: the allocated memory, or %NULL
422  */
423 gpointer
424 g_try_malloc0_n (gsize n_blocks,
425                  gsize n_block_bytes)
426 {
427   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
428     return NULL;
429
430   return g_try_malloc0 (n_blocks * n_block_bytes);
431 }
432
433 /**
434  * g_try_realloc_n:
435  * @mem: (allow-none): previously-allocated memory, or %NULL.
436  * @n_blocks: the number of blocks to allocate
437  * @n_block_bytes: the size of each block in bytes
438  * 
439  * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
440  * but care is taken to detect possible overflow during multiplication.
441  * 
442  * Since: 2.24
443  * Returns: the allocated memory, or %NULL.
444  */
445 gpointer
446 g_try_realloc_n (gpointer mem,
447                  gsize    n_blocks,
448                  gsize    n_block_bytes)
449 {
450   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
451     return NULL;
452
453   return g_try_realloc (mem, n_blocks * n_block_bytes);
454 }
455
456
457
458 static gpointer
459 fallback_calloc (gsize n_blocks,
460                  gsize n_block_bytes)
461 {
462   gsize l = n_blocks * n_block_bytes;
463   gpointer mem = glib_mem_vtable.malloc (l);
464
465   if (mem)
466     memset (mem, 0, l);
467
468   return mem;
469 }
470
471 static gboolean vtable_set = FALSE;
472
473 /**
474  * g_mem_is_system_malloc:
475  * 
476  * Checks whether the allocator used by g_malloc() is the system's
477  * malloc implementation. If it returns %TRUE memory allocated with
478  * malloc() can be used interchangeable with memory allocated using g_malloc().
479  * This function is useful for avoiding an extra copy of allocated memory returned
480  * by a non-GLib-based API.
481  *
482  * A different allocator can be set using g_mem_set_vtable().
483  *
484  * Returns: if %TRUE, malloc() and g_malloc() can be mixed.
485  **/
486 gboolean
487 g_mem_is_system_malloc (void)
488 {
489   return !vtable_set;
490 }
491
492 /**
493  * g_mem_set_vtable:
494  * @vtable: table of memory allocation routines.
495  * 
496  * Sets the #GMemVTable to use for memory allocation. You can use this
497  * to provide custom memory allocation routines.
498  *
499  * The @vtable only needs to provide malloc(), realloc(), and free()
500  * functions; GLib can provide default implementations of the others.
501  * The malloc() and realloc() implementations should return %NULL on
502  * failure, GLib will handle error-checking for you. @vtable is copied,
503  * so need not persist after this function has been called.
504  *
505  * Note that this function must be called before using any other GLib
506  * functions.
507  */
508 void
509 g_mem_set_vtable (GMemVTable *vtable)
510 {
511   if (!vtable_set)
512     {
513       if (vtable->malloc && vtable->realloc && vtable->free)
514         {
515           glib_mem_vtable.malloc = vtable->malloc;
516           glib_mem_vtable.realloc = vtable->realloc;
517           glib_mem_vtable.free = vtable->free;
518           glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
519           glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
520           glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
521           vtable_set = TRUE;
522         }
523       else
524         g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
525     }
526   else
527     g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
528 }
529
530
531 /* --- memory profiling and checking --- */
532 #ifdef  G_DISABLE_CHECKS
533 /**
534  * glib_mem_profiler_table:
535  * 
536  * A #GMemVTable containing profiling variants of the memory
537  * allocation functions. Use them together with g_mem_profile()
538  * in order to get information about the memory allocation pattern
539  * of your program.
540  */
541 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
542 void
543 g_mem_profile (void)
544 {
545 }
546 #else   /* !G_DISABLE_CHECKS */
547 typedef enum {
548   PROFILER_FREE         = 0,
549   PROFILER_ALLOC        = 1,
550   PROFILER_RELOC        = 2,
551   PROFILER_ZINIT        = 4
552 } ProfilerJob;
553 static guint *profile_data = NULL;
554 static gsize profile_allocs = 0;
555 static gsize profile_zinit = 0;
556 static gsize profile_frees = 0;
557 static GMutex gmem_profile_mutex;
558
559 #define PROFILE_TABLE(f1,f2,f3)   ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
560
561 static void
562 profiler_log (ProfilerJob job,
563               gsize       n_bytes,
564               gboolean    success)
565 {
566   g_mutex_lock (&gmem_profile_mutex);
567   if (!profile_data)
568     {
569       profile_data = calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8, 
570                              sizeof (profile_data[0]));
571       if (!profile_data)        /* memory system kiddin' me, eh? */
572         {
573           g_mutex_unlock (&gmem_profile_mutex);
574           return;
575         }
576     }
577
578   if (n_bytes < MEM_PROFILE_TABLE_SIZE)
579     profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
580                                           (job & PROFILER_RELOC) != 0,
581                                           success != 0)] += 1;
582   else
583     profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
584                                                          (job & PROFILER_RELOC) != 0,
585                                                          success != 0)] += 1;
586   if (success)
587     {
588       if (job & PROFILER_ALLOC)
589         {
590           profile_allocs += n_bytes;
591           if (job & PROFILER_ZINIT)
592             profile_zinit += n_bytes;
593         }
594       else
595         profile_frees += n_bytes;
596     }
597   g_mutex_unlock (&gmem_profile_mutex);
598 }
599
600 static void
601 profile_print_locked (guint   *local_data,
602                       gboolean success)
603 {
604   gboolean need_header = TRUE;
605   guint i;
606
607   for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
608     {
609       glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
610       glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
611       glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
612       glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
613       
614       if (!t_malloc && !t_realloc && !t_free && !t_refree)
615         continue;
616       else if (need_header)
617         {
618           need_header = FALSE;
619           g_print (" blocks of | allocated  | freed      | allocated  | freed      | n_bytes   \n");
620           g_print ("  n_bytes  | n_times by | n_times by | n_times by | n_times by | remaining \n");
621           g_print ("           | malloc()   | free()     | realloc()  | realloc()  |           \n");
622           g_print ("===========|============|============|============|============|===========\n");
623         }
624       if (i < MEM_PROFILE_TABLE_SIZE)
625         g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
626                  i, t_malloc, t_free, t_realloc, t_refree,
627                  (t_malloc - t_free + t_realloc - t_refree) * i);
628       else if (i >= MEM_PROFILE_TABLE_SIZE)
629         g_print ("   >%6u | %10ld | %10ld | %10ld | %10ld |        ***\n",
630                  i, t_malloc, t_free, t_realloc, t_refree);
631     }
632   if (need_header)
633     g_print (" --- none ---\n");
634 }
635
636 /**
637  * g_mem_profile:
638  * 
639  * Outputs a summary of memory usage.
640  * 
641  * It outputs the frequency of allocations of different sizes,
642  * the total number of bytes which have been allocated,
643  * the total number of bytes which have been freed,
644  * and the difference between the previous two values, i.e. the number of bytes
645  * still in use.
646  * 
647  * Note that this function will not output anything unless you have
648  * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
649  */
650
651 void
652 g_mem_profile (void)
653 {
654   guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8];
655   gsize local_allocs;
656   gsize local_zinit;
657   gsize local_frees;
658
659   g_mutex_lock (&gmem_profile_mutex);
660
661   local_allocs = profile_allocs;
662   local_zinit = profile_zinit;
663   local_frees = profile_frees;
664
665   if (!profile_data)
666     {
667       g_mutex_unlock (&gmem_profile_mutex);
668       return;
669     }
670
671   memcpy (local_data, profile_data, 
672           (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
673   
674   g_mutex_unlock (&gmem_profile_mutex);
675
676   g_print ("GLib Memory statistics (successful operations):\n");
677   profile_print_locked (local_data, TRUE);
678   g_print ("GLib Memory statistics (failing operations):\n");
679   profile_print_locked (local_data, FALSE);
680   g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
681            "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
682            "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
683            "remaining=%"G_GSIZE_FORMAT"\n",
684            local_allocs,
685            local_zinit,
686            ((gdouble) local_zinit) / local_allocs * 100.0,
687            local_frees,
688            ((gdouble) local_frees) / local_allocs * 100.0,
689            local_allocs - local_frees);
690 }
691
692 static gpointer
693 profiler_try_malloc (gsize n_bytes)
694 {
695   gsize *p;
696
697   p = malloc (sizeof (gsize) * 2 + n_bytes);
698
699   if (p)
700     {
701       p[0] = 0;         /* free count */
702       p[1] = n_bytes;   /* length */
703       profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
704       p += 2;
705     }
706   else
707     profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
708   
709   return p;
710 }
711
712 static gpointer
713 profiler_malloc (gsize n_bytes)
714 {
715   gpointer mem = profiler_try_malloc (n_bytes);
716
717   if (!mem)
718     g_mem_profile ();
719
720   return mem;
721 }
722
723 static gpointer
724 profiler_calloc (gsize n_blocks,
725                  gsize n_block_bytes)
726 {
727   gsize l = n_blocks * n_block_bytes;
728   gsize *p;
729
730   p = calloc (1, sizeof (gsize) * 2 + l);
731
732   if (p)
733     {
734       p[0] = 0;         /* free count */
735       p[1] = l;         /* length */
736       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
737       p += 2;
738     }
739   else
740     {
741       profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
742       g_mem_profile ();
743     }
744
745   return p;
746 }
747
748 static void
749 profiler_free (gpointer mem)
750 {
751   gsize *p = mem;
752
753   p -= 2;
754   if (p[0])     /* free count */
755     {
756       g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
757                  p + 2, p[0]);
758       profiler_log (PROFILER_FREE,
759                     p[1],       /* length */
760                     FALSE);
761     }
762   else
763     {
764       profiler_log (PROFILER_FREE,
765                     p[1],       /* length */
766                     TRUE);
767       memset (p + 2, 0xaa, p[1]);
768
769       /* for all those that miss free (p); in this place, yes,
770        * we do leak all memory when profiling, and that is intentional
771        * to catch double frees. patch submissions are futile.
772        */
773     }
774   p[0] += 1;
775 }
776
777 static gpointer
778 profiler_try_realloc (gpointer mem,
779                       gsize    n_bytes)
780 {
781   gsize *p = mem;
782
783   p -= 2;
784   
785   if (mem && p[0])      /* free count */
786     {
787       g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
788                  "memory has been freed %"G_GSIZE_FORMAT" times already",
789                  p + 2, (gsize) n_bytes, p[0]);
790       profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
791
792       return NULL;
793     }
794   else
795     {
796       p = realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
797
798       if (p)
799         {
800           if (mem)
801             profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
802           p[0] = 0;
803           p[1] = n_bytes;
804           profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
805           p += 2;
806         }
807       else
808         profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
809
810       return p;
811     }
812 }
813
814 static gpointer
815 profiler_realloc (gpointer mem,
816                   gsize    n_bytes)
817 {
818   mem = profiler_try_realloc (mem, n_bytes);
819
820   if (!mem)
821     g_mem_profile ();
822
823   return mem;
824 }
825
826 static GMemVTable profiler_table = {
827   profiler_malloc,
828   profiler_realloc,
829   profiler_free,
830   profiler_calloc,
831   profiler_try_malloc,
832   profiler_try_realloc,
833 };
834 GMemVTable *glib_mem_profiler_table = &profiler_table;
835
836 #endif  /* !G_DISABLE_CHECKS */