xref: /PHP-5.3/sapi/cli/php_cli.c (revision babeca35)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 5                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2013 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    | Author: Edin Kadribasic <edink@php.net>                              |
16    |         Marcus Boerger <helly@php.net>                               |
17    |         Johannes Schlueter <johannes@php.net>                        |
18    |         Parts based on CGI SAPI Module by                            |
19    |         Rasmus Lerdorf, Stig Bakken and Zeev Suraski                 |
20    +----------------------------------------------------------------------+
21 */
22 
23 /* $Id$ */
24 
25 #include "php.h"
26 #include "php_globals.h"
27 #include "php_variables.h"
28 #include "zend_hash.h"
29 #include "zend_modules.h"
30 #include "zend_interfaces.h"
31 
32 #include "ext/reflection/php_reflection.h"
33 
34 #include "SAPI.h"
35 
36 #include <stdio.h>
37 #include "php.h"
38 #ifdef PHP_WIN32
39 #include "win32/time.h"
40 #include "win32/signal.h"
41 #include <process.h>
42 #endif
43 #if HAVE_SYS_TIME_H
44 #include <sys/time.h>
45 #endif
46 #if HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49 #if HAVE_SIGNAL_H
50 #include <signal.h>
51 #endif
52 #if HAVE_SETLOCALE
53 #include <locale.h>
54 #endif
55 #include "zend.h"
56 #include "zend_extensions.h"
57 #include "php_ini.h"
58 #include "php_globals.h"
59 #include "php_main.h"
60 #include "fopen_wrappers.h"
61 #include "ext/standard/php_standard.h"
62 #ifdef PHP_WIN32
63 #include <io.h>
64 #include <fcntl.h>
65 #include "win32/php_registry.h"
66 #endif
67 
68 #if HAVE_SIGNAL_H
69 #include <signal.h>
70 #endif
71 
72 #ifdef __riscos__
73 #include <unixlib/local.h>
74 #endif
75 
76 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
77 #if HAVE_LIBEDIT
78 #include <editline/readline.h>
79 #else
80 #include <readline/readline.h>
81 #include <readline/history.h>
82 #endif
83 #include "php_cli_readline.h"
84 #endif /* HAVE_LIBREADLINE || HAVE_LIBEDIT */
85 
86 #include "zend_compile.h"
87 #include "zend_execute.h"
88 #include "zend_highlight.h"
89 #include "zend_indent.h"
90 #include "zend_exceptions.h"
91 
92 #include "php_getopt.h"
93 
94 #ifndef PHP_WIN32
95 # define php_select(m, r, w, e, t)	select(m, r, w, e, t)
96 #else
97 # include "win32/select.h"
98 #endif
99 
100 PHPAPI extern char *php_ini_opened_path;
101 PHPAPI extern char *php_ini_scanned_path;
102 PHPAPI extern char *php_ini_scanned_files;
103 
104 #ifndef O_BINARY
105 #define O_BINARY 0
106 #endif
107 
108 #define PHP_MODE_STANDARD      1
109 #define PHP_MODE_HIGHLIGHT     2
110 #define PHP_MODE_INDENT        3
111 #define PHP_MODE_LINT          4
112 #define PHP_MODE_STRIP         5
113 #define PHP_MODE_CLI_DIRECT    6
114 #define PHP_MODE_PROCESS_STDIN 7
115 #define PHP_MODE_REFLECTION_FUNCTION    8
116 #define PHP_MODE_REFLECTION_CLASS       9
117 #define PHP_MODE_REFLECTION_EXTENSION   10
118 #define PHP_MODE_REFLECTION_EXT_INFO    11
119 #define PHP_MODE_SHOW_INI_CONFIG        12
120 
121 const char HARDCODED_INI[] =
122 	"html_errors=0\n"
123 	"register_argc_argv=1\n"
124 	"implicit_flush=1\n"
125 	"output_buffering=0\n"
126 	"max_execution_time=0\n"
127 	"max_input_time=-1\n\0";
128 
129 static char *php_optarg = NULL;
130 static int php_optind = 1;
131 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
132 static char php_last_char = '\0';
133 #endif
134 
135 static const opt_struct OPTIONS[] = {
136 	{'a', 0, "interactive"},
137 	{'B', 1, "process-begin"},
138 	{'C', 0, "no-chdir"}, /* for compatibility with CGI (do not chdir to script directory) */
139 	{'c', 1, "php-ini"},
140 	{'d', 1, "define"},
141 	{'E', 1, "process-end"},
142 	{'e', 0, "profile-info"},
143 	{'F', 1, "process-file"},
144 	{'f', 1, "file"},
145 	{'h', 0, "help"},
146 	{'i', 0, "info"},
147 	{'l', 0, "syntax-check"},
148 	{'m', 0, "modules"},
149 	{'n', 0, "no-php-ini"},
150 	{'q', 0, "no-header"}, /* for compatibility with CGI (do not generate HTTP headers) */
151 	{'R', 1, "process-code"},
152 	{'H', 0, "hide-args"},
153 	{'r', 1, "run"},
154 	{'s', 0, "syntax-highlight"},
155 	{'s', 0, "syntax-highlighting"},
156 	{'w', 0, "strip"},
157 	{'?', 0, "usage"},/* help alias (both '?' and 'usage') */
158 	{'v', 0, "version"},
159 	{'z', 1, "zend-extension"},
160 	{10,  1, "rf"},
161 	{10,  1, "rfunction"},
162 	{11,  1, "rc"},
163 	{11,  1, "rclass"},
164 	{12,  1, "re"},
165 	{12,  1, "rextension"},
166 	{13,  1, "ri"},
167 	{13,  1, "rextinfo"},
168 	{14,  0, "ini"},
169 	{'-', 0, NULL} /* end of args */
170 };
171 
print_module_info(zend_module_entry * module TSRMLS_DC)172 static int print_module_info(zend_module_entry *module TSRMLS_DC) /* {{{ */
173 {
174 	php_printf("%s\n", module->name);
175 	return ZEND_HASH_APPLY_KEEP;
176 }
177 /* }}} */
178 
module_name_cmp(const void * a,const void * b TSRMLS_DC)179 static int module_name_cmp(const void *a, const void *b TSRMLS_DC) /* {{{ */
180 {
181 	Bucket *f = *((Bucket **) a);
182 	Bucket *s = *((Bucket **) b);
183 
184 	return strcasecmp(((zend_module_entry *)f->pData)->name,
185 				  ((zend_module_entry *)s->pData)->name);
186 }
187 /* }}} */
188 
print_modules(TSRMLS_D)189 static void print_modules(TSRMLS_D) /* {{{ */
190 {
191 	HashTable sorted_registry;
192 	zend_module_entry tmp;
193 
194 	zend_hash_init(&sorted_registry, 50, NULL, NULL, 1);
195 	zend_hash_copy(&sorted_registry, &module_registry, NULL, &tmp, sizeof(zend_module_entry));
196 	zend_hash_sort(&sorted_registry, zend_qsort, module_name_cmp, 0 TSRMLS_CC);
197 	zend_hash_apply(&sorted_registry, (apply_func_t) print_module_info TSRMLS_CC);
198 	zend_hash_destroy(&sorted_registry);
199 }
200 /* }}} */
201 
print_extension_info(zend_extension * ext,void * arg TSRMLS_DC)202 static int print_extension_info(zend_extension *ext, void *arg TSRMLS_DC) /* {{{ */
203 {
204 	php_printf("%s\n", ext->name);
205 	return ZEND_HASH_APPLY_KEEP;
206 }
207 /* }}} */
208 
extension_name_cmp(const zend_llist_element ** f,const zend_llist_element ** s TSRMLS_DC)209 static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s TSRMLS_DC) /* {{{ */
210 {
211 	return strcmp(((zend_extension *)(*f)->data)->name,
212 				  ((zend_extension *)(*s)->data)->name);
213 }
214 /* }}} */
215 
print_extensions(TSRMLS_D)216 static void print_extensions(TSRMLS_D) /* {{{ */
217 {
218 	zend_llist sorted_exts;
219 
220 	zend_llist_copy(&sorted_exts, &zend_extensions);
221 	sorted_exts.dtor = NULL;
222 	zend_llist_sort(&sorted_exts, extension_name_cmp TSRMLS_CC);
223 	zend_llist_apply(&sorted_exts, (llist_apply_func_t) print_extension_info TSRMLS_CC);
224 	zend_llist_destroy(&sorted_exts);
225 }
226 /* }}} */
227 
228 #ifndef STDOUT_FILENO
229 #define STDOUT_FILENO 1
230 #endif
231 
sapi_cli_select(int fd TSRMLS_DC)232 static inline int sapi_cli_select(int fd TSRMLS_DC)
233 {
234 	fd_set wfd, dfd;
235 	struct timeval tv;
236 	int ret;
237 
238 	FD_ZERO(&wfd);
239 	FD_ZERO(&dfd);
240 
241 	PHP_SAFE_FD_SET(fd, &wfd);
242 
243 	tv.tv_sec = FG(default_socket_timeout);
244 	tv.tv_usec = 0;
245 
246 	ret = php_select(fd+1, &dfd, &wfd, &dfd, &tv);
247 
248 	return ret != -1;
249 }
250 
sapi_cli_single_write(const char * str,uint str_length TSRMLS_DC)251 static inline size_t sapi_cli_single_write(const char *str, uint str_length TSRMLS_DC) /* {{{ */
252 {
253 #ifdef PHP_WRITE_STDOUT
254 	long ret;
255 
256 	do {
257 		ret = write(STDOUT_FILENO, str, str_length);
258 	} while (ret <= 0 && errno == EAGAIN && sapi_cli_select(STDOUT_FILENO TSRMLS_CC));
259 
260 	if (ret <= 0) {
261 		return 0;
262 	}
263 
264 	return ret;
265 #else
266 	size_t ret;
267 
268 	ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
269 	return ret;
270 #endif
271 }
272 /* }}} */
273 
sapi_cli_ub_write(const char * str,uint str_length TSRMLS_DC)274 static int sapi_cli_ub_write(const char *str, uint str_length TSRMLS_DC) /* {{{ */
275 {
276 	const char *ptr = str;
277 	uint remaining = str_length;
278 	size_t ret;
279 
280 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
281 	if (!str_length) {
282 		return 0;
283 	}
284 	php_last_char = str[str_length-1];
285 #endif
286 
287 	while (remaining > 0)
288 	{
289 		ret = sapi_cli_single_write(ptr, remaining TSRMLS_CC);
290 		if (!ret) {
291 #ifndef PHP_CLI_WIN32_NO_CONSOLE
292 			php_handle_aborted_connection();
293 #endif
294 			break;
295 		}
296 		ptr += ret;
297 		remaining -= ret;
298 	}
299 
300 	return (ptr - str);
301 }
302 /* }}} */
303 
sapi_cli_flush(void * server_context)304 static void sapi_cli_flush(void *server_context) /* {{{ */
305 {
306 	/* Ignore EBADF here, it's caused by the fact that STDIN/STDOUT/STDERR streams
307 	 * are/could be closed before fflush() is called.
308 	 */
309 	if (fflush(stdout)==EOF && errno!=EBADF) {
310 #ifndef PHP_CLI_WIN32_NO_CONSOLE
311 		php_handle_aborted_connection();
312 #endif
313 	}
314 }
315 /* }}} */
316 
317 static char *php_self = "";
318 static char *script_filename = "";
319 
sapi_cli_register_variables(zval * track_vars_array TSRMLS_DC)320 static void sapi_cli_register_variables(zval *track_vars_array TSRMLS_DC) /* {{{ */
321 {
322 	unsigned int len;
323 	char   *docroot = "";
324 
325 	/* In CGI mode, we consider the environment to be a part of the server
326 	 * variables
327 	 */
328 	php_import_environment_variables(track_vars_array TSRMLS_CC);
329 
330 	/* Build the special-case PHP_SELF variable for the CLI version */
331 	len = strlen(php_self);
332 	if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, len, &len TSRMLS_CC)) {
333 		php_register_variable("PHP_SELF", php_self, track_vars_array TSRMLS_CC);
334 	}
335 	if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &php_self, len, &len TSRMLS_CC)) {
336 		php_register_variable("SCRIPT_NAME", php_self, track_vars_array TSRMLS_CC);
337 	}
338 	/* filenames are empty for stdin */
339 	len = strlen(script_filename);
340 	if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &script_filename, len, &len TSRMLS_CC)) {
341 		php_register_variable("SCRIPT_FILENAME", script_filename, track_vars_array TSRMLS_CC);
342 	}
343 	if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &script_filename, len, &len TSRMLS_CC)) {
344 		php_register_variable("PATH_TRANSLATED", script_filename, track_vars_array TSRMLS_CC);
345 	}
346 	/* just make it available */
347 	len = 0U;
348 	if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len, &len TSRMLS_CC)) {
349 		php_register_variable("DOCUMENT_ROOT", docroot, track_vars_array TSRMLS_CC);
350 	}
351 }
352 /* }}} */
353 
sapi_cli_log_message(char * message)354 static void sapi_cli_log_message(char *message) /* {{{ */
355 {
356 	fprintf(stderr, "%s\n", message);
357 }
358 /* }}} */
359 
sapi_cli_deactivate(TSRMLS_D)360 static int sapi_cli_deactivate(TSRMLS_D) /* {{{ */
361 {
362 	fflush(stdout);
363 	if(SG(request_info).argv0) {
364 		free(SG(request_info).argv0);
365 		SG(request_info).argv0 = NULL;
366 	}
367 	return SUCCESS;
368 }
369 /* }}} */
370 
sapi_cli_read_cookies(TSRMLS_D)371 static char* sapi_cli_read_cookies(TSRMLS_D) /* {{{ */
372 {
373 	return NULL;
374 }
375 /* }}} */
376 
sapi_cli_header_handler(sapi_header_struct * h,sapi_header_op_enum op,sapi_headers_struct * s TSRMLS_DC)377 static int sapi_cli_header_handler(sapi_header_struct *h, sapi_header_op_enum op, sapi_headers_struct *s TSRMLS_DC) /* {{{ */
378 {
379 	return 0;
380 }
381 /* }}} */
382 
sapi_cli_send_headers(sapi_headers_struct * sapi_headers TSRMLS_DC)383 static int sapi_cli_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC) /* {{{ */
384 {
385 	/* We do nothing here, this function is needed to prevent that the fallback
386 	 * header handling is called. */
387 	return SAPI_HEADER_SENT_SUCCESSFULLY;
388 }
389 /* }}} */
390 
sapi_cli_send_header(sapi_header_struct * sapi_header,void * server_context TSRMLS_DC)391 static void sapi_cli_send_header(sapi_header_struct *sapi_header, void *server_context TSRMLS_DC) /* {{{ */
392 {
393 }
394 /* }}} */
395 
php_cli_startup(sapi_module_struct * sapi_module)396 static int php_cli_startup(sapi_module_struct *sapi_module) /* {{{ */
397 {
398 	if (php_module_startup(sapi_module, NULL, 0)==FAILURE) {
399 		return FAILURE;
400 	}
401 	return SUCCESS;
402 }
403 /* }}} */
404 
405 /* {{{ sapi_cli_ini_defaults */
406 
407 /* overwriteable ini defaults must be set in sapi_cli_ini_defaults() */
408 #define INI_DEFAULT(name,value)\
409 	Z_SET_REFCOUNT(tmp, 0);\
410 	Z_UNSET_ISREF(tmp);	\
411 	ZVAL_STRINGL(&tmp, zend_strndup(value, sizeof(value)-1), sizeof(value)-1, 0);\
412 	zend_hash_update(configuration_hash, name, sizeof(name), &tmp, sizeof(zval), NULL);\
413 
sapi_cli_ini_defaults(HashTable * configuration_hash)414 static void sapi_cli_ini_defaults(HashTable *configuration_hash)
415 {
416 	zval tmp;
417 	INI_DEFAULT("report_zend_debug", "0");
418 	INI_DEFAULT("display_errors", "1");
419 }
420 /* }}} */
421 
422 /* {{{ sapi_module_struct cli_sapi_module
423  */
424 static sapi_module_struct cli_sapi_module = {
425 	"cli",							/* name */
426 	"Command Line Interface",    	/* pretty name */
427 
428 	php_cli_startup,				/* startup */
429 	php_module_shutdown_wrapper,	/* shutdown */
430 
431 	NULL,							/* activate */
432 	sapi_cli_deactivate,			/* deactivate */
433 
434 	sapi_cli_ub_write,		    	/* unbuffered write */
435 	sapi_cli_flush,				    /* flush */
436 	NULL,							/* get uid */
437 	NULL,							/* getenv */
438 
439 	php_error,						/* error handler */
440 
441 	sapi_cli_header_handler,		/* header handler */
442 	sapi_cli_send_headers,			/* send headers handler */
443 	sapi_cli_send_header,			/* send header handler */
444 
445 	NULL,				            /* read POST data */
446 	sapi_cli_read_cookies,          /* read Cookies */
447 
448 	sapi_cli_register_variables,	/* register server variables */
449 	sapi_cli_log_message,			/* Log message */
450 	NULL,							/* Get request time */
451 	NULL,							/* Child terminate */
452 
453 	STANDARD_SAPI_MODULE_PROPERTIES
454 };
455 /* }}} */
456 
457 /* {{{ arginfo ext/standard/dl.c */
458 ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
459 	ZEND_ARG_INFO(0, extension_filename)
460 ZEND_END_ARG_INFO()
461 /* }}} */
462 
463 static const zend_function_entry additional_functions[] = {
464 	ZEND_FE(dl, arginfo_dl)
465 	{NULL, NULL, NULL}
466 };
467 
468 /* {{{ php_cli_usage
469  */
php_cli_usage(char * argv0)470 static void php_cli_usage(char *argv0)
471 {
472 	char *prog;
473 
474 	prog = strrchr(argv0, '/');
475 	if (prog) {
476 		prog++;
477 	} else {
478 		prog = "php";
479 	}
480 
481 	php_printf( "Usage: %s [options] [-f] <file> [--] [args...]\n"
482 	            "       %s [options] -r <code> [--] [args...]\n"
483 	            "       %s [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]\n"
484 	            "       %s [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]\n"
485 	            "       %s [options] -- [args...]\n"
486 	            "       %s [options] -a\n"
487 	            "\n"
488 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
489 				"  -a               Run as interactive shell\n"
490 #else
491 				"  -a               Run interactively\n"
492 #endif
493 				"  -c <path>|<file> Look for php.ini file in this directory\n"
494 				"  -n               No php.ini file will be used\n"
495 				"  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
496 				"  -e               Generate extended information for debugger/profiler\n"
497 				"  -f <file>        Parse and execute <file>.\n"
498 				"  -h               This help\n"
499 				"  -i               PHP information\n"
500 				"  -l               Syntax check only (lint)\n"
501 				"  -m               Show compiled in modules\n"
502 				"  -r <code>        Run PHP <code> without using script tags <?..?>\n"
503 				"  -B <begin_code>  Run PHP <begin_code> before processing input lines\n"
504 				"  -R <code>        Run PHP <code> for every input line\n"
505 				"  -F <file>        Parse and execute <file> for every input line\n"
506 				"  -E <end_code>    Run PHP <end_code> after processing all input lines\n"
507 				"  -H               Hide any passed arguments from external tools.\n"
508 				"  -s               Output HTML syntax highlighted source.\n"
509 				"  -v               Version number\n"
510 				"  -w               Output source with stripped comments and whitespace.\n"
511 				"  -z <file>        Load Zend extension <file>.\n"
512 				"\n"
513 				"  args...          Arguments passed to script. Use -- args when first argument\n"
514 				"                   starts with - or script is read from stdin\n"
515 				"\n"
516 				"  --ini            Show configuration file names\n"
517 				"\n"
518 				"  --rf <name>      Show information about function <name>.\n"
519 				"  --rc <name>      Show information about class <name>.\n"
520 				"  --re <name>      Show information about extension <name>.\n"
521 				"  --ri <name>      Show configuration for extension <name>.\n"
522 				"\n"
523 				, prog, prog, prog, prog, prog, prog);
524 }
525 /* }}} */
526 
527 static php_stream *s_in_process = NULL;
528 
cli_register_file_handles(TSRMLS_D)529 static void cli_register_file_handles(TSRMLS_D) /* {{{ */
530 {
531 	zval *zin, *zout, *zerr;
532 	php_stream *s_in, *s_out, *s_err;
533 	php_stream_context *sc_in=NULL, *sc_out=NULL, *sc_err=NULL;
534 	zend_constant ic, oc, ec;
535 
536 	MAKE_STD_ZVAL(zin);
537 	MAKE_STD_ZVAL(zout);
538 	MAKE_STD_ZVAL(zerr);
539 
540 	s_in  = php_stream_open_wrapper_ex("php://stdin",  "rb", 0, NULL, sc_in);
541 	s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
542 	s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
543 
544 	if (s_in==NULL || s_out==NULL || s_err==NULL) {
545 		FREE_ZVAL(zin);
546 		FREE_ZVAL(zout);
547 		FREE_ZVAL(zerr);
548 		if (s_in) php_stream_close(s_in);
549 		if (s_out) php_stream_close(s_out);
550 		if (s_err) php_stream_close(s_err);
551 		return;
552 	}
553 
554 #if PHP_DEBUG
555 	/* do not close stdout and stderr */
556 	s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
557 	s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
558 #endif
559 
560 	s_in_process = s_in;
561 
562 	php_stream_to_zval(s_in,  zin);
563 	php_stream_to_zval(s_out, zout);
564 	php_stream_to_zval(s_err, zerr);
565 
566 	ic.value = *zin;
567 	ic.flags = CONST_CS;
568 	ic.name = zend_strndup(ZEND_STRL("STDIN"));
569 	ic.name_len = sizeof("STDIN");
570 	ic.module_number = 0;
571 	zend_register_constant(&ic TSRMLS_CC);
572 
573 	oc.value = *zout;
574 	oc.flags = CONST_CS;
575 	oc.name = zend_strndup(ZEND_STRL("STDOUT"));
576 	oc.name_len = sizeof("STDOUT");
577 	oc.module_number = 0;
578 	zend_register_constant(&oc TSRMLS_CC);
579 
580 	ec.value = *zerr;
581 	ec.flags = CONST_CS;
582 	ec.name = zend_strndup(ZEND_STRL("STDERR"));
583 	ec.name_len = sizeof("STDERR");
584 	ec.module_number = 0;
585 	zend_register_constant(&ec TSRMLS_CC);
586 
587 	FREE_ZVAL(zin);
588 	FREE_ZVAL(zout);
589 	FREE_ZVAL(zerr);
590 }
591 /* }}} */
592 
593 static const char *param_mode_conflict = "Either execute direct code, process stdin or use a file.\n";
594 
595 /* {{{ cli_seek_file_begin
596  */
cli_seek_file_begin(zend_file_handle * file_handle,char * script_file,int * lineno TSRMLS_DC)597 static int cli_seek_file_begin(zend_file_handle *file_handle, char *script_file, int *lineno TSRMLS_DC)
598 {
599 	int c;
600 
601 	*lineno = 1;
602 
603 	file_handle->type = ZEND_HANDLE_FP;
604 	file_handle->opened_path = NULL;
605 	file_handle->free_filename = 0;
606 	if (!(file_handle->handle.fp = VCWD_FOPEN(script_file, "rb"))) {
607 		php_printf("Could not open input file: %s\n", script_file);
608 		return FAILURE;
609 	}
610 	file_handle->filename = script_file;
611 
612 	/* #!php support */
613 	c = fgetc(file_handle->handle.fp);
614 	if (c == '#' && (c = fgetc(file_handle->handle.fp)) == '!') {
615 		while (c != '\n' && c != '\r' && c != EOF) {
616 			c = fgetc(file_handle->handle.fp);	/* skip to end of line */
617 		}
618 		/* handle situations where line is terminated by \r\n */
619 		if (c == '\r') {
620 			if (fgetc(file_handle->handle.fp) != '\n') {
621 				long pos = ftell(file_handle->handle.fp);
622 				fseek(file_handle->handle.fp, pos - 1, SEEK_SET);
623 			}
624 		}
625 		*lineno = 2;
626 	} else {
627 		rewind(file_handle->handle.fp);
628 	}
629 
630 	return SUCCESS;
631 }
632 /* }}} */
633 
634 /* {{{ main
635  */
636 #ifdef PHP_CLI_WIN32_NO_CONSOLE
WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)637 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
638 #else
639 int main(int argc, char *argv[])
640 #endif
641 {
642 	volatile int exit_status = SUCCESS;
643 	int c;
644 	zend_file_handle file_handle;
645 /* temporary locals */
646 	int behavior=PHP_MODE_STANDARD;
647 	char *reflection_what = NULL;
648 	int orig_optind=php_optind;
649 	char *orig_optarg=php_optarg;
650 	char *arg_free=NULL, **arg_excp=&arg_free;
651 	char *script_file=NULL, *translated_path = NULL;
652 	int interactive=0;
653 	volatile int module_started = 0;
654 	volatile int request_started = 0;
655 	int lineno = 0;
656 	char *exec_direct=NULL, *exec_run=NULL, *exec_begin=NULL, *exec_end=NULL;
657 	const char *param_error=NULL;
658 	int hide_argv = 0;
659 /* end of temporary locals */
660 #ifdef ZTS
661 	void ***tsrm_ls;
662 #endif
663 #ifdef PHP_CLI_WIN32_NO_CONSOLE
664 	int argc = __argc;
665 	char **argv = __argv;
666 #endif
667 	int ini_entries_len = 0;
668 
669 #if defined(PHP_WIN32) && defined(_DEBUG) && defined(PHP_WIN32_DEBUG_HEAP)
670 	{
671 		int tmp_flag;
672 		_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
673 		_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
674 		_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
675 		_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
676 		_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
677 		_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
678 		tmp_flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
679 		tmp_flag |= _CRTDBG_DELAY_FREE_MEM_DF;
680 		tmp_flag |= _CRTDBG_LEAK_CHECK_DF;
681 
682 		_CrtSetDbgFlag(tmp_flag);
683 	}
684 #endif
685 
686 #ifdef HAVE_SIGNAL_H
687 #if defined(SIGPIPE) && defined(SIG_IGN)
688 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
689 								that sockets created via fsockopen()
690 								don't kill PHP if the remote site
691 								closes it.  in apache|apxs mode apache
692 								does that for us!  thies@thieso.net
693 								20000419 */
694 #endif
695 #endif
696 
697 
698 #ifdef ZTS
699 	tsrm_startup(1, 1, 0, NULL);
700 	tsrm_ls = ts_resource(0);
701 #endif
702 
703 	cli_sapi_module.ini_defaults = sapi_cli_ini_defaults;
704 	cli_sapi_module.php_ini_path_override = NULL;
705 	cli_sapi_module.phpinfo_as_text = 1;
706 	sapi_startup(&cli_sapi_module);
707 
708 #ifdef PHP_WIN32
709 	_fmode = _O_BINARY;			/*sets default for file streams to binary */
710 	setmode(_fileno(stdin), O_BINARY);		/* make the stdio mode be binary */
711 	setmode(_fileno(stdout), O_BINARY);		/* make the stdio mode be binary */
712 	setmode(_fileno(stderr), O_BINARY);		/* make the stdio mode be binary */
713 #endif
714 
715 	ini_entries_len = sizeof(HARDCODED_INI)-2;
716 	cli_sapi_module.ini_entries = malloc(sizeof(HARDCODED_INI));
717 	memcpy(cli_sapi_module.ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI));
718 
719 	while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2))!=-1) {
720 		switch (c) {
721 			case 'c':
722 				if (cli_sapi_module.php_ini_path_override) {
723 					free(cli_sapi_module.php_ini_path_override);
724 				}
725  				cli_sapi_module.php_ini_path_override = strdup(php_optarg);
726 				break;
727 			case 'n':
728 				cli_sapi_module.php_ini_ignore = 1;
729 				break;
730 			case 'd': {
731 				/* define ini entries on command line */
732 				int len = strlen(php_optarg);
733 				char *val;
734 
735 				if ((val = strchr(php_optarg, '='))) {
736 					val++;
737 					if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
738 						cli_sapi_module.ini_entries = realloc(cli_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
739 						memcpy(cli_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
740 						ini_entries_len += (val - php_optarg);
741 						memcpy(cli_sapi_module.ini_entries + ini_entries_len, "\"", 1);
742 						ini_entries_len++;
743 						memcpy(cli_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
744 						ini_entries_len += len - (val - php_optarg);
745 						memcpy(cli_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
746 						ini_entries_len += sizeof("\n\0\"") - 2;
747 					} else {
748 						cli_sapi_module.ini_entries = realloc(cli_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
749 						memcpy(cli_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
750 						memcpy(cli_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
751 						ini_entries_len += len + sizeof("\n\0") - 2;
752 					}
753 				} else {
754 					cli_sapi_module.ini_entries = realloc(cli_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
755 					memcpy(cli_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
756 					memcpy(cli_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
757 					ini_entries_len += len + sizeof("=1\n\0") - 2;
758 				}
759 				break;
760 			}
761 		}
762 	}
763 	php_optind = orig_optind;
764 	php_optarg = orig_optarg;
765 
766 	cli_sapi_module.executable_location = argv[0];
767 	cli_sapi_module.additional_functions = additional_functions;
768 
769 	/* startup after we get the above ini override se we get things right */
770 	if (cli_sapi_module.startup(&cli_sapi_module)==FAILURE) {
771 		/* there is no way to see if we must call zend_ini_deactivate()
772 		 * since we cannot check if EG(ini_directives) has been initialised
773 		 * because the executor's constructor does not set initialize it.
774 		 * Apart from that there seems no need for zend_ini_deactivate() yet.
775 		 * So we goto out_err.*/
776 		exit_status = 1;
777 		goto out_err;
778 	}
779 	module_started = 1;
780 
781 	zend_first_try {
782 		CG(in_compilation) = 0; /* not initialized but needed for several options */
783 		EG(uninitialized_zval_ptr) = NULL;
784 
785 		while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
786 			switch (c) {
787 
788 			case 'h': /* help & quit */
789 			case '?':
790 				if (php_request_startup(TSRMLS_C)==FAILURE) {
791 					goto err;
792 				}
793 				request_started = 1;
794 				php_cli_usage(argv[0]);
795 				php_end_ob_buffers(1 TSRMLS_CC);
796 				exit_status = (c == '?' && argc > 1 && !strchr(argv[1],  c));
797 				goto out;
798 
799 			case 'i': /* php info & quit */
800 				if (php_request_startup(TSRMLS_C)==FAILURE) {
801 					goto err;
802 				}
803 				request_started = 1;
804 				php_print_info(0xFFFFFFFF TSRMLS_CC);
805 				php_end_ob_buffers(1 TSRMLS_CC);
806 				exit_status=0;
807 				goto out;
808 
809 			case 'm': /* list compiled in modules */
810 				if (php_request_startup(TSRMLS_C)==FAILURE) {
811 					goto err;
812 				}
813 				request_started = 1;
814 				php_printf("[PHP Modules]\n");
815 				print_modules(TSRMLS_C);
816 				php_printf("\n[Zend Modules]\n");
817 				print_extensions(TSRMLS_C);
818 				php_printf("\n");
819 				php_end_ob_buffers(1 TSRMLS_CC);
820 				exit_status=0;
821 				goto out;
822 
823 			case 'v': /* show php version & quit */
824 				if (php_request_startup(TSRMLS_C) == FAILURE) {
825 					goto err;
826 				}
827 
828 				request_started = 1;
829 				php_printf("PHP %s (%s) (built: %s %s) %s\nCopyright (c) 1997-2014 The PHP Group\n%s",
830 					PHP_VERSION, sapi_module.name, __DATE__, __TIME__,
831 #if ZEND_DEBUG && defined(HAVE_GCOV)
832 					"(DEBUG GCOV)",
833 #elif ZEND_DEBUG
834 					"(DEBUG)",
835 #elif defined(HAVE_GCOV)
836 					"(GCOV)",
837 #else
838 					"",
839 #endif
840 					get_zend_version()
841 				);
842 				php_end_ob_buffers(1 TSRMLS_CC);
843 				exit_status=0;
844 				goto out;
845 
846 			default:
847 				break;
848 			}
849 		}
850 
851 		/* Set some CLI defaults */
852 		SG(options) |= SAPI_OPTION_NO_CHDIR;
853 
854 		php_optind = orig_optind;
855 		php_optarg = orig_optarg;
856 		while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
857 			switch (c) {
858 
859 			case 'a':	/* interactive mode */
860 				if (!interactive) {
861 					if (behavior != PHP_MODE_STANDARD) {
862 						param_error = param_mode_conflict;
863 						break;
864 					}
865 
866 					interactive=1;
867 				}
868 				break;
869 
870 			case 'C': /* don't chdir to the script directory */
871 				/* This is default so NOP */
872 				break;
873 
874 			case 'e': /* enable extended info output */
875 				CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
876 				break;
877 
878 			case 'F':
879 				if (behavior == PHP_MODE_PROCESS_STDIN) {
880 					if (exec_run || script_file) {
881 						param_error = "You can use -R or -F only once.\n";
882 						break;
883 					}
884 				} else if (behavior != PHP_MODE_STANDARD) {
885 					param_error = param_mode_conflict;
886 					break;
887 				}
888 				behavior=PHP_MODE_PROCESS_STDIN;
889 				script_file = php_optarg;
890 				break;
891 
892 			case 'f': /* parse file */
893 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
894 					param_error = param_mode_conflict;
895 					break;
896 				} else if (script_file) {
897 					param_error = "You can use -f only once.\n";
898 					break;
899 				}
900 				script_file = php_optarg;
901 				break;
902 
903 			case 'l': /* syntax check mode */
904 				if (behavior != PHP_MODE_STANDARD) {
905 					break;
906 				}
907 				behavior=PHP_MODE_LINT;
908 				break;
909 
910 #if 0 /* not yet operational, see also below ... */
911 			case '': /* generate indented source mode*/
912 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
913 					param_error = "Source indenting only works for files.\n";
914 					break;
915 				}
916 				behavior=PHP_MODE_INDENT;
917 				break;
918 #endif
919 
920 			case 'q': /* do not generate HTTP headers */
921 				/* This is default so NOP */
922 				break;
923 
924 			case 'r': /* run code from command line */
925 				if (behavior == PHP_MODE_CLI_DIRECT) {
926 					if (exec_direct || script_file) {
927 						param_error = "You can use -r only once.\n";
928 						break;
929 					}
930 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
931 					param_error = param_mode_conflict;
932 					break;
933 				}
934 				behavior=PHP_MODE_CLI_DIRECT;
935 				exec_direct=php_optarg;
936 				break;
937 
938 			case 'R':
939 				if (behavior == PHP_MODE_PROCESS_STDIN) {
940 					if (exec_run || script_file) {
941 						param_error = "You can use -R or -F only once.\n";
942 						break;
943 					}
944 				} else if (behavior != PHP_MODE_STANDARD) {
945 					param_error = param_mode_conflict;
946 					break;
947 				}
948 				behavior=PHP_MODE_PROCESS_STDIN;
949 				exec_run=php_optarg;
950 				break;
951 
952 			case 'B':
953 				if (behavior == PHP_MODE_PROCESS_STDIN) {
954 					if (exec_begin) {
955 						param_error = "You can use -B only once.\n";
956 						break;
957 					}
958 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
959 					param_error = param_mode_conflict;
960 					break;
961 				}
962 				behavior=PHP_MODE_PROCESS_STDIN;
963 				exec_begin=php_optarg;
964 				break;
965 
966 			case 'E':
967 				if (behavior == PHP_MODE_PROCESS_STDIN) {
968 					if (exec_end) {
969 						param_error = "You can use -E only once.\n";
970 						break;
971 					}
972 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
973 					param_error = param_mode_conflict;
974 					break;
975 				}
976 				behavior=PHP_MODE_PROCESS_STDIN;
977 				exec_end=php_optarg;
978 				break;
979 
980 			case 's': /* generate highlighted HTML from source */
981 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
982 					param_error = "Source highlighting only works for files.\n";
983 					break;
984 				}
985 				behavior=PHP_MODE_HIGHLIGHT;
986 				break;
987 
988 			case 'w':
989 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
990 					param_error = "Source stripping only works for files.\n";
991 					break;
992 				}
993 				behavior=PHP_MODE_STRIP;
994 				break;
995 
996 			case 'z': /* load extension file */
997 				zend_load_extension(php_optarg);
998 				break;
999 			case 'H':
1000 				hide_argv = 1;
1001 				break;
1002 			case 10:
1003 				behavior=PHP_MODE_REFLECTION_FUNCTION;
1004 				reflection_what = php_optarg;
1005 				break;
1006 			case 11:
1007 				behavior=PHP_MODE_REFLECTION_CLASS;
1008 				reflection_what = php_optarg;
1009 				break;
1010 			case 12:
1011 				behavior=PHP_MODE_REFLECTION_EXTENSION;
1012 				reflection_what = php_optarg;
1013 				break;
1014 			case 13:
1015 				behavior=PHP_MODE_REFLECTION_EXT_INFO;
1016 				reflection_what = php_optarg;
1017 				break;
1018 			case 14:
1019 				behavior = PHP_MODE_SHOW_INI_CONFIG;
1020 				break;
1021 			default:
1022 				break;
1023 			}
1024 		}
1025 
1026 		if (param_error) {
1027 			PUTS(param_error);
1028 			exit_status=1;
1029 			goto err;
1030 		}
1031 
1032 		if (interactive) {
1033 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
1034 			printf("Interactive shell\n\n");
1035 #else
1036 			printf("Interactive mode enabled\n\n");
1037 #endif
1038 			fflush(stdout);
1039 		}
1040 
1041 		CG(interactive) = interactive;
1042 
1043 		/* only set script_file if not set already and not in direct mode and not at end of parameter list */
1044 		if (argc > php_optind
1045 		  && !script_file
1046 		  && behavior!=PHP_MODE_CLI_DIRECT
1047 		  && behavior!=PHP_MODE_PROCESS_STDIN
1048 		  && strcmp(argv[php_optind-1],"--"))
1049 		{
1050 			script_file=argv[php_optind];
1051 			php_optind++;
1052 		}
1053 		if (script_file) {
1054 			if (cli_seek_file_begin(&file_handle, script_file, &lineno TSRMLS_CC) != SUCCESS) {
1055 				goto err;
1056 			} else {
1057 				char real_path[MAXPATHLEN];
1058 				if (VCWD_REALPATH(script_file, real_path)) {
1059 					translated_path = strdup(real_path);
1060 				}
1061 				script_filename = script_file;
1062 			}
1063 		} else {
1064 			/* We could handle PHP_MODE_PROCESS_STDIN in a different manner  */
1065 			/* here but this would make things only more complicated. And it */
1066 			/* is consitent with the way -R works where the stdin file handle*/
1067 			/* is also accessible. */
1068 			file_handle.filename = "-";
1069 			file_handle.handle.fp = stdin;
1070 		}
1071 		file_handle.type = ZEND_HANDLE_FP;
1072 		file_handle.opened_path = NULL;
1073 		file_handle.free_filename = 0;
1074 		php_self = file_handle.filename;
1075 
1076 		/* before registering argv to module exchange the *new* argv[0] */
1077 		/* we can achieve this without allocating more memory */
1078 		SG(request_info).argc=argc-php_optind+1;
1079 		arg_excp = argv+php_optind-1;
1080 		arg_free = argv[php_optind-1];
1081 		SG(request_info).path_translated = translated_path? translated_path : file_handle.filename;
1082 		argv[php_optind-1] = file_handle.filename;
1083 		SG(request_info).argv=argv+php_optind-1;
1084 
1085 		if (php_request_startup(TSRMLS_C)==FAILURE) {
1086 			*arg_excp = arg_free;
1087 			fclose(file_handle.handle.fp);
1088 			PUTS("Could not startup.\n");
1089 			goto err;
1090 		}
1091 		request_started = 1;
1092 		CG(start_lineno) = lineno;
1093 		*arg_excp = arg_free; /* reconstuct argv */
1094 
1095 		if (hide_argv) {
1096 			int i;
1097 			for (i = 1; i < argc; i++) {
1098 				memset(argv[i], 0, strlen(argv[i]));
1099 			}
1100 		}
1101 
1102 		zend_is_auto_global("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
1103 
1104 		PG(during_request_startup) = 0;
1105 		switch (behavior) {
1106 		case PHP_MODE_STANDARD:
1107 			if (strcmp(file_handle.filename, "-")) {
1108 				cli_register_file_handles(TSRMLS_C);
1109 			}
1110 
1111 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
1112 			if (interactive) {
1113 				char *line;
1114 				size_t size = 4096, pos = 0, len;
1115 				char *code = emalloc(size);
1116 				char *prompt = "php > ";
1117 				char *history_file;
1118 
1119 				if (PG(auto_prepend_file) && PG(auto_prepend_file)[0]) {
1120 					zend_file_handle *prepend_file_p;
1121 					zend_file_handle prepend_file = {0};
1122 
1123 					prepend_file.filename = PG(auto_prepend_file);
1124 					prepend_file.opened_path = NULL;
1125 					prepend_file.free_filename = 0;
1126 					prepend_file.type = ZEND_HANDLE_FILENAME;
1127 					prepend_file_p = &prepend_file;
1128 
1129 					zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 1, prepend_file_p);
1130 				}
1131 
1132 				history_file = tilde_expand("~/.php_history");
1133 				rl_attempted_completion_function = cli_code_completion;
1134 				rl_special_prefixes = "$";
1135 				read_history(history_file);
1136 
1137 				EG(exit_status) = 0;
1138 				while ((line = readline(prompt)) != NULL) {
1139 					if (strcmp(line, "exit") == 0 || strcmp(line, "quit") == 0) {
1140 						free(line);
1141 						break;
1142 					}
1143 
1144 					if (!pos && !*line) {
1145 						free(line);
1146 						continue;
1147 					}
1148 
1149 					len = strlen(line);
1150 					if (pos + len + 2 > size) {
1151 						size = pos + len + 2;
1152 						code = erealloc(code, size);
1153 					}
1154 					memcpy(&code[pos], line, len);
1155 					pos += len;
1156 					code[pos] = '\n';
1157 					code[++pos] = '\0';
1158 
1159 					if (*line) {
1160 						add_history(line);
1161 					}
1162 
1163 					free(line);
1164 
1165 					if (!cli_is_valid_code(code, pos, &prompt TSRMLS_CC)) {
1166 						continue;
1167 					}
1168 
1169 					zend_eval_stringl(code, pos, NULL, "php shell code" TSRMLS_CC);
1170 					pos = 0;
1171 
1172 					if (php_last_char != '\0' && php_last_char != '\n') {
1173 						sapi_cli_single_write("\n", 1 TSRMLS_CC);
1174 					}
1175 
1176 					if (EG(exception)) {
1177 						zend_exception_error(EG(exception), E_WARNING TSRMLS_CC);
1178 					}
1179 
1180 					php_last_char = '\0';
1181 				}
1182 				write_history(history_file);
1183 				free(history_file);
1184 				efree(code);
1185 				exit_status = EG(exit_status);
1186 				break;
1187 			}
1188 #endif /* HAVE_LIBREADLINE || HAVE_LIBEDIT */
1189 			php_execute_script(&file_handle TSRMLS_CC);
1190 			exit_status = EG(exit_status);
1191 			break;
1192 		case PHP_MODE_LINT:
1193 			exit_status = php_lint_script(&file_handle TSRMLS_CC);
1194 			if (exit_status==SUCCESS) {
1195 				zend_printf("No syntax errors detected in %s\n", file_handle.filename);
1196 			} else {
1197 				zend_printf("Errors parsing %s\n", file_handle.filename);
1198 			}
1199 			break;
1200 		case PHP_MODE_STRIP:
1201 			if (open_file_for_scanning(&file_handle TSRMLS_CC)==SUCCESS) {
1202 				zend_strip(TSRMLS_C);
1203 			}
1204 			goto out;
1205 			break;
1206 		case PHP_MODE_HIGHLIGHT:
1207 			{
1208 				zend_syntax_highlighter_ini syntax_highlighter_ini;
1209 
1210 				if (open_file_for_scanning(&file_handle TSRMLS_CC)==SUCCESS) {
1211 					php_get_highlight_struct(&syntax_highlighter_ini);
1212 					zend_highlight(&syntax_highlighter_ini TSRMLS_CC);
1213 				}
1214 				goto out;
1215 			}
1216 			break;
1217 #if 0
1218 			/* Zeev might want to do something with this one day */
1219 		case PHP_MODE_INDENT:
1220 			open_file_for_scanning(&file_handle TSRMLS_CC);
1221 			zend_indent();
1222 			zend_file_handle_dtor(file_handle.handle TSRMLS_CC);
1223 			goto out;
1224 			break;
1225 #endif
1226 		case PHP_MODE_CLI_DIRECT:
1227 			cli_register_file_handles(TSRMLS_C);
1228 			if (zend_eval_string_ex(exec_direct, NULL, "Command line code", 1 TSRMLS_CC) == FAILURE) {
1229 				exit_status=254;
1230 			}
1231 			break;
1232 
1233 		case PHP_MODE_PROCESS_STDIN:
1234 			{
1235 				char *input;
1236 				size_t len, index = 0;
1237 				zval *argn, *argi;
1238 
1239 				cli_register_file_handles(TSRMLS_C);
1240 
1241 				if (exec_begin && zend_eval_string_ex(exec_begin, NULL, "Command line begin code", 1 TSRMLS_CC) == FAILURE) {
1242 					exit_status=254;
1243 				}
1244 				ALLOC_ZVAL(argi);
1245 				Z_TYPE_P(argi) = IS_LONG;
1246 				Z_LVAL_P(argi) = index;
1247 				INIT_PZVAL(argi);
1248 				zend_hash_update(&EG(symbol_table), "argi", sizeof("argi"), &argi, sizeof(zval *), NULL);
1249 				while (exit_status == SUCCESS && (input=php_stream_gets(s_in_process, NULL, 0)) != NULL) {
1250 					len = strlen(input);
1251 					while (len-- && (input[len]=='\n' || input[len]=='\r')) {
1252 						input[len] = '\0';
1253 					}
1254 					ALLOC_ZVAL(argn);
1255 					Z_TYPE_P(argn) = IS_STRING;
1256 					Z_STRLEN_P(argn) = ++len;
1257 					Z_STRVAL_P(argn) = estrndup(input, len);
1258 					INIT_PZVAL(argn);
1259 					zend_hash_update(&EG(symbol_table), "argn", sizeof("argn"), &argn, sizeof(zval *), NULL);
1260 					Z_LVAL_P(argi) = ++index;
1261 					if (exec_run) {
1262 						if (zend_eval_string_ex(exec_run, NULL, "Command line run code", 1 TSRMLS_CC) == FAILURE) {
1263 							exit_status=254;
1264 						}
1265 					} else {
1266 						if (script_file) {
1267 							if (cli_seek_file_begin(&file_handle, script_file, &lineno TSRMLS_CC) != SUCCESS) {
1268 								exit_status = 1;
1269 							} else {
1270 								CG(start_lineno) = lineno;
1271 								php_execute_script(&file_handle TSRMLS_CC);
1272 								exit_status = EG(exit_status);
1273 							}
1274 						}
1275 					}
1276 					efree(input);
1277 				}
1278 				if (exec_end && zend_eval_string_ex(exec_end, NULL, "Command line end code", 1 TSRMLS_CC) == FAILURE) {
1279 					exit_status=254;
1280 				}
1281 
1282 				break;
1283 			}
1284 			case PHP_MODE_REFLECTION_FUNCTION:
1285 			case PHP_MODE_REFLECTION_CLASS:
1286 			case PHP_MODE_REFLECTION_EXTENSION:
1287 				{
1288 					zend_class_entry *pce = NULL;
1289 					zval *arg, *ref;
1290 					zend_execute_data execute_data;
1291 
1292 					switch (behavior) {
1293 						default:
1294 							break;
1295 						case PHP_MODE_REFLECTION_FUNCTION:
1296 							if (strstr(reflection_what, "::")) {
1297 								pce = reflection_method_ptr;
1298 							} else {
1299 								pce = reflection_function_ptr;
1300 							}
1301 							break;
1302 						case PHP_MODE_REFLECTION_CLASS:
1303 							pce = reflection_class_ptr;
1304 							break;
1305 						case PHP_MODE_REFLECTION_EXTENSION:
1306 							pce = reflection_extension_ptr;
1307 							break;
1308 					}
1309 
1310 					MAKE_STD_ZVAL(arg);
1311 					ZVAL_STRING(arg, reflection_what, 1);
1312 					ALLOC_ZVAL(ref);
1313 					object_init_ex(ref, pce);
1314 					INIT_PZVAL(ref);
1315 
1316 					memset(&execute_data, 0, sizeof(zend_execute_data));
1317 					EG(current_execute_data) = &execute_data;
1318 					EX(function_state).function = pce->constructor;
1319 					zend_call_method_with_1_params(&ref, pce, &pce->constructor, "__construct", NULL, arg);
1320 
1321 					if (EG(exception)) {
1322 						zval *msg = zend_read_property(zend_exception_get_default(TSRMLS_C), EG(exception), "message", sizeof("message")-1, 0 TSRMLS_CC);
1323 						zend_printf("Exception: %s\n", Z_STRVAL_P(msg));
1324 						zval_ptr_dtor(&EG(exception));
1325 						EG(exception) = NULL;
1326 					} else {
1327 						zend_call_method_with_1_params(NULL, reflection_ptr, NULL, "export", NULL, ref);
1328 					}
1329 					zval_ptr_dtor(&ref);
1330 					zval_ptr_dtor(&arg);
1331 
1332 					break;
1333 				}
1334 			case PHP_MODE_REFLECTION_EXT_INFO:
1335 				{
1336 					int len = strlen(reflection_what);
1337 					char *lcname = zend_str_tolower_dup(reflection_what, len);
1338 					zend_module_entry *module;
1339 
1340 					if (zend_hash_find(&module_registry, lcname, len+1, (void**)&module) == FAILURE) {
1341 						if (!strcmp(reflection_what, "main")) {
1342 							display_ini_entries(NULL);
1343 						} else {
1344 							zend_printf("Extension '%s' not present.\n", reflection_what);
1345 							exit_status = 1;
1346 						}
1347 					} else {
1348 						php_info_print_module(module TSRMLS_CC);
1349 					}
1350 
1351 					efree(lcname);
1352 					break;
1353 				}
1354 			case PHP_MODE_SHOW_INI_CONFIG:
1355 				{
1356 					zend_printf("Configuration File (php.ini) Path: %s\n", PHP_CONFIG_FILE_PATH);
1357 					zend_printf("Loaded Configuration File:         %s\n", php_ini_opened_path ? php_ini_opened_path : "(none)");
1358 					zend_printf("Scan for additional .ini files in: %s\n", php_ini_scanned_path ? php_ini_scanned_path : "(none)");
1359 					zend_printf("Additional .ini files parsed:      %s\n", php_ini_scanned_files ? php_ini_scanned_files : "(none)");
1360 					break;
1361 				}
1362 		}
1363 
1364 	} zend_end_try();
1365 
1366 out:
1367 	if (request_started) {
1368 		php_request_shutdown((void *) 0);
1369 	}
1370 	if (translated_path) {
1371 		free(translated_path);
1372 	}
1373 	if (exit_status == 0) {
1374 		exit_status = EG(exit_status);
1375 	}
1376 out_err:
1377 	if (cli_sapi_module.php_ini_path_override) {
1378 		free(cli_sapi_module.php_ini_path_override);
1379 	}
1380 	if (cli_sapi_module.ini_entries) {
1381 		free(cli_sapi_module.ini_entries);
1382 	}
1383 
1384 	if (module_started) {
1385 		php_module_shutdown(TSRMLS_C);
1386 	}
1387 	sapi_shutdown();
1388 #ifdef ZTS
1389 	tsrm_shutdown();
1390 #endif
1391 
1392 	exit(exit_status);
1393 
1394 err:
1395 	sapi_deactivate(TSRMLS_C);
1396 	zend_ini_deactivate(TSRMLS_C);
1397 	exit_status = 1;
1398 	goto out_err;
1399 }
1400 /* }}} */
1401 
1402 /*
1403  * Local variables:
1404  * tab-width: 4
1405  * c-basic-offset: 4
1406  * End:
1407  * vim600: sw=4 ts=4 fdm=marker
1408  * vim<600: sw=4 ts=4
1409  */
1410