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.1 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 #ifndef __G_MEM_H__
26 #define __G_MEM_H__
27 
28 #if !defined (__GLIB_H_INSIDE__) && !defined (GLIB_COMPILATION)
29 #error "Only <glib.h> can be included directly."
30 #endif
31 
32 #include <glib/gutils.h>
33 #include <glib/glib-typeof.h>
34 
35 G_BEGIN_DECLS
36 
37 /**
38  * GMemVTable:
39  * @malloc: function to use for allocating memory.
40  * @realloc: function to use for reallocating memory.
41  * @free: function to use to free memory.
42  * @calloc: function to use for allocating zero-filled memory.
43  * @try_malloc: function to use for allocating memory without a default error handler.
44  * @try_realloc: function to use for reallocating memory without a default error handler.
45  *
46  * A set of functions used to perform memory allocation. The same #GMemVTable must
47  * be used for all allocations in the same program; a call to g_mem_set_vtable(),
48  * if it exists, should be prior to any use of GLib.
49  *
50  * This functions related to this has been deprecated in 2.46, and no longer work.
51  */
52 typedef struct _GMemVTable GMemVTable;
53 
54 
55 #if GLIB_SIZEOF_VOID_P > GLIB_SIZEOF_LONG
56 /**
57  * G_MEM_ALIGN:
58  *
59  * Indicates the number of bytes to which memory will be aligned on the
60  * current platform.
61  */
62 #  define G_MEM_ALIGN	GLIB_SIZEOF_VOID_P
63 #else	/* GLIB_SIZEOF_VOID_P <= GLIB_SIZEOF_LONG */
64 #  define G_MEM_ALIGN	GLIB_SIZEOF_LONG
65 #endif	/* GLIB_SIZEOF_VOID_P <= GLIB_SIZEOF_LONG */
66 
67 
68 /* Memory allocation functions
69  */
70 
71 GLIB_AVAILABLE_IN_ALL
72 void	 g_free	          (gpointer	 mem);
73 
74 GLIB_AVAILABLE_IN_2_34
75 void     g_clear_pointer  (gpointer      *pp,
76                            GDestroyNotify destroy);
77 
78 GLIB_AVAILABLE_IN_ALL
79 gpointer g_malloc         (gsize	 n_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1);
80 GLIB_AVAILABLE_IN_ALL
81 gpointer g_malloc0        (gsize	 n_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1);
82 GLIB_AVAILABLE_IN_ALL
83 gpointer g_realloc        (gpointer	 mem,
84 			   gsize	 n_bytes) G_GNUC_WARN_UNUSED_RESULT;
85 GLIB_AVAILABLE_IN_ALL
86 gpointer g_try_malloc     (gsize	 n_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1);
87 GLIB_AVAILABLE_IN_ALL
88 gpointer g_try_malloc0    (gsize	 n_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1);
89 GLIB_AVAILABLE_IN_ALL
90 gpointer g_try_realloc    (gpointer	 mem,
91 			   gsize	 n_bytes) G_GNUC_WARN_UNUSED_RESULT;
92 
93 GLIB_AVAILABLE_IN_ALL
94 gpointer g_malloc_n       (gsize	 n_blocks,
95 			   gsize	 n_block_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE2(1,2);
96 GLIB_AVAILABLE_IN_ALL
97 gpointer g_malloc0_n      (gsize	 n_blocks,
98 			   gsize	 n_block_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE2(1,2);
99 GLIB_AVAILABLE_IN_ALL
100 gpointer g_realloc_n      (gpointer	 mem,
101 			   gsize	 n_blocks,
102 			   gsize	 n_block_bytes) G_GNUC_WARN_UNUSED_RESULT;
103 GLIB_AVAILABLE_IN_ALL
104 gpointer g_try_malloc_n   (gsize	 n_blocks,
105 			   gsize	 n_block_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE2(1,2);
106 GLIB_AVAILABLE_IN_ALL
107 gpointer g_try_malloc0_n  (gsize	 n_blocks,
108 			   gsize	 n_block_bytes) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE2(1,2);
109 GLIB_AVAILABLE_IN_ALL
110 gpointer g_try_realloc_n  (gpointer	 mem,
111 			   gsize	 n_blocks,
112 			   gsize	 n_block_bytes) G_GNUC_WARN_UNUSED_RESULT;
113 
114 #if defined(glib_typeof) && GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_58
115 #define g_clear_pointer(pp, destroy)                     \
116   G_STMT_START                                           \
117   {                                                      \
118     G_STATIC_ASSERT (sizeof *(pp) == sizeof (gpointer)); \
119     glib_typeof ((pp)) _pp = (pp);                       \
120     glib_typeof (*(pp)) _ptr = *_pp;                     \
121     *_pp = NULL;                                         \
122     if (_ptr)                                            \
123       (destroy) (_ptr);                                  \
124   }                                                      \
125   G_STMT_END                                             \
126   GLIB_AVAILABLE_MACRO_IN_2_34
127 #else /* __GNUC__ */
128 #define g_clear_pointer(pp, destroy) \
129   G_STMT_START {                                                               \
130     G_STATIC_ASSERT (sizeof *(pp) == sizeof (gpointer));                       \
131     /* Only one access, please; work around type aliasing */                   \
132     union { char *in; gpointer *out; } _pp;                                    \
133     gpointer _p;                                                               \
134     /* This assignment is needed to avoid a gcc warning */                     \
135     GDestroyNotify _destroy = (GDestroyNotify) (destroy);                      \
136                                                                                \
137     _pp.in = (char *) (pp);                                                    \
138     _p = *_pp.out;                                                             \
139     if (_p) 								       \
140       { 								       \
141         *_pp.out = NULL;                                                       \
142         _destroy (_p);                                                         \
143       }                                                                        \
144   } G_STMT_END                                                                 \
145   GLIB_AVAILABLE_MACRO_IN_2_34
146 #endif /* __GNUC__ */
147 
148 /**
149  * g_steal_pointer:
150  * @pp: (not nullable): a pointer to a pointer
151  *
152  * Sets @pp to %NULL, returning the value that was there before.
153  *
154  * Conceptually, this transfers the ownership of the pointer from the
155  * referenced variable to the "caller" of the macro (ie: "steals" the
156  * reference).
157  *
158  * The return value will be properly typed, according to the type of
159  * @pp.
160  *
161  * This can be very useful when combined with g_autoptr() to prevent the
162  * return value of a function from being automatically freed.  Consider
163  * the following example (which only works on GCC and clang):
164  *
165  * |[
166  * GObject *
167  * create_object (void)
168  * {
169  *   g_autoptr(GObject) obj = g_object_new (G_TYPE_OBJECT, NULL);
170  *
171  *   if (early_error_case)
172  *     return NULL;
173  *
174  *   return g_steal_pointer (&obj);
175  * }
176  * ]|
177  *
178  * It can also be used in similar ways for 'out' parameters and is
179  * particularly useful for dealing with optional out parameters:
180  *
181  * |[
182  * gboolean
183  * get_object (GObject **obj_out)
184  * {
185  *   g_autoptr(GObject) obj = g_object_new (G_TYPE_OBJECT, NULL);
186  *
187  *   if (early_error_case)
188  *     return FALSE;
189  *
190  *   if (obj_out)
191  *     *obj_out = g_steal_pointer (&obj);
192  *
193  *   return TRUE;
194  * }
195  * ]|
196  *
197  * In the above example, the object will be automatically freed in the
198  * early error case and also in the case that %NULL was given for
199  * @obj_out.
200  *
201  * Since: 2.44
202  */
203 GLIB_AVAILABLE_STATIC_INLINE_IN_2_44
204 static inline gpointer
g_steal_pointer(gpointer pp)205 g_steal_pointer (gpointer pp)
206 {
207   gpointer *ptr = (gpointer *) pp;
208   gpointer ref;
209 
210   ref = *ptr;
211   *ptr = NULL;
212 
213   return ref;
214 }
215 
216 /* type safety */
217 #if defined(glib_typeof) && GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_58
218 #define g_steal_pointer(pp) ((glib_typeof (*pp)) (g_steal_pointer) (pp))
219 #else  /* __GNUC__ */
220 /* This version does not depend on gcc extensions, but gcc does not warn
221  * about incompatible-pointer-types: */
222 #define g_steal_pointer(pp) \
223   (0 ? (*(pp)) : (g_steal_pointer) (pp))
224 #endif /* __GNUC__ */
225 
226 /* Optimise: avoid the call to the (slower) _n function if we can
227  * determine at compile-time that no overflow happens.
228  */
229 #if defined (__GNUC__) && (__GNUC__ >= 2) && defined (__OPTIMIZE__)
230 #  define _G_NEW(struct_type, n_structs, func) \
231 	(struct_type *) (G_GNUC_EXTENSION ({			\
232 	  gsize __n = (gsize) (n_structs);			\
233 	  gsize __s = sizeof (struct_type);			\
234 	  gpointer __p;						\
235 	  if (__s == 1)						\
236 	    __p = g_##func (__n);				\
237 	  else if (__builtin_constant_p (__n) &&		\
238 	           (__s == 0 || __n <= G_MAXSIZE / __s))	\
239 	    __p = g_##func (__n * __s);				\
240 	  else							\
241 	    __p = g_##func##_n (__n, __s);			\
242 	  __p;							\
243 	}))
244 #  define _G_RENEW(struct_type, mem, n_structs, func) \
245 	(struct_type *) (G_GNUC_EXTENSION ({			\
246 	  gsize __n = (gsize) (n_structs);			\
247 	  gsize __s = sizeof (struct_type);			\
248 	  gpointer __p = (gpointer) (mem);			\
249 	  if (__s == 1)						\
250 	    __p = g_##func (__p, __n);				\
251 	  else if (__builtin_constant_p (__n) &&		\
252 	           (__s == 0 || __n <= G_MAXSIZE / __s))	\
253 	    __p = g_##func (__p, __n * __s);			\
254 	  else							\
255 	    __p = g_##func##_n (__p, __n, __s);			\
256 	  __p;							\
257 	}))
258 
259 #else
260 
261 /* Unoptimised version: always call the _n() function. */
262 
263 #define _G_NEW(struct_type, n_structs, func) \
264         ((struct_type *) g_##func##_n ((n_structs), sizeof (struct_type)))
265 #define _G_RENEW(struct_type, mem, n_structs, func) \
266         ((struct_type *) g_##func##_n (mem, (n_structs), sizeof (struct_type)))
267 
268 #endif
269 
270 /**
271  * g_new:
272  * @struct_type: the type of the elements to allocate
273  * @n_structs: the number of elements to allocate
274  *
275  * Allocates @n_structs elements of type @struct_type.
276  * The returned pointer is cast to a pointer to the given type.
277  * If @n_structs is 0 it returns %NULL.
278  * Care is taken to avoid overflow when calculating the size of the allocated block.
279  *
280  * Since the returned pointer is already casted to the right type,
281  * it is normally unnecessary to cast it explicitly, and doing
282  * so might hide memory allocation errors.
283  *
284  * Returns: a pointer to the allocated memory, cast to a pointer to @struct_type
285  */
286 #define g_new(struct_type, n_structs)			_G_NEW (struct_type, n_structs, malloc)
287 /**
288  * g_new0:
289  * @struct_type: the type of the elements to allocate.
290  * @n_structs: the number of elements to allocate.
291  *
292  * Allocates @n_structs elements of type @struct_type, initialized to 0's.
293  * The returned pointer is cast to a pointer to the given type.
294  * If @n_structs is 0 it returns %NULL.
295  * Care is taken to avoid overflow when calculating the size of the allocated block.
296  *
297  * Since the returned pointer is already casted to the right type,
298  * it is normally unnecessary to cast it explicitly, and doing
299  * so might hide memory allocation errors.
300  *
301  * Returns: a pointer to the allocated memory, cast to a pointer to @struct_type.
302  */
303 #define g_new0(struct_type, n_structs)			_G_NEW (struct_type, n_structs, malloc0)
304 /**
305  * g_renew:
306  * @struct_type: the type of the elements to allocate
307  * @mem: the currently allocated memory
308  * @n_structs: the number of elements to allocate
309  *
310  * Reallocates the memory pointed to by @mem, so that it now has space for
311  * @n_structs elements of type @struct_type. It returns the new address of
312  * the memory, which may have been moved.
313  * Care is taken to avoid overflow when calculating the size of the allocated block.
314  *
315  * Returns: a pointer to the new allocated memory, cast to a pointer to @struct_type
316  */
317 #define g_renew(struct_type, mem, n_structs)		_G_RENEW (struct_type, mem, n_structs, realloc)
318 /**
319  * g_try_new:
320  * @struct_type: the type of the elements to allocate
321  * @n_structs: the number of elements to allocate
322  *
323  * Attempts to allocate @n_structs elements of type @struct_type, and returns
324  * %NULL on failure. Contrast with g_new(), which aborts the program on failure.
325  * The returned pointer is cast to a pointer to the given type.
326  * The function returns %NULL when @n_structs is 0 of if an overflow occurs.
327  *
328  * Since: 2.8
329  * Returns: a pointer to the allocated memory, cast to a pointer to @struct_type
330  */
331 #define g_try_new(struct_type, n_structs)		_G_NEW (struct_type, n_structs, try_malloc)
332 /**
333  * g_try_new0:
334  * @struct_type: the type of the elements to allocate
335  * @n_structs: the number of elements to allocate
336  *
337  * Attempts to allocate @n_structs elements of type @struct_type, initialized
338  * to 0's, and returns %NULL on failure. Contrast with g_new0(), which aborts
339  * the program on failure.
340  * The returned pointer is cast to a pointer to the given type.
341  * The function returns %NULL when @n_structs is 0 or if an overflow occurs.
342  *
343  * Since: 2.8
344  * Returns: a pointer to the allocated memory, cast to a pointer to @struct_type
345  */
346 #define g_try_new0(struct_type, n_structs)		_G_NEW (struct_type, n_structs, try_malloc0)
347 /**
348  * g_try_renew:
349  * @struct_type: the type of the elements to allocate
350  * @mem: the currently allocated memory
351  * @n_structs: the number of elements to allocate
352  *
353  * Attempts to reallocate the memory pointed to by @mem, so that it now has
354  * space for @n_structs elements of type @struct_type, and returns %NULL on
355  * failure. Contrast with g_renew(), which aborts the program on failure.
356  * It returns the new address of the memory, which may have been moved.
357  * The function returns %NULL if an overflow occurs.
358  *
359  * Since: 2.8
360  * Returns: a pointer to the new allocated memory, cast to a pointer to @struct_type
361  */
362 #define g_try_renew(struct_type, mem, n_structs)	_G_RENEW (struct_type, mem, n_structs, try_realloc)
363 
364 
365 /* Memory allocation virtualization for debugging purposes
366  * g_mem_set_vtable() has to be the very first GLib function called
367  * if being used
368  */
369 struct _GMemVTable {
370   gpointer (*malloc)      (gsize    n_bytes);
371   gpointer (*realloc)     (gpointer mem,
372 			   gsize    n_bytes);
373   void     (*free)        (gpointer mem);
374   /* optional; set to NULL if not used ! */
375   gpointer (*calloc)      (gsize    n_blocks,
376 			   gsize    n_block_bytes);
377   gpointer (*try_malloc)  (gsize    n_bytes);
378   gpointer (*try_realloc) (gpointer mem,
379 			   gsize    n_bytes);
380 };
381 GLIB_DEPRECATED_IN_2_46
382 void	 g_mem_set_vtable (GMemVTable	*vtable);
383 GLIB_DEPRECATED_IN_2_46
384 gboolean g_mem_is_system_malloc (void);
385 
386 GLIB_VAR gboolean g_mem_gc_friendly;
387 
388 /* Memory profiler and checker, has to be enabled via g_mem_set_vtable()
389  */
390 GLIB_VAR GMemVTable	*glib_mem_profiler_table;
391 GLIB_DEPRECATED_IN_2_46
392 void	g_mem_profile	(void);
393 
394 G_END_DECLS
395 
396 #endif /* __G_MEM_H__ */
397