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