xref: /PHP-8.2/Zend/zend.c (revision c149b4f5)
1 /*
2    +----------------------------------------------------------------------+
3    | Zend Engine                                                          |
4    +----------------------------------------------------------------------+
5    | Copyright (c) Zend Technologies Ltd. (http://www.zend.com)           |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 2.00 of the Zend license,     |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.zend.com/license/2_00.txt.                                |
11    | If you did not receive a copy of the Zend license and are unable to  |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@zend.com so we can mail you a copy immediately.              |
14    +----------------------------------------------------------------------+
15    | Authors: Andi Gutmans <andi@php.net>                                 |
16    |          Zeev Suraski <zeev@php.net>                                 |
17    +----------------------------------------------------------------------+
18 */
19 
20 #include "zend.h"
21 #include "zend_extensions.h"
22 #include "zend_modules.h"
23 #include "zend_constants.h"
24 #include "zend_list.h"
25 #include "zend_API.h"
26 #include "zend_exceptions.h"
27 #include "zend_builtin_functions.h"
28 #include "zend_ini.h"
29 #include "zend_vm.h"
30 #include "zend_dtrace.h"
31 #include "zend_virtual_cwd.h"
32 #include "zend_smart_str.h"
33 #include "zend_smart_string.h"
34 #include "zend_cpuinfo.h"
35 #include "zend_attributes.h"
36 #include "zend_observer.h"
37 #include "zend_fibers.h"
38 #include "zend_call_stack.h"
39 #include "zend_max_execution_timer.h"
40 #include "zend_hrtime.h"
41 #include "Optimizer/zend_optimizer.h"
42 #include "php.h"
43 #include "php_globals.h"
44 
45 // FIXME: Breaks the declaration of the function below
46 #undef zenderror
47 
48 static size_t global_map_ptr_last = 0;
49 static bool startup_done = false;
50 
51 #ifdef ZTS
52 ZEND_API int compiler_globals_id;
53 ZEND_API int executor_globals_id;
54 ZEND_API size_t compiler_globals_offset;
55 ZEND_API size_t executor_globals_offset;
56 static HashTable *global_function_table = NULL;
57 static HashTable *global_class_table = NULL;
58 static HashTable *global_constants_table = NULL;
59 static HashTable *global_auto_globals_table = NULL;
60 static HashTable *global_persistent_list = NULL;
61 TSRMLS_MAIN_CACHE_DEFINE()
62 # define GLOBAL_FUNCTION_TABLE		global_function_table
63 # define GLOBAL_CLASS_TABLE			global_class_table
64 # define GLOBAL_CONSTANTS_TABLE		global_constants_table
65 # define GLOBAL_AUTO_GLOBALS_TABLE	global_auto_globals_table
66 #else
67 # define GLOBAL_FUNCTION_TABLE		CG(function_table)
68 # define GLOBAL_CLASS_TABLE			CG(class_table)
69 # define GLOBAL_AUTO_GLOBALS_TABLE	CG(auto_globals)
70 # define GLOBAL_CONSTANTS_TABLE		EG(zend_constants)
71 #endif
72 
73 ZEND_API zend_utility_values zend_uv;
74 ZEND_API bool zend_dtrace_enabled;
75 
76 /* version information */
77 static char *zend_version_info;
78 static uint32_t zend_version_info_length;
79 #define ZEND_CORE_VERSION_INFO	"Zend Engine v" ZEND_VERSION ", Copyright (c) Zend Technologies\n"
80 #define PRINT_ZVAL_INDENT 4
81 
82 /* true multithread-shared globals */
83 ZEND_API zend_class_entry *zend_standard_class_def = NULL;
84 ZEND_API size_t (*zend_printf)(const char *format, ...);
85 ZEND_API zend_write_func_t zend_write;
86 ZEND_API FILE *(*zend_fopen)(zend_string *filename, zend_string **opened_path);
87 ZEND_API zend_result (*zend_stream_open_function)(zend_file_handle *handle);
88 ZEND_API void (*zend_ticks_function)(int ticks);
89 ZEND_API void (*zend_interrupt_function)(zend_execute_data *execute_data);
90 ZEND_API void (*zend_error_cb)(int type, zend_string *error_filename, const uint32_t error_lineno, zend_string *message);
91 void (*zend_printf_to_smart_string)(smart_string *buf, const char *format, va_list ap);
92 void (*zend_printf_to_smart_str)(smart_str *buf, const char *format, va_list ap);
93 ZEND_API char *(*zend_getenv)(const char *name, size_t name_len);
94 ZEND_API zend_string *(*zend_resolve_path)(zend_string *filename);
95 ZEND_API zend_result (*zend_post_startup_cb)(void) = NULL;
96 ZEND_API void (*zend_post_shutdown_cb)(void) = NULL;
97 
98 /* This callback must be signal handler safe! */
99 void (*zend_on_timeout)(int seconds);
100 
101 static void (*zend_message_dispatcher_p)(zend_long message, const void *data);
102 static zval *(*zend_get_configuration_directive_p)(zend_string *name);
103 
104 #if ZEND_RC_DEBUG
105 ZEND_API bool zend_rc_debug = 0;
106 #endif
107 
ZEND_INI_MH(OnUpdateErrorReporting)108 static ZEND_INI_MH(OnUpdateErrorReporting) /* {{{ */
109 {
110 	if (!new_value) {
111 		EG(error_reporting) = E_ALL;
112 	} else {
113 		EG(error_reporting) = atoi(ZSTR_VAL(new_value));
114 	}
115 	return SUCCESS;
116 }
117 /* }}} */
118 
ZEND_INI_MH(OnUpdateGCEnabled)119 static ZEND_INI_MH(OnUpdateGCEnabled) /* {{{ */
120 {
121 	bool val;
122 
123 	val = zend_ini_parse_bool(new_value);
124 	gc_enable(val);
125 
126 	return SUCCESS;
127 }
128 /* }}} */
129 
ZEND_INI_DISP(zend_gc_enabled_displayer_cb)130 static ZEND_INI_DISP(zend_gc_enabled_displayer_cb) /* {{{ */
131 {
132 	if (gc_enabled()) {
133 		ZEND_PUTS("On");
134 	} else {
135 		ZEND_PUTS("Off");
136 	}
137 }
138 /* }}} */
139 
140 
ZEND_INI_MH(OnUpdateScriptEncoding)141 static ZEND_INI_MH(OnUpdateScriptEncoding) /* {{{ */
142 {
143 	if (!CG(multibyte)) {
144 		return FAILURE;
145 	}
146 	if (!zend_multibyte_get_functions()) {
147 		return SUCCESS;
148 	}
149 	return zend_multibyte_set_script_encoding_by_string(new_value ? ZSTR_VAL(new_value) : NULL, new_value ? ZSTR_LEN(new_value) : 0);
150 }
151 /* }}} */
152 
ZEND_INI_MH(OnUpdateAssertions)153 static ZEND_INI_MH(OnUpdateAssertions) /* {{{ */
154 {
155 	zend_long *p = (zend_long *) ZEND_INI_GET_ADDR();
156 
157 	zend_long val = zend_ini_parse_quantity_warn(new_value, entry->name);
158 
159 	if (stage != ZEND_INI_STAGE_STARTUP &&
160 	    stage != ZEND_INI_STAGE_SHUTDOWN &&
161 	    *p != val &&
162 	    (*p < 0 || val < 0)) {
163 		zend_error(E_WARNING, "zend.assertions may be completely enabled or disabled only in php.ini");
164 		return FAILURE;
165 	}
166 
167 	*p = val;
168 	return SUCCESS;
169 }
170 /* }}} */
171 
ZEND_INI_MH(OnSetExceptionStringParamMaxLen)172 static ZEND_INI_MH(OnSetExceptionStringParamMaxLen) /* {{{ */
173 {
174 	zend_long i = ZEND_ATOL(ZSTR_VAL(new_value));
175 	if (i >= 0 && i <= 1000000) {
176 		EG(exception_string_param_max_len) = i;
177 		return SUCCESS;
178 	} else {
179 		return FAILURE;
180 	}
181 }
182 /* }}} */
183 
184 #ifdef ZEND_CHECK_STACK_LIMIT
ZEND_INI_MH(OnUpdateMaxAllowedStackSize)185 static ZEND_INI_MH(OnUpdateMaxAllowedStackSize) /* {{{ */
186 {
187 	zend_long size = zend_ini_parse_quantity_warn(new_value, entry->name);
188 
189 	if (size < ZEND_MAX_ALLOWED_STACK_SIZE_UNCHECKED) {
190 		zend_error(E_WARNING, "Invalid \"%s\" setting. Value must be >= %d, but got " ZEND_LONG_FMT,
191 			ZSTR_VAL(entry->name), ZEND_MAX_ALLOWED_STACK_SIZE_UNCHECKED, size);
192 		return FAILURE;
193 	}
194 
195 	EG(max_allowed_stack_size) = size;
196 
197 	return SUCCESS;
198 }
199 /* }}} */
200 
ZEND_INI_MH(OnUpdateReservedStackSize)201 static ZEND_INI_MH(OnUpdateReservedStackSize) /* {{{ */
202 {
203 	zend_ulong size = zend_ini_parse_uquantity_warn(new_value, entry->name);
204 
205 	/* Min value accounts for alloca, PCRE2 START_FRAMES_SIZE, and some buffer
206 	 * for normal function calls.
207 	 * We could reduce this on systems without alloca if we also add stack size
208 	 * checks before pcre2_match(). */
209 #ifdef ZEND_ALLOCA_MAX_SIZE
210 	zend_ulong min = ZEND_ALLOCA_MAX_SIZE + 16*1024;
211 #else
212 	zend_ulong min = 32*1024;
213 #endif
214 
215 	if (size == 0) {
216 		size = min;
217 	} else if (size < min) {
218 		zend_error(E_WARNING, "Invalid \"%s\" setting. Value must be >= " ZEND_ULONG_FMT ", but got " ZEND_ULONG_FMT "\n",
219 			ZSTR_VAL(entry->name), min, size);
220 		return FAILURE;
221 	}
222 
223 	EG(reserved_stack_size) = size;
224 
225 	return SUCCESS;
226 }
227 /* }}} */
228 #endif /* ZEND_CHECK_STACK_LIMIT */
229 
ZEND_INI_MH(OnUpdateFiberStackSize)230 static ZEND_INI_MH(OnUpdateFiberStackSize) /* {{{ */
231 {
232 	if (new_value) {
233 		zend_long tmp = zend_ini_parse_quantity_warn(new_value, entry->name);
234 		if (tmp < 0) {
235 			zend_error(E_WARNING, "fiber.stack_size must be a positive number");
236 			return FAILURE;
237 		}
238 		EG(fiber_stack_size) = tmp;
239 	} else {
240 		EG(fiber_stack_size) = ZEND_FIBER_DEFAULT_C_STACK_SIZE;
241 	}
242 	return SUCCESS;
243 }
244 /* }}} */
245 
246 #if ZEND_DEBUG
247 # define SIGNAL_CHECK_DEFAULT "1"
248 #else
249 # define SIGNAL_CHECK_DEFAULT "0"
250 #endif
251 
252 ZEND_INI_BEGIN()
253 	ZEND_INI_ENTRY("error_reporting",				NULL,		ZEND_INI_ALL,		OnUpdateErrorReporting)
254 	STD_ZEND_INI_ENTRY("zend.assertions",				"1",    ZEND_INI_ALL,       OnUpdateAssertions,           assertions,   zend_executor_globals,  executor_globals)
255 	ZEND_INI_ENTRY3_EX("zend.enable_gc",				"1",	ZEND_INI_ALL,		OnUpdateGCEnabled, NULL, NULL, NULL, zend_gc_enabled_displayer_cb)
256 	STD_ZEND_INI_BOOLEAN("zend.multibyte", "0", ZEND_INI_PERDIR, OnUpdateBool, multibyte,      zend_compiler_globals, compiler_globals)
257 	ZEND_INI_ENTRY("zend.script_encoding",			NULL,		ZEND_INI_ALL,		OnUpdateScriptEncoding)
258 	STD_ZEND_INI_BOOLEAN("zend.detect_unicode",			"1",	ZEND_INI_ALL,		OnUpdateBool, detect_unicode, zend_compiler_globals, compiler_globals)
259 #ifdef ZEND_SIGNALS
260 	STD_ZEND_INI_BOOLEAN("zend.signal_check", SIGNAL_CHECK_DEFAULT, ZEND_INI_SYSTEM, OnUpdateBool, check, zend_signal_globals_t, zend_signal_globals)
261 #endif
262 	STD_ZEND_INI_BOOLEAN("zend.exception_ignore_args",	"0",	ZEND_INI_ALL,		OnUpdateBool, exception_ignore_args, zend_executor_globals, executor_globals)
263 	STD_ZEND_INI_ENTRY("zend.exception_string_param_max_len",	"15",	ZEND_INI_ALL,	OnSetExceptionStringParamMaxLen,	exception_string_param_max_len,		zend_executor_globals,	executor_globals)
264 	STD_ZEND_INI_ENTRY("fiber.stack_size",		NULL,			ZEND_INI_ALL,		OnUpdateFiberStackSize,		fiber_stack_size,	zend_executor_globals, 		executor_globals)
265 #ifdef ZEND_CHECK_STACK_LIMIT
266 	/* The maximum allowed call stack size. 0: auto detect, -1: no limit. For fibers, this is fiber.stack_size. */
267 	STD_ZEND_INI_ENTRY("zend.max_allowed_stack_size",	"0",	ZEND_INI_SYSTEM,	OnUpdateMaxAllowedStackSize,	max_allowed_stack_size,		zend_executor_globals,	executor_globals)
268 	/* Substracted from the max allowed stack size, as a buffer, when checking for overflow. 0: auto detect. */
269 	STD_ZEND_INI_ENTRY("zend.reserved_stack_size",	"0",	ZEND_INI_SYSTEM,	OnUpdateReservedStackSize,	reserved_stack_size,		zend_executor_globals,	executor_globals)
270 #endif
271 
ZEND_INI_END()272 ZEND_INI_END()
273 
274 ZEND_API size_t zend_vspprintf(char **pbuf, size_t max_len, const char *format, va_list ap) /* {{{ */
275 {
276 	smart_string buf = {0};
277 
278 	/* since there are places where (v)spprintf called without checking for null,
279 	   a bit of defensive coding here */
280 	if (!pbuf) {
281 		return 0;
282 	}
283 
284 	zend_printf_to_smart_string(&buf, format, ap);
285 
286 	if (max_len && buf.len > max_len) {
287 		buf.len = max_len;
288 	}
289 
290 	smart_string_0(&buf);
291 
292 	if (buf.c) {
293 		*pbuf = buf.c;
294 		return buf.len;
295 	} else {
296 		*pbuf = estrndup("", 0);
297 		return 0;
298 	}
299 }
300 /* }}} */
301 
zend_spprintf(char ** message,size_t max_len,const char * format,...)302 ZEND_API size_t zend_spprintf(char **message, size_t max_len, const char *format, ...) /* {{{ */
303 {
304 	va_list arg;
305 	size_t len;
306 
307 	va_start(arg, format);
308 	len = zend_vspprintf(message, max_len, format, arg);
309 	va_end(arg);
310 	return len;
311 }
312 /* }}} */
313 
zend_spprintf_unchecked(char ** message,size_t max_len,const char * format,...)314 ZEND_API size_t zend_spprintf_unchecked(char **message, size_t max_len, const char *format, ...) /* {{{ */
315 {
316 	va_list arg;
317 	size_t len;
318 
319 	va_start(arg, format);
320 	len = zend_vspprintf(message, max_len, format, arg);
321 	va_end(arg);
322 	return len;
323 }
324 /* }}} */
325 
zend_vstrpprintf(size_t max_len,const char * format,va_list ap)326 ZEND_API zend_string *zend_vstrpprintf(size_t max_len, const char *format, va_list ap) /* {{{ */
327 {
328 	smart_str buf = {0};
329 
330 	zend_printf_to_smart_str(&buf, format, ap);
331 
332 	if (!buf.s) {
333 		return ZSTR_EMPTY_ALLOC();
334 	}
335 
336 	if (max_len && ZSTR_LEN(buf.s) > max_len) {
337 		ZSTR_LEN(buf.s) = max_len;
338 	}
339 
340 	return smart_str_extract(&buf);
341 }
342 /* }}} */
343 
zend_strpprintf(size_t max_len,const char * format,...)344 ZEND_API zend_string *zend_strpprintf(size_t max_len, const char *format, ...) /* {{{ */
345 {
346 	va_list arg;
347 	zend_string *str;
348 
349 	va_start(arg, format);
350 	str = zend_vstrpprintf(max_len, format, arg);
351 	va_end(arg);
352 	return str;
353 }
354 /* }}} */
355 
zend_strpprintf_unchecked(size_t max_len,const char * format,...)356 ZEND_API zend_string *zend_strpprintf_unchecked(size_t max_len, const char *format, ...) /* {{{ */
357 {
358 	va_list arg;
359 	zend_string *str;
360 
361 	va_start(arg, format);
362 	str = zend_vstrpprintf(max_len, format, arg);
363 	va_end(arg);
364 	return str;
365 }
366 /* }}} */
367 
368 static void zend_print_zval_r_to_buf(smart_str *buf, zval *expr, int indent);
369 
print_hash(smart_str * buf,HashTable * ht,int indent,bool is_object)370 static void print_hash(smart_str *buf, HashTable *ht, int indent, bool is_object) /* {{{ */
371 {
372 	zval *tmp;
373 	zend_string *string_key;
374 	zend_ulong num_key;
375 	int i;
376 
377 	for (i = 0; i < indent; i++) {
378 		smart_str_appendc(buf, ' ');
379 	}
380 	smart_str_appends(buf, "(\n");
381 	indent += PRINT_ZVAL_INDENT;
382 	ZEND_HASH_FOREACH_KEY_VAL_IND(ht, num_key, string_key, tmp) {
383 		for (i = 0; i < indent; i++) {
384 			smart_str_appendc(buf, ' ');
385 		}
386 		smart_str_appendc(buf, '[');
387 		if (string_key) {
388 			if (is_object) {
389 				const char *prop_name, *class_name;
390 				size_t prop_len;
391 				int mangled = zend_unmangle_property_name_ex(string_key, &class_name, &prop_name, &prop_len);
392 
393 				smart_str_appendl(buf, prop_name, prop_len);
394 				if (class_name && mangled == SUCCESS) {
395 					if (class_name[0] == '*') {
396 						smart_str_appends(buf, ":protected");
397 					} else {
398 						smart_str_appends(buf, ":");
399 						smart_str_appends(buf, class_name);
400 						smart_str_appends(buf, ":private");
401 					}
402 				}
403 			} else {
404 				smart_str_append(buf, string_key);
405 			}
406 		} else {
407 			smart_str_append_long(buf, num_key);
408 		}
409 		smart_str_appends(buf, "] => ");
410 		zend_print_zval_r_to_buf(buf, tmp, indent+PRINT_ZVAL_INDENT);
411 		smart_str_appends(buf, "\n");
412 	} ZEND_HASH_FOREACH_END();
413 	indent -= PRINT_ZVAL_INDENT;
414 	for (i = 0; i < indent; i++) {
415 		smart_str_appendc(buf, ' ');
416 	}
417 	smart_str_appends(buf, ")\n");
418 }
419 /* }}} */
420 
print_flat_hash(smart_str * buf,HashTable * ht)421 static void print_flat_hash(smart_str *buf, HashTable *ht) /* {{{ */
422 {
423 	zval *tmp;
424 	zend_string *string_key;
425 	zend_ulong num_key;
426 	int i = 0;
427 
428 	ZEND_HASH_FOREACH_KEY_VAL_IND(ht, num_key, string_key, tmp) {
429 		if (i++ > 0) {
430 			smart_str_appendc(buf, ',');
431 		}
432 		smart_str_appendc(buf, '[');
433 		if (string_key) {
434 			smart_str_append(buf, string_key);
435 		} else {
436 			smart_str_append_unsigned(buf, num_key);
437 		}
438 		smart_str_appends(buf, "] => ");
439 		zend_print_flat_zval_r_to_buf(buf, tmp);
440 	} ZEND_HASH_FOREACH_END();
441 }
442 /* }}} */
443 
zend_make_printable_zval(zval * expr,zval * expr_copy)444 ZEND_API bool zend_make_printable_zval(zval *expr, zval *expr_copy) /* {{{ */
445 {
446 	if (Z_TYPE_P(expr) == IS_STRING) {
447 		return 0;
448 	} else {
449 		ZVAL_STR(expr_copy, zval_get_string_func(expr));
450 		return 1;
451 	}
452 }
453 /* }}} */
454 
zend_print_zval(zval * expr,int indent)455 ZEND_API size_t zend_print_zval(zval *expr, int indent) /* {{{ */
456 {
457 	zend_string *tmp_str;
458 	zend_string *str = zval_get_tmp_string(expr, &tmp_str);
459 	size_t len = ZSTR_LEN(str);
460 
461 	if (len != 0) {
462 		zend_write(ZSTR_VAL(str), len);
463 	}
464 
465 	zend_tmp_string_release(tmp_str);
466 	return len;
467 }
468 /* }}} */
469 
zend_print_flat_zval_r_to_buf(smart_str * buf,zval * expr)470 void zend_print_flat_zval_r_to_buf(smart_str *buf, zval *expr) /* {{{ */
471 {
472 	switch (Z_TYPE_P(expr)) {
473 		case IS_ARRAY:
474 			smart_str_appends(buf, "Array (");
475 			if (!(GC_FLAGS(Z_ARRVAL_P(expr)) & GC_IMMUTABLE)) {
476 				if (GC_IS_RECURSIVE(Z_ARRVAL_P(expr))) {
477 					smart_str_appends(buf, " *RECURSION*");
478 					return;
479 				}
480 				GC_PROTECT_RECURSION(Z_ARRVAL_P(expr));
481 			}
482 			print_flat_hash(buf, Z_ARRVAL_P(expr));
483 			smart_str_appendc(buf, ')');
484 			GC_TRY_UNPROTECT_RECURSION(Z_ARRVAL_P(expr));
485 			break;
486 		case IS_OBJECT:
487 		{
488 			HashTable *properties;
489 			zend_string *class_name = Z_OBJ_HANDLER_P(expr, get_class_name)(Z_OBJ_P(expr));
490 			smart_str_append(buf, class_name);
491 			smart_str_appends(buf, " Object (");
492 			zend_string_release_ex(class_name, 0);
493 
494 			if (GC_IS_RECURSIVE(Z_COUNTED_P(expr))) {
495 				smart_str_appends(buf, " *RECURSION*");
496 				return;
497 			}
498 
499 			properties = Z_OBJPROP_P(expr);
500 			if (properties) {
501 				GC_PROTECT_RECURSION(Z_OBJ_P(expr));
502 				print_flat_hash(buf, properties);
503 				GC_UNPROTECT_RECURSION(Z_OBJ_P(expr));
504 			}
505 			smart_str_appendc(buf, ')');
506 			break;
507 		}
508 		case IS_REFERENCE:
509 			zend_print_flat_zval_r_to_buf(buf, Z_REFVAL_P(expr));
510 			break;
511 		case IS_STRING:
512 			smart_str_append(buf, Z_STR_P(expr));
513 			break;
514 		default:
515 		{
516 			zend_string *str = zval_get_string_func(expr);
517 			smart_str_append(buf, str);
518 			zend_string_release_ex(str, 0);
519 			break;
520 		}
521 	}
522 }
523 /* }}} */
524 
zend_print_flat_zval_r(zval * expr)525 ZEND_API void zend_print_flat_zval_r(zval *expr)
526 {
527 	smart_str buf = {0};
528 	zend_print_flat_zval_r_to_buf(&buf, expr);
529 	smart_str_0(&buf);
530 	zend_write(ZSTR_VAL(buf.s), ZSTR_LEN(buf.s));
531 	smart_str_free(&buf);
532 }
533 
zend_print_zval_r_to_buf(smart_str * buf,zval * expr,int indent)534 static void zend_print_zval_r_to_buf(smart_str *buf, zval *expr, int indent) /* {{{ */
535 {
536 	switch (Z_TYPE_P(expr)) {
537 		case IS_ARRAY:
538 			smart_str_appends(buf, "Array\n");
539 			if (!(GC_FLAGS(Z_ARRVAL_P(expr)) & GC_IMMUTABLE)) {
540 				if (GC_IS_RECURSIVE(Z_ARRVAL_P(expr))) {
541 					smart_str_appends(buf, " *RECURSION*");
542 					return;
543 				}
544 				GC_PROTECT_RECURSION(Z_ARRVAL_P(expr));
545 			}
546 			print_hash(buf, Z_ARRVAL_P(expr), indent, 0);
547 			GC_TRY_UNPROTECT_RECURSION(Z_ARRVAL_P(expr));
548 			break;
549 		case IS_OBJECT:
550 			{
551 				HashTable *properties;
552 
553 				zend_object *zobj = Z_OBJ_P(expr);
554 				uint32_t *guard = zend_get_recursion_guard(zobj);
555 				zend_string *class_name = Z_OBJ_HANDLER_P(expr, get_class_name)(zobj);
556 				smart_str_appends(buf, ZSTR_VAL(class_name));
557 				zend_string_release_ex(class_name, 0);
558 
559 				if (!(zobj->ce->ce_flags & ZEND_ACC_ENUM)) {
560 					smart_str_appends(buf, " Object\n");
561 				} else {
562 					smart_str_appends(buf, " Enum");
563 					if (zobj->ce->enum_backing_type != IS_UNDEF) {
564 						smart_str_appendc(buf, ':');
565 						smart_str_appends(buf, zend_get_type_by_const(zobj->ce->enum_backing_type));
566 					}
567 					smart_str_appendc(buf, '\n');
568 				}
569 
570 				if (ZEND_GUARD_OR_GC_IS_RECURSIVE(guard, DEBUG, zobj)) {
571 					smart_str_appends(buf, " *RECURSION*");
572 					return;
573 				}
574 
575 				if ((properties = zend_get_properties_for(expr, ZEND_PROP_PURPOSE_DEBUG)) == NULL) {
576 					print_hash(buf, (HashTable*) &zend_empty_array, indent, 1);
577 					break;
578 				}
579 
580 				ZEND_GUARD_OR_GC_PROTECT_RECURSION(guard, DEBUG, zobj);
581 				print_hash(buf, properties, indent, 1);
582 				ZEND_GUARD_OR_GC_UNPROTECT_RECURSION(guard, DEBUG, zobj);
583 
584 				zend_release_properties(properties);
585 				break;
586 			}
587 		case IS_LONG:
588 			smart_str_append_long(buf, Z_LVAL_P(expr));
589 			break;
590 		case IS_REFERENCE:
591 			zend_print_zval_r_to_buf(buf, Z_REFVAL_P(expr), indent);
592 			break;
593 		case IS_STRING:
594 			smart_str_append(buf, Z_STR_P(expr));
595 			break;
596 		default:
597 			{
598 				zend_string *str = zval_get_string_func(expr);
599 				smart_str_append(buf, str);
600 				zend_string_release_ex(str, 0);
601 			}
602 			break;
603 	}
604 }
605 /* }}} */
606 
zend_print_zval_r_to_str(zval * expr,int indent)607 ZEND_API zend_string *zend_print_zval_r_to_str(zval *expr, int indent) /* {{{ */
608 {
609 	smart_str buf = {0};
610 	zend_print_zval_r_to_buf(&buf, expr, indent);
611 	smart_str_0(&buf);
612 	return buf.s;
613 }
614 /* }}} */
615 
zend_print_zval_r(zval * expr,int indent)616 ZEND_API void zend_print_zval_r(zval *expr, int indent) /* {{{ */
617 {
618 	zend_string *str = zend_print_zval_r_to_str(expr, indent);
619 	zend_write(ZSTR_VAL(str), ZSTR_LEN(str));
620 	zend_string_release_ex(str, 0);
621 }
622 /* }}} */
623 
zend_fopen_wrapper(zend_string * filename,zend_string ** opened_path)624 static FILE *zend_fopen_wrapper(zend_string *filename, zend_string **opened_path) /* {{{ */
625 {
626 	if (opened_path) {
627 		*opened_path = zend_string_copy(filename);
628 	}
629 	return fopen(ZSTR_VAL(filename), "rb");
630 }
631 /* }}} */
632 
633 #ifdef ZTS
634 static bool short_tags_default      = 1;
635 static uint32_t compiler_options_default = ZEND_COMPILE_DEFAULT;
636 #else
637 # define short_tags_default			1
638 # define compiler_options_default	ZEND_COMPILE_DEFAULT
639 #endif
640 
zend_set_default_compile_time_values(void)641 static void zend_set_default_compile_time_values(void) /* {{{ */
642 {
643 	/* default compile-time values */
644 	CG(short_tags) = short_tags_default;
645 	CG(compiler_options) = compiler_options_default;
646 
647 	CG(rtd_key_counter) = 0;
648 }
649 /* }}} */
650 
651 #ifdef ZEND_WIN32
zend_get_windows_version_info(OSVERSIONINFOEX * osvi)652 static void zend_get_windows_version_info(OSVERSIONINFOEX *osvi) /* {{{ */
653 {
654 	ZeroMemory(osvi, sizeof(OSVERSIONINFOEX));
655 	osvi->dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
656 	if(!GetVersionEx((OSVERSIONINFO *) osvi)) {
657 		ZEND_UNREACHABLE(); /* Should not happen as sizeof is used. */
658 	}
659 }
660 /* }}} */
661 #endif
662 
zend_init_exception_op(void)663 static void zend_init_exception_op(void) /* {{{ */
664 {
665 	memset(EG(exception_op), 0, sizeof(EG(exception_op)));
666 	EG(exception_op)[0].opcode = ZEND_HANDLE_EXCEPTION;
667 	ZEND_VM_SET_OPCODE_HANDLER(EG(exception_op));
668 	EG(exception_op)[1].opcode = ZEND_HANDLE_EXCEPTION;
669 	ZEND_VM_SET_OPCODE_HANDLER(EG(exception_op)+1);
670 	EG(exception_op)[2].opcode = ZEND_HANDLE_EXCEPTION;
671 	ZEND_VM_SET_OPCODE_HANDLER(EG(exception_op)+2);
672 }
673 /* }}} */
674 
zend_init_call_trampoline_op(void)675 static void zend_init_call_trampoline_op(void) /* {{{ */
676 {
677 	memset(&EG(call_trampoline_op), 0, sizeof(EG(call_trampoline_op)));
678 	EG(call_trampoline_op).opcode = ZEND_CALL_TRAMPOLINE;
679 	ZEND_VM_SET_OPCODE_HANDLER(&EG(call_trampoline_op));
680 }
681 /* }}} */
682 
auto_global_dtor(zval * zv)683 static void auto_global_dtor(zval *zv) /* {{{ */
684 {
685 	free(Z_PTR_P(zv));
686 }
687 /* }}} */
688 
689 #ifdef ZTS
auto_global_copy_ctor(zval * zv)690 static void auto_global_copy_ctor(zval *zv) /* {{{ */
691 {
692 	zend_auto_global *old_ag = (zend_auto_global *) Z_PTR_P(zv);
693 	zend_auto_global *new_ag = pemalloc(sizeof(zend_auto_global), 1);
694 
695 	new_ag->name = old_ag->name;
696 	new_ag->auto_global_callback = old_ag->auto_global_callback;
697 	new_ag->jit = old_ag->jit;
698 
699 	Z_PTR_P(zv) = new_ag;
700 }
701 /* }}} */
702 
compiler_globals_ctor(zend_compiler_globals * compiler_globals)703 static void compiler_globals_ctor(zend_compiler_globals *compiler_globals) /* {{{ */
704 {
705 	compiler_globals->compiled_filename = NULL;
706 
707 	compiler_globals->function_table = (HashTable *) malloc(sizeof(HashTable));
708 	zend_hash_init(compiler_globals->function_table, 1024, NULL, ZEND_FUNCTION_DTOR, 1);
709 	zend_hash_copy(compiler_globals->function_table, global_function_table, NULL);
710 	compiler_globals->copied_functions_count = zend_hash_num_elements(compiler_globals->function_table);
711 
712 	compiler_globals->class_table = (HashTable *) malloc(sizeof(HashTable));
713 	zend_hash_init(compiler_globals->class_table, 64, NULL, ZEND_CLASS_DTOR, 1);
714 	zend_hash_copy(compiler_globals->class_table, global_class_table, zend_class_add_ref);
715 
716 	zend_set_default_compile_time_values();
717 
718 	compiler_globals->auto_globals = (HashTable *) malloc(sizeof(HashTable));
719 	zend_hash_init(compiler_globals->auto_globals, 8, NULL, auto_global_dtor, 1);
720 	zend_hash_copy(compiler_globals->auto_globals, global_auto_globals_table, auto_global_copy_ctor);
721 
722 	compiler_globals->script_encoding_list = NULL;
723 	compiler_globals->current_linking_class = NULL;
724 
725 	/* Map region is going to be created and resized at run-time. */
726 	compiler_globals->map_ptr_real_base = NULL;
727 	compiler_globals->map_ptr_base = ZEND_MAP_PTR_BIASED_BASE(NULL);
728 	compiler_globals->map_ptr_size = 0;
729 	compiler_globals->map_ptr_last = global_map_ptr_last;
730 	if (compiler_globals->map_ptr_last) {
731 		/* Allocate map_ptr table */
732 		compiler_globals->map_ptr_size = ZEND_MM_ALIGNED_SIZE_EX(compiler_globals->map_ptr_last, 4096);
733 		void *base = pemalloc(compiler_globals->map_ptr_size * sizeof(void*), 1);
734 		compiler_globals->map_ptr_real_base = base;
735 		compiler_globals->map_ptr_base = ZEND_MAP_PTR_BIASED_BASE(base);
736 		memset(base, 0, compiler_globals->map_ptr_last * sizeof(void*));
737 	}
738 }
739 /* }}} */
740 
compiler_globals_dtor(zend_compiler_globals * compiler_globals)741 static void compiler_globals_dtor(zend_compiler_globals *compiler_globals) /* {{{ */
742 {
743 	if (compiler_globals->function_table != GLOBAL_FUNCTION_TABLE) {
744 		uint32_t n = compiler_globals->copied_functions_count;
745 
746 	    /* Prevent destruction of functions copied from the main process context */
747 		if (zend_hash_num_elements(compiler_globals->function_table) <= n) {
748 			compiler_globals->function_table->nNumUsed = 0;
749 		} else {
750 			Bucket *p = compiler_globals->function_table->arData;
751 
752 			compiler_globals->function_table->nNumOfElements -= n;
753 			while (n != 0) {
754 				ZVAL_UNDEF(&p->val);
755 				p++;
756 				n--;
757 			}
758 		}
759 		zend_hash_destroy(compiler_globals->function_table);
760 		free(compiler_globals->function_table);
761 	}
762 	if (compiler_globals->class_table != GLOBAL_CLASS_TABLE) {
763 		/* Child classes may reuse structures from parent classes, so destroy in reverse order. */
764 		zend_hash_graceful_reverse_destroy(compiler_globals->class_table);
765 		free(compiler_globals->class_table);
766 	}
767 	if (compiler_globals->auto_globals != GLOBAL_AUTO_GLOBALS_TABLE) {
768 		zend_hash_destroy(compiler_globals->auto_globals);
769 		free(compiler_globals->auto_globals);
770 	}
771 	if (compiler_globals->script_encoding_list) {
772 		pefree((char*)compiler_globals->script_encoding_list, 1);
773 	}
774 	if (compiler_globals->map_ptr_real_base) {
775 		free(compiler_globals->map_ptr_real_base);
776 		compiler_globals->map_ptr_real_base = NULL;
777 		compiler_globals->map_ptr_base = ZEND_MAP_PTR_BIASED_BASE(NULL);
778 		compiler_globals->map_ptr_size = 0;
779 	}
780 }
781 /* }}} */
782 
executor_globals_ctor(zend_executor_globals * executor_globals)783 static void executor_globals_ctor(zend_executor_globals *executor_globals) /* {{{ */
784 {
785 	zend_startup_constants();
786 	zend_copy_constants(executor_globals->zend_constants, GLOBAL_CONSTANTS_TABLE);
787 	zend_init_rsrc_plist();
788 	zend_init_exception_op();
789 	zend_init_call_trampoline_op();
790 	memset(&executor_globals->trampoline, 0, sizeof(zend_op_array));
791 	executor_globals->capture_warnings_during_sccp = 0;
792 	ZVAL_UNDEF(&executor_globals->user_error_handler);
793 	ZVAL_UNDEF(&executor_globals->user_exception_handler);
794 	executor_globals->in_autoload = NULL;
795 	executor_globals->current_execute_data = NULL;
796 	executor_globals->current_module = NULL;
797 	executor_globals->exit_status = 0;
798 #if XPFPA_HAVE_CW
799 	executor_globals->saved_fpu_cw = 0;
800 #endif
801 	executor_globals->saved_fpu_cw_ptr = NULL;
802 	executor_globals->active = 0;
803 	executor_globals->bailout = NULL;
804 	executor_globals->error_handling  = EH_NORMAL;
805 	executor_globals->exception_class = NULL;
806 	executor_globals->exception = NULL;
807 	executor_globals->objects_store.object_buckets = NULL;
808 	executor_globals->current_fiber_context = NULL;
809 	executor_globals->main_fiber_context = NULL;
810 	executor_globals->active_fiber = NULL;
811 #ifdef ZEND_WIN32
812 	zend_get_windows_version_info(&executor_globals->windows_version_info);
813 #endif
814 	executor_globals->flags = EG_FLAGS_INITIAL;
815 	executor_globals->record_errors = false;
816 	executor_globals->num_errors = 0;
817 	executor_globals->errors = NULL;
818 #ifdef ZEND_CHECK_STACK_LIMIT
819 	executor_globals->stack_limit = (void*)0;
820 	executor_globals->stack_base = (void*)0;
821 #endif
822 #ifdef ZEND_MAX_EXECUTION_TIMERS
823 	executor_globals->pid = 0;
824 	executor_globals->oldact = (struct sigaction){0};
825 #endif
826 }
827 /* }}} */
828 
executor_globals_dtor(zend_executor_globals * executor_globals)829 static void executor_globals_dtor(zend_executor_globals *executor_globals) /* {{{ */
830 {
831 	zend_ini_dtor(executor_globals->ini_directives);
832 
833 	if (&executor_globals->persistent_list != global_persistent_list) {
834 		zend_destroy_rsrc_list(&executor_globals->persistent_list);
835 	}
836 	if (executor_globals->zend_constants != GLOBAL_CONSTANTS_TABLE) {
837 		zend_hash_destroy(executor_globals->zend_constants);
838 		free(executor_globals->zend_constants);
839 	}
840 }
841 /* }}} */
842 
zend_new_thread_end_handler(THREAD_T thread_id)843 static void zend_new_thread_end_handler(THREAD_T thread_id) /* {{{ */
844 {
845 	zend_copy_ini_directives();
846 	zend_ini_refresh_caches(ZEND_INI_STAGE_STARTUP);
847 #ifdef ZEND_CHECK_STACK_LIMIT
848 	zend_call_stack_init();
849 #endif
850 	zend_max_execution_timer_init();
851 }
852 /* }}} */
853 #endif
854 
855 #if defined(__FreeBSD__) || defined(__DragonFly__)
856 /* FreeBSD and DragonFly floating point precision fix */
857 #include <floatingpoint.h>
858 #endif
859 
ini_scanner_globals_ctor(zend_ini_scanner_globals * scanner_globals_p)860 static void ini_scanner_globals_ctor(zend_ini_scanner_globals *scanner_globals_p) /* {{{ */
861 {
862 	memset(scanner_globals_p, 0, sizeof(*scanner_globals_p));
863 }
864 /* }}} */
865 
php_scanner_globals_ctor(zend_php_scanner_globals * scanner_globals_p)866 static void php_scanner_globals_ctor(zend_php_scanner_globals *scanner_globals_p) /* {{{ */
867 {
868 	memset(scanner_globals_p, 0, sizeof(*scanner_globals_p));
869 }
870 /* }}} */
871 
module_destructor_zval(zval * zv)872 static void module_destructor_zval(zval *zv) /* {{{ */
873 {
874 	zend_module_entry *module = (zend_module_entry*)Z_PTR_P(zv);
875 	module_destructor(module);
876 }
877 /* }}} */
878 
php_auto_globals_create_globals(zend_string * name)879 static bool php_auto_globals_create_globals(zend_string *name) /* {{{ */
880 {
881 	/* While we keep registering $GLOBALS as an auto-global, we do not create an
882 	 * actual variable for it. Access to it handled specially by the compiler. */
883 	return 0;
884 }
885 /* }}} */
886 
zend_startup(zend_utility_functions * utility_functions)887 void zend_startup(zend_utility_functions *utility_functions) /* {{{ */
888 {
889 #ifdef ZTS
890 	zend_compiler_globals *compiler_globals;
891 	zend_executor_globals *executor_globals;
892 	extern ZEND_API ts_rsrc_id ini_scanner_globals_id;
893 	extern ZEND_API ts_rsrc_id language_scanner_globals_id;
894 #else
895 	extern zend_ini_scanner_globals ini_scanner_globals;
896 	extern zend_php_scanner_globals language_scanner_globals;
897 #endif
898 
899 	zend_cpu_startup();
900 
901 #ifdef ZEND_WIN32
902 	php_win32_cp_set_by_id(65001);
903 #endif
904 
905 	start_memory_manager();
906 
907 	virtual_cwd_startup(); /* Could use shutdown to free the main cwd but it would just slow it down for CGI */
908 
909 #if defined(__FreeBSD__) || defined(__DragonFly__)
910 	/* FreeBSD and DragonFly floating point precision fix */
911 	fpsetmask(0);
912 #endif
913 
914 	zend_startup_hrtime();
915 	zend_startup_strtod();
916 	zend_startup_extensions_mechanism();
917 
918 	/* Set up utility functions and values */
919 	zend_error_cb = utility_functions->error_function;
920 	zend_printf = utility_functions->printf_function;
921 	zend_write = utility_functions->write_function;
922 	zend_fopen = utility_functions->fopen_function;
923 	if (!zend_fopen) {
924 		zend_fopen = zend_fopen_wrapper;
925 	}
926 	zend_stream_open_function = utility_functions->stream_open_function;
927 	zend_message_dispatcher_p = utility_functions->message_handler;
928 	zend_get_configuration_directive_p = utility_functions->get_configuration_directive;
929 	zend_ticks_function = utility_functions->ticks_function;
930 	zend_on_timeout = utility_functions->on_timeout;
931 	zend_printf_to_smart_string = utility_functions->printf_to_smart_string_function;
932 	zend_printf_to_smart_str = utility_functions->printf_to_smart_str_function;
933 	zend_getenv = utility_functions->getenv_function;
934 	zend_resolve_path = utility_functions->resolve_path_function;
935 
936 	zend_interrupt_function = NULL;
937 
938 #ifdef HAVE_DTRACE
939 /* build with dtrace support */
940 	{
941 		char *tmp = getenv("USE_ZEND_DTRACE");
942 
943 		if (tmp && ZEND_ATOL(tmp)) {
944 			zend_dtrace_enabled = 1;
945 			zend_compile_file = dtrace_compile_file;
946 			zend_execute_ex = dtrace_execute_ex;
947 			zend_execute_internal = dtrace_execute_internal;
948 
949 			zend_observer_error_register(dtrace_error_notify_cb);
950 		} else {
951 			zend_compile_file = compile_file;
952 			zend_execute_ex = execute_ex;
953 			zend_execute_internal = NULL;
954 		}
955 	}
956 #else
957 	zend_compile_file = compile_file;
958 	zend_execute_ex = execute_ex;
959 	zend_execute_internal = NULL;
960 #endif /* HAVE_DTRACE */
961 	zend_compile_string = compile_string;
962 	zend_throw_exception_hook = NULL;
963 
964 	/* Set up the default garbage collection implementation. */
965 	gc_collect_cycles = zend_gc_collect_cycles;
966 
967 	zend_vm_init();
968 
969 	/* set up version */
970 	zend_version_info = strdup(ZEND_CORE_VERSION_INFO);
971 	zend_version_info_length = sizeof(ZEND_CORE_VERSION_INFO) - 1;
972 
973 	GLOBAL_FUNCTION_TABLE = (HashTable *) malloc(sizeof(HashTable));
974 	GLOBAL_CLASS_TABLE = (HashTable *) malloc(sizeof(HashTable));
975 	GLOBAL_AUTO_GLOBALS_TABLE = (HashTable *) malloc(sizeof(HashTable));
976 	GLOBAL_CONSTANTS_TABLE = (HashTable *) malloc(sizeof(HashTable));
977 
978 	zend_hash_init(GLOBAL_FUNCTION_TABLE, 1024, NULL, ZEND_FUNCTION_DTOR, 1);
979 	zend_hash_init(GLOBAL_CLASS_TABLE, 64, NULL, ZEND_CLASS_DTOR, 1);
980 	zend_hash_init(GLOBAL_AUTO_GLOBALS_TABLE, 8, NULL, auto_global_dtor, 1);
981 	zend_hash_init(GLOBAL_CONSTANTS_TABLE, 128, NULL, ZEND_CONSTANT_DTOR, 1);
982 
983 	zend_hash_init(&module_registry, 32, NULL, module_destructor_zval, 1);
984 	zend_init_rsrc_list_dtors();
985 
986 #ifdef ZTS
987 	ts_allocate_fast_id(&compiler_globals_id, &compiler_globals_offset, sizeof(zend_compiler_globals), (ts_allocate_ctor) compiler_globals_ctor, (ts_allocate_dtor) compiler_globals_dtor);
988 	ts_allocate_fast_id(&executor_globals_id, &executor_globals_offset, sizeof(zend_executor_globals), (ts_allocate_ctor) executor_globals_ctor, (ts_allocate_dtor) executor_globals_dtor);
989 	ts_allocate_fast_id(&language_scanner_globals_id, &language_scanner_globals_offset, sizeof(zend_php_scanner_globals), (ts_allocate_ctor) php_scanner_globals_ctor, NULL);
990 	ts_allocate_fast_id(&ini_scanner_globals_id, &ini_scanner_globals_offset, sizeof(zend_ini_scanner_globals), (ts_allocate_ctor) ini_scanner_globals_ctor, NULL);
991 	compiler_globals = ts_resource(compiler_globals_id);
992 	executor_globals = ts_resource(executor_globals_id);
993 
994 	compiler_globals_dtor(compiler_globals);
995 	compiler_globals->in_compilation = 0;
996 	compiler_globals->function_table = (HashTable *) malloc(sizeof(HashTable));
997 	compiler_globals->class_table = (HashTable *) malloc(sizeof(HashTable));
998 
999 	*compiler_globals->function_table = *GLOBAL_FUNCTION_TABLE;
1000 	*compiler_globals->class_table = *GLOBAL_CLASS_TABLE;
1001 	compiler_globals->auto_globals = GLOBAL_AUTO_GLOBALS_TABLE;
1002 
1003 	zend_hash_destroy(executor_globals->zend_constants);
1004 	*executor_globals->zend_constants = *GLOBAL_CONSTANTS_TABLE;
1005 #else
1006 	ini_scanner_globals_ctor(&ini_scanner_globals);
1007 	php_scanner_globals_ctor(&language_scanner_globals);
1008 	zend_set_default_compile_time_values();
1009 #ifdef ZEND_WIN32
1010 	zend_get_windows_version_info(&EG(windows_version_info));
1011 #endif
1012 	/* Map region is going to be created and resized at run-time. */
1013 	CG(map_ptr_real_base) = NULL;
1014 	CG(map_ptr_base) = ZEND_MAP_PTR_BIASED_BASE(NULL);
1015 	CG(map_ptr_size) = 0;
1016 	CG(map_ptr_last) = 0;
1017 #endif /* ZTS */
1018 	EG(error_reporting) = E_ALL & ~E_NOTICE;
1019 
1020 	zend_interned_strings_init();
1021 	zend_startup_builtin_functions();
1022 	zend_register_standard_constants();
1023 	zend_register_auto_global(zend_string_init_interned("GLOBALS", sizeof("GLOBALS") - 1, 1), 1, php_auto_globals_create_globals);
1024 
1025 #ifndef ZTS
1026 	zend_init_rsrc_plist();
1027 	zend_init_exception_op();
1028 	zend_init_call_trampoline_op();
1029 #endif
1030 
1031 	zend_ini_startup();
1032 
1033 #ifdef ZEND_WIN32
1034 	/* Uses INI settings, so needs to be run after it. */
1035 	php_win32_cp_setup();
1036 #endif
1037 
1038 	zend_optimizer_startup();
1039 
1040 #ifdef ZTS
1041 	tsrm_set_new_thread_end_handler(zend_new_thread_end_handler);
1042 	tsrm_set_shutdown_handler(zend_interned_strings_dtor);
1043 #endif
1044 }
1045 /* }}} */
1046 
zend_register_standard_ini_entries(void)1047 void zend_register_standard_ini_entries(void) /* {{{ */
1048 {
1049 	zend_register_ini_entries_ex(ini_entries, 0, MODULE_PERSISTENT);
1050 }
1051 /* }}} */
1052 
1053 
1054 /* Unlink the global (r/o) copies of the class, function and constant tables,
1055  * and use a fresh r/w copy for the startup thread
1056  */
zend_post_startup(void)1057 zend_result zend_post_startup(void) /* {{{ */
1058 {
1059 #ifdef ZTS
1060 	zend_encoding **script_encoding_list;
1061 
1062 	zend_compiler_globals *compiler_globals = ts_resource(compiler_globals_id);
1063 	zend_executor_globals *executor_globals = ts_resource(executor_globals_id);
1064 #endif
1065 
1066 	startup_done = true;
1067 
1068 	if (zend_post_startup_cb) {
1069 		zend_result (*cb)(void) = zend_post_startup_cb;
1070 
1071 		zend_post_startup_cb = NULL;
1072 		if (cb() != SUCCESS) {
1073 			return FAILURE;
1074 		}
1075 	}
1076 
1077 #ifdef ZTS
1078 	*GLOBAL_FUNCTION_TABLE = *compiler_globals->function_table;
1079 	*GLOBAL_CLASS_TABLE = *compiler_globals->class_table;
1080 	*GLOBAL_CONSTANTS_TABLE = *executor_globals->zend_constants;
1081 	global_map_ptr_last = compiler_globals->map_ptr_last;
1082 
1083 	short_tags_default = CG(short_tags);
1084 	compiler_options_default = CG(compiler_options);
1085 
1086 	zend_destroy_rsrc_list(&EG(persistent_list));
1087 	free(compiler_globals->function_table);
1088 	compiler_globals->function_table = NULL;
1089 	free(compiler_globals->class_table);
1090 	compiler_globals->class_table = NULL;
1091 	if (compiler_globals->map_ptr_real_base) {
1092 		free(compiler_globals->map_ptr_real_base);
1093 	}
1094 	compiler_globals->map_ptr_real_base = NULL;
1095 	compiler_globals->map_ptr_base = ZEND_MAP_PTR_BIASED_BASE(NULL);
1096 	if ((script_encoding_list = (zend_encoding **)compiler_globals->script_encoding_list)) {
1097 		compiler_globals_ctor(compiler_globals);
1098 		compiler_globals->script_encoding_list = (const zend_encoding **)script_encoding_list;
1099 	} else {
1100 		compiler_globals_ctor(compiler_globals);
1101 	}
1102 	free(EG(zend_constants));
1103 	EG(zend_constants) = NULL;
1104 
1105 	executor_globals_ctor(executor_globals);
1106 	global_persistent_list = &EG(persistent_list);
1107 	zend_copy_ini_directives();
1108 #else
1109 	global_map_ptr_last = CG(map_ptr_last);
1110 #endif
1111 
1112 #ifdef ZEND_CHECK_STACK_LIMIT
1113 	zend_call_stack_init();
1114 #endif
1115 
1116 	return SUCCESS;
1117 }
1118 /* }}} */
1119 
zend_shutdown(void)1120 void zend_shutdown(void) /* {{{ */
1121 {
1122 	zend_vm_dtor();
1123 
1124 	zend_destroy_rsrc_list(&EG(persistent_list));
1125 	zend_destroy_modules();
1126 
1127 	virtual_cwd_deactivate();
1128 	virtual_cwd_shutdown();
1129 
1130 	zend_hash_destroy(GLOBAL_FUNCTION_TABLE);
1131 	/* Child classes may reuse structures from parent classes, so destroy in reverse order. */
1132 	zend_hash_graceful_reverse_destroy(GLOBAL_CLASS_TABLE);
1133 
1134 	zend_flf_capacity = 0;
1135 	zend_flf_count = 0;
1136 	free(zend_flf_functions);
1137 	free(zend_flf_handlers);
1138 	zend_flf_functions = NULL;
1139 	zend_flf_handlers = NULL;
1140 
1141 	zend_hash_destroy(GLOBAL_AUTO_GLOBALS_TABLE);
1142 	free(GLOBAL_AUTO_GLOBALS_TABLE);
1143 
1144 	zend_shutdown_extensions();
1145 	free(zend_version_info);
1146 
1147 	free(GLOBAL_FUNCTION_TABLE);
1148 	free(GLOBAL_CLASS_TABLE);
1149 
1150 	zend_hash_destroy(GLOBAL_CONSTANTS_TABLE);
1151 	free(GLOBAL_CONSTANTS_TABLE);
1152 	zend_shutdown_strtod();
1153 	zend_attributes_shutdown();
1154 
1155 #ifdef ZTS
1156 	GLOBAL_FUNCTION_TABLE = NULL;
1157 	GLOBAL_CLASS_TABLE = NULL;
1158 	GLOBAL_AUTO_GLOBALS_TABLE = NULL;
1159 	GLOBAL_CONSTANTS_TABLE = NULL;
1160 	ts_free_id(executor_globals_id);
1161 	ts_free_id(compiler_globals_id);
1162 #else
1163 	if (CG(map_ptr_real_base)) {
1164 		free(CG(map_ptr_real_base));
1165 		CG(map_ptr_real_base) = NULL;
1166 		CG(map_ptr_base) = ZEND_MAP_PTR_BIASED_BASE(NULL);
1167 		CG(map_ptr_size) = 0;
1168 	}
1169 	if (CG(script_encoding_list)) {
1170 		free(ZEND_VOIDP(CG(script_encoding_list)));
1171 		CG(script_encoding_list) = NULL;
1172 		CG(script_encoding_list_size) = 0;
1173 	}
1174 #endif
1175 	zend_destroy_rsrc_list_dtors();
1176 
1177 	zend_optimizer_shutdown();
1178 	startup_done = false;
1179 }
1180 /* }}} */
1181 
zend_set_utility_values(zend_utility_values * utility_values)1182 void zend_set_utility_values(zend_utility_values *utility_values) /* {{{ */
1183 {
1184 	zend_uv = *utility_values;
1185 }
1186 /* }}} */
1187 
1188 /* this should be compatible with the standard zenderror */
zenderror(const char * error)1189 ZEND_COLD void zenderror(const char *error) /* {{{ */
1190 {
1191 	CG(parse_error) = 0;
1192 
1193 	if (EG(exception)) {
1194 		/* An exception was thrown in the lexer, don't throw another in the parser. */
1195 		return;
1196 	}
1197 
1198 	zend_throw_exception(zend_ce_parse_error, error, 0);
1199 }
1200 /* }}} */
1201 
_zend_bailout(const char * filename,uint32_t lineno)1202 ZEND_API ZEND_COLD ZEND_NORETURN void _zend_bailout(const char *filename, uint32_t lineno) /* {{{ */
1203 {
1204 
1205 	if (!EG(bailout)) {
1206 		zend_output_debug_string(1, "%s(%d) : Bailed out without a bailout address!", filename, lineno);
1207 		exit(-1);
1208 	}
1209 	gc_protect(1);
1210 	CG(unclean_shutdown) = 1;
1211 	CG(active_class_entry) = NULL;
1212 	CG(in_compilation) = 0;
1213 	CG(memoize_mode) = 0;
1214 	EG(current_execute_data) = NULL;
1215 	LONGJMP(*EG(bailout), FAILURE);
1216 }
1217 /* }}} */
1218 
zend_get_page_size(void)1219 ZEND_API size_t zend_get_page_size(void)
1220 {
1221 #ifdef _WIN32
1222 	SYSTEM_INFO system_info;
1223 	GetSystemInfo(&system_info);
1224 	return system_info.dwPageSize;
1225 #elif defined(__FreeBSD__)
1226 	/* This returns the value obtained from
1227 	 * the auxv vector, avoiding a syscall. */
1228 	return getpagesize();
1229 #else
1230 	return (size_t) sysconf(_SC_PAGESIZE);
1231 #endif
1232 }
1233 
zend_append_version_info(const zend_extension * extension)1234 ZEND_API void zend_append_version_info(const zend_extension *extension) /* {{{ */
1235 {
1236 	char *new_info;
1237 	uint32_t new_info_length;
1238 
1239 	new_info_length = (uint32_t)(sizeof("    with  v, , by \n")
1240 						+ strlen(extension->name)
1241 						+ strlen(extension->version)
1242 						+ strlen(extension->copyright)
1243 						+ strlen(extension->author));
1244 
1245 	new_info = (char *) malloc(new_info_length + 1);
1246 
1247 	snprintf(new_info, new_info_length, "    with %s v%s, %s, by %s\n", extension->name, extension->version, extension->copyright, extension->author);
1248 
1249 	zend_version_info = (char *) realloc(zend_version_info, zend_version_info_length+new_info_length + 1);
1250 	strncat(zend_version_info, new_info, new_info_length);
1251 	zend_version_info_length += new_info_length;
1252 	free(new_info);
1253 }
1254 /* }}} */
1255 
get_zend_version(void)1256 ZEND_API const char *get_zend_version(void) /* {{{ */
1257 {
1258 	return zend_version_info;
1259 }
1260 /* }}} */
1261 
zend_activate(void)1262 ZEND_API void zend_activate(void) /* {{{ */
1263 {
1264 #ifdef ZTS
1265 	virtual_cwd_activate();
1266 #endif
1267 	gc_reset();
1268 	init_compiler();
1269 	init_executor();
1270 	startup_scanner();
1271 	if (CG(map_ptr_last)) {
1272 		memset(CG(map_ptr_real_base), 0, CG(map_ptr_last) * sizeof(void*));
1273 	}
1274 	zend_init_internal_run_time_cache();
1275 	zend_observer_activate();
1276 }
1277 /* }}} */
1278 
zend_call_destructors(void)1279 void zend_call_destructors(void) /* {{{ */
1280 {
1281 	zend_try {
1282 		shutdown_destructors();
1283 	} zend_end_try();
1284 }
1285 /* }}} */
1286 
zend_deactivate(void)1287 ZEND_API void zend_deactivate(void) /* {{{ */
1288 {
1289 	/* we're no longer executing anything */
1290 	EG(current_execute_data) = NULL;
1291 
1292 	zend_try {
1293 		shutdown_scanner();
1294 	} zend_end_try();
1295 
1296 	/* shutdown_executor() takes care of its own bailout handling */
1297 	shutdown_executor();
1298 
1299 	zend_try {
1300 		zend_ini_deactivate();
1301 	} zend_end_try();
1302 
1303 	zend_try {
1304 		shutdown_compiler();
1305 	} zend_end_try();
1306 
1307 	zend_destroy_rsrc_list(&EG(regular_list));
1308 
1309 	/* See GH-8646: https://github.com/php/php-src/issues/8646
1310 	 *
1311 	 * Interned strings that hold class entries can get a corresponding slot in map_ptr for the CE cache.
1312 	 * map_ptr works like a bump allocator: there is a counter which increases to allocate the next slot in the map.
1313 	 *
1314 	 * For class name strings in non-opcache we have:
1315 	 *   - on startup: permanent + interned
1316 	 *   - on request: interned
1317 	 * For class name strings in opcache we have:
1318 	 *   - on startup: permanent + interned
1319 	 *   - on request: either not interned at all, which we can ignore because they won't get a CE cache entry
1320 	 *                 or they were already permanent + interned
1321 	 *                 or we get a new permanent + interned string in the opcache persistence code
1322 	 *
1323 	 * Notice that the map_ptr layout always has the permanent strings first, and the request strings after.
1324 	 * In non-opcache, a request string may get a slot in map_ptr, and that interned request string
1325 	 * gets destroyed at the end of the request. The corresponding map_ptr slot can thereafter never be used again.
1326 	 * This causes map_ptr to keep reallocating to larger and larger sizes.
1327 	 *
1328 	 * We solve it as follows:
1329 	 * We can check whether we had any interned request strings, which only happens in non-opcache.
1330 	 * If we have any, we reset map_ptr to the last permanent string.
1331 	 * We can't lose any permanent strings because of map_ptr's layout.
1332 	 */
1333 	if (zend_hash_num_elements(&CG(interned_strings)) > 0) {
1334 		zend_map_ptr_reset();
1335 	}
1336 
1337 #if GC_BENCH
1338 	gc_bench_print();
1339 #endif
1340 }
1341 /* }}} */
1342 
zend_message_dispatcher(zend_long message,const void * data)1343 ZEND_API void zend_message_dispatcher(zend_long message, const void *data) /* {{{ */
1344 {
1345 	if (zend_message_dispatcher_p) {
1346 		zend_message_dispatcher_p(message, data);
1347 	}
1348 }
1349 /* }}} */
1350 
zend_get_configuration_directive(zend_string * name)1351 ZEND_API zval *zend_get_configuration_directive(zend_string *name) /* {{{ */
1352 {
1353 	if (zend_get_configuration_directive_p) {
1354 		return zend_get_configuration_directive_p(name);
1355 	} else {
1356 		return NULL;
1357 	}
1358 }
1359 /* }}} */
1360 
1361 #define SAVE_STACK(stack) do { \
1362 		if (CG(stack).top) { \
1363 			memcpy(&stack, &CG(stack), sizeof(zend_stack)); \
1364 			CG(stack).top = CG(stack).max = 0; \
1365 			CG(stack).elements = NULL; \
1366 		} else { \
1367 			stack.top = 0; \
1368 		} \
1369 	} while (0)
1370 
1371 #define RESTORE_STACK(stack) do { \
1372 		if (stack.top) { \
1373 			zend_stack_destroy(&CG(stack)); \
1374 			memcpy(&CG(stack), &stack, sizeof(zend_stack)); \
1375 		} \
1376 	} while (0)
1377 
zend_error_zstr_at(int orig_type,zend_string * error_filename,uint32_t error_lineno,zend_string * message)1378 ZEND_API ZEND_COLD void zend_error_zstr_at(
1379 		int orig_type, zend_string *error_filename, uint32_t error_lineno, zend_string *message)
1380 {
1381 	zval params[4];
1382 	zval retval;
1383 	zval orig_user_error_handler;
1384 	bool in_compilation;
1385 	zend_class_entry *saved_class_entry;
1386 	zend_stack loop_var_stack;
1387 	zend_stack delayed_oplines_stack;
1388 	int type = orig_type & E_ALL;
1389 	bool orig_record_errors;
1390 	uint32_t orig_num_errors;
1391 	zend_error_info **orig_errors;
1392 	zend_result res;
1393 
1394 	/* If we're executing a function during SCCP, count any warnings that may be emitted,
1395 	 * but don't perform any other error handling. */
1396 	if (EG(capture_warnings_during_sccp)) {
1397 		ZEND_ASSERT(!(type & E_FATAL_ERRORS) && "Fatal error during SCCP");
1398 		EG(capture_warnings_during_sccp)++;
1399 		return;
1400 	}
1401 
1402 	if (EG(record_errors)) {
1403 		zend_error_info *info = emalloc(sizeof(zend_error_info));
1404 		info->type = type;
1405 		info->lineno = error_lineno;
1406 		info->filename = zend_string_copy(error_filename);
1407 		info->message = zend_string_copy(message);
1408 
1409 		/* This is very inefficient for a large number of errors.
1410 		 * Use pow2 realloc if it becomes a problem. */
1411 		EG(num_errors)++;
1412 		EG(errors) = erealloc(EG(errors), sizeof(zend_error_info*) * EG(num_errors));
1413 		EG(errors)[EG(num_errors)-1] = info;
1414 	}
1415 
1416 	/* Report about uncaught exception in case of fatal errors */
1417 	if (EG(exception)) {
1418 		zend_execute_data *ex;
1419 		const zend_op *opline;
1420 
1421 		if (type & E_FATAL_ERRORS) {
1422 			ex = EG(current_execute_data);
1423 			opline = NULL;
1424 			while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
1425 				ex = ex->prev_execute_data;
1426 			}
1427 			if (ex && ex->opline->opcode == ZEND_HANDLE_EXCEPTION &&
1428 			    EG(opline_before_exception)) {
1429 				opline = EG(opline_before_exception);
1430 			}
1431 			zend_exception_error(EG(exception), E_WARNING);
1432 			EG(exception) = NULL;
1433 			if (opline) {
1434 				ex->opline = opline;
1435 			}
1436 		}
1437 	}
1438 
1439 	zend_observer_error_notify(type, error_filename, error_lineno, message);
1440 
1441 	/* if we don't have a user defined error handler */
1442 	if (Z_TYPE(EG(user_error_handler)) == IS_UNDEF
1443 		|| !(EG(user_error_handler_error_reporting) & type)
1444 		|| EG(error_handling) != EH_NORMAL) {
1445 		zend_error_cb(orig_type, error_filename, error_lineno, message);
1446 	} else switch (type) {
1447 		case E_ERROR:
1448 		case E_PARSE:
1449 		case E_CORE_ERROR:
1450 		case E_CORE_WARNING:
1451 		case E_COMPILE_ERROR:
1452 		case E_COMPILE_WARNING:
1453 			/* The error may not be safe to handle in user-space */
1454 			zend_error_cb(orig_type, error_filename, error_lineno, message);
1455 			break;
1456 		default:
1457 			/* Handle the error in user space */
1458 			ZVAL_STR_COPY(&params[1], message);
1459 			ZVAL_LONG(&params[0], type);
1460 
1461 			if (error_filename) {
1462 				ZVAL_STR_COPY(&params[2], error_filename);
1463 			} else {
1464 				ZVAL_NULL(&params[2]);
1465 			}
1466 
1467 			ZVAL_LONG(&params[3], error_lineno);
1468 
1469 			ZVAL_COPY_VALUE(&orig_user_error_handler, &EG(user_error_handler));
1470 			ZVAL_UNDEF(&EG(user_error_handler));
1471 
1472 			/* User error handler may include() additional PHP files.
1473 			 * If an error was generated during compilation PHP will compile
1474 			 * such scripts recursively, but some CG() variables may be
1475 			 * inconsistent. */
1476 
1477 			in_compilation = CG(in_compilation);
1478 			if (in_compilation) {
1479 				saved_class_entry = CG(active_class_entry);
1480 				CG(active_class_entry) = NULL;
1481 				SAVE_STACK(loop_var_stack);
1482 				SAVE_STACK(delayed_oplines_stack);
1483 				CG(in_compilation) = 0;
1484 			}
1485 
1486 			orig_record_errors = EG(record_errors);
1487 			orig_num_errors = EG(num_errors);
1488 			orig_errors = EG(errors);
1489 			EG(record_errors) = false;
1490 			EG(num_errors) = 0;
1491 			EG(errors) = NULL;
1492 
1493 			res = call_user_function(CG(function_table), NULL, &orig_user_error_handler, &retval, 4, params);
1494 
1495 			EG(record_errors) = orig_record_errors;
1496 			EG(num_errors) = orig_num_errors;
1497 			EG(errors) = orig_errors;
1498 
1499 			if (res == SUCCESS) {
1500 				if (Z_TYPE(retval) != IS_UNDEF) {
1501 					if (Z_TYPE(retval) == IS_FALSE) {
1502 						zend_error_cb(orig_type, error_filename, error_lineno, message);
1503 					}
1504 					zval_ptr_dtor(&retval);
1505 				}
1506 			} else if (!EG(exception)) {
1507 				/* The user error handler failed, use built-in error handler */
1508 				zend_error_cb(orig_type, error_filename, error_lineno, message);
1509 			}
1510 
1511 			if (in_compilation) {
1512 				CG(active_class_entry) = saved_class_entry;
1513 				RESTORE_STACK(loop_var_stack);
1514 				RESTORE_STACK(delayed_oplines_stack);
1515 				CG(in_compilation) = 1;
1516 			}
1517 
1518 			zval_ptr_dtor(&params[2]);
1519 			zval_ptr_dtor(&params[1]);
1520 
1521 			if (Z_TYPE(EG(user_error_handler)) == IS_UNDEF) {
1522 				ZVAL_COPY_VALUE(&EG(user_error_handler), &orig_user_error_handler);
1523 			} else {
1524 				zval_ptr_dtor(&orig_user_error_handler);
1525 			}
1526 			break;
1527 	}
1528 
1529 	if (type == E_PARSE) {
1530 		/* eval() errors do not affect exit_status */
1531 		if (!(EG(current_execute_data) &&
1532 			EG(current_execute_data)->func &&
1533 			ZEND_USER_CODE(EG(current_execute_data)->func->type) &&
1534 			EG(current_execute_data)->opline->opcode == ZEND_INCLUDE_OR_EVAL &&
1535 			EG(current_execute_data)->opline->extended_value == ZEND_EVAL)) {
1536 			EG(exit_status) = 255;
1537 		}
1538 	}
1539 }
1540 /* }}} */
1541 
zend_error_va_list(int orig_type,zend_string * error_filename,uint32_t error_lineno,const char * format,va_list args)1542 static ZEND_COLD void zend_error_va_list(
1543 		int orig_type, zend_string *error_filename, uint32_t error_lineno,
1544 		const char *format, va_list args)
1545 {
1546 	zend_string *message = zend_vstrpprintf(0, format, args);
1547 	zend_error_zstr_at(orig_type, error_filename, error_lineno, message);
1548 	zend_string_release(message);
1549 }
1550 
get_filename_lineno(int type,zend_string ** filename,uint32_t * lineno)1551 static ZEND_COLD void get_filename_lineno(int type, zend_string **filename, uint32_t *lineno) {
1552 	/* Obtain relevant filename and lineno */
1553 	switch (type) {
1554 		case E_CORE_ERROR:
1555 		case E_CORE_WARNING:
1556 			*filename = NULL;
1557 			*lineno = 0;
1558 			break;
1559 		case E_PARSE:
1560 		case E_COMPILE_ERROR:
1561 		case E_COMPILE_WARNING:
1562 		case E_ERROR:
1563 		case E_NOTICE:
1564 		case E_STRICT:
1565 		case E_DEPRECATED:
1566 		case E_WARNING:
1567 		case E_USER_ERROR:
1568 		case E_USER_WARNING:
1569 		case E_USER_NOTICE:
1570 		case E_USER_DEPRECATED:
1571 		case E_RECOVERABLE_ERROR:
1572 			if (zend_is_compiling()) {
1573 				*filename = zend_get_compiled_filename();
1574 				*lineno = zend_get_compiled_lineno();
1575 			} else if (zend_is_executing()) {
1576 				*filename = zend_get_executed_filename_ex();
1577 				*lineno = zend_get_executed_lineno();
1578 			} else {
1579 				*filename = NULL;
1580 				*lineno = 0;
1581 			}
1582 			break;
1583 		default:
1584 			*filename = NULL;
1585 			*lineno = 0;
1586 			break;
1587 	}
1588 	if (!*filename) {
1589 		*filename = ZSTR_KNOWN(ZEND_STR_UNKNOWN_CAPITALIZED);
1590 	}
1591 }
1592 
zend_error_at(int type,zend_string * filename,uint32_t lineno,const char * format,...)1593 ZEND_API ZEND_COLD void zend_error_at(
1594 		int type, zend_string *filename, uint32_t lineno, const char *format, ...) {
1595 	va_list args;
1596 
1597 	if (!filename) {
1598 		uint32_t dummy_lineno;
1599 		get_filename_lineno(type, &filename, &dummy_lineno);
1600 	}
1601 
1602 	va_start(args, format);
1603 	zend_error_va_list(type, filename, lineno, format, args);
1604 	va_end(args);
1605 }
1606 
1607 #define zend_error_impl(type, format) do { \
1608 		zend_string *filename; \
1609 		uint32_t lineno; \
1610 		va_list args; \
1611 		get_filename_lineno(type, &filename, &lineno); \
1612 		va_start(args, format); \
1613 		zend_error_va_list(type, filename, lineno, format, args); \
1614 		va_end(args); \
1615 	} while (0)
1616 
zend_error(int type,const char * format,...)1617 ZEND_API ZEND_COLD void zend_error(int type, const char *format, ...) {
1618 	zend_error_impl(type, format);
1619 }
1620 
zend_error_unchecked(int type,const char * format,...)1621 ZEND_API ZEND_COLD void zend_error_unchecked(int type, const char *format, ...) {
1622 	zend_error_impl(type, format);
1623 }
1624 
zend_error_at_noreturn(int type,zend_string * filename,uint32_t lineno,const char * format,...)1625 ZEND_API ZEND_COLD ZEND_NORETURN void zend_error_at_noreturn(
1626 		int type, zend_string *filename, uint32_t lineno, const char *format, ...)
1627 {
1628 	va_list args;
1629 
1630 	if (!filename) {
1631 		uint32_t dummy_lineno;
1632 		get_filename_lineno(type, &filename, &dummy_lineno);
1633 	}
1634 
1635 	va_start(args, format);
1636 	zend_error_va_list(type, filename, lineno, format, args);
1637 	va_end(args);
1638 	/* Should never reach this. */
1639 	abort();
1640 }
1641 
1642 #define zend_error_noreturn_impl(type, format) do { \
1643 		zend_string *filename; \
1644 		uint32_t lineno; \
1645 		va_list args; \
1646 		get_filename_lineno(type, &filename, &lineno); \
1647 		va_start(args, format); \
1648 		zend_error_va_list(type, filename, lineno, format, args); \
1649 		va_end(args); \
1650 		/* Should never reach this. */ \
1651 		abort(); \
1652 	} while (0)
1653 
zend_error_noreturn(int type,const char * format,...)1654 ZEND_API ZEND_COLD ZEND_NORETURN void zend_error_noreturn(int type, const char *format, ...)
1655 {
1656 	zend_error_noreturn_impl(type, format);
1657 }
1658 
zend_error_noreturn_unchecked(int type,const char * format,...)1659 ZEND_API ZEND_COLD ZEND_NORETURN void zend_error_noreturn_unchecked(int type, const char *format, ...)
1660 {
1661 	zend_error_noreturn_impl(type, format);
1662 }
1663 
zend_strerror_noreturn(int type,int errn,const char * message)1664 ZEND_API ZEND_COLD ZEND_NORETURN void zend_strerror_noreturn(int type, int errn, const char *message)
1665 {
1666 #ifdef HAVE_STRERROR_R
1667 	char b[1024];
1668 
1669 # ifdef STRERROR_R_CHAR_P
1670 	char *buf = strerror_r(errn, b, sizeof(b));
1671 # else
1672 	strerror_r(errn, b, sizeof(b));
1673 	char *buf = b;
1674 # endif
1675 #else
1676 	char *buf = strerror(errn);
1677 #endif
1678 
1679 	zend_error_noreturn(type, "%s: %s (%d)", message, buf, errn);
1680 }
1681 
zend_error_zstr(int type,zend_string * message)1682 ZEND_API ZEND_COLD void zend_error_zstr(int type, zend_string *message) {
1683 	zend_string *filename;
1684 	uint32_t lineno;
1685 	get_filename_lineno(type, &filename, &lineno);
1686 	zend_error_zstr_at(type, filename, lineno, message);
1687 }
1688 
zend_begin_record_errors(void)1689 ZEND_API void zend_begin_record_errors(void)
1690 {
1691 	ZEND_ASSERT(!EG(record_errors) && "Error recording already enabled");
1692 	EG(record_errors) = true;
1693 	EG(num_errors) = 0;
1694 	EG(errors) = NULL;
1695 }
1696 
zend_emit_recorded_errors(void)1697 ZEND_API void zend_emit_recorded_errors(void)
1698 {
1699 	EG(record_errors) = false;
1700 	for (uint32_t i = 0; i < EG(num_errors); i++) {
1701 		zend_error_info *error = EG(errors)[i];
1702 		zend_error_zstr_at(error->type, error->filename, error->lineno, error->message);
1703 	}
1704 }
1705 
zend_free_recorded_errors(void)1706 ZEND_API void zend_free_recorded_errors(void)
1707 {
1708 	if (!EG(num_errors)) {
1709 		return;
1710 	}
1711 
1712 	for (uint32_t i = 0; i < EG(num_errors); i++) {
1713 		zend_error_info *info = EG(errors)[i];
1714 		zend_string_release(info->filename);
1715 		zend_string_release(info->message);
1716 		efree(info);
1717 	}
1718 	efree(EG(errors));
1719 	EG(errors) = NULL;
1720 	EG(num_errors) = 0;
1721 }
1722 
zend_throw_error(zend_class_entry * exception_ce,const char * format,...)1723 ZEND_API ZEND_COLD void zend_throw_error(zend_class_entry *exception_ce, const char *format, ...) /* {{{ */
1724 {
1725 	va_list va;
1726 	char *message = NULL;
1727 
1728 	if (!exception_ce) {
1729 		exception_ce = zend_ce_error;
1730 	}
1731 
1732 	/* Marker used to disable exception generation during preloading. */
1733 	if (EG(exception) == (void*)(uintptr_t)-1) {
1734 		return;
1735 	}
1736 
1737 	va_start(va, format);
1738 	zend_vspprintf(&message, 0, format, va);
1739 
1740 	//TODO: we can't convert compile-time errors to exceptions yet???
1741 	if (EG(current_execute_data) && !CG(in_compilation)) {
1742 		zend_throw_exception(exception_ce, message, 0);
1743 	} else {
1744 		zend_error_noreturn(E_ERROR, "%s", message);
1745 	}
1746 
1747 	efree(message);
1748 	va_end(va);
1749 }
1750 /* }}} */
1751 
1752 /* type should be one of the BP_VAR_* constants, only special messages happen for isset/empty and unset */
zend_illegal_container_offset(const zend_string * container,const zval * offset,int type)1753 ZEND_API ZEND_COLD void zend_illegal_container_offset(const zend_string *container, const zval *offset, int type)
1754 {
1755 	switch (type) {
1756 		case BP_VAR_IS:
1757 			zend_type_error("Cannot access offset of type %s in isset or empty",
1758 				zend_zval_type_name(offset));
1759 			return;
1760 		case BP_VAR_UNSET:
1761 			/* Consistent error for when trying to unset a string offset */
1762 			if (zend_string_equals(container, ZSTR_KNOWN(ZEND_STR_STRING))) {
1763 				zend_throw_error(NULL, "Cannot unset string offsets");
1764 			} else {
1765 				zend_type_error("Cannot unset offset of type %s on %s", zend_zval_type_name(offset), ZSTR_VAL(container));
1766 			}
1767 			return;
1768 		default:
1769 			zend_type_error("Cannot access offset of type %s on %s",
1770 				zend_zval_type_name(offset), ZSTR_VAL(container));
1771 			return;
1772 	}
1773 }
1774 
zend_type_error(const char * format,...)1775 ZEND_API ZEND_COLD void zend_type_error(const char *format, ...) /* {{{ */
1776 {
1777 	va_list va;
1778 	char *message = NULL;
1779 
1780 	va_start(va, format);
1781 	zend_vspprintf(&message, 0, format, va);
1782 	zend_throw_exception(zend_ce_type_error, message, 0);
1783 	efree(message);
1784 	va_end(va);
1785 } /* }}} */
1786 
zend_argument_count_error(const char * format,...)1787 ZEND_API ZEND_COLD void zend_argument_count_error(const char *format, ...) /* {{{ */
1788 {
1789 	va_list va;
1790 	char *message = NULL;
1791 
1792 	va_start(va, format);
1793 	zend_vspprintf(&message, 0, format, va);
1794 	zend_throw_exception(zend_ce_argument_count_error, message, 0);
1795 	efree(message);
1796 
1797 	va_end(va);
1798 } /* }}} */
1799 
zend_value_error(const char * format,...)1800 ZEND_API ZEND_COLD void zend_value_error(const char *format, ...) /* {{{ */
1801 {
1802 	va_list va;
1803 	char *message = NULL;
1804 
1805 	va_start(va, format);
1806 	zend_vspprintf(&message, 0, format, va);
1807 	zend_throw_exception(zend_ce_value_error, message, 0);
1808 	efree(message);
1809 	va_end(va);
1810 } /* }}} */
1811 
zend_output_debug_string(bool trigger_break,const char * format,...)1812 ZEND_API ZEND_COLD void zend_output_debug_string(bool trigger_break, const char *format, ...) /* {{{ */
1813 {
1814 #if ZEND_DEBUG
1815 	va_list args;
1816 
1817 	va_start(args, format);
1818 #	ifdef ZEND_WIN32
1819 	{
1820 		char output_buf[1024];
1821 
1822 		vsnprintf(output_buf, 1024, format, args);
1823 		OutputDebugString(output_buf);
1824 		OutputDebugString("\n");
1825 		if (trigger_break && IsDebuggerPresent()) {
1826 			DebugBreak();
1827 		}
1828 	}
1829 #	else
1830 	vfprintf(stderr, format, args);
1831 	fprintf(stderr, "\n");
1832 #	endif
1833 	va_end(args);
1834 #endif
1835 }
1836 /* }}} */
1837 
zend_user_exception_handler(void)1838 ZEND_API ZEND_COLD void zend_user_exception_handler(void) /* {{{ */
1839 {
1840 	zval orig_user_exception_handler;
1841 	zval params[1], retval2;
1842 	zend_object *old_exception;
1843 
1844 	if (zend_is_unwind_exit(EG(exception))) {
1845 		return;
1846 	}
1847 
1848 	old_exception = EG(exception);
1849 	EG(exception) = NULL;
1850 	ZVAL_OBJ(&params[0], old_exception);
1851 	ZVAL_COPY_VALUE(&orig_user_exception_handler, &EG(user_exception_handler));
1852 	ZVAL_UNDEF(&EG(user_exception_handler));
1853 
1854 	if (call_user_function(CG(function_table), NULL, &orig_user_exception_handler, &retval2, 1, params) == SUCCESS) {
1855 		zval_ptr_dtor(&retval2);
1856 		if (EG(exception)) {
1857 			OBJ_RELEASE(EG(exception));
1858 			EG(exception) = NULL;
1859 		}
1860 		OBJ_RELEASE(old_exception);
1861 	} else {
1862 		EG(exception) = old_exception;
1863 	}
1864 
1865 	zval_ptr_dtor(&orig_user_exception_handler);
1866 } /* }}} */
1867 
zend_execute_script(int type,zval * retval,zend_file_handle * file_handle)1868 ZEND_API zend_result zend_execute_script(int type, zval *retval, zend_file_handle *file_handle)
1869 {
1870 	zend_op_array *op_array = zend_compile_file(file_handle, type);
1871 	if (file_handle->opened_path) {
1872 		zend_hash_add_empty_element(&EG(included_files), file_handle->opened_path);
1873 	}
1874 
1875 	zend_result ret = SUCCESS;
1876 	if (op_array) {
1877 		zend_execute(op_array, retval);
1878 		zend_exception_restore();
1879 		if (UNEXPECTED(EG(exception))) {
1880 			if (Z_TYPE(EG(user_exception_handler)) != IS_UNDEF) {
1881 				zend_user_exception_handler();
1882 			}
1883 			if (EG(exception)) {
1884 				ret = zend_exception_error(EG(exception), E_ERROR);
1885 			}
1886 		}
1887 		zend_destroy_static_vars(op_array);
1888 		destroy_op_array(op_array);
1889 		efree_size(op_array, sizeof(zend_op_array));
1890 	} else if (type == ZEND_REQUIRE) {
1891 		ret = FAILURE;
1892 	}
1893 
1894 	return ret;
1895 }
1896 
zend_execute_scripts(int type,zval * retval,int file_count,...)1897 ZEND_API zend_result zend_execute_scripts(int type, zval *retval, int file_count, ...) /* {{{ */
1898 {
1899 	va_list files;
1900 	int i;
1901 	zend_file_handle *file_handle;
1902 	zend_result ret = SUCCESS;
1903 
1904 	va_start(files, file_count);
1905 	for (i = 0; i < file_count; i++) {
1906 		file_handle = va_arg(files, zend_file_handle *);
1907 		if (!file_handle) {
1908 			continue;
1909 		}
1910 		if (ret == FAILURE) {
1911 			continue;
1912 		}
1913 		ret = zend_execute_script(type, retval, file_handle);
1914 	}
1915 	va_end(files);
1916 
1917 	return ret;
1918 }
1919 /* }}} */
1920 
1921 #define COMPILED_STRING_DESCRIPTION_FORMAT "%s(%d) : %s"
1922 
zend_make_compiled_string_description(const char * name)1923 ZEND_API char *zend_make_compiled_string_description(const char *name) /* {{{ */
1924 {
1925 	const char *cur_filename;
1926 	int cur_lineno;
1927 	char *compiled_string_description;
1928 
1929 	if (zend_is_compiling()) {
1930 		cur_filename = ZSTR_VAL(zend_get_compiled_filename());
1931 		cur_lineno = zend_get_compiled_lineno();
1932 	} else if (zend_is_executing()) {
1933 		cur_filename = zend_get_executed_filename();
1934 		cur_lineno = zend_get_executed_lineno();
1935 	} else {
1936 		cur_filename = "Unknown";
1937 		cur_lineno = 0;
1938 	}
1939 
1940 	zend_spprintf(&compiled_string_description, 0, COMPILED_STRING_DESCRIPTION_FORMAT, cur_filename, cur_lineno, name);
1941 	return compiled_string_description;
1942 }
1943 /* }}} */
1944 
free_estring(char ** str_p)1945 void free_estring(char **str_p) /* {{{ */
1946 {
1947 	efree(*str_p);
1948 }
1949 /* }}} */
1950 
zend_map_ptr_reset(void)1951 ZEND_API void zend_map_ptr_reset(void)
1952 {
1953 	CG(map_ptr_last) = global_map_ptr_last;
1954 }
1955 
zend_map_ptr_new(void)1956 ZEND_API void *zend_map_ptr_new(void)
1957 {
1958 	void **ptr;
1959 
1960 	if (CG(map_ptr_last) >= CG(map_ptr_size)) {
1961 		/* Grow map_ptr table */
1962 		CG(map_ptr_size) = ZEND_MM_ALIGNED_SIZE_EX(CG(map_ptr_last) + 1, 4096);
1963 		CG(map_ptr_real_base) = perealloc(CG(map_ptr_real_base), CG(map_ptr_size) * sizeof(void*), 1);
1964 		CG(map_ptr_base) = ZEND_MAP_PTR_BIASED_BASE(CG(map_ptr_real_base));
1965 	}
1966 	ptr = (void**)CG(map_ptr_real_base) + CG(map_ptr_last);
1967 	*ptr = NULL;
1968 	CG(map_ptr_last)++;
1969 	return ZEND_MAP_PTR_PTR2OFFSET(ptr);
1970 }
1971 
zend_map_ptr_extend(size_t last)1972 ZEND_API void zend_map_ptr_extend(size_t last)
1973 {
1974 	if (last > CG(map_ptr_last)) {
1975 		void **ptr;
1976 
1977 		if (last >= CG(map_ptr_size)) {
1978 			/* Grow map_ptr table */
1979 			CG(map_ptr_size) = ZEND_MM_ALIGNED_SIZE_EX(last, 4096);
1980 			CG(map_ptr_real_base) = perealloc(CG(map_ptr_real_base), CG(map_ptr_size) * sizeof(void*), 1);
1981 			CG(map_ptr_base) = ZEND_MAP_PTR_BIASED_BASE(CG(map_ptr_real_base));
1982 		}
1983 		ptr = (void**)CG(map_ptr_real_base) + CG(map_ptr_last);
1984 		memset(ptr, 0, (last - CG(map_ptr_last)) * sizeof(void*));
1985 		CG(map_ptr_last) = last;
1986 	}
1987 }
1988 
zend_alloc_ce_cache(zend_string * type_name)1989 ZEND_API void zend_alloc_ce_cache(zend_string *type_name)
1990 {
1991 	if (ZSTR_HAS_CE_CACHE(type_name) || !ZSTR_IS_INTERNED(type_name)) {
1992 		return;
1993 	}
1994 
1995 	if ((GC_FLAGS(type_name) & IS_STR_PERMANENT) && startup_done) {
1996 		/* Don't allocate slot on permanent interned string outside module startup.
1997 		 * The cache slot would no longer be valid on the next request. */
1998 		return;
1999 	}
2000 
2001 	if (zend_string_equals_literal_ci(type_name, "self")
2002 			|| zend_string_equals_literal_ci(type_name, "parent")) {
2003 		return;
2004 	}
2005 
2006 	/* We use the refcount to keep map_ptr of corresponding type */
2007 	uint32_t ret;
2008 	do {
2009 		ret = ZEND_MAP_PTR_NEW_OFFSET();
2010 	} while (ret <= 2);
2011 	GC_ADD_FLAGS(type_name, IS_STR_CLASS_NAME_MAP_PTR);
2012 	GC_SET_REFCOUNT(type_name, ret);
2013 }
2014