LCOV - code coverage report
Current view: top level - src/backend/main - main.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 43 100 43.0 %
Date: 2021-11-29 06:09:26 Functions: 4 5 80.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * main.c
       4             :  *    Stub main() routine for the postgres executable.
       5             :  *
       6             :  * This does some essential startup tasks for any incarnation of postgres
       7             :  * (postmaster, standalone backend, standalone bootstrap process, or a
       8             :  * separately exec'd child of a postmaster) and then dispatches to the
       9             :  * proper FooMain() routine for the incarnation.
      10             :  *
      11             :  *
      12             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
      13             :  * Portions Copyright (c) 1994, Regents of the University of California
      14             :  *
      15             :  *
      16             :  * IDENTIFICATION
      17             :  *    src/backend/main/main.c
      18             :  *
      19             :  *-------------------------------------------------------------------------
      20             :  */
      21             : #include "postgres.h"
      22             : 
      23             : #include <unistd.h>
      24             : 
      25             : #if defined(__NetBSD__)
      26             : #include <sys/param.h>
      27             : #endif
      28             : 
      29             : #if defined(_M_AMD64) && _MSC_VER == 1800
      30             : #include <math.h>
      31             : #include <versionhelpers.h>
      32             : #endif
      33             : 
      34             : #include "bootstrap/bootstrap.h"
      35             : #include "common/username.h"
      36             : #include "port/atomics.h"
      37             : #include "postmaster/postmaster.h"
      38             : #include "storage/spin.h"
      39             : #include "tcop/tcopprot.h"
      40             : #include "utils/help_config.h"
      41             : #include "utils/memutils.h"
      42             : #include "utils/pg_locale.h"
      43             : #include "utils/ps_status.h"
      44             : 
      45             : 
      46             : const char *progname;
      47             : 
      48             : 
      49             : static void startup_hacks(const char *progname);
      50             : static void init_locale(const char *categoryname, int category, const char *locale);
      51             : static void help(const char *progname);
      52             : static void check_root(const char *progname);
      53             : 
      54             : 
      55             : /*
      56             :  * Any Postgres server process begins execution here.
      57             :  */
      58             : int
      59        4080 : main(int argc, char *argv[])
      60             : {
      61        4080 :     bool        do_check_root = true;
      62             : 
      63             :     /*
      64             :      * If supported on the current platform, set up a handler to be called if
      65             :      * the backend/postmaster crashes with a fatal signal or exception.
      66             :      */
      67             : #if defined(WIN32) && defined(HAVE_MINIDUMP_TYPE)
      68             :     pgwin32_install_crashdump_handler();
      69             : #endif
      70             : 
      71        4080 :     progname = get_progname(argv[0]);
      72             : 
      73             :     /*
      74             :      * Platform-specific startup hacks
      75             :      */
      76        4080 :     startup_hacks(progname);
      77             : 
      78             :     /*
      79             :      * Remember the physical location of the initially given argv[] array for
      80             :      * possible use by ps display.  On some platforms, the argv[] storage must
      81             :      * be overwritten in order to set the process title for ps. In such cases
      82             :      * save_ps_display_args makes and returns a new copy of the argv[] array.
      83             :      *
      84             :      * save_ps_display_args may also move the environment strings to make
      85             :      * extra room. Therefore this should be done as early as possible during
      86             :      * startup, to avoid entanglements with code that might save a getenv()
      87             :      * result pointer.
      88             :      */
      89        4080 :     argv = save_ps_display_args(argc, argv);
      90             : 
      91             :     /*
      92             :      * Fire up essential subsystems: error and memory management
      93             :      *
      94             :      * Code after this point is allowed to use elog/ereport, though
      95             :      * localization of messages may not work right away, and messages won't go
      96             :      * anywhere but stderr until GUC settings get loaded.
      97             :      */
      98        4080 :     MemoryContextInit();
      99             : 
     100             :     /*
     101             :      * Set up locale information
     102             :      */
     103        4080 :     set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("postgres"));
     104             : 
     105             :     /*
     106             :      * In the postmaster, absorb the environment values for LC_COLLATE and
     107             :      * LC_CTYPE.  Individual backends will change these later to settings
     108             :      * taken from pg_database, but the postmaster cannot do that.  If we leave
     109             :      * these set to "C" then message localization might not work well in the
     110             :      * postmaster.
     111             :      */
     112        4080 :     init_locale("LC_COLLATE", LC_COLLATE, "");
     113        4080 :     init_locale("LC_CTYPE", LC_CTYPE, "");
     114             : 
     115             :     /*
     116             :      * LC_MESSAGES will get set later during GUC option processing, but we set
     117             :      * it here to allow startup error messages to be localized.
     118             :      */
     119             : #ifdef LC_MESSAGES
     120        4080 :     init_locale("LC_MESSAGES", LC_MESSAGES, "");
     121             : #endif
     122             : 
     123             :     /*
     124             :      * We keep these set to "C" always, except transiently in pg_locale.c; see
     125             :      * that file for explanations.
     126             :      */
     127        4080 :     init_locale("LC_MONETARY", LC_MONETARY, "C");
     128        4080 :     init_locale("LC_NUMERIC", LC_NUMERIC, "C");
     129        4080 :     init_locale("LC_TIME", LC_TIME, "C");
     130             : 
     131             :     /*
     132             :      * Now that we have absorbed as much as we wish to from the locale
     133             :      * environment, remove any LC_ALL setting, so that the environment
     134             :      * variables installed by pg_perm_setlocale have force.
     135             :      */
     136        4080 :     unsetenv("LC_ALL");
     137             : 
     138        4080 :     check_strxfrm_bug();
     139             : 
     140             :     /*
     141             :      * Catch standard options before doing much else, in particular before we
     142             :      * insist on not being root.
     143             :      */
     144        4080 :     if (argc > 1)
     145             :     {
     146        4080 :         if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
     147             :         {
     148           0 :             help(progname);
     149           0 :             exit(0);
     150             :         }
     151        4080 :         if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
     152             :         {
     153        1208 :             fputs(PG_BACKEND_VERSIONSTR, stdout);
     154        1208 :             exit(0);
     155             :         }
     156             : 
     157             :         /*
     158             :          * In addition to the above, we allow "--describe-config" and "-C var"
     159             :          * to be called by root.  This is reasonably safe since these are
     160             :          * read-only activities.  The -C case is important because pg_ctl may
     161             :          * try to invoke it while still holding administrator privileges on
     162             :          * Windows.  Note that while -C can normally be in any argv position,
     163             :          * if you want to bypass the root check you must put it first.  This
     164             :          * reduces the risk that we might misinterpret some other mode's -C
     165             :          * switch as being the postmaster/postgres one.
     166             :          */
     167        2872 :         if (strcmp(argv[1], "--describe-config") == 0)
     168           0 :             do_check_root = false;
     169        2872 :         else if (argc > 2 && strcmp(argv[1], "-C") == 0)
     170           0 :             do_check_root = false;
     171             :     }
     172             : 
     173             :     /*
     174             :      * Make sure we are not running as root, unless it's safe for the selected
     175             :      * option.
     176             :      */
     177        2872 :     if (do_check_root)
     178        2872 :         check_root(progname);
     179             : 
     180             :     /*
     181             :      * Dispatch to one of various subprograms depending on first argument.
     182             :      */
     183             : 
     184        2872 :     if (argc > 1 && strcmp(argv[1], "--check") == 0)
     185         952 :         BootstrapModeMain(argc, argv, true);
     186        1920 :     else if (argc > 1 && strcmp(argv[1], "--boot") == 0)
     187         476 :         BootstrapModeMain(argc, argv, false);
     188             : #ifdef EXEC_BACKEND
     189             :     else if (argc > 1 && strncmp(argv[1], "--fork", 6) == 0)
     190             :         SubPostmasterMain(argc, argv);
     191             : #endif
     192        1444 :     else if (argc > 1 && strcmp(argv[1], "--describe-config") == 0)
     193           0 :         GucInfoMain();
     194        1444 :     else if (argc > 1 && strcmp(argv[1], "--single") == 0)
     195         498 :         PostgresSingleUserMain(argc, argv,
     196         498 :                                strdup(get_user_name_or_exit(progname)));
     197             :     else
     198         946 :         PostmasterMain(argc, argv);
     199             :     /* the functions above should not return */
     200             :     abort();
     201             : }
     202             : 
     203             : 
     204             : 
     205             : /*
     206             :  * Place platform-specific startup hacks here.  This is the right
     207             :  * place to put code that must be executed early in the launch of any new
     208             :  * server process.  Note that this code will NOT be executed when a backend
     209             :  * or sub-bootstrap process is forked, unless we are in a fork/exec
     210             :  * environment (ie EXEC_BACKEND is defined).
     211             :  *
     212             :  * XXX The need for code here is proof that the platform in question
     213             :  * is too brain-dead to provide a standard C execution environment
     214             :  * without help.  Avoid adding more here, if you can.
     215             :  */
     216             : static void
     217        4080 : startup_hacks(const char *progname)
     218             : {
     219             :     /*
     220             :      * Windows-specific execution environment hacking.
     221             :      */
     222             : #ifdef WIN32
     223             :     {
     224             :         WSADATA     wsaData;
     225             :         int         err;
     226             : 
     227             :         /* Make output streams unbuffered by default */
     228             :         setvbuf(stdout, NULL, _IONBF, 0);
     229             :         setvbuf(stderr, NULL, _IONBF, 0);
     230             : 
     231             :         /* Prepare Winsock */
     232             :         err = WSAStartup(MAKEWORD(2, 2), &wsaData);
     233             :         if (err != 0)
     234             :         {
     235             :             write_stderr("%s: WSAStartup failed: %d\n",
     236             :                          progname, err);
     237             :             exit(1);
     238             :         }
     239             : 
     240             :         /* In case of general protection fault, don't show GUI popup box */
     241             :         SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
     242             : 
     243             : #if defined(_M_AMD64) && _MSC_VER == 1800
     244             : 
     245             :         /*----------
     246             :          * Avoid crashing in certain floating-point operations if we were
     247             :          * compiled for x64 with MS Visual Studio 2013 and are running on
     248             :          * Windows prior to 7/2008R2 SP1 on an AVX2-capable CPU.
     249             :          *
     250             :          * Ref: https://connect.microsoft.com/VisualStudio/feedback/details/811093/visual-studio-2013-rtm-c-x64-code-generation-bug-for-avx2-instructions
     251             :          *----------
     252             :          */
     253             :         if (!IsWindows7SP1OrGreater())
     254             :         {
     255             :             _set_FMA3_enable(0);
     256             :         }
     257             : #endif                          /* defined(_M_AMD64) && _MSC_VER == 1800 */
     258             : 
     259             :     }
     260             : #endif                          /* WIN32 */
     261             : 
     262             :     /*
     263             :      * Initialize dummy_spinlock, in case we are on a platform where we have
     264             :      * to use the fallback implementation of pg_memory_barrier().
     265             :      */
     266        4080 :     SpinLockInit(&dummy_spinlock);
     267        4080 : }
     268             : 
     269             : 
     270             : /*
     271             :  * Make the initial permanent setting for a locale category.  If that fails,
     272             :  * perhaps due to LC_foo=invalid in the environment, use locale C.  If even
     273             :  * that fails, perhaps due to out-of-memory, the entire startup fails with it.
     274             :  * When this returns, we are guaranteed to have a setting for the given
     275             :  * category's environment variable.
     276             :  */
     277             : static void
     278       24480 : init_locale(const char *categoryname, int category, const char *locale)
     279             : {
     280       24480 :     if (pg_perm_setlocale(category, locale) == NULL &&
     281           0 :         pg_perm_setlocale(category, "C") == NULL)
     282           0 :         elog(FATAL, "could not adopt \"%s\" locale nor C locale for %s",
     283             :              locale, categoryname);
     284       24480 : }
     285             : 
     286             : 
     287             : 
     288             : /*
     289             :  * Help display should match the options accepted by PostmasterMain()
     290             :  * and PostgresMain().
     291             :  *
     292             :  * XXX On Windows, non-ASCII localizations of these messages only display
     293             :  * correctly if the console output code page covers the necessary characters.
     294             :  * Messages emitted in write_console() do not exhibit this problem.
     295             :  */
     296             : static void
     297           0 : help(const char *progname)
     298             : {
     299           0 :     printf(_("%s is the PostgreSQL server.\n\n"), progname);
     300           0 :     printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
     301           0 :     printf(_("Options:\n"));
     302           0 :     printf(_("  -B NBUFFERS        number of shared buffers\n"));
     303           0 :     printf(_("  -c NAME=VALUE      set run-time parameter\n"));
     304           0 :     printf(_("  -C NAME            print value of run-time parameter, then exit\n"));
     305           0 :     printf(_("  -d 1-5             debugging level\n"));
     306           0 :     printf(_("  -D DATADIR         database directory\n"));
     307           0 :     printf(_("  -e                 use European date input format (DMY)\n"));
     308           0 :     printf(_("  -F                 turn fsync off\n"));
     309           0 :     printf(_("  -h HOSTNAME        host name or IP address to listen on\n"));
     310           0 :     printf(_("  -i                 enable TCP/IP connections\n"));
     311           0 :     printf(_("  -k DIRECTORY       Unix-domain socket location\n"));
     312             : #ifdef USE_SSL
     313           0 :     printf(_("  -l                 enable SSL connections\n"));
     314             : #endif
     315           0 :     printf(_("  -N MAX-CONNECT     maximum number of allowed connections\n"));
     316           0 :     printf(_("  -p PORT            port number to listen on\n"));
     317           0 :     printf(_("  -s                 show statistics after each query\n"));
     318           0 :     printf(_("  -S WORK-MEM        set amount of memory for sorts (in kB)\n"));
     319           0 :     printf(_("  -V, --version      output version information, then exit\n"));
     320           0 :     printf(_("  --NAME=VALUE       set run-time parameter\n"));
     321           0 :     printf(_("  --describe-config  describe configuration parameters, then exit\n"));
     322           0 :     printf(_("  -?, --help         show this help, then exit\n"));
     323             : 
     324           0 :     printf(_("\nDeveloper options:\n"));
     325           0 :     printf(_("  -f s|i|n|m|h       forbid use of some plan types\n"));
     326           0 :     printf(_("  -n                 do not reinitialize shared memory after abnormal exit\n"));
     327           0 :     printf(_("  -O                 allow system table structure changes\n"));
     328           0 :     printf(_("  -P                 disable system indexes\n"));
     329           0 :     printf(_("  -t pa|pl|ex        show timings after each query\n"));
     330           0 :     printf(_("  -T                 send SIGSTOP to all backend processes if one dies\n"));
     331           0 :     printf(_("  -W NUM             wait NUM seconds to allow attach from a debugger\n"));
     332             : 
     333           0 :     printf(_("\nOptions for single-user mode:\n"));
     334           0 :     printf(_("  --single           selects single-user mode (must be first argument)\n"));
     335           0 :     printf(_("  DBNAME             database name (defaults to user name)\n"));
     336           0 :     printf(_("  -d 0-5             override debugging level\n"));
     337           0 :     printf(_("  -E                 echo statement before execution\n"));
     338           0 :     printf(_("  -j                 do not use newline as interactive query delimiter\n"));
     339           0 :     printf(_("  -r FILENAME        send stdout and stderr to given file\n"));
     340             : 
     341           0 :     printf(_("\nOptions for bootstrapping mode:\n"));
     342           0 :     printf(_("  --boot             selects bootstrapping mode (must be first argument)\n"));
     343           0 :     printf(_("  --check            selects check mode (must be first argument)\n"));
     344           0 :     printf(_("  DBNAME             database name (mandatory argument in bootstrapping mode)\n"));
     345           0 :     printf(_("  -r FILENAME        send stdout and stderr to given file\n"));
     346             : 
     347           0 :     printf(_("\nPlease read the documentation for the complete list of run-time\n"
     348             :              "configuration settings and how to set them on the command line or in\n"
     349             :              "the configuration file.\n\n"
     350             :              "Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
     351           0 :     printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
     352           0 : }
     353             : 
     354             : 
     355             : 
     356             : static void
     357        2872 : check_root(const char *progname)
     358             : {
     359             : #ifndef WIN32
     360        2872 :     if (geteuid() == 0)
     361             :     {
     362           0 :         write_stderr("\"root\" execution of the PostgreSQL server is not permitted.\n"
     363             :                      "The server must be started under an unprivileged user ID to prevent\n"
     364             :                      "possible system security compromise.  See the documentation for\n"
     365             :                      "more information on how to properly start the server.\n");
     366           0 :         exit(1);
     367             :     }
     368             : 
     369             :     /*
     370             :      * Also make sure that real and effective uids are the same. Executing as
     371             :      * a setuid program from a root shell is a security hole, since on many
     372             :      * platforms a nefarious subroutine could setuid back to root if real uid
     373             :      * is root.  (Since nobody actually uses postgres as a setuid program,
     374             :      * trying to actively fix this situation seems more trouble than it's
     375             :      * worth; we'll just expend the effort to check for it.)
     376             :      */
     377        2872 :     if (getuid() != geteuid())
     378             :     {
     379           0 :         write_stderr("%s: real and effective user IDs must match\n",
     380             :                      progname);
     381           0 :         exit(1);
     382             :     }
     383             : #else                           /* WIN32 */
     384             :     if (pgwin32_is_admin())
     385             :     {
     386             :         write_stderr("Execution of PostgreSQL by a user with administrative permissions is not\n"
     387             :                      "permitted.\n"
     388             :                      "The server must be started under an unprivileged user ID to prevent\n"
     389             :                      "possible system security compromises.  See the documentation for\n"
     390             :                      "more information on how to properly start the server.\n");
     391             :         exit(1);
     392             :     }
     393             : #endif                          /* WIN32 */
     394        2872 : }

Generated by: LCOV version 1.14