Coverage Report

Created: 2025-07-18 06:26

/src/glib/glib/grcbox.c
Line
Count
Source (jump to first uncovered line)
1
/* grcbox.c: Reference counted data
2
 *
3
 * Copyright 2018  Emmanuele Bassi
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
#include "config.h"
20
21
#include "grcboxprivate.h"
22
23
#include "gmessages.h"
24
#include "grefcount.h"
25
#include "gtestutils.h"
26
27
#ifdef ENABLE_VALGRIND
28
#include "valgrind.h"
29
#endif
30
31
#include "glib_trace.h"
32
33
#include <string.h>
34
35
/**
36
 * SECTION:rcbox
37
 * @Title: Reference counted data
38
 * @Short_description: Allocated memory with reference counting semantics
39
 *
40
 * A "reference counted box", or "RcBox", is an opaque wrapper data type
41
 * that is guaranteed to be as big as the size of a given data type, and
42
 * which augments the given data type with reference counting semantics
43
 * for its memory management.
44
 *
45
 * RcBox is useful if you have a plain old data type, like a structure
46
 * typically placed on the stack, and you wish to provide additional API
47
 * to use it on the heap; or if you want to implement a new type to be
48
 * passed around by reference without necessarily implementing copy/free
49
 * semantics or your own reference counting.
50
 *
51
 * The typical use is:
52
 *
53
 * |[<!-- language="C" -->
54
 * typedef struct {
55
 *   char *name;
56
 *   char *address;
57
 *   char *city;
58
 *   char *state;
59
 *   int age;
60
 * } Person;
61
 *
62
 * Person *
63
 * person_new (void)
64
 * {
65
 *   return g_rc_box_new0 (Person);
66
 * }
67
 * ]|
68
 *
69
 * Every time you wish to acquire a reference on the memory, you should
70
 * call g_rc_box_acquire(); similarly, when you wish to release a reference
71
 * you should call g_rc_box_release():
72
 *
73
 * |[<!-- language="C" -->
74
 * // Add a Person to the Database; the Database acquires ownership
75
 * // of the Person instance
76
 * void
77
 * add_person_to_database (Database *db, Person *p)
78
 * {
79
 *   db->persons = g_list_prepend (db->persons, g_rc_box_acquire (p));
80
 * }
81
 *
82
 * // Removes a Person from the Database; the reference acquired by
83
 * // add_person_to_database() is released here
84
 * void
85
 * remove_person_from_database (Database *db, Person *p)
86
 * {
87
 *   db->persons = g_list_remove (db->persons, p);
88
 *   g_rc_box_release (p);
89
 * }
90
 * ]|
91
 *
92
 * If you have additional memory allocated inside the structure, you can
93
 * use g_rc_box_release_full(), which takes a function pointer, which
94
 * will be called if the reference released was the last:
95
 *
96
 * |[<!-- language="C" -->
97
 * void
98
 * person_clear (Person *p)
99
 * {
100
 *   g_free (p->name);
101
 *   g_free (p->address);
102
 *   g_free (p->city);
103
 *   g_free (p->state);
104
 * }
105
 *
106
 * void
107
 * remove_person_from_database (Database *db, Person *p)
108
 * {
109
 *   db->persons = g_list_remove (db->persons, p);
110
 *   g_rc_box_release_full (p, (GDestroyNotify) person_clear);
111
 * }
112
 * ]|
113
 *
114
 * If you wish to transfer the ownership of a reference counted data
115
 * type without increasing the reference count, you can use g_steal_pointer():
116
 *
117
 * |[<!-- language="C" -->
118
 *   Person *p = g_rc_box_new (Person);
119
 *
120
 *   // fill_person_details() is defined elsewhere
121
 *   fill_person_details (p);
122
 *
123
 *   // add_person_to_database_no_ref() is defined elsewhere; it adds
124
 *   // a Person to the Database without taking a reference
125
 *   add_person_to_database_no_ref (db, g_steal_pointer (&p));
126
 * ]|
127
 *
128
 * ## Thread safety
129
 *
130
 * The reference counting operations on data allocated using g_rc_box_alloc(),
131
 * g_rc_box_new(), and g_rc_box_dup() are not thread safe; it is your code's
132
 * responsibility to ensure that references are acquired are released on the
133
 * same thread.
134
 *
135
 * If you need thread safe reference counting, see the [atomic reference counted
136
 * data][arcbox] API.
137
 *
138
 * ## Automatic pointer clean up
139
 *
140
 * If you want to add g_autoptr() support to your plain old data type through
141
 * reference counting, you can use the G_DEFINE_AUTOPTR_CLEANUP_FUNC() and
142
 * g_rc_box_release():
143
 *
144
 * |[<!-- language="C" -->
145
 * G_DEFINE_AUTOPTR_CLEANUP_FUNC (MyDataStruct, g_rc_box_release)
146
 * ]|
147
 *
148
 * If you need to clear the contents of the data, you will need to use an
149
 * ancillary function that calls g_rc_box_release_full():
150
 *
151
 * |[<!-- language="C" -->
152
 * static void
153
 * my_data_struct_release (MyDataStruct *data)
154
 * {
155
 *   // my_data_struct_clear() is defined elsewhere
156
 *   g_rc_box_release_full (data, (GDestroyNotify) my_data_struct_clear);
157
 * }
158
 *
159
 * G_DEFINE_AUTOPTR_CLEANUP_FUNC (MyDataStruct, my_data_struct_release)
160
 * ]|
161
 *
162
 * Since: 2.58
163
 */
