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