1 /* 2 * QEMU Object Model. 3 * 4 * Based on ideas by Avi Kivity <avi@redhat.com> 5 * 6 * Copyright (C) 2009, 2015 Red Hat Inc. 7 * 8 * Authors: 9 * Luiz Capitulino <lcapitulino@redhat.com> 10 * 11 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later. 12 * See the COPYING.LIB file in the top-level directory. 13 * 14 * QObject Reference Counts Terminology 15 * ------------------------------------ 16 * 17 * - Returning references: A function that returns an object may 18 * return it as either a weak or a strong reference. If the reference 19 * is strong, you are responsible for calling QDECREF() on the reference 20 * when you are done. 21 * 22 * If the reference is weak, the owner of the reference may free it at 23 * any time in the future. Before storing the reference anywhere, you 24 * should call QINCREF() to make the reference strong. 25 * 26 * - Transferring ownership: when you transfer ownership of a reference 27 * by calling a function, you are no longer responsible for calling 28 * QDECREF() when the reference is no longer needed. In other words, 29 * when the function returns you must behave as if the reference to the 30 * passed object was weak. 31 */ 32 #ifndef QOBJECT_H 33 #define QOBJECT_H 34 35 #include <stddef.h> 36 #include <assert.h> 37 #include "qapi-types.h" 38 39 struct QObject { 40 QType type; 41 size_t refcnt; 42 }; 43 44 /* Get the 'base' part of an object */ 45 #define QOBJECT(obj) (&(obj)->base) 46 47 /* High-level interface for qobject_incref() */ 48 #define QINCREF(obj) \ 49 qobject_incref(QOBJECT(obj)) 50 51 /* High-level interface for qobject_decref() */ 52 #define QDECREF(obj) \ 53 qobject_decref(obj ? QOBJECT(obj) : NULL) 54 55 /* Initialize an object to default values */ 56 static inline void qobject_init(QObject *obj, QType type) 57 { 58 assert(QTYPE_NONE < type && type < QTYPE__MAX); 59 obj->refcnt = 1; 60 obj->type = type; 61 } 62 63 /** 64 * qobject_incref(): Increment QObject's reference count 65 */ 66 static inline void qobject_incref(QObject *obj) 67 { 68 if (obj) 69 obj->refcnt++; 70 } 71 72 /** 73 * qobject_destroy(): Free resources used by the object 74 */ 75 void qobject_destroy(QObject *obj); 76 77 /** 78 * qobject_decref(): Decrement QObject's reference count, deallocate 79 * when it reaches zero 80 */ 81 static inline void qobject_decref(QObject *obj) 82 { 83 assert(!obj || obj->refcnt); 84 if (obj && --obj->refcnt == 0) { 85 qobject_destroy(obj); 86 } 87 } 88 89 /** 90 * qobject_type(): Return the QObject's type 91 */ 92 static inline QType qobject_type(const QObject *obj) 93 { 94 assert(QTYPE_NONE < obj->type && obj->type < QTYPE__MAX); 95 return obj->type; 96 } 97 98 extern QObject qnull_; 99 100 static inline QObject *qnull(void) 101 { 102 qobject_incref(&qnull_); 103 return &qnull_; 104 } 105 106 #endif /* QOBJECT_H */ 107