164
165
/* We use the same alignment as GTypeInstance and GNU libc's malloc */
166
#define ALIGN_STRUCT(offset)    ((offset + (STRUCT_ALIGNMENT - 1)) & -STRUCT_ALIGNMENT)
167
168
0
#define G_RC_BOX(p)             (GRcBox *) (((char *) (p)) - G_RC_BOX_SIZE)
169
170
gpointer
171
g_rc_box_alloc_full (gsize    block_size,
172
                     gsize    alignment,
173
                     gboolean atomic,
174
                     gboolean clear)
175
0
{
176
  /* We don't do an (atomic ? G_ARC_BOX_SIZE : G_RC_BOX_SIZE) check, here
177
   * because we have a static assertion that sizeof(GArcBox) == sizeof(GRcBox)
178
   * inside grcboxprivate.h, and we don't want the compiler to unnecessarily
179
   * warn about both branches of the conditional yielding identical results
180
   */
181
0
  gsize private_size = G_ARC_BOX_SIZE;
182
0
  gsize private_offset = 0;
183
0
  gsize real_size;
184
0
  char *allocated;
185
186
0
  g_assert (alignment != 0);
187
188
  /* We need to ensure that the private data is aligned */
189
0
  if (private_size % alignment != 0)
190
0
    {
191
0
      private_offset = private_size % alignment;
192
0
      private_size += (alignment - private_offset);
193
0
    }
194
195
0
  g_assert (block_size < (G_MAXSIZE - private_size));
196
0
  real_size = private_size + block_size;
197
198
  /* The real allocated size must be a multiple of @alignment, to
199
   * maintain the alignment of block_size
200
   */
201
0
  if (real_size % alignment != 0)
202
0
    {
203
0
      gsize offset = real_size % alignment;
204
0
      g_assert (real_size < (G_MAXSIZE - (alignment - offset)));
205
0
      real_size += (alignment - offset);
206
0
    }
207
208
#ifdef ENABLE_VALGRIND
209
  if (RUNNING_ON_VALGRIND)
210
    {
211
      /* When running under Valgrind we massage the memory allocation
212
       * to include a pointer at the tail end of the block; the pointer
213
       * is then set to the start of the block. This trick allows
214
       * Valgrind to keep track of the over-allocation and not be
215
       * confused when passing the pointer around
216
       */
217
      g_assert (private_size < (G_MAXSIZE - ALIGN_STRUCT (1)));
218
      private_size += ALIGN_STRUCT (1);
219
220
      if (clear)
221
        allocated = g_malloc0 (real_size + sizeof (gpointer));
222
      else
223
        allocated = g_malloc (real_size + sizeof (gpointer));
224
225
      *(gpointer *) (allocated + private_size + block_size) = allocated + ALIGN_STRUCT (1);
226
227
      VALGRIND_MALLOCLIKE_BLOCK (allocated + private_size, block_size + sizeof (gpointer), 0, TRUE);
228
      VALGRIND_MALLOCLIKE_BLOCK (allocated + ALIGN_STRUCT (1), private_size - ALIGN_STRUCT (1), 0, TRUE);
229
    }
230
  else
231
#endif /* ENABLE_VALGRIND */
232
0
    {
233
0
      if (clear)
234
0
        allocated = g_malloc0 (real_size);
235
0
      else
236
0
        allocated = g_malloc (real_size);
237
0
    }
238
239
0
  if (atomic)
240
0
    {
241
      /* We leave the alignment padding at the top of the allocation,
242
       * so we have an in memory layout of:
243
       *
244
       *  |[ offset ][ sizeof(GArcBox) ]||[ block_size ]|
245
       */
246
0
      GArcBox *real_box = (GArcBox *) (allocated + private_offset);
247
      /* Store the real size */
248
0
      real_box->mem_size = block_size;
249
      /* Store the alignment offset, to be used when freeing the
250
       * allocated block
251
       */
252
0
      real_box->private_offset = private_offset;
253
0
#ifndef G_DISABLE_ASSERT
254
0
      real_box->magic = G_BOX_MAGIC;
255
0
#endif
256
0
      g_atomic_ref_count_init (&real_box->ref_count);
257
0
    }
258
0
  else
259
0
    {
260
      /* We leave the alignment padding at the top of the allocation,
261
       * so we have an in memory layout of:
262
       *
263
       *  |[ offset ][ sizeof(GRcBox) ]||[ block_size ]|
264
       */
265
0
      GRcBox *real_box = (GRcBox *) (allocated + private_offset);
266
      /* Store the real size */
267
0
      real_box->mem_size = block_size;
268
      /* Store the alignment offset, to be used when freeing the
269
       * allocated block
270
       */
271
0
      real_box->private_offset = private_offset;
272
0
#ifndef G_DISABLE_ASSERT
273
0
      real_box->magic = G_BOX_MAGIC;
274
0
#endif
275
0
      g_ref_count_init (&real_box->ref_count);
276
0
    }
277
278
0
  TRACE (GLIB_RCBOX_ALLOC (allocated, block_size, atomic, clear));
279
280
0
  return allocated + private_size;
281
0
}
282
283
/**
284
 * g_rc_box_alloc:
285
 * @block_size: the size of the allocation, must be greater than 0
286
 *
287
 * Allocates @block_size bytes of memory, and adds reference
288
 * counting semantics to it.
289
 *
290
 * The data will be freed when its reference count drops to
291
 * zero.
292
 *
293
 * The allocated data is guaranteed to be suitably aligned for any
294
 * built-in type.
295
 *
296
 * Returns: (transfer full) (not nullable): a pointer to the allocated memory
297
 *
298
 * Since: 2.58
299
 */
