xref: /PHP-7.2/ext/spl/spl_array.c (revision 8f221bde)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2018 The PHP Group                                |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Marcus Boerger <helly@php.net>                              |
16    +----------------------------------------------------------------------+
17  */
18 
19 /* $Id$ */
20 
21 #ifdef HAVE_CONFIG_H
22 # include "config.h"
23 #endif
24 
25 #include "php.h"
26 #include "php_ini.h"
27 #include "ext/standard/info.h"
28 #include "ext/standard/php_var.h"
29 #include "zend_smart_str.h"
30 #include "zend_interfaces.h"
31 #include "zend_exceptions.h"
32 
33 #include "php_spl.h"
34 #include "spl_functions.h"
35 #include "spl_engine.h"
36 #include "spl_iterators.h"
37 #include "spl_array.h"
38 #include "spl_exceptions.h"
39 
40 zend_object_handlers spl_handler_ArrayObject;
41 PHPAPI zend_class_entry  *spl_ce_ArrayObject;
42 
43 zend_object_handlers spl_handler_ArrayIterator;
44 PHPAPI zend_class_entry  *spl_ce_ArrayIterator;
45 PHPAPI zend_class_entry  *spl_ce_RecursiveArrayIterator;
46 
47 #define SPL_ARRAY_STD_PROP_LIST      0x00000001
48 #define SPL_ARRAY_ARRAY_AS_PROPS     0x00000002
49 #define SPL_ARRAY_CHILD_ARRAYS_ONLY  0x00000004
50 #define SPL_ARRAY_OVERLOADED_REWIND  0x00010000
51 #define SPL_ARRAY_OVERLOADED_VALID   0x00020000
52 #define SPL_ARRAY_OVERLOADED_KEY     0x00040000
53 #define SPL_ARRAY_OVERLOADED_CURRENT 0x00080000
54 #define SPL_ARRAY_OVERLOADED_NEXT    0x00100000
55 #define SPL_ARRAY_IS_SELF            0x01000000
56 #define SPL_ARRAY_USE_OTHER          0x02000000
57 #define SPL_ARRAY_INT_MASK           0xFFFF0000
58 #define SPL_ARRAY_CLONE_MASK         0x0100FFFF
59 
60 #define SPL_ARRAY_METHOD_NO_ARG				0
61 #define SPL_ARRAY_METHOD_USE_ARG    		1
62 #define SPL_ARRAY_METHOD_MAY_USER_ARG 		2
63 
64 typedef struct _spl_array_object {
65 	zval              array;
66 	uint32_t          ht_iter;
67 	int               ar_flags;
68 	unsigned char	  nApplyCount;
69 	zend_function     *fptr_offset_get;
70 	zend_function     *fptr_offset_set;
71 	zend_function     *fptr_offset_has;
72 	zend_function     *fptr_offset_del;
73 	zend_function     *fptr_count;
74 	zend_class_entry* ce_get_iterator;
75 	zend_object       std;
76 } spl_array_object;
77 
spl_array_from_obj(zend_object * obj)78 static inline spl_array_object *spl_array_from_obj(zend_object *obj) /* {{{ */ {
79 	return (spl_array_object*)((char*)(obj) - XtOffsetOf(spl_array_object, std));
80 }
81 /* }}} */
82 
83 #define Z_SPLARRAY_P(zv)  spl_array_from_obj(Z_OBJ_P((zv)))
84 
spl_array_get_hash_table_ptr(spl_array_object * intern)85 static inline HashTable **spl_array_get_hash_table_ptr(spl_array_object* intern) { /* {{{ */
86 	//??? TODO: Delay duplication for arrays; only duplicate for write operations
87 	if (intern->ar_flags & SPL_ARRAY_IS_SELF) {
88 		if (!intern->std.properties) {
89 			rebuild_object_properties(&intern->std);
90 		}
91 		return &intern->std.properties;
92 	} else if (intern->ar_flags & SPL_ARRAY_USE_OTHER) {
93 		spl_array_object *other = Z_SPLARRAY_P(&intern->array);
94 		return spl_array_get_hash_table_ptr(other);
95 	} else if (Z_TYPE(intern->array) == IS_ARRAY) {
96 		return &Z_ARRVAL(intern->array);
97 	} else {
98 		zend_object *obj = Z_OBJ(intern->array);
99 		if (!obj->properties) {
100 			rebuild_object_properties(obj);
101 		} else if (GC_REFCOUNT(obj->properties) > 1) {
102 			if (EXPECTED(!(GC_FLAGS(obj->properties) & IS_ARRAY_IMMUTABLE))) {
103 				GC_REFCOUNT(obj->properties)--;
104 			}
105 			obj->properties = zend_array_dup(obj->properties);
106 		}
107 		return &obj->properties;
108 	}
109 }
110 /* }}} */
111 
spl_array_get_hash_table(spl_array_object * intern)112 static inline HashTable *spl_array_get_hash_table(spl_array_object* intern) { /* {{{ */
113 	return *spl_array_get_hash_table_ptr(intern);
114 }
115 /* }}} */
116 
spl_array_replace_hash_table(spl_array_object * intern,HashTable * ht)117 static inline void spl_array_replace_hash_table(spl_array_object* intern, HashTable *ht) { /* {{{ */
118 	HashTable **ht_ptr = spl_array_get_hash_table_ptr(intern);
119 	zend_array_destroy(*ht_ptr);
120 	*ht_ptr = ht;
121 }
122 /* }}} */
123 
spl_array_is_object(spl_array_object * intern)124 static inline zend_bool spl_array_is_object(spl_array_object *intern) /* {{{ */
125 {
126 	while (intern->ar_flags & SPL_ARRAY_USE_OTHER) {
127 		intern = Z_SPLARRAY_P(&intern->array);
128 	}
129 	return (intern->ar_flags & SPL_ARRAY_IS_SELF) || Z_TYPE(intern->array) == IS_OBJECT;
130 }
131 /* }}} */
132 
133 static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht);
134 
spl_array_create_ht_iter(HashTable * ht,spl_array_object * intern)135 static zend_never_inline void spl_array_create_ht_iter(HashTable *ht, spl_array_object* intern) /* {{{ */
136 {
137 	intern->ht_iter = zend_hash_iterator_add(ht, ht->nInternalPointer);
138 	zend_hash_internal_pointer_reset_ex(ht, &EG(ht_iterators)[intern->ht_iter].pos);
139 	spl_array_skip_protected(intern, ht);
140 }
141 /* }}} */
142 
spl_array_get_pos_ptr(HashTable * ht,spl_array_object * intern)143 static zend_always_inline uint32_t *spl_array_get_pos_ptr(HashTable *ht, spl_array_object* intern) /* {{{ */
144 {
145 	if (UNEXPECTED(intern->ht_iter == (uint32_t)-1)) {
146 		spl_array_create_ht_iter(ht, intern);
147 	}
148 	return &EG(ht_iterators)[intern->ht_iter].pos;
149 }
150 /* }}} */
151 
152 /* {{{ spl_array_object_free_storage */
spl_array_object_free_storage(zend_object * object)153 static void spl_array_object_free_storage(zend_object *object)
154 {
155 	spl_array_object *intern = spl_array_from_obj(object);
156 
157 	if (intern->ht_iter != (uint32_t) -1) {
158 		zend_hash_iterator_del(intern->ht_iter);
159 	}
160 
161 	zend_object_std_dtor(&intern->std);
162 
163 	zval_ptr_dtor(&intern->array);
164 }
165 /* }}} */
166 
167 zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref);
168 
169 /* {{{ spl_array_object_new_ex */
spl_array_object_new_ex(zend_class_entry * class_type,zval * orig,int clone_orig)170 static zend_object *spl_array_object_new_ex(zend_class_entry *class_type, zval *orig, int clone_orig)
171 {
172 	spl_array_object *intern;
173 	zend_class_entry *parent = class_type;
174 	int inherited = 0;
175 
176 	intern = ecalloc(1, sizeof(spl_array_object) + zend_object_properties_size(parent));
177 
178 	zend_object_std_init(&intern->std, class_type);
179 	object_properties_init(&intern->std, class_type);
180 
181 	intern->ar_flags = 0;
182 	intern->ce_get_iterator = spl_ce_ArrayIterator;
183 	if (orig) {
184 		spl_array_object *other = Z_SPLARRAY_P(orig);
185 
186 		intern->ar_flags &= ~ SPL_ARRAY_CLONE_MASK;
187 		intern->ar_flags |= (other->ar_flags & SPL_ARRAY_CLONE_MASK);
188 		intern->ce_get_iterator = other->ce_get_iterator;
189 		if (clone_orig) {
190 			if (other->ar_flags & SPL_ARRAY_IS_SELF) {
191 				ZVAL_UNDEF(&intern->array);
192 			} else if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayObject) {
193 				ZVAL_ARR(&intern->array,
194 					zend_array_dup(spl_array_get_hash_table(other)));
195 			} else {
196 				ZEND_ASSERT(Z_OBJ_HT_P(orig) == &spl_handler_ArrayIterator);
197 				ZVAL_COPY(&intern->array, orig);
198 				intern->ar_flags |= SPL_ARRAY_USE_OTHER;
199 			}
200 		} else {
201 			ZVAL_COPY(&intern->array, orig);
202 			intern->ar_flags |= SPL_ARRAY_USE_OTHER;
203 		}
204 	} else {
205 		array_init(&intern->array);
206 	}
207 
208 	while (parent) {
209 		if (parent == spl_ce_ArrayIterator || parent == spl_ce_RecursiveArrayIterator) {
210 			intern->std.handlers = &spl_handler_ArrayIterator;
211 			class_type->get_iterator = spl_array_get_iterator;
212 			break;
213 		} else if (parent == spl_ce_ArrayObject) {
214 			intern->std.handlers = &spl_handler_ArrayObject;
215 			break;
216 		}
217 		parent = parent->parent;
218 		inherited = 1;
219 	}
220 	if (!parent) { /* this must never happen */
221 		php_error_docref(NULL, E_COMPILE_ERROR, "Internal compiler error, Class is not child of ArrayObject or ArrayIterator");
222 	}
223 	if (inherited) {
224 		intern->fptr_offset_get = zend_hash_str_find_ptr(&class_type->function_table, "offsetget", sizeof("offsetget") - 1);
225 		if (intern->fptr_offset_get->common.scope == parent) {
226 			intern->fptr_offset_get = NULL;
227 		}
228 		intern->fptr_offset_set = zend_hash_str_find_ptr(&class_type->function_table, "offsetset", sizeof("offsetset") - 1);
229 		if (intern->fptr_offset_set->common.scope == parent) {
230 			intern->fptr_offset_set = NULL;
231 		}
232 		intern->fptr_offset_has = zend_hash_str_find_ptr(&class_type->function_table, "offsetexists", sizeof("offsetexists") - 1);
233 		if (intern->fptr_offset_has->common.scope == parent) {
234 			intern->fptr_offset_has = NULL;
235 		}
236 		intern->fptr_offset_del = zend_hash_str_find_ptr(&class_type->function_table, "offsetunset",  sizeof("offsetunset") - 1);
237 		if (intern->fptr_offset_del->common.scope == parent) {
238 			intern->fptr_offset_del = NULL;
239 		}
240 		intern->fptr_count = zend_hash_str_find_ptr(&class_type->function_table, "count", sizeof("count") - 1);
241 		if (intern->fptr_count->common.scope == parent) {
242 			intern->fptr_count = NULL;
243 		}
244 	}
245 	/* Cache iterator functions if ArrayIterator or derived. Check current's */
246 	/* cache since only current is always required */
247 	if (intern->std.handlers == &spl_handler_ArrayIterator) {
248 		if (!class_type->iterator_funcs.zf_current) {
249 			class_type->iterator_funcs.zf_rewind = zend_hash_str_find_ptr(&class_type->function_table, "rewind", sizeof("rewind") - 1);
250 			class_type->iterator_funcs.zf_valid = zend_hash_str_find_ptr(&class_type->function_table, "valid", sizeof("valid") - 1);
251 			class_type->iterator_funcs.zf_key = zend_hash_str_find_ptr(&class_type->function_table, "key", sizeof("key") - 1);
252 			class_type->iterator_funcs.zf_current = zend_hash_str_find_ptr(&class_type->function_table, "current", sizeof("current") - 1);
253 			class_type->iterator_funcs.zf_next = zend_hash_str_find_ptr(&class_type->function_table, "next", sizeof("next") - 1);
254 		}
255 		if (inherited) {
256 			if (class_type->iterator_funcs.zf_rewind->common.scope  != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_REWIND;
257 			if (class_type->iterator_funcs.zf_valid->common.scope   != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_VALID;
258 			if (class_type->iterator_funcs.zf_key->common.scope     != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_KEY;
259 			if (class_type->iterator_funcs.zf_current->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_CURRENT;
260 			if (class_type->iterator_funcs.zf_next->common.scope    != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_NEXT;
261 		}
262 	}
263 
264 	intern->ht_iter = (uint32_t)-1;
265 	return &intern->std;
266 }
267 /* }}} */
268 
269 /* {{{ spl_array_object_new */
spl_array_object_new(zend_class_entry * class_type)270 static zend_object *spl_array_object_new(zend_class_entry *class_type)
271 {
272 	return spl_array_object_new_ex(class_type, NULL, 0);
273 }
274 /* }}} */
275 
276 /* {{{ spl_array_object_clone */
spl_array_object_clone(zval * zobject)277 static zend_object *spl_array_object_clone(zval *zobject)
278 {
279 	zend_object *old_object;
280 	zend_object *new_object;
281 
282 	old_object = Z_OBJ_P(zobject);
283 	new_object = spl_array_object_new_ex(old_object->ce, zobject, 1);
284 
285 	zend_objects_clone_members(new_object, old_object);
286 
287 	return new_object;
288 }
289 /* }}} */
290 
spl_array_get_dimension_ptr(int check_inherited,spl_array_object * intern,zval * offset,int type)291 static zval *spl_array_get_dimension_ptr(int check_inherited, spl_array_object *intern, zval *offset, int type) /* {{{ */
292 {
293 	zval *retval;
294 	zend_long index;
295 	zend_string *offset_key;
296 	HashTable *ht = spl_array_get_hash_table(intern);
297 
298 	if (!offset || Z_ISUNDEF_P(offset) || !ht) {
299 		return &EG(uninitialized_zval);
300 	}
301 
302 	if ((type == BP_VAR_W || type == BP_VAR_RW) && intern->nApplyCount > 0) {
303 		zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
304 		return &EG(error_zval);
305 	}
306 
307 try_again:
308 	switch (Z_TYPE_P(offset)) {
309 	case IS_NULL:
310 	   offset_key = ZSTR_EMPTY_ALLOC();
311 	   goto fetch_dim_string;
312 	case IS_STRING:
313 	   offset_key = Z_STR_P(offset);
314 fetch_dim_string:
315 		retval = zend_symtable_find(ht, offset_key);
316 		if (retval) {
317 			if (Z_TYPE_P(retval) == IS_INDIRECT) {
318 				retval = Z_INDIRECT_P(retval);
319 				if (Z_TYPE_P(retval) == IS_UNDEF) {
320 					switch (type) {
321 						case BP_VAR_R:
322 							zend_error(E_NOTICE, "Undefined index: %s", ZSTR_VAL(offset_key));
323 						case BP_VAR_UNSET:
324 						case BP_VAR_IS:
325 							retval = &EG(uninitialized_zval);
326 							break;
327 						case BP_VAR_RW:
328 							zend_error(E_NOTICE,"Undefined index: %s", ZSTR_VAL(offset_key));
329 						case BP_VAR_W: {
330 							ZVAL_NULL(retval);
331 						}
332 					}
333 				}
334 			}
335 		} else {
336 			switch (type) {
337 				case BP_VAR_R:
338 					zend_error(E_NOTICE, "Undefined index: %s", ZSTR_VAL(offset_key));
339 				case BP_VAR_UNSET:
340 				case BP_VAR_IS:
341 					retval = &EG(uninitialized_zval);
342 					break;
343 				case BP_VAR_RW:
344 					zend_error(E_NOTICE,"Undefined index: %s", ZSTR_VAL(offset_key));
345 				case BP_VAR_W: {
346 				    zval value;
347 					ZVAL_NULL(&value);
348 				    retval = zend_symtable_update(ht, offset_key, &value);
349 				}
350 			}
351 		}
352 		return retval;
353 	case IS_RESOURCE:
354 		zend_error(E_NOTICE, "Resource ID#%d used as offset, casting to integer (%d)", Z_RES_P(offset)->handle, Z_RES_P(offset)->handle);
355 		index = Z_RES_P(offset)->handle;
356 		goto num_index;
357 	case IS_DOUBLE:
358 		index = (zend_long)Z_DVAL_P(offset);
359 		goto num_index;
360 	case IS_FALSE:
361 		index = 0;
362 		goto num_index;
363 	case IS_TRUE:
364 		index = 1;
365 		goto num_index;
366 	case IS_LONG:
367 		index = Z_LVAL_P(offset);
368 num_index:
369 		if ((retval = zend_hash_index_find(ht, index)) == NULL) {
370 			switch (type) {
371 				case BP_VAR_R:
372 					zend_error(E_NOTICE, "Undefined offset: " ZEND_LONG_FMT, index);
373 				case BP_VAR_UNSET:
374 				case BP_VAR_IS:
375 					retval = &EG(uninitialized_zval);
376 					break;
377 				case BP_VAR_RW:
378 					zend_error(E_NOTICE, "Undefined offset: " ZEND_LONG_FMT, index);
379 				case BP_VAR_W: {
380 				    zval value;
381 					ZVAL_UNDEF(&value);
382 					retval = zend_hash_index_update(ht, index, &value);
383 			   }
384 			}
385 		}
386 		return retval;
387 	case IS_REFERENCE:
388 		ZVAL_DEREF(offset);
389 		goto try_again;
390 	default:
391 		zend_error(E_WARNING, "Illegal offset type");
392 		return (type == BP_VAR_W || type == BP_VAR_RW) ?
393 			&EG(error_zval) : &EG(uninitialized_zval);
394 	}
395 } /* }}} */
396 
397 static int spl_array_has_dimension(zval *object, zval *offset, int check_empty);
398 
spl_array_read_dimension_ex(int check_inherited,zval * object,zval * offset,int type,zval * rv)399 static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type, zval *rv) /* {{{ */
400 {
401 	spl_array_object *intern = Z_SPLARRAY_P(object);
402 	zval *ret;
403 
404 	if (check_inherited &&
405 			(intern->fptr_offset_get || (type == BP_VAR_IS && intern->fptr_offset_has))) {
406 		if (type == BP_VAR_IS) {
407 			if (!spl_array_has_dimension(object, offset, 0)) {
408 				return &EG(uninitialized_zval);
409 			}
410 		}
411 
412 		if (intern->fptr_offset_get) {
413 			zval tmp;
414 			if (!offset) {
415 				ZVAL_UNDEF(&tmp);
416 				offset = &tmp;
417 			} else {
418 				SEPARATE_ARG_IF_REF(offset);
419 			}
420 			zend_call_method_with_1_params(object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", rv, offset);
421 			zval_ptr_dtor(offset);
422 
423 			if (!Z_ISUNDEF_P(rv)) {
424 				return rv;
425 			}
426 			return &EG(uninitialized_zval);
427 		}
428 	}
429 
430 	ret = spl_array_get_dimension_ptr(check_inherited, intern, offset, type);
431 
432 	/* When in a write context,
433 	 * ZE has to be fooled into thinking this is in a reference set
434 	 * by separating (if necessary) and returning as IS_REFERENCE (with refcount == 1)
435 	 */
436 
437 	if ((type == BP_VAR_W || type == BP_VAR_RW || type == BP_VAR_UNSET) &&
438 	    !Z_ISREF_P(ret) &&
439 	    EXPECTED(ret != &EG(uninitialized_zval))) {
440 		ZVAL_NEW_REF(ret, ret);
441 	}
442 
443 	return ret;
444 } /* }}} */
445 
spl_array_read_dimension(zval * object,zval * offset,int type,zval * rv)446 static zval *spl_array_read_dimension(zval *object, zval *offset, int type, zval *rv) /* {{{ */
447 {
448 	return spl_array_read_dimension_ex(1, object, offset, type, rv);
449 } /* }}} */
450 
spl_array_write_dimension_ex(int check_inherited,zval * object,zval * offset,zval * value)451 static void spl_array_write_dimension_ex(int check_inherited, zval *object, zval *offset, zval *value) /* {{{ */
452 {
453 	spl_array_object *intern = Z_SPLARRAY_P(object);
454 	zend_long index;
455 	HashTable *ht;
456 
457 	if (check_inherited && intern->fptr_offset_set) {
458 		zval tmp;
459 
460 		if (!offset) {
461 			ZVAL_NULL(&tmp);
462 			offset = &tmp;
463 		} else {
464 			SEPARATE_ARG_IF_REF(offset);
465 		}
466 		zend_call_method_with_2_params(object, Z_OBJCE_P(object), &intern->fptr_offset_set, "offsetSet", NULL, offset, value);
467 		zval_ptr_dtor(offset);
468 		return;
469 	}
470 
471 	if (intern->nApplyCount > 0) {
472 		zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
473 		return;
474 	}
475 
476 	if (Z_REFCOUNTED_P(value)) {
477 		Z_ADDREF_P(value);
478 	}
479 
480 	if (!offset) {
481 		ht = spl_array_get_hash_table(intern);
482 		zend_hash_next_index_insert(ht, value);
483 		return;
484 	}
485 
486 try_again:
487 	switch (Z_TYPE_P(offset)) {
488 		case IS_STRING:
489 			ht = spl_array_get_hash_table(intern);
490 			zend_symtable_update_ind(ht, Z_STR_P(offset), value);
491 			return;
492 		case IS_DOUBLE:
493 			index = (zend_long)Z_DVAL_P(offset);
494 			goto num_index;
495 		case IS_RESOURCE:
496 			index = Z_RES_HANDLE_P(offset);
497 			goto num_index;
498 		case IS_FALSE:
499 			index = 0;
500 			goto num_index;
501 		case IS_TRUE:
502 			index = 1;
503 			goto num_index;
504 		case IS_LONG:
505 			index = Z_LVAL_P(offset);
506 num_index:
507 			ht = spl_array_get_hash_table(intern);
508 			zend_hash_index_update(ht, index, value);
509 			return;
510 		case IS_NULL:
511 			ht = spl_array_get_hash_table(intern);
512 			zend_hash_next_index_insert(ht, value);
513 			return;
514 		case IS_REFERENCE:
515 			ZVAL_DEREF(offset);
516 			goto try_again;
517 		default:
518 			zend_error(E_WARNING, "Illegal offset type");
519 			zval_ptr_dtor(value);
520 			return;
521 	}
522 } /* }}} */
523 
spl_array_write_dimension(zval * object,zval * offset,zval * value)524 static void spl_array_write_dimension(zval *object, zval *offset, zval *value) /* {{{ */
525 {
526 	spl_array_write_dimension_ex(1, object, offset, value);
527 } /* }}} */
528 
spl_array_unset_dimension_ex(int check_inherited,zval * object,zval * offset)529 static void spl_array_unset_dimension_ex(int check_inherited, zval *object, zval *offset) /* {{{ */
530 {
531 	zend_long index;
532 	HashTable *ht;
533 	spl_array_object *intern = Z_SPLARRAY_P(object);
534 
535 	if (check_inherited && intern->fptr_offset_del) {
536 		SEPARATE_ARG_IF_REF(offset);
537 		zend_call_method_with_1_params(object, Z_OBJCE_P(object), &intern->fptr_offset_del, "offsetUnset", NULL, offset);
538 		zval_ptr_dtor(offset);
539 		return;
540 	}
541 
542 	if (intern->nApplyCount > 0) {
543 		zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
544 		return;
545 	}
546 
547 try_again:
548 	switch (Z_TYPE_P(offset)) {
549 	case IS_STRING:
550 		ht = spl_array_get_hash_table(intern);
551 		if (ht == &EG(symbol_table)) {
552 			if (zend_delete_global_variable(Z_STR_P(offset))) {
553 				zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
554 			}
555 		} else {
556 			zval *data = zend_symtable_find(ht, Z_STR_P(offset));
557 
558 			if (data) {
559 				if (Z_TYPE_P(data) == IS_INDIRECT) {
560 					data = Z_INDIRECT_P(data);
561 					if (Z_TYPE_P(data) == IS_UNDEF) {
562 						zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
563 					} else {
564 						zval_ptr_dtor(data);
565 						ZVAL_UNDEF(data);
566 						ht->u.v.flags |= HASH_FLAG_HAS_EMPTY_IND;
567 						zend_hash_move_forward_ex(ht, spl_array_get_pos_ptr(ht, intern));
568 						if (spl_array_is_object(intern)) {
569 							spl_array_skip_protected(intern, ht);
570 						}
571 					}
572 				} else if (zend_symtable_del(ht, Z_STR_P(offset)) == FAILURE) {
573 					zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
574 				}
575 			} else {
576 				zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset));
577 			}
578 		}
579 		break;
580 	case IS_DOUBLE:
581 		index = (zend_long)Z_DVAL_P(offset);
582 		goto num_index;
583 	case IS_RESOURCE:
584 		index = Z_RES_HANDLE_P(offset);
585 		goto num_index;
586 	case IS_FALSE:
587 		index = 0;
588 		goto num_index;
589 	case IS_TRUE:
590 		index = 1;
591 		goto num_index;
592 	case IS_LONG:
593 		index = Z_LVAL_P(offset);
594 num_index:
595 		ht = spl_array_get_hash_table(intern);
596 		if (zend_hash_index_del(ht, index) == FAILURE) {
597 			zend_error(E_NOTICE,"Undefined offset: " ZEND_LONG_FMT, index);
598 		}
599 		break;
600 	case IS_REFERENCE:
601 		ZVAL_DEREF(offset);
602 		goto try_again;
603 	default:
604 		zend_error(E_WARNING, "Illegal offset type");
605 		return;
606 	}
607 } /* }}} */
608 
spl_array_unset_dimension(zval * object,zval * offset)609 static void spl_array_unset_dimension(zval *object, zval *offset) /* {{{ */
610 {
611 	spl_array_unset_dimension_ex(1, object, offset);
612 } /* }}} */
613 
spl_array_has_dimension_ex(int check_inherited,zval * object,zval * offset,int check_empty)614 static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty) /* {{{ */
615 {
616 	spl_array_object *intern = Z_SPLARRAY_P(object);
617 	zend_long index;
618 	zval rv, *value = NULL, *tmp;
619 
620 	if (check_inherited && intern->fptr_offset_has) {
621 		SEPARATE_ARG_IF_REF(offset);
622 		zend_call_method_with_1_params(object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset);
623 		zval_ptr_dtor(offset);
624 
625 		if (!Z_ISUNDEF(rv) && zend_is_true(&rv)) {
626 			zval_ptr_dtor(&rv);
627 			if (check_empty != 1) {
628 				return 1;
629 			} else if (intern->fptr_offset_get) {
630 				value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R, &rv);
631 			}
632 		} else {
633 			zval_ptr_dtor(&rv);
634 			return 0;
635 		}
636 	}
637 
638 	if (!value) {
639 		HashTable *ht = spl_array_get_hash_table(intern);
640 
641 try_again:
642 		switch (Z_TYPE_P(offset)) {
643 			case IS_STRING:
644 				if ((tmp = zend_symtable_find(ht, Z_STR_P(offset))) != NULL) {
645 					if (check_empty == 2) {
646 						return 1;
647 					}
648 				} else {
649 					return 0;
650 				}
651 				break;
652 
653 			case IS_DOUBLE:
654 				index = (zend_long)Z_DVAL_P(offset);
655 				goto num_index;
656 			case IS_RESOURCE:
657 				index = Z_RES_HANDLE_P(offset);
658 				goto num_index;
659 			case IS_FALSE:
660 				index = 0;
661 				goto num_index;
662 			case IS_TRUE:
663 				index = 1;
664 				goto num_index;
665 			case IS_LONG:
666 				index = Z_LVAL_P(offset);
667 num_index:
668 				if ((tmp = zend_hash_index_find(ht, index)) != NULL) {
669 					if (check_empty == 2) {
670 						return 1;
671 					}
672 				} else {
673 					return 0;
674 				}
675 				break;
676 			case IS_REFERENCE:
677 				ZVAL_DEREF(offset);
678 				goto try_again;
679 			default:
680 				zend_error(E_WARNING, "Illegal offset type");
681 				return 0;
682 		}
683 
684 		if (check_empty && check_inherited && intern->fptr_offset_get) {
685 			value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R, &rv);
686 		} else {
687 			value = tmp;
688 		}
689 	}
690 
691 	{
692 		zend_bool result = check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL;
693 		if (value == &rv) {
694 			zval_ptr_dtor(&rv);
695 		}
696 		return result;
697 	}
698 } /* }}} */
699 
spl_array_has_dimension(zval * object,zval * offset,int check_empty)700 static int spl_array_has_dimension(zval *object, zval *offset, int check_empty) /* {{{ */
701 {
702 	return spl_array_has_dimension_ex(1, object, offset, check_empty);
703 } /* }}} */
704 
705 /* {{{ spl_array_object_verify_pos_ex */
spl_array_object_verify_pos_ex(spl_array_object * object,HashTable * ht,const char * msg_prefix)706 static inline int spl_array_object_verify_pos_ex(spl_array_object *object, HashTable *ht, const char *msg_prefix)
707 {
708 	if (!ht) {
709 		php_error_docref(NULL, E_NOTICE, "%sArray was modified outside object and is no longer an array", msg_prefix);
710 		return FAILURE;
711 	}
712 
713 	return SUCCESS;
714 } /* }}} */
715 
716 /* {{{ spl_array_object_verify_pos */
spl_array_object_verify_pos(spl_array_object * object,HashTable * ht)717 static inline int spl_array_object_verify_pos(spl_array_object *object, HashTable *ht)
718 {
719 	return spl_array_object_verify_pos_ex(object, ht, "");
720 } /* }}} */
721 
722 /* {{{ proto bool ArrayObject::offsetExists(mixed $index)
723        proto bool ArrayIterator::offsetExists(mixed $index)
724    Returns whether the requested $index exists. */
SPL_METHOD(Array,offsetExists)725 SPL_METHOD(Array, offsetExists)
726 {
727 	zval *index;
728 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &index) == FAILURE) {
729 		return;
730 	}
731 	RETURN_BOOL(spl_array_has_dimension_ex(0, getThis(), index, 2));
732 } /* }}} */
733 
734 /* {{{ proto mixed ArrayObject::offsetGet(mixed $index)
735        proto mixed ArrayIterator::offsetGet(mixed $index)
736    Returns the value at the specified $index. */
SPL_METHOD(Array,offsetGet)737 SPL_METHOD(Array, offsetGet)
738 {
739 	zval *value, *index;
740 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &index) == FAILURE) {
741 		return;
742 	}
743 	value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R, return_value);
744 	if (value != return_value) {
745 		ZVAL_DEREF(value);
746 		ZVAL_COPY(return_value, value);
747 	}
748 } /* }}} */
749 
750 /* {{{ proto void ArrayObject::offsetSet(mixed $index, mixed $newval)
751        proto void ArrayIterator::offsetSet(mixed $index, mixed $newval)
752    Sets the value at the specified $index to $newval. */
SPL_METHOD(Array,offsetSet)753 SPL_METHOD(Array, offsetSet)
754 {
755 	zval *index, *value;
756 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &index, &value) == FAILURE) {
757 		return;
758 	}
759 	spl_array_write_dimension_ex(0, getThis(), index, value);
760 } /* }}} */
761 
spl_array_iterator_append(zval * object,zval * append_value)762 void spl_array_iterator_append(zval *object, zval *append_value) /* {{{ */
763 {
764 	spl_array_object *intern = Z_SPLARRAY_P(object);
765 	HashTable *aht = spl_array_get_hash_table(intern);
766 
767 	if (!aht) {
768 		php_error_docref(NULL, E_NOTICE, "Array was modified outside object and is no longer an array");
769 		return;
770 	}
771 
772 	if (spl_array_is_object(intern)) {
773 		zend_throw_error(NULL, "Cannot append properties to objects, use %s::offsetSet() instead", ZSTR_VAL(Z_OBJCE_P(object)->name));
774 		return;
775 	}
776 
777 	spl_array_write_dimension(object, NULL, append_value);
778 } /* }}} */
779 
780 /* {{{ proto void ArrayObject::append(mixed $newval)
781        proto void ArrayIterator::append(mixed $newval)
782    Appends the value (cannot be called for objects). */
SPL_METHOD(Array,append)783 SPL_METHOD(Array, append)
784 {
785 	zval *value;
786 
787 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &value) == FAILURE) {
788 		return;
789 	}
790 	spl_array_iterator_append(getThis(), value);
791 } /* }}} */
792 
793 /* {{{ proto void ArrayObject::offsetUnset(mixed $index)
794        proto void ArrayIterator::offsetUnset(mixed $index)
795    Unsets the value at the specified $index. */
SPL_METHOD(Array,offsetUnset)796 SPL_METHOD(Array, offsetUnset)
797 {
798 	zval *index;
799 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &index) == FAILURE) {
800 		return;
801 	}
802 	spl_array_unset_dimension_ex(0, getThis(), index);
803 } /* }}} */
804 
805 /* {{{ proto array ArrayObject::getArrayCopy()
806       proto array ArrayIterator::getArrayCopy()
807    Return a copy of the contained array */
SPL_METHOD(Array,getArrayCopy)808 SPL_METHOD(Array, getArrayCopy)
809 {
810 	zval *object = getThis();
811 	spl_array_object *intern = Z_SPLARRAY_P(object);
812 
813 	RETURN_ARR(zend_array_dup(spl_array_get_hash_table(intern)));
814 } /* }}} */
815 
spl_array_get_properties(zval * object)816 static HashTable *spl_array_get_properties(zval *object) /* {{{ */
817 {
818 	spl_array_object *intern = Z_SPLARRAY_P(object);
819 
820 	if (intern->ar_flags & SPL_ARRAY_STD_PROP_LIST) {
821 		if (!intern->std.properties) {
822 			rebuild_object_properties(&intern->std);
823 		}
824 		return intern->std.properties;
825 	}
826 
827 	return spl_array_get_hash_table(intern);
828 } /* }}} */
829 
spl_array_get_debug_info(zval * obj,int * is_temp)830 static HashTable* spl_array_get_debug_info(zval *obj, int *is_temp) /* {{{ */
831 {
832 	zval *storage;
833 	zend_string *zname;
834 	zend_class_entry *base;
835 	spl_array_object *intern = Z_SPLARRAY_P(obj);
836 
837 	if (!intern->std.properties) {
838 		rebuild_object_properties(&intern->std);
839 	}
840 
841 	if (intern->ar_flags & SPL_ARRAY_IS_SELF) {
842 		*is_temp = 0;
843 		return intern->std.properties;
844 	} else {
845 		HashTable *debug_info;
846 		*is_temp = 1;
847 
848 		ALLOC_HASHTABLE(debug_info);
849 		ZEND_INIT_SYMTABLE_EX(debug_info, zend_hash_num_elements(intern->std.properties) + 1, 0);
850 		zend_hash_copy(debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref);
851 
852 		storage = &intern->array;
853 		Z_TRY_ADDREF_P(storage);
854 
855 		base = Z_OBJ_HT_P(obj) == &spl_handler_ArrayIterator
856 			? spl_ce_ArrayIterator : spl_ce_ArrayObject;
857 		zname = spl_gen_private_prop_name(base, "storage", sizeof("storage")-1);
858 		zend_symtable_update(debug_info, zname, storage);
859 		zend_string_release(zname);
860 
861 		return debug_info;
862 	}
863 }
864 /* }}} */
865 
spl_array_get_gc(zval * obj,zval ** gc_data,int * gc_data_count)866 static HashTable *spl_array_get_gc(zval *obj, zval **gc_data, int *gc_data_count) /* {{{ */
867 {
868 	spl_array_object *intern = Z_SPLARRAY_P(obj);
869 	*gc_data = &intern->array;
870 	*gc_data_count = 1;
871 	return zend_std_get_properties(obj);
872 }
873 /* }}} */
874 
spl_array_read_property(zval * object,zval * member,int type,void ** cache_slot,zval * rv)875 static zval *spl_array_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv) /* {{{ */
876 {
877 	spl_array_object *intern = Z_SPLARRAY_P(object);
878 
879 	if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
880 		&& !std_object_handlers.has_property(object, member, 2, NULL)) {
881 		return spl_array_read_dimension(object, member, type, rv);
882 	}
883 	return std_object_handlers.read_property(object, member, type, cache_slot, rv);
884 } /* }}} */
885 
spl_array_write_property(zval * object,zval * member,zval * value,void ** cache_slot)886 static void spl_array_write_property(zval *object, zval *member, zval *value, void **cache_slot) /* {{{ */
887 {
888 	spl_array_object *intern = Z_SPLARRAY_P(object);
889 
890 	if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
891 	&& !std_object_handlers.has_property(object, member, 2, NULL)) {
892 		spl_array_write_dimension(object, member, value);
893 		return;
894 	}
895 	std_object_handlers.write_property(object, member, value, cache_slot);
896 } /* }}} */
897 
spl_array_get_property_ptr_ptr(zval * object,zval * member,int type,void ** cache_slot)898 static zval *spl_array_get_property_ptr_ptr(zval *object, zval *member, int type, void **cache_slot) /* {{{ */
899 {
900 	spl_array_object *intern = Z_SPLARRAY_P(object);
901 
902 	if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
903 		&& !std_object_handlers.has_property(object, member, 2, NULL)) {
904 		/* If object has offsetGet() overridden, then fallback to read_property,
905 		 * which will call offsetGet(). */
906 		if (intern->fptr_offset_get) {
907 			return NULL;
908 		}
909 		return spl_array_get_dimension_ptr(1, intern, member, type);
910 	}
911 	return std_object_handlers.get_property_ptr_ptr(object, member, type, cache_slot);
912 } /* }}} */
913 
spl_array_has_property(zval * object,zval * member,int has_set_exists,void ** cache_slot)914 static int spl_array_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot) /* {{{ */
915 {
916 	spl_array_object *intern = Z_SPLARRAY_P(object);
917 
918 	if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
919 		&& !std_object_handlers.has_property(object, member, 2, NULL)) {
920 		return spl_array_has_dimension(object, member, has_set_exists);
921 	}
922 	return std_object_handlers.has_property(object, member, has_set_exists, cache_slot);
923 } /* }}} */
924 
spl_array_unset_property(zval * object,zval * member,void ** cache_slot)925 static void spl_array_unset_property(zval *object, zval *member, void **cache_slot) /* {{{ */
926 {
927 	spl_array_object *intern = Z_SPLARRAY_P(object);
928 
929 	if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0
930 		&& !std_object_handlers.has_property(object, member, 2, NULL)) {
931 		spl_array_unset_dimension(object, member);
932 		return;
933 	}
934 	std_object_handlers.unset_property(object, member, cache_slot);
935 } /* }}} */
936 
spl_array_compare_objects(zval * o1,zval * o2)937 static int spl_array_compare_objects(zval *o1, zval *o2) /* {{{ */
938 {
939 	HashTable			*ht1,
940 						*ht2;
941 	spl_array_object	*intern1,
942 						*intern2;
943 	int					result	= 0;
944 
945 	intern1	= Z_SPLARRAY_P(o1);
946 	intern2	= Z_SPLARRAY_P(o2);
947 	ht1		= spl_array_get_hash_table(intern1);
948 	ht2		= spl_array_get_hash_table(intern2);
949 
950 	result = zend_compare_symbol_tables(ht1, ht2);
951 	/* if we just compared std.properties, don't do it again */
952 	if (result == 0 &&
953 			!(ht1 == intern1->std.properties && ht2 == intern2->std.properties)) {
954 		result = std_object_handlers.compare_objects(o1, o2);
955 	}
956 	return result;
957 } /* }}} */
958 
spl_array_skip_protected(spl_array_object * intern,HashTable * aht)959 static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht) /* {{{ */
960 {
961 	zend_string *string_key;
962 	zend_ulong num_key;
963 	zval *data;
964 
965 	if (spl_array_is_object(intern)) {
966 		uint32_t *pos_ptr = spl_array_get_pos_ptr(aht, intern);
967 
968 		do {
969 			if (zend_hash_get_current_key_ex(aht, &string_key, &num_key, pos_ptr) == HASH_KEY_IS_STRING) {
970 				data = zend_hash_get_current_data_ex(aht, pos_ptr);
971 				if (data && Z_TYPE_P(data) == IS_INDIRECT &&
972 				    Z_TYPE_P(data = Z_INDIRECT_P(data)) == IS_UNDEF) {
973 					/* skip */
974 				} else if (!ZSTR_LEN(string_key) || ZSTR_VAL(string_key)[0]) {
975 					return SUCCESS;
976 				}
977 			} else {
978 				return SUCCESS;
979 			}
980 			if (zend_hash_has_more_elements_ex(aht, pos_ptr) != SUCCESS) {
981 				return FAILURE;
982 			}
983 			zend_hash_move_forward_ex(aht, pos_ptr);
984 		} while (1);
985 	}
986 	return FAILURE;
987 } /* }}} */
988 
spl_array_next_ex(spl_array_object * intern,HashTable * aht)989 static int spl_array_next_ex(spl_array_object *intern, HashTable *aht) /* {{{ */
990 {
991 	uint32_t *pos_ptr = spl_array_get_pos_ptr(aht, intern);
992 
993 	zend_hash_move_forward_ex(aht, pos_ptr);
994 	if (spl_array_is_object(intern)) {
995 		return spl_array_skip_protected(intern, aht);
996 	} else {
997 		return zend_hash_has_more_elements_ex(aht, pos_ptr);
998 	}
999 } /* }}} */
1000 
spl_array_next(spl_array_object * intern)1001 static int spl_array_next(spl_array_object *intern) /* {{{ */
1002 {
1003 	HashTable *aht = spl_array_get_hash_table(intern);
1004 
1005 	return spl_array_next_ex(intern, aht);
1006 
1007 } /* }}} */
1008 
spl_array_it_dtor(zend_object_iterator * iter)1009 static void spl_array_it_dtor(zend_object_iterator *iter) /* {{{ */
1010 {
1011 	zend_user_it_invalidate_current(iter);
1012 	zval_ptr_dtor(&iter->data);
1013 }
1014 /* }}} */
1015 
spl_array_it_valid(zend_object_iterator * iter)1016 static int spl_array_it_valid(zend_object_iterator *iter) /* {{{ */
1017 {
1018 	spl_array_object *object = Z_SPLARRAY_P(&iter->data);
1019 	HashTable *aht = spl_array_get_hash_table(object);
1020 
1021 	if (object->ar_flags & SPL_ARRAY_OVERLOADED_VALID) {
1022 		return zend_user_it_valid(iter);
1023 	} else {
1024 		if (spl_array_object_verify_pos_ex(object, aht, "ArrayIterator::valid(): ") == FAILURE) {
1025 			return FAILURE;
1026 		}
1027 
1028 		return zend_hash_has_more_elements_ex(aht, spl_array_get_pos_ptr(aht, object));
1029 	}
1030 }
1031 /* }}} */
1032 
spl_array_it_get_current_data(zend_object_iterator * iter)1033 static zval *spl_array_it_get_current_data(zend_object_iterator *iter) /* {{{ */
1034 {
1035 	spl_array_object *object = Z_SPLARRAY_P(&iter->data);
1036 	HashTable *aht = spl_array_get_hash_table(object);
1037 
1038 	if (object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT) {
1039 		return zend_user_it_get_current_data(iter);
1040 	} else {
1041 		zval *data = zend_hash_get_current_data_ex(aht, spl_array_get_pos_ptr(aht, object));
1042 		if (data && Z_TYPE_P(data) == IS_INDIRECT) {
1043 			data = Z_INDIRECT_P(data);
1044 		}
1045 		return data;
1046 	}
1047 }
1048 /* }}} */
1049 
spl_array_it_get_current_key(zend_object_iterator * iter,zval * key)1050 static void spl_array_it_get_current_key(zend_object_iterator *iter, zval *key) /* {{{ */
1051 {
1052 	spl_array_object *object = Z_SPLARRAY_P(&iter->data);
1053 	HashTable *aht = spl_array_get_hash_table(object);
1054 
1055 	if (object->ar_flags & SPL_ARRAY_OVERLOADED_KEY) {
1056 		zend_user_it_get_current_key(iter, key);
1057 	} else {
1058 		if (spl_array_object_verify_pos_ex(object, aht, "ArrayIterator::current(): ") == FAILURE) {
1059 			ZVAL_NULL(key);
1060 		} else {
1061 			zend_hash_get_current_key_zval_ex(aht, key, spl_array_get_pos_ptr(aht, object));
1062 		}
1063 	}
1064 }
1065 /* }}} */
1066 
spl_array_it_move_forward(zend_object_iterator * iter)1067 static void spl_array_it_move_forward(zend_object_iterator *iter) /* {{{ */
1068 {
1069 	spl_array_object *object = Z_SPLARRAY_P(&iter->data);
1070 	HashTable *aht = spl_array_get_hash_table(object);
1071 
1072 	if (object->ar_flags & SPL_ARRAY_OVERLOADED_NEXT) {
1073 		zend_user_it_move_forward(iter);
1074 	} else {
1075 		zend_user_it_invalidate_current(iter);
1076 		if (!aht) {
1077 			php_error_docref(NULL, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array");
1078 			return;
1079 		}
1080 
1081 		spl_array_next_ex(object, aht);
1082 	}
1083 }
1084 /* }}} */
1085 
spl_array_rewind(spl_array_object * intern)1086 static void spl_array_rewind(spl_array_object *intern) /* {{{ */
1087 {
1088 	HashTable *aht = spl_array_get_hash_table(intern);
1089 
1090 	if (!aht) {
1091 		php_error_docref(NULL, E_NOTICE, "ArrayIterator::rewind(): Array was modified outside object and is no longer an array");
1092 		return;
1093 	}
1094 
1095 	if (intern->ht_iter == (uint32_t)-1) {
1096 		spl_array_get_pos_ptr(aht, intern);
1097 	} else {
1098 		zend_hash_internal_pointer_reset_ex(aht, spl_array_get_pos_ptr(aht, intern));
1099 		spl_array_skip_protected(intern, aht);
1100 	}
1101 }
1102 /* }}} */
1103 
spl_array_it_rewind(zend_object_iterator * iter)1104 static void spl_array_it_rewind(zend_object_iterator *iter) /* {{{ */
1105 {
1106 	spl_array_object *object = Z_SPLARRAY_P(&iter->data);
1107 
1108 	if (object->ar_flags & SPL_ARRAY_OVERLOADED_REWIND) {
1109 		zend_user_it_rewind(iter);
1110 	} else {
1111 		zend_user_it_invalidate_current(iter);
1112 		spl_array_rewind(object);
1113 	}
1114 }
1115 /* }}} */
1116 
1117 /* {{{ spl_array_set_array */
spl_array_set_array(zval * object,spl_array_object * intern,zval * array,zend_long ar_flags,int just_array)1118 static void spl_array_set_array(zval *object, spl_array_object *intern, zval *array, zend_long ar_flags, int just_array) {
1119 	if (Z_TYPE_P(array) != IS_OBJECT && Z_TYPE_P(array) != IS_ARRAY) {
1120 		zend_throw_exception(spl_ce_InvalidArgumentException, "Passed variable is not an array or object", 0);
1121 		return;
1122 	}
1123 
1124 	if (Z_TYPE_P(array) == IS_ARRAY) {
1125 		//??? TODO: try to avoid array duplication
1126 		zval_ptr_dtor(&intern->array);
1127 		ZVAL_DUP(&intern->array, array);
1128 	} else {
1129 		if (Z_OBJ_HT_P(array) == &spl_handler_ArrayObject || Z_OBJ_HT_P(array) == &spl_handler_ArrayIterator) {
1130 			zval_ptr_dtor(&intern->array);
1131 			if (just_array)	{
1132 				spl_array_object *other = Z_SPLARRAY_P(array);
1133 				ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK;
1134 			}
1135 			if (Z_OBJ_P(object) == Z_OBJ_P(array)) {
1136 				ar_flags |= SPL_ARRAY_IS_SELF;
1137 				ZVAL_UNDEF(&intern->array);
1138 			} else {
1139 				ar_flags |= SPL_ARRAY_USE_OTHER;
1140 				ZVAL_COPY(&intern->array, array);
1141 			}
1142 		} else {
1143 			zend_object_get_properties_t handler = Z_OBJ_HANDLER_P(array, get_properties);
1144 			if (handler != std_object_handlers.get_properties) {
1145 				zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
1146 					"Overloaded object of type %s is not compatible with %s",
1147 					ZSTR_VAL(Z_OBJCE_P(array)->name), ZSTR_VAL(intern->std.ce->name));
1148 				return;
1149 			}
1150 			zval_ptr_dtor(&intern->array);
1151 			ZVAL_COPY(&intern->array, array);
1152 		}
1153 	}
1154 
1155 	intern->ar_flags &= ~SPL_ARRAY_IS_SELF & ~SPL_ARRAY_USE_OTHER;
1156 	intern->ar_flags |= ar_flags;
1157 	intern->ht_iter = (uint32_t)-1;
1158 }
1159 /* }}} */
1160 
1161 /* iterator handler table */
1162 zend_object_iterator_funcs spl_array_it_funcs = {
1163 	spl_array_it_dtor,
1164 	spl_array_it_valid,
1165 	spl_array_it_get_current_data,
1166 	spl_array_it_get_current_key,
1167 	spl_array_it_move_forward,
1168 	spl_array_it_rewind,
1169 	NULL
1170 };
1171 
spl_array_get_iterator(zend_class_entry * ce,zval * object,int by_ref)1172 zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
1173 {
1174 	zend_user_iterator *iterator;
1175 	spl_array_object *array_object = Z_SPLARRAY_P(object);
1176 
1177 	if (by_ref && (array_object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT)) {
1178 		zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
1179 	}
1180 
1181 	iterator = emalloc(sizeof(zend_user_iterator));
1182 
1183 	zend_iterator_init(&iterator->it);
1184 
1185 	ZVAL_COPY(&iterator->it.data, object);
1186 	iterator->it.funcs = &spl_array_it_funcs;
1187 	iterator->ce = ce;
1188 	ZVAL_UNDEF(&iterator->value);
1189 
1190 	return &iterator->it;
1191 }
1192 /* }}} */
1193 
1194 /* {{{ proto void ArrayObject::__construct([array|object ar = array() [, int flags = 0 [, string iterator_class = "ArrayIterator"]]])
1195    Constructs a new array object from an array or object. */
SPL_METHOD(Array,__construct)1196 SPL_METHOD(Array, __construct)
1197 {
1198 	zval *object = getThis();
1199 	spl_array_object *intern;
1200 	zval *array;
1201 	zend_long ar_flags = 0;
1202 	zend_class_entry *ce_get_iterator = spl_ce_Iterator;
1203 
1204 	if (ZEND_NUM_ARGS() == 0) {
1205 		return; /* nothing to do */
1206 	}
1207 
1208 	if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "z|lC", &array, &ar_flags, &ce_get_iterator) == FAILURE) {
1209 		return;
1210 	}
1211 
1212 	intern = Z_SPLARRAY_P(object);
1213 
1214 	if (ZEND_NUM_ARGS() > 2) {
1215 		intern->ce_get_iterator = ce_get_iterator;
1216 	}
1217 
1218 	ar_flags &= ~SPL_ARRAY_INT_MASK;
1219 
1220 	spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1);
1221 }
1222  /* }}} */
1223 
1224 /* {{{ proto void ArrayIterator::__construct([array|object ar = array() [, int flags = 0]])
1225    Constructs a new array iterator from an array or object. */
SPL_METHOD(ArrayIterator,__construct)1226 SPL_METHOD(ArrayIterator, __construct)
1227 {
1228 	zval *object = getThis();
1229 	spl_array_object *intern;
1230 	zval *array;
1231 	zend_long ar_flags = 0;
1232 
1233 	if (ZEND_NUM_ARGS() == 0) {
1234 		return; /* nothing to do */
1235 	}
1236 
1237 	if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "z|l", &array, &ar_flags) == FAILURE) {
1238 		return;
1239 	}
1240 
1241 	intern = Z_SPLARRAY_P(object);
1242 
1243 	ar_flags &= ~SPL_ARRAY_INT_MASK;
1244 
1245 	spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1);
1246 }
1247  /* }}} */
1248 
1249 /* {{{ proto void ArrayObject::setIteratorClass(string iterator_class)
1250    Set the class used in getIterator. */
SPL_METHOD(Array,setIteratorClass)1251 SPL_METHOD(Array, setIteratorClass)
1252 {
1253 	zval *object = getThis();
1254 	spl_array_object *intern = Z_SPLARRAY_P(object);
1255 	zend_class_entry * ce_get_iterator = spl_ce_Iterator;
1256 
1257 	ZEND_PARSE_PARAMETERS_START(1, 1)
1258 		Z_PARAM_CLASS(ce_get_iterator)
1259 	ZEND_PARSE_PARAMETERS_END();
1260 
1261 	intern->ce_get_iterator = ce_get_iterator;
1262 }
1263 /* }}} */
1264 
1265 /* {{{ proto string ArrayObject::getIteratorClass()
1266    Get the class used in getIterator. */
SPL_METHOD(Array,getIteratorClass)1267 SPL_METHOD(Array, getIteratorClass)
1268 {
1269 	zval *object = getThis();
1270 	spl_array_object *intern = Z_SPLARRAY_P(object);
1271 
1272 	if (zend_parse_parameters_none() == FAILURE) {
1273 		return;
1274 	}
1275 
1276 	zend_string_addref(intern->ce_get_iterator->name);
1277 	RETURN_STR(intern->ce_get_iterator->name);
1278 }
1279 /* }}} */
1280 
1281 /* {{{ proto int ArrayObject::getFlags()
1282    Get flags */
SPL_METHOD(Array,getFlags)1283 SPL_METHOD(Array, getFlags)
1284 {
1285 	zval *object = getThis();
1286 	spl_array_object *intern = Z_SPLARRAY_P(object);
1287 
1288 	if (zend_parse_parameters_none() == FAILURE) {
1289 		return;
1290 	}
1291 
1292 	RETURN_LONG(intern->ar_flags & ~SPL_ARRAY_INT_MASK);
1293 }
1294 /* }}} */
1295 
1296 /* {{{ proto void ArrayObject::setFlags(int flags)
1297    Set flags */
SPL_METHOD(Array,setFlags)1298 SPL_METHOD(Array, setFlags)
1299 {
1300 	zval *object = getThis();
1301 	spl_array_object *intern = Z_SPLARRAY_P(object);
1302 	zend_long ar_flags = 0;
1303 
1304 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &ar_flags) == FAILURE) {
1305 		return;
1306 	}
1307 
1308 	intern->ar_flags = (intern->ar_flags & SPL_ARRAY_INT_MASK) | (ar_flags & ~SPL_ARRAY_INT_MASK);
1309 }
1310 /* }}} */
1311 
1312 /* {{{ proto Array|Object ArrayObject::exchangeArray(Array|Object ar = array())
1313    Replace the referenced array or object with a new one and return the old one (right now copy - to be changed) */
SPL_METHOD(Array,exchangeArray)1314 SPL_METHOD(Array, exchangeArray)
1315 {
1316 	zval *object = getThis(), *array;
1317 	spl_array_object *intern = Z_SPLARRAY_P(object);
1318 
1319 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &array) == FAILURE) {
1320 		return;
1321 	}
1322 
1323 	if (intern->nApplyCount > 0) {
1324 		zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
1325 		return;
1326 	}
1327 
1328 	RETVAL_ARR(zend_array_dup(spl_array_get_hash_table(intern)));
1329 	spl_array_set_array(object, intern, array, 0L, 1);
1330 }
1331 /* }}} */
1332 
1333 /* {{{ proto ArrayIterator ArrayObject::getIterator()
1334    Create a new iterator from a ArrayObject instance */
SPL_METHOD(Array,getIterator)1335 SPL_METHOD(Array, getIterator)
1336 {
1337 	zval *object = getThis();
1338 	spl_array_object *intern = Z_SPLARRAY_P(object);
1339 	HashTable *aht = spl_array_get_hash_table(intern);
1340 
1341 	if (zend_parse_parameters_none() == FAILURE) {
1342 		return;
1343 	}
1344 
1345 	if (!aht) {
1346 		php_error_docref(NULL, E_NOTICE, "Array was modified outside object and is no longer an array");
1347 		return;
1348 	}
1349 
1350 	ZVAL_OBJ(return_value, spl_array_object_new_ex(intern->ce_get_iterator, object, 0));
1351 }
1352 /* }}} */
1353 
1354 /* {{{ proto void ArrayIterator::rewind()
1355    Rewind array back to the start */
SPL_METHOD(Array,rewind)1356 SPL_METHOD(Array, rewind)
1357 {
1358 	zval *object = getThis();
1359 	spl_array_object *intern = Z_SPLARRAY_P(object);
1360 
1361 	if (zend_parse_parameters_none() == FAILURE) {
1362 		return;
1363 	}
1364 
1365 	spl_array_rewind(intern);
1366 }
1367 /* }}} */
1368 
1369 /* {{{ proto void ArrayIterator::seek(int $position)
1370    Seek to position. */
SPL_METHOD(Array,seek)1371 SPL_METHOD(Array, seek)
1372 {
1373 	zend_long opos, position;
1374 	zval *object = getThis();
1375 	spl_array_object *intern = Z_SPLARRAY_P(object);
1376 	HashTable *aht = spl_array_get_hash_table(intern);
1377 	int result;
1378 
1379 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &position) == FAILURE) {
1380 		return;
1381 	}
1382 
1383 	if (!aht) {
1384 		php_error_docref(NULL, E_NOTICE, "Array was modified outside object and is no longer an array");
1385 		return;
1386 	}
1387 
1388 	opos = position;
1389 
1390 	if (position >= 0) { /* negative values are not supported */
1391 		spl_array_rewind(intern);
1392 		result = SUCCESS;
1393 
1394 		while (position-- > 0 && (result = spl_array_next(intern)) == SUCCESS);
1395 
1396 		if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, spl_array_get_pos_ptr(aht, intern)) == SUCCESS) {
1397 			return; /* ok */
1398 		}
1399 	}
1400 	zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0, "Seek position " ZEND_LONG_FMT " is out of range", opos);
1401 } /* }}} */
1402 
spl_array_object_count_elements_helper(spl_array_object * intern,zend_long * count)1403 static int spl_array_object_count_elements_helper(spl_array_object *intern, zend_long *count) /* {{{ */
1404 {
1405 	HashTable *aht = spl_array_get_hash_table(intern);
1406 	HashPosition pos, *pos_ptr;
1407 
1408 	if (!aht) {
1409 		php_error_docref(NULL, E_NOTICE, "Array was modified outside object and is no longer an array");
1410 		*count = 0;
1411 		return FAILURE;
1412 	}
1413 
1414 	if (spl_array_is_object(intern)) {
1415 		/* We need to store the 'pos' since we'll modify it in the functions
1416 		 * we're going to call and which do not support 'pos' as parameter. */
1417 		pos_ptr = spl_array_get_pos_ptr(aht, intern);
1418 		pos = *pos_ptr;
1419 		*count = 0;
1420 		spl_array_rewind(intern);
1421 		while (*pos_ptr != HT_INVALID_IDX && spl_array_next(intern) == SUCCESS) {
1422 			(*count)++;
1423 		}
1424 		*pos_ptr = pos;
1425 		return SUCCESS;
1426 	} else {
1427 		*count = zend_hash_num_elements(aht);
1428 		return SUCCESS;
1429 	}
1430 } /* }}} */
1431 
spl_array_object_count_elements(zval * object,zend_long * count)1432 int spl_array_object_count_elements(zval *object, zend_long *count) /* {{{ */
1433 {
1434 	spl_array_object *intern = Z_SPLARRAY_P(object);
1435 
1436 	if (intern->fptr_count) {
1437 		zval rv;
1438 		zend_call_method_with_0_params(object, intern->std.ce, &intern->fptr_count, "count", &rv);
1439 		if (Z_TYPE(rv) != IS_UNDEF) {
1440 			*count = zval_get_long(&rv);
1441 			zval_ptr_dtor(&rv);
1442 			return SUCCESS;
1443 		}
1444 		*count = 0;
1445 		return FAILURE;
1446 	}
1447 	return spl_array_object_count_elements_helper(intern, count);
1448 } /* }}} */
1449 
1450 /* {{{ proto int ArrayObject::count()
1451        proto int ArrayIterator::count()
1452    Return the number of elements in the Iterator. */
SPL_METHOD(Array,count)1453 SPL_METHOD(Array, count)
1454 {
1455 	zend_long count;
1456 	spl_array_object *intern = Z_SPLARRAY_P(getThis());
1457 
1458 	if (zend_parse_parameters_none() == FAILURE) {
1459 		return;
1460 	}
1461 
1462 	spl_array_object_count_elements_helper(intern, &count);
1463 
1464 	RETURN_LONG(count);
1465 } /* }}} */
1466 
spl_array_method(INTERNAL_FUNCTION_PARAMETERS,char * fname,int fname_len,int use_arg)1467 static void spl_array_method(INTERNAL_FUNCTION_PARAMETERS, char *fname, int fname_len, int use_arg) /* {{{ */
1468 {
1469 	spl_array_object *intern = Z_SPLARRAY_P(getThis());
1470 	HashTable *aht = spl_array_get_hash_table(intern);
1471 	zval function_name, params[2], *arg = NULL;
1472 
1473 	ZVAL_STRINGL(&function_name, fname, fname_len);
1474 
1475 	ZVAL_NEW_EMPTY_REF(&params[0]);
1476 	ZVAL_ARR(Z_REFVAL(params[0]), aht);
1477 	GC_REFCOUNT(aht)++;
1478 
1479 	if (!use_arg) {
1480 		intern->nApplyCount++;
1481 		call_user_function_ex(EG(function_table), NULL, &function_name, return_value, 1, params, 1, NULL);
1482 		intern->nApplyCount--;
1483 	} else if (use_arg == SPL_ARRAY_METHOD_MAY_USER_ARG) {
1484 		if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "|z", &arg) == FAILURE) {
1485 			zend_throw_exception(spl_ce_BadMethodCallException, "Function expects one argument at most", 0);
1486 			goto exit;
1487 		}
1488 		if (arg) {
1489 			ZVAL_COPY_VALUE(&params[1], arg);
1490 		}
1491 		intern->nApplyCount++;
1492 		call_user_function_ex(EG(function_table), NULL, &function_name, return_value, arg ? 2 : 1, params, 1, NULL);
1493 		intern->nApplyCount--;
1494 	} else {
1495 		if (ZEND_NUM_ARGS() != 1 || zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "z", &arg) == FAILURE) {
1496 			zend_throw_exception(spl_ce_BadMethodCallException, "Function expects exactly one argument", 0);
1497 			goto exit;
1498 		}
1499 		ZVAL_COPY_VALUE(&params[1], arg);
1500 		intern->nApplyCount++;
1501 		call_user_function_ex(EG(function_table), NULL, &function_name, return_value, 2, params, 1, NULL);
1502 		intern->nApplyCount--;
1503 	}
1504 
1505 exit:
1506 	{
1507 		HashTable *new_ht = Z_ARRVAL_P(Z_REFVAL(params[0]));
1508 		if (aht != new_ht) {
1509 			spl_array_replace_hash_table(intern, new_ht);
1510 		} else {
1511 			GC_REFCOUNT(aht)--;
1512 		}
1513 		efree(Z_REF(params[0]));
1514 		zend_string_free(Z_STR(function_name));
1515 	}
1516 } /* }}} */
1517 
1518 #define SPL_ARRAY_METHOD(cname, fname, use_arg) \
1519 SPL_METHOD(cname, fname) \
1520 { \
1521 	spl_array_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, #fname, sizeof(#fname)-1, use_arg); \
1522 }
1523 
1524 /* {{{ proto int ArrayObject::asort([int $sort_flags = SORT_REGULAR ])
1525        proto int ArrayIterator::asort([int $sort_flags = SORT_REGULAR ])
1526    Sort the entries by values. */
SPL_ARRAY_METHOD(Array,asort,SPL_ARRAY_METHOD_MAY_USER_ARG)1527 SPL_ARRAY_METHOD(Array, asort, SPL_ARRAY_METHOD_MAY_USER_ARG) /* }}} */
1528 
1529 /* {{{ proto int ArrayObject::ksort([int $sort_flags = SORT_REGULAR ])
1530        proto int ArrayIterator::ksort([int $sort_flags = SORT_REGULAR ])
1531    Sort the entries by key. */
1532 SPL_ARRAY_METHOD(Array, ksort, SPL_ARRAY_METHOD_MAY_USER_ARG) /* }}} */
1533 
1534 /* {{{ proto int ArrayObject::uasort(callback cmp_function)
1535        proto int ArrayIterator::uasort(callback cmp_function)
1536    Sort the entries by values user defined function. */
1537 SPL_ARRAY_METHOD(Array, uasort, SPL_ARRAY_METHOD_USE_ARG) /* }}} */
1538 
1539 /* {{{ proto int ArrayObject::uksort(callback cmp_function)
1540        proto int ArrayIterator::uksort(callback cmp_function)
1541    Sort the entries by key using user defined function. */
1542 SPL_ARRAY_METHOD(Array, uksort, SPL_ARRAY_METHOD_USE_ARG) /* }}} */
1543 
1544 /* {{{ proto int ArrayObject::natsort()
1545        proto int ArrayIterator::natsort()
1546    Sort the entries by values using "natural order" algorithm. */
1547 SPL_ARRAY_METHOD(Array, natsort, SPL_ARRAY_METHOD_NO_ARG) /* }}} */
1548 
1549 /* {{{ proto int ArrayObject::natcasesort()
1550        proto int ArrayIterator::natcasesort()
1551    Sort the entries by key using case insensitive "natural order" algorithm. */
1552 SPL_ARRAY_METHOD(Array, natcasesort, SPL_ARRAY_METHOD_NO_ARG) /* }}} */
1553 
1554 /* {{{ proto mixed|NULL ArrayIterator::current()
1555    Return current array entry */
1556 SPL_METHOD(Array, current)
1557 {
1558 	zval *object = getThis();
1559 	spl_array_object *intern = Z_SPLARRAY_P(object);
1560 	zval *entry;
1561 	HashTable *aht = spl_array_get_hash_table(intern);
1562 
1563 	if (zend_parse_parameters_none() == FAILURE) {
1564 		return;
1565 	}
1566 
1567 	if (spl_array_object_verify_pos(intern, aht) == FAILURE) {
1568 		return;
1569 	}
1570 
1571 	if ((entry = zend_hash_get_current_data_ex(aht, spl_array_get_pos_ptr(aht, intern))) == NULL) {
1572 		return;
1573 	}
1574 	if (Z_TYPE_P(entry) == IS_INDIRECT) {
1575 		entry = Z_INDIRECT_P(entry);
1576 		if (Z_TYPE_P(entry) == IS_UNDEF) {
1577 			return;
1578 		}
1579 	}
1580 	ZVAL_DEREF(entry);
1581 	ZVAL_COPY(return_value, entry);
1582 }
1583 /* }}} */
1584 
1585 /* {{{ proto mixed|NULL ArrayIterator::key()
1586    Return current array key */
SPL_METHOD(Array,key)1587 SPL_METHOD(Array, key)
1588 {
1589 	if (zend_parse_parameters_none() == FAILURE) {
1590 		return;
1591 	}
1592 
1593 	spl_array_iterator_key(getThis(), return_value);
1594 } /* }}} */
1595 
spl_array_iterator_key(zval * object,zval * return_value)1596 void spl_array_iterator_key(zval *object, zval *return_value) /* {{{ */
1597 {
1598 	spl_array_object *intern = Z_SPLARRAY_P(object);
1599 	HashTable *aht = spl_array_get_hash_table(intern);
1600 
1601 	if (spl_array_object_verify_pos(intern, aht) == FAILURE) {
1602 		return;
1603 	}
1604 
1605 	zend_hash_get_current_key_zval_ex(aht, return_value, spl_array_get_pos_ptr(aht, intern));
1606 }
1607 /* }}} */
1608 
1609 /* {{{ proto void ArrayIterator::next()
1610    Move to next entry */
SPL_METHOD(Array,next)1611 SPL_METHOD(Array, next)
1612 {
1613 	zval *object = getThis();
1614 	spl_array_object *intern = Z_SPLARRAY_P(object);
1615 	HashTable *aht = spl_array_get_hash_table(intern);
1616 
1617 	if (zend_parse_parameters_none() == FAILURE) {
1618 		return;
1619 	}
1620 
1621 	if (spl_array_object_verify_pos(intern, aht) == FAILURE) {
1622 		return;
1623 	}
1624 
1625 	spl_array_next_ex(intern, aht);
1626 }
1627 /* }}} */
1628 
1629 /* {{{ proto bool ArrayIterator::valid()
1630    Check whether array contains more entries */
SPL_METHOD(Array,valid)1631 SPL_METHOD(Array, valid)
1632 {
1633 	zval *object = getThis();
1634 	spl_array_object *intern = Z_SPLARRAY_P(object);
1635 	HashTable *aht = spl_array_get_hash_table(intern);
1636 
1637 	if (zend_parse_parameters_none() == FAILURE) {
1638 		return;
1639 	}
1640 
1641 	if (spl_array_object_verify_pos(intern, aht) == FAILURE) {
1642 		RETURN_FALSE;
1643 	} else {
1644 		RETURN_BOOL(zend_hash_has_more_elements_ex(aht, spl_array_get_pos_ptr(aht, intern)) == SUCCESS);
1645 	}
1646 }
1647 /* }}} */
1648 
1649 /* {{{ proto bool RecursiveArrayIterator::hasChildren()
1650    Check whether current element has children (e.g. is an array) */
SPL_METHOD(Array,hasChildren)1651 SPL_METHOD(Array, hasChildren)
1652 {
1653 	zval *object = getThis(), *entry;
1654 	spl_array_object *intern = Z_SPLARRAY_P(object);
1655 	HashTable *aht = spl_array_get_hash_table(intern);
1656 
1657 	if (zend_parse_parameters_none() == FAILURE) {
1658 		return;
1659 	}
1660 
1661 	if (spl_array_object_verify_pos(intern, aht) == FAILURE) {
1662 		RETURN_FALSE;
1663 	}
1664 
1665 	if ((entry = zend_hash_get_current_data_ex(aht, spl_array_get_pos_ptr(aht, intern))) == NULL) {
1666 		RETURN_FALSE;
1667 	}
1668 
1669 	if (Z_TYPE_P(entry) == IS_INDIRECT) {
1670 		entry = Z_INDIRECT_P(entry);
1671 	}
1672 
1673 	ZVAL_DEREF(entry);
1674 	RETURN_BOOL(Z_TYPE_P(entry) == IS_ARRAY || (Z_TYPE_P(entry) == IS_OBJECT && (intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) == 0));
1675 }
1676 /* }}} */
1677 
1678 /* {{{ proto object RecursiveArrayIterator::getChildren()
1679    Create a sub iterator for the current element (same class as $this) */
SPL_METHOD(Array,getChildren)1680 SPL_METHOD(Array, getChildren)
1681 {
1682 	zval *object = getThis(), *entry, flags;
1683 	spl_array_object *intern = Z_SPLARRAY_P(object);
1684 	HashTable *aht = spl_array_get_hash_table(intern);
1685 
1686 	if (zend_parse_parameters_none() == FAILURE) {
1687 		return;
1688 	}
1689 
1690 	if (spl_array_object_verify_pos(intern, aht) == FAILURE) {
1691 		return;
1692 	}
1693 
1694 	if ((entry = zend_hash_get_current_data_ex(aht, spl_array_get_pos_ptr(aht, intern))) == NULL) {
1695 		return;
1696 	}
1697 
1698 	if (Z_TYPE_P(entry) == IS_INDIRECT) {
1699 		entry = Z_INDIRECT_P(entry);
1700 	}
1701 
1702 	ZVAL_DEREF(entry);
1703 	if (Z_TYPE_P(entry) == IS_OBJECT) {
1704 		if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) {
1705 			return;
1706 		}
1707 		if (instanceof_function(Z_OBJCE_P(entry), Z_OBJCE_P(getThis()))) {
1708 			ZVAL_OBJ(return_value, Z_OBJ_P(entry));
1709 			Z_ADDREF_P(return_value);
1710 			return;
1711 		}
1712 	}
1713 
1714 	ZVAL_LONG(&flags, intern->ar_flags);
1715 	spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), return_value, entry, &flags);
1716 }
1717 /* }}} */
1718 
1719 /* {{{ proto string ArrayObject::serialize()
1720    Serialize the object */
SPL_METHOD(Array,serialize)1721 SPL_METHOD(Array, serialize)
1722 {
1723 	zval *object = getThis();
1724 	spl_array_object *intern = Z_SPLARRAY_P(object);
1725 	HashTable *aht = spl_array_get_hash_table(intern);
1726 	zval members, flags;
1727 	php_serialize_data_t var_hash;
1728 	smart_str buf = {0};
1729 
1730 	if (zend_parse_parameters_none() == FAILURE) {
1731 		return;
1732 	}
1733 
1734 	if (!aht) {
1735 		php_error_docref(NULL, E_NOTICE, "Array was modified outside object and is no longer an array");
1736 		return;
1737 	}
1738 
1739 	PHP_VAR_SERIALIZE_INIT(var_hash);
1740 
1741 	ZVAL_LONG(&flags, (intern->ar_flags & SPL_ARRAY_CLONE_MASK));
1742 
1743 	/* storage */
1744 	smart_str_appendl(&buf, "x:", 2);
1745 	php_var_serialize(&buf, &flags, &var_hash);
1746 
1747 	if (!(intern->ar_flags & SPL_ARRAY_IS_SELF)) {
1748 		php_var_serialize(&buf, &intern->array, &var_hash);
1749 		smart_str_appendc(&buf, ';');
1750 	}
1751 
1752 	/* members */
1753 	smart_str_appendl(&buf, "m:", 2);
1754 	if (!intern->std.properties) {
1755 		rebuild_object_properties(&intern->std);
1756 	}
1757 
1758 	ZVAL_ARR(&members, intern->std.properties);
1759 
1760 	php_var_serialize(&buf, &members, &var_hash); /* finishes the string */
1761 
1762 	/* done */
1763 	PHP_VAR_SERIALIZE_DESTROY(var_hash);
1764 
1765 	if (buf.s) {
1766 		RETURN_NEW_STR(buf.s);
1767 	}
1768 
1769 	RETURN_NULL();
1770 } /* }}} */
1771 
1772 /* {{{ proto void ArrayObject::unserialize(string serialized)
1773  * unserialize the object
1774  */
SPL_METHOD(Array,unserialize)1775 SPL_METHOD(Array, unserialize)
1776 {
1777 	zval *object = getThis();
1778 	spl_array_object *intern = Z_SPLARRAY_P(object);
1779 
1780 	char *buf;
1781 	size_t buf_len;
1782 	const unsigned char *p, *s;
1783 	php_unserialize_data_t var_hash;
1784 	zval *members, *zflags, *array;
1785 	zend_long flags;
1786 
1787 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) {
1788 		return;
1789 	}
1790 
1791 	if (buf_len == 0) {
1792 		return;
1793 	}
1794 
1795 	if (intern->nApplyCount > 0) {
1796 		zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
1797 		return;
1798 	}
1799 
1800 	/* storage */
1801 	s = p = (const unsigned char*)buf;
1802 	PHP_VAR_UNSERIALIZE_INIT(var_hash);
1803 
1804 	if (*p!= 'x' || *++p != ':') {
1805 		goto outexcept;
1806 	}
1807 	++p;
1808 
1809 	zflags = var_tmp_var(&var_hash);
1810 	if (!php_var_unserialize(zflags, &p, s + buf_len, &var_hash) || Z_TYPE_P(zflags) != IS_LONG) {
1811 		goto outexcept;
1812 	}
1813 
1814 	--p; /* for ';' */
1815 	flags = Z_LVAL_P(zflags);
1816 	/* flags needs to be verified and we also need to verify whether the next
1817 	 * thing we get is ';'. After that we require an 'm' or something else
1818 	 * where 'm' stands for members and anything else should be an array. If
1819 	 * neither 'a' or 'm' follows we have an error. */
1820 
1821 	if (*p != ';') {
1822 		goto outexcept;
1823 	}
1824 	++p;
1825 
1826 	if (flags & SPL_ARRAY_IS_SELF) {
1827 		/* If IS_SELF is used, the flags are not followed by an array/object */
1828 		intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;
1829 		intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;
1830 		zval_ptr_dtor(&intern->array);
1831 		ZVAL_UNDEF(&intern->array);
1832 	} else {
1833 		if (*p!='a' && *p!='O' && *p!='C' && *p!='r') {
1834 			goto outexcept;
1835 		}
1836 
1837 		array = var_tmp_var(&var_hash);
1838 		if (!php_var_unserialize(array, &p, s + buf_len, &var_hash)
1839 				|| (Z_TYPE_P(array) != IS_ARRAY && Z_TYPE_P(array) != IS_OBJECT)) {
1840 			goto outexcept;
1841 		}
1842 
1843 		intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK;
1844 		intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK;
1845 
1846 		if (Z_TYPE_P(array) == IS_ARRAY) {
1847 			zval_ptr_dtor(&intern->array);
1848 			ZVAL_COPY(&intern->array, array);
1849 		} else {
1850 			spl_array_set_array(object, intern, array, 0L, 1);
1851 		}
1852 
1853 		if (*p != ';') {
1854 			goto outexcept;
1855 		}
1856         ++p;
1857 	}
1858 
1859 	/* members */
1860 	if (*p!= 'm' || *++p != ':') {
1861 		goto outexcept;
1862 	}
1863 	++p;
1864 
1865 	members = var_tmp_var(&var_hash);
1866 	if (!php_var_unserialize(members, &p, s + buf_len, &var_hash) || Z_TYPE_P(members) != IS_ARRAY) {
1867 		goto outexcept;
1868 	}
1869 
1870 	/* copy members */
1871 	object_properties_load(&intern->std, Z_ARRVAL_P(members));
1872 
1873 	/* done reading $serialized */
1874 	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1875 	return;
1876 
1877 outexcept:
1878 	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1879 	zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset " ZEND_LONG_FMT " of %zd bytes", (zend_long)((char*)p - buf), buf_len);
1880 	return;
1881 
1882 } /* }}} */
1883 
1884 /* {{{ arginfo and function table */
1885 ZEND_BEGIN_ARG_INFO_EX(arginfo_array___construct, 0, 0, 0)
1886 	ZEND_ARG_INFO(0, input)
1887 	ZEND_ARG_INFO(0, flags)
1888 	ZEND_ARG_INFO(0, iterator_class)
1889 ZEND_END_ARG_INFO()
1890 
1891 /* ArrayIterator::__construct and ArrayObject::__construct have different signatures */
1892 ZEND_BEGIN_ARG_INFO_EX(arginfo_array_iterator___construct, 0, 0, 0)
1893 	ZEND_ARG_INFO(0, array)
1894 	ZEND_ARG_INFO(0, ar_flags)
1895 ZEND_END_ARG_INFO()
1896 
1897 ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetGet, 0, 0, 1)
1898 	ZEND_ARG_INFO(0, index)
1899 ZEND_END_ARG_INFO()
1900 
1901 ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetSet, 0, 0, 2)
1902 	ZEND_ARG_INFO(0, index)
1903 	ZEND_ARG_INFO(0, newval)
1904 ZEND_END_ARG_INFO()
1905 
1906 ZEND_BEGIN_ARG_INFO(arginfo_array_append, 0)
1907 	ZEND_ARG_INFO(0, value)
1908 ZEND_END_ARG_INFO()
1909 
1910 ZEND_BEGIN_ARG_INFO(arginfo_array_seek, 0)
1911 	ZEND_ARG_INFO(0, position)
1912 ZEND_END_ARG_INFO()
1913 
1914 ZEND_BEGIN_ARG_INFO(arginfo_array_exchangeArray, 0)
1915 	ZEND_ARG_INFO(0, array)
1916 ZEND_END_ARG_INFO()
1917 
1918 ZEND_BEGIN_ARG_INFO(arginfo_array_setFlags, 0)
1919 	ZEND_ARG_INFO(0, flags)
1920 ZEND_END_ARG_INFO()
1921 
1922 ZEND_BEGIN_ARG_INFO(arginfo_array_setIteratorClass, 0)
1923 	ZEND_ARG_INFO(0, iteratorClass)
1924 ZEND_END_ARG_INFO()
1925 
1926 ZEND_BEGIN_ARG_INFO(arginfo_array_uXsort, 0)
1927 	ZEND_ARG_INFO(0, cmp_function)
1928 ZEND_END_ARG_INFO();
1929 
1930 ZEND_BEGIN_ARG_INFO(arginfo_array_unserialize, 0)
1931 	ZEND_ARG_INFO(0, serialized)
1932 ZEND_END_ARG_INFO();
1933 
1934 ZEND_BEGIN_ARG_INFO(arginfo_array_void, 0)
1935 ZEND_END_ARG_INFO()
1936 
1937 static const zend_function_entry spl_funcs_ArrayObject[] = {
1938 	SPL_ME(Array, __construct,      arginfo_array___construct,      ZEND_ACC_PUBLIC)
1939 	SPL_ME(Array, offsetExists,     arginfo_array_offsetGet,        ZEND_ACC_PUBLIC)
1940 	SPL_ME(Array, offsetGet,        arginfo_array_offsetGet,        ZEND_ACC_PUBLIC)
1941 	SPL_ME(Array, offsetSet,        arginfo_array_offsetSet,        ZEND_ACC_PUBLIC)
1942 	SPL_ME(Array, offsetUnset,      arginfo_array_offsetGet,        ZEND_ACC_PUBLIC)
1943 	SPL_ME(Array, append,           arginfo_array_append,           ZEND_ACC_PUBLIC)
1944 	SPL_ME(Array, getArrayCopy,     arginfo_array_void,             ZEND_ACC_PUBLIC)
1945 	SPL_ME(Array, count,            arginfo_array_void,             ZEND_ACC_PUBLIC)
1946 	SPL_ME(Array, getFlags,         arginfo_array_void,             ZEND_ACC_PUBLIC)
1947 	SPL_ME(Array, setFlags,         arginfo_array_setFlags,         ZEND_ACC_PUBLIC)
1948 	SPL_ME(Array, asort,            arginfo_array_void,             ZEND_ACC_PUBLIC)
1949 	SPL_ME(Array, ksort,            arginfo_array_void,             ZEND_ACC_PUBLIC)
1950 	SPL_ME(Array, uasort,           arginfo_array_uXsort,           ZEND_ACC_PUBLIC)
1951 	SPL_ME(Array, uksort,           arginfo_array_uXsort,           ZEND_ACC_PUBLIC)
1952 	SPL_ME(Array, natsort,          arginfo_array_void,             ZEND_ACC_PUBLIC)
1953 	SPL_ME(Array, natcasesort,      arginfo_array_void,             ZEND_ACC_PUBLIC)
1954 	SPL_ME(Array, unserialize,      arginfo_array_unserialize,      ZEND_ACC_PUBLIC)
1955 	SPL_ME(Array, serialize,        arginfo_array_void,             ZEND_ACC_PUBLIC)
1956 	/* ArrayObject specific */
1957 	SPL_ME(Array, getIterator,      arginfo_array_void,             ZEND_ACC_PUBLIC)
1958 	SPL_ME(Array, exchangeArray,    arginfo_array_exchangeArray,    ZEND_ACC_PUBLIC)
1959 	SPL_ME(Array, setIteratorClass, arginfo_array_setIteratorClass, ZEND_ACC_PUBLIC)
1960 	SPL_ME(Array, getIteratorClass, arginfo_array_void,             ZEND_ACC_PUBLIC)
1961 	PHP_FE_END
1962 };
1963 
1964 static const zend_function_entry spl_funcs_ArrayIterator[] = {
1965 	SPL_ME(ArrayIterator, __construct, arginfo_array_iterator___construct,      ZEND_ACC_PUBLIC)
1966 	SPL_ME(Array, offsetExists,     arginfo_array_offsetGet,        ZEND_ACC_PUBLIC)
1967 	SPL_ME(Array, offsetGet,        arginfo_array_offsetGet,        ZEND_ACC_PUBLIC)
1968 	SPL_ME(Array, offsetSet,        arginfo_array_offsetSet,        ZEND_ACC_PUBLIC)
1969 	SPL_ME(Array, offsetUnset,      arginfo_array_offsetGet,        ZEND_ACC_PUBLIC)
1970 	SPL_ME(Array, append,           arginfo_array_append,           ZEND_ACC_PUBLIC)
1971 	SPL_ME(Array, getArrayCopy,     arginfo_array_void,             ZEND_ACC_PUBLIC)
1972 	SPL_ME(Array, count,            arginfo_array_void,             ZEND_ACC_PUBLIC)
1973 	SPL_ME(Array, getFlags,         arginfo_array_void,             ZEND_ACC_PUBLIC)
1974 	SPL_ME(Array, setFlags,         arginfo_array_setFlags,         ZEND_ACC_PUBLIC)
1975 	SPL_ME(Array, asort,            arginfo_array_void,             ZEND_ACC_PUBLIC)
1976 	SPL_ME(Array, ksort,            arginfo_array_void,             ZEND_ACC_PUBLIC)
1977 	SPL_ME(Array, uasort,           arginfo_array_uXsort,           ZEND_ACC_PUBLIC)
1978 	SPL_ME(Array, uksort,           arginfo_array_uXsort,           ZEND_ACC_PUBLIC)
1979 	SPL_ME(Array, natsort,          arginfo_array_void,             ZEND_ACC_PUBLIC)
1980 	SPL_ME(Array, natcasesort,      arginfo_array_void,             ZEND_ACC_PUBLIC)
1981 	SPL_ME(Array, unserialize,      arginfo_array_unserialize,      ZEND_ACC_PUBLIC)
1982 	SPL_ME(Array, serialize,        arginfo_array_void,             ZEND_ACC_PUBLIC)
1983 	/* ArrayIterator specific */
1984 	SPL_ME(Array, rewind,           arginfo_array_void,             ZEND_ACC_PUBLIC)
1985 	SPL_ME(Array, current,          arginfo_array_void,             ZEND_ACC_PUBLIC)
1986 	SPL_ME(Array, key,              arginfo_array_void,             ZEND_ACC_PUBLIC)
1987 	SPL_ME(Array, next,             arginfo_array_void,             ZEND_ACC_PUBLIC)
1988 	SPL_ME(Array, valid,            arginfo_array_void,             ZEND_ACC_PUBLIC)
1989 	SPL_ME(Array, seek,             arginfo_array_seek,             ZEND_ACC_PUBLIC)
1990 	PHP_FE_END
1991 };
1992 
1993 static const zend_function_entry spl_funcs_RecursiveArrayIterator[] = {
1994 	SPL_ME(Array, hasChildren,   arginfo_array_void, ZEND_ACC_PUBLIC)
1995 	SPL_ME(Array, getChildren,   arginfo_array_void, ZEND_ACC_PUBLIC)
1996 	PHP_FE_END
1997 };
1998 /* }}} */
1999 
2000 /* {{{ PHP_MINIT_FUNCTION(spl_array) */
PHP_MINIT_FUNCTION(spl_array)2001 PHP_MINIT_FUNCTION(spl_array)
2002 {
2003 	REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
2004 	REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
2005 	REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
2006 	REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
2007 	REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
2008 	memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
2009 
2010 	spl_handler_ArrayObject.offset = XtOffsetOf(spl_array_object, std);
2011 
2012 	spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
2013 	spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
2014 	spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
2015 	spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
2016 	spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
2017 	spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
2018 
2019 	spl_handler_ArrayObject.get_properties = spl_array_get_properties;
2020 	spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
2021 	spl_handler_ArrayObject.get_gc = spl_array_get_gc;
2022 	spl_handler_ArrayObject.read_property = spl_array_read_property;
2023 	spl_handler_ArrayObject.write_property = spl_array_write_property;
2024 	spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
2025 	spl_handler_ArrayObject.has_property = spl_array_has_property;
2026 	spl_handler_ArrayObject.unset_property = spl_array_unset_property;
2027 
2028 	spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
2029 	spl_handler_ArrayObject.dtor_obj = zend_objects_destroy_object;
2030 	spl_handler_ArrayObject.free_obj = spl_array_object_free_storage;
2031 
2032 	REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
2033 	REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
2034 	REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
2035 	REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
2036 	REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
2037 	REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
2038 	memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
2039 	spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
2040 
2041 	REGISTER_SPL_CLASS_CONST_LONG(ArrayObject,   "STD_PROP_LIST",    SPL_ARRAY_STD_PROP_LIST);
2042 	REGISTER_SPL_CLASS_CONST_LONG(ArrayObject,   "ARRAY_AS_PROPS",   SPL_ARRAY_ARRAY_AS_PROPS);
2043 
2044 	REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST",    SPL_ARRAY_STD_PROP_LIST);
2045 	REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS",   SPL_ARRAY_ARRAY_AS_PROPS);
2046 
2047 	REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
2048 	REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
2049 	spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
2050 
2051 	REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
2052 
2053 	return SUCCESS;
2054 }
2055 /* }}} */
2056 
2057 /*
2058  * Local variables:
2059  * tab-width: 4
2060  * c-basic-offset: 4
2061  * End:
2062  * vim600: fdm=marker
2063  * vim: noet sw=4 ts=4
2064  */
2065