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