300
gpointer
301
g_rc_box_alloc (gsize block_size)
302
0
{
303
0
  g_return_val_if_fail (block_size > 0, NULL);
304
305
0
  return g_rc_box_alloc_full (block_size, STRUCT_ALIGNMENT, FALSE, FALSE);
306
0
}
307
308
/**
309
 * g_rc_box_alloc0:
310
 * @block_size: the size of the allocation, must be greater than 0
311
 *
312
 * Allocates @block_size bytes of memory, and adds reference
313
 * counting semantics to it.
314
 *
315
 * The contents of the returned data is set to zero.
316
 *
317
 * The data will be freed when its reference count drops to
318
 * zero.
319
 *
320
 * The allocated data is guaranteed to be suitably aligned for any
321
 * built-in type.
322
 *
323
 * Returns: (transfer full) (not nullable): a pointer to the allocated memory
324
 *
325
 * Since: 2.58
326
 */
327
gpointer
328
g_rc_box_alloc0 (gsize block_size)
329
0
{
330
0
  g_return_val_if_fail (block_size > 0, NULL);
331
332
0
  return g_rc_box_alloc_full (block_size, STRUCT_ALIGNMENT, FALSE, TRUE);
333
0
}
334
335
/**
336
 * g_rc_box_new:
337
 * @type: the type to allocate, typically a structure name
338
 *
339
 * A convenience macro to allocate reference counted data with
340
 * the size of the given @type.
341
 *
342
 * This macro calls g_rc_box_alloc() with `sizeof (@type)` and
343
 * casts the returned pointer to a pointer of the given @type,
344
 * avoiding a type cast in the source code.
345
 *
346
 * Returns: (transfer full) (not nullable): a pointer to the
347
 *   allocated memory, cast to a pointer for the given @type
348
 *
349
 * Since: 2.58
350
 */
351
352
/**
353
 * g_rc_box_new0:
354
 * @type: the type to allocate, typically a structure name
355
 *
356
 * A convenience macro to allocate reference counted data with
357
 * the size of the given @type, and set its contents to zero.
358
 *
359
 * This macro calls g_rc_box_alloc0() with `sizeof (@type)` and
360
 * casts the returned pointer to a pointer of the given @type,
361
 * avoiding a type cast in the source code.
362
 *
363
 * Returns: (transfer full) (not nullable): a pointer to the
364
 *   allocated memory, cast to a pointer for the given @type
365
 *
366
 * Since: 2.58
367
 */
