Imported Upstream version 2.74.3
[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  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
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 "gmem.h"
34
35 #if defined(HAVE_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
36 # define _XOPEN_SOURCE 600
37 #endif
38
39 #if defined(HAVE_MEMALIGN) || defined(HAVE__ALIGNED_MALLOC)
40 /* Required for _aligned_malloc() and _aligned_free() on Windows */
41 #include <malloc.h>
42 #endif
43
44 #ifdef HAVE__ALIGNED_MALLOC
45 /* _aligned_malloc() takes parameters of aligned_malloc() in reverse order */
46 # define aligned_alloc(alignment, size) _aligned_malloc (size, alignment)
47
48 /* _aligned_malloc()'ed memory must be freed by _align_free() on MSVC */
49 # define aligned_free(x) _aligned_free (x)
50 #else
51 # define aligned_free(x) free (x)
52 #endif
53
54 #include <stdlib.h>
55 #include <string.h>
56 #include <signal.h>
57
58 #include "gslice.h"
59 #include "gbacktrace.h"
60 #include "gtestutils.h"
61 #include "gthread.h"
62 #include "glib_trace.h"
63
64 /* notes on macros:
65  * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
66  * g_mem_profile().
67  * If g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
68  */
69
70 /* --- variables --- */
71 static GMemVTable glib_mem_vtable = {
72   malloc,
73   realloc,
74   free,
75   calloc,
76   malloc,
77   realloc,
78 };
79
80 /**
81  * SECTION:memory
82  * @Short_Description: general memory-handling
83  * @Title: Memory Allocation
84  * 
85  * These functions provide support for allocating and freeing memory.
86  * 
87  * If any call to allocate memory using functions g_new(), g_new0(), g_renew(),
88  * g_malloc(), g_malloc0(), g_malloc0_n(), g_realloc(), and g_realloc_n()
89  * fails, the application is terminated. This also means that there is no
90  * need to check if the call succeeded. On the other hand, the `g_try_...()` family
91  * of functions returns %NULL on failure that can be used as a check
92  * for unsuccessful memory allocation. The application is not terminated
93  * in this case.
94  *
95  * As all GLib functions and data structures use `g_malloc()` internally, unless
96  * otherwise specified, any allocation failure will result in the application
97  * being terminated.
98  *
99  * It's important to match g_malloc() (and wrappers such as g_new()) with
100  * g_free(), g_slice_alloc() (and wrappers such as g_slice_new()) with
101  * g_slice_free(), plain malloc() with free(), and (if you're using C++)
102  * new with delete and new[] with delete[]. Otherwise bad things can happen,
103  * since these allocators may use different memory pools (and new/delete call
104  * constructors and destructors).
105  *
106  * Since GLib 2.46 g_malloc() is hardcoded to always use the system malloc
107  * implementation.
108  */
109
110 /* --- functions --- */
111 /**
112  * g_malloc:
113  * @n_bytes: the number of bytes to allocate
114  *
115  * Allocates @n_bytes bytes of memory.
116  * If @n_bytes is 0 it returns %NULL.
117  *
118  * If the allocation fails (because the system is out of memory),
119  * the program is terminated.
120  *
121  * Returns: a pointer to the allocated memory
122  */
123 gpointer
124 g_malloc (gsize n_bytes)
125 {
126   if (G_LIKELY (n_bytes))
127     {
128       gpointer mem;
129
130       mem = malloc (n_bytes);
131       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
132       if (mem)
133         return mem;
134
135       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
136                G_STRLOC, n_bytes);
137     }
138
139   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
140
141   return NULL;
142 }
143
144 /**
145  * g_malloc0:
146  * @n_bytes: the number of bytes to allocate
147  *
148  * Allocates @n_bytes bytes of memory, initialized to 0's.
149  * If @n_bytes is 0 it returns %NULL.
150  *
151  * If the allocation fails (because the system is out of memory),
152  * the program is terminated.
153  *
154  * Returns: a pointer to the allocated memory
155  */
156 gpointer
157 g_malloc0 (gsize n_bytes)
158 {
159   if (G_LIKELY (n_bytes))
160     {
161       gpointer mem;
162
163       mem = calloc (1, n_bytes);
164       TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
165       if (mem)
166         return mem;
167
168       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
169                G_STRLOC, n_bytes);
170     }
171
172   TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
173
174   return NULL;
175 }
176
177 /**
178  * g_realloc:
179  * @mem: (nullable): the memory to reallocate
180  * @n_bytes: new size of the memory in bytes
181  *
182  * Reallocates the memory pointed to by @mem, so that it now has space for
183  * @n_bytes bytes of memory. It returns the new address of the memory, which may
184  * have been moved. @mem may be %NULL, in which case it's considered to
185  * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
186  * and @mem will be freed unless it is %NULL.
187  *
188  * If the allocation fails (because the system is out of memory),
189  * the program is terminated.
190  *
191  * Returns: the new address of the allocated memory
192  */
193 gpointer
194 g_realloc (gpointer mem,
195            gsize    n_bytes)
196 {
197   gpointer newmem;
198
199   if (G_LIKELY (n_bytes))
200     {
201       newmem = realloc (mem, n_bytes);
202       TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
203       if (newmem)
204         return newmem;
205
206       g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
207                G_STRLOC, n_bytes);
208     }
209
210   free (mem);
211
212   TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
213
214   return NULL;
215 }
216
217 /**
218  * g_free:
219  * @mem: (nullable): the memory to free
220  * 
221  * Frees the memory pointed to by @mem.
222  *
223  * If @mem is %NULL it simply returns, so there is no need to check @mem
224  * against %NULL before calling this function.
225  */
226 void
227 g_free (gpointer mem)
228 {
229   free (mem);
230   TRACE(GLIB_MEM_FREE((void*) mem));
231 }
232
233 /**
234  * g_clear_pointer: (skip)
235  * @pp: (not nullable): a pointer to a variable, struct member etc. holding a
236  *    pointer
237  * @destroy: a function to which a gpointer can be passed, to destroy *@pp
238  *
239  * Clears a reference to a variable.
240  *
241  * @pp must not be %NULL.
242  *
243  * If the reference is %NULL then this function does nothing.
244  * Otherwise, the variable is destroyed using @destroy and the
245  * pointer is set to %NULL.
246  *
247  * A macro is also included that allows this function to be used without
248  * pointer casts. This will mask any warnings about incompatible function types
249  * or calling conventions, so you must ensure that your @destroy function is
250  * compatible with being called as `GDestroyNotify` using the standard calling
251  * convention for the platform that GLib was compiled for; otherwise the program
252  * will experience undefined behaviour.
253  *
254  * Since: 2.34
255  **/
256 #undef g_clear_pointer
257 void
258 g_clear_pointer (gpointer      *pp,
259                  GDestroyNotify destroy)
260 {
261   gpointer _p;
262
263   _p = *pp;
264   if (_p)
265     {
266       *pp = NULL;
267       destroy (_p);
268     }
269 }
270
271 /**
272  * g_try_malloc:
273  * @n_bytes: number of bytes to allocate.
274  * 
275  * Attempts to allocate @n_bytes, and returns %NULL on failure.
276  * Contrast with g_malloc(), which aborts the program on failure.
277  * 
278  * Returns: the allocated memory, or %NULL.
279  */
280 gpointer
281 g_try_malloc (gsize n_bytes)
282 {
283   gpointer mem;
284
285   if (G_LIKELY (n_bytes))
286     mem = malloc (n_bytes);
287   else
288     mem = NULL;
289
290   TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
291
292   return mem;
293 }
294
295 /**
296  * g_try_malloc0:
297  * @n_bytes: number of bytes to allocate
298  * 
299  * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
300  * failure. Contrast with g_malloc0(), which aborts the program on failure.
301  * 
302  * Since: 2.8
303  * Returns: the allocated memory, or %NULL
304  */
305 gpointer
306 g_try_malloc0 (gsize n_bytes)
307 {
308   gpointer mem;
309
310   if (G_LIKELY (n_bytes))
311     mem = calloc (1, n_bytes);
312   else
313     mem = NULL;
314
315   return mem;
316 }
317
318 /**
319  * g_try_realloc:
320  * @mem: (nullable): previously-allocated memory, or %NULL.
321  * @n_bytes: number of bytes to allocate.
322  * 
323  * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
324  * on failure. Contrast with g_realloc(), which aborts the program
325  * on failure.
326  *
327  * If @mem is %NULL, behaves the same as g_try_malloc().
328  * 
329  * Returns: the allocated memory, or %NULL.
330  */
331 gpointer
332 g_try_realloc (gpointer mem,
333                gsize    n_bytes)
334 {
335   gpointer newmem;
336
337   if (G_LIKELY (n_bytes))
338     newmem = realloc (mem, n_bytes);
339   else
340     {
341       newmem = NULL;
342       free (mem);
343     }
344
345   TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
346
347   return newmem;
348 }
349
350
351 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
352
353 /**
354  * g_malloc_n:
355  * @n_blocks: the number of blocks to allocate
356  * @n_block_bytes: the size of each block in bytes
357  *
358  * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
359  * but care is taken to detect possible overflow during multiplication.
360  *
361  * If the allocation fails (because the system is out of memory),
362  * the program is terminated.
363  *
364  * Since: 2.24
365  * Returns: a pointer to the allocated memory
366  */
367 gpointer
368 g_malloc_n (gsize n_blocks,
369             gsize n_block_bytes)
370 {
371   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
372     {
373       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
374                G_STRLOC, n_blocks, n_block_bytes);
375     }
376
377   return g_malloc (n_blocks * n_block_bytes);
378 }
379
380 /**
381  * g_malloc0_n:
382  * @n_blocks: the number of blocks to allocate
383  * @n_block_bytes: the size of each block in bytes
384  *
385  * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
386  * but care is taken to detect possible overflow during multiplication.
387  *
388  * If the allocation fails (because the system is out of memory),
389  * the program is terminated.
390  *
391  * Since: 2.24
392  * Returns: a pointer to the allocated memory
393  */
394 gpointer
395 g_malloc0_n (gsize n_blocks,
396              gsize n_block_bytes)
397 {
398   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
399     {
400       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
401                G_STRLOC, n_blocks, n_block_bytes);
402     }
403
404   return g_malloc0 (n_blocks * n_block_bytes);
405 }
406
407 /**
408  * g_realloc_n:
409  * @mem: (nullable): the memory to reallocate
410  * @n_blocks: the number of blocks to allocate
411  * @n_block_bytes: the size of each block in bytes
412  *
413  * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
414  * but care is taken to detect possible overflow during multiplication.
415  *
416  * If the allocation fails (because the system is out of memory),
417  * the program is terminated.
418  *
419  * Since: 2.24
420  * Returns: the new address of the allocated memory
421  */
422 gpointer
423 g_realloc_n (gpointer mem,
424              gsize    n_blocks,
425              gsize    n_block_bytes)
426 {
427   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
428     {
429       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
430                G_STRLOC, n_blocks, n_block_bytes);
431     }
432
433   return g_realloc (mem, n_blocks * n_block_bytes);
434 }
435
436 /**
437  * g_try_malloc_n:
438  * @n_blocks: the number of blocks to allocate
439  * @n_block_bytes: the size of each block in bytes
440  * 
441  * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
442  * but care is taken to detect possible overflow during multiplication.
443  * 
444  * Since: 2.24
445  * Returns: the allocated memory, or %NULL.
446  */
447 gpointer
448 g_try_malloc_n (gsize n_blocks,
449                 gsize n_block_bytes)
450 {
451   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
452     return NULL;
453
454   return g_try_malloc (n_blocks * n_block_bytes);
455 }
456
457 /**
458  * g_try_malloc0_n:
459  * @n_blocks: the number of blocks to allocate
460  * @n_block_bytes: the size of each block in bytes
461  * 
462  * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
463  * but care is taken to detect possible overflow during multiplication.
464  * 
465  * Since: 2.24
466  * Returns: the allocated memory, or %NULL
467  */
468 gpointer
469 g_try_malloc0_n (gsize n_blocks,
470                  gsize n_block_bytes)
471 {
472   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
473     return NULL;
474
475   return g_try_malloc0 (n_blocks * n_block_bytes);
476 }
477
478 /**
479  * g_try_realloc_n:
480  * @mem: (nullable): previously-allocated memory, or %NULL.
481  * @n_blocks: the number of blocks to allocate
482  * @n_block_bytes: the size of each block in bytes
483  * 
484  * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
485  * but care is taken to detect possible overflow during multiplication.
486  * 
487  * Since: 2.24
488  * Returns: the allocated memory, or %NULL.
489  */
490 gpointer
491 g_try_realloc_n (gpointer mem,
492                  gsize    n_blocks,
493                  gsize    n_block_bytes)
494 {
495   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
496     return NULL;
497
498   return g_try_realloc (mem, n_blocks * n_block_bytes);
499 }
500
501 /**
502  * g_mem_is_system_malloc:
503  * 
504  * Checks whether the allocator used by g_malloc() is the system's
505  * malloc implementation. If it returns %TRUE memory allocated with
506  * malloc() can be used interchangeably with memory allocated using g_malloc().
507  * This function is useful for avoiding an extra copy of allocated memory returned
508  * by a non-GLib-based API.
509  *
510  * Returns: if %TRUE, malloc() and g_malloc() can be mixed.
511  *
512  * Deprecated: 2.46: GLib always uses the system malloc, so this function always
513  * returns %TRUE.
514  **/
515 gboolean
516 g_mem_is_system_malloc (void)
517 {
518   return TRUE;
519 }
520
521 /**
522  * g_mem_set_vtable:
523  * @vtable: table of memory allocation routines.
524  * 
525  * This function used to let you override the memory allocation function.
526  * However, its use was incompatible with the use of global constructors
527  * in GLib and GIO, because those use the GLib allocators before main is
528  * reached. Therefore this function is now deprecated and is just a stub.
529  *
530  * Deprecated: 2.46: This function now does nothing. Use other memory
531  * profiling tools instead
532  */
533 void
534 g_mem_set_vtable (GMemVTable *vtable)
535 {
536   g_warning (G_STRLOC ": custom memory allocation vtable not supported");
537 }
538
539
540 /**
541  * glib_mem_profiler_table:
542  *
543  * Used to be a #GMemVTable containing profiling variants of the memory
544  * allocation functions, but this variable shouldn't be modified anymore.
545  *
546  * Deprecated: 2.46: Use other memory profiling tools instead
547  */
548 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
549
550 /**
551  * g_mem_profile:
552  *
553  * GLib used to support some tools for memory profiling, but this
554  * no longer works. There are many other useful tools for memory
555  * profiling these days which can be used instead.
556  *
557  * Deprecated: 2.46: Use other memory profiling tools instead
558  */
559 void
560 g_mem_profile (void)
561 {
562   g_warning (G_STRLOC ": memory profiling not supported");
563 }
564
565 /**
566  * g_aligned_alloc:
567  * @n_blocks: the number of blocks to allocate
568  * @n_block_bytes: the size of each block in bytes
569  * @alignment: the alignment to be enforced, which must be a positive power of 2
570  *   and a multiple of `sizeof(void*)`
571  *
572  * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes)
573  * bytes, but care is taken to align the allocated memory to with the given
574  * alignment value. Additionally, it will detect possible overflow during
575  * multiplication.
576  *
577  * If the allocation fails (because the system is out of memory),
578  * the program is terminated.
579  *
580  * Aligned memory allocations returned by this function can only be
581  * freed using g_aligned_free().
582  *
583  * Returns: (transfer full): the allocated memory
584  *
585  * Since: 2.72
586  */
587 gpointer
588 g_aligned_alloc (gsize n_blocks,
589                  gsize n_block_bytes,
590                  gsize alignment)
591 {
592   gpointer res = NULL;
593   gsize real_size;
594
595   if (G_UNLIKELY ((alignment == 0) || (alignment & (alignment - 1)) != 0))
596     {
597       g_error ("%s: alignment %"G_GSIZE_FORMAT" must be a positive power of two",
598                G_STRLOC, alignment);
599     }
600
601   if (G_UNLIKELY ((alignment % sizeof (void *)) != 0))
602     {
603       g_error ("%s: alignment %"G_GSIZE_FORMAT" must be a multiple of %"G_GSIZE_FORMAT,
604                G_STRLOC, alignment, sizeof (void *));
605     }
606
607   if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
608     {
609       g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
610                G_STRLOC, n_blocks, n_block_bytes);
611     }
612
613   real_size = n_blocks * n_block_bytes;
614
615   if (G_UNLIKELY (real_size == 0))
616     {
617       TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) real_size, 0, 0));
618       return NULL;
619     }
620
621   /* We need to clear errno because posix_memalign() will use its return
622    * value in the same way memalign() and aligned_alloc() will set errno.
623    * Additionally, posix_memalign() will warn if its return value is left
624    * unassigned.
625    *
626    * We handle all possible return values (ENOMEM and EINVAL) with either
627    * precondition or postcondition checking.
628    */
629   errno = 0;
630
631 #if defined(HAVE_POSIX_MEMALIGN)
632   errno = posix_memalign (&res, alignment, real_size);
633 #elif defined(HAVE_ALIGNED_ALLOC) || defined(HAVE__ALIGNED_MALLOC)
634   /* real_size must be a multiple of alignment */
635   if (real_size % alignment != 0)
636     {
637       gsize offset = real_size % alignment;
638
639       if (G_MAXSIZE - real_size < (alignment - offset))
640         {
641           g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"+%"G_GSIZE_FORMAT" bytes",
642                    G_STRLOC, real_size, (alignment - offset));
643         }
644
645       real_size += (alignment - offset);
646     }
647
648   res = aligned_alloc (alignment, real_size);
649 #elif defined(HAVE_MEMALIGN)
650   res = memalign (alignment, real_size);
651 #else
652 # error "This platform does not have an aligned memory allocator."
653 #endif
654
655   TRACE (GLIB_MEM_ALLOC((void*) res, (unsigned int) real_size, 0, 0));
656   if (res)
657     return res;
658
659   g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
660            G_STRLOC, real_size);
661
662   return NULL;
663 }
664
665 /**
666  * g_aligned_alloc0:
667  * @n_blocks: the number of blocks to allocate
668  * @n_block_bytes: the size of each block in bytes
669  * @alignment: the alignment to be enforced, which must be a positive power of 2
670  *   and a multiple of `sizeof(void*)`
671  *
672  * This function is similar to g_aligned_alloc(), but it will
673  * also clear the allocated memory before returning it.
674  *
675  * Returns: (transfer full): the allocated, cleared memory
676  *
677  * Since: 2.72
678  */
679 gpointer
680 g_aligned_alloc0 (gsize n_blocks,
681                   gsize n_block_bytes,
682                   gsize alignment)
683 {
684   gpointer res = g_aligned_alloc (n_blocks, n_block_bytes, alignment);
685
686   if (G_LIKELY (res != NULL))
687     memset (res, 0, n_blocks * n_block_bytes);
688
689   return res;
690 }
691
692 /**
693  * g_aligned_free:
694  * @mem: (nullable): the memory to deallocate
695  *
696  * Frees the memory allocated by g_aligned_alloc().
697  *
698  * Since: 2.72
699  */
700 void
701 g_aligned_free (gpointer mem)
702 {
703   aligned_free (mem);
704 }