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