Commits

Thomas Heller  committed 3ff6d3f

Prevent creation (followed by a segfault) of array types when the size
overflows the valid Py_ssize_t range. Check return values of
PyMem_Malloc.

Backported from trunk.

  • Participants
  • Parent commits 0ea5595
  • Branches 2.5

Comments (0)

Files changed (1)

File Modules/_ctypes/_ctypes.c

 	}
 
 	itemsize = itemdict->size;
+	if (length * itemsize < 0) {
+		PyErr_SetString(PyExc_OverflowError,
+				"array too large");
+		return NULL;
+	}
+
 	itemalign = itemdict->align;
 
 	stgdict->size = itemsize * length;
 	0,					/* tp_free */
 };
 
-static void CData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
+static int CData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
 {
 	if ((size_t)dict->size <= sizeof(obj->b_value)) {
 		/* No need to call malloc, can use the default buffer */
 		   33% of the creation time for c_int().
 		*/
 		obj->b_ptr = (char *)PyMem_Malloc(dict->size);
+		if (obj->b_ptr == NULL) {
+			PyErr_NoMemory();
+			return -1;
+		}
 		obj->b_needsfree = 1;
 		memset(obj->b_ptr, 0, dict->size);
 	}
 	obj->b_size = dict->size;
+	return 0;
 }
 
 PyObject *
 		cmem->b_base = (CDataObject *)base;
 		cmem->b_index = index;
 	} else { /* copy contents of adr */
-		CData_MallocBuffer(cmem, dict);
+		if (-1 == CData_MallocBuffer(cmem, dict)) {
+			return NULL;
+			Py_DECREF(cmem);
+		}
 		memcpy(cmem->b_ptr, adr, dict->size);
 		cmem->b_index = index;
 	}
 	obj->b_objects = NULL;
 	obj->b_length = dict->length;
 			
-	CData_MallocBuffer(obj, dict);
+	if (-1 == CData_MallocBuffer(obj, dict)) {
+		Py_DECREF(obj);
+		return NULL;
+	}
 	return (PyObject *)obj;
 }
 /*****************************************************************/