diff mbox series

[v3,6/9] qom: enforce use of static, const string with object_new()

Message ID 20241115172521.504102-7-berrange@redhat.com (mailing list archive)
State New
Headers show
Series Require error handling for dynamically created objects | expand

Commit Message

Daniel P. Berrangé Nov. 15, 2024, 5:25 p.m. UTC
Since object_new() will assert(), it should only be used in scenarios
where the caller knows exactly what type it is asking to be created,
and can thus be confident in avoiding abstract types.

Enforce this by using a macro wrapper which types to paste "" to the
type name. This will generate a compile error if not passed a static
const string, forcing callers to use object_new_dynamic() instead.

Reviewed-by: Peter Xu <peterx@redhat.com>
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
---
 include/qom/object.h | 12 +++++++++++-
 qom/object.c         |  3 ++-
 2 files changed, 13 insertions(+), 2 deletions(-)
diff mbox series

Patch

diff --git a/include/qom/object.h b/include/qom/object.h
index 4fc01336c4..2d5a0d84b5 100644
--- a/include/qom/object.h
+++ b/include/qom/object.h
@@ -637,7 +637,17 @@  Object *object_new_with_class(ObjectClass *klass, Error **errp);
  *
  * Returns: The newly allocated and instantiated object.
  */
-Object *object_new(const char *typename);
+
+/*
+ * NB, object_new_internal is just an internal helper, wrapped by
+ * the object_new() macro which prevents invokation unless given
+ * a static, const string.
+ *
+ * Code should call object_new(), or object_new_dynamic(), not
+ * object_new_internal().
+ */
+Object *object_new_internal(const char *typename);
+#define object_new(typename) object_new_internal(typename "")
 
 /**
  * object_new_dynamic:
diff --git a/qom/object.c b/qom/object.c
index 42ef40a1fd..ee56710348 100644
--- a/qom/object.c
+++ b/qom/object.c
@@ -799,7 +799,8 @@  Object *object_new_with_class(ObjectClass *klass, Error **errp)
     return object_new_with_type(klass->type, errp);
 }
 
-Object *object_new(const char *typename)
+/* Only to be called via the 'object_new' macro */
+Object *object_new_internal(const char *typename)
 {
     TypeImpl *ti = type_get_or_load_by_name(typename, &error_fatal);