368
369
/**
370
 * g_rc_box_dup:
371
 * @block_size: the number of bytes to copy, must be greater than 0
372
 * @mem_block: (not nullable): the memory to copy
373
 *
374
 * Allocates a new block of data with reference counting
375
 * semantics, and copies @block_size bytes of @mem_block
376
 * into it.
377
 *
378
 * Returns: (transfer full) (not nullable): a pointer to the allocated
379
 *   memory
380
 *
381
 * Since: 2.58
382
 */
383
gpointer
384
(g_rc_box_dup) (gsize         block_size,
385
                gconstpointer mem_block)
386
0
{
387
0
  gpointer res;
388
389
0
  g_return_val_if_fail (block_size > 0, NULL);
390
0
  g_return_val_if_fail (mem_block != NULL, NULL);
391
392
0
  res = g_rc_box_alloc_full (block_size, STRUCT_ALIGNMENT, FALSE, FALSE);
393
0
  memcpy (res, mem_block, block_size);
394
395
0
  return res;
396
0
}
397
398
/**
399
 * g_rc_box_acquire:
400
 * @mem_block: (not nullable): a pointer to reference counted data
401
 *
402
 * Acquires a reference on the data pointed by @mem_block.
403
 *
404
 * Returns: (transfer full) (not nullable): a pointer to the data,
405
 *   with its reference count increased
406
 *
407
 * Since: 2.58
408
 */
409
gpointer
410
(g_rc_box_acquire) (gpointer mem_block)
411
0
{
412
0
  GRcBox *real_box = G_RC_BOX (mem_block);
413
414
0
  g_return_val_if_fail (mem_block != NULL, NULL);
415
0
#ifndef G_DISABLE_ASSERT
416
0
  g_return_val_if_fail (real_box->magic == G_BOX_MAGIC, NULL);
417
0
#endif
418
419
0
  g_ref_count_inc (&real_box->ref_count);
420
421
0
  TRACE (GLIB_RCBOX_ACQUIRE (mem_block, 0));
422
423
0
  return mem_block;
424
0
}
425
426
/**
427
 * g_rc_box_release:
428
 * @mem_block: (transfer full) (not nullable): a pointer to reference counted data
429
 *
430
 * Releases a reference on the data pointed by @mem_block.
431
 *
432
 * If the reference was the last one, it will free the
433
 * resources allocated for @mem_block.
434
 *
435
 * Since: 2.58
436
 */
437
void
438
g_rc_box_release (gpointer mem_block)
439
0
{
440
0
  g_rc_box_release_full (mem_block, NULL);
441
0
}
442
443
/**
444
 * g_rc_box_release_full:
445
 * @mem_block: (transfer full) (not nullable): a pointer to reference counted data
446
 * @clear_func: (not nullable): a function to call when clearing the data
447
 *
448
 * Releases a reference on the data pointed by @mem_block.
449
 *
450
 * If the reference was the last one, it will call @clear_func
451
 * to clear the contents of @mem_block, and then will free the
452
 * resources allocated for @mem_block.
453
 *
454
 * Since: 2.58
455
 */
456
void
457
g_rc_box_release_full (gpointer       mem_block,
458
                       GDestroyNotify clear_func)
459
0
{
460
0
  GRcBox *real_box = G_RC_BOX (mem_block);
461
462
0
  g_return_if_fail (mem_block != NULL);
463
0
#ifndef G_DISABLE_ASSERT
464
0
  g_return_if_fail (real_box->magic == G_BOX_MAGIC);
465
0
#endif
466
467
0
  if (g_ref_count_dec (&real_box->ref_count))
468
0
    {
469
0
      char *real_mem = (char *) real_box - real_box->private_offset;
470
471
0
      TRACE (GLIB_RCBOX_RELEASE (mem_block, 0));
472
473
0
      if (clear_func != NULL)
474
0
        clear_func (mem_block);
475
476
0
      TRACE (GLIB_RCBOX_FREE (mem_block));
477
0
      g_free (real_mem);
478
0
    }
479
0
}
480
481
/**
482
 * g_rc_box_get_size:
483
 * @mem_block: (not nullable): a pointer to reference counted data
484
 *
485
 * Retrieves the size of the reference counted data pointed by @mem_block.
486
 *
487
 * Returns: the size of the data, in bytes
488
 *
489
 * Since: 2.58
490
 */
491
gsize
492
g_rc_box_get_size (gpointer mem_block)
493
0
{
494
0
  GRcBox *real_box = G_RC_BOX (mem_block);
495
496
0
  g_return_val_if_fail (mem_block != NULL, 0);
497
0
#ifndef G_DISABLE_ASSERT
498
0
  g_return_val_if_fail (real_box->magic == G_BOX_MAGIC, 0);
499
0
#endif
500
501
0
  return real_box->mem_size;
502
0
}