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