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