xref: /php-src/Zend/zend_exceptions.c (revision cd66fcc6)
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 	/* Should never be executable */
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 (Z_TYPE_P(arg) <= IS_STRING) {
505 		smart_str_append_scalar(str, arg, EG(exception_string_param_max_len));
506 		smart_str_appends(str, ", ");
507 	} else {
508 		switch (Z_TYPE_P(arg)) {
509 			case IS_RESOURCE:
510 				smart_str_appends(str, "Resource id #");
511 				smart_str_append_long(str, Z_RES_HANDLE_P(arg));
512 				smart_str_appends(str, ", ");
513 				break;
514 			case IS_ARRAY:
515 				smart_str_appends(str, "Array, ");
516 				break;
517 			case IS_OBJECT: {
518 				zend_string *class_name = Z_OBJ_HANDLER_P(arg, get_class_name)(Z_OBJ_P(arg));
519 				smart_str_appends(str, "Object(");
520 				smart_str_appends(str, ZSTR_VAL(class_name));
521 				smart_str_appends(str, "), ");
522 				zend_string_release_ex(class_name, 0);
523 				break;
524 			}
525 		}
526 	}
527 }
528 /* }}} */
529 
_build_trace_string(smart_str * str,HashTable * ht,uint32_t num)530 static void _build_trace_string(smart_str *str, HashTable *ht, uint32_t num) /* {{{ */
531 {
532 	zval *file, *tmp;
533 
534 	smart_str_appendc(str, '#');
535 	smart_str_append_long(str, num);
536 	smart_str_appendc(str, ' ');
537 
538 	file = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_FILE));
539 	if (file) {
540 		if (Z_TYPE_P(file) != IS_STRING) {
541 			zend_error(E_WARNING, "File name is not a string");
542 			smart_str_appends(str, "[unknown file]: ");
543 		} else{
544 			zend_long line = 0;
545 			tmp = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_LINE));
546 			if (tmp) {
547 				if (Z_TYPE_P(tmp) == IS_LONG) {
548 					line = Z_LVAL_P(tmp);
549 				} else {
550 					zend_error(E_WARNING, "Line is not an int");
551 				}
552 			}
553 			smart_str_append(str, Z_STR_P(file));
554 			smart_str_appendc(str, '(');
555 			smart_str_append_long(str, line);
556 			smart_str_appends(str, "): ");
557 		}
558 	} else {
559 		smart_str_appends(str, "[internal function]: ");
560 	}
561 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_CLASS));
562 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_TYPE));
563 	TRACE_APPEND_KEY(ZSTR_KNOWN(ZEND_STR_FUNCTION));
564 	smart_str_appendc(str, '(');
565 	tmp = zend_hash_find_known_hash(ht, ZSTR_KNOWN(ZEND_STR_ARGS));
566 	if (tmp) {
567 		if (Z_TYPE_P(tmp) == IS_ARRAY) {
568 			size_t last_len = ZSTR_LEN(str->s);
569 			zend_string *name;
570 			zval *arg;
571 
572 			ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(tmp), name, arg) {
573 				if (name) {
574 					smart_str_append(str, name);
575 					smart_str_appends(str, ": ");
576 				}
577 				_build_trace_args(arg, str);
578 			} ZEND_HASH_FOREACH_END();
579 
580 			if (last_len != ZSTR_LEN(str->s)) {
581 				ZSTR_LEN(str->s) -= 2; /* remove last ', ' */
582 			}
583 		} else {
584 			zend_error(E_WARNING, "args element is not an array");
585 		}
586 	}
587 	smart_str_appends(str, ")\n");
588 }
589 /* }}} */
590 
zend_trace_to_string(HashTable * trace,bool include_main)591 ZEND_API zend_string *zend_trace_to_string(HashTable *trace, bool include_main) {
592 	zend_ulong index;
593 	zval *frame;
594 	uint32_t num = 0;
595 	smart_str str = {0};
596 
597 	ZEND_HASH_FOREACH_NUM_KEY_VAL(trace, index, frame) {
598 		if (Z_TYPE_P(frame) != IS_ARRAY) {
599 			zend_error(E_WARNING, "Expected array for frame " ZEND_ULONG_FMT, index);
600 			continue;
601 		}
602 
603 		_build_trace_string(&str, Z_ARRVAL_P(frame), num++);
604 	} ZEND_HASH_FOREACH_END();
605 
606 	if (include_main) {
607 		smart_str_appendc(&str, '#');
608 		smart_str_append_long(&str, num);
609 		smart_str_appends(&str, " {main}");
610 	}
611 
612 	smart_str_0(&str);
613 	return str.s ? str.s : ZSTR_EMPTY_ALLOC();
614 }
615 
616 /* {{{ Obtain the backtrace for the exception as a string (instead of an array) */
ZEND_METHOD(Exception,getTraceAsString)617 ZEND_METHOD(Exception, getTraceAsString)
618 {
619 
620 	ZEND_PARSE_PARAMETERS_NONE();
621 
622 	zval *object = ZEND_THIS;
623 	zend_class_entry *base_ce = i_get_exception_base(Z_OBJ_P(object));
624 	zval rv;
625 	zval *trace = zend_read_property_ex(base_ce, Z_OBJ_P(object), ZSTR_KNOWN(ZEND_STR_TRACE), 1, &rv);
626 	if (EG(exception)) {
627 		RETURN_THROWS();
628 	}
629 
630 	/* Type should be guaranteed by property type. */
631 	ZEND_ASSERT(Z_TYPE_P(trace) == IS_ARRAY);
632 	RETURN_NEW_STR(zend_trace_to_string(Z_ARRVAL_P(trace), /* include_main */ true));
633 }
634 /* }}} */
635 
636 /* {{{ Return previous Throwable or NULL. */
ZEND_METHOD(Exception,getPrevious)637 ZEND_METHOD(Exception, getPrevious)
638 {
639 	zval rv;
640 
641 	ZEND_PARSE_PARAMETERS_NONE();
642 
643 	ZVAL_COPY(return_value, GET_PROPERTY_SILENT(ZEND_THIS, ZEND_STR_PREVIOUS));
644 } /* }}} */
645 
646 /* {{{ Obtain the string representation of the Exception object */
ZEND_METHOD(Exception,__toString)647 ZEND_METHOD(Exception, __toString)
648 {
649 	zval trace, *exception;
650 	zend_class_entry *base_ce;
651 	zend_string *str;
652 	zend_fcall_info fci;
653 	zval rv, tmp;
654 	zend_string *fname;
655 
656 	ZEND_PARSE_PARAMETERS_NONE();
657 
658 	str = ZSTR_EMPTY_ALLOC();
659 
660 	exception = ZEND_THIS;
661 	fname = ZSTR_INIT_LITERAL("gettraceasstring", 0);
662 
663 	while (exception && Z_TYPE_P(exception) == IS_OBJECT && instanceof_function(Z_OBJCE_P(exception), zend_ce_throwable)) {
664 		zend_string *prev_str = str;
665 		zend_string *message = zval_get_string(GET_PROPERTY(exception, ZEND_STR_MESSAGE));
666 		zend_string *file = zval_get_string(GET_PROPERTY(exception, ZEND_STR_FILE));
667 		zend_long line = zval_get_long(GET_PROPERTY(exception, ZEND_STR_LINE));
668 
669 		fci.size = sizeof(fci);
670 		ZVAL_STR(&fci.function_name, fname);
671 		fci.object = Z_OBJ_P(exception);
672 		fci.retval = &trace;
673 		fci.param_count = 0;
674 		fci.params = NULL;
675 		fci.named_params = NULL;
676 
677 		zend_call_function(&fci, NULL);
678 
679 		if (Z_TYPE(trace) != IS_STRING) {
680 			zval_ptr_dtor(&trace);
681 			ZVAL_UNDEF(&trace);
682 		}
683 
684 		if ((Z_OBJCE_P(exception) == zend_ce_type_error || Z_OBJCE_P(exception) == zend_ce_argument_count_error) && strstr(ZSTR_VAL(message), ", called in ")) {
685 			zend_string *real_message = zend_strpprintf_unchecked(0, "%S and defined", message);
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 		zend_string *name = Z_OBJCE_P(exception)->name;
695 
696 		if (ZSTR_LEN(message) > 0) {
697 			zval message_zv;
698 			ZVAL_STR(&message_zv, message);
699 
700 			str = zend_strpprintf_unchecked(0, "%S: %S in %S:" ZEND_LONG_FMT "\nStack trace:\n%S%s%S",
701 				name, message, file, line,
702 				tmp_trace, ZSTR_LEN(prev_str) ? "\n\nNext " : "", prev_str);
703 		} else {
704 			str = zend_strpprintf_unchecked(0, "%S in %S:" ZEND_LONG_FMT "\nStack trace:\n%S%s%S",
705 				name, file, line,
706 				tmp_trace, ZSTR_LEN(prev_str) ? "\n\nNext " : "", prev_str);
707 		}
708 		zend_string_release_ex(tmp_trace, false);
709 
710 		zend_string_release_ex(prev_str, 0);
711 		zend_string_release_ex(message, 0);
712 		zend_string_release_ex(file, 0);
713 		zval_ptr_dtor(&trace);
714 
715 		Z_PROTECT_RECURSION_P(exception);
716 		exception = GET_PROPERTY(exception, ZEND_STR_PREVIOUS);
717 		if (exception && Z_TYPE_P(exception) == IS_OBJECT && Z_IS_RECURSIVE_P(exception)) {
718 			break;
719 		}
720 	}
721 	zend_string_release_ex(fname, 0);
722 
723 	exception = ZEND_THIS;
724 	/* Reset apply counts */
725 	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)) {
726 		if (Z_IS_RECURSIVE_P(exception)) {
727 			Z_UNPROTECT_RECURSION_P(exception);
728 		} else {
729 			break;
730 		}
731 		exception = GET_PROPERTY(exception, ZEND_STR_PREVIOUS);
732 	}
733 
734 	exception = ZEND_THIS;
735 	base_ce = i_get_exception_base(Z_OBJ_P(exception));
736 
737 	/* We store the result in the private property string so we can access
738 	 * the result in uncaught exception handlers without memleaks. */
739 	ZVAL_STR(&tmp, str);
740 	zend_update_property_ex(base_ce, Z_OBJ_P(exception), ZSTR_KNOWN(ZEND_STR_STRING), &tmp);
741 
742 	RETURN_STR(str);
743 }
744 /* }}} */
745 
zend_init_exception_class_entry(zend_class_entry * ce)746 static void zend_init_exception_class_entry(zend_class_entry *ce) {
747 	ce->create_object = zend_default_exception_new;
748 	ce->default_object_handlers = &default_exception_handlers;
749 }
750 
zend_register_default_exception(void)751 void zend_register_default_exception(void) /* {{{ */
752 {
753 	zend_ce_throwable = register_class_Throwable(zend_ce_stringable);
754 	zend_ce_throwable->interface_gets_implemented = zend_implement_throwable;
755 
756 	memcpy(&default_exception_handlers, &std_object_handlers, sizeof(zend_object_handlers));
757 	default_exception_handlers.clone_obj = NULL;
758 
759 	zend_ce_exception = register_class_Exception(zend_ce_throwable);
760 	zend_init_exception_class_entry(zend_ce_exception);
761 
762 	zend_ce_error_exception = register_class_ErrorException(zend_ce_exception);
763 	zend_init_exception_class_entry(zend_ce_error_exception);
764 
765 	zend_ce_error = register_class_Error(zend_ce_throwable);
766 	zend_init_exception_class_entry(zend_ce_error);
767 
768 	zend_ce_compile_error = register_class_CompileError(zend_ce_error);
769 	zend_init_exception_class_entry(zend_ce_compile_error);
770 
771 	zend_ce_parse_error = register_class_ParseError(zend_ce_compile_error);
772 	zend_init_exception_class_entry(zend_ce_parse_error);
773 
774 	zend_ce_type_error = register_class_TypeError(zend_ce_error);
775 	zend_init_exception_class_entry(zend_ce_type_error);
776 
777 	zend_ce_argument_count_error = register_class_ArgumentCountError(zend_ce_type_error);
778 	zend_init_exception_class_entry(zend_ce_argument_count_error);
779 
780 	zend_ce_value_error = register_class_ValueError(zend_ce_error);
781 	zend_init_exception_class_entry(zend_ce_value_error);
782 
783 	zend_ce_arithmetic_error = register_class_ArithmeticError(zend_ce_error);
784 	zend_init_exception_class_entry(zend_ce_arithmetic_error);
785 
786 	zend_ce_division_by_zero_error = register_class_DivisionByZeroError(zend_ce_arithmetic_error);
787 	zend_init_exception_class_entry(zend_ce_division_by_zero_error);
788 
789 	zend_ce_unhandled_match_error = register_class_UnhandledMatchError(zend_ce_error);
790 	zend_init_exception_class_entry(zend_ce_unhandled_match_error);
791 
792 	zend_ce_request_parse_body_exception = register_class_RequestParseBodyException(zend_ce_exception);
793 	zend_init_exception_class_entry(zend_ce_request_parse_body_exception);
794 
795 	INIT_CLASS_ENTRY(zend_ce_unwind_exit, "UnwindExit", NULL);
796 
797 	INIT_CLASS_ENTRY(zend_ce_graceful_exit, "GracefulExit", NULL);
798 }
799 /* }}} */
800 
801 /* {{{ Deprecated - Use zend_ce_exception directly instead */
zend_exception_get_default(void)802 ZEND_API zend_class_entry *zend_exception_get_default(void)
803 {
804 	return zend_ce_exception;
805 }
806 /* }}} */
807 
808 /* {{{ Deprecated - Use zend_ce_error_exception directly instead */
zend_get_error_exception(void)809 ZEND_API zend_class_entry *zend_get_error_exception(void)
810 {
811 	return zend_ce_error_exception;
812 }
813 /* }}} */
814 
zend_throw_exception_zstr(zend_class_entry * exception_ce,zend_string * message,zend_long code)815 static zend_object *zend_throw_exception_zstr(zend_class_entry *exception_ce, zend_string *message, zend_long code) /* {{{ */
816 {
817 	zval ex, tmp;
818 
819 	if (!exception_ce) {
820 		exception_ce = zend_ce_exception;
821 	}
822 
823 	ZEND_ASSERT(instanceof_function(exception_ce, zend_ce_throwable)
824 		&& "Exceptions must implement Throwable");
825 
826 	object_init_ex(&ex, exception_ce);
827 
828 	if (message) {
829 		ZVAL_STR(&tmp, message);
830 		zend_update_property_ex(exception_ce, Z_OBJ(ex), ZSTR_KNOWN(ZEND_STR_MESSAGE), &tmp);
831 	}
832 	if (code) {
833 		ZVAL_LONG(&tmp, code);
834 		zend_update_property_ex(exception_ce, Z_OBJ(ex), ZSTR_KNOWN(ZEND_STR_CODE), &tmp);
835 	}
836 
837 	zend_throw_exception_internal(Z_OBJ(ex));
838 
839 	return Z_OBJ(ex);
840 }
841 /* }}} */
842 
zend_throw_exception(zend_class_entry * exception_ce,const char * message,zend_long code)843 ZEND_API ZEND_COLD zend_object *zend_throw_exception(zend_class_entry *exception_ce, const char *message, zend_long code) /* {{{ */
844 {
845 	zend_string *msg_str = message ? zend_string_init(message, strlen(message), 0) : NULL;
846 	zend_object *ex = zend_throw_exception_zstr(exception_ce, msg_str, code);
847 	if (msg_str) {
848 		zend_string_release(msg_str);
849 	}
850 	return ex;
851 }
852 /* }}} */
853 
zend_throw_exception_ex(zend_class_entry * exception_ce,zend_long code,const char * format,...)854 ZEND_API ZEND_COLD zend_object *zend_throw_exception_ex(zend_class_entry *exception_ce, zend_long code, const char *format, ...) /* {{{ */
855 {
856 	va_list arg;
857 	char *message;
858 	zend_object *obj;
859 
860 	va_start(arg, format);
861 	zend_vspprintf(&message, 0, format, arg);
862 	va_end(arg);
863 	obj = zend_throw_exception(exception_ce, message, code);
864 	efree(message);
865 	return obj;
866 }
867 /* }}} */
868 
zend_throw_error_exception(zend_class_entry * exception_ce,zend_string * message,zend_long code,int severity)869 ZEND_API ZEND_COLD zend_object *zend_throw_error_exception(zend_class_entry *exception_ce, zend_string *message, zend_long code, int severity) /* {{{ */
870 {
871 	zend_object *obj = zend_throw_exception_zstr(exception_ce, message, code);
872 	if (exception_ce && instanceof_function(exception_ce, zend_ce_error_exception)) {
873 		zval tmp;
874 		ZVAL_LONG(&tmp, severity);
875 		zend_update_property_ex(zend_ce_error_exception, obj, ZSTR_KNOWN(ZEND_STR_SEVERITY), &tmp);
876 	}
877 	return obj;
878 }
879 /* }}} */
880 
zend_error_va(int type,zend_string * file,uint32_t lineno,const char * format,...)881 static void zend_error_va(int type, zend_string *file, uint32_t lineno, const char *format, ...) /* {{{ */
882 {
883 	va_list args;
884 	va_start(args, format);
885 	zend_string *message = zend_vstrpprintf(0, format, args);
886 	zend_observer_error_notify(type, file, lineno, message);
887 	zend_error_cb(type, file, lineno, message);
888 	zend_string_release(message);
889 	va_end(args);
890 }
891 /* }}} */
892 
893 /* This function doesn't return if it uses E_ERROR */
zend_exception_error(zend_object * ex,int severity)894 ZEND_API ZEND_COLD zend_result zend_exception_error(zend_object *ex, int severity) /* {{{ */
895 {
896 	zval exception, rv;
897 	zend_class_entry *ce_exception;
898 	zend_result result = FAILURE;
899 
900 	ZVAL_OBJ(&exception, ex);
901 	ce_exception = ex->ce;
902 	EG(exception) = NULL;
903 	if (ce_exception == zend_ce_parse_error || ce_exception == zend_ce_compile_error) {
904 		zend_string *message = zval_get_string(GET_PROPERTY(&exception, ZEND_STR_MESSAGE));
905 		zend_string *file = zval_get_string(GET_PROPERTY_SILENT(&exception, ZEND_STR_FILE));
906 		zend_long line = zval_get_long(GET_PROPERTY_SILENT(&exception, ZEND_STR_LINE));
907 		int type = (ce_exception == zend_ce_parse_error ? E_PARSE : E_COMPILE_ERROR) | E_DONT_BAIL;
908 
909 		zend_observer_error_notify(type, file, line, message);
910 		zend_error_cb(type, file, line, message);
911 
912 		zend_string_release_ex(file, 0);
913 		zend_string_release_ex(message, 0);
914 	} else if (instanceof_function(ce_exception, zend_ce_throwable)) {
915 		zval tmp;
916 		zend_string *str, *file = NULL;
917 		zend_long line = 0;
918 
919 		zend_call_known_instance_method_with_0_params(ex->ce->__tostring, ex, &tmp);
920 		if (!EG(exception)) {
921 			if (Z_TYPE(tmp) != IS_STRING) {
922 				zend_error(E_WARNING, "%s::__toString() must return a string", ZSTR_VAL(ce_exception->name));
923 			} else {
924 				zend_update_property_ex(i_get_exception_base(ex), ex, ZSTR_KNOWN(ZEND_STR_STRING), &tmp);
925 			}
926 		}
927 		zval_ptr_dtor(&tmp);
928 
929 		if (EG(exception)) {
930 			zval zv;
931 
932 			ZVAL_OBJ(&zv, EG(exception));
933 			/* do the best we can to inform about the inner exception */
934 			if (instanceof_function(ce_exception, zend_ce_exception) || instanceof_function(ce_exception, zend_ce_error)) {
935 				file = zval_get_string(GET_PROPERTY_SILENT(&zv, ZEND_STR_FILE));
936 				line = zval_get_long(GET_PROPERTY_SILENT(&zv, ZEND_STR_LINE));
937 			}
938 
939 			zend_error_va(E_WARNING, (file && ZSTR_LEN(file) > 0) ? file : NULL, line,
940 				"Uncaught %s in exception handling during call to %s::__toString()",
941 				ZSTR_VAL(Z_OBJCE(zv)->name), ZSTR_VAL(ce_exception->name));
942 
943 			if (file) {
944 				zend_string_release_ex(file, 0);
945 			}
946 		}
947 
948 		str = zval_get_string(GET_PROPERTY_SILENT(&exception, ZEND_STR_STRING));
949 		file = zval_get_string(GET_PROPERTY_SILENT(&exception, ZEND_STR_FILE));
950 		line = zval_get_long(GET_PROPERTY_SILENT(&exception, ZEND_STR_LINE));
951 
952 		zend_error_va(severity | E_DONT_BAIL,
953 			(file && ZSTR_LEN(file) > 0) ? file : NULL, line,
954 			"Uncaught %S\n  thrown", str);
955 
956 		zend_string_release_ex(str, 0);
957 		zend_string_release_ex(file, 0);
958 	} else if (ce_exception == &zend_ce_unwind_exit || ce_exception == &zend_ce_graceful_exit) {
959 		/* We successfully unwound, nothing more to do.
960 		 * We still return FAILURE in this case, as further execution should still be aborted. */
961 	} else {
962 		zend_error(severity, "Uncaught exception %s", ZSTR_VAL(ce_exception->name));
963 	}
964 
965 	OBJ_RELEASE(ex);
966 	return result;
967 }
968 /* }}} */
969 
zend_exception_uncaught_error(const char * format,...)970 ZEND_NORETURN void zend_exception_uncaught_error(const char *format, ...) {
971 	va_list va;
972 	va_start(va, format);
973 	zend_string *prefix = zend_vstrpprintf(0, format, va);
974 	va_end(va);
975 
976 	ZEND_ASSERT(EG(exception));
977 	zval exception_zv;
978 	ZVAL_OBJ_COPY(&exception_zv, EG(exception));
979 	zend_clear_exception();
980 
981 	zend_string *exception_str = zval_get_string(&exception_zv);
982 	zend_error_noreturn(E_ERROR,
983 		"%s: Uncaught %s", ZSTR_VAL(prefix), ZSTR_VAL(exception_str));
984 }
985 
zend_throw_exception_object(zval * exception)986 ZEND_API ZEND_COLD void zend_throw_exception_object(zval *exception) /* {{{ */
987 {
988 	if (exception == NULL || Z_TYPE_P(exception) != IS_OBJECT) {
989 		zend_error_noreturn(E_CORE_ERROR, "Need to supply an object when throwing an exception");
990 	}
991 
992 	zend_class_entry *exception_ce = Z_OBJCE_P(exception);
993 
994 	if (!exception_ce || !instanceof_function(exception_ce, zend_ce_throwable)) {
995 		zend_throw_error(NULL, "Cannot throw objects that do not implement Throwable");
996 		zval_ptr_dtor(exception);
997 		return;
998 	}
999 
1000 	zend_throw_exception_internal(Z_OBJ_P(exception));
1001 }
1002 /* }}} */
1003 
zend_create_unwind_exit(void)1004 ZEND_API ZEND_COLD zend_object *zend_create_unwind_exit(void)
1005 {
1006 	return zend_objects_new(&zend_ce_unwind_exit);
1007 }
1008 
zend_create_graceful_exit(void)1009 ZEND_API ZEND_COLD zend_object *zend_create_graceful_exit(void)
1010 {
1011 	return zend_objects_new(&zend_ce_graceful_exit);
1012 }
1013 
zend_throw_unwind_exit(void)1014 ZEND_API ZEND_COLD void zend_throw_unwind_exit(void)
1015 {
1016 	ZEND_ASSERT(!EG(exception));
1017 	EG(exception) = zend_create_unwind_exit();
1018 	EG(opline_before_exception) = EG(current_execute_data)->opline;
1019 	EG(current_execute_data)->opline = EG(exception_op);
1020 }
1021 
zend_throw_graceful_exit(void)1022 ZEND_API ZEND_COLD void zend_throw_graceful_exit(void)
1023 {
1024 	ZEND_ASSERT(!EG(exception));
1025 	EG(exception) = zend_create_graceful_exit();
1026 	EG(opline_before_exception) = EG(current_execute_data)->opline;
1027 	EG(current_execute_data)->opline = EG(exception_op);
1028 }
1029 
zend_is_unwind_exit(const zend_object * ex)1030 ZEND_API bool zend_is_unwind_exit(const zend_object *ex)
1031 {
1032 	return ex->ce == &zend_ce_unwind_exit;
1033 }
1034 
zend_is_graceful_exit(const zend_object * ex)1035 ZEND_API bool zend_is_graceful_exit(const zend_object *ex)
1036 {
1037 	return ex->ce == &zend_ce_graceful_exit;
1038 }
1039