xref: /PHP-8.3/Zend/zend_exceptions.c (revision 498e8848)
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    |          Marcus Boerger <helly@php.net>                              |
17    |          Sterling Hughes <sterling@php.net>                          |
18    |          Zeev Suraski <zeev@php.net>                                 |
19    +----------------------------------------------------------------------+
20 */
21 
22 #include "zend.h"
23 #include "zend_API.h"
24 #include "zend_builtin_functions.h"
25 #include "zend_interfaces.h"
26 #include "zend_exceptions.h"
27 #include "zend_vm.h"
28 #include "zend_dtrace.h"
29 #include "zend_smart_str.h"
30 #include "zend_exceptions_arginfo.h"
31 #include "zend_observer.h"
32 
33 ZEND_API zend_class_entry *zend_ce_throwable;
34 ZEND_API zend_class_entry *zend_ce_exception;
35 ZEND_API zend_class_entry *zend_ce_error_exception;
36 ZEND_API zend_class_entry *zend_ce_error;
37 ZEND_API zend_class_entry *zend_ce_compile_error;
38 ZEND_API zend_class_entry *zend_ce_parse_error;
39 ZEND_API zend_class_entry *zend_ce_type_error;
40 ZEND_API zend_class_entry *zend_ce_argument_count_error;
41 ZEND_API zend_class_entry *zend_ce_value_error;
42 ZEND_API zend_class_entry *zend_ce_arithmetic_error;
43 ZEND_API zend_class_entry *zend_ce_division_by_zero_error;
44 ZEND_API zend_class_entry *zend_ce_unhandled_match_error;
45 
46 /* Internal pseudo-exception that is not exposed to userland. Throwing this exception *does not* execute finally blocks. */
47 static zend_class_entry zend_ce_unwind_exit;
48 
49 /* Internal pseudo-exception that is not exposed to userland. Throwing this exception *does* execute finally blocks. */
50 static zend_class_entry zend_ce_graceful_exit;
51 
52 ZEND_API void (*zend_throw_exception_hook)(zend_object *ex);
53 
54 static zend_object_handlers default_exception_handlers;
55 
56 /* {{{ zend_implement_throwable */
zend_implement_throwable(zend_class_entry * interface,zend_class_entry * class_type)57 static int zend_implement_throwable(zend_class_entry *interface, zend_class_entry *class_type)
58 {
59 	/* zend_ce_exception and zend_ce_error may not be initialized yet when this is called (e.g when
60 	 * implementing Throwable for Exception itself). Perform a manual inheritance check. */
61 	zend_class_entry *root = class_type;
62 	while (root->parent) {
63 		root = root->parent;
64 	}
65 	if (zend_string_equals_literal(root->name, "Exception")
66 			|| zend_string_equals_literal(root->name, "Error")) {
67 		return SUCCESS;
68 	}
69 
70 	bool can_extend = (class_type->ce_flags & ZEND_ACC_ENUM) == 0;
71 
72 	zend_error_noreturn(E_ERROR,
73 		can_extend
74 			? "%s %s cannot implement interface %s, extend Exception or Error instead"
75 			: "%s %s cannot implement interface %s",
76 		zend_get_object_type_uc(class_type),
77 		ZSTR_VAL(class_type->name),
78 		ZSTR_VAL(interface->name));
79 	return FAILURE;
80 }
81 /* }}} */
82 
i_get_exception_base(zend_object * object)83 static inline zend_class_entry *i_get_exception_base(zend_object *object) /* {{{ */
84 {
85 	return instanceof_function(object->ce, zend_ce_exception) ? zend_ce_exception : zend_ce_error;
86 }
87 /* }}} */
88 
zend_get_exception_base(zend_object * object)89 ZEND_API zend_class_entry *zend_get_exception_base(zend_object *object) /* {{{ */
90 {
91 	return i_get_exception_base(object);
92 }
93 /* }}} */
94 
zend_exception_set_previous(zend_object * exception,zend_object * add_previous)95 void zend_exception_set_previous(zend_object *exception, zend_object *add_previous) /* {{{ */
96 {
97 	zval *previous, *ancestor, *ex;
98 	zval  pv, zv, rv;
99 	zend_class_entry *base_ce;
100 
101 	if (!exception || !add_previous) {
102 		return;
103 	}
104 
105 	if (exception == add_previous || zend_is_unwind_exit(add_previous) || zend_is_graceful_exit(add_previous)) {
106 		OBJ_RELEASE(add_previous);
107 		return;
108 	}
109 
110 	ZEND_ASSERT(instanceof_function(add_previous->ce, zend_ce_throwable)
111 		&& "Previous exception must implement Throwable");
112 
113 	ZVAL_OBJ(&pv, add_previous);
114 	ZVAL_OBJ(&zv, exception);
115 	ex = &zv;
116 	do {
117 		ancestor = zend_read_property_ex(i_get_exception_base(add_previous), add_previous, ZSTR_KNOWN(ZEND_STR_PREVIOUS), 1, &rv);
118 		ZVAL_DEREF(ancestor);
119 		while (Z_TYPE_P(ancestor) == IS_OBJECT) {
120 			if (Z_OBJ_P(ancestor) == Z_OBJ_P(ex)) {
121 				OBJ_RELEASE(add_previous);
122 				return;
123 			}
124 			ancestor = zend_read_property_ex(i_get_exception_base(Z_OBJ_P(ancestor)), Z_OBJ_P(ancestor), ZSTR_KNOWN(ZEND_STR_PREVIOUS), 1, &rv);
125 			ZVAL_DEREF(ancestor);
126 		}
127 		base_ce = i_get_exception_base(Z_OBJ_P(ex));
128 		previous = zend_read_property_ex(base_ce, Z_OBJ_P(ex), ZSTR_KNOWN(ZEND_STR_PREVIOUS), 1, &rv);
129 		ZVAL_DEREF(previous);
130 		if (Z_TYPE_P(previous) == IS_NULL) {
131 			zend_update_property_ex(base_ce, Z_OBJ_P(ex), ZSTR_KNOWN(ZEND_STR_PREVIOUS), &pv);
132 			GC_DELREF(add_previous);
133 			return;
134 		}
135 		ex = previous;
136 	} while (Z_OBJ_P(ex) != add_previous);
137 }
138 /* }}} */
139 
zend_exception_save(void)140 void zend_exception_save(void) /* {{{ */
141 {
142 	if (EG(prev_exception)) {
143 		zend_exception_set_previous(EG(exception), EG(prev_exception));
144 	}
145 	if (EG(exception)) {
146 		EG(prev_exception) = EG(exception);
147 	}
148 	EG(exception) = NULL;
149 }
150 /* }}} */
151 
zend_exception_restore(void)152 void zend_exception_restore(void) /* {{{ */
153 {
154 	if (EG(prev_exception)) {
155 		if (EG(exception)) {
156 			zend_exception_set_previous(EG(exception), EG(prev_exception));
157 		} else {
158 			EG(exception) = EG(prev_exception);
159 		}
160 		EG(prev_exception) = NULL;
161 	}
162 }
163 /* }}} */
164 
is_handle_exception_set(void)165 static zend_always_inline bool is_handle_exception_set(void) {
166 	zend_execute_data *execute_data = EG(current_execute_data);
167 	return !execute_data
168 		|| !execute_data->func
169 		|| !ZEND_USER_CODE(execute_data->func->common.type)
170 		|| execute_data->opline->opcode == ZEND_HANDLE_EXCEPTION;
171 }
172 
zend_throw_exception_internal(zend_object * exception)173 ZEND_API ZEND_COLD void zend_throw_exception_internal(zend_object *exception) /* {{{ */
174 {
175 #ifdef HAVE_DTRACE
176 	if (DTRACE_EXCEPTION_THROWN_ENABLED()) {
177 		if (exception != NULL) {
178 			DTRACE_EXCEPTION_THROWN(ZSTR_VAL(exception->ce->name));
179 		} else {
180 			DTRACE_EXCEPTION_THROWN(NULL);
181 		}
182 	}
183 #endif /* HAVE_DTRACE */
184 
185 	if (exception != NULL) {
186 		zend_object *previous = EG(exception);
187 		if (previous && zend_is_unwind_exit(previous)) {
188 			/* Don't replace unwinding exception with different exception. */
189 			OBJ_RELEASE(exception);
190 			return;
191 		}
192 
193 		zend_exception_set_previous(exception, EG(exception));
194 		EG(exception) = exception;
195 		if (previous) {
196 			ZEND_ASSERT(is_handle_exception_set() && "HANDLE_EXCEPTION not set?");
197 			return;
198 		}
199 	}
200 	if (!EG(current_execute_data)) {
201 		if (exception && (exception->ce == zend_ce_parse_error || exception->ce == zend_ce_compile_error)) {
202 			return;
203 		}
204 		if (EG(exception)) {
205 			if (Z_TYPE(EG(user_exception_handler)) != IS_UNDEF
206 			 && !zend_is_unwind_exit(EG(exception))
207 			 && !zend_is_graceful_exit(EG(exception))) {
208 				zend_user_exception_handler();
209 				if (EG(exception)) {
210 					zend_exception_error(EG(exception), E_ERROR);
211 				}
212 				return;
213 			} else {
214 				zend_exception_error(EG(exception), E_ERROR);
215 			}
216 			zend_bailout();
217 		}
218 		zend_error_noreturn(E_CORE_ERROR, "Exception thrown without a stack frame");
219 	}
220 
221 	if (zend_throw_exception_hook) {
222 		zend_throw_exception_hook(exception);
223 	}
224 
225 	if (is_handle_exception_set()) {
226 		/* no need to rethrow the exception */
227 		return;
228 	}
229 	EG(opline_before_exception) = EG(current_execute_data)->opline;
230 	EG(current_execute_data)->opline = EG(exception_op);
231 }
232 /* }}} */
233 
zend_clear_exception(void)234 ZEND_API void zend_clear_exception(void) /* {{{ */
235 {
236 	zend_object *exception;
237 	if (EG(prev_exception)) {
238 		OBJ_RELEASE(EG(prev_exception));
239 		EG(prev_exception) = NULL;
240 	}
241 	if (!EG(exception)) {
242 		return;
243 	}
244 	/* exception may have destructor */
245 	exception = EG(exception);
246 	EG(exception) = NULL;
247 	OBJ_RELEASE(exception);
248 	if (EG(current_execute_data)) {
249 		EG(current_execute_data)->opline = EG(opline_before_exception);
250 	}
251 #if ZEND_DEBUG
252 	EG(opline_before_exception) = NULL;
253 #endif
254 }
255 /* }}} */
256 
zend_default_exception_new(zend_class_entry * class_type)257 static zend_object *zend_default_exception_new(zend_class_entry *class_type) /* {{{ */
258 {
259 	zval tmp;
260 	zval trace;
261 	zend_class_entry *base_ce;
262 	zend_string *filename;
263 
264 	zend_object *object = zend_objects_new(class_type);
265 	object_properties_init(object, class_type);
266 
267 	if (EG(current_execute_data)) {
268 		zend_fetch_debug_backtrace(&trace,
269 			0,
270 			EG(exception_ignore_args) ? DEBUG_BACKTRACE_IGNORE_ARGS : 0, 0);
271 	} else {
272 		array_init(&trace);
273 	}
274 	Z_SET_REFCOUNT(trace, 0);
275 
276 	base_ce = i_get_exception_base(object);
277 
278 	if (EXPECTED((class_type != zend_ce_parse_error && class_type != zend_ce_compile_error)
279 			|| !(filename = zend_get_compiled_filename()))) {
280 		ZVAL_STRING(&tmp, zend_get_executed_filename());
281 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_FILE), &tmp);
282 		zval_ptr_dtor(&tmp);
283 		ZVAL_LONG(&tmp, zend_get_executed_lineno());
284 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
285 	} else {
286 		ZVAL_STR(&tmp, filename);
287 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_FILE), &tmp);
288 		ZVAL_LONG(&tmp, zend_get_compiled_lineno());
289 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
290 	}
291 	zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_TRACE), &trace);
292 
293 	return object;
294 }
295 /* }}} */
296 
297 /* {{{ Clone the exception object */
ZEND_METHOD(Exception,__clone)298 ZEND_COLD ZEND_METHOD(Exception, __clone)
299 {
300 	/* Should never be executable */
301 	zend_throw_exception(NULL, "Cannot clone object using __clone()", 0);
302 }
303 /* }}} */
304 
305 /* {{{ Exception constructor */
ZEND_METHOD(Exception,__construct)306 ZEND_METHOD(Exception, __construct)
307 {
308 	zend_string *message = NULL;
309 	zend_long   code = 0;
310 	zval  tmp, *object, *previous = NULL;
311 	zend_class_entry *base_ce;
312 
313 	object = ZEND_THIS;
314 	base_ce = i_get_exception_base(Z_OBJ_P(object));
315 
316 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|SlO!", &message, &code, &previous, zend_ce_throwable) == FAILURE) {
317 		RETURN_THROWS();
318 	}
319 
320 	if (message) {
321 		ZVAL_STR(&tmp, message);
322 		zend_update_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_MESSAGE), &tmp);
323 	}
324 
325 	if (code) {
326 		ZVAL_LONG(&tmp, code);
327 		zend_update_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_CODE), &tmp);
328 	}
329 
330 	if (previous) {
331 		zend_update_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_PREVIOUS), previous);
332 	}
333 }
334 /* }}} */
335 
336 /* {{{ Exception unserialize checks */
337 #define CHECK_EXC_TYPE(id, type) \
338 	pvalue = zend_read_property_ex(i_get_exception_base(Z_OBJ_P(object)), Z_OBJ_P(object), ZSTR_KNOWN(id), 1, &value); \
339 	if (Z_TYPE_P(pvalue) != IS_NULL && Z_TYPE_P(pvalue) != type) { \
340 		zend_unset_property(i_get_exception_base(Z_OBJ_P(object)), Z_OBJ_P(object), ZSTR_VAL(ZSTR_KNOWN(id)), ZSTR_LEN(ZSTR_KNOWN(id))); \
341 	}
342 
ZEND_METHOD(Exception,__wakeup)343 ZEND_METHOD(Exception, __wakeup)
344 {
345 	ZEND_PARSE_PARAMETERS_NONE();
346 
347 	zval value, *pvalue;
348 	zval *object = ZEND_THIS;
349 	CHECK_EXC_TYPE(ZEND_STR_MESSAGE, IS_STRING);
350 	CHECK_EXC_TYPE(ZEND_STR_CODE,    IS_LONG);
351 	/* The type of all other properties is enforced through typed properties. */
352 }
353 /* }}} */
354 
355 /* {{{ ErrorException constructor */
ZEND_METHOD(ErrorException,__construct)356 ZEND_METHOD(ErrorException, __construct)
357 {
358 	zend_string *message = NULL, *filename = NULL;
359 	zend_long   code = 0, severity = E_ERROR, lineno;
360 	bool lineno_is_null = 1;
361 	zval   tmp, *object, *previous = NULL;
362 
363 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|SllS!l!O!", &message, &code, &severity, &filename, &lineno, &lineno_is_null, &previous, zend_ce_throwable) == FAILURE) {
364 		RETURN_THROWS();
365 	}
366 
367 	object = ZEND_THIS;
368 
369 	if (message) {
370 		ZVAL_STR_COPY(&tmp, message);
371 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_MESSAGE), &tmp);
372 		zval_ptr_dtor(&tmp);
373 	}
374 
375 	if (code) {
376 		ZVAL_LONG(&tmp, code);
377 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_CODE), &tmp);
378 	}
379 
380 	if (previous) {
381 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_PREVIOUS), previous);
382 	}
383 
384 	ZVAL_LONG(&tmp, severity);
385 	zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_SEVERITY), &tmp);
386 
387 	if (filename) {
388 		ZVAL_STR_COPY(&tmp, filename);
389 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_FILE), &tmp);
390 		zval_ptr_dtor(&tmp);
391 	}
392 
393 	if (!lineno_is_null) {
394 		ZVAL_LONG(&tmp, lineno);
395 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
396 	} else if (filename) {
397 		ZVAL_LONG(&tmp, 0);
398 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
399 	}
400 }
401 /* }}} */
402 
403 #define GET_PROPERTY(object, id) \
404 	zend_read_property_ex(i_get_exception_base(Z_OBJ_P(object)), Z_OBJ_P(object), ZSTR_KNOWN(id), 0, &rv)
405 #define GET_PROPERTY_SILENT(object, id) \
406 	zend_read_property_ex(i_get_exception_base(Z_OBJ_P(object)), Z_OBJ_P(object), ZSTR_KNOWN(id), 1, &rv)
407 
408 /* {{{ Get the file in which the exception occurred */
ZEND_METHOD(Exception,getFile)409 ZEND_METHOD(Exception, getFile)
410 {
411 	zval *prop, rv;
412 
413 	ZEND_PARSE_PARAMETERS_NONE();
414 
415 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_FILE);
416 	RETURN_STR(zval_get_string(prop));
417 }
418 /* }}} */
419 
420 /* {{{ Get the line in which the exception occurred */
ZEND_METHOD(Exception,getLine)421 ZEND_METHOD(Exception, getLine)
422 {
423 	zval *prop, rv;
424 
425 	ZEND_PARSE_PARAMETERS_NONE();
426 
427 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_LINE);
428 	RETURN_LONG(zval_get_long(prop));
429 }
430 /* }}} */
431 
432 /* {{{ Get the exception message */
ZEND_METHOD(Exception,getMessage)433 ZEND_METHOD(Exception, getMessage)
434 {
435 	zval *prop, rv;
436 
437 	ZEND_PARSE_PARAMETERS_NONE();
438 
439 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_MESSAGE);
440 	RETURN_STR(zval_get_string(prop));
441 }
442 /* }}} */
443 
444 /* {{{ Get the exception code */
ZEND_METHOD(Exception,getCode)445 ZEND_METHOD(Exception, getCode)
446 {
447 	zval *prop, rv;
448 
449 	ZEND_PARSE_PARAMETERS_NONE();
450 
451 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_CODE);
452 	ZVAL_DEREF(prop);
453 	ZVAL_COPY(return_value, prop);
454 }
455 /* }}} */
456 
457 /* {{{ Get the stack trace for the location in which the exception occurred */
ZEND_METHOD(Exception,getTrace)458 ZEND_METHOD(Exception, getTrace)
459 {
460 	zval *prop, rv;
461 
462 	ZEND_PARSE_PARAMETERS_NONE();
463 
464 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_TRACE);
465 	ZVAL_DEREF(prop);
466 	ZVAL_COPY(return_value, prop);
467 }
468 /* }}} */
469 
470 /* {{{ Get the exception severity */
ZEND_METHOD(ErrorException,getSeverity)471 ZEND_METHOD(ErrorException, getSeverity)
472 {
473 	zval *prop, rv;
474 
475 	ZEND_PARSE_PARAMETERS_NONE();
476 
477 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_SEVERITY);
478 	ZVAL_DEREF(prop);
479 	ZVAL_COPY(return_value, prop);
480 }
481 /* }}} */
482 
483 #define TRACE_APPEND_KEY(key) do {                                          \
484 		tmp = zend_hash_find(ht, key);                                      \
485 		if (tmp) {                                                          \
486 			if (Z_TYPE_P(tmp) != IS_STRING) {                               \
487 				zend_error(E_WARNING, "Value for %s is not a string",       \
488 					ZSTR_VAL(key));                                         \
489 				smart_str_appends(str, "[unknown]");                        \
490 			} else {                                                        \
491 				smart_str_appends(str, Z_STRVAL_P(tmp));                    \
492 			}                                                               \
493 		} \
494 	} while (0)
495 
_build_trace_args(zval * arg,smart_str * str)496 static void _build_trace_args(zval *arg, smart_str *str) /* {{{ */
497 {
498 	/* the trivial way would be to do
499 	 * convert_to_string(arg);
500 	 * append it and kill the now tmp arg.
501 	 * but that could cause some E_NOTICE and also damn long lines.
502 	 */
503 
504 	ZVAL_DEREF(arg);
505 
506 	if (Z_TYPE_P(arg) <= IS_STRING) {
507 		smart_str_append_scalar(str, arg, EG(exception_string_param_max_len));
508 		smart_str_appends(str, ", ");
509 	} else {
510 		switch (Z_TYPE_P(arg)) {
511 			case IS_RESOURCE:
512 				smart_str_appends(str, "Resource id #");
513 				smart_str_append_long(str, Z_RES_HANDLE_P(arg));
514 				smart_str_appends(str, ", ");
515 				break;
516 			case IS_ARRAY:
517 				smart_str_appends(str, "Array, ");
518 				break;
519 			case IS_OBJECT: {
520 				zend_string *class_name = Z_OBJ_HANDLER_P(arg, get_class_name)(Z_OBJ_P(arg));
521 				smart_str_appends(str, "Object(");
522 				smart_str_appends(str, ZSTR_VAL(class_name));
523 				smart_str_appends(str, "), ");
524 				zend_string_release_ex(class_name, 0);
525 				break;
526 			}
527 		}
528 	}
529 }
530 /* }}} */
531 
_build_trace_string(smart_str * str,HashTable * ht,uint32_t num)532 static void _build_trace_string(smart_str *str, HashTable *ht, uint32_t num) /* {{{ */
533 {
534 	zval *file, *tmp;
535 
536 	smart_str_appendc(str, '#');
537 	smart_str_append_long(str, num);
538 	smart_str_appendc(str, ' ');
539 
540 	file = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_FILE));
541 	if (file) {
542 		if (Z_TYPE_P(file) != IS_STRING) {
543 			zend_error(E_WARNING, "File name is not a string");
544 			smart_str_appends(str, "[unknown file]: ");
545 		} else{
546 			zend_long line = 0;
547 			tmp = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_LINE));
548 			if (tmp) {
549 				if (Z_TYPE_P(tmp) == IS_LONG) {
550 					line = Z_LVAL_P(tmp);
551 				} else {
552 					zend_error(E_WARNING, "Line is not an int");
553 				}
554 			}
555 			smart_str_append(str, Z_STR_P(file));
556 			smart_str_appendc(str, '(');
557 			smart_str_append_long(str, line);
558 			smart_str_appends(str, "): ");
559 		}
560 	} else {
561 		smart_str_appends(str, "[internal function]: ");
562 	}
563 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_CLASS));
564 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_TYPE));
565 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_FUNCTION));
566 	smart_str_appendc(str, '(');
567 	tmp = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_ARGS));
568 	if (tmp) {
569 		if (Z_TYPE_P(tmp) == IS_ARRAY) {
570 			size_t last_len = ZSTR_LEN(str->s);
571 			zend_string *name;
572 			zval *arg;
573 
574 			ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(tmp), name, arg) {
575 				if (name) {
576 					smart_str_append(str, name);
577 					smart_str_appends(str, ": ");
578 				}
579 				_build_trace_args(arg, str);
580 			} ZEND_HASH_FOREACH_END();
581 
582 			if (last_len != ZSTR_LEN(str->s)) {
583 				ZSTR_LEN(str->s) -= 2; /* remove last ', ' */
584 			}
585 		} else {
586 			zend_error(E_WARNING, "args element is not an array");
587 		}
588 	}
589 	smart_str_appends(str, ")\n");
590 }
591 /* }}} */
592 
zend_trace_to_string(HashTable * trace,bool include_main)593 ZEND_API zend_string *zend_trace_to_string(HashTable *trace, bool include_main) {
594 	zend_ulong index;
595 	zval *frame;
596 	uint32_t num = 0;
597 	smart_str str = {0};
598 
599 	ZEND_HASH_FOREACH_NUM_KEY_VAL(trace, index, frame) {
600 		if (Z_TYPE_P(frame) != IS_ARRAY) {
601 			zend_error(E_WARNING, "Expected array for frame " ZEND_ULONG_FMT, index);
602 			continue;
603 		}
604 
605 		_build_trace_string(&str, Z_ARRVAL_P(frame), num++);
606 	} ZEND_HASH_FOREACH_END();
607 
608 	if (include_main) {
609 		smart_str_appendc(&str, '#');
610 		smart_str_append_long(&str, num);
611 		smart_str_appends(&str, " {main}");
612 	}
613 
614 	smart_str_0(&str);
615 	return str.s ? str.s : ZSTR_EMPTY_ALLOC();
616 }
617 
618 /* {{{ Obtain the backtrace for the exception as a string (instead of an array) */
ZEND_METHOD(Exception,getTraceAsString)619 ZEND_METHOD(Exception, getTraceAsString)
620 {
621 
622 	ZEND_PARSE_PARAMETERS_NONE();
623 
624 	zval *object = ZEND_THIS;
625 	zend_class_entry *base_ce = i_get_exception_base(Z_OBJ_P(object));
626 	zval rv;
627 	zval *trace = zend_read_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_TRACE), 1, &rv);
628 	if (EG(exception)) {
629 		RETURN_THROWS();
630 	}
631 
632 	ZVAL_DEREF(trace);
633 	/* Type should be guaranteed by property type. */
634 	ZEND_ASSERT(Z_TYPE_P(trace) == IS_ARRAY);
635 	RETURN_NEW_STR(zend_trace_to_string(Z_ARRVAL_P(trace), /* include_main */ true));
636 }
637 /* }}} */
638 
639 /* {{{ Return previous Throwable or NULL. */
ZEND_METHOD(Exception,getPrevious)640 ZEND_METHOD(Exception, getPrevious)
641 {
642 	zval rv;
643 
644 	ZEND_PARSE_PARAMETERS_NONE();
645 
646 	ZVAL_COPY_DEREF(return_value, GET_PROPERTY_SILENT(ZEND_THIS, ZEND_STR_PREVIOUS));
647 } /* }}} */
648 
649 /* {{{ Obtain the string representation of the Exception object */
ZEND_METHOD(Exception,__toString)650 ZEND_METHOD(Exception, __toString)
651 {
652 	zval trace, *exception;
653 	zend_class_entry *base_ce;
654 	zend_string *str;
655 	zend_fcall_info fci;
656 	zval rv, tmp;
657 	zend_string *fname;
658 
659 	ZEND_PARSE_PARAMETERS_NONE();
660 
661 	str = ZSTR_EMPTY_ALLOC();
662 
663 	exception = ZEND_THIS;
664 	fname = ZSTR_INIT_LITERAL("gettraceasstring", 0);
665 
666 	while (exception && Z_TYPE_P(exception) == IS_OBJECT && instanceof_function(Z_OBJCE_P(exception), zend_ce_throwable)) {
667 		zend_string *prev_str = str;
668 		zend_string *message = zval_get_string(GET_PROPERTY(exception, ZEND_STR_MESSAGE));
669 		zend_string *file = zval_get_string(GET_PROPERTY(exception, ZEND_STR_FILE));
670 		zend_long line = zval_get_long(GET_PROPERTY(exception, ZEND_STR_LINE));
671 
672 		fci.size = sizeof(fci);
673 		ZVAL_STR(&fci.function_name, fname);
674 		fci.object = Z_OBJ_P(exception);
675 		fci.retval = &trace;
676 		fci.param_count = 0;
677 		fci.params = NULL;
678 		fci.named_params = NULL;
679 
680 		zend_call_function(&fci, NULL);
681 
682 		if (Z_TYPE(trace) != IS_STRING) {
683 			zval_ptr_dtor(&trace);
684 			ZVAL_UNDEF(&trace);
685 		}
686 
687 		if ((Z_OBJCE_P(exception) == zend_ce_type_error || Z_OBJCE_P(exception) == zend_ce_argument_count_error) && strstr(ZSTR_VAL(message), ", called in ")) {
688 			zval message_zv;
689 			ZVAL_STR(&message_zv, message);
690 			zend_string *real_message = zend_strpprintf_unchecked(0, "%Z and defined", &message_zv);
691 			zend_string_release_ex(message, 0);
692 			message = real_message;
693 		}
694 
695 		zend_string *tmp_trace = (Z_TYPE(trace) == IS_STRING && Z_STRLEN(trace))
696 			? zend_string_copy(Z_STR(trace))
697 			: ZSTR_INIT_LITERAL("#0 {main}\n", false);
698 
699 		zval name_zv, trace_zv, file_zv, prev_str_zv;
700 		ZVAL_STR(&name_zv, Z_OBJCE_P(exception)->name);
701 		ZVAL_STR(&trace_zv, tmp_trace);
702 		ZVAL_STR(&file_zv, file);
703 		ZVAL_STR(&prev_str_zv, prev_str);
704 
705 		if (ZSTR_LEN(message) > 0) {
706 			zval message_zv;
707 			ZVAL_STR(&message_zv, message);
708 
709 			str = zend_strpprintf_unchecked(0, "%Z: %Z in %Z:" ZEND_LONG_FMT "\nStack trace:\n%Z%s%Z",
710 				&name_zv, &message_zv, &file_zv, line,
711 				&trace_zv, ZSTR_LEN(prev_str) ? "\n\nNext " : "", &prev_str_zv);
712 		} else {
713 			str = zend_strpprintf_unchecked(0, "%Z in %Z:" ZEND_LONG_FMT "\nStack trace:\n%Z%s%Z",
714 				&name_zv, &file_zv, line,
715 				&trace_zv, ZSTR_LEN(prev_str) ? "\n\nNext " : "", &prev_str_zv);
716 		}
717 		zend_string_release_ex(tmp_trace, false);
718 
719 		zend_string_release_ex(prev_str, 0);
720 		zend_string_release_ex(message, 0);
721 		zend_string_release_ex(file, 0);
722 		zval_ptr_dtor(&trace);
723 
724 		Z_PROTECT_RECURSION_P(exception);
725 		exception = GET_PROPERTY(exception, ZEND_STR_PREVIOUS);
726 		ZVAL_DEREF(exception);
727 		if (Z_TYPE_P(exception) == IS_OBJECT && Z_IS_RECURSIVE_P(exception)) {
728 			break;
729 		}
730 	}
731 	zend_string_release_ex(fname, 0);
732 
733 	exception = ZEND_THIS;
734 	/* Reset apply counts */
735 	while (Z_TYPE_P(exception) == IS_OBJECT && (base_ce = i_get_exception_base(Z_OBJ_P(exception))) && instanceof_function(Z_OBJCE_P(exception), base_ce)) {
736 		if (Z_IS_RECURSIVE_P(exception)) {
737 			Z_UNPROTECT_RECURSION_P(exception);
738 		} else {
739 			break;
740 		}
741 		exception = GET_PROPERTY(exception, ZEND_STR_PREVIOUS);
742 		ZVAL_DEREF(exception);
743 	}
744 
745 	exception = ZEND_THIS;
746 	base_ce = i_get_exception_base(Z_OBJ_P(exception));
747 
748 	/* We store the result in the private property string so we can access
749 	 * the result in uncaught exception handlers without memleaks. */
750 	ZVAL_STR(&tmp, str);
751 	zend_update_property_ex(base_ce, Z_OBJ_P(exception), ZSTR_KNOWN(ZEND_STR_STRING), &tmp);
752 
753 	RETURN_STR(str);
754 }
755 /* }}} */
756 
zend_init_exception_class_entry(zend_class_entry * ce)757 static void zend_init_exception_class_entry(zend_class_entry *ce) {
758 	ce->create_object = zend_default_exception_new;
759 	ce->default_object_handlers = &default_exception_handlers;
760 }
761 
zend_register_default_exception(void)762 void zend_register_default_exception(void) /* {{{ */
763 {
764 	zend_ce_throwable = register_class_Throwable(zend_ce_stringable);
765 	zend_ce_throwable->interface_gets_implemented = zend_implement_throwable;
766 
767 	memcpy(&default_exception_handlers, &std_object_handlers, sizeof(zend_object_handlers));
768 	default_exception_handlers.clone_obj = NULL;
769 
770 	zend_ce_exception = register_class_Exception(zend_ce_throwable);
771 	zend_init_exception_class_entry(zend_ce_exception);
772 
773 	zend_ce_error_exception = register_class_ErrorException(zend_ce_exception);
774 	zend_init_exception_class_entry(zend_ce_error_exception);
775 
776 	zend_ce_error = register_class_Error(zend_ce_throwable);
777 	zend_init_exception_class_entry(zend_ce_error);
778 
779 	zend_ce_compile_error = register_class_CompileError(zend_ce_error);
780 	zend_init_exception_class_entry(zend_ce_compile_error);
781 
782 	zend_ce_parse_error = register_class_ParseError(zend_ce_compile_error);
783 	zend_init_exception_class_entry(zend_ce_parse_error);
784 
785 	zend_ce_type_error = register_class_TypeError(zend_ce_error);
786 	zend_init_exception_class_entry(zend_ce_type_error);
787 
788 	zend_ce_argument_count_error = register_class_ArgumentCountError(zend_ce_type_error);
789 	zend_init_exception_class_entry(zend_ce_argument_count_error);
790 
791 	zend_ce_value_error = register_class_ValueError(zend_ce_error);
792 	zend_init_exception_class_entry(zend_ce_value_error);
793 
794 	zend_ce_arithmetic_error = register_class_ArithmeticError(zend_ce_error);
795 	zend_init_exception_class_entry(zend_ce_arithmetic_error);
796 
797 	zend_ce_division_by_zero_error = register_class_DivisionByZeroError(zend_ce_arithmetic_error);
798 	zend_init_exception_class_entry(zend_ce_division_by_zero_error);
799 
800 	zend_ce_unhandled_match_error = register_class_UnhandledMatchError(zend_ce_error);
801 	zend_init_exception_class_entry(zend_ce_unhandled_match_error);
802 
803 	INIT_CLASS_ENTRY(zend_ce_unwind_exit, "UnwindExit", NULL);
804 
805 	INIT_CLASS_ENTRY(zend_ce_graceful_exit, "GracefulExit", NULL);
806 }
807 /* }}} */
808 
809 /* {{{ Deprecated - Use zend_ce_exception directly instead */
zend_exception_get_default(void)810 ZEND_API zend_class_entry *zend_exception_get_default(void)
811 {
812 	return zend_ce_exception;
813 }
814 /* }}} */
815 
816 /* {{{ Deprecated - Use zend_ce_error_exception directly instead */
zend_get_error_exception(void)817 ZEND_API zend_class_entry *zend_get_error_exception(void)
818 {
819 	return zend_ce_error_exception;
820 }
821 /* }}} */
822 
zend_throw_exception_zstr(zend_class_entry * exception_ce,zend_string * message,zend_long code)823 static zend_object *zend_throw_exception_zstr(zend_class_entry *exception_ce, zend_string *message, zend_long code) /* {{{ */
824 {
825 	zval ex, tmp;
826 
827 	if (!exception_ce) {
828 		exception_ce = zend_ce_exception;
829 	}
830 
831 	ZEND_ASSERT(instanceof_function(exception_ce, zend_ce_throwable)
832 		&& "Exceptions must implement Throwable");
833 
834 	object_init_ex(&ex, exception_ce);
835 
836 	if (message) {
837 		ZVAL_STR(&tmp, message);
838 		zend_update_property_ex(exception_ce, Z_OBJ(ex), ZSTR_KNOWN(ZEND_STR_MESSAGE), &tmp);
839 	}
840 	if (code) {
841 		ZVAL_LONG(&tmp, code);
842 		zend_update_property_ex(exception_ce, Z_OBJ(ex), ZSTR_KNOWN(ZEND_STR_CODE), &tmp);
843 	}
844 
845 	zend_throw_exception_internal(Z_OBJ(ex));
846 
847 	return Z_OBJ(ex);
848 }
849 /* }}} */
850 
zend_throw_exception(zend_class_entry * exception_ce,const char * message,zend_long code)851 ZEND_API ZEND_COLD zend_object *zend_throw_exception(zend_class_entry *exception_ce, const char *message, zend_long code) /* {{{ */
852 {
853 	zend_string *msg_str = message ? zend_string_init(message, strlen(message), 0) : NULL;
854 	zend_object *ex = zend_throw_exception_zstr(exception_ce, msg_str, code);
855 	if (msg_str) {
856 		zend_string_release(msg_str);
857 	}
858 	return ex;
859 }
860 /* }}} */
861 
zend_throw_exception_ex(zend_class_entry * exception_ce,zend_long code,const char * format,...)862 ZEND_API ZEND_COLD zend_object *zend_throw_exception_ex(zend_class_entry *exception_ce, zend_long code, const char *format, ...) /* {{{ */
863 {
864 	va_list arg;
865 	char *message;
866 	zend_object *obj;
867 
868 	va_start(arg, format);
869 	zend_vspprintf(&message, 0, format, arg);
870 	va_end(arg);
871 	obj = zend_throw_exception(exception_ce, message, code);
872 	efree(message);
873 	return obj;
874 }
875 /* }}} */
876 
zend_throw_error_exception(zend_class_entry * exception_ce,zend_string * message,zend_long code,int severity)877 ZEND_API ZEND_COLD zend_object *zend_throw_error_exception(zend_class_entry *exception_ce, zend_string *message, zend_long code, int severity) /* {{{ */
878 {
879 	zend_object *obj = zend_throw_exception_zstr(exception_ce, message, code);
880 	if (exception_ce && instanceof_function(exception_ce, zend_ce_error_exception)) {
881 		zval tmp;
882 		ZVAL_LONG(&tmp, severity);
883 		zend_update_property_ex(zend_ce_error_exception, obj, ZSTR_KNOWN(ZEND_STR_SEVERITY), &tmp);
884 	}
885 	return obj;
886 }
887 /* }}} */
888 
zend_error_va(int type,zend_string * file,uint32_t lineno,const char * format,...)889 static void zend_error_va(int type, zend_string *file, uint32_t lineno, const char *format, ...) /* {{{ */
890 {
891 	va_list args;
892 	va_start(args, format);
893 	zend_string *message = zend_vstrpprintf(0, format, args);
894 	zend_observer_error_notify(type, file, lineno, message);
895 	zend_error_cb(type, file, lineno, message);
896 	zend_string_release(message);
897 	va_end(args);
898 }
899 /* }}} */
900 
901 /* This function doesn't return if it uses E_ERROR */
zend_exception_error(zend_object * ex,int severity)902 ZEND_API ZEND_COLD zend_result zend_exception_error(zend_object *ex, int severity) /* {{{ */
903 {
904 	zval exception, rv;
905 	zend_class_entry *ce_exception;
906 	zend_result result = FAILURE;
907 
908 	ZVAL_OBJ(&exception, ex);
909 	ce_exception = ex->ce;
910 	EG(exception) = NULL;
911 	if (ce_exception == zend_ce_parse_error || ce_exception == zend_ce_compile_error) {
912 		zend_string *message = zval_get_string(GET_PROPERTY(&exception, ZEND_STR_MESSAGE));
913 		zend_string *file = zval_get_string(GET_PROPERTY_SILENT(&exception, ZEND_STR_FILE));
914 		zend_long line = zval_get_long(GET_PROPERTY_SILENT(&exception, ZEND_STR_LINE));
915 		int type = (ce_exception == zend_ce_parse_error ? E_PARSE : E_COMPILE_ERROR) | E_DONT_BAIL;
916 
917 		zend_observer_error_notify(type, file, line, message);
918 		zend_error_cb(type, file, line, message);
919 
920 		zend_string_release_ex(file, 0);
921 		zend_string_release_ex(message, 0);
922 	} else if (instanceof_function(ce_exception, zend_ce_throwable)) {
923 		zval tmp;
924 		zend_string *str, *file = NULL;
925 		zend_long line = 0;
926 
927 		zend_call_known_instance_method_with_0_params(ex->ce->__tostring, ex, &tmp);
928 		if (!EG(exception)) {
929 			if (Z_TYPE(tmp) != IS_STRING) {
930 				zend_error(E_WARNING, "%s::__toString() must return a string", ZSTR_VAL(ce_exception->name));
931 			} else {
932 				zend_update_property_ex(i_get_exception_base(ex), ex, ZSTR_KNOWN(ZEND_STR_STRING), &tmp);
933 			}
934 		}
935 		zval_ptr_dtor(&tmp);
936 
937 		if (EG(exception)) {
938 			zval zv;
939 
940 			ZVAL_OBJ(&zv, EG(exception));
941 			/* do the best we can to inform about the inner exception */
942 			if (instanceof_function(ce_exception, zend_ce_exception) || instanceof_function(ce_exception, zend_ce_error)) {
943 				file = zval_get_string(GET_PROPERTY_SILENT(&zv, ZEND_STR_FILE));
944 				line = zval_get_long(GET_PROPERTY_SILENT(&zv, ZEND_STR_LINE));
945 			}
946 
947 			zend_error_va(E_WARNING, (file && ZSTR_LEN(file) > 0) ? file : NULL, line,
948 				"Uncaught %s in exception handling during call to %s::__toString()",
949 				ZSTR_VAL(Z_OBJCE(zv)->name), ZSTR_VAL(ce_exception->name));
950 
951 			if (file) {
952 				zend_string_release_ex(file, 0);
953 			}
954 		}
955 
956 		str = zval_get_string(GET_PROPERTY_SILENT(&exception, ZEND_STR_STRING));
957 		file = zval_get_string(GET_PROPERTY_SILENT(&exception, ZEND_STR_FILE));
958 		line = zval_get_long(GET_PROPERTY_SILENT(&exception, ZEND_STR_LINE));
959 
960 		ZVAL_STR(&tmp, str);
961 		zend_error_va(severity | E_DONT_BAIL,
962 			(file && ZSTR_LEN(file) > 0) ? file : NULL, line,
963 			"Uncaught %Z\n  thrown", &tmp);
964 
965 		zend_string_release_ex(str, 0);
966 		zend_string_release_ex(file, 0);
967 	} else if (ce_exception == &zend_ce_unwind_exit || ce_exception == &zend_ce_graceful_exit) {
968 		/* We successfully unwound, nothing more to do.
969 		 * We still return FAILURE in this case, as further execution should still be aborted. */
970 	} else {
971 		zend_error(severity, "Uncaught exception %s", ZSTR_VAL(ce_exception->name));
972 	}
973 
974 	OBJ_RELEASE(ex);
975 	return result;
976 }
977 /* }}} */
978 
zend_exception_uncaught_error(const char * format,...)979 ZEND_NORETURN void zend_exception_uncaught_error(const char *format, ...) {
980 	va_list va;
981 	va_start(va, format);
982 	zend_string *prefix = zend_vstrpprintf(0, format, va);
983 	va_end(va);
984 
985 	ZEND_ASSERT(EG(exception));
986 	zval exception_zv;
987 	ZVAL_OBJ_COPY(&exception_zv, EG(exception));
988 	zend_clear_exception();
989 
990 	zend_string *exception_str = zval_get_string(&exception_zv);
991 	zend_error_noreturn(E_ERROR,
992 		"%s: Uncaught %s", ZSTR_VAL(prefix), ZSTR_VAL(exception_str));
993 }
994 
zend_throw_exception_object(zval * exception)995 ZEND_API ZEND_COLD void zend_throw_exception_object(zval *exception) /* {{{ */
996 {
997 	if (exception == NULL || Z_TYPE_P(exception) != IS_OBJECT) {
998 		zend_error_noreturn(E_CORE_ERROR, "Need to supply an object when throwing an exception");
999 	}
1000 
1001 	zend_class_entry *exception_ce = Z_OBJCE_P(exception);
1002 
1003 	if (!exception_ce || !instanceof_function(exception_ce, zend_ce_throwable)) {
1004 		zend_throw_error(NULL, "Cannot throw objects that do not implement Throwable");
1005 		zval_ptr_dtor(exception);
1006 		return;
1007 	}
1008 
1009 	zend_throw_exception_internal(Z_OBJ_P(exception));
1010 }
1011 /* }}} */
1012 
zend_create_unwind_exit(void)1013 ZEND_API ZEND_COLD zend_object *zend_create_unwind_exit(void)
1014 {
1015 	return zend_objects_new(&zend_ce_unwind_exit);
1016 }
1017 
zend_create_graceful_exit(void)1018 ZEND_API ZEND_COLD zend_object *zend_create_graceful_exit(void)
1019 {
1020 	return zend_objects_new(&zend_ce_graceful_exit);
1021 }
1022 
zend_throw_unwind_exit(void)1023 ZEND_API ZEND_COLD void zend_throw_unwind_exit(void)
1024 {
1025 	ZEND_ASSERT(!EG(exception));
1026 	EG(exception) = zend_create_unwind_exit();
1027 	EG(opline_before_exception) = EG(current_execute_data)->opline;
1028 	EG(current_execute_data)->opline = EG(exception_op);
1029 }
1030 
zend_throw_graceful_exit(void)1031 ZEND_API ZEND_COLD void zend_throw_graceful_exit(void)
1032 {
1033 	ZEND_ASSERT(!EG(exception));
1034 	EG(exception) = zend_create_graceful_exit();
1035 	EG(opline_before_exception) = EG(current_execute_data)->opline;
1036 	EG(current_execute_data)->opline = EG(exception_op);
1037 }
1038 
zend_is_unwind_exit(const zend_object * ex)1039 ZEND_API bool zend_is_unwind_exit(const zend_object *ex)
1040 {
1041 	return ex->ce == &zend_ce_unwind_exit;
1042 }
1043 
zend_is_graceful_exit(const zend_object * ex)1044 ZEND_API bool zend_is_graceful_exit(const zend_object *ex)
1045 {
1046 	return ex->ce == &zend_ce_graceful_exit;
1047 }
1048