xref: /PHP-7.0/sapi/phpdbg/phpdbg_prompt.c (revision 4bebcb84)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2017 The PHP Group                                |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP 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.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Felipe Pena <felipe@php.net>                                |
16    | Authors: Joe Watkins <joe.watkins@live.co.uk>                        |
17    | Authors: Bob Weinand <bwoebi@php.net>                                |
18    +----------------------------------------------------------------------+
19 */
20 
21 #include <stdio.h>
22 #include <string.h>
23 #include "zend.h"
24 #include "zend_compile.h"
25 #include "zend_exceptions.h"
26 #include "zend_vm.h"
27 #include "zend_generators.h"
28 #include "zend_interfaces.h"
29 #include "zend_smart_str.h"
30 #include "phpdbg.h"
31 #include "phpdbg_io.h"
32 
33 #include "phpdbg_help.h"
34 #include "phpdbg_print.h"
35 #include "phpdbg_info.h"
36 #include "phpdbg_break.h"
37 #include "phpdbg_opcode.h"
38 #include "phpdbg_list.h"
39 #include "phpdbg_utils.h"
40 #include "phpdbg_prompt.h"
41 #include "phpdbg_cmd.h"
42 #include "phpdbg_set.h"
43 #include "phpdbg_frame.h"
44 #include "phpdbg_lexer.h"
45 #include "phpdbg_parser.h"
46 #include "phpdbg_wait.h"
47 #include "phpdbg_eol.h"
48 
49 #if ZEND_VM_KIND != ZEND_VM_KIND_CALL
50 #error "phpdbg can only be built with CALL zend vm kind"
51 #endif
52 
53 ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
54 extern int phpdbg_startup_run;
55 
56 #ifdef HAVE_LIBDL
57 #ifdef PHP_WIN32
58 #include "win32/param.h"
59 #include "win32/winutil.h"
60 #define GET_DL_ERROR()  php_win_err()
61 #elif defined(NETWARE)
62 #include <sys/param.h>
63 #define GET_DL_ERROR()  dlerror()
64 #else
65 #include <sys/param.h>
66 #define GET_DL_ERROR()  DL_ERROR()
67 #endif
68 #endif
69 
70 /* {{{ command declarations */
71 const phpdbg_command_t phpdbg_prompt_commands[] = {
72 	PHPDBG_COMMAND_D(exec,    "set execution context",                    'e', NULL, "s", 0),
73 	PHPDBG_COMMAND_D(stdin,   "read script from stdin",                    0 , NULL, "s", 0),
74 	PHPDBG_COMMAND_D(step,    "step through execution",                   's', NULL, 0, PHPDBG_ASYNC_SAFE),
75 	PHPDBG_COMMAND_D(continue,"continue execution",                       'c', NULL, 0, PHPDBG_ASYNC_SAFE),
76 	PHPDBG_COMMAND_D(run,     "attempt execution",                        'r', NULL, "|s", 0),
77 	PHPDBG_COMMAND_D(ev,      "evaluate some code",                        0 , NULL, "i", PHPDBG_ASYNC_SAFE), /* restricted ASYNC_SAFE */
78 	PHPDBG_COMMAND_D(until,   "continue past the current line",           'u', NULL, 0, 0),
79 	PHPDBG_COMMAND_D(finish,  "continue past the end of the stack",       'F', NULL, 0, 0),
80 	PHPDBG_COMMAND_D(leave,   "continue until the end of the stack",      'L', NULL, 0, 0),
81 	PHPDBG_COMMAND_D(print,   "print something",                          'p', phpdbg_print_commands, "|*c", 0),
82 	PHPDBG_COMMAND_D(break,   "set breakpoint",                           'b', phpdbg_break_commands, "|*c", 0),
83 	PHPDBG_COMMAND_D(back,    "show trace",                               't', NULL, "|n", PHPDBG_ASYNC_SAFE),
84 	PHPDBG_COMMAND_D(frame,   "switch to a frame",                        'f', NULL, "|n", PHPDBG_ASYNC_SAFE),
85 	PHPDBG_COMMAND_D(list,    "lists some code",                          'l', phpdbg_list_commands,  "*", PHPDBG_ASYNC_SAFE),
86 	PHPDBG_COMMAND_D(info,    "displays some informations",               'i', phpdbg_info_commands, "|s", PHPDBG_ASYNC_SAFE),
87 	PHPDBG_COMMAND_D(clean,   "clean the execution environment",          'X', NULL, 0, 0),
88 	PHPDBG_COMMAND_D(clear,   "clear breakpoints",                        'C', NULL, 0, 0),
89 	PHPDBG_COMMAND_D(help,    "show help menu",                           'h', phpdbg_help_commands, "|s", PHPDBG_ASYNC_SAFE),
90 	PHPDBG_COMMAND_D(set,     "set phpdbg configuration",                 'S', phpdbg_set_commands,   "s", PHPDBG_ASYNC_SAFE),
91 	PHPDBG_COMMAND_D(register,"register a function",                      'R', NULL, "s", 0),
92 	PHPDBG_COMMAND_D(source,  "execute a phpdbginit",                     '<', NULL, "s", 0),
93 	PHPDBG_COMMAND_D(export,  "export breaks to a .phpdbginit script",    '>', NULL, "s", PHPDBG_ASYNC_SAFE),
94 	PHPDBG_COMMAND_D(sh,   	  "shell a command",                           0 , NULL, "i", 0),
95 	PHPDBG_COMMAND_D(quit,    "exit phpdbg",                              'q', NULL, 0, PHPDBG_ASYNC_SAFE),
96 	PHPDBG_COMMAND_D(wait,    "wait for other process",                   'W', NULL, 0, 0),
97 	PHPDBG_COMMAND_D(watch,   "set watchpoint",                           'w', phpdbg_watch_commands, "|ss", 0),
98 	PHPDBG_COMMAND_D(next,    "step over next line",                      'n', NULL, 0, PHPDBG_ASYNC_SAFE),
99 	PHPDBG_COMMAND_D(eol,     "set EOL",                                  'E', NULL, "|s", 0),
100 	PHPDBG_END_COMMAND
101 }; /* }}} */
102 
phpdbg_call_register(phpdbg_param_t * stack)103 static inline int phpdbg_call_register(phpdbg_param_t *stack) /* {{{ */
104 {
105 	phpdbg_param_t *name = NULL;
106 
107 	if (stack->type == STACK_PARAM) {
108 		char *lc_name;
109 
110 		name = stack->next;
111 
112 		if (!name || name->type != STR_PARAM) {
113 			return FAILURE;
114 		}
115 
116 		lc_name = zend_str_tolower_dup(name->str, name->len);
117 
118 		if (zend_hash_str_exists(&PHPDBG_G(registered), lc_name, name->len)) {
119 			zval fretval;
120 			zend_fcall_info fci;
121 
122 			memset(&fci, 0, sizeof(zend_fcall_info));
123 
124 			ZVAL_STRINGL(&fci.function_name, lc_name, name->len);
125 			fci.size = sizeof(zend_fcall_info);
126 			fci.function_table = &PHPDBG_G(registered);
127 			//???fci.symbol_table = zend_rebuild_symbol_table();
128 			fci.symbol_table = NULL;
129 			fci.object = NULL;
130 			fci.retval = &fretval;
131 			fci.no_separation = 1;
132 
133 			if (name->next) {
134 				zval params;
135 				phpdbg_param_t *next = name->next;
136 
137 				array_init(&params);
138 
139 				while (next) {
140 					char *buffered = NULL;
141 
142 					switch (next->type) {
143 						case OP_PARAM:
144 						case COND_PARAM:
145 						case STR_PARAM:
146 							add_next_index_stringl(&params, next->str, next->len);
147 						break;
148 
149 						case NUMERIC_PARAM:
150 							add_next_index_long(&params, next->num);
151 						break;
152 
153 						case METHOD_PARAM:
154 							spprintf(&buffered, 0, "%s::%s", next->method.class, next->method.name);
155 							add_next_index_string(&params, buffered);
156 						break;
157 
158 						case NUMERIC_METHOD_PARAM:
159 							spprintf(&buffered, 0, "%s::%s#%ld", next->method.class, next->method.name, next->num);
160 							add_next_index_string(&params, buffered);
161 						break;
162 
163 						case NUMERIC_FUNCTION_PARAM:
164 							spprintf(&buffered, 0, "%s#%ld", next->str, next->num);
165 							add_next_index_string(&params, buffered);
166 						break;
167 
168 						case FILE_PARAM:
169 							spprintf(&buffered, 0, "%s:%ld", next->file.name, next->file.line);
170 							add_next_index_string(&params, buffered);
171 						break;
172 
173 						case NUMERIC_FILE_PARAM:
174 							spprintf(&buffered, 0, "%s:#%ld", next->file.name, next->file.line);
175 							add_next_index_string(&params, buffered);
176 						break;
177 
178 						default: {
179 							/* not yet */
180 						}
181 					}
182 
183 					next = next->next;
184 				}
185 
186 				zend_fcall_info_args(&fci, &params);
187 			} else {
188 				fci.params = NULL;
189 				fci.param_count = 0;
190 			}
191 
192 			phpdbg_activate_err_buf(0);
193 			phpdbg_free_err_buf();
194 
195 			phpdbg_debug("created %d params from arguments", fci.param_count);
196 
197 			if (zend_call_function(&fci, NULL) == SUCCESS) {
198 				zend_print_zval_r(&fretval, 0);
199 				phpdbg_out("\n");
200 				zval_ptr_dtor(&fretval);
201 			}
202 
203 			zval_dtor(&fci.function_name);
204 			efree(lc_name);
205 
206 			return SUCCESS;
207 		}
208 
209 		efree(lc_name);
210 	}
211 
212 	return FAILURE;
213 } /* }}} */
214 
215 struct phpdbg_init_state {
216 	int line;
217 	zend_bool in_code;
218 	char *code;
219 	size_t code_len;
220 	const char *init_file;
221 };
222 
phpdbg_line_init(char * cmd,struct phpdbg_init_state * state)223 static void phpdbg_line_init(char *cmd, struct phpdbg_init_state *state) {
224 	size_t cmd_len = strlen(cmd);
225 
226 	state->line++;
227 
228 	while (cmd_len > 0L && isspace(cmd[cmd_len-1])) {
229 		cmd_len--;
230 	}
231 
232 	cmd[cmd_len] = '\0';
233 
234 	if (*cmd && cmd_len > 0L && cmd[0] != '#') {
235 		if (cmd_len == 2) {
236 			if (memcmp(cmd, "<:", sizeof("<:")-1) == SUCCESS) {
237 				state->in_code = 1;
238 				return;
239 			} else {
240 				if (memcmp(cmd, ":>", sizeof(":>")-1) == SUCCESS) {
241 					state->in_code = 0;
242 					state->code[state->code_len] = '\0';
243 					zend_eval_stringl(state->code, state->code_len, NULL, "phpdbginit code");
244 					free(state->code);
245 					state->code = NULL;
246 					return;
247 				}
248 			}
249 		}
250 
251 		if (state->in_code) {
252 			if (state->code == NULL) {
253 				state->code = malloc(cmd_len + 1);
254 			} else {
255 				state->code = realloc(state->code, state->code_len + cmd_len + 1);
256 			}
257 
258 			if (state->code) {
259 				memcpy(&state->code[state->code_len], cmd, cmd_len);
260 				state->code_len += cmd_len;
261 			}
262 
263 			return;
264 		}
265 
266 		zend_try {
267 			char *input = phpdbg_read_input(cmd);
268 			phpdbg_param_t stack;
269 
270 			phpdbg_init_param(&stack, STACK_PARAM);
271 
272 			phpdbg_activate_err_buf(1);
273 
274 			if (phpdbg_do_parse(&stack, input) <= 0) {
275 				switch (phpdbg_stack_execute(&stack, 1 /* allow_async_unsafe == 1 */)) {
276 					case FAILURE:
277 						phpdbg_activate_err_buf(0);
278 						if (phpdbg_call_register(&stack) == FAILURE) {
279 							if (state->init_file) {
280 								phpdbg_output_err_buf("initfailure", "%b file=\"%s\" line=\"%d\" input=\"%s\"", "Unrecognized command in %s:%d: %s, %b!", state->init_file, state->line, input);
281 							} else {
282 								phpdbg_output_err_buf("initfailure", "%b line=\"%d\" input=\"%s\"", "Unrecognized command on line %d: %s, %b!", state->line, input);
283 							}
284 						}
285 					break;
286 				}
287 			}
288 
289 			phpdbg_activate_err_buf(0);
290 			phpdbg_free_err_buf();
291 
292 			phpdbg_stack_free(&stack);
293 			phpdbg_destroy_input(&input);
294 		} zend_catch {
295 			PHPDBG_G(flags) &= ~(PHPDBG_IS_RUNNING | PHPDBG_IS_CLEANING);
296 			if (PHPDBG_G(flags) & PHPDBG_IS_QUITTING) {
297 				zend_bailout();
298 			}
299 		} zend_end_try();
300 	}
301 
302 }
303 
phpdbg_string_init(char * buffer)304 void phpdbg_string_init(char *buffer) {
305 	struct phpdbg_init_state state = {0};
306 	char *str = strtok(buffer, "\n");
307 
308 	while (str) {
309 		phpdbg_line_init(str, &state);
310 
311 		str = strtok(NULL, "\n");
312 	}
313 
314 	if (state.code) {
315 		free(state.code);
316 	}
317 }
318 
phpdbg_try_file_init(char * init_file,size_t init_file_len,zend_bool free_init)319 void phpdbg_try_file_init(char *init_file, size_t init_file_len, zend_bool free_init) /* {{{ */
320 {
321 	zend_stat_t sb;
322 
323 	if (init_file && VCWD_STAT(init_file, &sb) != -1) {
324 		FILE *fp = fopen(init_file, "r");
325 		if (fp) {
326 			char cmd[PHPDBG_MAX_CMD];
327 			struct phpdbg_init_state state = {0};
328 
329 			state.init_file = init_file;
330 
331 			while (fgets(cmd, PHPDBG_MAX_CMD, fp) != NULL) {
332 				phpdbg_line_init(cmd, &state);
333 			}
334 
335 			if (state.code) {
336 				free(state.code);
337 			}
338 
339 			fclose(fp);
340 		} else {
341 			phpdbg_error("initfailure", "type=\"openfile\" file=\"%s\"", "Failed to open %s for initialization", init_file);
342 		}
343 
344 		if (free_init) {
345 			free(init_file);
346 		}
347 	}
348 } /* }}} */
349 
phpdbg_init(char * init_file,size_t init_file_len,zend_bool use_default)350 void phpdbg_init(char *init_file, size_t init_file_len, zend_bool use_default) /* {{{ */
351 {
352 	if (init_file) {
353 		phpdbg_try_file_init(init_file, init_file_len, 1);
354 	} else if (use_default) {
355 		char *scan_dir = getenv("PHP_INI_SCAN_DIR");
356 		char *sys_ini;
357 		int i;
358 
359 		ZEND_IGNORE_VALUE(asprintf(&sys_ini, "%s/" PHPDBG_INIT_FILENAME, PHP_CONFIG_FILE_PATH));
360 		phpdbg_try_file_init(sys_ini, strlen(sys_ini), 0);
361 		free(sys_ini);
362 
363 		if (!scan_dir) {
364 			scan_dir = PHP_CONFIG_FILE_SCAN_DIR;
365 		}
366 		while (*scan_dir != 0) {
367 			i = 0;
368 			while (scan_dir[i] != ':') {
369 				if (scan_dir[i++] == 0) {
370 					i = -1;
371 					break;
372 				}
373 			}
374 			if (i != -1) {
375 				scan_dir[i] = 0;
376 			}
377 
378 			ZEND_IGNORE_VALUE(asprintf(&init_file, "%s/%s", scan_dir, PHPDBG_INIT_FILENAME));
379 			phpdbg_try_file_init(init_file, strlen(init_file), 1);
380 			if (i == -1) {
381 				break;
382 			}
383 			scan_dir += i + 1;
384 		}
385 
386 		phpdbg_try_file_init(PHPDBG_STRL(PHPDBG_INIT_FILENAME), 0);
387 	}
388 }
389 /* }}} */
390 
phpdbg_clean(zend_bool full,zend_bool resubmit)391 void phpdbg_clean(zend_bool full, zend_bool resubmit) /* {{{ */
392 {
393 	/* this is implicitly required */
394 	if (PHPDBG_G(ops)) {
395 		destroy_op_array(PHPDBG_G(ops));
396 		efree(PHPDBG_G(ops));
397 		PHPDBG_G(ops) = NULL;
398 	}
399 
400 	if (!resubmit && PHPDBG_G(cur_command)) {
401 		free(PHPDBG_G(cur_command));
402 		PHPDBG_G(cur_command) = NULL;
403 	}
404 
405 	if (full) {
406 		PHPDBG_G(flags) |= PHPDBG_IS_CLEANING;
407 	}
408 } /* }}} */
409 
PHPDBG_COMMAND(exec)410 PHPDBG_COMMAND(exec) /* {{{ */
411 {
412 	zend_stat_t sb;
413 
414 	if (VCWD_STAT(param->str, &sb) != FAILURE) {
415 		if (sb.st_mode & (S_IFREG|S_IFLNK)) {
416 			char *res = phpdbg_resolve_path(param->str);
417 			size_t res_len = strlen(res);
418 
419 			if ((res_len != PHPDBG_G(exec_len)) || (memcmp(res, PHPDBG_G(exec), res_len) != SUCCESS)) {
420 				if (PHPDBG_G(in_execution)) {
421 					if (phpdbg_ask_user_permission("Do you really want to stop execution to set a new execution context?") == FAILURE) {
422 						return FAILURE;
423 					}
424 				}
425 
426 				if (PHPDBG_G(exec)) {
427 					phpdbg_notice("exec", "type=\"unset\" context=\"%s\"", "Unsetting old execution context: %s", PHPDBG_G(exec));
428 					efree(PHPDBG_G(exec));
429 					PHPDBG_G(exec) = NULL;
430 					PHPDBG_G(exec_len) = 0L;
431 				}
432 
433 				if (PHPDBG_G(ops)) {
434 					phpdbg_notice("exec", "type=\"unsetops\"", "Destroying compiled opcodes");
435 					phpdbg_clean(0, 0);
436 				}
437 
438 				PHPDBG_G(exec) = res;
439 				PHPDBG_G(exec_len) = res_len;
440 
441 				VCWD_CHDIR_FILE(res);
442 
443 				*SG(request_info).argv = PHPDBG_G(exec);
444 				php_build_argv(NULL, &PG(http_globals)[TRACK_VARS_SERVER]);
445 
446 				phpdbg_notice("exec", "type=\"set\" context=\"%s\"", "Set execution context: %s", PHPDBG_G(exec));
447 
448 				if (PHPDBG_G(in_execution)) {
449 					phpdbg_clean(1, 0);
450 					return SUCCESS;
451 				}
452 
453 				phpdbg_compile();
454 			} else {
455 				phpdbg_notice("exec", "type=\"unchanged\"", "Execution context not changed");
456 			}
457 		} else {
458 			phpdbg_error("exec", "type=\"invalid\" context=\"%s\"", "Cannot use %s as execution context, not a valid file or symlink", param->str);
459 		}
460 	} else {
461 		phpdbg_error("exec", "type=\"notfound\" context=\"%s\"", "Cannot stat %s, ensure the file exists", param->str);
462 	}
463 	return SUCCESS;
464 } /* }}} */
465 
PHPDBG_COMMAND(stdin)466 PHPDBG_COMMAND(stdin)
467 {
468 	smart_str code = {0};
469 	char *buf;
470 	char *sep = param->str;
471 	int seplen = param->len;
472 	int bytes = 0;
473 
474 	smart_str_appends(&code, "?>");
475 
476 	do {
477 		PHPDBG_G(input_buflen) += bytes;
478 		if (PHPDBG_G(input_buflen) <= 0) {
479 			continue;
480 		}
481 
482 		if (sep && seplen) {
483 			char *nl = buf = PHPDBG_G(input_buffer);
484 			do {
485 				if (buf == nl + seplen) {
486 					if (!memcmp(sep, nl, seplen) && (*buf == '\n' || (*buf == '\r' && buf[1] == '\n'))) {
487 						smart_str_appendl(&code, PHPDBG_G(input_buffer), nl - PHPDBG_G(input_buffer));
488 						memmove(PHPDBG_G(input_buffer), ++buf, --PHPDBG_G(input_buflen));
489 						goto exec_code;
490 					}
491 				}
492 				if (*buf == '\n') {
493 					nl = buf + 1;
494 				}
495 				buf++;
496 			} while (--PHPDBG_G(input_buflen));
497 			if (buf != nl && buf <= nl + seplen) {
498 				smart_str_appendl(&code, PHPDBG_G(input_buffer), nl - PHPDBG_G(input_buffer));
499 				PHPDBG_G(input_buflen) = buf - nl;
500 				memmove(PHPDBG_G(input_buffer), nl, PHPDBG_G(input_buflen));
501 			} else {
502 				PHPDBG_G(input_buflen) = 0;
503 				smart_str_appendl(&code, PHPDBG_G(input_buffer), buf - PHPDBG_G(input_buffer));
504 			}
505 		} else {
506 			smart_str_appendl(&code, PHPDBG_G(input_buffer), PHPDBG_G(input_buflen));
507 			PHPDBG_G(input_buflen) = 0;
508 		}
509 	} while ((bytes = phpdbg_mixed_read(PHPDBG_G(io)[PHPDBG_STDIN].fd, PHPDBG_G(input_buffer) + PHPDBG_G(input_buflen), PHPDBG_MAX_CMD - PHPDBG_G(input_buflen), -1)) > 0);
510 
511 	if (bytes < 0) {
512 		PHPDBG_G(flags) |= PHPDBG_IS_QUITTING | PHPDBG_IS_DISCONNECTED;
513 		zend_bailout();
514 	}
515 
516 exec_code:
517 	smart_str_0(&code);
518 
519 	if (phpdbg_compile_stdin(code.s) == FAILURE) {
520 		zend_exception_error(EG(exception), E_ERROR);
521 		zend_bailout();
522 	}
523 
524 	return SUCCESS;
525 } /* }}} */
526 
phpdbg_compile_stdin(zend_string * code)527 int phpdbg_compile_stdin(zend_string *code) {
528 	zval zv;
529 
530 	ZVAL_STR(&zv, code);
531 
532 	PHPDBG_G(ops) = zend_compile_string(&zv, "-");
533 
534 	zend_string_release(code);
535 
536 	if (EG(exception)) {
537 		return FAILURE;
538 	}
539 
540 	if (PHPDBG_G(exec)) {
541 		efree(PHPDBG_G(exec));
542 	}
543 	PHPDBG_G(exec) = estrdup("-");
544 	PHPDBG_G(exec_len) = 1;
545 	{ /* remove leading ?> from source */
546 		int i;
547 		/* remove trailing data after zero byte, used for avoiding conflicts in eval()'ed code snippets */
548 		zend_string *source_path = strpprintf(0, "-%c%p", 0, PHPDBG_G(ops)->opcodes);
549 		phpdbg_file_source *data = zend_hash_find_ptr(&PHPDBG_G(file_sources), source_path);
550 		dtor_func_t dtor = PHPDBG_G(file_sources).pDestructor;
551 		PHPDBG_G(file_sources).pDestructor = NULL;
552 		zend_hash_del(&PHPDBG_G(file_sources), source_path);
553 		PHPDBG_G(file_sources).pDestructor = dtor;
554 		zend_hash_str_update_ptr(&PHPDBG_G(file_sources), "-", 1, data);
555 		zend_string_release(source_path);
556 
557 		for (i = 1; i <= data->lines; i++) {
558 			data->line[i] -= 2;
559 		}
560 		data->len -= 2;
561 		memmove(data->buf, data->buf + 2, data->len);
562 	}
563 
564 	phpdbg_notice("compile", "context=\"-\"", "Successful compilation of stdin input");
565 
566 	return SUCCESS;
567 }
568 
phpdbg_compile(void)569 int phpdbg_compile(void) /* {{{ */
570 {
571 	zend_file_handle fh;
572 	char *buf;
573 	char *start_line = NULL;
574 	size_t len;
575 	size_t start_line_len;
576 	int i;
577 
578 	if (!PHPDBG_G(exec)) {
579 		phpdbg_error("inactive", "type=\"nocontext\"", "No execution context");
580 		return FAILURE;
581 	}
582 
583 	if (php_stream_open_for_zend_ex(PHPDBG_G(exec), &fh, USE_PATH|STREAM_OPEN_FOR_INCLUDE) == SUCCESS && zend_stream_fixup(&fh, &buf, &len) == SUCCESS) {
584 		/* Skip #! line */
585 		if (len >= 3 && buf[0] == '#' && buf[1] == '!') {
586 			char *end = buf + len;
587 			do {
588 				switch (fh.handle.stream.mmap.buf++[0]) {
589 					case '\r':
590 						if (fh.handle.stream.mmap.buf[0] == '\n') {
591 							fh.handle.stream.mmap.buf++;
592 						}
593 					case '\n':
594 						CG(start_lineno) = 2;
595 						start_line_len = fh.handle.stream.mmap.buf - buf;
596 						start_line = emalloc(start_line_len);
597 						memcpy(start_line, buf, start_line_len);
598 						fh.handle.stream.mmap.len -= start_line_len;
599 						end = fh.handle.stream.mmap.buf;
600 				}
601 			} while (fh.handle.stream.mmap.buf + 1 < end);
602 		}
603 
604 		PHPDBG_G(ops) = zend_compile_file(&fh, ZEND_INCLUDE);
605 
606 		/* prepend shebang line to file_source */
607 		if (start_line) {
608 			phpdbg_file_source *data = zend_hash_find_ptr(&PHPDBG_G(file_sources), PHPDBG_G(ops)->filename);
609 
610 			dtor_func_t dtor = PHPDBG_G(file_sources).pDestructor;
611 			PHPDBG_G(file_sources).pDestructor = NULL;
612 			zend_hash_del(&PHPDBG_G(file_sources), PHPDBG_G(ops)->filename);
613 			PHPDBG_G(file_sources).pDestructor = dtor;
614 
615 			data = erealloc(data, sizeof(phpdbg_file_source) + sizeof(uint) * ++data->lines);
616 			memmove(data->line + 1, data->line, sizeof(uint) * data->lines);
617 			data->line[0] = 0;
618 			data->buf = erealloc(data->buf, data->len + start_line_len);
619 			memmove(data->buf + start_line_len, data->buf, data->len);
620 			memcpy(data->buf, start_line, start_line_len);
621 			efree(start_line);
622 			data->len += start_line_len;
623 			for (i = 1; i <= data->lines; i++) {
624 				data->line[i] += start_line_len;
625 			}
626 			zend_hash_update_ptr(&PHPDBG_G(file_sources), PHPDBG_G(ops)->filename, data);
627 		}
628 
629 		fh.handle.stream.mmap.buf = buf;
630 		fh.handle.stream.mmap.len = len;
631 		zend_destroy_file_handle(&fh);
632 		if (EG(exception)) {
633 			zend_exception_error(EG(exception), E_ERROR);
634 			zend_bailout();
635 		}
636 
637 		phpdbg_notice("compile", "context=\"%s\"", "Successful compilation of %s", PHPDBG_G(exec));
638 
639 		return SUCCESS;
640 	} else {
641 		phpdbg_error("compile", "type=\"openfailure\" context=\"%s\"", "Could not open file %s", PHPDBG_G(exec));
642 	}
643 
644 	return FAILURE;
645 } /* }}} */
646 
PHPDBG_COMMAND(step)647 PHPDBG_COMMAND(step) /* {{{ */
648 {
649 	if (PHPDBG_G(in_execution)) {
650 		PHPDBG_G(flags) |= PHPDBG_IS_STEPPING;
651 	}
652 
653 	return PHPDBG_NEXT;
654 } /* }}} */
655 
PHPDBG_COMMAND(continue)656 PHPDBG_COMMAND(continue) /* {{{ */
657 {
658 	return PHPDBG_NEXT;
659 } /* }}} */
660 
phpdbg_skip_line_helper()661 int phpdbg_skip_line_helper() /* {{{ */ {
662 	zend_execute_data *ex = phpdbg_user_execute_data(EG(current_execute_data));
663 	const zend_op_array *op_array = &ex->func->op_array;
664 	const zend_op *opline = op_array->opcodes;
665 
666 	PHPDBG_G(flags) |= PHPDBG_IN_UNTIL;
667 	PHPDBG_G(seek_ex) = ex;
668 	do {
669 		if (opline->lineno != ex->opline->lineno
670 		 || opline->opcode == ZEND_RETURN
671 		 || opline->opcode == ZEND_FAST_RET
672 		 || opline->opcode == ZEND_GENERATOR_RETURN
673 		 || opline->opcode == ZEND_EXIT
674 		 || opline->opcode == ZEND_YIELD
675 		 || opline->opcode == ZEND_YIELD_FROM
676 		) {
677 			zend_hash_index_update_ptr(&PHPDBG_G(seek), (zend_ulong) opline, (void *) opline);
678 		}
679 	} while (++opline < op_array->opcodes + op_array->last);
680 
681 	return PHPDBG_UNTIL;
682 }
683 /* }}} */
684 
PHPDBG_COMMAND(until)685 PHPDBG_COMMAND(until) /* {{{ */
686 {
687 	if (!PHPDBG_G(in_execution)) {
688 		phpdbg_error("inactive", "type=\"noexec\"", "Not executing");
689 		return SUCCESS;
690 	}
691 
692 	return phpdbg_skip_line_helper();
693 } /* }}} */
694 
PHPDBG_COMMAND(next)695 PHPDBG_COMMAND(next) /* {{{ */
696 {
697 	if (!PHPDBG_G(in_execution)) {
698 		phpdbg_error("inactive", "type=\"noexec\"", "Not executing");
699 		return SUCCESS;
700 	}
701 
702 	PHPDBG_G(flags) |= PHPDBG_IS_STEPPING;
703 	return phpdbg_skip_line_helper();
704 } /* }}} */
705 
phpdbg_seek_to_end(void)706 static void phpdbg_seek_to_end(void) /* {{{ */ {
707 	zend_execute_data *ex = phpdbg_user_execute_data(EG(current_execute_data));
708 	const zend_op_array *op_array = &ex->func->op_array;
709 	const zend_op *opline = op_array->opcodes;
710 
711 	PHPDBG_G(seek_ex) = ex;
712 	do {
713 		switch (opline->opcode) {
714 			case ZEND_RETURN:
715 			case ZEND_FAST_RET:
716 			case ZEND_GENERATOR_RETURN:
717 			case ZEND_EXIT:
718 			case ZEND_YIELD:
719 			case ZEND_YIELD_FROM:
720 				zend_hash_index_update_ptr(&PHPDBG_G(seek), (zend_ulong) opline, (void *) opline);
721 		}
722 	} while (++opline < op_array->opcodes + op_array->last);
723 }
724 /* }}} */
725 
PHPDBG_COMMAND(finish)726 PHPDBG_COMMAND(finish) /* {{{ */
727 {
728 	if (!PHPDBG_G(in_execution)) {
729 		phpdbg_error("inactive", "type=\"noexec\"", "Not executing");
730 		return SUCCESS;
731 	}
732 
733 	phpdbg_seek_to_end();
734 	if (zend_hash_index_exists(&PHPDBG_G(seek), (zend_ulong) phpdbg_user_execute_data(EG(current_execute_data))->opline)) {
735 		zend_hash_clean(&PHPDBG_G(seek));
736 	} else {
737 		PHPDBG_G(flags) |= PHPDBG_IN_FINISH;
738 	}
739 
740 	return PHPDBG_FINISH;
741 } /* }}} */
742 
PHPDBG_COMMAND(leave)743 PHPDBG_COMMAND(leave) /* {{{ */
744 {
745 	if (!PHPDBG_G(in_execution)) {
746 		phpdbg_error("inactive", "type=\"noexec\"", "Not executing");
747 		return SUCCESS;
748 	}
749 
750 	phpdbg_seek_to_end();
751 	if (zend_hash_index_exists(&PHPDBG_G(seek), (zend_ulong) phpdbg_user_execute_data(EG(current_execute_data))->opline)) {
752 		zend_hash_clean(&PHPDBG_G(seek));
753 		phpdbg_notice("leave", "type=\"end\"", "Already at the end of the function");
754 		return SUCCESS;
755 	} else {
756 		PHPDBG_G(flags) |= PHPDBG_IN_LEAVE;
757 		return PHPDBG_LEAVE;
758 	}
759 } /* }}} */
760 
PHPDBG_COMMAND(frame)761 PHPDBG_COMMAND(frame) /* {{{ */
762 {
763 	if (!param) {
764 		phpdbg_notice("frame", "id=\"%d\"", "Currently in frame #%d", PHPDBG_G(frame).num);
765 	} else {
766 		phpdbg_switch_frame(param->num);
767 	}
768 
769 	return SUCCESS;
770 } /* }}} */
771 
phpdbg_handle_exception(void)772 static inline void phpdbg_handle_exception(void) /* {{{ */
773 {
774 	zend_object *ex = EG(exception);
775 	zend_string *msg, *file;
776 	zend_long line;
777 	zval zv, rv, tmp;
778 
779 	EG(exception) = NULL;
780 
781 	ZVAL_OBJ(&zv, ex);
782 	zend_call_method_with_0_params(&zv, ex->ce, NULL, "__tostring", &tmp);
783 	file = zval_get_string(zend_read_property(zend_get_exception_base(&zv), &zv, ZEND_STRL("file"), 1, &rv));
784 	line = zval_get_long(zend_read_property(zend_get_exception_base(&zv), &zv, ZEND_STRL("line"), 1, &rv));
785 
786 	if (EG(exception)) {
787 		EG(exception) = NULL;
788 		msg = ZSTR_EMPTY_ALLOC();
789 	} else {
790 		zend_update_property_string(zend_get_exception_base(&zv), &zv, ZEND_STRL("string"), Z_STRVAL(tmp));
791 		zval_ptr_dtor(&tmp);
792 		msg = zval_get_string(zend_read_property(zend_get_exception_base(&zv), &zv, ZEND_STRL("string"), 1, &rv));
793 	}
794 
795 	phpdbg_error("exception", "name=\"%s\" file=\"%s\" line=\"" ZEND_LONG_FMT "\"", "Uncaught %s in %s on line " ZEND_LONG_FMT, ZSTR_VAL(ex->ce->name), ZSTR_VAL(file), line);
796 	zend_string_release(file);
797 	phpdbg_writeln("exceptionmsg", "msg=\"%s\"", ZSTR_VAL(msg));
798 	zend_string_release(msg);
799 
800 	if (EG(prev_exception)) {
801 		OBJ_RELEASE(EG(prev_exception));
802 		EG(prev_exception) = 0;
803 	}
804 	OBJ_RELEASE(ex);
805 	EG(opline_before_exception) = NULL;
806 
807 	EG(exit_status) = 255;
808 } /* }}} */
809 
PHPDBG_COMMAND(run)810 PHPDBG_COMMAND(run) /* {{{ */
811 {
812 	if (PHPDBG_G(ops) || PHPDBG_G(exec)) {
813 		zend_execute_data *ex = EG(current_execute_data);
814 		zend_bool restore = 1;
815 
816 		if (PHPDBG_G(in_execution)) {
817 			if (phpdbg_ask_user_permission("Do you really want to restart execution?") == SUCCESS) {
818 				phpdbg_startup_run++;
819 				phpdbg_clean(1, 1);
820 			}
821 			return SUCCESS;
822 		}
823 
824 		if (!PHPDBG_G(ops)) {
825 			if (phpdbg_compile() == FAILURE) {
826 				phpdbg_error("compile", "type=\"compilefailure\" context=\"%s\"", "Failed to compile %s, cannot run", PHPDBG_G(exec));
827 				goto out;
828 			}
829 		}
830 
831 		if (param && param->type != EMPTY_PARAM && param->len != 0) {
832 			char **argv = emalloc(5 * sizeof(char *));
833 			char *end = param->str + param->len, *p = param->str;
834 			int argc = 0;
835 			int i;
836 
837 			while (*end == '\r' || *end == '\n') *(end--) = 0;
838 
839 			while (*p == ' ') p++;
840 			while (*p) {
841 				char sep = ' ';
842 				char *buf = emalloc(end - p + 1), *q = buf;
843 
844 				if (*p == '<') {
845 					/* use as STDIN */
846 					do p++; while (*p == ' ');
847 
848 					if (*p == '\'' || *p == '"') {
849 						sep = *(p++);
850 					}
851 					while (*p && *p != sep) {
852 						if (*p == '\\' && (p[1] == sep || p[1] == '\\')) {
853 							p++;
854 						}
855 						*(q++) = *(p++);
856 					}
857 					*(q++) = 0;
858 					if (*p) {
859 						do p++; while (*p == ' ');
860 					}
861 
862 					if (*p) {
863 						phpdbg_error("cmd", "", "Invalid run command, cannot put further arguments after stdin");
864 						goto free_cmd;
865 					}
866 
867 					PHPDBG_G(stdin_file) = fopen(buf, "r");
868 					if (PHPDBG_G(stdin_file) == NULL) {
869 						phpdbg_error("stdin", "path=\"%s\"", "Could not open '%s' for reading from stdin", buf);
870 						goto free_cmd;
871 					}
872 					efree(buf);
873 					phpdbg_register_file_handles();
874 					break;
875 				}
876 
877 				if (argc >= 4 && argc == (argc & -argc)) {
878 					argv = erealloc(argv, (argc * 2 + 1) * sizeof(char *));
879 				}
880 
881 				if (*p == '\'' || *p == '"') {
882 					sep = *(p++);
883 				}
884 				if (*p == '\\' && (p[1] == '<' || p[1] == '\'' || p[1] == '"')) {
885 					p++;
886 				}
887 				while (*p && *p != sep) {
888 					if (*p == '\\' && (p[1] == sep || p[1] == '\\' || (p[1] == '#' && sep == ' '))) {
889 						p++;
890 					}
891 					*(q++) = *(p++);
892 				}
893 				if (!*p && sep != ' ') {
894 					phpdbg_error("cmd", "", "Invalid run command, unterminated escape sequence");
895 free_cmd:
896 					efree(buf);
897 					for (i = 0; i < argc; i++) {
898 						efree(argv[i]);
899 					}
900 					efree(argv);
901 					return SUCCESS;
902 				}
903 
904 				*(q++) = 0;
905 				argv[++argc] = erealloc(buf, q - buf);
906 
907 				if (*p) {
908 					do p++; while (*p == ' ');
909 				}
910 			}
911 			argv[0] = SG(request_info).argv[0];
912 			for (i = SG(request_info).argc; --i;) {
913 				efree(SG(request_info).argv[i]);
914 			}
915 			efree(SG(request_info).argv);
916 			SG(request_info).argv = erealloc(argv, ++argc * sizeof(char *));
917 			SG(request_info).argc = argc;
918 
919 			php_build_argv(NULL, &PG(http_globals)[TRACK_VARS_SERVER]);
920 		}
921 
922 		/* clean up from last execution */
923 		if (ex && ex->symbol_table) {
924 			zend_hash_clean(ex->symbol_table);
925 		} else {
926 			zend_rebuild_symbol_table();
927 		}
928 		PHPDBG_G(handled_exception) = NULL;
929 
930 		/* clean seek state */
931 		PHPDBG_G(flags) &= ~PHPDBG_SEEK_MASK;
932 		zend_hash_clean(&PHPDBG_G(seek));
933 
934 		/* reset hit counters */
935 		phpdbg_reset_breakpoints();
936 
937 		zend_try {
938 			PHPDBG_G(flags) ^= PHPDBG_IS_INTERACTIVE;
939 			PHPDBG_G(flags) |= PHPDBG_IS_RUNNING;
940 			zend_execute(PHPDBG_G(ops), &PHPDBG_G(retval));
941 			PHPDBG_G(flags) ^= PHPDBG_IS_INTERACTIVE;
942 		} zend_catch {
943 			PHPDBG_G(in_execution) = 0;
944 
945 			if (!(PHPDBG_G(flags) & PHPDBG_IS_STOPPING)) {
946 				restore = 0;
947 			} else {
948 				zend_bailout();
949 			}
950 		} zend_end_try();
951 
952 		if (PHPDBG_G(socket_fd) != -1) {
953 			close(PHPDBG_G(socket_fd));
954 			PHPDBG_G(socket_fd) = -1;
955 		}
956 
957 		if (restore) {
958 			zend_exception_restore();
959 			zend_try {
960 				zend_try_exception_handler();
961 				PHPDBG_G(in_execution) = 1;
962 			} zend_catch {
963 				PHPDBG_G(in_execution) = 0;
964 
965 				if (PHPDBG_G(flags) & PHPDBG_IS_STOPPING) {
966 					zend_bailout();
967 				}
968 			} zend_end_try();
969 
970 			if (EG(exception)) {
971 				phpdbg_handle_exception();
972 			}
973 		}
974 
975 		PHPDBG_G(flags) &= ~PHPDBG_IS_RUNNING;
976 
977 		phpdbg_clean(1, 0);
978 	} else {
979 		phpdbg_error("inactive", "type=\"nocontext\"", "Nothing to execute!");
980 	}
981 
982 out:
983 	PHPDBG_FRAME(num) = 0;
984 	return SUCCESS;
985 } /* }}} */
986 
phpdbg_output_ev_variable(char * name,size_t len,char * keyname,size_t keylen,HashTable * parent,zval * zv)987 int phpdbg_output_ev_variable(char *name, size_t len, char *keyname, size_t keylen, HashTable *parent, zval *zv) /* {{{ */ {
988 	phpdbg_notice("eval", "variable=\"%.*s\"", "Printing variable %.*s", (int) len, name);
989 	phpdbg_xml("<eval %r>");
990 	zend_print_zval_r(zv, 0);
991 	phpdbg_xml("</eval>");
992 	phpdbg_out("\n");
993 
994 	efree(name);
995 	efree(keyname);
996 
997 	return SUCCESS;
998 }
999 /* }}} */
1000 
PHPDBG_COMMAND(ev)1001 PHPDBG_COMMAND(ev) /* {{{ */
1002 {
1003 	zend_bool stepping = ((PHPDBG_G(flags) & PHPDBG_IS_STEPPING) == PHPDBG_IS_STEPPING);
1004 	zval retval;
1005 
1006 	zend_execute_data *original_execute_data = EG(current_execute_data);
1007 	zend_class_entry *original_scope = EG(scope);
1008 	zend_vm_stack original_stack = EG(vm_stack);
1009 	zend_object *ex = NULL;
1010 
1011 	PHPDBG_OUTPUT_BACKUP();
1012 
1013 	original_stack->top = EG(vm_stack_top);
1014 
1015 	if (PHPDBG_G(flags) & PHPDBG_IN_SIGNAL_HANDLER) {
1016 		phpdbg_try_access {
1017 			phpdbg_parse_variable(param->str, param->len, &EG(symbol_table), 0, phpdbg_output_ev_variable, 0);
1018 		} phpdbg_catch_access {
1019 			phpdbg_error("signalsegv", "", "Could not fetch data, invalid data source");
1020 		} phpdbg_end_try_access();
1021 
1022 		PHPDBG_OUTPUT_BACKUP_RESTORE();
1023 		return SUCCESS;
1024 	}
1025 
1026 	if (!(PHPDBG_G(flags) & PHPDBG_IS_STEPONEVAL)) {
1027 		PHPDBG_G(flags) &= ~PHPDBG_IS_STEPPING;
1028 	}
1029 
1030 	/* disable stepping while eval() in progress */
1031 	PHPDBG_G(flags) |= PHPDBG_IN_EVAL;
1032 	zend_try {
1033 		if (zend_eval_stringl(param->str, param->len, &retval, "eval()'d code") == SUCCESS) {
1034 			if (EG(exception)) {
1035 				ex = EG(exception);
1036 				zend_exception_error(EG(exception), E_ERROR);
1037 			} else {
1038 				phpdbg_xml("<eval %r>");
1039 				if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1040 					zval *zvp = &retval;
1041 					phpdbg_xml_var_dump(zvp);
1042 				}
1043 				zend_print_zval_r(&retval, 0);
1044 				phpdbg_xml("</eval>");
1045 				phpdbg_out("\n");
1046 				zval_ptr_dtor(&retval);
1047 			}
1048 		}
1049 	} zend_catch {
1050 		PHPDBG_G(unclean_eval) = 1;
1051 		if (ex) {
1052 			OBJ_RELEASE(ex);
1053 		}
1054 		EG(current_execute_data) = original_execute_data;
1055 		EG(scope) = original_scope;
1056 		EG(vm_stack_top) = original_stack->top;
1057 		EG(vm_stack_end) = original_stack->end;
1058 		EG(vm_stack) = original_stack;
1059 		EG(exit_status) = 0;
1060 	} zend_end_try();
1061 
1062 	PHPDBG_G(flags) &= ~PHPDBG_IN_EVAL;
1063 
1064 	/* switch stepping back on */
1065 	if (stepping && !(PHPDBG_G(flags) & PHPDBG_IS_STEPONEVAL)) {
1066 		PHPDBG_G(flags) |= PHPDBG_IS_STEPPING;
1067 	}
1068 
1069 	CG(unclean_shutdown) = 0;
1070 
1071 	PHPDBG_OUTPUT_BACKUP_RESTORE();
1072 
1073 	return SUCCESS;
1074 } /* }}} */
1075 
PHPDBG_COMMAND(back)1076 PHPDBG_COMMAND(back) /* {{{ */
1077 {
1078 	if (!PHPDBG_G(in_execution)) {
1079 		phpdbg_error("inactive", "type=\"noexec\"", "Not executing!");
1080 		return SUCCESS;
1081 	}
1082 
1083 	if (!param) {
1084 		phpdbg_dump_backtrace(0);
1085 	} else {
1086 		phpdbg_dump_backtrace(param->num);
1087 	}
1088 
1089 	return SUCCESS;
1090 } /* }}} */
1091 
PHPDBG_COMMAND(print)1092 PHPDBG_COMMAND(print) /* {{{ */
1093 {
1094 	if (!param || param->type == EMPTY_PARAM) {
1095 		return phpdbg_do_print_stack(param);
1096 	} else switch (param->type) {
1097 		case STR_PARAM:
1098 			return phpdbg_do_print_func(param);
1099 		case METHOD_PARAM:
1100 			return phpdbg_do_print_method(param);
1101 		default:
1102 			phpdbg_error("print", "type=\"invalidarg\"", "Invalid arguments to print, expected nothing, function name or method name");
1103 			return SUCCESS;
1104 	}
1105 } /* }}} */
1106 
PHPDBG_COMMAND(info)1107 PHPDBG_COMMAND(info) /* {{{ */
1108 {
1109 	phpdbg_out("Execution Context Information\n\n");
1110 	phpdbg_xml("<printinfo %r>");
1111 #ifdef HAVE_LIBREADLINE
1112 	phpdbg_writeln("info", "readline=\"yes\"", "Readline   yes");
1113 #else
1114 	phpdbg_writeln("info", "readline=\"no\"", "Readline   no");
1115 #endif
1116 #ifdef HAVE_LIBEDIT
1117 	phpdbg_writeln("info", "libedit=\"yes\"", "Libedit    yes");
1118 #else
1119 	phpdbg_writeln("info", "libedit=\"no\"", "Libedit    no");
1120 #endif
1121 
1122 	phpdbg_writeln("info", "context=\"%s\"", "Exec       %s", PHPDBG_G(exec) ? PHPDBG_G(exec) : "none");
1123 	phpdbg_writeln("info", "compiled=\"%s\"", "Compiled   %s", PHPDBG_G(ops) ? "yes" : "no");
1124 	phpdbg_writeln("info", "stepping=\"%s\"", "Stepping   %s", (PHPDBG_G(flags) & PHPDBG_IS_STEPPING) ? "on" : "off");
1125 	phpdbg_writeln("info", "quiet=\"%s\"", "Quietness  %s", (PHPDBG_G(flags) & PHPDBG_IS_QUIET) ? "on" : "off");
1126 	phpdbg_writeln("info", "oplog=\"%s\"", "Oplog      %s", PHPDBG_G(oplog) ? "on" : "off");
1127 
1128 	if (PHPDBG_G(ops)) {
1129 		phpdbg_writeln("info", "ops=\"%d\"", "Opcodes    %d", PHPDBG_G(ops)->last);
1130 		phpdbg_writeln("info", "vars=\"%d\"", "Variables  %d", PHPDBG_G(ops)->last_var ? PHPDBG_G(ops)->last_var - 1 : 0);
1131 	}
1132 
1133 	phpdbg_writeln("info", "executing=\"%d\"", "Executing  %s", PHPDBG_G(in_execution) ? "yes" : "no");
1134 	if (PHPDBG_G(in_execution)) {
1135 		phpdbg_writeln("info", "vmret=\"%d\"", "VM Return  %d", PHPDBG_G(vmret));
1136 	}
1137 
1138 	phpdbg_writeln("info", "classes=\"%d\"", "Classes    %d", zend_hash_num_elements(EG(class_table)));
1139 	phpdbg_writeln("info", "functions=\"%d\"", "Functions  %d", zend_hash_num_elements(EG(function_table)));
1140 	phpdbg_writeln("info", "constants=\"%d\"", "Constants  %d", zend_hash_num_elements(EG(zend_constants)));
1141 	phpdbg_writeln("info", "includes=\"%d\"", "Included   %d", zend_hash_num_elements(&EG(included_files)));
1142 	phpdbg_xml("</printinfo>");
1143 
1144 	return SUCCESS;
1145 } /* }}} */
1146 
PHPDBG_COMMAND(set)1147 PHPDBG_COMMAND(set) /* {{{ */
1148 {
1149 	phpdbg_error("set", "type=\"toofewargs\" expected=\"1\"", "No set command selected!");
1150 
1151 	return SUCCESS;
1152 } /* }}} */
1153 
PHPDBG_COMMAND(break)1154 PHPDBG_COMMAND(break) /* {{{ */
1155 {
1156 	if (!param) {
1157 		if (PHPDBG_G(exec)) {
1158 			phpdbg_set_breakpoint_file_ex(
1159 				zend_get_executed_filename(),
1160 				strlen(zend_get_executed_filename()),
1161 				zend_get_executed_lineno());
1162 		} else {
1163 			phpdbg_error("inactive", "type=\"noexec\"", "Execution context not set!");
1164 		}
1165 	} else switch (param->type) {
1166 		case ADDR_PARAM:
1167 			phpdbg_set_breakpoint_opline(param->addr);
1168 			break;
1169 		case NUMERIC_PARAM:
1170 			if (PHPDBG_G(exec)) {
1171 				phpdbg_set_breakpoint_file_ex(phpdbg_current_file(), strlen(phpdbg_current_file()), param->num);
1172 			} else {
1173 				phpdbg_error("inactive", "type=\"noexec\"", "Execution context not set!");
1174 			}
1175 			break;
1176 		case METHOD_PARAM:
1177 			phpdbg_set_breakpoint_method(param->method.class, param->method.name);
1178 			break;
1179 		case NUMERIC_METHOD_PARAM:
1180 			phpdbg_set_breakpoint_method_opline(param->method.class, param->method.name, param->num);
1181 			break;
1182 		case NUMERIC_FUNCTION_PARAM:
1183 			phpdbg_set_breakpoint_function_opline(param->str, param->num);
1184 			break;
1185 		case FILE_PARAM:
1186 			phpdbg_set_breakpoint_file(param->file.name, param->file.line);
1187 			break;
1188 		case NUMERIC_FILE_PARAM:
1189 			phpdbg_set_breakpoint_file_opline(param->file.name, param->file.line);
1190 			break;
1191 		case COND_PARAM:
1192 			phpdbg_set_breakpoint_expression(param->str, param->len);
1193 			break;
1194 		case STR_PARAM:
1195 			phpdbg_set_breakpoint_symbol(param->str, param->len);
1196 			break;
1197 		case OP_PARAM:
1198 			phpdbg_set_breakpoint_opcode(param->str, param->len);
1199 			break;
1200 
1201 		phpdbg_default_switch_case();
1202 	}
1203 
1204 	return SUCCESS;
1205 } /* }}} */
1206 
PHPDBG_COMMAND(sh)1207 PHPDBG_COMMAND(sh) /* {{{ */
1208 {
1209 	FILE *fd = NULL;
1210 	if ((fd=VCWD_POPEN((char*)param->str, "w"))) {
1211 		/* TODO: do something perhaps ?? do we want input ?? */
1212 		pclose(fd);
1213 	} else {
1214 		phpdbg_error("sh", "type=\"failure\" smd=\"%s\"", "Failed to execute %s", param->str);
1215 	}
1216 
1217 	return SUCCESS;
1218 } /* }}} */
1219 
add_module_info(zend_module_entry * module)1220 static int add_module_info(zend_module_entry *module) /* {{{ */ {
1221 	phpdbg_write("module", "name=\"%s\"", "%s\n", module->name);
1222 	return 0;
1223 }
1224 /* }}} */
1225 
add_zendext_info(zend_extension * ext)1226 static int add_zendext_info(zend_extension *ext) /* {{{ */ {
1227 	phpdbg_write("extension", "name=\"%s\"", "%s\n", ext->name);
1228 	return 0;
1229 }
1230 /* }}} */
1231 
1232 #ifdef HAVE_LIBDL
phpdbg_load_module_or_extension(char ** path,char ** name)1233 PHPDBG_API const char *phpdbg_load_module_or_extension(char **path, char **name) /* {{{ */ {
1234 	DL_HANDLE handle;
1235 	char *extension_dir;
1236 
1237 	extension_dir = INI_STR("extension_dir");
1238 
1239 	if (strchr(*path, '/') != NULL || strchr(*path, DEFAULT_SLASH) != NULL) {
1240 		/* path is fine */
1241 	} else if (extension_dir && extension_dir[0]) {
1242 		char *libpath;
1243 		int extension_dir_len = strlen(extension_dir);
1244 		if (IS_SLASH(extension_dir[extension_dir_len-1])) {
1245 			spprintf(&libpath, 0, "%s%s", extension_dir, *path); /* SAFE */
1246 		} else {
1247 			spprintf(&libpath, 0, "%s%c%s", extension_dir, DEFAULT_SLASH, *path); /* SAFE */
1248 		}
1249 		efree(*path);
1250 		*path = libpath;
1251 	} else {
1252 		phpdbg_error("dl", "type=\"relpath\"", "Not a full path given or extension_dir ini setting is not set");
1253 
1254 		return NULL;
1255 	}
1256 
1257 	handle = DL_LOAD(*path);
1258 
1259 	if (!handle) {
1260 #ifdef PHP_WIN32
1261 		char *err = GET_DL_ERROR();
1262 		if (err && err[0]) {
1263 			phpdbg_error("dl", "type=\"unknown\"", "%s", err);
1264 			LocalFree(err);
1265 		} else {
1266 			phpdbg_error("dl", "type=\"unknown\"", "Unknown reason");
1267 		}
1268 #else
1269 		phpdbg_error("dl", "type=\"unknown\"", "%s", GET_DL_ERROR());
1270 #endif
1271 		return NULL;
1272 	}
1273 
1274 #if ZEND_EXTENSIONS_SUPPORT
1275 	do {
1276 		zend_extension *new_extension;
1277 		zend_extension_version_info *extension_version_info;
1278 
1279 		extension_version_info = (zend_extension_version_info *) DL_FETCH_SYMBOL(handle, "extension_version_info");
1280 		if (!extension_version_info) {
1281 			extension_version_info = (zend_extension_version_info *) DL_FETCH_SYMBOL(handle, "_extension_version_info");
1282 		}
1283 		new_extension = (zend_extension *) DL_FETCH_SYMBOL(handle, "zend_extension_entry");
1284 		if (!new_extension) {
1285 			new_extension = (zend_extension *) DL_FETCH_SYMBOL(handle, "_zend_extension_entry");
1286 		}
1287 		if (!extension_version_info || !new_extension) {
1288 			break;
1289 		}
1290 		if (extension_version_info->zend_extension_api_no != ZEND_EXTENSION_API_NO &&(!new_extension->api_no_check || new_extension->api_no_check(ZEND_EXTENSION_API_NO) != SUCCESS)) {
1291 			phpdbg_error("dl", "type=\"wrongapi\" extension=\"%s\" apineeded=\"%d\" apiinstalled=\"%d\"", "%s requires Zend Engine API version %d, which does not match the installed Zend Engine API version %d", new_extension->name, extension_version_info->zend_extension_api_no, ZEND_EXTENSION_API_NO);
1292 
1293 			goto quit;
1294 		} else if (strcmp(ZEND_EXTENSION_BUILD_ID, extension_version_info->build_id) && (!new_extension->build_id_check || new_extension->build_id_check(ZEND_EXTENSION_BUILD_ID) != SUCCESS)) {
1295 			phpdbg_error("dl", "type=\"wrongbuild\" extension=\"%s\" buildneeded=\"%s\" buildinstalled=\"%s\"", "%s was built with configuration %s, whereas running engine is %s", new_extension->name, extension_version_info->build_id, ZEND_EXTENSION_BUILD_ID);
1296 
1297 			goto quit;
1298 		}
1299 
1300 		*name = new_extension->name;
1301 
1302 		zend_register_extension(new_extension, handle);
1303 
1304 		if (new_extension->startup) {
1305 			if (new_extension->startup(new_extension) != SUCCESS) {
1306 				phpdbg_error("dl", "type=\"startupfailure\" extension=\"%s\"", "Unable to startup Zend extension %s", new_extension->name);
1307 
1308 				goto quit;
1309 			}
1310 			zend_append_version_info(new_extension);
1311 		}
1312 
1313 		return "Zend extension";
1314 	} while (0);
1315 #endif
1316 
1317 	do {
1318 		zend_module_entry *module_entry;
1319 		zend_module_entry *(*get_module)(void);
1320 
1321 		get_module = (zend_module_entry *(*)(void)) DL_FETCH_SYMBOL(handle, "get_module");
1322 		if (!get_module) {
1323 			get_module = (zend_module_entry *(*)(void)) DL_FETCH_SYMBOL(handle, "_get_module");
1324 		}
1325 
1326 		if (!get_module) {
1327 			break;
1328 		}
1329 
1330 		module_entry = get_module();
1331 		*name = (char *) module_entry->name;
1332 
1333 		if (strcmp(ZEND_EXTENSION_BUILD_ID, module_entry->build_id)) {
1334 			phpdbg_error("dl", "type=\"wrongbuild\" module=\"%s\" buildneeded=\"%s\" buildinstalled=\"%s\"",  "%s was built with configuration %s, whereas running engine is %s", module_entry->name, module_entry->build_id, ZEND_EXTENSION_BUILD_ID);
1335 
1336 			goto quit;
1337 		}
1338 
1339 		module_entry->type = MODULE_PERSISTENT;
1340 		module_entry->module_number = zend_next_free_module();
1341 		module_entry->handle = handle;
1342 
1343 		if ((module_entry = zend_register_module_ex(module_entry)) == NULL) {
1344 			phpdbg_error("dl", "type=\"registerfailure\" module=\"%s\"", "Unable to register module %s", module_entry->name);
1345 
1346 			goto quit;
1347 		}
1348 
1349 		if (zend_startup_module_ex(module_entry) == FAILURE) {
1350 			phpdbg_error("dl", "type=\"startupfailure\" module=\"%s\"", "Unable to startup module %s", module_entry->name);
1351 
1352 			goto quit;
1353 		}
1354 
1355 		if (module_entry->request_startup_func) {
1356 			if (module_entry->request_startup_func(MODULE_PERSISTENT, module_entry->module_number) == FAILURE) {
1357 				phpdbg_error("dl", "type=\"initfailure\" module=\"%s\"", "Unable to initialize module %s", module_entry->name);
1358 
1359 				goto quit;
1360 			}
1361 		}
1362 
1363 		return "module";
1364 	} while (0);
1365 
1366 	phpdbg_error("dl", "type=\"nophpso\"", "This shared object is nor a Zend extension nor a module");
1367 
1368 quit:
1369 	DL_UNLOAD(handle);
1370 	return NULL;
1371 }
1372 /* }}} */
1373 #endif
1374 
PHPDBG_COMMAND(dl)1375 PHPDBG_COMMAND(dl) /* {{{ */
1376 {
1377 	const char *type;
1378 	char *name, *path;
1379 
1380 	if (!param || param->type == EMPTY_PARAM) {
1381 		phpdbg_notice("dl", "extensiontype=\"Zend extension\"", "Zend extensions");
1382 		zend_llist_apply(&zend_extensions, (llist_apply_func_t) add_zendext_info);
1383 		phpdbg_out("\n");
1384 		phpdbg_notice("dl", "extensiontype=\"module\"", "Modules");
1385 		zend_hash_apply(&module_registry, (apply_func_t) add_module_info);
1386 	} else switch (param->type) {
1387 		case STR_PARAM:
1388 #ifdef HAVE_LIBDL
1389 			path = estrndup(param->str, param->len);
1390 
1391 			phpdbg_activate_err_buf(1);
1392 			if ((type = phpdbg_load_module_or_extension(&path, &name)) == NULL) {
1393 				phpdbg_error("dl", "path=\"%s\" %b", "Could not load %s, not found or invalid zend extension / module: %b", path);
1394 				efree(name);
1395 			} else {
1396 				phpdbg_notice("dl", "extensiontype=\"%s\" name=\"%s\" path=\"%s\"", "Successfully loaded the %s %s at path %s", type, name, path);
1397 			}
1398 			phpdbg_activate_err_buf(0);
1399 			phpdbg_free_err_buf();
1400 			efree(path);
1401 #else
1402 			phpdbg_error("dl", "type=\"unsupported\" path=\"%.*s\"", "Cannot dynamically load %.*s - dynamic modules are not supported", (int) param->len, param->str);
1403 #endif
1404 			break;
1405 
1406 		phpdbg_default_switch_case();
1407 	}
1408 
1409 	return SUCCESS;
1410 } /* }}} */
1411 
PHPDBG_COMMAND(source)1412 PHPDBG_COMMAND(source) /* {{{ */
1413 {
1414 	zend_stat_t sb;
1415 
1416 	if (VCWD_STAT(param->str, &sb) != -1) {
1417 		phpdbg_try_file_init(param->str, param->len, 0);
1418 	} else {
1419 		phpdbg_error("source", "type=\"notfound\" file=\"%s\"", "Failed to stat %s, file does not exist", param->str);
1420 	}
1421 
1422 	return SUCCESS;
1423 } /* }}} */
1424 
PHPDBG_COMMAND(export)1425 PHPDBG_COMMAND(export) /* {{{ */
1426 {
1427 	FILE *handle = VCWD_FOPEN(param->str, "w+");
1428 
1429 	if (handle) {
1430 		phpdbg_export_breakpoints(handle);
1431 		fclose(handle);
1432 	} else {
1433 		phpdbg_error("export", "type=\"openfailure\" file=\"%s\"", "Failed to open or create %s, check path and permissions", param->str);
1434 	}
1435 
1436 	return SUCCESS;
1437 } /* }}} */
1438 
PHPDBG_COMMAND(register)1439 PHPDBG_COMMAND(register) /* {{{ */
1440 {
1441 	zend_function *function;
1442 	char *lcname = zend_str_tolower_dup(param->str, param->len);
1443 	size_t lcname_len = strlen(lcname);
1444 
1445 	if (!zend_hash_str_exists(&PHPDBG_G(registered), lcname, lcname_len)) {
1446 		if ((function = zend_hash_str_find_ptr(EG(function_table), lcname, lcname_len))) {
1447 			zend_hash_str_update_ptr(&PHPDBG_G(registered), lcname, lcname_len, function);
1448 			function_add_ref(function);
1449 
1450 			phpdbg_notice("register", "function=\"%s\"", "Registered %s", lcname);
1451 		} else {
1452 			phpdbg_error("register", "type=\"notfound\" function=\"%s\"", "The requested function (%s) could not be found", param->str);
1453 		}
1454 	} else {
1455 		phpdbg_error("register", "type=\"inuse\" function=\"%s\"", "The requested name (%s) is already in use", lcname);
1456 	}
1457 
1458 	efree(lcname);
1459 	return SUCCESS;
1460 } /* }}} */
1461 
PHPDBG_COMMAND(quit)1462 PHPDBG_COMMAND(quit) /* {{{ */
1463 {
1464 	PHPDBG_G(flags) |= PHPDBG_IS_QUITTING;
1465 	PHPDBG_G(flags) &= ~PHPDBG_IS_CLEANING;
1466 
1467 	return SUCCESS;
1468 } /* }}} */
1469 
PHPDBG_COMMAND(clean)1470 PHPDBG_COMMAND(clean) /* {{{ */
1471 {
1472 	if (PHPDBG_G(in_execution)) {
1473 		if (phpdbg_ask_user_permission("Do you really want to clean your current environment?") == FAILURE) {
1474 			return SUCCESS;
1475 		}
1476 	}
1477 
1478 	phpdbg_out("Cleaning Execution Environment\n");
1479 	phpdbg_xml("<cleaninfo %r>");
1480 
1481 	phpdbg_writeln("clean", "classes=\"%d\"", "Classes    %d", zend_hash_num_elements(EG(class_table)));
1482 	phpdbg_writeln("clean", "functions=\"%d\"", "Functions  %d", zend_hash_num_elements(EG(function_table)));
1483 	phpdbg_writeln("clean", "constants=\"%d\"", "Constants  %d", zend_hash_num_elements(EG(zend_constants)));
1484 	phpdbg_writeln("clean", "includes=\"%d\"", "Includes   %d", zend_hash_num_elements(&EG(included_files)));
1485 
1486 	phpdbg_clean(1, 0);
1487 
1488 	phpdbg_xml("</cleaninfo>");
1489 
1490 	return SUCCESS;
1491 } /* }}} */
1492 
PHPDBG_COMMAND(clear)1493 PHPDBG_COMMAND(clear) /* {{{ */
1494 {
1495 	phpdbg_out("Clearing Breakpoints\n");
1496 	phpdbg_xml("<clearinfo %r>");
1497 
1498 	phpdbg_writeln("clear", "files=\"%d\"", "File              %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_FILE]));
1499 	phpdbg_writeln("clear", "functions=\"%d\"", "Functions         %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_SYM]));
1500 	phpdbg_writeln("clear", "methods=\"%d\"", "Methods           %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_METHOD]));
1501 	phpdbg_writeln("clear", "oplines=\"%d\"", "Oplines           %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_OPLINE]));
1502 	phpdbg_writeln("clear", "fileoplines=\"%d\"", "File oplines      %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_FILE_OPLINE]));
1503 	phpdbg_writeln("clear", "functionoplines=\"%d\"", "Function oplines  %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_FUNCTION_OPLINE]));
1504 	phpdbg_writeln("clear", "methodoplines=\"%d\"", "Method oplines    %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_METHOD_OPLINE]));
1505 	phpdbg_writeln("clear", "eval=\"%d\"", "Conditionals      %d", zend_hash_num_elements(&PHPDBG_G(bp)[PHPDBG_BREAK_COND]));
1506 
1507 	phpdbg_clear_breakpoints();
1508 
1509 	phpdbg_xml("</clearinfo>");
1510 
1511 	return SUCCESS;
1512 } /* }}} */
1513 
PHPDBG_COMMAND(list)1514 PHPDBG_COMMAND(list) /* {{{ */
1515 {
1516 	if (!param) {
1517 		return PHPDBG_LIST_HANDLER(lines)(PHPDBG_COMMAND_ARGS);
1518 	} else switch (param->type) {
1519 		case NUMERIC_PARAM:
1520 			return PHPDBG_LIST_HANDLER(lines)(PHPDBG_COMMAND_ARGS);
1521 
1522 		case FILE_PARAM:
1523 			return PHPDBG_LIST_HANDLER(lines)(PHPDBG_COMMAND_ARGS);
1524 
1525 		case STR_PARAM:
1526 			phpdbg_list_function_byname(param->str, param->len);
1527 			break;
1528 
1529 		case METHOD_PARAM:
1530 			return PHPDBG_LIST_HANDLER(method)(PHPDBG_COMMAND_ARGS);
1531 
1532 		phpdbg_default_switch_case();
1533 	}
1534 
1535 	return SUCCESS;
1536 } /* }}} */
1537 
PHPDBG_COMMAND(watch)1538 PHPDBG_COMMAND(watch) /* {{{ */
1539 {
1540 	if (!param || param->type == EMPTY_PARAM) {
1541 		phpdbg_list_watchpoints();
1542 	} else switch (param->type) {
1543 		case STR_PARAM:
1544 			if (phpdbg_create_var_watchpoint(param->str, param->len) != FAILURE) {
1545 				phpdbg_notice("watch", "variable=\"%.*s\"", "Set watchpoint on %.*s", (int) param->len, param->str);
1546 			}
1547 			break;
1548 
1549 		phpdbg_default_switch_case();
1550 	}
1551 
1552 	return SUCCESS;
1553 } /* }}} */
1554 
phpdbg_interactive(zend_bool allow_async_unsafe,char * input)1555 int phpdbg_interactive(zend_bool allow_async_unsafe, char *input) /* {{{ */
1556 {
1557 	int ret = SUCCESS;
1558 	phpdbg_param_t stack;
1559 
1560 	PHPDBG_G(flags) |= PHPDBG_IS_INTERACTIVE;
1561 
1562 	while (ret == SUCCESS || ret == FAILURE) {
1563 		if (PHPDBG_G(flags) & PHPDBG_IS_STOPPING) {
1564 			zend_bailout();
1565 		}
1566 
1567 		if (!input && !(input = phpdbg_read_input(NULL))) {
1568 			break;
1569 		}
1570 
1571 
1572 		phpdbg_init_param(&stack, STACK_PARAM);
1573 
1574 		if (phpdbg_do_parse(&stack, input) <= 0) {
1575 			phpdbg_activate_err_buf(1);
1576 
1577 #ifdef PHP_WIN32
1578 #define PARA ((phpdbg_param_t *)stack.next)->type
1579 			if (PHPDBG_G(flags) & PHPDBG_IS_REMOTE && (RUN_PARAM == PARA || EVAL_PARAM == PARA)) {
1580 				sigio_watcher_start();
1581 			}
1582 #endif
1583 			switch (ret = phpdbg_stack_execute(&stack, allow_async_unsafe)) {
1584 				case FAILURE:
1585 					if (!(PHPDBG_G(flags) & PHPDBG_IS_STOPPING)) {
1586 						if (!allow_async_unsafe || phpdbg_call_register(&stack) == FAILURE) {
1587 							phpdbg_output_err_buf(NULL, "%b", "%b");
1588 						}
1589 					}
1590 				break;
1591 
1592 				case PHPDBG_LEAVE:
1593 				case PHPDBG_FINISH:
1594 				case PHPDBG_UNTIL:
1595 				case PHPDBG_NEXT: {
1596 					phpdbg_activate_err_buf(0);
1597 					phpdbg_free_err_buf();
1598 					if (!PHPDBG_G(in_execution) && !(PHPDBG_G(flags) & PHPDBG_IS_STOPPING)) {
1599 						phpdbg_error("command", "type=\"noexec\"", "Not running");
1600 					}
1601 					break;
1602 				}
1603 			}
1604 
1605 			phpdbg_activate_err_buf(0);
1606 			phpdbg_free_err_buf();
1607 #ifdef PHP_WIN32
1608 			if (PHPDBG_G(flags) & PHPDBG_IS_REMOTE && (RUN_PARAM == PARA || EVAL_PARAM == PARA)) {
1609 				sigio_watcher_stop();
1610 			}
1611 #undef PARA
1612 #endif
1613 		}
1614 
1615 		phpdbg_stack_free(&stack);
1616 		phpdbg_destroy_input(&input);
1617 		PHPDBG_G(req_id) = 0;
1618 		input = NULL;
1619 	}
1620 
1621 	if (input) {
1622 		phpdbg_stack_free(&stack);
1623 		phpdbg_destroy_input(&input);
1624 		PHPDBG_G(req_id) = 0;
1625 	}
1626 
1627 	if (PHPDBG_G(in_execution)) {
1628 		phpdbg_restore_frame();
1629 	}
1630 
1631 	PHPDBG_G(flags) &= ~PHPDBG_IS_INTERACTIVE;
1632 
1633 	phpdbg_print_changed_zvals();
1634 
1635 	return ret;
1636 } /* }}} */
1637 
1638 /* code may behave weirdly if EG(exception) is set; thus backup it */
1639 #define DO_INTERACTIVE(allow_async_unsafe) do { \
1640 	const zend_op *backup_opline; \
1641 	const zend_op *before_ex; \
1642 	if (exception) { \
1643 		if (EG(current_execute_data) && EG(current_execute_data)->func && ZEND_USER_CODE(EG(current_execute_data)->func->common.type)) { \
1644 			backup_opline = EG(current_execute_data)->opline; \
1645 		} \
1646 		before_ex = EG(opline_before_exception); \
1647 		++GC_REFCOUNT(exception); \
1648 		zend_clear_exception(); \
1649 	} \
1650 	if (!(PHPDBG_G(flags) & PHPDBG_IN_EVAL)) { \
1651 		const char *file_char = zend_get_executed_filename(); \
1652 		zend_string *file = zend_string_init(file_char, strlen(file_char), 0); \
1653 		phpdbg_list_file(file, 3, zend_get_executed_lineno()-1, zend_get_executed_lineno()); \
1654 		efree(file); \
1655 	} \
1656 	\
1657 	switch (phpdbg_interactive(allow_async_unsafe, NULL)) { \
1658 		zval zv; \
1659 		case PHPDBG_LEAVE: \
1660 		case PHPDBG_FINISH: \
1661 		case PHPDBG_UNTIL: \
1662 		case PHPDBG_NEXT: \
1663 			if (exception) { \
1664 				if (EG(current_execute_data) && EG(current_execute_data)->func && ZEND_USER_CODE(EG(current_execute_data)->func->common.type) \
1665 				 && (backup_opline->opcode == ZEND_HANDLE_EXCEPTION || backup_opline->opcode == ZEND_CATCH)) { \
1666 					EG(current_execute_data)->opline = backup_opline; \
1667 					EG(exception) = exception; \
1668 				} else { \
1669 					Z_OBJ(zv) = exception; \
1670 					zend_throw_exception_internal(&zv); \
1671 				} \
1672 				EG(opline_before_exception) = before_ex; \
1673 			} \
1674 			/* fallthrough */ \
1675 		default: \
1676 			goto next; \
1677 	} \
1678 } while (0)
1679 
phpdbg_execute_ex(zend_execute_data * execute_data)1680 void phpdbg_execute_ex(zend_execute_data *execute_data) /* {{{ */
1681 {
1682 	zend_bool original_in_execution = PHPDBG_G(in_execution);
1683 
1684 	if ((PHPDBG_G(flags) & PHPDBG_IS_STOPPING) && !(PHPDBG_G(flags) & PHPDBG_IS_RUNNING)) {
1685 		zend_bailout();
1686 	}
1687 
1688 	PHPDBG_G(in_execution) = 1;
1689 
1690 	while (1) {
1691 		zend_object *exception = EG(exception);
1692 
1693 		if ((PHPDBG_G(flags) & PHPDBG_BP_RESOLVE_MASK)) {
1694 			/* resolve nth opline breakpoints */
1695 			phpdbg_resolve_op_array_breaks(&execute_data->func->op_array);
1696 		}
1697 
1698 #ifdef ZEND_WIN32
1699 		if (EG(timed_out)) {
1700 			zend_timeout(0);
1701 		}
1702 #endif
1703 
1704 		if (PHPDBG_G(flags) & PHPDBG_PREVENT_INTERACTIVE) {
1705 			phpdbg_print_opline_ex(execute_data, 0);
1706 			goto next;
1707 		}
1708 
1709 		/* check for uncaught exceptions */
1710 		if (exception && PHPDBG_G(handled_exception) != exception && !(PHPDBG_G(flags) & PHPDBG_IN_EVAL)) {
1711 			zend_execute_data *prev_ex = execute_data;
1712 			zval zv, rv;
1713 			zend_string *file, *msg;
1714 			zend_long line;
1715 
1716 			do {
1717 				prev_ex = zend_generator_check_placeholder_frame(prev_ex);
1718 				/* assuming that no internal functions will silently swallow exceptions ... */
1719 				if (!prev_ex->func || !ZEND_USER_CODE(prev_ex->func->common.type)) {
1720 					continue;
1721 				}
1722 
1723 				if (phpdbg_check_caught_ex(prev_ex, exception)) {
1724 					goto ex_is_caught;
1725 				}
1726 			} while ((prev_ex = prev_ex->prev_execute_data));
1727 
1728 			PHPDBG_G(handled_exception) = exception;
1729 
1730 			ZVAL_OBJ(&zv, exception);
1731 			file = zval_get_string(zend_read_property(zend_get_exception_base(&zv), &zv, ZEND_STRL("file"), 1, &rv));
1732 			line = zval_get_long(zend_read_property(zend_get_exception_base(&zv), &zv, ZEND_STRL("line"), 1, &rv));
1733 			msg = zval_get_string(zend_read_property(zend_get_exception_base(&zv), &zv, ZEND_STRL("message"), 1, &rv));
1734 
1735 			phpdbg_error("exception",
1736 				"name=\"%s\" file=\"%s\" line=\"" ZEND_LONG_FMT "\"",
1737 				"Uncaught %s in %s on line " ZEND_LONG_FMT ": %.*s",
1738 				ZSTR_VAL(exception->ce->name), ZSTR_VAL(file), line,
1739 				ZSTR_LEN(msg) < 80 ? (int) ZSTR_LEN(msg) : 80, ZSTR_VAL(msg));
1740 			zend_string_release(msg);
1741 			zend_string_release(file);
1742 
1743 			DO_INTERACTIVE(1);
1744 		}
1745 ex_is_caught:
1746 
1747 		/* allow conditional breakpoints and initialization to access the vm uninterrupted */
1748 		if (PHPDBG_G(flags) & (PHPDBG_IN_COND_BP | PHPDBG_IS_INITIALIZING)) {
1749 			/* skip possible breakpoints */
1750 			goto next;
1751 		}
1752 
1753 		/* not while in conditionals */
1754 		phpdbg_print_opline_ex(execute_data, 0);
1755 
1756 		/* perform seek operation */
1757 		if ((PHPDBG_G(flags) & PHPDBG_SEEK_MASK) && !(PHPDBG_G(flags) & PHPDBG_IN_EVAL)) {
1758 			/* current address */
1759 			zend_ulong address = (zend_ulong) execute_data->opline;
1760 
1761 			if (PHPDBG_G(seek_ex) != execute_data) {
1762 				if (PHPDBG_G(flags) & PHPDBG_IS_STEPPING) {
1763 					goto stepping;
1764 				}
1765 				goto next;
1766 			}
1767 
1768 #define INDEX_EXISTS_CHECK (zend_hash_index_exists(&PHPDBG_G(seek), address) || (exception && phpdbg_check_caught_ex(execute_data, exception) == 0))
1769 
1770 			/* run to next line */
1771 			if (PHPDBG_G(flags) & PHPDBG_IN_UNTIL) {
1772 				if (INDEX_EXISTS_CHECK) {
1773 					PHPDBG_G(flags) &= ~PHPDBG_IN_UNTIL;
1774 					zend_hash_clean(&PHPDBG_G(seek));
1775 				} else {
1776 					/* skip possible breakpoints */
1777 					goto next;
1778 				}
1779 			}
1780 
1781 			/* run to finish */
1782 			if (PHPDBG_G(flags) & PHPDBG_IN_FINISH) {
1783 				if (INDEX_EXISTS_CHECK) {
1784 					PHPDBG_G(flags) &= ~PHPDBG_IN_FINISH;
1785 					zend_hash_clean(&PHPDBG_G(seek));
1786 				}
1787 				/* skip possible breakpoints */
1788 				goto next;
1789 			}
1790 
1791 			/* break for leave */
1792 			if (PHPDBG_G(flags) & PHPDBG_IN_LEAVE) {
1793 				if (INDEX_EXISTS_CHECK) {
1794 					PHPDBG_G(flags) &= ~PHPDBG_IN_LEAVE;
1795 					zend_hash_clean(&PHPDBG_G(seek));
1796 					phpdbg_notice("breakpoint", "id=\"leave\" file=\"%s\" line=\"%u\"", "Breaking for leave at %s:%u",
1797 						zend_get_executed_filename(),
1798 						zend_get_executed_lineno()
1799 					);
1800 					DO_INTERACTIVE(1);
1801 				} else {
1802 					/* skip possible breakpoints */
1803 					goto next;
1804 				}
1805 			}
1806 		}
1807 
1808 		if (PHPDBG_G(flags) & PHPDBG_IS_STEPPING && (PHPDBG_G(flags) & PHPDBG_STEP_OPCODE || execute_data->opline->lineno != PHPDBG_G(last_line))) {
1809 stepping:
1810 			PHPDBG_G(flags) &= ~PHPDBG_IS_STEPPING;
1811 			DO_INTERACTIVE(1);
1812 		}
1813 
1814 		/* check if some watchpoint was hit */
1815 		{
1816 			if (phpdbg_print_changed_zvals() == SUCCESS) {
1817 				DO_INTERACTIVE(1);
1818 			}
1819 		}
1820 
1821 		/* search for breakpoints */
1822 		{
1823 			phpdbg_breakbase_t *brake;
1824 
1825 			if ((PHPDBG_G(flags) & PHPDBG_BP_MASK)
1826 			    && (brake = phpdbg_find_breakpoint(execute_data))
1827 			    && (brake->type != PHPDBG_BREAK_FILE || execute_data->opline->lineno != PHPDBG_G(last_line))) {
1828 				phpdbg_hit_breakpoint(brake, 1);
1829 				DO_INTERACTIVE(1);
1830 			}
1831 		}
1832 
1833 		if (PHPDBG_G(flags) & PHPDBG_IS_SIGNALED) {
1834 			PHPDBG_G(flags) &= ~PHPDBG_IS_SIGNALED;
1835 
1836 			phpdbg_out("\n");
1837 			phpdbg_notice("signal", "type=\"SIGINT\"", "Program received signal SIGINT");
1838 			DO_INTERACTIVE(1);
1839 		}
1840 
1841 next:
1842 
1843 		PHPDBG_G(last_line) = execute_data->opline->lineno;
1844 
1845 		/* stupid hack to make zend_do_fcall_common_helper return ZEND_VM_ENTER() instead of recursively calling zend_execute() and eventually segfaulting */
1846 		if ((execute_data->opline->opcode == ZEND_DO_FCALL ||
1847 		     execute_data->opline->opcode == ZEND_DO_UCALL ||
1848 		     execute_data->opline->opcode == ZEND_DO_FCALL_BY_NAME) &&
1849 		     execute_data->call->func->type == ZEND_USER_FUNCTION) {
1850 			zend_execute_ex = execute_ex;
1851 		}
1852 		PHPDBG_G(vmret) = zend_vm_call_opcode_handler(execute_data);
1853 		zend_execute_ex = phpdbg_execute_ex;
1854 
1855 		if (PHPDBG_G(vmret) != 0) {
1856 			if (PHPDBG_G(vmret) < 0) {
1857 				PHPDBG_G(in_execution) = original_in_execution;
1858 				return;
1859 			} else {
1860 				execute_data = EG(current_execute_data);
1861 			}
1862 		}
1863 	}
1864 	zend_error_noreturn(E_ERROR, "Arrived at end of main loop which shouldn't happen");
1865 } /* }}} */
1866 
1867 /* only if *not* interactive and while executing */
phpdbg_force_interruption(void)1868 void phpdbg_force_interruption(void) /* {{{ */ {
1869 	zend_object *exception = EG(exception);
1870 	zend_execute_data *data = EG(current_execute_data); /* should be always readable if not NULL */
1871 
1872 	PHPDBG_G(flags) |= PHPDBG_IN_SIGNAL_HANDLER;
1873 
1874 	if (data) {
1875 		if (data->func) {
1876 			if (ZEND_USER_CODE(data->func->type)) {
1877 				phpdbg_notice("hardinterrupt", "opline=\"%p\" num=\"%lu\" file=\"%s\" line=\"%u\"", "Current opline: %p (op #%lu) in %s:%u", data->opline, (data->opline - data->func->op_array.opcodes) / sizeof(data->opline), data->func->op_array.filename->val, data->opline->lineno);
1878 			} else if (data->func->internal_function.function_name) {
1879 				phpdbg_notice("hardinterrupt", "func=\"%s\"", "Current opline: in internal function %s", data->func->internal_function.function_name->val);
1880 			} else {
1881 				phpdbg_notice("hardinterrupt", "", "Current opline: executing internal code");
1882 			}
1883 		} else {
1884 			phpdbg_notice("hardinterrupt", "opline=\"%p\"", "Current opline: %p (op_array information unavailable)", data->opline);
1885 		}
1886 	} else {
1887 		phpdbg_notice("hardinterrupt", "", "No information available about executing context");
1888 	}
1889 
1890 	DO_INTERACTIVE(0);
1891 
1892 next:
1893 	PHPDBG_G(flags) &= ~PHPDBG_IN_SIGNAL_HANDLER;
1894 
1895 	if (PHPDBG_G(flags) & PHPDBG_IS_STOPPING) {
1896 		zend_bailout();
1897 	}
1898 }
1899 /* }}} */
1900 
PHPDBG_COMMAND(eol)1901 PHPDBG_COMMAND(eol) /* {{{ */
1902 {
1903 	if (!param || param->type == EMPTY_PARAM) {
1904 		phpdbg_notice("eol", "argument required", "argument required");
1905 	} else switch (param->type) {
1906 		case STR_PARAM:
1907 			if (FAILURE == phpdbg_eol_global_update(param->str)) {
1908 				phpdbg_notice("eol", "unknown EOL name '%s', give crlf, lf, cr", "unknown EOL name '%s', give  crlf, lf, cr", param->str);
1909 			}
1910 			break;
1911 
1912 		phpdbg_default_switch_case();
1913 	}
1914 
1915 	return SUCCESS;
1916 } /* }}} */
1917