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