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