xref: /PHP-8.2/ext/spl/spl_fixedarray.c (revision 8494058a)
1 /*
2   +----------------------------------------------------------------------+
3   | Copyright (c) The PHP Group                                          |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | https://www.php.net/license/3_01.txt                                 |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Author: Antony Dovgal <tony@daylessday.org>                          |
14   |         Etienne Kneuss <colder@php.net>                              |
15   +----------------------------------------------------------------------+
16 */
17 
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21 
22 #include "php.h"
23 #include "php_ini.h"
24 #include "ext/standard/info.h"
25 #include "zend_exceptions.h"
26 
27 #include "php_spl.h"
28 #include "spl_fixedarray_arginfo.h"
29 #include "spl_functions.h"
30 #include "spl_engine.h"
31 #include "spl_fixedarray.h"
32 #include "spl_exceptions.h"
33 #include "spl_iterators.h"
34 #include "ext/json/php_json.h"
35 
36 zend_object_handlers spl_handler_SplFixedArray;
37 PHPAPI zend_class_entry *spl_ce_SplFixedArray;
38 
39 #ifdef COMPILE_DL_SPL_FIXEDARRAY
40 ZEND_GET_MODULE(spl_fixedarray)
41 #endif
42 
43 /* Check if the object is an instance of a subclass of SplFixedArray that overrides method's implementation.
44  * Expect subclassing SplFixedArray to be rare and check that first. */
45 #define HAS_FIXEDARRAY_ARRAYACCESS_OVERRIDE(object, method) UNEXPECTED((object)->ce != spl_ce_SplFixedArray && (object)->ce->arrayaccess_funcs_ptr->method->common.scope != spl_ce_SplFixedArray)
46 
47 typedef struct _spl_fixedarray {
48 	zend_long size;
49 	/* It is possible to resize this, so this can't be combined with the object */
50 	zval *elements;
51 	/* True if this was modified after the last call to get_properties or the hash table wasn't rebuilt. */
52 	bool                 should_rebuild_properties;
53 	/* If positive, it's a resize within a resize and the value gives the desired size. If -1, it's not. */
54 	zend_long cached_resize;
55 } spl_fixedarray;
56 
57 typedef struct _spl_fixedarray_object {
58 	spl_fixedarray          array;
59 	zend_function          *fptr_count;
60 	zend_object             std;
61 } spl_fixedarray_object;
62 
63 typedef struct _spl_fixedarray_it {
64 	zend_object_iterator intern;
65 	zend_long            current;
66 } spl_fixedarray_it;
67 
spl_fixed_array_from_obj(zend_object * obj)68 static spl_fixedarray_object *spl_fixed_array_from_obj(zend_object *obj)
69 {
70 	return (spl_fixedarray_object*)((char*)(obj) - XtOffsetOf(spl_fixedarray_object, std));
71 }
72 
73 #define Z_SPLFIXEDARRAY_P(zv)  spl_fixed_array_from_obj(Z_OBJ_P((zv)))
74 
75 /* Helps enforce the invariants in debug mode:
76  *   - if size == 0, then elements == NULL
77  *   - if size > 0, then elements != NULL
78  *   - size is not less than 0
79  */
spl_fixedarray_empty(spl_fixedarray * array)80 static bool spl_fixedarray_empty(spl_fixedarray *array)
81 {
82 	if (array->elements) {
83 		ZEND_ASSERT(array->size > 0);
84 		return false;
85 	}
86 	ZEND_ASSERT(array->size == 0);
87 	return true;
88 }
89 
spl_fixedarray_default_ctor(spl_fixedarray * array)90 static void spl_fixedarray_default_ctor(spl_fixedarray *array)
91 {
92 	array->size = 0;
93 	array->elements = NULL;
94 	array->cached_resize = -1;
95 }
96 
97 /* Initializes the range [from, to) to null. Does not dtor existing elements. */
spl_fixedarray_init_elems(spl_fixedarray * array,zend_long from,zend_long to)98 static void spl_fixedarray_init_elems(spl_fixedarray *array, zend_long from, zend_long to)
99 {
100 	ZEND_ASSERT(from <= to);
101 	zval *begin = array->elements + from, *end = array->elements + to;
102 
103 	while (begin != end) {
104 		ZVAL_NULL(begin++);
105 	}
106 }
107 
spl_fixedarray_init_non_empty_struct(spl_fixedarray * array,zend_long size)108 static void spl_fixedarray_init_non_empty_struct(spl_fixedarray *array, zend_long size)
109 {
110 	array->size = 0; /* reset size in case ecalloc() fails */
111 	array->elements = size ? safe_emalloc(size, sizeof(zval), 0) : NULL;
112 	array->size = size;
113 	array->should_rebuild_properties = true;
114 	array->cached_resize = -1;
115 }
116 
spl_fixedarray_init(spl_fixedarray * array,zend_long size)117 static void spl_fixedarray_init(spl_fixedarray *array, zend_long size)
118 {
119 	if (size > 0) {
120 		spl_fixedarray_init_non_empty_struct(array, size);
121 		spl_fixedarray_init_elems(array, 0, size);
122 	} else {
123 		spl_fixedarray_default_ctor(array);
124 	}
125 }
126 
127 /* Copies the range [begin, end) into the fixedarray, beginning at `offset`.
128  * Does not dtor the existing elements.
129  */
spl_fixedarray_copy_range(spl_fixedarray * array,zend_long offset,zval * begin,zval * end)130 static void spl_fixedarray_copy_range(spl_fixedarray *array, zend_long offset, zval *begin, zval *end)
131 {
132 	ZEND_ASSERT(offset >= 0);
133 	ZEND_ASSERT(array->size - offset >= end - begin);
134 
135 	zval *to = &array->elements[offset];
136 	while (begin != end) {
137 		ZVAL_COPY(to++, begin++);
138 	}
139 }
140 
spl_fixedarray_copy_ctor(spl_fixedarray * to,spl_fixedarray * from)141 static void spl_fixedarray_copy_ctor(spl_fixedarray *to, spl_fixedarray *from)
142 {
143 	zend_long size = from->size;
144 	spl_fixedarray_init(to, size);
145 	if (size != 0) {
146 		zval *begin = from->elements, *end = from->elements + size;
147 		spl_fixedarray_copy_range(to, 0, begin, end);
148 	}
149 }
150 
151 /* Destructs the elements in the range [from, to).
152  * Caller is expected to bounds check.
153  */
spl_fixedarray_dtor_range(spl_fixedarray * array,zend_long from,zend_long to)154 static void spl_fixedarray_dtor_range(spl_fixedarray *array, zend_long from, zend_long to)
155 {
156 	array->size = from;
157 	zval *begin = array->elements + from, *end = array->elements + to;
158 	while (begin != end) {
159 		zval_ptr_dtor(begin++);
160 	}
161 }
162 
163 /* Destructs and frees contents but not the array itself.
164  * If you want to re-use the array then you need to re-initialize it.
165  */
spl_fixedarray_dtor(spl_fixedarray * array)166 static void spl_fixedarray_dtor(spl_fixedarray *array)
167 {
168 	if (!spl_fixedarray_empty(array)) {
169 		zval *begin = array->elements, *end = array->elements + array->size;
170 		array->elements = NULL;
171 		array->size = 0;
172 		while (begin != end) {
173 			zval_ptr_dtor(--end);
174 		}
175 		efree(begin);
176 	}
177 }
178 
spl_fixedarray_resize(spl_fixedarray * array,zend_long size)179 static void spl_fixedarray_resize(spl_fixedarray *array, zend_long size)
180 {
181 	if (size == array->size) {
182 		/* nothing to do */
183 		return;
184 	}
185 	array->should_rebuild_properties = true;
186 
187 	/* first initialization */
188 	if (array->size == 0) {
189 		spl_fixedarray_init(array, size);
190 		return;
191 	}
192 
193 	if (UNEXPECTED(array->cached_resize >= 0)) {
194 		/* We're already resizing, so just remember the desired size.
195 		 * The resize will happen later. */
196 		array->cached_resize = size;
197 		return;
198 	}
199 	array->cached_resize = size;
200 
201 	/* clearing the array */
202 	if (size == 0) {
203 		spl_fixedarray_dtor(array);
204 		array->elements = NULL;
205 		array->size = 0;
206 	} else if (size > array->size) {
207 		array->elements = safe_erealloc(array->elements, size, sizeof(zval), 0);
208 		spl_fixedarray_init_elems(array, array->size, size);
209 		array->size = size;
210 	} else { /* size < array->size */
211 		/* Size set in spl_fixedarray_dtor_range() */
212 		spl_fixedarray_dtor_range(array, size, array->size);
213 		array->elements = erealloc(array->elements, sizeof(zval) * size);
214 	}
215 
216 	/* If resized within the destructor, take the last resize command and perform it */
217 	zend_long cached_resize = array->cached_resize;
218 	array->cached_resize = -1;
219 	if (cached_resize != size) {
220 		spl_fixedarray_resize(array, cached_resize);
221 	}
222 }
223 
spl_fixedarray_object_get_gc(zend_object * obj,zval ** table,int * n)224 static HashTable* spl_fixedarray_object_get_gc(zend_object *obj, zval **table, int *n)
225 {
226 	spl_fixedarray_object *intern = spl_fixed_array_from_obj(obj);
227 	HashTable *ht = zend_std_get_properties(obj);
228 
229 	*table = intern->array.elements;
230 	*n = (int)intern->array.size;
231 
232 	return ht;
233 }
234 
spl_fixedarray_object_get_properties(zend_object * obj)235 static HashTable* spl_fixedarray_object_get_properties(zend_object *obj)
236 {
237 	spl_fixedarray_object *intern = spl_fixed_array_from_obj(obj);
238 	HashTable *ht = zend_std_get_properties(obj);
239 
240 	if (!spl_fixedarray_empty(&intern->array)) {
241 		/*
242 		 * Usually, the reference count of the hash table is 1,
243 		 * except during cyclic reference cycles.
244 		 *
245 		 * Maintain the DEBUG invariant that a hash table isn't modified during iteration,
246 		 * and avoid unnecessary work rebuilding a hash table for unmodified properties.
247 		 *
248 		 * See https://github.com/php/php-src/issues/8079 and ext/spl/tests/fixedarray_022.phpt
249 		 * Also see https://github.com/php/php-src/issues/8044 for alternate considered approaches.
250 		 */
251 		if (!intern->array.should_rebuild_properties) {
252 			/* Return the same hash table so that recursion cycle detection works in internal functions. */
253 			return ht;
254 		}
255 		intern->array.should_rebuild_properties = false;
256 
257 		zend_long j = zend_hash_num_elements(ht);
258 
259 		if (GC_REFCOUNT(ht) > 1) {
260 			intern->std.properties = zend_array_dup(ht);
261 			GC_TRY_DELREF(ht);
262 		}
263 		for (zend_long i = 0; i < intern->array.size; i++) {
264 			zend_hash_index_update(ht, i, &intern->array.elements[i]);
265 			Z_TRY_ADDREF(intern->array.elements[i]);
266 		}
267 		if (j > intern->array.size) {
268 			for (zend_long i = intern->array.size; i < j; ++i) {
269 				zend_hash_index_del(ht, i);
270 			}
271 		}
272 		if (HT_IS_PACKED(ht)) {
273 			/* Engine doesn't expet packed array */
274 			zend_hash_packed_to_hash(ht);
275 		}
276 	}
277 
278 	return ht;
279 }
280 
spl_fixedarray_object_free_storage(zend_object * object)281 static void spl_fixedarray_object_free_storage(zend_object *object)
282 {
283 	spl_fixedarray_object *intern = spl_fixed_array_from_obj(object);
284 	spl_fixedarray_dtor(&intern->array);
285 	zend_object_std_dtor(&intern->std);
286 }
287 
spl_fixedarray_object_new_ex(zend_class_entry * class_type,zend_object * orig,bool clone_orig)288 static zend_object *spl_fixedarray_object_new_ex(zend_class_entry *class_type, zend_object *orig, bool clone_orig)
289 {
290 	spl_fixedarray_object *intern;
291 	zend_class_entry      *parent = class_type;
292 	bool                   inherited = false;
293 
294 	intern = zend_object_alloc(sizeof(spl_fixedarray_object), parent);
295 
296 	zend_object_std_init(&intern->std, class_type);
297 	object_properties_init(&intern->std, class_type);
298 
299 	if (orig && clone_orig) {
300 		spl_fixedarray_object *other = spl_fixed_array_from_obj(orig);
301 		spl_fixedarray_copy_ctor(&intern->array, &other->array);
302 	}
303 
304 	while (parent) {
305 		if (parent == spl_ce_SplFixedArray) {
306 			intern->std.handlers = &spl_handler_SplFixedArray;
307 			break;
308 		}
309 
310 		parent = parent->parent;
311 		inherited = true;
312 	}
313 
314 	ZEND_ASSERT(parent);
315 
316 	if (UNEXPECTED(inherited)) {
317 		zend_function *fptr_count = zend_hash_str_find_ptr(&class_type->function_table, "count", sizeof("count") - 1);
318 		if (fptr_count->common.scope == parent) {
319 			fptr_count = NULL;
320 		}
321 		intern->fptr_count = fptr_count;
322 	}
323 
324 	return &intern->std;
325 }
326 
spl_fixedarray_new(zend_class_entry * class_type)327 static zend_object *spl_fixedarray_new(zend_class_entry *class_type)
328 {
329 	return spl_fixedarray_object_new_ex(class_type, NULL, 0);
330 }
331 
spl_fixedarray_object_clone(zend_object * old_object)332 static zend_object *spl_fixedarray_object_clone(zend_object *old_object)
333 {
334 	zend_object *new_object = spl_fixedarray_object_new_ex(old_object->ce, old_object, 1);
335 
336 	zend_objects_clone_members(new_object, old_object);
337 
338 	return new_object;
339 }
340 
spl_offset_convert_to_long(zval * offset)341 static zend_long spl_offset_convert_to_long(zval *offset) /* {{{ */
342 {
343 	try_again:
344 	switch (Z_TYPE_P(offset)) {
345 		case IS_STRING: {
346 			zend_ulong index;
347 			if (ZEND_HANDLE_NUMERIC(Z_STR_P(offset), index)) {
348 				return (zend_long) index;
349 			}
350 			break;
351 		}
352 		case IS_DOUBLE:
353 			return zend_dval_to_lval_safe(Z_DVAL_P(offset));
354 		case IS_LONG:
355 			return Z_LVAL_P(offset);
356 		case IS_FALSE:
357 			return 0;
358 		case IS_TRUE:
359 			return 1;
360 		case IS_REFERENCE:
361 			offset = Z_REFVAL_P(offset);
362 			goto try_again;
363 		case IS_RESOURCE:
364 			zend_use_resource_as_offset(offset);
365 			return Z_RES_HANDLE_P(offset);
366 	}
367 
368 	zend_type_error("Illegal offset type");
369 	return 0;
370 }
371 
spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object * intern,zval * offset)372 static zval *spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object *intern, zval *offset)
373 {
374 	zend_long index;
375 
376 	/* we have to return NULL on error here to avoid memleak because of
377 	 * ZE duplicating uninitialized_zval_ptr */
378 	if (!offset) {
379 		zend_throw_error(NULL, "[] operator not supported for SplFixedArray");
380 		return NULL;
381 	}
382 
383 	index = spl_offset_convert_to_long(offset);
384 	if (EG(exception)) {
385 		return NULL;
386 	}
387 
388 	if (index < 0 || index >= intern->array.size) {
389 		// TODO Change error message and use OutOfBound SPL Exception?
390 		zend_throw_exception(spl_ce_RuntimeException, "Index invalid or out of range", 0);
391 		return NULL;
392 	} else {
393 		return &intern->array.elements[index];
394 	}
395 }
396 
397 static int spl_fixedarray_object_has_dimension(zend_object *object, zval *offset, int check_empty);
398 
spl_fixedarray_object_read_dimension(zend_object * object,zval * offset,int type,zval * rv)399 static zval *spl_fixedarray_object_read_dimension(zend_object *object, zval *offset, int type, zval *rv)
400 {
401 	if (type == BP_VAR_IS && !spl_fixedarray_object_has_dimension(object, offset, 0)) {
402 		return &EG(uninitialized_zval);
403 	}
404 
405 	if (HAS_FIXEDARRAY_ARRAYACCESS_OVERRIDE(object, zf_offsetget)) {
406 		zval tmp;
407 		if (!offset) {
408 			ZVAL_NULL(&tmp);
409 			offset = &tmp;
410 		}
411 		zend_call_known_instance_method_with_1_params(object->ce->arrayaccess_funcs_ptr->zf_offsetget, object, rv, offset);
412 		if (!Z_ISUNDEF_P(rv)) {
413 			return rv;
414 		}
415 		return &EG(uninitialized_zval);
416 	}
417 
418 	spl_fixedarray_object *intern = spl_fixed_array_from_obj(object);
419 	if (type != BP_VAR_IS && type != BP_VAR_R) {
420 		intern->array.should_rebuild_properties = true;
421 	}
422 	return spl_fixedarray_object_read_dimension_helper(intern, offset);
423 }
424 
spl_fixedarray_object_write_dimension_helper(spl_fixedarray_object * intern,zval * offset,zval * value)425 static void spl_fixedarray_object_write_dimension_helper(spl_fixedarray_object *intern, zval *offset, zval *value)
426 {
427 	zend_long index;
428 
429 	if (!offset) {
430 		/* '$array[] = value' syntax is not supported */
431 		zend_throw_error(NULL, "[] operator not supported for SplFixedArray");
432 		return;
433 	}
434 
435 	index = spl_offset_convert_to_long(offset);
436 	if (EG(exception)) {
437 		return;
438 	}
439 
440 	if (index < 0 || index >= intern->array.size) {
441 		// TODO Change error message and use OutOfBound SPL Exception?
442 		zend_throw_exception(spl_ce_RuntimeException, "Index invalid or out of range", 0);
443 		return;
444 	} else {
445 		intern->array.should_rebuild_properties = true;
446 		/* Fix #81429 */
447 		zval *ptr = &(intern->array.elements[index]);
448 		zval tmp;
449 		ZVAL_COPY_VALUE(&tmp, ptr);
450 		ZVAL_COPY_DEREF(ptr, value);
451 		zval_ptr_dtor(&tmp);
452 	}
453 }
454 
spl_fixedarray_object_write_dimension(zend_object * object,zval * offset,zval * value)455 static void spl_fixedarray_object_write_dimension(zend_object *object, zval *offset, zval *value)
456 {
457 	if (HAS_FIXEDARRAY_ARRAYACCESS_OVERRIDE(object, zf_offsetset)) {
458 		zval tmp;
459 
460 		if (!offset) {
461 			ZVAL_NULL(&tmp);
462 			offset = &tmp;
463 		}
464 		zend_call_known_instance_method_with_2_params(object->ce->arrayaccess_funcs_ptr->zf_offsetset, object, NULL, offset, value);
465 		return;
466 	}
467 
468 	spl_fixedarray_object *intern = spl_fixed_array_from_obj(object);
469 	spl_fixedarray_object_write_dimension_helper(intern, offset, value);
470 }
471 
spl_fixedarray_object_unset_dimension_helper(spl_fixedarray_object * intern,zval * offset)472 static void spl_fixedarray_object_unset_dimension_helper(spl_fixedarray_object *intern, zval *offset)
473 {
474 	zend_long index;
475 
476 	index = spl_offset_convert_to_long(offset);
477 	if (EG(exception)) {
478 		return;
479 	}
480 
481 	if (index < 0 || index >= intern->array.size) {
482 		// TODO Change error message and use OutOfBound SPL Exception?
483 		zend_throw_exception(spl_ce_RuntimeException, "Index invalid or out of range", 0);
484 		return;
485 	} else {
486 		intern->array.should_rebuild_properties = true;
487 		zval_ptr_dtor(&(intern->array.elements[index]));
488 		ZVAL_NULL(&intern->array.elements[index]);
489 	}
490 }
491 
spl_fixedarray_object_unset_dimension(zend_object * object,zval * offset)492 static void spl_fixedarray_object_unset_dimension(zend_object *object, zval *offset)
493 {
494 	if (UNEXPECTED(HAS_FIXEDARRAY_ARRAYACCESS_OVERRIDE(object, zf_offsetunset))) {
495 		zend_call_known_instance_method_with_1_params(object->ce->arrayaccess_funcs_ptr->zf_offsetunset, object, NULL, offset);
496 		return;
497 	}
498 
499 	spl_fixedarray_object *intern = spl_fixed_array_from_obj(object);
500 	spl_fixedarray_object_unset_dimension_helper(intern, offset);
501 }
502 
spl_fixedarray_object_has_dimension_helper(spl_fixedarray_object * intern,zval * offset,bool check_empty)503 static bool spl_fixedarray_object_has_dimension_helper(spl_fixedarray_object *intern, zval *offset, bool check_empty)
504 {
505 	zend_long index;
506 
507 	index = spl_offset_convert_to_long(offset);
508 	if (EG(exception)) {
509 		return false;
510 	}
511 
512 	if (index < 0 || index >= intern->array.size) {
513 		return false;
514 	}
515 
516 	if (check_empty) {
517 		return zend_is_true(&intern->array.elements[index]);
518 	}
519 
520 	return Z_TYPE(intern->array.elements[index]) != IS_NULL;
521 }
522 
spl_fixedarray_object_has_dimension(zend_object * object,zval * offset,int check_empty)523 static int spl_fixedarray_object_has_dimension(zend_object *object, zval *offset, int check_empty)
524 {
525 	if (HAS_FIXEDARRAY_ARRAYACCESS_OVERRIDE(object, zf_offsetexists)) {
526 		zval rv;
527 
528 		zend_call_known_instance_method_with_1_params(object->ce->arrayaccess_funcs_ptr->zf_offsetexists, object, &rv, offset);
529 		bool result = zend_is_true(&rv);
530 		zval_ptr_dtor(&rv);
531 		return result;
532 	}
533 
534 	spl_fixedarray_object *intern = spl_fixed_array_from_obj(object);
535 
536 	return spl_fixedarray_object_has_dimension_helper(intern, offset, check_empty);
537 }
538 
spl_fixedarray_object_count_elements(zend_object * object,zend_long * count)539 static zend_result spl_fixedarray_object_count_elements(zend_object *object, zend_long *count)
540 {
541 	spl_fixedarray_object *intern;
542 
543 	intern = spl_fixed_array_from_obj(object);
544 	if (UNEXPECTED(intern->fptr_count)) {
545 		zval rv;
546 		zend_call_known_instance_method_with_0_params(intern->fptr_count, object, &rv);
547 		if (!Z_ISUNDEF(rv)) {
548 			*count = zval_get_long(&rv);
549 			zval_ptr_dtor(&rv);
550 		} else {
551 			*count = 0;
552 		}
553 	} else {
554 		*count = intern->array.size;
555 	}
556 	return SUCCESS;
557 }
558 
PHP_METHOD(SplFixedArray,__construct)559 PHP_METHOD(SplFixedArray, __construct)
560 {
561 	zval *object = ZEND_THIS;
562 	spl_fixedarray_object *intern;
563 	zend_long size = 0;
564 
565 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &size) == FAILURE) {
566 		RETURN_THROWS();
567 	}
568 
569 	if (size < 0) {
570 		zend_argument_value_error(1, "must be greater than or equal to 0");
571 		RETURN_THROWS();
572 	}
573 
574 	intern = Z_SPLFIXEDARRAY_P(object);
575 
576 	if (!spl_fixedarray_empty(&intern->array)) {
577 		/* called __construct() twice, bail out */
578 		return;
579 	}
580 
581 	spl_fixedarray_init(&intern->array, size);
582 }
583 
PHP_METHOD(SplFixedArray,__wakeup)584 PHP_METHOD(SplFixedArray, __wakeup)
585 {
586 	spl_fixedarray_object *intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
587 	HashTable *intern_ht = zend_std_get_properties(Z_OBJ_P(ZEND_THIS));
588 	zval *data;
589 
590 	if (zend_parse_parameters_none() == FAILURE) {
591 		RETURN_THROWS();
592 	}
593 
594 	if (intern->array.size == 0) {
595 		int index = 0;
596 		int size = zend_hash_num_elements(intern_ht);
597 
598 		spl_fixedarray_init(&intern->array, size);
599 
600 		ZEND_HASH_FOREACH_VAL(intern_ht, data) {
601 			ZVAL_COPY(&intern->array.elements[index], data);
602 			index++;
603 		} ZEND_HASH_FOREACH_END();
604 
605 		/* Remove the unserialised properties, since we now have the elements
606 		 * within the spl_fixedarray_object structure. */
607 		zend_hash_clean(intern_ht);
608 	}
609 }
610 
PHP_METHOD(SplFixedArray,__serialize)611 PHP_METHOD(SplFixedArray, __serialize)
612 {
613 	spl_fixedarray_object *intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
614 	zval *current;
615 	zend_string *key;
616 
617 	if (zend_parse_parameters_none() == FAILURE) {
618 		RETURN_THROWS();
619 	}
620 
621 	HashTable *ht = zend_std_get_properties(&intern->std);
622 	uint32_t num_properties = zend_hash_num_elements(ht);
623 	array_init_size(return_value, intern->array.size + num_properties);
624 
625 	/* elements */
626 	for (zend_long i = 0; i < intern->array.size; i++) {
627 		current = &intern->array.elements[i];
628 		zend_hash_next_index_insert(Z_ARRVAL_P(return_value), current);
629 		Z_TRY_ADDREF_P(current);
630 	}
631 
632 	/* members */
633 	ZEND_HASH_FOREACH_STR_KEY_VAL_IND(ht, key, current) {
634 		/* If the properties table was already rebuild, it will also contain the
635 		 * array elements. The array elements are already added in the above loop.
636 		 * We can detect array elements by the fact that their key == NULL. */
637 		if (key != NULL) {
638 			zend_hash_add_new(Z_ARRVAL_P(return_value), key, current);
639 			Z_TRY_ADDREF_P(current);
640 		}
641 	} ZEND_HASH_FOREACH_END();
642 }
643 
PHP_METHOD(SplFixedArray,__unserialize)644 PHP_METHOD(SplFixedArray, __unserialize)
645 {
646 	spl_fixedarray_object *intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
647 	HashTable *data;
648 	zval members_zv, *elem;
649 	zend_string *key;
650 	zend_long size;
651 
652 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "h", &data) == FAILURE) {
653 		RETURN_THROWS();
654 	}
655 
656 	if (intern->array.size == 0) {
657 		size = zend_hash_num_elements(data);
658 		spl_fixedarray_init_non_empty_struct(&intern->array, size);
659 		if (!size) {
660 			return;
661 		}
662 		array_init(&members_zv);
663 
664 		intern->array.size = 0;
665 		ZEND_HASH_FOREACH_STR_KEY_VAL(data, key, elem) {
666 			if (key == NULL) {
667 				ZVAL_COPY(&intern->array.elements[intern->array.size], elem);
668 				intern->array.size++;
669 			} else {
670 				Z_TRY_ADDREF_P(elem);
671 				zend_hash_add(Z_ARRVAL(members_zv), key, elem);
672 			}
673 		} ZEND_HASH_FOREACH_END();
674 
675 		if (intern->array.size != size) {
676 			if (intern->array.size) {
677 				intern->array.elements = erealloc(intern->array.elements, sizeof(zval) * intern->array.size);
678 			} else {
679 				efree(intern->array.elements);
680 				intern->array.elements = NULL;
681 			}
682 		}
683 
684 		object_properties_load(&intern->std, Z_ARRVAL(members_zv));
685 		zval_ptr_dtor(&members_zv);
686 	}
687 }
688 
PHP_METHOD(SplFixedArray,count)689 PHP_METHOD(SplFixedArray, count)
690 {
691 	zval *object = ZEND_THIS;
692 	spl_fixedarray_object *intern;
693 
694 	if (zend_parse_parameters_none() == FAILURE) {
695 		RETURN_THROWS();
696 	}
697 
698 	intern = Z_SPLFIXEDARRAY_P(object);
699 	RETURN_LONG(intern->array.size);
700 }
701 
PHP_METHOD(SplFixedArray,toArray)702 PHP_METHOD(SplFixedArray, toArray)
703 {
704 	spl_fixedarray_object *intern;
705 
706 	if (zend_parse_parameters_none() == FAILURE) {
707 		RETURN_THROWS();
708 	}
709 
710 	intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
711 
712 	if (!spl_fixedarray_empty(&intern->array)) {
713 		array_init(return_value);
714 		for (zend_long i = 0; i < intern->array.size; i++) {
715 			zend_hash_index_update(Z_ARRVAL_P(return_value), i, &intern->array.elements[i]);
716 			Z_TRY_ADDREF(intern->array.elements[i]);
717 		}
718 	} else {
719 		RETURN_EMPTY_ARRAY();
720 	}
721 }
722 
PHP_METHOD(SplFixedArray,fromArray)723 PHP_METHOD(SplFixedArray, fromArray)
724 {
725 	zval *data;
726 	spl_fixedarray array;
727 	spl_fixedarray_object *intern;
728 	int num;
729 	bool save_indexes = 1;
730 
731 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "a|b", &data, &save_indexes) == FAILURE) {
732 		RETURN_THROWS();
733 	}
734 
735 	num = zend_hash_num_elements(Z_ARRVAL_P(data));
736 
737 	if (num > 0 && save_indexes) {
738 		zval *element;
739 		zend_string *str_index;
740 		zend_ulong num_index, max_index = 0;
741 		zend_long tmp;
742 
743 		ZEND_HASH_FOREACH_KEY(Z_ARRVAL_P(data), num_index, str_index) {
744 			if (str_index != NULL || (zend_long)num_index < 0) {
745 				zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "array must contain only positive integer keys");
746 				RETURN_THROWS();
747 			}
748 
749 			if (num_index > max_index) {
750 				max_index = num_index;
751 			}
752 		} ZEND_HASH_FOREACH_END();
753 
754 		tmp = max_index + 1;
755 		if (tmp <= 0) {
756 			zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "integer overflow detected");
757 			RETURN_THROWS();
758 		}
759 		spl_fixedarray_init(&array, tmp);
760 
761 		ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(data), num_index, str_index, element) {
762 			ZVAL_COPY_DEREF(&array.elements[num_index], element);
763 		} ZEND_HASH_FOREACH_END();
764 
765 	} else if (num > 0 && !save_indexes) {
766 		zval *element;
767 		zend_long i = 0;
768 
769 		spl_fixedarray_init(&array, num);
770 
771 		ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(data), element) {
772 			ZVAL_COPY_DEREF(&array.elements[i], element);
773 			i++;
774 		} ZEND_HASH_FOREACH_END();
775 	} else {
776 		spl_fixedarray_init(&array, 0);
777 	}
778 
779 	object_init_ex(return_value, spl_ce_SplFixedArray);
780 
781 	intern = Z_SPLFIXEDARRAY_P(return_value);
782 	intern->array = array;
783 }
784 
PHP_METHOD(SplFixedArray,getSize)785 PHP_METHOD(SplFixedArray, getSize)
786 {
787 	zval *object = ZEND_THIS;
788 	spl_fixedarray_object *intern;
789 
790 	if (zend_parse_parameters_none() == FAILURE) {
791 		RETURN_THROWS();
792 	}
793 
794 	intern = Z_SPLFIXEDARRAY_P(object);
795 	RETURN_LONG(intern->array.size);
796 }
797 
PHP_METHOD(SplFixedArray,setSize)798 PHP_METHOD(SplFixedArray, setSize)
799 {
800 	zval *object = ZEND_THIS;
801 	spl_fixedarray_object *intern;
802 	zend_long size;
803 
804 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &size) == FAILURE) {
805 		RETURN_THROWS();
806 	}
807 
808 	if (size < 0) {
809 		zend_argument_value_error(1, "must be greater than or equal to 0");
810 		RETURN_THROWS();
811 	}
812 
813 	intern = Z_SPLFIXEDARRAY_P(object);
814 
815 	spl_fixedarray_resize(&intern->array, size);
816 	RETURN_TRUE;
817 }
818 
819 /* Returns whether the requested $index exists. */
PHP_METHOD(SplFixedArray,offsetExists)820 PHP_METHOD(SplFixedArray, offsetExists)
821 {
822 	zval                  *zindex;
823 	spl_fixedarray_object  *intern;
824 
825 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zindex) == FAILURE) {
826 		RETURN_THROWS();
827 	}
828 
829 	intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
830 
831 	RETURN_BOOL(spl_fixedarray_object_has_dimension_helper(intern, zindex, 0));
832 }
833 
834 /* Returns the value at the specified $index. */
PHP_METHOD(SplFixedArray,offsetGet)835 PHP_METHOD(SplFixedArray, offsetGet)
836 {
837 	zval *zindex, *value;
838 	spl_fixedarray_object  *intern;
839 
840 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zindex) == FAILURE) {
841 		RETURN_THROWS();
842 	}
843 
844 	intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
845 	value = spl_fixedarray_object_read_dimension_helper(intern, zindex);
846 
847 	if (value) {
848 		RETURN_COPY_DEREF(value);
849 	} else {
850 		RETURN_NULL();
851 	}
852 }
853 
854 /* Sets the value at the specified $index to $newval. */
PHP_METHOD(SplFixedArray,offsetSet)855 PHP_METHOD(SplFixedArray, offsetSet)
856 {
857 	zval                  *zindex, *value;
858 	spl_fixedarray_object  *intern;
859 
860 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) {
861 		RETURN_THROWS();
862 	}
863 
864 	intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
865 	spl_fixedarray_object_write_dimension_helper(intern, zindex, value);
866 
867 }
868 
869 /* Unsets the value at the specified $index. */
PHP_METHOD(SplFixedArray,offsetUnset)870 PHP_METHOD(SplFixedArray, offsetUnset)
871 {
872 	zval                  *zindex;
873 	spl_fixedarray_object  *intern;
874 
875 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zindex) == FAILURE) {
876 		RETURN_THROWS();
877 	}
878 
879 	intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
880 	spl_fixedarray_object_unset_dimension_helper(intern, zindex);
881 
882 }
883 
884 /* Create a new iterator from a SplFixedArray instance. */
PHP_METHOD(SplFixedArray,getIterator)885 PHP_METHOD(SplFixedArray, getIterator)
886 {
887 	if (zend_parse_parameters_none() == FAILURE) {
888 		RETURN_THROWS();
889 	}
890 
891 	zend_create_internal_iterator_zval(return_value, ZEND_THIS);
892 }
893 
PHP_METHOD(SplFixedArray,jsonSerialize)894 PHP_METHOD(SplFixedArray, jsonSerialize)
895 {
896 	ZEND_PARSE_PARAMETERS_NONE();
897 
898 	spl_fixedarray_object *intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
899 	array_init_size(return_value, intern->array.size);
900 	for (zend_long i = 0; i < intern->array.size; i++) {
901 		zend_hash_next_index_insert_new(Z_ARR_P(return_value), &intern->array.elements[i]);
902 		Z_TRY_ADDREF(intern->array.elements[i]);
903 	}
904 }
905 
spl_fixedarray_it_dtor(zend_object_iterator * iter)906 static void spl_fixedarray_it_dtor(zend_object_iterator *iter)
907 {
908 	zval_ptr_dtor(&iter->data);
909 }
910 
spl_fixedarray_it_rewind(zend_object_iterator * iter)911 static void spl_fixedarray_it_rewind(zend_object_iterator *iter)
912 {
913 	((spl_fixedarray_it*)iter)->current = 0;
914 }
915 
spl_fixedarray_it_valid(zend_object_iterator * iter)916 static int spl_fixedarray_it_valid(zend_object_iterator *iter)
917 {
918 	spl_fixedarray_it     *iterator = (spl_fixedarray_it*)iter;
919 	spl_fixedarray_object *object   = Z_SPLFIXEDARRAY_P(&iter->data);
920 
921 	if (iterator->current >= 0 && iterator->current < object->array.size) {
922 		return SUCCESS;
923 	}
924 
925 	return FAILURE;
926 }
927 
spl_fixedarray_it_get_current_data(zend_object_iterator * iter)928 static zval *spl_fixedarray_it_get_current_data(zend_object_iterator *iter)
929 {
930 	zval zindex, *data;
931 	spl_fixedarray_it     *iterator = (spl_fixedarray_it*)iter;
932 	spl_fixedarray_object *object   = Z_SPLFIXEDARRAY_P(&iter->data);
933 
934 	ZVAL_LONG(&zindex, iterator->current);
935 	data = spl_fixedarray_object_read_dimension_helper(object, &zindex);
936 
937 	if (data == NULL) {
938 		data = &EG(uninitialized_zval);
939 	}
940 	return data;
941 }
942 
spl_fixedarray_it_get_current_key(zend_object_iterator * iter,zval * key)943 static void spl_fixedarray_it_get_current_key(zend_object_iterator *iter, zval *key)
944 {
945 	ZVAL_LONG(key, ((spl_fixedarray_it*)iter)->current);
946 }
947 
spl_fixedarray_it_move_forward(zend_object_iterator * iter)948 static void spl_fixedarray_it_move_forward(zend_object_iterator *iter)
949 {
950 	((spl_fixedarray_it*)iter)->current++;
951 }
952 
953 /* iterator handler table */
954 static const zend_object_iterator_funcs spl_fixedarray_it_funcs = {
955 	spl_fixedarray_it_dtor,
956 	spl_fixedarray_it_valid,
957 	spl_fixedarray_it_get_current_data,
958 	spl_fixedarray_it_get_current_key,
959 	spl_fixedarray_it_move_forward,
960 	spl_fixedarray_it_rewind,
961 	NULL,
962 	NULL, /* get_gc */
963 };
964 
spl_fixedarray_get_iterator(zend_class_entry * ce,zval * object,int by_ref)965 zend_object_iterator *spl_fixedarray_get_iterator(zend_class_entry *ce, zval *object, int by_ref)
966 {
967 	spl_fixedarray_it *iterator;
968 
969 	if (by_ref) {
970 		zend_throw_error(NULL, "An iterator cannot be used with foreach by reference");
971 		return NULL;
972 	}
973 
974 	iterator = emalloc(sizeof(spl_fixedarray_it));
975 
976 	zend_iterator_init((zend_object_iterator*)iterator);
977 
978 	ZVAL_OBJ_COPY(&iterator->intern.data, Z_OBJ_P(object));
979 	iterator->intern.funcs = &spl_fixedarray_it_funcs;
980 
981 	return &iterator->intern;
982 }
983 
PHP_MINIT_FUNCTION(spl_fixedarray)984 PHP_MINIT_FUNCTION(spl_fixedarray)
985 {
986 	spl_ce_SplFixedArray = register_class_SplFixedArray(
987 		zend_ce_aggregate, zend_ce_arrayaccess, zend_ce_countable, php_json_serializable_ce);
988 	spl_ce_SplFixedArray->create_object = spl_fixedarray_new;
989 	spl_ce_SplFixedArray->get_iterator = spl_fixedarray_get_iterator;
990 
991 	memcpy(&spl_handler_SplFixedArray, &std_object_handlers, sizeof(zend_object_handlers));
992 
993 	spl_handler_SplFixedArray.offset          = XtOffsetOf(spl_fixedarray_object, std);
994 	spl_handler_SplFixedArray.clone_obj       = spl_fixedarray_object_clone;
995 	spl_handler_SplFixedArray.read_dimension  = spl_fixedarray_object_read_dimension;
996 	spl_handler_SplFixedArray.write_dimension = spl_fixedarray_object_write_dimension;
997 	spl_handler_SplFixedArray.unset_dimension = spl_fixedarray_object_unset_dimension;
998 	spl_handler_SplFixedArray.has_dimension   = spl_fixedarray_object_has_dimension;
999 	spl_handler_SplFixedArray.count_elements  = spl_fixedarray_object_count_elements;
1000 	spl_handler_SplFixedArray.get_properties  = spl_fixedarray_object_get_properties;
1001 	spl_handler_SplFixedArray.get_gc          = spl_fixedarray_object_get_gc;
1002 	spl_handler_SplFixedArray.free_obj        = spl_fixedarray_object_free_storage;
1003 
1004 	return SUCCESS;
1005 }
1006