[libvirt] [PATCH python] Protect against user accidentally calling constructors directly

Daniel P. Berrange berrange at redhat.com
Thu Jan 19 15:20:17 UTC 2017


When using libvirt python you must never call the object
constructors directly, as these are expecting to be passed
a wrapped C object. For example

   import libvirt
   c = libvirt.virConnect("qemu:///system")
   c.listAllDomains()

will mysteriously segfault. With this change the user now
gets an slightly more helpful error

  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/home/berrange/src/virt/libvirt-python/build/libvirt.py", line 3409, in __init__
      raise Exception("Expected a wrapped C Object but got %s" % type(_obj))
  Exception: Expected a wrapped C Object but got <type 'str'>

Signed-off-by: Daniel P. Berrange <berrange at redhat.com>
---
 generator.py | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/generator.py b/generator.py
index e9be8b1..6bcf80b 100755
--- a/generator.py
+++ b/generator.py
@@ -1532,6 +1532,8 @@ def buildWrappers(module):
                 elif classname in [ "virDomainSnapshot" ]:
                     classes.write("        self._dom = dom\n")
                     classes.write("        self._conn = dom.connect()\n")
+                classes.write("        if type(_obj).__name__ not in [\"PyCapsule\", \"PyCObject\"]:\n")
+                classes.write("            raise Exception(\"Expected a wrapped C Object but got %s\" % type(_obj))\n")
                 classes.write("        self._o = _obj\n\n")
             destruct=None
             if classname in classes_destructors:
-- 
2.9.3




More information about the libvir-list mailing list