xref: /PHP-8.1/Zend/zend_exceptions.c (revision b5726c2c)
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 	zend_error_noreturn(E_ERROR,
71 		"Class %s cannot implement interface %s, extend Exception or Error instead",
72 		ZSTR_VAL(class_type->name),
73 		ZSTR_VAL(interface->name));
74 	return FAILURE;
75 }
76 /* }}} */
77 
i_get_exception_base(zend_object * object)78 static inline zend_class_entry *i_get_exception_base(zend_object *object) /* {{{ */
79 {
80 	return instanceof_function(object->ce, zend_ce_exception) ? zend_ce_exception : zend_ce_error;
81 }
82 /* }}} */
83 
zend_get_exception_base(zend_object * object)84 ZEND_API zend_class_entry *zend_get_exception_base(zend_object *object) /* {{{ */
85 {
86 	return i_get_exception_base(object);
87 }
88 /* }}} */
89 
zend_exception_set_previous(zend_object * exception,zend_object * add_previous)90 void zend_exception_set_previous(zend_object *exception, zend_object *add_previous) /* {{{ */
91 {
92 	zval *previous, *ancestor, *ex;
93 	zval  pv, zv, rv;
94 	zend_class_entry *base_ce;
95 
96 	if (!exception || !add_previous) {
97 		return;
98 	}
99 
100 	if (exception == add_previous || zend_is_unwind_exit(add_previous) || zend_is_graceful_exit(add_previous)) {
101 		OBJ_RELEASE(add_previous);
102 		return;
103 	}
104 
105 	ZEND_ASSERT(instanceof_function(add_previous->ce, zend_ce_throwable)
106 		&& "Previous exception must implement Throwable");
107 
108 	ZVAL_OBJ(&pv, add_previous);
109 	ZVAL_OBJ(&zv, exception);
110 	ex = &zv;
111 	do {
112 		ancestor = zend_read_property_ex(i_get_exception_base(add_previous), add_previous, ZSTR_KNOWN(ZEND_STR_PREVIOUS), 1, &rv);
113 		while (Z_TYPE_P(ancestor) == IS_OBJECT) {
114 			if (Z_OBJ_P(ancestor) == Z_OBJ_P(ex)) {
115 				OBJ_RELEASE(add_previous);
116 				return;
117 			}
118 			ancestor = zend_read_property_ex(i_get_exception_base(Z_OBJ_P(ancestor)), Z_OBJ_P(ancestor), ZSTR_KNOWN(ZEND_STR_PREVIOUS), 1, &rv);
119 		}
120 		base_ce = i_get_exception_base(Z_OBJ_P(ex));
121 		previous = zend_read_property_ex(base_ce, Z_OBJ_P(ex), ZSTR_KNOWN(ZEND_STR_PREVIOUS), 1, &rv);
122 		if (Z_TYPE_P(previous) == IS_NULL) {
123 			zend_update_property_ex(base_ce, Z_OBJ_P(ex), ZSTR_KNOWN(ZEND_STR_PREVIOUS), &pv);
124 			GC_DELREF(add_previous);
125 			return;
126 		}
127 		ex = previous;
128 	} while (Z_OBJ_P(ex) != add_previous);
129 }
130 /* }}} */
131 
zend_exception_save(void)132 void zend_exception_save(void) /* {{{ */
133 {
134 	if (EG(prev_exception)) {
135 		zend_exception_set_previous(EG(exception), EG(prev_exception));
136 	}
137 	if (EG(exception)) {
138 		EG(prev_exception) = EG(exception);
139 	}
140 	EG(exception) = NULL;
141 }
142 /* }}} */
143 
zend_exception_restore(void)144 void zend_exception_restore(void) /* {{{ */
145 {
146 	if (EG(prev_exception)) {
147 		if (EG(exception)) {
148 			zend_exception_set_previous(EG(exception), EG(prev_exception));
149 		} else {
150 			EG(exception) = EG(prev_exception);
151 		}
152 		EG(prev_exception) = NULL;
153 	}
154 }
155 /* }}} */
156 
is_handle_exception_set(void)157 static zend_always_inline bool is_handle_exception_set(void) {
158 	zend_execute_data *execute_data = EG(current_execute_data);
159 	return !execute_data
160 		|| !execute_data->func
161 		|| !ZEND_USER_CODE(execute_data->func->common.type)
162 		|| execute_data->opline->opcode == ZEND_HANDLE_EXCEPTION;
163 }
164 
zend_throw_exception_internal(zend_object * exception)165 ZEND_API ZEND_COLD void zend_throw_exception_internal(zend_object *exception) /* {{{ */
166 {
167 #ifdef HAVE_DTRACE
168 	if (DTRACE_EXCEPTION_THROWN_ENABLED()) {
169 		if (exception != NULL) {
170 			DTRACE_EXCEPTION_THROWN(ZSTR_VAL(exception->ce->name));
171 		} else {
172 			DTRACE_EXCEPTION_THROWN(NULL);
173 		}
174 	}
175 #endif /* HAVE_DTRACE */
176 
177 	if (exception != NULL) {
178 		zend_object *previous = EG(exception);
179 		if (previous && zend_is_unwind_exit(previous)) {
180 			/* Don't replace unwinding exception with different exception. */
181 			OBJ_RELEASE(exception);
182 			return;
183 		}
184 
185 		zend_exception_set_previous(exception, EG(exception));
186 		EG(exception) = exception;
187 		if (previous) {
188 			ZEND_ASSERT(is_handle_exception_set() && "HANDLE_EXCEPTION not set?");
189 			return;
190 		}
191 	}
192 	if (!EG(current_execute_data)) {
193 		if (exception && (exception->ce == zend_ce_parse_error || exception->ce == zend_ce_compile_error)) {
194 			return;
195 		}
196 		if (EG(exception)) {
197 			zend_exception_error(EG(exception), E_ERROR);
198 			zend_bailout();
199 		}
200 		zend_error_noreturn(E_CORE_ERROR, "Exception thrown without a stack frame");
201 	}
202 
203 	if (zend_throw_exception_hook) {
204 		zend_throw_exception_hook(exception);
205 	}
206 
207 	if (is_handle_exception_set()) {
208 		/* no need to rethrow the exception */
209 		return;
210 	}
211 	EG(opline_before_exception) = EG(current_execute_data)->opline;
212 	EG(current_execute_data)->opline = EG(exception_op);
213 }
214 /* }}} */
215 
zend_clear_exception(void)216 ZEND_API void zend_clear_exception(void) /* {{{ */
217 {
218 	zend_object *exception;
219 	if (EG(prev_exception)) {
220 		OBJ_RELEASE(EG(prev_exception));
221 		EG(prev_exception) = NULL;
222 	}
223 	if (!EG(exception)) {
224 		return;
225 	}
226 	/* exception may have destructor */
227 	exception = EG(exception);
228 	EG(exception) = NULL;
229 	OBJ_RELEASE(exception);
230 	if (EG(current_execute_data)) {
231 		EG(current_execute_data)->opline = EG(opline_before_exception);
232 	}
233 #if ZEND_DEBUG
234 	EG(opline_before_exception) = NULL;
235 #endif
236 }
237 /* }}} */
238 
zend_default_exception_new_ex(zend_class_entry * class_type,bool skip_top_traces)239 static zend_object *zend_default_exception_new_ex(zend_class_entry *class_type, bool skip_top_traces) /* {{{ */
240 {
241 	zval tmp;
242 	zval trace;
243 	zend_class_entry *base_ce;
244 	zend_string *filename;
245 
246 	zend_object *object = zend_objects_new(class_type);
247 	object->handlers = &default_exception_handlers;
248 
249 	object_properties_init(object, class_type);
250 
251 	if (EG(current_execute_data)) {
252 		zend_fetch_debug_backtrace(&trace,
253 			skip_top_traces,
254 			EG(exception_ignore_args) ? DEBUG_BACKTRACE_IGNORE_ARGS : 0, 0);
255 	} else {
256 		array_init(&trace);
257 	}
258 	Z_SET_REFCOUNT(trace, 0);
259 
260 	base_ce = i_get_exception_base(object);
261 
262 	if (EXPECTED((class_type != zend_ce_parse_error && class_type != zend_ce_compile_error)
263 			|| !(filename = zend_get_compiled_filename()))) {
264 		ZVAL_STRING(&tmp, zend_get_executed_filename());
265 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_FILE), &tmp);
266 		zval_ptr_dtor(&tmp);
267 		ZVAL_LONG(&tmp, zend_get_executed_lineno());
268 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
269 	} else {
270 		ZVAL_STR(&tmp, filename);
271 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_FILE), &tmp);
272 		ZVAL_LONG(&tmp, zend_get_compiled_lineno());
273 		zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
274 	}
275 	zend_update_property_ex(base_ce, object, ZSTR_KNOWN(ZEND_STR_TRACE), &trace);
276 
277 	return object;
278 }
279 /* }}} */
280 
zend_default_exception_new(zend_class_entry * class_type)281 static zend_object *zend_default_exception_new(zend_class_entry *class_type) /* {{{ */
282 {
283 	return zend_default_exception_new_ex(class_type, 0);
284 }
285 /* }}} */
286 
zend_error_exception_new(zend_class_entry * class_type)287 static zend_object *zend_error_exception_new(zend_class_entry *class_type) /* {{{ */
288 {
289 	return zend_default_exception_new_ex(class_type, 0);
290 }
291 /* }}} */
292 
293 /* {{{ Clone the exception object */
ZEND_METHOD(Exception,__clone)294 ZEND_COLD ZEND_METHOD(Exception, __clone)
295 {
296 	/* Should never be executable */
297 	zend_throw_exception(NULL, "Cannot clone object using __clone()", 0);
298 }
299 /* }}} */
300 
301 /* {{{ Exception constructor */
ZEND_METHOD(Exception,__construct)302 ZEND_METHOD(Exception, __construct)
303 {
304 	zend_string *message = NULL;
305 	zend_long   code = 0;
306 	zval  tmp, *object, *previous = NULL;
307 	zend_class_entry *base_ce;
308 
309 	object = ZEND_THIS;
310 	base_ce = i_get_exception_base(Z_OBJ_P(object));
311 
312 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|SlO!", &message, &code, &previous, zend_ce_throwable) == FAILURE) {
313 		RETURN_THROWS();
314 	}
315 
316 	if (message) {
317 		ZVAL_STR(&tmp, message);
318 		zend_update_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_MESSAGE), &tmp);
319 	}
320 
321 	if (code) {
322 		ZVAL_LONG(&tmp, code);
323 		zend_update_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_CODE), &tmp);
324 	}
325 
326 	if (previous) {
327 		zend_update_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_PREVIOUS), previous);
328 	}
329 }
330 /* }}} */
331 
332 /* {{{ Exception unserialize checks */
333 #define CHECK_EXC_TYPE(id, type) \
334 	pvalue = zend_read_property_ex(i_get_exception_base(Z_OBJ_P(object)), Z_OBJ_P(object), ZSTR_KNOWN(id), 1, &value); \
335 	if (Z_TYPE_P(pvalue) != IS_NULL && Z_TYPE_P(pvalue) != type) { \
336 		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))); \
337 	}
338 
ZEND_METHOD(Exception,__wakeup)339 ZEND_METHOD(Exception, __wakeup)
340 {
341 	ZEND_PARSE_PARAMETERS_NONE();
342 
343 	zval value, *pvalue;
344 	zval *object = ZEND_THIS;
345 	CHECK_EXC_TYPE(ZEND_STR_MESSAGE, IS_STRING);
346 	CHECK_EXC_TYPE(ZEND_STR_CODE,    IS_LONG);
347 	/* The type of all other properties is enforced through typed properties. */
348 }
349 /* }}} */
350 
351 /* {{{ ErrorException constructor */
ZEND_METHOD(ErrorException,__construct)352 ZEND_METHOD(ErrorException, __construct)
353 {
354 	zend_string *message = NULL, *filename = NULL;
355 	zend_long   code = 0, severity = E_ERROR, lineno;
356 	bool lineno_is_null = 1;
357 	zval   tmp, *object, *previous = NULL;
358 
359 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|SllS!l!O!", &message, &code, &severity, &filename, &lineno, &lineno_is_null, &previous, zend_ce_throwable) == FAILURE) {
360 		RETURN_THROWS();
361 	}
362 
363 	object = ZEND_THIS;
364 
365 	if (message) {
366 		ZVAL_STR_COPY(&tmp, message);
367 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_MESSAGE), &tmp);
368 		zval_ptr_dtor(&tmp);
369 	}
370 
371 	if (code) {
372 		ZVAL_LONG(&tmp, code);
373 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_CODE), &tmp);
374 	}
375 
376 	if (previous) {
377 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_PREVIOUS), previous);
378 	}
379 
380 	ZVAL_LONG(&tmp, severity);
381 	zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_SEVERITY), &tmp);
382 
383 	if (filename) {
384 		ZVAL_STR_COPY(&tmp, filename);
385 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_FILE), &tmp);
386 		zval_ptr_dtor(&tmp);
387 	}
388 
389 	if (!lineno_is_null) {
390 		ZVAL_LONG(&tmp, lineno);
391 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
392 	} else if (filename) {
393 		ZVAL_LONG(&tmp, 0);
394 		zend_update_property_ex(zend_ce_exception, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_LINE), &tmp);
395 	}
396 }
397 /* }}} */
398 
399 #define GET_PROPERTY(object, id) \
400 	zend_read_property_ex(i_get_exception_base(Z_OBJ_P(object)), Z_OBJ_P(object), ZSTR_KNOWN(id), 0, &rv)
401 #define GET_PROPERTY_SILENT(object, id) \
402 	zend_read_property_ex(i_get_exception_base(Z_OBJ_P(object)), Z_OBJ_P(object), ZSTR_KNOWN(id), 1, &rv)
403 
404 /* {{{ Get the file in which the exception occurred */
ZEND_METHOD(Exception,getFile)405 ZEND_METHOD(Exception, getFile)
406 {
407 	zval *prop, rv;
408 
409 	ZEND_PARSE_PARAMETERS_NONE();
410 
411 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_FILE);
412 	RETURN_STR(zval_get_string(prop));
413 }
414 /* }}} */
415 
416 /* {{{ Get the line in which the exception occurred */
ZEND_METHOD(Exception,getLine)417 ZEND_METHOD(Exception, getLine)
418 {
419 	zval *prop, rv;
420 
421 	ZEND_PARSE_PARAMETERS_NONE();
422 
423 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_LINE);
424 	RETURN_LONG(zval_get_long(prop));
425 }
426 /* }}} */
427 
428 /* {{{ Get the exception message */
ZEND_METHOD(Exception,getMessage)429 ZEND_METHOD(Exception, getMessage)
430 {
431 	zval *prop, rv;
432 
433 	ZEND_PARSE_PARAMETERS_NONE();
434 
435 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_MESSAGE);
436 	RETURN_STR(zval_get_string(prop));
437 }
438 /* }}} */
439 
440 /* {{{ Get the exception code */
ZEND_METHOD(Exception,getCode)441 ZEND_METHOD(Exception, getCode)
442 {
443 	zval *prop, rv;
444 
445 	ZEND_PARSE_PARAMETERS_NONE();
446 
447 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_CODE);
448 	ZVAL_DEREF(prop);
449 	ZVAL_COPY(return_value, prop);
450 }
451 /* }}} */
452 
453 /* {{{ Get the stack trace for the location in which the exception occurred */
ZEND_METHOD(Exception,getTrace)454 ZEND_METHOD(Exception, getTrace)
455 {
456 	zval *prop, rv;
457 
458 	ZEND_PARSE_PARAMETERS_NONE();
459 
460 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_TRACE);
461 	ZVAL_DEREF(prop);
462 	ZVAL_COPY(return_value, prop);
463 }
464 /* }}} */
465 
466 /* {{{ Get the exception severity */
ZEND_METHOD(ErrorException,getSeverity)467 ZEND_METHOD(ErrorException, getSeverity)
468 {
469 	zval *prop, rv;
470 
471 	ZEND_PARSE_PARAMETERS_NONE();
472 
473 	prop = GET_PROPERTY(ZEND_THIS, ZEND_STR_SEVERITY);
474 	ZVAL_DEREF(prop);
475 	ZVAL_COPY(return_value, prop);
476 }
477 /* }}} */
478 
479 #define TRACE_APPEND_KEY(key) do {                                          \
480 		tmp = zend_hash_find(ht, key);                                      \
481 		if (tmp) {                                                          \
482 			if (Z_TYPE_P(tmp) != IS_STRING) {                               \
483 				zend_error(E_WARNING, "Value for %s is not a string",       \
484 					ZSTR_VAL(key));                                         \
485 				smart_str_appends(str, "[unknown]");                        \
486 			} else {                                                        \
487 				smart_str_appends(str, Z_STRVAL_P(tmp));                    \
488 			}                                                               \
489 		} \
490 	} while (0)
491 
_build_trace_args(zval * arg,smart_str * str)492 static void _build_trace_args(zval *arg, smart_str *str) /* {{{ */
493 {
494 	/* the trivial way would be to do
495 	 * convert_to_string(arg);
496 	 * append it and kill the now tmp arg.
497 	 * but that could cause some E_NOTICE and also damn long lines.
498 	 */
499 
500 	ZVAL_DEREF(arg);
501 
502 	if (Z_TYPE_P(arg) <= IS_STRING) {
503 		smart_str_append_scalar(str, arg, EG(exception_string_param_max_len));
504 		smart_str_appends(str, ", ");
505 	} else {
506 		switch (Z_TYPE_P(arg)) {
507 			case IS_RESOURCE:
508 				smart_str_appends(str, "Resource id #");
509 				smart_str_append_long(str, Z_RES_HANDLE_P(arg));
510 				smart_str_appends(str, ", ");
511 				break;
512 			case IS_ARRAY:
513 				smart_str_appends(str, "Array, ");
514 				break;
515 			case IS_OBJECT: {
516 				zend_string *class_name = Z_OBJ_HANDLER_P(arg, get_class_name)(Z_OBJ_P(arg));
517 				smart_str_appends(str, "Object(");
518 				smart_str_appends(str, ZSTR_VAL(class_name));
519 				smart_str_appends(str, "), ");
520 				zend_string_release_ex(class_name, 0);
521 				break;
522 			}
523 		}
524 	}
525 }
526 /* }}} */
527 
_build_trace_string(smart_str * str,HashTable * ht,uint32_t num)528 static void _build_trace_string(smart_str *str, HashTable *ht, uint32_t num) /* {{{ */
529 {
530 	zval *file, *tmp;
531 
532 	smart_str_appendc(str, '#');
533 	smart_str_append_long(str, num);
534 	smart_str_appendc(str, ' ');
535 
536 	file = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_FILE));
537 	if (file) {
538 		if (Z_TYPE_P(file) != IS_STRING) {
539 			zend_error(E_WARNING, "File name is not a string");
540 			smart_str_appends(str, "[unknown file]: ");
541 		} else{
542 			zend_long line = 0;
543 			tmp = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_LINE));
544 			if (tmp) {
545 				if (Z_TYPE_P(tmp) == IS_LONG) {
546 					line = Z_LVAL_P(tmp);
547 				} else {
548 					zend_error(E_WARNING, "Line is not an int");
549 				}
550 			}
551 			smart_str_append(str, Z_STR_P(file));
552 			smart_str_appendc(str, '(');
553 			smart_str_append_long(str, line);
554 			smart_str_appends(str, "): ");
555 		}
556 	} else {
557 		smart_str_appends(str, "[internal function]: ");
558 	}
559 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_CLASS));
560 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_TYPE));
561 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_FUNCTION));
562 	smart_str_appendc(str, '(');
563 	tmp = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_ARGS));
564 	if (tmp) {
565 		if (Z_TYPE_P(tmp) == IS_ARRAY) {
566 			size_t last_len = ZSTR_LEN(str->s);
567 			zend_string *name;
568 			zval *arg;
569 
570 			ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(tmp), name, arg) {
571 				if (name) {
572 					smart_str_append(str, name);
573 					smart_str_appends(str, ": ");
574 				}
575 				_build_trace_args(arg, str);
576 			} ZEND_HASH_FOREACH_END();
577 
578 			if (last_len != ZSTR_LEN(str->s)) {
579 				ZSTR_LEN(str->s) -= 2; /* remove last ', ' */
580 			}
581 		} else {
582 			zend_error(E_WARNING, "args element is not an array");
583 		}
584 	}
585 	smart_str_appends(str, ")\n");
586 }
587 /* }}} */
588 
zend_trace_to_string(HashTable * trace,bool include_main)589 ZEND_API zend_string *zend_trace_to_string(HashTable *trace, bool include_main) {
590 	zend_ulong index;
591 	zval *frame;
592 	uint32_t num = 0;
593 	smart_str str = {0};
594 
595 	ZEND_HASH_FOREACH_NUM_KEY_VAL(trace, index, frame) {
596 		if (Z_TYPE_P(frame) != IS_ARRAY) {
597 			zend_error(E_WARNING, "Expected array for frame " ZEND_ULONG_FMT, index);
598 			continue;
599 		}
600 
601 		_build_trace_string(&str, Z_ARRVAL_P(frame), num++);
602 	} ZEND_HASH_FOREACH_END();
603 
604 	if (include_main) {
605 		smart_str_appendc(&str, '#');
606 		smart_str_append_long(&str, num);
607 		smart_str_appends(&str, " {main}");
608 	}
609 
610 	smart_str_0(&str);
611 	return str.s ? str.s : ZSTR_EMPTY_ALLOC();
612 }
613 
614 /* {{{ Obtain the backtrace for the exception as a string (instead of an array) */
ZEND_METHOD(Exception,getTraceAsString)615 ZEND_METHOD(Exception, getTraceAsString)
616 {
617 
618 	ZEND_PARSE_PARAMETERS_NONE();
619 
620 	zval *object = ZEND_THIS;
621 	zend_class_entry *base_ce = i_get_exception_base(Z_OBJ_P(object));
622 	zval rv;
623 	zval *trace = zend_read_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_TRACE), 1, &rv);
624 	if (EG(exception)) {
625 		RETURN_THROWS();
626 	}
627 
628 	/* Type should be guaranteed by property type. */
629 	ZEND_ASSERT(Z_TYPE_P(trace) == IS_ARRAY);
630 	RETURN_NEW_STR(zend_trace_to_string(Z_ARRVAL_P(trace), /* include_main */ true));
631 }
632 /* }}} */
633 
634 /* {{{ Return previous Throwable or NULL. */
ZEND_METHOD(Exception,getPrevious)635 ZEND_METHOD(Exception, getPrevious)
636 {
637 	zval rv;
638 
639 	ZEND_PARSE_PARAMETERS_NONE();
640 
641 	ZVAL_COPY(return_value, GET_PROPERTY_SILENT(ZEND_THIS, ZEND_STR_PREVIOUS));
642 } /* }}} */
643 
644 /* {{{ Obtain the string representation of the Exception object */
ZEND_METHOD(Exception,__toString)645 ZEND_METHOD(Exception, __toString)
646 {
647 	zval trace, *exception;
648 	zend_class_entry *base_ce;
649 	zend_string *str;
650 	zend_fcall_info fci;
651 	zval rv, tmp;
652 	zend_string *fname;
653 
654 	ZEND_PARSE_PARAMETERS_NONE();
655 
656 	str = ZSTR_EMPTY_ALLOC();
657 
658 	exception = ZEND_THIS;
659 	fname = zend_string_init("gettraceasstring", sizeof("gettraceasstring")-1, 0);
660 
661 	while (exception && Z_TYPE_P(exception) == IS_OBJECT && instanceof_function(Z_OBJCE_P(exception), zend_ce_throwable)) {
662 		zend_string *prev_str = str;
663 		zend_string *message = zval_get_string(GET_PROPERTY(exception, ZEND_STR_MESSAGE));
664 		zend_string *file = zval_get_string(GET_PROPERTY(exception, ZEND_STR_FILE));
665 		zend_long line = zval_get_long(GET_PROPERTY(exception, ZEND_STR_LINE));
666 
667 		fci.size = sizeof(fci);
668 		ZVAL_STR(&fci.function_name, fname);
669 		fci.object = Z_OBJ_P(exception);
670 		fci.retval = &trace;
671 		fci.param_count = 0;
672 		fci.params = NULL;
673 		fci.named_params = NULL;
674 
675 		zend_call_function(&fci, NULL);
676 
677 		if (Z_TYPE(trace) != IS_STRING) {
678 			zval_ptr_dtor(&trace);
679 			ZVAL_UNDEF(&trace);
680 		}
681 
682 		if ((Z_OBJCE_P(exception) == zend_ce_type_error || Z_OBJCE_P(exception) == zend_ce_argument_count_error) && strstr(ZSTR_VAL(message), ", called in ")) {
683 			zval message_zv;
684 			ZVAL_STR(&message_zv, message);
685 			zend_string *real_message = zend_strpprintf_unchecked(0, "%Z and defined", &message_zv);
686 			zend_string_release_ex(message, 0);
687 			message = real_message;
688 		}
689 
690 		zend_string *tmp_trace = (Z_TYPE(trace) == IS_STRING && Z_STRLEN(trace))
691 			? zend_string_copy(Z_STR(trace))
692 			: ZSTR_INIT_LITERAL("#0 {main}\n", false);
693 
694 		zval name_zv, trace_zv, file_zv, prev_str_zv;
695 		ZVAL_STR(&name_zv, Z_OBJCE_P(exception)->name);
696 		ZVAL_STR(&trace_zv, tmp_trace);
697 		ZVAL_STR(&file_zv, file);
698 		ZVAL_STR(&prev_str_zv, prev_str);
699 
700 		if (ZSTR_LEN(message) > 0) {
701 			zval message_zv;
702 			ZVAL_STR(&message_zv, message);
703 
704 			str = zend_strpprintf_unchecked(0, "%Z: %Z in %Z:" ZEND_LONG_FMT "\nStack trace:\n%Z%s%Z",
705 				&name_zv, &message_zv, &file_zv, line,
706 				&trace_zv, ZSTR_LEN(prev_str) ? "\n\nNext " : "", &prev_str_zv);
707 		} else {
708 			str = zend_strpprintf_unchecked(0, "%Z in %Z:" ZEND_LONG_FMT "\nStack trace:\n%Z%s%Z",
709 				&name_zv, &file_zv, line,
710 				&trace_zv, ZSTR_LEN(prev_str) ? "\n\nNext " : "", &prev_str_zv);
711 		}
712 		zend_string_release_ex(tmp_trace, false);
713 
714 		zend_string_release_ex(prev_str, 0);
715 		zend_string_release_ex(message, 0);
716 		zend_string_release_ex(file, 0);
717 		zval_ptr_dtor(&trace);
718 
719 		Z_PROTECT_RECURSION_P(exception);
720 		exception = GET_PROPERTY(exception, ZEND_STR_PREVIOUS);
721 		if (exception && Z_TYPE_P(exception) == IS_OBJECT && Z_IS_RECURSIVE_P(exception)) {
722 			break;
723 		}
724 	}
725 	zend_string_release_ex(fname, 0);
726 
727 	exception = ZEND_THIS;
728 	/* Reset apply counts */
729 	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)) {
730 		if (Z_IS_RECURSIVE_P(exception)) {
731 			Z_UNPROTECT_RECURSION_P(exception);
732 		} else {
733 			break;
734 		}
735 		exception = GET_PROPERTY(exception, ZEND_STR_PREVIOUS);
736 	}
737 
738 	exception = ZEND_THIS;
739 	base_ce = i_get_exception_base(Z_OBJ_P(exception));
740 
741 	/* We store the result in the private property string so we can access
742 	 * the result in uncaught exception handlers without memleaks. */
743 	ZVAL_STR(&tmp, str);
744 	zend_update_property_ex(base_ce, Z_OBJ_P(exception), ZSTR_KNOWN(ZEND_STR_STRING), &tmp);
745 
746 	RETURN_STR(str);
747 }
748 /* }}} */
749 
zend_register_default_exception(void)750 void zend_register_default_exception(void) /* {{{ */
751 {
752 	zend_ce_throwable = register_class_Throwable(zend_ce_stringable);
753 	zend_ce_throwable->interface_gets_implemented = zend_implement_throwable;
754 
755 	memcpy(&default_exception_handlers, &std_object_handlers, sizeof(zend_object_handlers));
756 	default_exception_handlers.clone_obj = NULL;
757 
758 	zend_ce_exception = register_class_Exception(zend_ce_throwable);
759 	zend_ce_exception->create_object = zend_default_exception_new;
760 
761 	zend_ce_error_exception = register_class_ErrorException(zend_ce_exception);
762 	zend_ce_error_exception->create_object = zend_error_exception_new;
763 
764 	/* Declared manually because it uses constant E_ERROR. */
765 	zval severity_default_value;
766 	ZVAL_LONG(&severity_default_value, E_ERROR);
767 	zend_declare_typed_property(zend_ce_error_exception, ZSTR_KNOWN(ZEND_STR_SEVERITY), &severity_default_value, ZEND_ACC_PROTECTED, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
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 		zend_error_va(severity | E_DONT_BAIL,
954 			(file && ZSTR_LEN(file) > 0) ? file : NULL, line,
955 			"Uncaught %s\n  thrown", ZSTR_VAL(str));
956 
957 		zend_string_release_ex(str, 0);
958 		zend_string_release_ex(file, 0);
959 	} else if (ce_exception == &zend_ce_unwind_exit || ce_exception == &zend_ce_graceful_exit) {
960 		/* We successfully unwound, nothing more to do.
961 		 * We still return FAILURE in this case, as further execution should still be aborted. */
962 	} else {
963 		zend_error(severity, "Uncaught exception %s", ZSTR_VAL(ce_exception->name));
964 	}
965 
966 	OBJ_RELEASE(ex);
967 	return result;
968 }
969 /* }}} */
970 
zend_exception_uncaught_error(const char * format,...)971 ZEND_NORETURN void zend_exception_uncaught_error(const char *format, ...) {
972 	va_list va;
973 	va_start(va, format);
974 	zend_string *prefix = zend_vstrpprintf(0, format, va);
975 	va_end(va);
976 
977 	ZEND_ASSERT(EG(exception));
978 	zval exception_zv;
979 	ZVAL_OBJ_COPY(&exception_zv, EG(exception));
980 	zend_clear_exception();
981 
982 	zend_string *exception_str = zval_get_string(&exception_zv);
983 	zend_error_noreturn(E_ERROR,
984 		"%s: Uncaught %s", ZSTR_VAL(prefix), ZSTR_VAL(exception_str));
985 }
986 
zend_throw_exception_object(zval * exception)987 ZEND_API ZEND_COLD void zend_throw_exception_object(zval *exception) /* {{{ */
988 {
989 	if (exception == NULL || Z_TYPE_P(exception) != IS_OBJECT) {
990 		zend_error_noreturn(E_CORE_ERROR, "Need to supply an object when throwing an exception");
991 	}
992 
993 	zend_class_entry *exception_ce = Z_OBJCE_P(exception);
994 
995 	if (!exception_ce || !instanceof_function(exception_ce, zend_ce_throwable)) {
996 		zend_throw_error(NULL, "Cannot throw objects that do not implement Throwable");
997 		zval_ptr_dtor(exception);
998 		return;
999 	}
1000 
1001 	zend_throw_exception_internal(Z_OBJ_P(exception));
1002 }
1003 /* }}} */
1004 
zend_create_unwind_exit(void)1005 ZEND_API ZEND_COLD zend_object *zend_create_unwind_exit(void)
1006 {
1007 	return zend_objects_new(&zend_ce_unwind_exit);
1008 }
1009 
zend_create_graceful_exit(void)1010 ZEND_API ZEND_COLD zend_object *zend_create_graceful_exit(void)
1011 {
1012 	return zend_objects_new(&zend_ce_graceful_exit);
1013 }
1014 
zend_throw_unwind_exit(void)1015 ZEND_API ZEND_COLD void zend_throw_unwind_exit(void)
1016 {
1017 	ZEND_ASSERT(!EG(exception));
1018 	EG(exception) = zend_create_unwind_exit();
1019 	EG(opline_before_exception) = EG(current_execute_data)->opline;
1020 	EG(current_execute_data)->opline = EG(exception_op);
1021 }
1022 
zend_throw_graceful_exit(void)1023 ZEND_API ZEND_COLD void zend_throw_graceful_exit(void)
1024 {
1025 	ZEND_ASSERT(!EG(exception));
1026 	EG(exception) = zend_create_graceful_exit();
1027 	EG(opline_before_exception) = EG(current_execute_data)->opline;
1028 	EG(current_execute_data)->opline = EG(exception_op);
1029 }
1030 
zend_is_unwind_exit(const zend_object * ex)1031 ZEND_API bool zend_is_unwind_exit(const zend_object *ex)
1032 {
1033 	return ex->ce == &zend_ce_unwind_exit;
1034 }
1035 
zend_is_graceful_exit(const zend_object * ex)1036 ZEND_API bool zend_is_graceful_exit(const zend_object *ex)
1037 {
1038 	return ex->ce == &zend_ce_graceful_exit;
1039 }
1040