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