@@ -441,6 +441,91 @@ In addition, QEMU assumes that the compiler does not use the latitude
441
441
given in C99 and C11 to treat aspects of signed '<<' as undefined, as
442
442
documented in the GNU Compiler Collection manual starting at version 4.0.
443
443
444
+ Automatic memory deallocation
445
+ =============================
446
+
447
+ QEMU has a mandatory dependency either the GCC or CLang compiler. As
448
+ such it has the freedom to make use of a C language extension for
449
+ automatically running a cleanup function when a stack variable goes
450
+ out of scope. This can be used to simplify function cleanup paths,
451
+ often allowing many goto jumps to be eliminated, through automatic
452
+ free'ing of memory.
453
+
454
+ The GLib2 library provides a number of functions/macros for enabling
455
+ automatic cleanup:
456
+
457
+ `<https://developer.gnome.org/glib/stable/glib-Miscellaneous-Macros.html >`_
458
+
459
+ Most notably:
460
+
461
+ * g_autofree - will invoke g_free() on the variable going out of scope
462
+
463
+ * g_autoptr - for structs / objects, will invoke the cleanup func created
464
+ by a previous use of G_DEFINE_AUTOPTR_CLEANUP_FUNC. This is
465
+ supported for most GLib data types and GObjects
466
+
467
+ For example, instead of
468
+
469
+ .. code-block :: c
470
+
471
+ int somefunc(void) {
472
+ int ret = -1;
473
+ char *foo = g_strdup_printf("foo%", "wibble");
474
+ GList *bar = .....
475
+
476
+ if (eek) {
477
+ goto cleanup;
478
+ }
479
+
480
+ ret = 0;
481
+
482
+ cleanup:
483
+ g_free(foo);
484
+ g_list_free(bar);
485
+ return ret;
486
+ }
487
+
488
+ Using g_autofree/g_autoptr enables the code to be written as:
489
+
490
+ .. code-block :: c
491
+
492
+ int somefunc(void) {
493
+ g_autofree char *foo = g_strdup_printf("foo%", "wibble");
494
+ g_autoptr (GList) bar = .....
495
+
496
+ if (eek) {
497
+ return -1;
498
+ }
499
+
500
+ return 0;
501
+ }
502
+
503
+ While this generally results in simpler, less leak-prone code, there
504
+ are still some caveats to beware of
505
+
506
+ * Variables declared with g_auto* MUST always be initialized,
507
+ otherwise the cleanup function will use uninitialized stack memory
508
+
509
+ * If a variable declared with g_auto* holds a value which must
510
+ live beyond the life of the function, that value must be saved
511
+ and the original variable NULL'd out. This can be simpler using
512
+ g_steal_pointer
513
+
514
+
515
+ .. code-block :: c
516
+
517
+ char *somefunc(void) {
518
+ g_autofree char *foo = g_strdup_printf("foo%", "wibble");
519
+ g_autoptr (GList) bar = .....
520
+
521
+ if (eek) {
522
+ return NULL;
523
+ }
524
+
525
+ return g_steal_pointer(&foo);
526
+ }
527
+
528
+
444
529
Error handling and reporting
445
530
============================
446
531
0 commit comments