]> granicus.if.org Git - php/commitdiff
Fixed crash in usort() and uasort() in case user comparison function modifyes th
authorDmitry Stogov <dmitry@php.net>
Fri, 14 Aug 2009 06:21:49 +0000 (06:21 +0000)
committerDmitry Stogov <dmitry@php.net>
Fri, 14 Aug 2009 06:21:49 +0000 (06:21 +0000)
e array.

ext/standard/array.c

index 922bb6e830c6c999096753dbd97d871768c8a76c..d122faa6485bd5341f35fb16a8a0d72c374d775f 100644 (file)
@@ -640,6 +640,7 @@ static int php_array_user_compare(const void *a, const void *b TSRMLS_DC) /* {{{
 PHP_FUNCTION(usort)
 {
        zval *array;
+       int refcount;
        PHP_ARRAY_CMP_FUNC_VARS;
 
        PHP_ARRAY_CMP_FUNC_BACKUP();
@@ -649,12 +650,31 @@ PHP_FUNCTION(usort)
                return;
        }
 
+       /* Clear the is_ref flag, so the attemts to modify the array in user
+        * comaprison function will create a copy of array and won't affect the
+        * original array. The fact of modification is detected using refcount
+        * comparison. The result of sorting in such case is undefined and the
+        * function returns FALSE.
+        */
+       Z_UNSET_ISREF_P(array);
+       refcount = Z_REFCOUNT_P(array);
+
        if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 1 TSRMLS_CC) == FAILURE) {
-               PHP_ARRAY_CMP_FUNC_RESTORE();
-               RETURN_FALSE;
+               RETVAL_FALSE;
+       } else {
+               if (refcount > Z_REFCOUNT_P(array)) {
+                       php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function");
+                       RETVAL_FALSE;
+               } else {
+                       RETVAL_TRUE;
+               }
+       }
+       
+       if (Z_REFCOUNT_P(array) > 1) {
+               Z_SET_ISREF_P(array);
        }
+
        PHP_ARRAY_CMP_FUNC_RESTORE();
-       RETURN_TRUE;
 }
 /* }}} */