xref: /PHP-5.6/Zend/zend_exceptions.c (revision 40e7baab)
1 /*
2    +----------------------------------------------------------------------+
3    | Zend Engine                                                          |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1998-2016 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@zend.com>                                |
16    |          Marcus Boerger <helly@php.net>                              |
17    |          Sterling Hughes <sterling@php.net>                          |
18    |          Zeev Suraski <zeev@zend.com>                                |
19    +----------------------------------------------------------------------+
20 */
21 
22 /* $Id$ */
23 
24 #include "zend.h"
25 #include "zend_API.h"
26 #include "zend_builtin_functions.h"
27 #include "zend_interfaces.h"
28 #include "zend_exceptions.h"
29 #include "zend_vm.h"
30 #include "zend_dtrace.h"
31 
32 static zend_class_entry *default_exception_ce;
33 static zend_class_entry *error_exception_ce;
34 static zend_object_handlers default_exception_handlers;
35 ZEND_API void (*zend_throw_exception_hook)(zval *ex TSRMLS_DC);
36 
zend_exception_set_previous(zval * exception,zval * add_previous TSRMLS_DC)37 void zend_exception_set_previous(zval *exception, zval *add_previous TSRMLS_DC)
38 {
39 	zval *previous, *ancestor;
40 
41 	if (exception == add_previous || !add_previous || !exception) {
42 		return;
43 	}
44 	if (Z_TYPE_P(add_previous) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(add_previous), default_exception_ce TSRMLS_CC)) {
45 		zend_error(E_ERROR, "Cannot set non exception as previous exception");
46 		return;
47 	}
48 	while (exception && exception != add_previous && Z_OBJ_HANDLE_P(exception) != Z_OBJ_HANDLE_P(add_previous)) {
49 		ancestor = zend_read_property(default_exception_ce, add_previous, "previous", sizeof("previous")-1, 1 TSRMLS_CC);
50 		while (Z_TYPE_P(ancestor) == IS_OBJECT) {
51 			if (Z_OBJ_HANDLE_P(ancestor) == Z_OBJ_HANDLE_P(exception)) {
52 				zval_ptr_dtor(&add_previous);
53 				return;
54 			}
55 			ancestor = zend_read_property(default_exception_ce, ancestor, "previous", sizeof("previous")-1, 1 TSRMLS_CC);
56 		}
57 		previous = zend_read_property(default_exception_ce, exception, "previous", sizeof("previous")-1, 1 TSRMLS_CC);
58 		if (Z_TYPE_P(previous) == IS_NULL) {
59 			zend_update_property(default_exception_ce, exception, "previous", sizeof("previous")-1, add_previous TSRMLS_CC);
60 			Z_DELREF_P(add_previous);
61 			return;
62 		}
63 		exception = previous;
64 	}
65 }
66 
zend_exception_save(TSRMLS_D)67 void zend_exception_save(TSRMLS_D) /* {{{ */
68 {
69 	if (EG(prev_exception)) {
70 		zend_exception_set_previous(EG(exception), EG(prev_exception) TSRMLS_CC);
71 	}
72 	if (EG(exception)) {
73 		EG(prev_exception) = EG(exception);
74 	}
75 	EG(exception) = NULL;
76 }
77 /* }}} */
78 
zend_exception_restore(TSRMLS_D)79 void zend_exception_restore(TSRMLS_D) /* {{{ */
80 {
81 	if (EG(prev_exception)) {
82 		if (EG(exception)) {
83 			zend_exception_set_previous(EG(exception), EG(prev_exception) TSRMLS_CC);
84 		} else {
85 			EG(exception) = EG(prev_exception);
86 		}
87 		EG(prev_exception) = NULL;
88 	}
89 }
90 /* }}} */
91 
zend_throw_exception_internal(zval * exception TSRMLS_DC)92 void zend_throw_exception_internal(zval *exception TSRMLS_DC) /* {{{ */
93 {
94 #ifdef HAVE_DTRACE
95 	if (DTRACE_EXCEPTION_THROWN_ENABLED()) {
96 		const char *classname;
97 		zend_uint name_len;
98 
99 		if (exception != NULL) {
100 			zend_get_object_classname(exception, &classname, &name_len TSRMLS_CC);
101 			DTRACE_EXCEPTION_THROWN((char *)classname);
102 		} else {
103 			DTRACE_EXCEPTION_THROWN(NULL);
104 		}
105 	}
106 #endif /* HAVE_DTRACE */
107 
108 	if (exception != NULL) {
109 		zval *previous = EG(exception);
110 		zend_exception_set_previous(exception, EG(exception) TSRMLS_CC);
111 		EG(exception) = exception;
112 		if (previous) {
113 			return;
114 		}
115 	}
116 	if (!EG(current_execute_data)) {
117 		if(EG(exception)) {
118 			zend_exception_error(EG(exception), E_ERROR TSRMLS_CC);
119 		}
120 		zend_error(E_ERROR, "Exception thrown without a stack frame");
121 	}
122 
123 	if (zend_throw_exception_hook) {
124 		zend_throw_exception_hook(exception TSRMLS_CC);
125 	}
126 
127 	if (EG(current_execute_data)->opline == NULL ||
128 	    (EG(current_execute_data)->opline+1)->opcode == ZEND_HANDLE_EXCEPTION) {
129 		/* no need to rethrow the exception */
130 		return;
131 	}
132 	EG(opline_before_exception) = EG(current_execute_data)->opline;
133 	EG(current_execute_data)->opline = EG(exception_op);
134 }
135 /* }}} */
136 
zend_clear_exception(TSRMLS_D)137 ZEND_API void zend_clear_exception(TSRMLS_D) /* {{{ */
138 {
139 	if (EG(prev_exception)) {
140 		zval_ptr_dtor(&EG(prev_exception));
141 		EG(prev_exception) = NULL;
142 	}
143 	if (!EG(exception)) {
144 		return;
145 	}
146 	zval_ptr_dtor(&EG(exception));
147 	EG(exception) = NULL;
148 	EG(current_execute_data)->opline = EG(opline_before_exception);
149 #if ZEND_DEBUG
150 	EG(opline_before_exception) = NULL;
151 #endif
152 }
153 /* }}} */
154 
zend_default_exception_new_ex(zend_class_entry * class_type,int skip_top_traces TSRMLS_DC)155 static zend_object_value zend_default_exception_new_ex(zend_class_entry *class_type, int skip_top_traces TSRMLS_DC) /* {{{ */
156 {
157 	zval obj;
158 	zend_object *object;
159 	zval *trace;
160 
161 	Z_OBJVAL(obj) = zend_objects_new(&object, class_type TSRMLS_CC);
162 	Z_OBJ_HT(obj) = &default_exception_handlers;
163 
164 	object_properties_init(object, class_type);
165 
166 	ALLOC_ZVAL(trace);
167 	Z_UNSET_ISREF_P(trace);
168 	Z_SET_REFCOUNT_P(trace, 0);
169 	zend_fetch_debug_backtrace(trace, skip_top_traces, 0, 0 TSRMLS_CC);
170 
171 	zend_update_property_string(default_exception_ce, &obj, "file", sizeof("file")-1, zend_get_executed_filename(TSRMLS_C) TSRMLS_CC);
172 	zend_update_property_long(default_exception_ce, &obj, "line", sizeof("line")-1, zend_get_executed_lineno(TSRMLS_C) TSRMLS_CC);
173 	zend_update_property(default_exception_ce, &obj, "trace", sizeof("trace")-1, trace TSRMLS_CC);
174 
175 	return Z_OBJVAL(obj);
176 }
177 /* }}} */
178 
zend_default_exception_new(zend_class_entry * class_type TSRMLS_DC)179 static zend_object_value zend_default_exception_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
180 {
181 	return zend_default_exception_new_ex(class_type, 0 TSRMLS_CC);
182 }
183 /* }}} */
184 
zend_error_exception_new(zend_class_entry * class_type TSRMLS_DC)185 static zend_object_value zend_error_exception_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
186 {
187 	return zend_default_exception_new_ex(class_type, 2 TSRMLS_CC);
188 }
189 /* }}} */
190 
191 /* {{{ proto Exception Exception::__clone()
192    Clone the exception object */
ZEND_METHOD(exception,__clone)193 ZEND_METHOD(exception, __clone)
194 {
195 	/* Should never be executable */
196 	zend_throw_exception(NULL, "Cannot clone object using __clone()", 0 TSRMLS_CC);
197 }
198 /* }}} */
199 
200 /* {{{ proto Exception::__construct(string message, int code [, Exception previous])
201    Exception constructor */
ZEND_METHOD(exception,__construct)202 ZEND_METHOD(exception, __construct)
203 {
204 	char  *message = NULL;
205 	long   code = 0;
206 	zval  *object, *previous = NULL;
207 	int    argc = ZEND_NUM_ARGS(), message_len;
208 
209 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "|slO!", &message, &message_len, &code, &previous, default_exception_ce) == FAILURE) {
210 		zend_error(E_ERROR, "Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])");
211 	}
212 
213 	object = getThis();
214 
215 	if (message) {
216 		zend_update_property_stringl(default_exception_ce, object, "message", sizeof("message")-1, message, message_len TSRMLS_CC);
217 	}
218 
219 	if (code) {
220 		zend_update_property_long(default_exception_ce, object, "code", sizeof("code")-1, code TSRMLS_CC);
221 	}
222 
223 	if (previous) {
224 		zend_update_property(default_exception_ce, object, "previous", sizeof("previous")-1, previous TSRMLS_CC);
225 	}
226 }
227 /* }}} */
228 
229 /* {{{ proto Exception::__wakeup()
230    Exception unserialize checks */
231 #define CHECK_EXC_TYPE(name, type) \
232 	value = zend_read_property(default_exception_ce, object, name, sizeof(name)-1, 1 TSRMLS_CC); \
233 	if (value && Z_TYPE_P(value) != IS_NULL && Z_TYPE_P(value) != type) { \
234 		zend_unset_property(default_exception_ce, object, name, sizeof(name)-1 TSRMLS_CC); \
235 	}
236 
ZEND_METHOD(exception,__wakeup)237 ZEND_METHOD(exception, __wakeup)
238 {
239 	zval *value;
240 	zval *object = getThis();
241 	CHECK_EXC_TYPE("message", IS_STRING);
242 	CHECK_EXC_TYPE("string", IS_STRING);
243 	CHECK_EXC_TYPE("code", IS_LONG);
244 	CHECK_EXC_TYPE("file", IS_STRING);
245 	CHECK_EXC_TYPE("line", IS_LONG);
246 	CHECK_EXC_TYPE("trace", IS_ARRAY);
247 	value = zend_read_property(default_exception_ce, object, "previous", sizeof("previous")-1, 1 TSRMLS_CC);
248 	if (value && Z_TYPE_P(value) != IS_NULL && (Z_TYPE_P(value) != IS_OBJECT ||
249 			!instanceof_function(Z_OBJCE_P(value), default_exception_ce TSRMLS_CC) ||
250 			value == object)) {
251 		zend_unset_property(default_exception_ce, object, "previous", sizeof("previous")-1 TSRMLS_CC);
252 	}
253 }
254 /* }}} */
255 
256 /* {{{ proto ErrorException::__construct(string message, int code, int severity [, string filename [, int lineno [, Exception previous]]])
257    ErrorException constructor */
ZEND_METHOD(error_exception,__construct)258 ZEND_METHOD(error_exception, __construct)
259 {
260 	char  *message = NULL, *filename = NULL;
261 	long   code = 0, severity = E_ERROR, lineno;
262 	zval  *object, *previous = NULL;
263 	int    argc = ZEND_NUM_ARGS(), message_len, filename_len;
264 
265 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "|sllslO!", &message, &message_len, &code, &severity, &filename, &filename_len, &lineno, &previous, default_exception_ce) == FAILURE) {
266 		zend_error(E_ERROR, "Wrong parameters for ErrorException([string $exception [, long $code, [ long $severity, [ string $filename, [ long $lineno  [, Exception $previous = NULL]]]]]])");
267 	}
268 
269 	object = getThis();
270 
271 	if (message) {
272 		zend_update_property_string(default_exception_ce, object, "message", sizeof("message")-1, message TSRMLS_CC);
273 	}
274 
275 	if (code) {
276 		zend_update_property_long(default_exception_ce, object, "code", sizeof("code")-1, code TSRMLS_CC);
277 	}
278 
279 	if (previous) {
280 		zend_update_property(default_exception_ce, object, "previous", sizeof("previous")-1, previous TSRMLS_CC);
281 	}
282 
283 	zend_update_property_long(default_exception_ce, object, "severity", sizeof("severity")-1, severity TSRMLS_CC);
284 
285 	if (argc >= 4) {
286 	    zend_update_property_string(default_exception_ce, object, "file", sizeof("file")-1, filename TSRMLS_CC);
287     	if (argc < 5) {
288     	    lineno = 0; /* invalidate lineno */
289     	}
290     	zend_update_property_long(default_exception_ce, object, "line", sizeof("line")-1, lineno TSRMLS_CC);
291 	}
292 }
293 /* }}} */
294 
295 #define DEFAULT_0_PARAMS \
296 	if (zend_parse_parameters_none() == FAILURE) { \
297 		return; \
298 	}
299 
_default_exception_get_entry(zval * object,char * name,int name_len,zval * return_value TSRMLS_DC)300 static void _default_exception_get_entry(zval *object, char *name, int name_len, zval *return_value TSRMLS_DC) /* {{{ */
301 {
302 	zval *value;
303 
304 	value = zend_read_property(default_exception_ce, object, name, name_len, 0 TSRMLS_CC);
305 
306 	*return_value = *value;
307 	zval_copy_ctor(return_value);
308 	INIT_PZVAL(return_value);
309 }
310 /* }}} */
311 
312 /* {{{ proto string Exception::getFile()
313    Get the file in which the exception occurred */
ZEND_METHOD(exception,getFile)314 ZEND_METHOD(exception, getFile)
315 {
316 	DEFAULT_0_PARAMS;
317 
318 	_default_exception_get_entry(getThis(), "file", sizeof("file")-1, return_value TSRMLS_CC);
319 }
320 /* }}} */
321 
322 /* {{{ proto int Exception::getLine()
323    Get the line in which the exception occurred */
ZEND_METHOD(exception,getLine)324 ZEND_METHOD(exception, getLine)
325 {
326 	DEFAULT_0_PARAMS;
327 
328 	_default_exception_get_entry(getThis(), "line", sizeof("line")-1, return_value TSRMLS_CC);
329 }
330 /* }}} */
331 
332 /* {{{ proto string Exception::getMessage()
333    Get the exception message */
ZEND_METHOD(exception,getMessage)334 ZEND_METHOD(exception, getMessage)
335 {
336 	DEFAULT_0_PARAMS;
337 
338 	_default_exception_get_entry(getThis(), "message", sizeof("message")-1, return_value TSRMLS_CC);
339 }
340 /* }}} */
341 
342 /* {{{ proto int Exception::getCode()
343    Get the exception code */
ZEND_METHOD(exception,getCode)344 ZEND_METHOD(exception, getCode)
345 {
346 	DEFAULT_0_PARAMS;
347 
348 	_default_exception_get_entry(getThis(), "code", sizeof("code")-1, return_value TSRMLS_CC);
349 }
350 /* }}} */
351 
352 /* {{{ proto array Exception::getTrace()
353    Get the stack trace for the location in which the exception occurred */
ZEND_METHOD(exception,getTrace)354 ZEND_METHOD(exception, getTrace)
355 {
356 	DEFAULT_0_PARAMS;
357 
358 	_default_exception_get_entry(getThis(), "trace", sizeof("trace")-1, return_value TSRMLS_CC);
359 }
360 /* }}} */
361 
362 /* {{{ proto int ErrorException::getSeverity()
363    Get the exception severity */
ZEND_METHOD(error_exception,getSeverity)364 ZEND_METHOD(error_exception, getSeverity)
365 {
366 	DEFAULT_0_PARAMS;
367 
368 	_default_exception_get_entry(getThis(), "severity", sizeof("severity")-1, return_value TSRMLS_CC);
369 }
370 /* }}} */
371 
372 /* {{{ gettraceasstring() macros */
373 #define TRACE_APPEND_CHR(chr)                                            \
374 	*str = (char*)erealloc(*str, *len + 1 + 1);                          \
375 	(*str)[(*len)++] = chr
376 
377 #define TRACE_APPEND_STRL(val, vallen)                                   \
378 	{                                                                    \
379 		int l = vallen;                                                  \
380 		*str = (char*)erealloc(*str, *len + l + 1);                      \
381 		memcpy((*str) + *len, val, l);                                   \
382 		*len += l;                                                       \
383 	}
384 
385 #define TRACE_APPEND_STR(val)                                            \
386 	TRACE_APPEND_STRL(val, sizeof(val)-1)
387 
388 #define TRACE_APPEND_KEY(key)                                                   \
389 	if (zend_hash_find(ht, key, sizeof(key), (void**)&tmp) == SUCCESS) {    \
390 		if (Z_TYPE_PP(tmp) != IS_STRING) {                              \
391 			zend_error(E_WARNING, "Value for %s is no string", key); \
392 			TRACE_APPEND_STR("[unknown]");                          \
393 		} else {                                                        \
394 			TRACE_APPEND_STRL(Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));  \
395 		}                                                               \
396 	}
397 
398 
399 #define TRACE_ARG_APPEND(vallen)								\
400 	*str = (char*)erealloc(*str, *len + 1 + vallen);					\
401 	memmove((*str) + *len - l_added + 1 + vallen, (*str) + *len - l_added + 1, l_added);
402 
403 /* }}} */
404 
_build_trace_args(zval ** arg TSRMLS_DC,int num_args,va_list args,zend_hash_key * hash_key)405 static int _build_trace_args(zval **arg TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */
406 {
407 	char **str;
408 	int *len;
409 
410 	str = va_arg(args, char**);
411 	len = va_arg(args, int*);
412 
413 	/* the trivial way would be to do:
414 	 * convert_to_string_ex(arg);
415 	 * append it and kill the now tmp arg.
416 	 * but that could cause some E_NOTICE and also damn long lines.
417 	 */
418 
419 	switch (Z_TYPE_PP(arg)) {
420 		case IS_NULL:
421 			TRACE_APPEND_STR("NULL, ");
422 			break;
423 		case IS_STRING: {
424 			int l_added;
425 			TRACE_APPEND_CHR('\'');
426 			if (Z_STRLEN_PP(arg) > 15) {
427 				TRACE_APPEND_STRL(Z_STRVAL_PP(arg), 15);
428 				TRACE_APPEND_STR("...', ");
429 				l_added = 15 + 6 + 1; /* +1 because of while (--l_added) */
430 			} else {
431 				l_added = Z_STRLEN_PP(arg);
432 				TRACE_APPEND_STRL(Z_STRVAL_PP(arg), l_added);
433 				TRACE_APPEND_STR("', ");
434 				l_added += 3 + 1;
435 			}
436 			while (--l_added) {
437 				unsigned char chr = (*str)[*len - l_added];
438 				if (chr < 32 || chr == '\\' || chr > 126) {
439 					(*str)[*len - l_added] = '\\';
440 
441 					switch (chr) {
442 						case '\n':
443 							TRACE_ARG_APPEND(1);
444 							(*str)[++(*len) - l_added] = 'n';
445 							break;
446 						case '\r':
447 							TRACE_ARG_APPEND(1);
448 							(*str)[++(*len) - l_added] = 'r';
449 							break;
450 						case '\t':
451 							TRACE_ARG_APPEND(1);
452 							(*str)[++(*len) - l_added] = 't';
453 							break;
454 						case '\f':
455 							TRACE_ARG_APPEND(1);
456 							(*str)[++(*len) - l_added] = 'f';
457 							break;
458 						case '\v':
459 							TRACE_ARG_APPEND(1);
460 							(*str)[++(*len) - l_added] = 'v';
461 							break;
462 #ifndef PHP_WIN32
463 						case '\e':
464 #else
465 						case VK_ESCAPE:
466 #endif
467 							TRACE_ARG_APPEND(1);
468 							(*str)[++(*len) - l_added] = 'e';
469 							break;
470 						case '\\':
471 							TRACE_ARG_APPEND(1);
472 							(*str)[++(*len) - l_added] = '\\';
473 							break;
474 						default:
475 							TRACE_ARG_APPEND(3);
476 							(*str)[*len - l_added + 1] = 'x';
477 							if ((chr >> 4) < 10) {
478 								(*str)[*len - l_added + 2] = (chr >> 4) + '0';
479 							} else {
480 								(*str)[*len - l_added + 2] = (chr >> 4) + 'A' - 10;
481 							}
482 							if (chr % 16 < 10) {
483 								(*str)[*len - l_added + 3] = chr % 16 + '0';
484 							} else {
485 								(*str)[*len - l_added + 3] = chr % 16 + 'A' - 10;
486 							}
487 							*len += 3;
488 					}
489 				}
490 			}
491 			break;
492 		}
493 		case IS_BOOL:
494 			if (Z_LVAL_PP(arg)) {
495 				TRACE_APPEND_STR("true, ");
496 			} else {
497 				TRACE_APPEND_STR("false, ");
498 			}
499 			break;
500 		case IS_RESOURCE:
501 			TRACE_APPEND_STR("Resource id #");
502 			/* break; */
503 		case IS_LONG: {
504 			long lval = Z_LVAL_PP(arg);
505 			char s_tmp[MAX_LENGTH_OF_LONG + 1];
506 			int l_tmp = zend_sprintf(s_tmp, "%ld", lval);  /* SAFE */
507 			TRACE_APPEND_STRL(s_tmp, l_tmp);
508 			TRACE_APPEND_STR(", ");
509 			break;
510 		}
511 		case IS_DOUBLE: {
512 			double dval = Z_DVAL_PP(arg);
513 			char *s_tmp;
514 			int l_tmp;
515 
516 			s_tmp = emalloc(MAX_LENGTH_OF_DOUBLE + EG(precision) + 1);
517 			l_tmp = zend_sprintf(s_tmp, "%.*G", (int) EG(precision), dval);  /* SAFE */
518 			TRACE_APPEND_STRL(s_tmp, l_tmp);
519 			/* %G already handles removing trailing zeros from the fractional part, yay */
520 			efree(s_tmp);
521 			TRACE_APPEND_STR(", ");
522 			break;
523 		}
524 		case IS_ARRAY:
525 			TRACE_APPEND_STR("Array, ");
526 			break;
527 		case IS_OBJECT: {
528 			const char *class_name;
529 			zend_uint class_name_len;
530 			int dup;
531 
532 			TRACE_APPEND_STR("Object(");
533 
534 			dup = zend_get_object_classname(*arg, &class_name, &class_name_len TSRMLS_CC);
535 
536 			TRACE_APPEND_STRL(class_name, class_name_len);
537 			if(!dup) {
538 				efree((char*)class_name);
539 			}
540 
541 			TRACE_APPEND_STR("), ");
542 			break;
543 		}
544 		default:
545 			break;
546 	}
547 	return ZEND_HASH_APPLY_KEEP;
548 }
549 /* }}} */
550 
_build_trace_string(zval ** frame TSRMLS_DC,int num_args,va_list args,zend_hash_key * hash_key)551 static int _build_trace_string(zval **frame TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */
552 {
553 	char *s_tmp, **str;
554 	int *len, *num;
555 	long line;
556 	HashTable *ht = Z_ARRVAL_PP(frame);
557 	zval **file, **tmp;
558 
559 	if (Z_TYPE_PP(frame) != IS_ARRAY) {
560 		zend_error(E_WARNING, "Expected array for frame %lu", hash_key->h);
561 		return ZEND_HASH_APPLY_KEEP;
562 	}
563 
564 	str = va_arg(args, char**);
565 	len = va_arg(args, int*);
566 	num = va_arg(args, int*);
567 
568 	s_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 1 + 1);
569 	sprintf(s_tmp, "#%d ", (*num)++);
570 	TRACE_APPEND_STRL(s_tmp, strlen(s_tmp));
571 	efree(s_tmp);
572 	if (zend_hash_find(ht, "file", sizeof("file"), (void**)&file) == SUCCESS) {
573 		if (Z_TYPE_PP(file) != IS_STRING) {
574 			zend_error(E_WARNING, "Function name is no string");
575 			TRACE_APPEND_STR("[unknown function]");
576 		} else{
577 			if (zend_hash_find(ht, "line", sizeof("line"), (void**)&tmp) == SUCCESS) {
578 				if (Z_TYPE_PP(tmp) == IS_LONG) {
579 					line = Z_LVAL_PP(tmp);
580 				} else {
581 					zend_error(E_WARNING, "Line is no long");
582 					line = 0;
583 				}
584 			} else {
585 				line = 0;
586 			}
587 			s_tmp = emalloc(Z_STRLEN_PP(file) + MAX_LENGTH_OF_LONG + 4 + 1);
588 			sprintf(s_tmp, "%s(%ld): ", Z_STRVAL_PP(file), line);
589 			TRACE_APPEND_STRL(s_tmp, strlen(s_tmp));
590 			efree(s_tmp);
591 		}
592 	} else {
593 		TRACE_APPEND_STR("[internal function]: ");
594 	}
595 	TRACE_APPEND_KEY("class");
596 	TRACE_APPEND_KEY("type");
597 	TRACE_APPEND_KEY("function");
598 	TRACE_APPEND_CHR('(');
599 	if (zend_hash_find(ht, "args", sizeof("args"), (void**)&tmp) == SUCCESS) {
600 		if (Z_TYPE_PP(tmp) == IS_ARRAY) {
601 			int last_len = *len;
602 			zend_hash_apply_with_arguments(Z_ARRVAL_PP(tmp) TSRMLS_CC, (apply_func_args_t)_build_trace_args, 2, str, len);
603 			if (last_len != *len) {
604 				*len -= 2; /* remove last ', ' */
605 			}
606 		} else {
607 			zend_error(E_WARNING, "args element is no array");
608 		}
609 	}
610 	TRACE_APPEND_STR(")\n");
611 	return ZEND_HASH_APPLY_KEEP;
612 }
613 /* }}} */
614 
615 /* {{{ proto string Exception::getTraceAsString()
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 	zval *trace;
620 	char *res, **str, *s_tmp;
621 	int res_len = 0, *len = &res_len, num = 0;
622 
623 	DEFAULT_0_PARAMS;
624 
625 	trace = zend_read_property(default_exception_ce, getThis(), "trace", sizeof("trace")-1, 1 TSRMLS_CC);
626 	if (Z_TYPE_P(trace) != IS_ARRAY) {
627 		RETURN_FALSE;
628 	}
629 
630 	res = estrdup("");
631 	str = &res;
632 
633 	zend_hash_apply_with_arguments(Z_ARRVAL_P(trace) TSRMLS_CC, (apply_func_args_t)_build_trace_string, 3, str, len, &num);
634 
635 	s_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 7 + 1);
636 	sprintf(s_tmp, "#%d {main}", num);
637 	TRACE_APPEND_STRL(s_tmp, strlen(s_tmp));
638 	efree(s_tmp);
639 
640 	res[res_len] = '\0';
641 	RETURN_STRINGL(res, res_len, 0);
642 }
643 /* }}} */
644 
645 /* {{{ proto string Exception::getPrevious()
646    Return previous Exception or NULL. */
ZEND_METHOD(exception,getPrevious)647 ZEND_METHOD(exception, getPrevious)
648 {
649 	zval *previous;
650 
651 	DEFAULT_0_PARAMS;
652 
653 	previous = zend_read_property(default_exception_ce, getThis(), "previous", sizeof("previous")-1, 1 TSRMLS_CC);
654 	RETURN_ZVAL(previous, 1, 0);
655 }
656 /* }}} */
657 
zend_spprintf(char ** message,int max_len,const char * format,...)658 int zend_spprintf(char **message, int max_len, const char *format, ...) /* {{{ */
659 {
660 	va_list arg;
661 	int len;
662 
663 	va_start(arg, format);
664 	len = zend_vspprintf(message, max_len, format, arg);
665 	va_end(arg);
666 	return len;
667 }
668 /* }}} */
669 
670 /* {{{ proto string Exception::__toString()
671    Obtain the string representation of the Exception object */
ZEND_METHOD(exception,__toString)672 ZEND_METHOD(exception, __toString)
673 {
674 	zval message, file, line, *trace, *exception;
675 	char *str, *prev_str;
676 	int len = 0;
677 	zend_fcall_info fci;
678 	zval fname;
679 
680 	DEFAULT_0_PARAMS;
681 
682 	str = estrndup("", 0);
683 
684 	exception = getThis();
685 	ZVAL_STRINGL(&fname, "gettraceasstring", sizeof("gettraceasstring")-1, 1);
686 
687 	while (exception && Z_TYPE_P(exception) == IS_OBJECT && instanceof_function(Z_OBJCE_P(exception), default_exception_ce TSRMLS_CC)) {
688 		prev_str = str;
689 		_default_exception_get_entry(exception, "message", sizeof("message")-1, &message TSRMLS_CC);
690 		_default_exception_get_entry(exception, "file", sizeof("file")-1, &file TSRMLS_CC);
691 		_default_exception_get_entry(exception, "line", sizeof("line")-1, &line TSRMLS_CC);
692 
693 		convert_to_string(&message);
694 		convert_to_string(&file);
695 		convert_to_long(&line);
696 
697 		trace = NULL;
698 		fci.size = sizeof(fci);
699 		fci.function_table = &Z_OBJCE_P(exception)->function_table;
700 		fci.function_name = &fname;
701 		fci.symbol_table = NULL;
702 		fci.object_ptr = exception;
703 		fci.retval_ptr_ptr = &trace;
704 		fci.param_count = 0;
705 		fci.params = NULL;
706 		fci.no_separation = 1;
707 
708 		zend_call_function(&fci, NULL TSRMLS_CC);
709 
710 		if (trace && Z_TYPE_P(trace) != IS_STRING) {
711 			zval_ptr_dtor(&trace);
712 			trace = NULL;
713 		}
714 
715 		if (Z_STRLEN(message) > 0) {
716 			len = zend_spprintf(&str, 0, "exception '%s' with message '%s' in %s:%ld\nStack trace:\n%s%s%s",
717 								Z_OBJCE_P(exception)->name, Z_STRVAL(message), Z_STRVAL(file), Z_LVAL(line),
718 								(trace && Z_STRLEN_P(trace)) ? Z_STRVAL_P(trace) : "#0 {main}\n",
719 								len ? "\n\nNext " : "", prev_str);
720 		} else {
721 			len = zend_spprintf(&str, 0, "exception '%s' in %s:%ld\nStack trace:\n%s%s%s",
722 								Z_OBJCE_P(exception)->name, Z_STRVAL(file), Z_LVAL(line),
723 								(trace && Z_STRLEN_P(trace)) ? Z_STRVAL_P(trace) : "#0 {main}\n",
724 								len ? "\n\nNext " : "", prev_str);
725 		}
726 		efree(prev_str);
727 		zval_dtor(&message);
728 		zval_dtor(&file);
729 		zval_dtor(&line);
730 
731 		Z_OBJPROP_P(exception)->nApplyCount++;
732 		exception = zend_read_property(default_exception_ce, exception, "previous", sizeof("previous")-1, 1 TSRMLS_CC);
733 		if (exception && Z_TYPE_P(exception) == IS_OBJECT && Z_OBJPROP_P(exception)->nApplyCount > 0) {
734 			exception = NULL;
735 		}
736 
737 		if (trace) {
738 			zval_ptr_dtor(&trace);
739 		}
740 
741 	}
742 	zval_dtor(&fname);
743 
744 	/* Reset apply counts */
745 	exception = getThis();
746 	while (exception && Z_TYPE_P(exception) == IS_OBJECT && instanceof_function(Z_OBJCE_P(exception), default_exception_ce TSRMLS_CC)) {
747 		if(Z_OBJPROP_P(exception)->nApplyCount) {
748 			Z_OBJPROP_P(exception)->nApplyCount--;
749 		} else {
750 			break;
751 		}
752 		exception = zend_read_property(default_exception_ce, exception, "previous", sizeof("previous")-1, 1 TSRMLS_CC);
753 	}
754 
755 	/* We store the result in the private property string so we can access
756 	 * the result in uncaught exception handlers without memleaks. */
757 	zend_update_property_string(default_exception_ce, getThis(), "string", sizeof("string")-1, str TSRMLS_CC);
758 
759 	RETURN_STRINGL(str, len, 0);
760 }
761 /* }}} */
762 
763 /* {{{ internal structs */
764 /* All functions that may be used in uncaught exception handlers must be final
765  * and must not throw exceptions. Otherwise we would need a facility to handle
766  * such exceptions in that handler.
767  * Also all getXY() methods are final because thy serve as read only access to
768  * their corresponding properties, no more, no less. If after all you need to
769  * override somthing then it is method __toString().
770  * And never try to change the state of exceptions and never implement anything
771  * that gives the user anything to accomplish this.
772  */
773 ZEND_BEGIN_ARG_INFO_EX(arginfo_exception___construct, 0, 0, 0)
774 	ZEND_ARG_INFO(0, message)
775 	ZEND_ARG_INFO(0, code)
776 	ZEND_ARG_INFO(0, previous)
777 ZEND_END_ARG_INFO()
778 
779 const static zend_function_entry default_exception_functions[] = {
780 	ZEND_ME(exception, __clone, NULL, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
781 	ZEND_ME(exception, __construct, arginfo_exception___construct, ZEND_ACC_PUBLIC)
782 	ZEND_ME(exception, __wakeup, NULL, ZEND_ACC_PUBLIC)
783 	ZEND_ME(exception, getMessage, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
784 	ZEND_ME(exception, getCode, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
785 	ZEND_ME(exception, getFile, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
786 	ZEND_ME(exception, getLine, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
787 	ZEND_ME(exception, getTrace, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
788 	ZEND_ME(exception, getPrevious, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
789 	ZEND_ME(exception, getTraceAsString, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
790 	ZEND_ME(exception, __toString, NULL, 0)
791 	{NULL, NULL, NULL}
792 };
793 
794 ZEND_BEGIN_ARG_INFO_EX(arginfo_error_exception___construct, 0, 0, 0)
795 	ZEND_ARG_INFO(0, message)
796 	ZEND_ARG_INFO(0, code)
797 	ZEND_ARG_INFO(0, severity)
798 	ZEND_ARG_INFO(0, filename)
799 	ZEND_ARG_INFO(0, lineno)
800 	ZEND_ARG_INFO(0, previous)
801 ZEND_END_ARG_INFO()
802 
803 static const zend_function_entry error_exception_functions[] = {
804 	ZEND_ME(error_exception, __construct, arginfo_error_exception___construct, ZEND_ACC_PUBLIC)
805 	ZEND_ME(error_exception, getSeverity, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
806 	{NULL, NULL, NULL}
807 };
808 /* }}} */
809 
zend_register_default_exception(TSRMLS_D)810 void zend_register_default_exception(TSRMLS_D) /* {{{ */
811 {
812 	zend_class_entry ce;
813 
814 	INIT_CLASS_ENTRY(ce, "Exception", default_exception_functions);
815 	default_exception_ce = zend_register_internal_class(&ce TSRMLS_CC);
816 	default_exception_ce->create_object = zend_default_exception_new;
817 	memcpy(&default_exception_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
818 	default_exception_handlers.clone_obj = NULL;
819 
820 	zend_declare_property_string(default_exception_ce, "message", sizeof("message")-1, "", ZEND_ACC_PROTECTED TSRMLS_CC);
821 	zend_declare_property_string(default_exception_ce, "string", sizeof("string")-1, "", ZEND_ACC_PRIVATE TSRMLS_CC);
822 	zend_declare_property_long(default_exception_ce, "code", sizeof("code")-1, 0, ZEND_ACC_PROTECTED TSRMLS_CC);
823 	zend_declare_property_null(default_exception_ce, "file", sizeof("file")-1, ZEND_ACC_PROTECTED TSRMLS_CC);
824 	zend_declare_property_null(default_exception_ce, "line", sizeof("line")-1, ZEND_ACC_PROTECTED TSRMLS_CC);
825 	zend_declare_property_null(default_exception_ce, "trace", sizeof("trace")-1, ZEND_ACC_PRIVATE TSRMLS_CC);
826 	zend_declare_property_null(default_exception_ce, "previous", sizeof("previous")-1, ZEND_ACC_PRIVATE TSRMLS_CC);
827 
828 	INIT_CLASS_ENTRY(ce, "ErrorException", error_exception_functions);
829 	error_exception_ce = zend_register_internal_class_ex(&ce, default_exception_ce, NULL TSRMLS_CC);
830 	error_exception_ce->create_object = zend_error_exception_new;
831 	zend_declare_property_long(error_exception_ce, "severity", sizeof("severity")-1, E_ERROR, ZEND_ACC_PROTECTED TSRMLS_CC);
832 }
833 /* }}} */
834 
zend_exception_get_default(TSRMLS_D)835 ZEND_API zend_class_entry *zend_exception_get_default(TSRMLS_D) /* {{{ */
836 {
837 	return default_exception_ce;
838 }
839 /* }}} */
840 
zend_get_error_exception(TSRMLS_D)841 ZEND_API zend_class_entry *zend_get_error_exception(TSRMLS_D) /* {{{ */
842 {
843 	return error_exception_ce;
844 }
845 /* }}} */
846 
zend_throw_exception(zend_class_entry * exception_ce,const char * message,long code TSRMLS_DC)847 ZEND_API zval * zend_throw_exception(zend_class_entry *exception_ce, const char *message, long code TSRMLS_DC) /* {{{ */
848 {
849 	zval *ex;
850 
851 	MAKE_STD_ZVAL(ex);
852 	if (exception_ce) {
853 		if (!instanceof_function(exception_ce, default_exception_ce TSRMLS_CC)) {
854 			zend_error(E_NOTICE, "Exceptions must be derived from the Exception base class");
855 			exception_ce = default_exception_ce;
856 		}
857 	} else {
858 		exception_ce = default_exception_ce;
859 	}
860 	object_init_ex(ex, exception_ce);
861 
862 
863 	if (message) {
864 		zend_update_property_string(default_exception_ce, ex, "message", sizeof("message")-1, message TSRMLS_CC);
865 	}
866 	if (code) {
867 		zend_update_property_long(default_exception_ce, ex, "code", sizeof("code")-1, code TSRMLS_CC);
868 	}
869 
870 	zend_throw_exception_internal(ex TSRMLS_CC);
871 	return ex;
872 }
873 /* }}} */
874 
zend_throw_exception_ex(zend_class_entry * exception_ce,long code TSRMLS_DC,const char * format,...)875 ZEND_API zval * zend_throw_exception_ex(zend_class_entry *exception_ce, long code TSRMLS_DC, const char *format, ...) /* {{{ */
876 {
877 	va_list arg;
878 	char *message;
879 	zval *zexception;
880 
881 	va_start(arg, format);
882 	zend_vspprintf(&message, 0, format, arg);
883 	va_end(arg);
884 	zexception = zend_throw_exception(exception_ce, message, code TSRMLS_CC);
885 	efree(message);
886 	return zexception;
887 }
888 /* }}} */
889 
zend_throw_error_exception(zend_class_entry * exception_ce,const char * message,long code,int severity TSRMLS_DC)890 ZEND_API zval * zend_throw_error_exception(zend_class_entry *exception_ce, const char *message, long code, int severity TSRMLS_DC) /* {{{ */
891 {
892 	zval *ex = zend_throw_exception(exception_ce, message, code TSRMLS_CC);
893 	zend_update_property_long(default_exception_ce, ex, "severity", sizeof("severity")-1, severity TSRMLS_CC);
894 	return ex;
895 }
896 /* }}} */
897 
zend_error_va(int type,const char * file,uint lineno,const char * format,...)898 static void zend_error_va(int type, const char *file, uint lineno, const char *format, ...) /* {{{ */
899 {
900 	va_list args;
901 
902 	va_start(args, format);
903 	zend_error_cb(type, file, lineno, format, args);
904 	va_end(args);
905 }
906 /* }}} */
907 
908 /* This function doesn't return if it uses E_ERROR */
zend_exception_error(zval * exception,int severity TSRMLS_DC)909 ZEND_API void zend_exception_error(zval *exception, int severity TSRMLS_DC) /* {{{ */
910 {
911 	zend_class_entry *ce_exception = Z_OBJCE_P(exception);
912 	EG(exception) = NULL;
913 	if (instanceof_function(ce_exception, default_exception_ce TSRMLS_CC)) {
914 		zval *str, *file, *line;
915 
916 		zend_call_method_with_0_params(&exception, ce_exception, NULL, "__tostring", &str);
917 		if (!EG(exception)) {
918 			if (Z_TYPE_P(str) != IS_STRING) {
919 				zend_error(E_WARNING, "%s::__toString() must return a string", ce_exception->name);
920 			} else {
921 				zend_update_property_string(default_exception_ce, exception, "string", sizeof("string")-1, EG(exception) ? ce_exception->name : Z_STRVAL_P(str) TSRMLS_CC);
922 			}
923 		}
924 		zval_ptr_dtor(&str);
925 
926 		if (EG(exception)) {
927 			/* do the best we can to inform about the inner exception */
928 			if (instanceof_function(ce_exception, default_exception_ce TSRMLS_CC)) {
929 				file = zend_read_property(default_exception_ce, EG(exception), "file", sizeof("file")-1, 1 TSRMLS_CC);
930 				line = zend_read_property(default_exception_ce, EG(exception), "line", sizeof("line")-1, 1 TSRMLS_CC);
931 
932 				convert_to_string(file);
933 				file = (Z_STRLEN_P(file) > 0) ? file : NULL;
934 				line = (Z_TYPE_P(line) == IS_LONG) ? line : NULL;
935 			} else {
936 				file = NULL;
937 				line = NULL;
938 			}
939 			zend_error_va(E_WARNING, file ? Z_STRVAL_P(file) : NULL, line ? Z_LVAL_P(line) : 0, "Uncaught %s in exception handling during call to %s::__tostring()", Z_OBJCE_P(EG(exception))->name, ce_exception->name);
940 		}
941 
942 		str = zend_read_property(default_exception_ce, exception, "string", sizeof("string")-1, 1 TSRMLS_CC);
943 		file = zend_read_property(default_exception_ce, exception, "file", sizeof("file")-1, 1 TSRMLS_CC);
944 		line = zend_read_property(default_exception_ce, exception, "line", sizeof("line")-1, 1 TSRMLS_CC);
945 
946 		convert_to_string(str);
947 		convert_to_string(file);
948 		convert_to_long(line);
949 
950 		zend_error_va(severity, (Z_STRLEN_P(file) > 0) ? Z_STRVAL_P(file) : NULL, Z_LVAL_P(line), "Uncaught %s\n  thrown", Z_STRVAL_P(str));
951 	} else {
952 		zend_error(severity, "Uncaught exception '%s'", ce_exception->name);
953 	}
954 	zval_ptr_dtor(&exception);
955 }
956 /* }}} */
957 
zend_throw_exception_object(zval * exception TSRMLS_DC)958 ZEND_API void zend_throw_exception_object(zval *exception TSRMLS_DC) /* {{{ */
959 {
960 	zend_class_entry *exception_ce;
961 
962 	if (exception == NULL || Z_TYPE_P(exception) != IS_OBJECT) {
963 		zend_error(E_ERROR, "Need to supply an object when throwing an exception");
964 	}
965 
966 	exception_ce = Z_OBJCE_P(exception);
967 
968 	if (!exception_ce || !instanceof_function(exception_ce, default_exception_ce TSRMLS_CC)) {
969 		zend_error(E_ERROR, "Exceptions must be valid objects derived from the Exception base class");
970 	}
971 	zend_throw_exception_internal(exception TSRMLS_CC);
972 }
973 /* }}} */
974 
975 /*
976  * Local variables:
977  * tab-width: 4
978  * c-basic-offset: 4
979  * indent-tabs-mode: t
980  * End:
981  */
982