xref: /PHP-8.3/ext/standard/var.c (revision 53aa53f4)
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    | Authors: Jani Lehtimäki <jkl@njet.net>                               |
14    |          Thies C. Arntzen <thies@thieso.net>                         |
15    |          Sascha Schumann <sascha@schumann.cx>                        |
16    +----------------------------------------------------------------------+
17 */
18 
19 /* {{{ includes */
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <errno.h>
23 #include "php.h"
24 #include "php_string.h"
25 #include "php_var.h"
26 #include "zend_smart_str.h"
27 #include "basic_functions.h"
28 #include "php_incomplete_class.h"
29 #include "zend_enum.h"
30 #include "zend_exceptions.h"
31 /* }}} */
32 
33 struct php_serialize_data {
34 	HashTable ht;
35 	uint32_t n;
36 };
37 
38 #define COMMON (is_ref ? "&" : "")
39 
php_array_element_dump(zval * zv,zend_ulong index,zend_string * key,int level)40 static void php_array_element_dump(zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
41 {
42 	if (key == NULL) { /* numeric key */
43 		php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
44 	} else { /* string key */
45 		php_printf("%*c[\"", level + 1, ' ');
46 		PHPWRITE(ZSTR_VAL(key), ZSTR_LEN(key));
47 		php_printf("\"]=>\n");
48 	}
49 	php_var_dump(zv, level + 2);
50 }
51 /* }}} */
52 
php_object_property_dump(zend_property_info * prop_info,zval * zv,zend_ulong index,zend_string * key,int level)53 static void php_object_property_dump(zend_property_info *prop_info, zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
54 {
55 	const char *prop_name, *class_name;
56 
57 	if (key == NULL) { /* numeric key */
58 		php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
59 	} else { /* string key */
60 		int unmangle = zend_unmangle_property_name(key, &class_name, &prop_name);
61 		php_printf("%*c[", level + 1, ' ');
62 
63 		if (class_name && unmangle == SUCCESS) {
64 			if (class_name[0] == '*') {
65 				php_printf("\"%s\":protected", prop_name);
66 			} else {
67 				php_printf("\"%s\":\"%s\":private", prop_name, class_name);
68 			}
69 		} else {
70 			php_printf("\"");
71 			PHPWRITE(ZSTR_VAL(key), ZSTR_LEN(key));
72 			php_printf("\"");
73 		}
74 		ZEND_PUTS("]=>\n");
75 	}
76 
77 	if (Z_TYPE_P(zv) == IS_UNDEF) {
78 		ZEND_ASSERT(ZEND_TYPE_IS_SET(prop_info->type));
79 		zend_string *type_str = zend_type_to_string(prop_info->type);
80 		php_printf("%*cuninitialized(%s)\n",
81 			level + 1, ' ', ZSTR_VAL(type_str));
82 		zend_string_release(type_str);
83 	} else {
84 		php_var_dump(zv, level + 2);
85 	}
86 }
87 /* }}} */
88 
php_var_dump(zval * struc,int level)89 PHPAPI void php_var_dump(zval *struc, int level) /* {{{ */
90 {
91 	HashTable *myht;
92 	zend_string *class_name;
93 	int is_ref = 0;
94 	zend_ulong num;
95 	zend_string *key;
96 	zval *val;
97 	uint32_t count;
98 
99 	if (level > 1) {
100 		php_printf("%*c", level - 1, ' ');
101 	}
102 
103 again:
104 	switch (Z_TYPE_P(struc)) {
105 		case IS_FALSE:
106 			php_printf("%sbool(false)\n", COMMON);
107 			break;
108 		case IS_TRUE:
109 			php_printf("%sbool(true)\n", COMMON);
110 			break;
111 		case IS_NULL:
112 			php_printf("%sNULL\n", COMMON);
113 			break;
114 		case IS_LONG:
115 			php_printf("%sint(" ZEND_LONG_FMT ")\n", COMMON, Z_LVAL_P(struc));
116 			break;
117 		case IS_DOUBLE:
118 			php_printf_unchecked("%sfloat(%.*H)\n", COMMON, (int) PG(serialize_precision), Z_DVAL_P(struc));
119 			break;
120 		case IS_STRING:
121 			php_printf("%sstring(%zd) \"", COMMON, Z_STRLEN_P(struc));
122 			PHPWRITE(Z_STRVAL_P(struc), Z_STRLEN_P(struc));
123 			PUTS("\"\n");
124 			break;
125 		case IS_ARRAY:
126 			myht = Z_ARRVAL_P(struc);
127 			if (!(GC_FLAGS(myht) & GC_IMMUTABLE)) {
128 				if (GC_IS_RECURSIVE(myht)) {
129 					PUTS("*RECURSION*\n");
130 					return;
131 				}
132 				GC_ADDREF(myht);
133 				GC_PROTECT_RECURSION(myht);
134 			}
135 			count = zend_hash_num_elements(myht);
136 			php_printf("%sarray(%d) {\n", COMMON, count);
137 			ZEND_HASH_FOREACH_KEY_VAL(myht, num, key, val) {
138 				php_array_element_dump(val, num, key, level);
139 			} ZEND_HASH_FOREACH_END();
140 			if (!(GC_FLAGS(myht) & GC_IMMUTABLE)) {
141 				GC_UNPROTECT_RECURSION(myht);
142 				GC_DELREF(myht);
143 			}
144 			if (level > 1) {
145 				php_printf("%*c", level-1, ' ');
146 			}
147 			PUTS("}\n");
148 			break;
149 		case IS_OBJECT: {
150 			zend_class_entry *ce = Z_OBJCE_P(struc);
151 			if (ce->ce_flags & ZEND_ACC_ENUM) {
152 				zval *case_name_zval = zend_enum_fetch_case_name(Z_OBJ_P(struc));
153 				php_printf("%senum(%s::%s)\n", COMMON, ZSTR_VAL(ce->name), Z_STRVAL_P(case_name_zval));
154 				return;
155 			}
156 			zend_object *zobj = Z_OBJ_P(struc);
157 			uint32_t *guard = zend_get_recursion_guard(zobj);
158 			if (ZEND_GUARD_OR_GC_IS_RECURSIVE(guard, DEBUG, zobj)) {
159 				PUTS("*RECURSION*\n");
160 				return;
161 			}
162 			ZEND_GUARD_OR_GC_PROTECT_RECURSION(guard, DEBUG, zobj);
163 
164 			myht = zend_get_properties_for(struc, ZEND_PROP_PURPOSE_DEBUG);
165 			class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc));
166 			php_printf("%sobject(%s)#%d (%d) {\n", COMMON, ZSTR_VAL(class_name), Z_OBJ_HANDLE_P(struc), myht ? zend_array_count(myht) : 0);
167 			zend_string_release_ex(class_name, 0);
168 
169 			if (myht) {
170 				zend_ulong num;
171 				zend_string *key;
172 				zval *val;
173 
174 				ZEND_HASH_FOREACH_KEY_VAL(myht, num, key, val) {
175 					zend_property_info *prop_info = NULL;
176 
177 					if (Z_TYPE_P(val) == IS_INDIRECT) {
178 						val = Z_INDIRECT_P(val);
179 						if (key) {
180 							prop_info = zend_get_typed_property_info_for_slot(Z_OBJ_P(struc), val);
181 						}
182 					}
183 
184 					if (!Z_ISUNDEF_P(val) || prop_info) {
185 						php_object_property_dump(prop_info, val, num, key, level);
186 					}
187 				} ZEND_HASH_FOREACH_END();
188 				zend_release_properties(myht);
189 			}
190 			if (level > 1) {
191 				php_printf("%*c", level-1, ' ');
192 			}
193 			PUTS("}\n");
194 			ZEND_GUARD_OR_GC_UNPROTECT_RECURSION(guard, DEBUG, zobj);
195 			break;
196 		}
197 		case IS_RESOURCE: {
198 			const char *type_name = zend_rsrc_list_get_rsrc_type(Z_RES_P(struc));
199 			php_printf("%sresource(" ZEND_LONG_FMT ") of type (%s)\n", COMMON, Z_RES_P(struc)->handle, type_name ? type_name : "Unknown");
200 			break;
201 		}
202 		case IS_REFERENCE:
203 			//??? hide references with refcount==1 (for compatibility)
204 			if (Z_REFCOUNT_P(struc) > 1) {
205 				is_ref = 1;
206 			}
207 			struc = Z_REFVAL_P(struc);
208 			goto again;
209 			break;
210 		default:
211 			php_printf("%sUNKNOWN:0\n", COMMON);
212 			break;
213 	}
214 }
215 /* }}} */
216 
217 /* {{{ Dumps a string representation of variable to output */
PHP_FUNCTION(var_dump)218 PHP_FUNCTION(var_dump)
219 {
220 	zval *args;
221 	int argc;
222 	int	i;
223 
224 	ZEND_PARSE_PARAMETERS_START(1, -1)
225 		Z_PARAM_VARIADIC('+', args, argc)
226 	ZEND_PARSE_PARAMETERS_END();
227 
228 	for (i = 0; i < argc; i++) {
229 		php_var_dump(&args[i], 1);
230 	}
231 }
232 /* }}} */
233 
zval_array_element_dump(zval * zv,zend_ulong index,zend_string * key,int level)234 static void zval_array_element_dump(zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
235 {
236 	if (key == NULL) { /* numeric key */
237 		php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
238 	} else { /* string key */
239 		php_printf("%*c[\"", level + 1, ' ');
240 		PHPWRITE(ZSTR_VAL(key), ZSTR_LEN(key));
241 		php_printf("\"]=>\n");
242 	}
243 	php_debug_zval_dump(zv, level + 2);
244 }
245 /* }}} */
246 
zval_object_property_dump(zend_property_info * prop_info,zval * zv,zend_ulong index,zend_string * key,int level)247 static void zval_object_property_dump(zend_property_info *prop_info, zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
248 {
249 	const char *prop_name, *class_name;
250 
251 	if (key == NULL) { /* numeric key */
252 		php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
253 	} else { /* string key */
254 		zend_unmangle_property_name(key, &class_name, &prop_name);
255 		php_printf("%*c[", level + 1, ' ');
256 
257 		if (class_name) {
258 			if (class_name[0] == '*') {
259 				php_printf("\"%s\":protected", prop_name);
260 			} else {
261 				php_printf("\"%s\":\"%s\":private", prop_name, class_name);
262 			}
263 		} else {
264 			php_printf("\"%s\"", prop_name);
265 		}
266 		ZEND_PUTS("]=>\n");
267 	}
268 	if (prop_info && Z_TYPE_P(zv) == IS_UNDEF) {
269 		zend_string *type_str = zend_type_to_string(prop_info->type);
270 		php_printf("%*cuninitialized(%s)\n",
271 			level + 1, ' ', ZSTR_VAL(type_str));
272 		zend_string_release(type_str);
273 	} else {
274 		php_debug_zval_dump(zv, level + 2);
275 	}
276 }
277 /* }}} */
278 
php_debug_zval_dump(zval * struc,int level)279 PHPAPI void php_debug_zval_dump(zval *struc, int level) /* {{{ */
280 {
281 	HashTable *myht = NULL;
282 	zend_string *class_name;
283 	zend_ulong index;
284 	zend_string *key;
285 	zval *val;
286 	uint32_t count;
287 
288 	if (level > 1) {
289 		php_printf("%*c", level - 1, ' ');
290 	}
291 
292 	switch (Z_TYPE_P(struc)) {
293 	case IS_FALSE:
294 		PUTS("bool(false)\n");
295 		break;
296 	case IS_TRUE:
297 		PUTS("bool(true)\n");
298 		break;
299 	case IS_NULL:
300 		PUTS("NULL\n");
301 		break;
302 	case IS_LONG:
303 		php_printf("int(" ZEND_LONG_FMT ")\n", Z_LVAL_P(struc));
304 		break;
305 	case IS_DOUBLE:
306 		php_printf_unchecked("float(%.*H)\n", (int) PG(serialize_precision), Z_DVAL_P(struc));
307 		break;
308 	case IS_STRING:
309 		php_printf("string(%zd) \"", Z_STRLEN_P(struc));
310 		PHPWRITE(Z_STRVAL_P(struc), Z_STRLEN_P(struc));
311 		if (Z_REFCOUNTED_P(struc)) {
312 			php_printf("\" refcount(%u)\n", Z_REFCOUNT_P(struc));
313 		} else {
314 			PUTS("\" interned\n");
315 		}
316 		break;
317 	case IS_ARRAY:
318 		myht = Z_ARRVAL_P(struc);
319 		if (!(GC_FLAGS(myht) & GC_IMMUTABLE)) {
320 			if (GC_IS_RECURSIVE(myht)) {
321 				PUTS("*RECURSION*\n");
322 				return;
323 			}
324 			GC_ADDREF(myht);
325 			GC_PROTECT_RECURSION(myht);
326 		}
327 		count = zend_hash_num_elements(myht);
328 		if (Z_REFCOUNTED_P(struc)) {
329 			/* -1 because of ADDREF above. */
330 			php_printf("array(%d) refcount(%u){\n", count, Z_REFCOUNT_P(struc) - 1);
331 		} else {
332 			php_printf("array(%d) interned {\n", count);
333 		}
334 		ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, val) {
335 			zval_array_element_dump(val, index, key, level);
336 		} ZEND_HASH_FOREACH_END();
337 		if (!(GC_FLAGS(myht) & GC_IMMUTABLE)) {
338 			GC_UNPROTECT_RECURSION(myht);
339 			GC_DELREF(myht);
340 		}
341 		if (level > 1) {
342 			php_printf("%*c", level - 1, ' ');
343 		}
344 		PUTS("}\n");
345 		break;
346 	case IS_OBJECT: {
347 		/* Check if this is already recursing on the object before calling zend_get_properties_for,
348 		 * to allow infinite recursion detection to work even if classes return temporary arrays,
349 		 * and to avoid the need to update the properties table in place to reflect the state
350 		 * if the result won't be used. (https://github.com/php/php-src/issues/8044) */
351 		zend_object *zobj = Z_OBJ_P(struc);
352 		uint32_t *guard = zend_get_recursion_guard(zobj);
353 		if (ZEND_GUARD_OR_GC_IS_RECURSIVE(guard, DEBUG, zobj)) {
354 			PUTS("*RECURSION*\n");
355 			return;
356 		}
357 		ZEND_GUARD_OR_GC_PROTECT_RECURSION(guard, DEBUG, zobj);
358 
359 		myht = zend_get_properties_for(struc, ZEND_PROP_PURPOSE_DEBUG);
360 		class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc));
361 		php_printf("object(%s)#%d (%d) refcount(%u){\n", ZSTR_VAL(class_name), Z_OBJ_HANDLE_P(struc), myht ? zend_array_count(myht) : 0, Z_REFCOUNT_P(struc));
362 		zend_string_release_ex(class_name, 0);
363 		if (myht) {
364 			ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, val) {
365 				zend_property_info *prop_info = NULL;
366 
367 				if (Z_TYPE_P(val) == IS_INDIRECT) {
368 					val = Z_INDIRECT_P(val);
369 					if (key) {
370 						prop_info = zend_get_typed_property_info_for_slot(Z_OBJ_P(struc), val);
371 					}
372 				}
373 
374 				if (!Z_ISUNDEF_P(val) || prop_info) {
375 					zval_object_property_dump(prop_info, val, index, key, level);
376 				}
377 			} ZEND_HASH_FOREACH_END();
378 			zend_release_properties(myht);
379 		}
380 		if (level > 1) {
381 			php_printf("%*c", level - 1, ' ');
382 		}
383 		PUTS("}\n");
384 		ZEND_GUARD_OR_GC_UNPROTECT_RECURSION(guard, DEBUG, zobj);
385 		break;
386 	}
387 	case IS_RESOURCE: {
388 		const char *type_name = zend_rsrc_list_get_rsrc_type(Z_RES_P(struc));
389 		php_printf("resource(" ZEND_LONG_FMT ") of type (%s) refcount(%u)\n", Z_RES_P(struc)->handle, type_name ? type_name : "Unknown", Z_REFCOUNT_P(struc));
390 		break;
391 	}
392 	case IS_REFERENCE:
393 		php_printf("reference refcount(%u) {\n", Z_REFCOUNT_P(struc));
394 		php_debug_zval_dump(Z_REFVAL_P(struc), level + 2);
395 		if (level > 1) {
396 			php_printf("%*c", level - 1, ' ');
397 		}
398 		PUTS("}\n");
399 		break;
400 	default:
401 		PUTS("UNKNOWN:0\n");
402 		break;
403 	}
404 }
405 /* }}} */
406 
407 /* {{{ Dumps a string representation of an internal zend value to output. */
PHP_FUNCTION(debug_zval_dump)408 PHP_FUNCTION(debug_zval_dump)
409 {
410 	zval *args;
411 	int argc;
412 	int	i;
413 
414 	ZEND_PARSE_PARAMETERS_START(1, -1)
415 		Z_PARAM_VARIADIC('+', args, argc)
416 	ZEND_PARSE_PARAMETERS_END();
417 
418 	for (i = 0; i < argc; i++) {
419 		php_debug_zval_dump(&args[i], 1);
420 	}
421 }
422 /* }}} */
423 
424 #define buffer_append_spaces(buf, num_spaces) \
425 	do { \
426 		char *tmp_spaces; \
427 		size_t tmp_spaces_len; \
428 		tmp_spaces_len = spprintf(&tmp_spaces, 0,"%*c", num_spaces, ' '); \
429 		smart_str_appendl(buf, tmp_spaces, tmp_spaces_len); \
430 		efree(tmp_spaces); \
431 	} while(0);
432 
php_array_element_export(zval * zv,zend_ulong index,zend_string * key,int level,smart_str * buf)433 static void php_array_element_export(zval *zv, zend_ulong index, zend_string *key, int level, smart_str *buf) /* {{{ */
434 {
435 	if (key == NULL) { /* numeric key */
436 		buffer_append_spaces(buf, level+1);
437 		smart_str_append_long(buf, (zend_long) index);
438 		smart_str_appendl(buf, " => ", 4);
439 
440 	} else { /* string key */
441 		zend_string *tmp_str;
442 		zend_string *ckey = php_addcslashes(key, "'\\", 2);
443 		tmp_str = php_str_to_str(ZSTR_VAL(ckey), ZSTR_LEN(ckey), "\0", 1, "' . \"\\0\" . '", 12);
444 
445 		buffer_append_spaces(buf, level + 1);
446 
447 		smart_str_appendc(buf, '\'');
448 		smart_str_append(buf, tmp_str);
449 		smart_str_appendl(buf, "' => ", 5);
450 
451 		zend_string_free(ckey);
452 		zend_string_free(tmp_str);
453 	}
454 	php_var_export_ex(zv, level + 2, buf);
455 
456 	smart_str_appendc(buf, ',');
457 	smart_str_appendc(buf, '\n');
458 }
459 /* }}} */
460 
php_object_element_export(zval * zv,zend_ulong index,zend_string * key,int level,smart_str * buf)461 static void php_object_element_export(zval *zv, zend_ulong index, zend_string *key, int level, smart_str *buf) /* {{{ */
462 {
463 	buffer_append_spaces(buf, level + 2);
464 	if (key != NULL) {
465 		const char *class_name, *prop_name;
466 		size_t prop_name_len;
467 		zend_string *pname_esc;
468 
469 		zend_unmangle_property_name_ex(key, &class_name, &prop_name, &prop_name_len);
470 		pname_esc = php_addcslashes_str(prop_name, prop_name_len, "'\\", 2);
471 
472 		smart_str_appendc(buf, '\'');
473 		smart_str_append(buf, pname_esc);
474 		smart_str_appendc(buf, '\'');
475 		zend_string_release_ex(pname_esc, 0);
476 	} else {
477 		smart_str_append_long(buf, (zend_long) index);
478 	}
479 	smart_str_appendl(buf, " => ", 4);
480 	php_var_export_ex(zv, level + 2, buf);
481 	smart_str_appendc(buf, ',');
482 	smart_str_appendc(buf, '\n');
483 }
484 /* }}} */
485 
php_var_export_ex(zval * struc,int level,smart_str * buf)486 PHPAPI void php_var_export_ex(zval *struc, int level, smart_str *buf) /* {{{ */
487 {
488 	HashTable *myht;
489 	zend_string *ztmp, *ztmp2;
490 	zend_ulong index;
491 	zend_string *key;
492 	zval *val;
493 
494 again:
495 	switch (Z_TYPE_P(struc)) {
496 		case IS_FALSE:
497 			smart_str_appendl(buf, "false", 5);
498 			break;
499 		case IS_TRUE:
500 			smart_str_appendl(buf, "true", 4);
501 			break;
502 		case IS_NULL:
503 			smart_str_appendl(buf, "NULL", 4);
504 			break;
505 		case IS_LONG:
506 			/* INT_MIN as a literal will be parsed as a float. Emit something like
507 			 * -9223372036854775807-1 to avoid this. */
508 			if (Z_LVAL_P(struc) == ZEND_LONG_MIN) {
509 				smart_str_append_long(buf, ZEND_LONG_MIN+1);
510 				smart_str_appends(buf, "-1");
511 				break;
512 			}
513 			smart_str_append_long(buf, Z_LVAL_P(struc));
514 			break;
515 		case IS_DOUBLE:
516 			smart_str_append_double(
517 				buf, Z_DVAL_P(struc), (int) PG(serialize_precision), /* zero_fraction */ true);
518 			break;
519 		case IS_STRING:
520 			ztmp = php_addcslashes(Z_STR_P(struc), "'\\", 2);
521 			ztmp2 = php_str_to_str(ZSTR_VAL(ztmp), ZSTR_LEN(ztmp), "\0", 1, "' . \"\\0\" . '", 12);
522 
523 			smart_str_appendc(buf, '\'');
524 			smart_str_append(buf, ztmp2);
525 			smart_str_appendc(buf, '\'');
526 
527 			zend_string_free(ztmp);
528 			zend_string_free(ztmp2);
529 			break;
530 		case IS_ARRAY:
531 			myht = Z_ARRVAL_P(struc);
532 			if (!(GC_FLAGS(myht) & GC_IMMUTABLE)) {
533 				if (GC_IS_RECURSIVE(myht)) {
534 					smart_str_appendl(buf, "NULL", 4);
535 					zend_error(E_WARNING, "var_export does not handle circular references");
536 					return;
537 				}
538 				GC_ADDREF(myht);
539 				GC_PROTECT_RECURSION(myht);
540 			}
541 			if (level > 1) {
542 				smart_str_appendc(buf, '\n');
543 				buffer_append_spaces(buf, level - 1);
544 			}
545 			smart_str_appendl(buf, "array (\n", 8);
546 			ZEND_HASH_FOREACH_KEY_VAL(myht, index, key, val) {
547 				php_array_element_export(val, index, key, level, buf);
548 			} ZEND_HASH_FOREACH_END();
549 			if (!(GC_FLAGS(myht) & GC_IMMUTABLE)) {
550 				GC_UNPROTECT_RECURSION(myht);
551 				GC_DELREF(myht);
552 			}
553 			if (level > 1) {
554 				buffer_append_spaces(buf, level - 1);
555 			}
556 			smart_str_appendc(buf, ')');
557 
558 			break;
559 
560 		case IS_OBJECT: {
561 			/* Check if this is already recursing on the object before calling zend_get_properties_for,
562 			 * to allow infinite recursion detection to work even if classes return temporary arrays,
563 			 * and to avoid the need to update the properties table in place to reflect the state
564 			 * if the result won't be used. (https://github.com/php/php-src/issues/8044) */
565 			zend_object *zobj = Z_OBJ_P(struc);
566 			uint32_t *guard = zend_get_recursion_guard(zobj);
567 			if (ZEND_GUARD_OR_GC_IS_RECURSIVE(guard, EXPORT, zobj)) {
568 				smart_str_appendl(buf, "NULL", 4);
569 				zend_error(E_WARNING, "var_export does not handle circular references");
570 				return;
571 			}
572 			ZEND_GUARD_OR_GC_PROTECT_RECURSION(guard, EXPORT, zobj);
573 			myht = zend_get_properties_for(struc, ZEND_PROP_PURPOSE_VAR_EXPORT);
574 			if (level > 1) {
575 				smart_str_appendc(buf, '\n');
576 				buffer_append_spaces(buf, level - 1);
577 			}
578 
579 			zend_class_entry *ce = Z_OBJCE_P(struc);
580 			bool is_enum = ce->ce_flags & ZEND_ACC_ENUM;
581 
582 			/* stdClass has no __set_state method, but can be casted to */
583 			if (ce == zend_standard_class_def) {
584 				smart_str_appendl(buf, "(object) array(\n", 16);
585 			} else {
586 				smart_str_appendc(buf, '\\');
587 				smart_str_append(buf, ce->name);
588 				if (is_enum) {
589 					zend_object *zobj = Z_OBJ_P(struc);
590 					zval *case_name_zval = zend_enum_fetch_case_name(zobj);
591 					smart_str_appendl(buf, "::", 2);
592 					smart_str_append(buf, Z_STR_P(case_name_zval));
593 				} else {
594 					smart_str_appendl(buf, "::__set_state(array(\n", 21);
595 				}
596 			}
597 
598 			if (myht) {
599 				if (!is_enum) {
600 					ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
601 						php_object_element_export(val, index, key, level, buf);
602 					} ZEND_HASH_FOREACH_END();
603 				}
604 				zend_release_properties(myht);
605 			}
606 			ZEND_GUARD_OR_GC_UNPROTECT_RECURSION(guard, EXPORT, zobj);
607 			if (level > 1 && !is_enum) {
608 				buffer_append_spaces(buf, level - 1);
609 			}
610 			if (ce == zend_standard_class_def) {
611 				smart_str_appendc(buf, ')');
612 			} else if (!is_enum) {
613 				smart_str_appendl(buf, "))", 2);
614 			}
615 
616 			break;
617 		}
618 		case IS_REFERENCE:
619 			struc = Z_REFVAL_P(struc);
620 			goto again;
621 			break;
622 		default:
623 			smart_str_appendl(buf, "NULL", 4);
624 			break;
625 	}
626 }
627 /* }}} */
628 
629 /* FOR BC reasons, this will always perform and then print */
php_var_export(zval * struc,int level)630 PHPAPI void php_var_export(zval *struc, int level) /* {{{ */
631 {
632 	smart_str buf = {0};
633 	php_var_export_ex(struc, level, &buf);
634 	smart_str_0(&buf);
635 	PHPWRITE(ZSTR_VAL(buf.s), ZSTR_LEN(buf.s));
636 	smart_str_free(&buf);
637 }
638 /* }}} */
639 
640 /* {{{ Outputs or returns a string representation of a variable */
PHP_FUNCTION(var_export)641 PHP_FUNCTION(var_export)
642 {
643 	zval *var;
644 	bool return_output = 0;
645 	smart_str buf = {0};
646 
647 	ZEND_PARSE_PARAMETERS_START(1, 2)
648 		Z_PARAM_ZVAL(var)
649 		Z_PARAM_OPTIONAL
650 		Z_PARAM_BOOL(return_output)
651 	ZEND_PARSE_PARAMETERS_END();
652 
653 	php_var_export_ex(var, 1, &buf);
654 	smart_str_0 (&buf);
655 
656 	if (return_output) {
657 		RETURN_STR(smart_str_extract(&buf));
658 	} else {
659 		PHPWRITE(ZSTR_VAL(buf.s), ZSTR_LEN(buf.s));
660 		smart_str_free(&buf);
661 	}
662 }
663 /* }}} */
664 
665 static void php_var_serialize_intern(smart_str *buf, zval *struc, php_serialize_data_t var_hash, bool in_rcn_array, bool is_root);
666 
667 /**
668  * @param bool in_rcn_array Whether the element appears in a potentially nested array with RC > 1.
669  */
php_add_var_hash(php_serialize_data_t data,zval * var,bool in_rcn_array)670 static inline zend_long php_add_var_hash(php_serialize_data_t data, zval *var, bool in_rcn_array) /* {{{ */
671 {
672 	zval *zv;
673 	zend_ulong key;
674 	bool is_ref = Z_ISREF_P(var);
675 
676 	data->n += 1;
677 
678 	if (is_ref) {
679 		/* pass */
680 	} else if (Z_TYPE_P(var) != IS_OBJECT) {
681 		return 0;
682 	} else if (!in_rcn_array
683 	 && Z_REFCOUNT_P(var) == 1
684 	 && (Z_OBJ_P(var)->properties == NULL || GC_REFCOUNT(Z_OBJ_P(var)->properties) == 1)) {
685 		return 0;
686 	}
687 
688 	/* References to objects are treated as if the reference didn't exist */
689 	if (is_ref && Z_TYPE_P(Z_REFVAL_P(var)) == IS_OBJECT) {
690 		var = Z_REFVAL_P(var);
691 	}
692 
693 	/* Index for the variable is stored using the numeric value of the pointer to
694 	 * the zend_refcounted struct */
695 	key = (zend_ulong) (uintptr_t) Z_COUNTED_P(var);
696 	zv = zend_hash_index_find(&data->ht, key);
697 
698 	if (zv) {
699 		/* References are only counted once, undo the data->n increment above */
700 		if (is_ref && Z_LVAL_P(zv) != -1) {
701 			data->n -= 1;
702 		}
703 
704 		return Z_LVAL_P(zv);
705 	} else {
706 		zval zv_n;
707 		ZVAL_LONG(&zv_n, data->n);
708 		zend_hash_index_add_new(&data->ht, key, &zv_n);
709 
710 		/* Additionally to the index, we also store the variable, to ensure that it is
711 		 * not destroyed during serialization and its pointer reused. The variable is
712 		 * stored at the numeric value of the pointer + 1, which cannot be the location
713 		 * of another zend_refcounted structure. */
714 		zend_hash_index_add_new(&data->ht, key + 1, var);
715 		Z_ADDREF_P(var);
716 
717 		return 0;
718 	}
719 }
720 /* }}} */
721 
php_var_serialize_long(smart_str * buf,zend_long val)722 static inline void php_var_serialize_long(smart_str *buf, zend_long val) /* {{{ */
723 {
724 	char b[32];
725 	char *s = zend_print_long_to_buf(b + sizeof(b) - 1, val);
726 	size_t l = b + sizeof(b) - 1 - s;
727 	char *res = smart_str_extend(buf, 2 + l + 1);
728 	memcpy(res, "i:", 2);
729 	res += 2;
730 	memcpy(res, s, l);
731 	res[l] = ';';
732 }
733 /* }}} */
734 
php_var_serialize_string(smart_str * buf,char * str,size_t len)735 static inline void php_var_serialize_string(smart_str *buf, char *str, size_t len) /* {{{ */
736 {
737 	char b[32];
738 	char *s = zend_print_long_to_buf(b + sizeof(b) - 1, len);
739 	size_t l = b + sizeof(b) - 1 - s;
740 	char *res = smart_str_extend(buf, 2 + l + 2 + len + 2);
741 	memcpy(res, "s:", 2);
742 	res += 2;
743 	memcpy(res, s, l);
744 	res += l;
745 	memcpy(res, ":\"", 2);
746 	res += 2;
747 	memcpy(res, str, len);
748 	res += len;
749 	memcpy(res, "\";", 2);
750 }
751 /* }}} */
752 
php_var_serialize_class_name(smart_str * buf,zval * struc)753 static inline bool php_var_serialize_class_name(smart_str *buf, zval *struc) /* {{{ */
754 {
755 	char b[32];
756 	PHP_CLASS_ATTRIBUTES;
757 
758 	PHP_SET_CLASS_ATTRIBUTES(struc);
759 	size_t class_name_len = ZSTR_LEN(class_name);
760 	char *s = zend_print_long_to_buf(b + sizeof(b) - 1, class_name_len);
761 	size_t l = b + sizeof(b) - 1 - s;
762 	char *res = smart_str_extend(buf, 2 + l + 2 + class_name_len + 2);
763 	memcpy(res, "O:", 2);
764 	res += 2;
765 	memcpy(res, s, l);
766 	res += l;
767 	memcpy(res, ":\"", 2);
768 	res += 2;
769 	memcpy(res, ZSTR_VAL(class_name), class_name_len);
770 	res += class_name_len;
771 	memcpy(res, "\":", 2);
772 	PHP_CLEANUP_CLASS_ATTRIBUTES();
773 	return incomplete_class;
774 }
775 /* }}} */
776 
php_var_serialize_call_sleep(zend_object * obj,zend_function * fn)777 static HashTable* php_var_serialize_call_sleep(zend_object *obj, zend_function *fn) /* {{{ */
778 {
779 	zval retval;
780 
781 	BG(serialize_lock)++;
782 	zend_call_known_instance_method(fn, obj, &retval, /* param_count */ 0, /* params */ NULL);
783 	BG(serialize_lock)--;
784 
785 	if (Z_ISUNDEF(retval) || EG(exception)) {
786 		zval_ptr_dtor(&retval);
787 		return NULL;
788 	}
789 
790 	if (Z_TYPE(retval) != IS_ARRAY) {
791 		zval_ptr_dtor(&retval);
792 		php_error_docref(NULL, E_WARNING, "%s::__sleep() should return an array only containing the names of instance-variables to serialize", ZSTR_VAL(obj->ce->name));
793 		return NULL;
794 	}
795 
796 	return Z_ARRVAL(retval);
797 }
798 /* }}} */
799 
php_var_serialize_call_magic_serialize(zval * retval,zval * obj)800 static int php_var_serialize_call_magic_serialize(zval *retval, zval *obj) /* {{{ */
801 {
802 	BG(serialize_lock)++;
803 	zend_call_known_instance_method_with_0_params(
804 		Z_OBJCE_P(obj)->__serialize, Z_OBJ_P(obj), retval);
805 	BG(serialize_lock)--;
806 
807 	if (EG(exception)) {
808 		zval_ptr_dtor(retval);
809 		return FAILURE;
810 	}
811 
812 	if (Z_TYPE_P(retval) != IS_ARRAY) {
813 		zval_ptr_dtor(retval);
814 		zend_type_error("%s::__serialize() must return an array", ZSTR_VAL(Z_OBJCE_P(obj)->name));
815 		return FAILURE;
816 	}
817 
818 	return SUCCESS;
819 }
820 /* }}} */
821 
php_var_serialize_try_add_sleep_prop(HashTable * ht,HashTable * props,zend_string * name,zend_string * error_name,zval * struc)822 static int php_var_serialize_try_add_sleep_prop(
823 		HashTable *ht, HashTable *props, zend_string *name, zend_string *error_name, zval *struc) /* {{{ */
824 {
825 	zval *val = zend_hash_find(props, name);
826 	if (val == NULL) {
827 		return FAILURE;
828 	}
829 
830 	if (Z_TYPE_P(val) == IS_INDIRECT) {
831 		val = Z_INDIRECT_P(val);
832 		if (Z_TYPE_P(val) == IS_UNDEF) {
833 			zend_property_info *info = zend_get_typed_property_info_for_slot(Z_OBJ_P(struc), val);
834 			if (info) {
835 				return SUCCESS;
836 			}
837 			return FAILURE;
838 		}
839 	}
840 
841 	if (!zend_hash_add(ht, name, val)) {
842 		php_error_docref(NULL, E_WARNING,
843 			"\"%s\" is returned from __sleep() multiple times", ZSTR_VAL(error_name));
844 		return SUCCESS;
845 	}
846 
847 	Z_TRY_ADDREF_P(val);
848 	return SUCCESS;
849 }
850 /* }}} */
851 
php_var_serialize_get_sleep_props(HashTable * ht,zval * struc,HashTable * sleep_retval)852 static int php_var_serialize_get_sleep_props(
853 		HashTable *ht, zval *struc, HashTable *sleep_retval) /* {{{ */
854 {
855 	zend_class_entry *ce = Z_OBJCE_P(struc);
856 	HashTable *props = zend_get_properties_for(struc, ZEND_PROP_PURPOSE_SERIALIZE);
857 	zval *name_val;
858 	int retval = SUCCESS;
859 
860 	zend_hash_init(ht, zend_hash_num_elements(sleep_retval), NULL, ZVAL_PTR_DTOR, 0);
861 	/* TODO: Rewrite this by fetching the property info instead of trying out different
862 	 * name manglings? */
863 	ZEND_HASH_FOREACH_VAL_IND(sleep_retval, name_val) {
864 		zend_string *name, *tmp_name, *priv_name, *prot_name;
865 
866 		ZVAL_DEREF(name_val);
867 		if (Z_TYPE_P(name_val) != IS_STRING) {
868 			php_error_docref(NULL, E_WARNING,
869 					"%s::__sleep() should return an array only containing the names of instance-variables to serialize",
870 					ZSTR_VAL(ce->name));
871 		}
872 
873 		name = zval_get_tmp_string(name_val, &tmp_name);
874 		if (php_var_serialize_try_add_sleep_prop(ht, props, name, name, struc) == SUCCESS) {
875 			zend_tmp_string_release(tmp_name);
876 			continue;
877 		}
878 
879 		if (EG(exception)) {
880 			zend_tmp_string_release(tmp_name);
881 			retval = FAILURE;
882 			break;
883 		}
884 
885 		priv_name = zend_mangle_property_name(
886 			ZSTR_VAL(ce->name), ZSTR_LEN(ce->name),
887 			ZSTR_VAL(name), ZSTR_LEN(name), ce->type & ZEND_INTERNAL_CLASS);
888 		if (php_var_serialize_try_add_sleep_prop(ht, props, priv_name, name, struc) == SUCCESS) {
889 			zend_tmp_string_release(tmp_name);
890 			zend_string_release(priv_name);
891 			continue;
892 		}
893 		zend_string_release(priv_name);
894 
895 		if (EG(exception)) {
896 			zend_tmp_string_release(tmp_name);
897 			retval = FAILURE;
898 			break;
899 		}
900 
901 		prot_name = zend_mangle_property_name(
902 			"*", 1, ZSTR_VAL(name), ZSTR_LEN(name), ce->type & ZEND_INTERNAL_CLASS);
903 		if (php_var_serialize_try_add_sleep_prop(ht, props, prot_name, name, struc) == SUCCESS) {
904 			zend_tmp_string_release(tmp_name);
905 			zend_string_release(prot_name);
906 			continue;
907 		}
908 		zend_string_release(prot_name);
909 
910 		if (EG(exception)) {
911 			zend_tmp_string_release(tmp_name);
912 			retval = FAILURE;
913 			break;
914 		}
915 
916 		php_error_docref(NULL, E_WARNING,
917 			"\"%s\" returned as member variable from __sleep() but does not exist", ZSTR_VAL(name));
918 		zend_tmp_string_release(tmp_name);
919 	} ZEND_HASH_FOREACH_END();
920 
921 	zend_release_properties(props);
922 	return retval;
923 }
924 /* }}} */
925 
php_var_serialize_nested_data(smart_str * buf,zval * struc,HashTable * ht,uint32_t count,bool incomplete_class,php_serialize_data_t var_hash,bool in_rcn_array)926 static void php_var_serialize_nested_data(smart_str *buf, zval *struc, HashTable *ht, uint32_t count, bool incomplete_class, php_serialize_data_t var_hash, bool in_rcn_array) /* {{{ */
927 {
928 	smart_str_append_unsigned(buf, count);
929 	smart_str_appendl(buf, ":{", 2);
930 	if (count > 0) {
931 		zend_string *key;
932 		zval *data;
933 		zend_ulong index;
934 
935 		ZEND_HASH_FOREACH_KEY_VAL_IND(ht, index, key, data) {
936 			if (incomplete_class && zend_string_equals_literal(key, MAGIC_MEMBER)) {
937 				incomplete_class = 0;
938 				continue;
939 			}
940 
941 			if (!key) {
942 				php_var_serialize_long(buf, index);
943 			} else {
944 				php_var_serialize_string(buf, ZSTR_VAL(key), ZSTR_LEN(key));
945 			}
946 
947 			if (Z_ISREF_P(data) && Z_REFCOUNT_P(data) == 1) {
948 				data = Z_REFVAL_P(data);
949 			}
950 
951 			/* we should still add element even if it's not OK,
952 			 * since we already wrote the length of the array before */
953 			if (Z_TYPE_P(data) == IS_ARRAY) {
954 				if (UNEXPECTED(Z_IS_RECURSIVE_P(data))
955 					|| UNEXPECTED(Z_TYPE_P(struc) == IS_ARRAY && Z_ARR_P(data) == Z_ARR_P(struc))) {
956 					php_add_var_hash(var_hash, struc, in_rcn_array);
957 					smart_str_appendl(buf, "N;", 2);
958 				} else {
959 					if (Z_REFCOUNTED_P(data)) {
960 						Z_PROTECT_RECURSION_P(data);
961 					}
962 					php_var_serialize_intern(buf, data, var_hash, in_rcn_array, false);
963 					if (Z_REFCOUNTED_P(data)) {
964 						Z_UNPROTECT_RECURSION_P(data);
965 					}
966 				}
967 			} else {
968 				php_var_serialize_intern(buf, data, var_hash, in_rcn_array, false);
969 			}
970 		} ZEND_HASH_FOREACH_END();
971 	}
972 	smart_str_appendc(buf, '}');
973 }
974 /* }}} */
975 
php_var_serialize_class(smart_str * buf,zval * struc,HashTable * ht,php_serialize_data_t var_hash)976 static void php_var_serialize_class(smart_str *buf, zval *struc, HashTable *ht, php_serialize_data_t var_hash) /* {{{ */
977 {
978 	HashTable props;
979 
980 	if (php_var_serialize_get_sleep_props(&props, struc, ht) == SUCCESS) {
981 		php_var_serialize_class_name(buf, struc);
982 		php_var_serialize_nested_data(
983 			buf, struc, &props, zend_hash_num_elements(&props), /* incomplete_class */ 0, var_hash, GC_REFCOUNT(&props) > 1);
984 	}
985 	zend_hash_destroy(&props);
986 }
987 /* }}} */
988 
php_var_serialize_intern(smart_str * buf,zval * struc,php_serialize_data_t var_hash,bool in_rcn_array,bool is_root)989 static void php_var_serialize_intern(smart_str *buf, zval *struc, php_serialize_data_t var_hash, bool in_rcn_array, bool is_root) /* {{{ */
990 {
991 	zend_long var_already;
992 	HashTable *myht;
993 
994 	if (EG(exception)) {
995 		return;
996 	}
997 
998 	if (var_hash && (var_already = php_add_var_hash(var_hash, struc, in_rcn_array))) {
999 		if (var_already == -1) {
1000 			/* Reference to an object that failed to serialize, replace with null. */
1001 			smart_str_appendl(buf, "N;", 2);
1002 			return;
1003 		} else if (Z_ISREF_P(struc)) {
1004 			smart_str_appendl(buf, "R:", 2);
1005 			smart_str_append_long(buf, var_already);
1006 			smart_str_appendc(buf, ';');
1007 			return;
1008 		} else if (Z_TYPE_P(struc) == IS_OBJECT) {
1009 			smart_str_appendl(buf, "r:", 2);
1010 			smart_str_append_long(buf, var_already);
1011 			smart_str_appendc(buf, ';');
1012 			return;
1013 		}
1014 	}
1015 
1016 again:
1017 	switch (Z_TYPE_P(struc)) {
1018 		case IS_FALSE:
1019 			smart_str_appendl(buf, "b:0;", 4);
1020 			return;
1021 
1022 		case IS_TRUE:
1023 			smart_str_appendl(buf, "b:1;", 4);
1024 			return;
1025 
1026 		case IS_NULL:
1027 			smart_str_appendl(buf, "N;", 2);
1028 			return;
1029 
1030 		case IS_LONG:
1031 			php_var_serialize_long(buf, Z_LVAL_P(struc));
1032 			return;
1033 
1034 		case IS_DOUBLE: {
1035 			char tmp_str[ZEND_DOUBLE_MAX_LENGTH];
1036 			zend_gcvt(Z_DVAL_P(struc), (int)PG(serialize_precision), '.', 'E', tmp_str);
1037 
1038 			size_t len = strlen(tmp_str);
1039 			char *res = smart_str_extend(buf, 2 + len + 1);
1040 			memcpy(res, "d:", 2);
1041 			res += 2;
1042 			memcpy(res, tmp_str, len);
1043 			res[len] = ';';
1044 			return;
1045 		}
1046 
1047 		case IS_STRING:
1048 			php_var_serialize_string(buf, Z_STRVAL_P(struc), Z_STRLEN_P(struc));
1049 			return;
1050 
1051 		case IS_OBJECT: {
1052 				zend_class_entry *ce = Z_OBJCE_P(struc);
1053 				bool incomplete_class;
1054 				uint32_t count;
1055 
1056 				if (ce->ce_flags & ZEND_ACC_NOT_SERIALIZABLE) {
1057 					zend_throw_exception_ex(NULL, 0, "Serialization of '%s' is not allowed",
1058 						ZSTR_VAL(ce->name));
1059 					return;
1060 				}
1061 
1062 				if (ce->ce_flags & ZEND_ACC_ENUM) {
1063 					PHP_CLASS_ATTRIBUTES;
1064 
1065 					zval *case_name_zval = zend_enum_fetch_case_name(Z_OBJ_P(struc));
1066 
1067 					PHP_SET_CLASS_ATTRIBUTES(struc);
1068 					smart_str_appendl(buf, "E:", 2);
1069 					smart_str_append_unsigned(buf, ZSTR_LEN(class_name) + strlen(":") + Z_STRLEN_P(case_name_zval));
1070 					smart_str_appendl(buf, ":\"", 2);
1071 					smart_str_append(buf, class_name);
1072 					smart_str_appendc(buf, ':');
1073 					smart_str_append(buf, Z_STR_P(case_name_zval));
1074 					smart_str_appendl(buf, "\";", 2);
1075 					PHP_CLEANUP_CLASS_ATTRIBUTES();
1076 					return;
1077 				}
1078 
1079 				if (ce->__serialize) {
1080 					zval retval, obj;
1081 					zend_string *key;
1082 					zval *data;
1083 					zend_ulong index;
1084 
1085 					ZVAL_OBJ_COPY(&obj, Z_OBJ_P(struc));
1086 					if (php_var_serialize_call_magic_serialize(&retval, &obj) == FAILURE) {
1087 						if (!EG(exception)) {
1088 							smart_str_appendl(buf, "N;", 2);
1089 						}
1090 						zval_ptr_dtor(&obj);
1091 						return;
1092 					}
1093 
1094 					php_var_serialize_class_name(buf, &obj);
1095 					smart_str_append_unsigned(buf, zend_hash_num_elements(Z_ARRVAL(retval)));
1096 					smart_str_appendl(buf, ":{", 2);
1097 					ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(retval), index, key, data) {
1098 						if (!key) {
1099 							php_var_serialize_long(buf, index);
1100 						} else {
1101 							php_var_serialize_string(buf, ZSTR_VAL(key), ZSTR_LEN(key));
1102 						}
1103 
1104 						if (Z_ISREF_P(data) && Z_REFCOUNT_P(data) == 1) {
1105 							data = Z_REFVAL_P(data);
1106 						}
1107 						php_var_serialize_intern(buf, data, var_hash, Z_REFCOUNT(retval) > 1, false);
1108 					} ZEND_HASH_FOREACH_END();
1109 					smart_str_appendc(buf, '}');
1110 
1111 					zval_ptr_dtor(&obj);
1112 					zval_ptr_dtor(&retval);
1113 					return;
1114 				}
1115 
1116 				if (ce->serialize != NULL) {
1117 					/* has custom handler */
1118 					unsigned char *serialized_data = NULL;
1119 					size_t serialized_length;
1120 
1121 					if (ce->serialize(struc, &serialized_data, &serialized_length, (zend_serialize_data *)var_hash) == SUCCESS) {
1122 						char b1[32], b2[32];
1123 						char *s1 = zend_print_long_to_buf(b1 + sizeof(b1) - 1, ZSTR_LEN(Z_OBJCE_P(struc)->name));
1124 						size_t l1 = b1 + sizeof(b1) - 1 - s1;
1125 						char *s2 = zend_print_long_to_buf(b2 + sizeof(b2) - 1, serialized_length);
1126 						size_t l2 = b2 + sizeof(b2) - 1 - s2;
1127 						char *res = smart_str_extend(buf, 2 + l1 + 2 + ZSTR_LEN(Z_OBJCE_P(struc)->name) + 2 + l2 + 2 + serialized_length + 1);
1128 						memcpy(res, "C:", 2);
1129 						res += 2;
1130 						memcpy(res, s1, l1);
1131 						res += l1;
1132 						memcpy(res, ":\"", 2);
1133 						res += 2;
1134 						memcpy(res, ZSTR_VAL(Z_OBJCE_P(struc)->name), ZSTR_LEN(Z_OBJCE_P(struc)->name));
1135 						res += ZSTR_LEN(Z_OBJCE_P(struc)->name);
1136 						memcpy(res, "\":", 2);
1137 						res += 2;
1138 
1139 						memcpy(res, s2, l2);
1140 						res += l2;
1141 						memcpy(res, ":{", 2);
1142 						res += 2;
1143 						memcpy(res, (char *) serialized_data, serialized_length);
1144 						res[serialized_length] = '}';
1145 					} else {
1146 						/* Mark this value in the var_hash, to avoid creating references to it. */
1147 						zval *var_idx = zend_hash_index_find(&var_hash->ht,
1148 							(zend_ulong) (uintptr_t) Z_COUNTED_P(struc));
1149 						if (var_idx) {
1150 							ZVAL_LONG(var_idx, -1);
1151 						}
1152 						smart_str_appendl(buf, "N;", 2);
1153 					}
1154 					if (serialized_data) {
1155 						efree(serialized_data);
1156 					}
1157 					return;
1158 				}
1159 
1160 				if (ce != PHP_IC_ENTRY) {
1161 					zval *zv = zend_hash_find_known_hash(&ce->function_table, ZSTR_KNOWN(ZEND_STR_SLEEP));
1162 
1163 					if (zv) {
1164 						HashTable *ht;
1165 						zval tmp;
1166 
1167 						ZVAL_OBJ_COPY(&tmp, Z_OBJ_P(struc));
1168 						if (!(ht = php_var_serialize_call_sleep(Z_OBJ(tmp), Z_FUNC_P(zv)))) {
1169 							if (!EG(exception)) {
1170 								/* we should still add element even if it's not OK,
1171 								 * since we already wrote the length of the array before */
1172 								smart_str_appendl(buf, "N;", 2);
1173 							}
1174 							OBJ_RELEASE(Z_OBJ(tmp));
1175 							return;
1176 						}
1177 
1178 						php_var_serialize_class(buf, &tmp, ht, var_hash);
1179 						zend_array_release(ht);
1180 						OBJ_RELEASE(Z_OBJ(tmp));
1181 						return;
1182 					}
1183 				}
1184 
1185 				incomplete_class = php_var_serialize_class_name(buf, struc);
1186 
1187 				if (Z_OBJ_P(struc)->properties == NULL
1188 				 && Z_OBJ_HT_P(struc)->get_properties_for == NULL
1189 				 && Z_OBJ_HT_P(struc)->get_properties == zend_std_get_properties) {
1190 					/* Optimized version without rebulding properties HashTable */
1191 					zend_object *obj = Z_OBJ_P(struc);
1192 					zend_class_entry *ce = obj->ce;
1193 					zend_property_info *prop_info;
1194 					zval *prop;
1195 					int i;
1196 
1197 					count = ce->default_properties_count;
1198 					for (i = 0; i < ce->default_properties_count; i++) {
1199 						prop_info = ce->properties_info_table[i];
1200 						if (!prop_info) {
1201 							count--;
1202 							continue;
1203 						}
1204 						prop = OBJ_PROP(obj, prop_info->offset);
1205 						if (Z_TYPE_P(prop) == IS_UNDEF) {
1206 							count--;
1207 							continue;
1208 						}
1209 					}
1210 					if (count) {
1211 						smart_str_append_unsigned(buf, count);
1212 						smart_str_appendl(buf, ":{", 2);
1213 						for (i = 0; i < ce->default_properties_count; i++) {
1214 							prop_info = ce->properties_info_table[i];
1215 							if (!prop_info) {
1216 								continue;
1217 							}
1218 							prop = OBJ_PROP(obj, prop_info->offset);
1219 							if (Z_TYPE_P(prop) == IS_UNDEF) {
1220 								continue;
1221 							}
1222 
1223 							php_var_serialize_string(buf, ZSTR_VAL(prop_info->name), ZSTR_LEN(prop_info->name));
1224 
1225 							if (Z_ISREF_P(prop) && Z_REFCOUNT_P(prop) == 1) {
1226 								prop = Z_REFVAL_P(prop);
1227 							}
1228 
1229 							php_var_serialize_intern(buf, prop, var_hash, false, false);
1230 						}
1231 						smart_str_appendc(buf, '}');
1232 					} else {
1233 						smart_str_appendl(buf, "0:{}", 4);
1234 					}
1235 					return;
1236 				}
1237 				myht = zend_get_properties_for(struc, ZEND_PROP_PURPOSE_SERIALIZE);
1238 				/* count after serializing name, since php_var_serialize_class_name
1239 				 * changes the count if the variable is incomplete class */
1240 				count = zend_array_count(myht);
1241 				if (count > 0 && incomplete_class) {
1242 					--count;
1243 				}
1244 				php_var_serialize_nested_data(buf, struc, myht, count, incomplete_class, var_hash, GC_REFCOUNT(myht) > 1);
1245 				zend_release_properties(myht);
1246 				return;
1247 			}
1248 		case IS_ARRAY:
1249 			smart_str_appendl(buf, "a:", 2);
1250 			myht = Z_ARRVAL_P(struc);
1251 			php_var_serialize_nested_data(
1252 				buf, struc, myht, zend_array_count(myht), /* incomplete_class */ 0, var_hash,
1253 					!is_root && (in_rcn_array || GC_REFCOUNT(myht) > 1));
1254 			return;
1255 		case IS_REFERENCE:
1256 			struc = Z_REFVAL_P(struc);
1257 			goto again;
1258 		default:
1259 			smart_str_appendl(buf, "i:0;", 4);
1260 			return;
1261 	}
1262 }
1263 /* }}} */
1264 
php_var_serialize(smart_str * buf,zval * struc,php_serialize_data_t * data)1265 PHPAPI void php_var_serialize(smart_str *buf, zval *struc, php_serialize_data_t *data) /* {{{ */
1266 {
1267 	php_var_serialize_intern(buf, struc, *data, false, true);
1268 	smart_str_0(buf);
1269 }
1270 /* }}} */
1271 
php_var_serialize_init(void)1272 PHPAPI php_serialize_data_t php_var_serialize_init(void) {
1273 	struct php_serialize_data *d;
1274 	/* fprintf(stderr, "SERIALIZE_INIT      == lock: %u, level: %u\n", BG(serialize_lock), BG(serialize).level); */
1275 	if (BG(serialize_lock) || !BG(serialize).level) {
1276 		d = emalloc(sizeof(struct php_serialize_data));
1277 		zend_hash_init(&d->ht, 16, NULL, ZVAL_PTR_DTOR, 0);
1278 		d->n = 0;
1279 		if (!BG(serialize_lock)) {
1280 			BG(serialize).data = d;
1281 			BG(serialize).level = 1;
1282 		}
1283 	} else {
1284 		d = BG(serialize).data;
1285 		++BG(serialize).level;
1286 	}
1287 	return d;
1288 }
1289 
php_var_serialize_destroy(php_serialize_data_t d)1290 PHPAPI void php_var_serialize_destroy(php_serialize_data_t d) {
1291 	/* fprintf(stderr, "SERIALIZE_DESTROY   == lock: %u, level: %u\n", BG(serialize_lock), BG(serialize).level); */
1292 	if (BG(serialize_lock) || BG(serialize).level == 1) {
1293 		zend_hash_destroy(&d->ht);
1294 		efree(d);
1295 	}
1296 	if (!BG(serialize_lock) && !--BG(serialize).level) {
1297 		BG(serialize).data = NULL;
1298 	}
1299 }
1300 
1301 /* {{{ Returns a string representation of variable (which can later be unserialized) */
PHP_FUNCTION(serialize)1302 PHP_FUNCTION(serialize)
1303 {
1304 	zval *struc;
1305 	php_serialize_data_t var_hash;
1306 	smart_str buf = {0};
1307 
1308 	ZEND_PARSE_PARAMETERS_START(1, 1)
1309 		Z_PARAM_ZVAL(struc)
1310 	ZEND_PARSE_PARAMETERS_END();
1311 
1312 	PHP_VAR_SERIALIZE_INIT(var_hash);
1313 	php_var_serialize(&buf, struc, &var_hash);
1314 	PHP_VAR_SERIALIZE_DESTROY(var_hash);
1315 
1316 	if (EG(exception)) {
1317 		smart_str_free(&buf);
1318 		RETURN_THROWS();
1319 	}
1320 
1321 	RETURN_STR(smart_str_extract(&buf));
1322 }
1323 /* }}} */
1324 
1325 /* {{{ Takes a string representation of variable and recreates it, subject to the optional unserialize options HashTable */
php_unserialize_with_options(zval * return_value,const char * buf,const size_t buf_len,HashTable * options,const char * function_name)1326 PHPAPI void php_unserialize_with_options(zval *return_value, const char *buf, const size_t buf_len, HashTable *options, const char* function_name)
1327 {
1328 	const unsigned char *p;
1329 	php_unserialize_data_t var_hash;
1330 	zval *retval;
1331 	HashTable *class_hash = NULL, *prev_class_hash;
1332 	zend_long prev_max_depth, prev_cur_depth;
1333 
1334 	if (buf_len == 0) {
1335 		RETURN_FALSE;
1336 	}
1337 
1338 	p = (const unsigned char*) buf;
1339 	PHP_VAR_UNSERIALIZE_INIT(var_hash);
1340 
1341 	prev_class_hash = php_var_unserialize_get_allowed_classes(var_hash);
1342 	prev_max_depth = php_var_unserialize_get_max_depth(var_hash);
1343 	prev_cur_depth = php_var_unserialize_get_cur_depth(var_hash);
1344 	if (options != NULL) {
1345 		zval *classes, *max_depth;
1346 
1347 		classes = zend_hash_str_find_deref(options, "allowed_classes", sizeof("allowed_classes")-1);
1348 		if (classes && Z_TYPE_P(classes) != IS_ARRAY && Z_TYPE_P(classes) != IS_TRUE && Z_TYPE_P(classes) != IS_FALSE) {
1349 			zend_type_error("%s(): Option \"allowed_classes\" must be of type array|bool, %s given", function_name, zend_zval_value_name(classes));
1350 			goto cleanup;
1351 		}
1352 
1353 		if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {
1354 			ALLOC_HASHTABLE(class_hash);
1355 			zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);
1356 		}
1357 		if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {
1358 			zval *entry;
1359 			zend_string *lcname;
1360 
1361 			ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {
1362 				convert_to_string(entry);
1363 				lcname = zend_string_tolower(Z_STR_P(entry));
1364 				zend_hash_add_empty_element(class_hash, lcname);
1365 		        zend_string_release_ex(lcname, 0);
1366 			} ZEND_HASH_FOREACH_END();
1367 
1368 			/* Exception during string conversion. */
1369 			if (EG(exception)) {
1370 				goto cleanup;
1371 			}
1372 		}
1373 		php_var_unserialize_set_allowed_classes(var_hash, class_hash);
1374 
1375 		max_depth = zend_hash_str_find_deref(options, "max_depth", sizeof("max_depth") - 1);
1376 		if (max_depth) {
1377 			if (Z_TYPE_P(max_depth) != IS_LONG) {
1378 				zend_type_error("%s(): Option \"max_depth\" must be of type int, %s given", function_name, zend_zval_value_name(max_depth));
1379 				goto cleanup;
1380 			}
1381 			if (Z_LVAL_P(max_depth) < 0) {
1382 				zend_value_error("%s(): Option \"max_depth\" must be greater than or equal to 0", function_name);
1383 				goto cleanup;
1384 			}
1385 
1386 			php_var_unserialize_set_max_depth(var_hash, Z_LVAL_P(max_depth));
1387 			/* If the max_depth for a nested unserialize() call has been overridden,
1388 			 * start counting from zero again (for the nested call only). */
1389 			php_var_unserialize_set_cur_depth(var_hash, 0);
1390 		}
1391 	}
1392 
1393 	if (BG(unserialize).level > 1) {
1394 		retval = var_tmp_var(&var_hash);
1395 	} else {
1396 		retval = return_value;
1397 	}
1398 	if (!php_var_unserialize(retval, &p, p + buf_len, &var_hash)) {
1399 		if (!EG(exception)) {
1400 			php_error_docref(NULL, E_WARNING, "Error at offset " ZEND_LONG_FMT " of %zd bytes",
1401 				(zend_long)((char*)p - buf), buf_len);
1402 		}
1403 		if (BG(unserialize).level <= 1) {
1404 			zval_ptr_dtor(return_value);
1405 		}
1406 		RETVAL_FALSE;
1407 	} else {
1408 		if ((char*)p < buf + buf_len) {
1409 			if (!EG(exception)) {
1410 				php_error_docref(NULL, E_WARNING, "Extra data starting at offset " ZEND_LONG_FMT " of %zd bytes",
1411 					(zend_long)((char*)p - buf), buf_len);
1412 			}
1413 		}
1414 		if (BG(unserialize).level > 1) {
1415 			ZVAL_COPY(return_value, retval);
1416 		} else if (Z_REFCOUNTED_P(return_value)) {
1417 			zend_refcounted *ref = Z_COUNTED_P(return_value);
1418 			gc_check_possible_root(ref);
1419 		}
1420 	}
1421 
1422 cleanup:
1423 	if (class_hash) {
1424 		zend_hash_destroy(class_hash);
1425 		FREE_HASHTABLE(class_hash);
1426 	}
1427 
1428 	/* Reset to previous options in case this is a nested call */
1429 	php_var_unserialize_set_allowed_classes(var_hash, prev_class_hash);
1430 	php_var_unserialize_set_max_depth(var_hash, prev_max_depth);
1431 	php_var_unserialize_set_cur_depth(var_hash, prev_cur_depth);
1432 	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1433 
1434 	/* Per calling convention we must not return a reference here, so unwrap. We're doing this at
1435 	 * the very end, because __wakeup() calls performed during UNSERIALIZE_DESTROY might affect
1436 	 * the value we unwrap here. This is compatible with behavior in PHP <=7.0. */
1437 	if (Z_ISREF_P(return_value)) {
1438 		zend_unwrap_reference(return_value);
1439 	}
1440 }
1441 /* }}} */
1442 
1443 /* {{{ Takes a string representation of variable and recreates it */
PHP_FUNCTION(unserialize)1444 PHP_FUNCTION(unserialize)
1445 {
1446 	char *buf = NULL;
1447 	size_t buf_len;
1448 	HashTable *options = NULL;
1449 
1450 	ZEND_PARSE_PARAMETERS_START(1, 2)
1451 		Z_PARAM_STRING(buf, buf_len)
1452 		Z_PARAM_OPTIONAL
1453 		Z_PARAM_ARRAY_HT(options)
1454 	ZEND_PARSE_PARAMETERS_END();
1455 
1456 	php_unserialize_with_options(return_value, buf, buf_len, options, "unserialize");
1457 }
1458 /* }}} */
1459 
1460 /* {{{ Returns the allocated by PHP memory */
PHP_FUNCTION(memory_get_usage)1461 PHP_FUNCTION(memory_get_usage) {
1462 	bool real_usage = 0;
1463 
1464 	ZEND_PARSE_PARAMETERS_START(0, 1)
1465 		Z_PARAM_OPTIONAL
1466 		Z_PARAM_BOOL(real_usage)
1467 	ZEND_PARSE_PARAMETERS_END();
1468 
1469 	RETURN_LONG(zend_memory_usage(real_usage));
1470 }
1471 /* }}} */
1472 
1473 /* {{{ Returns the peak allocated by PHP memory */
PHP_FUNCTION(memory_get_peak_usage)1474 PHP_FUNCTION(memory_get_peak_usage) {
1475 	bool real_usage = 0;
1476 
1477 	ZEND_PARSE_PARAMETERS_START(0, 1)
1478 		Z_PARAM_OPTIONAL
1479 		Z_PARAM_BOOL(real_usage)
1480 	ZEND_PARSE_PARAMETERS_END();
1481 
1482 	RETURN_LONG(zend_memory_peak_usage(real_usage));
1483 }
1484 /* }}} */
1485 
1486 /* {{{ Resets the peak PHP memory usage */
PHP_FUNCTION(memory_reset_peak_usage)1487 PHP_FUNCTION(memory_reset_peak_usage) {
1488 	ZEND_PARSE_PARAMETERS_NONE();
1489 
1490 	zend_memory_reset_peak_usage();
1491 }
1492 /* }}} */
1493 
1494 PHP_INI_BEGIN()
1495 	STD_PHP_INI_ENTRY("unserialize_max_depth", "4096", PHP_INI_ALL, OnUpdateLong, unserialize_max_depth, php_basic_globals, basic_globals)
PHP_INI_END()1496 PHP_INI_END()
1497 
1498 PHP_MINIT_FUNCTION(var)
1499 {
1500 	REGISTER_INI_ENTRIES();
1501 	return SUCCESS;
1502 }
1503