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