diff Objects/stringobject.c @ 42005:2bd9417dacd5 2.5

Prevent expandtabs() on string and unicode objects from causing a segfault when a large width is passed on 32-bit platforms. Found by Google. It would be good for people to review this especially carefully and verify I don't have an off by one error and there is no other way to cause overflow.
author Neal Norwitz <nnorwitz@gmail.com>
date Sat, 09 Jun 2007 04:06:30 +0000
parents 9d1b0c295ebb
children 71f3192915e1
line wrap: on
line diff
--- a/Objects/stringobject.c	Fri Jun 08 19:39:31 2007 +0000
+++ b/Objects/stringobject.c	Sat Jun 09 04:06:30 2007 +0000
@@ -3298,7 +3298,7 @@
 {
     const char *e, *p;
     char *q;
-    Py_ssize_t i, j;
+    Py_ssize_t i, j, old_j;
     PyObject *u;
     int tabsize = 8;
 
@@ -3306,12 +3306,18 @@
 	return NULL;
 
     /* First pass: determine size of output string */
-    i = j = 0;
+    i = j = old_j = 0;
     e = PyString_AS_STRING(self) + PyString_GET_SIZE(self);
     for (p = PyString_AS_STRING(self); p < e; p++)
         if (*p == '\t') {
-	    if (tabsize > 0)
+	    if (tabsize > 0) {
 		j += tabsize - (j % tabsize);
+		if (old_j > j) {
+		    PyErr_SetString(PyExc_OverflowError, "new string is too long");
+		    return NULL;
+		}
+		old_j = j;
+            }
 	}
         else {
             j++;
@@ -3321,6 +3327,11 @@
             }
         }
 
+    if ((i + j) < 0) {
+        PyErr_SetString(PyExc_OverflowError, "new string is too long");
+        return NULL;
+    }
+
     /* Second pass: create output string and fill it */
     u = PyString_FromStringAndSize(NULL, i + j);
     if (!u)