[libvirt] [PATCH 2/2] python: return error if PyObject obj is NULL for unwrapper helper functions

Guannan Ren gren at redhat.com
Tue Apr 17 17:45:06 UTC 2012


    The result is indeterminate for NULL argument to python
    functions as follows. It's better to return negative value in
    these situations.

    PyObject_IsTrue will segfault if the argument is NULL
    PyFloat_AsDouble(NULL) is -1.000000
    PyLong_AsUnsignedLongLong(NULL) is 0.000000
---
 python/typewrappers.c |   26 +++++++++++++++++++++++---
 1 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/python/typewrappers.c b/python/typewrappers.c
index c525e59..58770be 100644
--- a/python/typewrappers.c
+++ b/python/typewrappers.c
@@ -124,6 +124,9 @@ libvirt_intUnwrap(PyObject *obj, int *val)
 {
     long long_val;
 
+    if (!obj)
+        return -1;
+
     /* If obj is type of PyInt_Type, PyInt_AsLong converts it
      * to C long type directly. If it is of PyLong_Type, PyInt_AsLong
      * will call PyLong_AsLong() to deal with it automatically.
@@ -151,6 +154,9 @@ libvirt_uintUnwrap(PyObject *obj, unsigned int *val)
 {
     long long_val;
 
+    if (!obj)
+        return -1;
+
     long_val = PyInt_AsLong(obj);
     if ((long_val == -1) && PyErr_Occurred())
         return -1;
@@ -170,6 +176,9 @@ libvirt_longUnwrap(PyObject *obj, long *val)
 {
     long long_val;
 
+    if (!obj)
+        return -1;
+
     long_val = PyInt_AsLong(obj);
     if ((long_val == -1) && PyErr_Occurred())
         return -1;
@@ -183,6 +192,9 @@ libvirt_ulongUnwrap(PyObject *obj, unsigned long *val)
 {
     long long_val;
 
+    if (!obj)
+        return -1;
+
     long_val = PyInt_AsLong(obj);
     if ((long_val == -1) && PyErr_Occurred())
         return -1;
@@ -202,6 +214,9 @@ libvirt_longlongUnwrap(PyObject *obj, long long *val)
 {
     long long llong_val;
 
+    if (!obj)
+        return -1;
+
     /* If obj is of PyInt_Type, PyLong_AsLongLong
      * will call PyInt_AsLong() to handle it automatically.
      */
@@ -219,6 +234,9 @@ libvirt_ulonglongUnwrap(PyObject *obj, unsigned long long *val)
     unsigned long long ullong_val = -1;
     long long llong_val;
 
+    if (!obj)
+        return -1;
+
     /* The PyLong_AsUnsignedLongLong doesn't check the type of
      * obj, only accept argument of PyLong_Type, so we check it instead.
      */
@@ -247,6 +265,9 @@ libvirt_doubleUnwrap(PyObject *obj, double *val)
 {
     double double_val;
 
+    if (!obj)
+        return -1;
+
     double_val = PyFloat_AsDouble(obj);
     if ((double_val == -1) && PyErr_Occurred())
         return -1;
@@ -260,9 +281,8 @@ libvirt_boolUnwrap(PyObject *obj, bool *val)
 {
     int ret;
 
-    ret = PyObject_IsTrue(obj);
-    if (ret < 0)
-        return ret;
+    if (!obj || ((ret = PyObject_IsTrue(obj)) < 0))
+       return -1;
 
     *val = ret > 0;
     return 0;
-- 
1.7.7.5




More information about the libvir-list mailing list