xref: /php-src/sapi/cli/php_cli.c (revision 1a0ef2c1)
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. Otherwise,
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 	Z_CONSTANT_FLAGS(ic.value) = 0;
561 	ic.name = zend_string_init_interned("STDIN", sizeof("STDIN")-1, 0);
562 	zend_register_constant(&ic);
563 
564 	Z_CONSTANT_FLAGS(oc.value) = 0;
565 	oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT")-1, 0);
566 	zend_register_constant(&oc);
567 
568 	Z_CONSTANT_FLAGS(ec.value) = 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 		fprintf(stderr, "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) = 0;
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 				/* We want to set the error exit status if at least one lint failed.
741 				 * If all were successful we set the exit status to 0.
742 				 * We already set EG(exit_status) here such that only failures set the exit status. */
743 				EG(exit_status) = 0;
744 				break;
745 
746 			case 'q': /* do not generate HTTP headers */
747 				/* This is default so NOP */
748 				break;
749 
750 			case 'r': /* run code from command line */
751 				if (behavior == PHP_MODE_CLI_DIRECT) {
752 					if (exec_direct || script_file) {
753 						param_error = "You can use -r only once.\n";
754 						break;
755 					}
756 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
757 					param_error = param_mode_conflict;
758 					break;
759 				}
760 				behavior=PHP_MODE_CLI_DIRECT;
761 				exec_direct=php_optarg;
762 				break;
763 
764 			case 'R':
765 				if (behavior == PHP_MODE_PROCESS_STDIN) {
766 					if (exec_run || script_file) {
767 						param_error = "You can use -R or -F only once.\n";
768 						break;
769 					}
770 				} else if (behavior != PHP_MODE_STANDARD) {
771 					param_error = param_mode_conflict;
772 					break;
773 				}
774 				behavior=PHP_MODE_PROCESS_STDIN;
775 				exec_run=php_optarg;
776 				break;
777 
778 			case 'B':
779 				if (behavior == PHP_MODE_PROCESS_STDIN) {
780 					if (exec_begin) {
781 						param_error = "You can use -B only once.\n";
782 						break;
783 					}
784 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
785 					param_error = param_mode_conflict;
786 					break;
787 				}
788 				behavior=PHP_MODE_PROCESS_STDIN;
789 				exec_begin=php_optarg;
790 				break;
791 
792 			case 'E':
793 				if (behavior == PHP_MODE_PROCESS_STDIN) {
794 					if (exec_end) {
795 						param_error = "You can use -E only once.\n";
796 						break;
797 					}
798 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
799 					param_error = param_mode_conflict;
800 					break;
801 				}
802 				behavior=PHP_MODE_PROCESS_STDIN;
803 				exec_end=php_optarg;
804 				break;
805 
806 			case 's': /* generate highlighted HTML from source */
807 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
808 					param_error = "Source highlighting only works for files.\n";
809 					break;
810 				}
811 				behavior=PHP_MODE_HIGHLIGHT;
812 				break;
813 
814 			case 'w':
815 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
816 					param_error = "Source stripping only works for files.\n";
817 					break;
818 				}
819 				behavior=PHP_MODE_STRIP;
820 				break;
821 
822 			case 'z': /* load extension file */
823 				zend_load_extension(php_optarg);
824 				break;
825 			case 'H':
826 				hide_argv = true;
827 				break;
828 			case 10:
829 				behavior=PHP_MODE_REFLECTION_FUNCTION;
830 				reflection_what = php_optarg;
831 				break;
832 			case 11:
833 				behavior=PHP_MODE_REFLECTION_CLASS;
834 				reflection_what = php_optarg;
835 				break;
836 			case 12:
837 				behavior=PHP_MODE_REFLECTION_EXTENSION;
838 				reflection_what = php_optarg;
839 				break;
840 			case 13:
841 				behavior=PHP_MODE_REFLECTION_ZEND_EXTENSION;
842 				reflection_what = php_optarg;
843 				break;
844 			case 14:
845 				behavior=PHP_MODE_REFLECTION_EXT_INFO;
846 				reflection_what = php_optarg;
847 				break;
848 			case 15:
849 				behavior = PHP_MODE_SHOW_INI_CONFIG;
850 				break;
851 			case 16:
852 				num_repeats = atoi(php_optarg);
853 				break;
854 			default:
855 				break;
856 			}
857 		}
858 
859 		if (param_error) {
860 			PUTS(param_error);
861 			EG(exit_status) = 1;
862 			goto err;
863 		}
864 
865 #if defined(PHP_WIN32) && !defined(PHP_CLI_WIN32_NO_CONSOLE) && (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
866 		if (!interactive) {
867 		/* The -a option was not passed. If there is no file, it could
868 		 	still make sense to run interactively. The presence of a file
869 			is essential to mitigate buggy console info. */
870 			interactive = php_win32_console_is_own() &&
871 				!(script_file ||
872 					argc > php_optind && behavior!=PHP_MODE_CLI_DIRECT &&
873 					behavior!=PHP_MODE_PROCESS_STDIN &&
874 					strcmp(argv[php_optind-1],"--")
875 				);
876 		}
877 #endif
878 
879 		if (interactive) {
880 			printf("Interactive shell\n\n");
881 			fflush(stdout);
882 		}
883 
884 		if (num_repeats > 1) {
885 			fprintf(stdout, "Executing for the first time...\n");
886 			fflush(stdout);
887 		}
888 
889 do_repeat:
890 		/* only set script_file if not set already and not in direct mode and not at end of parameter list */
891 		if (argc > php_optind
892 		  && !script_file
893 		  && behavior!=PHP_MODE_CLI_DIRECT
894 		  && behavior!=PHP_MODE_PROCESS_STDIN
895 		  && strcmp(argv[php_optind-1],"--"))
896 		{
897 			script_file=argv[php_optind];
898 			php_optind++;
899 		}
900 		if (script_file) {
901 			virtual_cwd_activate();
902 			if (cli_seek_file_begin(&file_handle, script_file) == FAILURE) {
903 				goto err;
904 			} else {
905 				char real_path[MAXPATHLEN];
906 				if (VCWD_REALPATH(script_file, real_path)) {
907 					translated_path = strdup(real_path);
908 				}
909 				script_filename = script_file;
910 				php_self = script_file;
911 			}
912 		} else {
913 			/* We could handle PHP_MODE_PROCESS_STDIN in a different manner  */
914 			/* here but this would make things only more complicated. And it */
915 			/* is consistent with the way -R works where the stdin file handle*/
916 			/* is also accessible. */
917 			php_self = "Standard input code";
918 			if (behavior < PHP_MODE_CLI_DIRECT
919 			 && (!interactive || PHP_MODE_STANDARD != PHP_MODE_STANDARD)) {
920 				zend_stream_init_fp(&file_handle, stdin, php_self);
921 				file_handle.primary_script = 1;
922 			}
923 		}
924 
925 		/* before registering argv to module exchange the *new* argv[0] */
926 		/* we can achieve this without allocating more memory */
927 		SG(request_info).argc=argc-php_optind+1;
928 		arg_excp = argv+php_optind-1;
929 		arg_free = argv[php_optind-1];
930 		SG(request_info).path_translated = translated_path ? translated_path : php_self;
931 		argv[php_optind-1] = php_self;
932 		SG(request_info).argv=argv+php_optind-1;
933 
934 		if (php_request_startup()==FAILURE) {
935 			*arg_excp = arg_free;
936 			PUTS("Could not startup.\n");
937 			goto err;
938 		}
939 		request_started = 1;
940 		CG(skip_shebang) = 1;
941 
942 		zend_register_bool_constant(
943 			ZEND_STRL("PHP_CLI_PROCESS_TITLE"),
944 			is_ps_title_available() == PS_TITLE_SUCCESS,
945 			0, 0);
946 
947 		*arg_excp = arg_free; /* reconstruct argv */
948 
949 		if (hide_argv) {
950 			int i;
951 			for (i = 1; i < argc; i++) {
952 				memset(argv[i], 0, strlen(argv[i]));
953 			}
954 		}
955 
956 		zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER));
957 
958 		PG(during_request_startup) = 0;
959 		switch (behavior) {
960 		case PHP_MODE_STANDARD:
961 			cli_register_file_handles();
962 
963 			if (interactive) {
964 				EG(exit_status) = cli_shell_callbacks.cli_shell_run();
965 			} else {
966 				php_execute_script(&file_handle);
967 			}
968 			break;
969 		case PHP_MODE_LINT:
970 			if (php_lint_script(&file_handle) == SUCCESS) {
971 				zend_printf("No syntax errors detected in %s\n", php_self);
972 			} else {
973 				zend_printf("Errors parsing %s\n", php_self);
974 				EG(exit_status) = 255;
975 			}
976 			break;
977 		case PHP_MODE_STRIP:
978 			if (open_file_for_scanning(&file_handle)==SUCCESS) {
979 				zend_strip();
980 			}
981 			goto out;
982 			break;
983 		case PHP_MODE_HIGHLIGHT:
984 			{
985 				zend_syntax_highlighter_ini syntax_highlighter_ini;
986 
987 				if (open_file_for_scanning(&file_handle)==SUCCESS) {
988 					php_get_highlight_struct(&syntax_highlighter_ini);
989 					zend_highlight(&syntax_highlighter_ini);
990 				}
991 				goto out;
992 			}
993 			break;
994 		case PHP_MODE_CLI_DIRECT:
995 			cli_register_file_handles();
996 			zend_eval_string_ex(exec_direct, NULL, "Command line code", 1);
997 			break;
998 
999 		case PHP_MODE_PROCESS_STDIN:
1000 			{
1001 				char *input;
1002 				size_t len, index = 0;
1003 				zval argn, argi;
1004 
1005 				if (!exec_run && script_file) {
1006 					zend_string_release_ex(file_handle.filename, 0);
1007 					file_handle.filename = NULL;
1008 				}
1009 
1010 				cli_register_file_handles();
1011 
1012 				if (exec_begin) {
1013 					zend_eval_string_ex(exec_begin, NULL, "Command line begin code", 1);
1014 				}
1015 				while (EG(exit_status) == SUCCESS && (input=php_stream_gets(s_in_process, NULL, 0)) != NULL) {
1016 					len = strlen(input);
1017 					while (len > 0 && len-- && (input[len]=='\n' || input[len]=='\r')) {
1018 						input[len] = '\0';
1019 					}
1020 					ZVAL_STRINGL(&argn, input, len + 1);
1021 					zend_hash_str_update(&EG(symbol_table), "argn", sizeof("argn")-1, &argn);
1022 					ZVAL_LONG(&argi, ++index);
1023 					zend_hash_str_update(&EG(symbol_table), "argi", sizeof("argi")-1, &argi);
1024 					if (exec_run) {
1025 						zend_eval_string_ex(exec_run, NULL, "Command line run code", 1);
1026 					} else {
1027 						if (script_file) {
1028 							if (cli_seek_file_begin(&file_handle, script_file) == FAILURE) {
1029 								EG(exit_status) = 1;
1030 							} else {
1031 								CG(skip_shebang) = 1;
1032 								php_execute_script(&file_handle);
1033 							}
1034 						}
1035 					}
1036 					efree(input);
1037 				}
1038 				if (exec_end) {
1039 					zend_eval_string_ex(exec_end, NULL, "Command line end code", 1);
1040 				}
1041 
1042 				break;
1043 			}
1044 
1045 			case PHP_MODE_REFLECTION_FUNCTION:
1046 			case PHP_MODE_REFLECTION_CLASS:
1047 			case PHP_MODE_REFLECTION_EXTENSION:
1048 			case PHP_MODE_REFLECTION_ZEND_EXTENSION:
1049 				{
1050 					zend_class_entry *pce = NULL;
1051 					zval arg, ref;
1052 					zend_execute_data execute_data;
1053 
1054 					switch (behavior) {
1055 						default:
1056 							break;
1057 						case PHP_MODE_REFLECTION_FUNCTION:
1058 							if (strstr(reflection_what, "::")) {
1059 								pce = reflection_method_ptr;
1060 							} else {
1061 								pce = reflection_function_ptr;
1062 							}
1063 							break;
1064 						case PHP_MODE_REFLECTION_CLASS:
1065 							pce = reflection_class_ptr;
1066 							break;
1067 						case PHP_MODE_REFLECTION_EXTENSION:
1068 							pce = reflection_extension_ptr;
1069 							break;
1070 						case PHP_MODE_REFLECTION_ZEND_EXTENSION:
1071 							pce = reflection_zend_extension_ptr;
1072 							break;
1073 					}
1074 
1075 					ZVAL_STRING(&arg, reflection_what);
1076 					object_init_ex(&ref, pce);
1077 
1078 					memset(&execute_data, 0, sizeof(zend_execute_data));
1079 					EG(current_execute_data) = &execute_data;
1080 					zend_call_known_instance_method_with_1_params(
1081 						pce->constructor, Z_OBJ(ref), NULL, &arg);
1082 
1083 					if (EG(exception)) {
1084 						zval rv;
1085 						zval *msg = zend_read_property_ex(zend_ce_exception, EG(exception), ZSTR_KNOWN(ZEND_STR_MESSAGE), /* silent */ false, &rv);
1086 						zend_printf("Exception: %s\n", Z_STRVAL_P(msg));
1087 						zend_object_release(EG(exception));
1088 						EG(exception) = NULL;
1089 						EG(exit_status) = 1;
1090 					} else {
1091 						zend_print_zval(&ref, 0);
1092 						zend_write("\n", 1);
1093 					}
1094 					zval_ptr_dtor(&ref);
1095 					zval_ptr_dtor(&arg);
1096 
1097 					break;
1098 				}
1099 			case PHP_MODE_REFLECTION_EXT_INFO:
1100 				{
1101 					size_t len = strlen(reflection_what);
1102 					char *lcname = zend_str_tolower_dup(reflection_what, len);
1103 					zend_module_entry *module;
1104 
1105 					if ((module = zend_hash_str_find_ptr(&module_registry, lcname, len)) == NULL) {
1106 						if (!strcmp(reflection_what, "main")) {
1107 							display_ini_entries(NULL);
1108 						} else {
1109 							zend_printf("Extension '%s' not present.\n", reflection_what);
1110 							EG(exit_status) = 1;
1111 						}
1112 					} else {
1113 						php_info_print_module(module);
1114 					}
1115 
1116 					efree(lcname);
1117 					break;
1118 				}
1119 
1120 			case PHP_MODE_SHOW_INI_CONFIG:
1121 				{
1122 					zend_printf("Configuration File (php.ini) Path: %s\n", PHP_CONFIG_FILE_PATH);
1123 					zend_printf("Loaded Configuration File:         %s\n", php_ini_opened_path ? php_ini_opened_path : "(none)");
1124 					zend_printf("Scan for additional .ini files in: %s\n", php_ini_scanned_path  ? php_ini_scanned_path : "(none)");
1125 					zend_printf("Additional .ini files parsed:      %s\n", php_ini_scanned_files ? php_ini_scanned_files : "(none)");
1126 					break;
1127 				}
1128 		}
1129 	} zend_end_try();
1130 
1131 out:
1132 	if (file_handle.filename) {
1133 		zend_destroy_file_handle(&file_handle);
1134 	}
1135 	if (request_started) {
1136 		php_request_shutdown((void *) 0);
1137 		request_started = 0;
1138 	}
1139 	if (translated_path) {
1140 		free(translated_path);
1141 		translated_path = NULL;
1142 	}
1143 	if (behavior == PHP_MODE_LINT && argc > php_optind && strcmp(argv[php_optind],"--")) {
1144 		script_file = NULL;
1145 		goto do_repeat;
1146 	}
1147 	/* Don't repeat fork()ed processes. */
1148 	if (--num_repeats && pid == getpid()) {
1149 		fprintf(stdout, "Finished execution, repeating...\n");
1150 		fflush(stdout);
1151 		goto do_repeat;
1152 	}
1153 	return EG(exit_status);
1154 err:
1155 	sapi_deactivate();
1156 	zend_ini_deactivate();
1157 	EG(exit_status) = 1;
1158 	goto out;
1159 }
1160 /* }}} */
1161 
1162 /* {{{ main */
1163 #ifdef PHP_CLI_WIN32_NO_CONSOLE
WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)1164 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
1165 #else
1166 int main(int argc, char *argv[])
1167 #endif
1168 {
1169 #if defined(PHP_WIN32)
1170 # ifdef PHP_CLI_WIN32_NO_CONSOLE
1171 	int argc = __argc;
1172 	char **argv = __argv;
1173 # endif
1174 	int num_args;
1175 	wchar_t **argv_wide;
1176 	char **argv_save = argv;
1177 	BOOL using_wide_argv = 0;
1178 #endif
1179 
1180 	int c;
1181 	int exit_status = SUCCESS;
1182 	int module_started = 0, sapi_started = 0;
1183 	char *php_optarg = NULL;
1184 	int php_optind = 1, use_extended_info = 0;
1185 	char *ini_path_override = NULL;
1186 	struct php_ini_builder ini_builder;
1187 	int ini_ignore = 0;
1188 	sapi_module_struct *sapi_module = &cli_sapi_module;
1189 
1190 	/*
1191 	 * Do not move this initialization. It needs to happen before argv is used
1192 	 * in any way.
1193 	 */
1194 	argv = save_ps_args(argc, argv);
1195 
1196 #if defined(PHP_WIN32) && !defined(PHP_CLI_WIN32_NO_CONSOLE)
1197 	php_win32_console_fileno_set_vt100(STDOUT_FILENO, TRUE);
1198 	php_win32_console_fileno_set_vt100(STDERR_FILENO, TRUE);
1199 #endif
1200 
1201 	cli_sapi_module.additional_functions = additional_functions;
1202 
1203 #if defined(PHP_WIN32) && defined(_DEBUG)
1204 	{
1205 		char *tmp = getenv("PHP_WIN32_DEBUG_HEAP");
1206 		if (tmp && ZEND_ATOL(tmp)) {
1207 			int tmp_flag;
1208 			_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1209 			_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1210 			_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
1211 			_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1212 			_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
1213 			_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1214 			tmp_flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
1215 			tmp_flag |= _CRTDBG_DELAY_FREE_MEM_DF;
1216 			tmp_flag |= _CRTDBG_LEAK_CHECK_DF;
1217 
1218 			_CrtSetDbgFlag(tmp_flag);
1219 		}
1220 	}
1221 #endif
1222 
1223 #if defined(SIGPIPE) && defined(SIG_IGN)
1224 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1225 								that sockets created via fsockopen()
1226 								don't kill PHP if the remote site
1227 								closes it.  in apache|apxs mode apache
1228 								does that for us!  thies@thieso.net
1229 								20000419 */
1230 #endif
1231 
1232 #ifdef ZTS
1233 	php_tsrm_startup();
1234 # ifdef PHP_WIN32
1235 	ZEND_TSRMLS_CACHE_UPDATE();
1236 # endif
1237 #endif
1238 
1239 	zend_signal_startup();
1240 
1241 #ifdef PHP_WIN32
1242 	_fmode = _O_BINARY;			/*sets default for file streams to binary */
1243 	setmode(_fileno(stdin), O_BINARY);		/* make the stdio mode be binary */
1244 	setmode(_fileno(stdout), O_BINARY);		/* make the stdio mode be binary */
1245 	setmode(_fileno(stderr), O_BINARY);		/* make the stdio mode be binary */
1246 #endif
1247 
1248 	php_ini_builder_init(&ini_builder);
1249 
1250 	while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2))!=-1) {
1251 		switch (c) {
1252 			case 'c':
1253 				if (ini_path_override) {
1254 					free(ini_path_override);
1255 				}
1256 				ini_path_override = strdup(php_optarg);
1257 				break;
1258 			case 'n':
1259 				ini_ignore = 1;
1260 				break;
1261 			case 'd':
1262 				/* define ini entries on command line */
1263 				php_ini_builder_define(&ini_builder, php_optarg);
1264 				break;
1265 #ifndef PHP_CLI_WIN32_NO_CONSOLE
1266 			case 'S':
1267 				sapi_module = &cli_server_sapi_module;
1268 				cli_server_sapi_module.additional_functions = server_additional_functions;
1269 				break;
1270 #endif
1271 			case 'h': /* help & quit */
1272 			case '?':
1273 				php_cli_usage(argv[0]);
1274 				goto out;
1275 			case PHP_GETOPT_INVALID_ARG: /* print usage on bad options, exit 1 */
1276 				php_cli_usage(argv[0]);
1277 				exit_status = 1;
1278 				goto out;
1279 			case 'i': case 'v': case 'm':
1280 				sapi_module = &cli_sapi_module;
1281 				goto exit_loop;
1282 			case 'e': /* enable extended info output */
1283 				use_extended_info = 1;
1284 				break;
1285 		}
1286 	}
1287 exit_loop:
1288 
1289 	sapi_module->ini_defaults = sapi_cli_ini_defaults;
1290 	sapi_module->php_ini_path_override = ini_path_override;
1291 	sapi_module->phpinfo_as_text = 1;
1292 	sapi_module->php_ini_ignore_cwd = 1;
1293 	sapi_startup(sapi_module);
1294 	sapi_started = 1;
1295 
1296 	sapi_module->php_ini_ignore = ini_ignore;
1297 
1298 	sapi_module->executable_location = argv[0];
1299 
1300 	if (sapi_module == &cli_sapi_module) {
1301 		php_ini_builder_prepend_literal(&ini_builder, HARDCODED_INI);
1302 	}
1303 
1304 	sapi_module->ini_entries = php_ini_builder_finish(&ini_builder);
1305 
1306 	/* startup after we get the above ini override se we get things right */
1307 	if (sapi_module->startup(sapi_module) == FAILURE) {
1308 		/* there is no way to see if we must call zend_ini_deactivate()
1309 		 * since we cannot check if EG(ini_directives) has been initialized
1310 		 * because the executor's constructor does not set initialize it.
1311 		 * Apart from that there seems no need for zend_ini_deactivate() yet.
1312 		 * So we goto out_err.*/
1313 		exit_status = 1;
1314 		goto out;
1315 	}
1316 	module_started = 1;
1317 
1318 #if defined(PHP_WIN32)
1319 	php_win32_cp_cli_setup();
1320 	orig_cp = (php_win32_cp_get_orig())->id;
1321 	/* Ignore the delivered argv and argc, read from W API. This place
1322 		might be too late though, but this is the earliest place ATW
1323 		we can access the internal charset information from PHP. */
1324 	argv_wide = CommandLineToArgvW(GetCommandLineW(), &num_args);
1325 	PHP_WIN32_CP_W_TO_ANY_ARRAY(argv_wide, num_args, argv, argc)
1326 	using_wide_argv = 1;
1327 
1328 	SetConsoleCtrlHandler(php_cli_win32_ctrl_handler, TRUE);
1329 #endif
1330 
1331 	/* -e option */
1332 	if (use_extended_info) {
1333 		CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
1334 	}
1335 
1336 	zend_first_try {
1337 #ifndef PHP_CLI_WIN32_NO_CONSOLE
1338 		if (sapi_module == &cli_sapi_module) {
1339 #endif
1340 			exit_status = do_cli(argc, argv);
1341 #ifndef PHP_CLI_WIN32_NO_CONSOLE
1342 		} else {
1343 			exit_status = do_cli_server(argc, argv);
1344 		}
1345 #endif
1346 	} zend_end_try();
1347 out:
1348 	if (ini_path_override) {
1349 		free(ini_path_override);
1350 	}
1351 	php_ini_builder_deinit(&ini_builder);
1352 	if (module_started) {
1353 		php_module_shutdown();
1354 	}
1355 	if (sapi_started) {
1356 		sapi_shutdown();
1357 	}
1358 #ifdef ZTS
1359 	tsrm_shutdown();
1360 #endif
1361 
1362 #if defined(PHP_WIN32)
1363 	(void)php_win32_cp_cli_restore();
1364 
1365 	if (using_wide_argv) {
1366 		PHP_WIN32_CP_FREE_ARRAY(argv, argc);
1367 		LocalFree(argv_wide);
1368 	}
1369 	argv = argv_save;
1370 #endif
1371 	/*
1372 	 * Do not move this de-initialization. It needs to happen right before
1373 	 * exiting.
1374 	 */
1375 	cleanup_ps_args(argv);
1376 	exit(exit_status);
1377 }
1378 /* }}} */
1379