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