1 /* grcbox.c: Reference counted data
3 * Copyright 2018 Emmanuele Bassi
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
23 #include "grcboxprivate.h"
25 #include "gmessages.h"
26 #include "grefcount.h"
27 #include "gtestutils.h"
29 #ifdef ENABLE_VALGRIND
33 #include "glib_trace.h"
39 * @Title: Reference counted data
40 * @Short_description: Allocated memory with reference counting semantics
42 * A "reference counted box", or "RcBox", is an opaque wrapper data type
43 * that is guaranteed to be as big as the size of a given data type, and
44 * which augments the given data type with reference counting semantics
45 * for its memory management.
47 * RcBox is useful if you have a plain old data type, like a structure
48 * typically placed on the stack, and you wish to provide additional API
49 * to use it on the heap; or if you want to implement a new type to be
50 * passed around by reference without necessarily implementing copy/free
51 * semantics or your own reference counting.
55 * |[<!-- language="C" -->
67 * return g_rc_box_new0 (Person);
71 * Every time you wish to acquire a reference on the memory, you should
72 * call g_rc_box_acquire(); similarly, when you wish to release a reference
73 * you should call g_rc_box_release():
75 * |[<!-- language="C" -->
76 * // Add a Person to the Database; the Database acquires ownership
77 * // of the Person instance
79 * add_person_to_database (Database *db, Person *p)
81 * db->persons = g_list_prepend (db->persons, g_rc_box_acquire (p));
84 * // Removes a Person from the Database; the reference acquired by
85 * // add_person_to_database() is released here
87 * remove_person_from_database (Database *db, Person *p)
89 * db->persons = g_list_remove (db->persons, p);
90 * g_rc_box_release (p);
94 * If you have additional memory allocated inside the structure, you can
95 * use g_rc_box_release_full(), which takes a function pointer, which
96 * will be called if the reference released was the last:
98 * |[<!-- language="C" -->
100 * person_clear (Person *p)
103 * g_free (p->address);
109 * remove_person_from_database (Database *db, Person *p)
111 * db->persons = g_list_remove (db->persons, p);
112 * g_rc_box_release_full (p, (GDestroyNotify) person_clear);
116 * If you wish to transfer the ownership of a reference counted data
117 * type without increasing the reference count, you can use g_steal_pointer():
119 * |[<!-- language="C" -->
120 * Person *p = g_rc_box_new (Person);
122 * // fill_person_details() is defined elsewhere
123 * fill_person_details (p);
125 * // add_person_to_database_no_ref() is defined elsewhere; it adds
126 * // a Person to the Database without taking a reference
127 * add_person_to_database_no_ref (db, g_steal_pointer (&p));
132 * The reference counting operations on data allocated using g_rc_box_alloc(),
133 * g_rc_box_new(), and g_rc_box_dup() are not thread safe; it is your code's
134 * responsibility to ensure that references are acquired are released on the
137 * If you need thread safe reference counting, see the [atomic reference counted
140 * ## Automatic pointer clean up
142 * If you want to add g_autoptr() support to your plain old data type through
143 * reference counting, you can use the G_DEFINE_AUTOPTR_CLEANUP_FUNC() and
144 * g_rc_box_release():
146 * |[<!-- language="C" -->
147 * G_DEFINE_AUTOPTR_CLEANUP_FUNC (MyDataStruct, g_rc_box_release)
150 * If you need to clear the contents of the data, you will need to use an
151 * ancillary function that calls g_rc_box_release_full():
153 * |[<!-- language="C" -->
155 * my_data_struct_release (MyDataStruct *data)
157 * // my_data_struct_clear() is defined elsewhere
158 * g_rc_box_release_full (data, (GDestroyNotify) my_data_struct_clear);
161 * G_DEFINE_AUTOPTR_CLEANUP_FUNC (MyDataStruct, my_data_struct_release)
167 /* We use the same alignment as GTypeInstance and GNU libc's malloc */
168 #define ALIGN_STRUCT(offset) ((offset + (STRUCT_ALIGNMENT - 1)) & -STRUCT_ALIGNMENT)
170 #define G_RC_BOX(p) (GRcBox *) (((char *) (p)) - G_RC_BOX_SIZE)
173 g_rc_box_alloc_full (gsize block_size,
178 /* We don't do an (atomic ? G_ARC_BOX_SIZE : G_RC_BOX_SIZE) check, here
179 * because we have a static assertion that sizeof(GArcBox) == sizeof(GRcBox)
180 * inside grcboxprivate.h, and we don't want the compiler to unnecessarily
181 * warn about both branches of the conditional yielding identical results
183 gsize private_size = G_ARC_BOX_SIZE;
184 gsize private_offset = 0;
188 g_assert (alignment != 0);
190 /* We need to ensure that the private data is aligned */
191 if (private_size % alignment != 0)
193 private_offset = private_size % alignment;
194 private_size += (alignment - private_offset);
197 g_assert (block_size < (G_MAXSIZE - private_size));
198 real_size = private_size + block_size;
200 /* The real allocated size must be a multiple of @alignment, to
201 * maintain the alignment of block_size
203 if (real_size % alignment != 0)
205 gsize offset = real_size % alignment;
206 g_assert (real_size < (G_MAXSIZE - (alignment - offset)));
207 real_size += (alignment - offset);
210 #ifdef ENABLE_VALGRIND
211 if (RUNNING_ON_VALGRIND)
213 /* When running under Valgrind we massage the memory allocation
214 * to include a pointer at the tail end of the block; the pointer
215 * is then set to the start of the block. This trick allows
216 * Valgrind to keep track of the over-allocation and not be
217 * confused when passing the pointer around
219 g_assert (private_size < (G_MAXSIZE - ALIGN_STRUCT (1)));
220 private_size += ALIGN_STRUCT (1);
223 allocated = g_malloc0 (real_size + sizeof (gpointer));
225 allocated = g_malloc (real_size + sizeof (gpointer));
227 *(gpointer *) (allocated + private_size + block_size) = allocated + ALIGN_STRUCT (1);
229 VALGRIND_MALLOCLIKE_BLOCK (allocated + private_size, block_size + sizeof (gpointer), 0, TRUE);
230 VALGRIND_MALLOCLIKE_BLOCK (allocated + ALIGN_STRUCT (1), private_size - ALIGN_STRUCT (1), 0, TRUE);
233 #endif /* ENABLE_VALGRIND */
236 allocated = g_malloc0 (real_size);
238 allocated = g_malloc (real_size);
243 /* We leave the alignment padding at the top of the allocation,
244 * so we have an in memory layout of:
246 * |[ offset ][ sizeof(GArcBox) ]||[ block_size ]|
248 GArcBox *real_box = (GArcBox *) (allocated + private_offset);
249 /* Store the real size */
250 real_box->mem_size = block_size;
251 /* Store the alignment offset, to be used when freeing the
254 real_box->private_offset = private_offset;
255 #ifndef G_DISABLE_ASSERT
256 real_box->magic = G_BOX_MAGIC;
258 g_atomic_ref_count_init (&real_box->ref_count);
262 /* We leave the alignment padding at the top of the allocation,
263 * so we have an in memory layout of:
265 * |[ offset ][ sizeof(GRcBox) ]||[ block_size ]|
267 GRcBox *real_box = (GRcBox *) (allocated + private_offset);
268 /* Store the real size */
269 real_box->mem_size = block_size;
270 /* Store the alignment offset, to be used when freeing the
273 real_box->private_offset = private_offset;
274 #ifndef G_DISABLE_ASSERT
275 real_box->magic = G_BOX_MAGIC;
277 g_ref_count_init (&real_box->ref_count);
280 TRACE (GLIB_RCBOX_ALLOC (allocated, block_size, atomic, clear));
282 return allocated + private_size;
287 * @block_size: the size of the allocation, must be greater than 0
289 * Allocates @block_size bytes of memory, and adds reference
290 * counting semantics to it.
292 * The data will be freed when its reference count drops to
295 * The allocated data is guaranteed to be suitably aligned for any
298 * Returns: (transfer full) (not nullable): a pointer to the allocated memory
303 g_rc_box_alloc (gsize block_size)
305 g_return_val_if_fail (block_size > 0, NULL);
307 return g_rc_box_alloc_full (block_size, STRUCT_ALIGNMENT, FALSE, FALSE);
312 * @block_size: the size of the allocation, must be greater than 0
314 * Allocates @block_size bytes of memory, and adds reference
315 * counting semantics to it.
317 * The contents of the returned data is set to zero.
319 * The data will be freed when its reference count drops to
322 * The allocated data is guaranteed to be suitably aligned for any
325 * Returns: (transfer full) (not nullable): a pointer to the allocated memory
330 g_rc_box_alloc0 (gsize block_size)
332 g_return_val_if_fail (block_size > 0, NULL);
334 return g_rc_box_alloc_full (block_size, STRUCT_ALIGNMENT, FALSE, TRUE);
339 * @type: the type to allocate, typically a structure name
341 * A convenience macro to allocate reference counted data with
342 * the size of the given @type.
344 * This macro calls g_rc_box_alloc() with `sizeof (@type)` and
345 * casts the returned pointer to a pointer of the given @type,
346 * avoiding a type cast in the source code.
348 * Returns: (transfer full) (not nullable): a pointer to the
349 * allocated memory, cast to a pointer for the given @type
356 * @type: the type to allocate, typically a structure name
358 * A convenience macro to allocate reference counted data with
359 * the size of the given @type, and set its contents to zero.
361 * This macro calls g_rc_box_alloc0() with `sizeof (@type)` and
362 * casts the returned pointer to a pointer of the given @type,
363 * avoiding a type cast in the source code.
365 * Returns: (transfer full) (not nullable): a pointer to the
366 * allocated memory, cast to a pointer for the given @type
373 * @block_size: the number of bytes to copy, must be greater than 0
374 * @mem_block: (not nullable): the memory to copy
376 * Allocates a new block of data with reference counting
377 * semantics, and copies @block_size bytes of @mem_block
380 * Returns: (transfer full) (not nullable): a pointer to the allocated
386 (g_rc_box_dup) (gsize block_size,
387 gconstpointer mem_block)
391 g_return_val_if_fail (block_size > 0, NULL);
392 g_return_val_if_fail (mem_block != NULL, NULL);
394 res = g_rc_box_alloc_full (block_size, STRUCT_ALIGNMENT, FALSE, FALSE);
395 memcpy (res, mem_block, block_size);
402 * @mem_block: (not nullable): a pointer to reference counted data
404 * Acquires a reference on the data pointed by @mem_block.
406 * Returns: (transfer full) (not nullable): a pointer to the data,
407 * with its reference count increased
412 (g_rc_box_acquire) (gpointer mem_block)
414 GRcBox *real_box = G_RC_BOX (mem_block);
416 g_return_val_if_fail (mem_block != NULL, NULL);
417 #ifndef G_DISABLE_ASSERT
418 g_return_val_if_fail (real_box->magic == G_BOX_MAGIC, NULL);
421 g_ref_count_inc (&real_box->ref_count);
423 TRACE (GLIB_RCBOX_ACQUIRE (mem_block, 0));
430 * @mem_block: (transfer full) (not nullable): a pointer to reference counted data
432 * Releases a reference on the data pointed by @mem_block.
434 * If the reference was the last one, it will free the
435 * resources allocated for @mem_block.
440 g_rc_box_release (gpointer mem_block)
442 g_rc_box_release_full (mem_block, NULL);
446 * g_rc_box_release_full:
447 * @mem_block: (transfer full) (not nullable): a pointer to reference counted data
448 * @clear_func: (not nullable): a function to call when clearing the data
450 * Releases a reference on the data pointed by @mem_block.
452 * If the reference was the last one, it will call @clear_func
453 * to clear the contents of @mem_block, and then will free the
454 * resources allocated for @mem_block.
459 g_rc_box_release_full (gpointer mem_block,
460 GDestroyNotify clear_func)
462 GRcBox *real_box = G_RC_BOX (mem_block);
464 g_return_if_fail (mem_block != NULL);
465 #ifndef G_DISABLE_ASSERT
466 g_return_if_fail (real_box->magic == G_BOX_MAGIC);
469 if (g_ref_count_dec (&real_box->ref_count))
471 char *real_mem = (char *) real_box - real_box->private_offset;
473 TRACE (GLIB_RCBOX_RELEASE (mem_block, 0));
475 if (clear_func != NULL)
476 clear_func (mem_block);
478 TRACE (GLIB_RCBOX_FREE (mem_block));
485 * @mem_block: (not nullable): a pointer to reference counted data
487 * Retrieves the size of the reference counted data pointed by @mem_block.
489 * Returns: the size of the data, in bytes
494 g_rc_box_get_size (gpointer mem_block)
496 GRcBox *real_box = G_RC_BOX (mem_block);
498 g_return_val_if_fail (mem_block != NULL, 0);
499 #ifndef G_DISABLE_ASSERT
500 g_return_val_if_fail (real_box->magic == G_BOX_MAGIC, 0);
503 return real_box->mem_size;