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