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