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