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