예제 #1
0
파일: init.c 프로젝트: atulyadavtech/kernel
int main(int argc, char **argv) {
    pid_t installpid, childpid;
    int waitStatus;
    int fd = -1;
    int doShutdown =0;
    reboot_action shutdown_method = HALT;
    int isSerial = 0;
    int isDevelMode = 0;
    char * console = NULL;
    int doKill = 1;
    char * argvc[15];
    char buf[1024];
    char ** argvp = argvc;
    char twelve = 12;
    struct serial_struct si;
    int i, disable_keys;
    int ret;

    if (!strncmp(basename(argv[0]), "poweroff", 8)) {
        printf("Running poweroff...\n");
        fd = getInitPid();
        if (fd > 0)
            kill(fd, SIGUSR2);
        doExit(0);
    } else if (!strncmp(basename(argv[0]), "halt", 4)) {
        printf("Running halt...\n");
        fd = getInitPid();
        if (fd > 0)
            kill(fd, SIGUSR1);
        doExit(0);
    } else if (!strncmp(basename(argv[0]), "reboot", 6)) {
        printf("Running reboot...\n");
        fd = getInitPid();
        if (fd > 0)
            kill(fd, SIGINT);
        doExit(0);
    }

    /* turn off screen blanking */
    printstr("\033[9;0]");
    printstr("\033[8]");

    umask(022);

    /* set up signal handler */
    setupBacktrace();

    printstr("\nGreetings.\n");

    printf("anaconda installer init version %s starting\n", VERSION);

    printf("mounting /proc filesystem... "); 
    fflush(stdout);
    if (mount("/proc", "/proc", "proc", 0, NULL))
        fatal_error(1);
    printf("done\n");

    /* check for development mode early */
    int fdn;
    if ((fdn = open("/proc/cmdline", O_RDONLY, 0)) != -1) {

        /* get cmdline info */
        int len = read(fdn, buf, sizeof(buf) - 1);
        char *develstart;
        close(fdn);

        /* check the arguments */
        if (len > 0) {
            develstart = buf;
            while (develstart && (*develstart) != '\0') {
                
                /* strip spaces */
		while(*develstart == ' ') develstart++;
		if(*develstart == '\0') break;
                
                /* not the word we are looking for */
                if (strncmp(develstart, "devel", 5)) {
                    develstart = strchr(develstart, ' ');
                    continue;
		}
                
                /* is it isolated? */
                if(((*(develstart+5)) == ' ' || (*(develstart+5)) == '\0')) {
                    printf("Enabling development mode - cores will be dumped\n");
                    isDevelMode++;
                    break;
                }
                
                /* Find next argument */
                develstart = strchr(develstart, ' ');
            }
        }
    }

    /* these args are only for testing from commandline */
    for (i = 1; i < argc; i++) {
        if (!strcmp (argv[i], "serial")) {
            isSerial = 1;
            break;
        }
    }

    printf("creating /dev filesystem... "); 
    fflush(stdout);
    if (mount("/dev", "/dev", "tmpfs", 0, NULL))
        fatal_error(1);
    createDevices();
    printf("done\n");

    printf("starting udev...");
    fflush(stdout);
    if ((childpid = fork()) == 0) {
        execl("/sbin/udevd", "/sbin/udevd", "--daemon", NULL);
        fprintf(stderr, " exec of /sbin/udevd failed.");
        exit(1);
    }

    /* wait at least until the udevd process that we forked exits */
    do {
        pid_t retpid;
        int waitstatus;

        retpid = wait(&waitstatus);
        if (retpid == -1) {
            if (errno == EINTR)
                continue;
            /* if the child exited before we called waitpid, we can get
             * ECHILD without anything really being wrong; we just lost
             * the race.*/
            if (errno == ECHILD)
                break;
            printf("init: error waiting on udevd: %m\n");
            exit(1);
        } else if ((retpid == childpid) && WIFEXITED(waitstatus)) {
            break;
        }
    } while (1);

    if (fork() == 0) {
        execl("/sbin/udevadm", "udevadm", "control", "--env=ANACONDA=1", NULL);
        fprintf(stderr, " exec of /sbin/udevadm failed.");
        exit(1);
    }
    printf("done\n");

    printf("mounting /dev/pts (unix98 pty) filesystem... "); 
    fflush(stdout);
    if (mount("/dev/pts", "/dev/pts", "devpts", 0, NULL))
        fatal_error(1);
    printf("done\n");

    printf("mounting /sys filesystem... "); 
    fflush(stdout);
    if (mount("/sys", "/sys", "sysfs", 0, NULL))
        fatal_error(1);
    printf("done\n");

    /* if anaconda dies suddenly we are doomed, so at least make a coredump */
    struct rlimit corelimit = { RLIM_INFINITY,  RLIM_INFINITY};
    ret = setrlimit(RLIMIT_CORE, &corelimit);
    if (ret) {
        perror("setrlimit failed - no coredumps will be available");
    }

    doKill = getKillPolicy();

#if !defined(__s390__) && !defined(__s390x__)
    static struct termios orig_cmode;
    static int            orig_flags;
    struct termios cmode, mode;
    int cfd;
    
    cfd =  open("/dev/console", O_RDONLY);
    tcgetattr(cfd,&orig_cmode);
    orig_flags = fcntl(cfd, F_GETFL);
    close(cfd);

    cmode = orig_cmode;
    cmode.c_lflag &= (~ECHO);

    cfd = open("/dev/console", O_WRONLY);
    tcsetattr(cfd,TCSANOW,&cmode);
    close(cfd);

    /* handle weird consoles */
#if defined(__powerpc__)
    char * consoles[] = { "/dev/hvc0", /* hvc for JS20 */

                          "/dev/hvsi0", "/dev/hvsi1",
                          "/dev/hvsi2", /* hvsi for POWER5 */
                          NULL };
#elif defined (__ia64__)
    char * consoles[] = { "/dev/ttySG0", "/dev/xvc0", "/dev/hvc0", NULL };
#elif defined (__i386__) || defined (__x86_64__)
    char * consoles[] = { "/dev/xvc0", "/dev/hvc0", NULL };
#else
    char * consoles[] = { NULL };
#endif
    for (i = 0; consoles[i] != NULL; i++) {
        if ((fd = open(consoles[i], O_RDWR)) >= 0 && !tcgetattr(fd, &mode) && !termcmp(&cmode, &mode)) {
            printf("anaconda installer init version %s using %s as console\n",
                   VERSION, consoles[i]);
            isSerial = 3;
            console = strdup(consoles[i]);
            break;
        }
        close(fd);
    }

    cfd = open("/dev/console", O_WRONLY);
    tcsetattr(cfd,TCSANOW,&orig_cmode);
    close(cfd); 

    if ((fd < 0) && (ioctl (0, TIOCLINUX, &twelve) < 0)) {
        isSerial = 2;

        if (ioctl(0, TIOCGSERIAL, &si) == -1) {
            isSerial = 0;
        }
    }

    if (isSerial && (isSerial != 3)) {
        char *device = "/dev/ttyS0";

        printf("anaconda installer init version %s using a serial console\n", 
               VERSION);

        if (isSerial == 2)
            device = "/dev/console";
        fd = open(device, O_RDWR, 0);
        if (fd < 0)
            device = "/dev/tts/0";

        if (fd < 0) {
            printf("failed to open %s\n", device);
            fatal_error(1);
        }

        setupTerminal(fd);
    } else if (isSerial == 3) {
        setupTerminal(fd);
    } else if (fd < 0)  {
        fd = open("/dev/tty1", O_RDWR, 0);
        if (fd < 0)
            fd = open("/dev/vc/1", O_RDWR, 0);

        if (fd < 0) {
            printf("failed to open /dev/tty1 and /dev/vc/1");
            fatal_error(1);
        }
    }

    setsid();
    if (ioctl(0, TIOCSCTTY, NULL)) {
        printf("could not set new controlling tty\n");
    }

    dup2(fd, 0);
    dup2(fd, 1);
    dup2(fd, 2);
    if (fd > 2)
        close(fd);
#else
    dup2(0, 1);
    dup2(0, 2);
#endif

    /* disable Ctrl+Z, Ctrl+C, etc ... but not in rescue mode */
    disable_keys = 1;
    if (argc > 1)
        if (strstr(argv[1], "rescue"))
            disable_keys = 0;

    if (disable_keys) {
        tcgetattr(0, &ts);
        ts.c_iflag &= ~BRKINT;
        ts.c_iflag |= IGNBRK;
        ts.c_iflag &= ~ISIG;
        tcsetattr(0, TCSANOW, &ts);
    }

    ret = sethostname("localhost.localdomain", 21);
    /* the default domainname (as of 2.0.35) is "(none)", which confuses 
     glibc */
    ret = setdomainname("", 0);

    printf("trying to remount root filesystem read write... ");
    fflush(stdout);
    if (mount("/", "/", "ext2", MS_REMOUNT | MS_MGC_VAL, NULL)) {
        fatal_error(1);
    }
    printf("done\n");

    /* we want our /tmp to be tmpfs, but we also want to let people hack
     * their initrds to add things like a ks.cfg, so this has to be a little
     * tricky */
    rename("/tmp", "/oldtmp");
    mkdir("/tmp", 0755);

    printf("mounting /tmp as tmpfs... ");
    fflush(stdout);
    if (mount("none", "/tmp", "tmpfs", 0, "size=250m"))
        fatal_error(1);
    printf("done\n");

    copyDirectory("/oldtmp", "/tmp", copyErrorFn, copyErrorFn);
    unlink("/oldtmp");

    /* Now we have some /tmp space set up, and /etc and /dev point to
       it. We should be in pretty good shape. */
    startSyslog();

    /* write out a pid file */
    if ((fd = open("/var/run/init.pid", O_WRONLY|O_CREAT, 0644)) > 0) {
        char * buf = malloc(10);
        int ret;

        snprintf(buf, 9, "%d", getpid());
        ret = write(fd, buf, strlen(buf));
        close(fd);
        free(buf);
    } else {
        printf("unable to write init.pid (%d): %m\n", errno);
        sleep(2);
    }

    /* D-Bus */
    if (fork() == 0) {
        execl("/sbin/dbus-uuidgen", "/sbin/dbus-uuidgen", "--ensure", NULL);
        fprintf(stderr, "exec of /sbin/dbus-uuidgen failed.");
        doExit(1);
    }

    if (fork() == 0) {
        execl("/sbin/dbus-daemon", "/sbin/dbus-daemon", "--system", NULL);
        fprintf(stderr, "exec of /sbin/dbus-daemon failed.");
        doExit(1);
    }

    sleep(2);

    /* Go into normal init mode - keep going, and then do a orderly shutdown
       when:

       1) /bin/install exits
       2) we receive a SIGHUP 
    */

    printf("running install...\n"); 

    if (!(installpid = fork())) {
        /* child */
        *argvp++ = "/sbin/loader";

        if (isSerial == 3) {
            *argvp++ = "--virtpconsole";
            *argvp++ = console;
        }

        if (isDevelMode) {
            *argvp++ = "--devel";
        }

        *argvp++ = NULL;

        printf("running %s\n", argvc[0]);
        execve(argvc[0], argvc, env);

        shutDown(1, HALT);
    }

    /* signal handlers for halt/poweroff */
    signal(SIGUSR1, sigUsr1Handler);
    signal(SIGUSR2, sigUsr2Handler);

    /* set up the ctrl+alt+delete handler to kill our pid, not pid 1 */
    signal(SIGINT, sigintHandler);
    if ((fd = open("/proc/sys/kernel/cad_pid", O_WRONLY)) != -1) {
        char buf[7];
        size_t count;
        sprintf(buf, "%d", getpid());
        count = write(fd, buf, strlen(buf));
        close(fd);
        /* if we succeeded in writing our pid, turn off the hard reboot
           ctrl-alt-del handler */
        if (count == strlen(buf) &&
            (fd = open("/proc/sys/kernel/ctrl-alt-del", O_WRONLY)) != -1) {
            int ret;

            ret = write(fd, "0", 1);
            close(fd);
        }
    }
    
    while (!doShutdown) {
        pid_t childpid;
        childpid = wait(&waitStatus);

        if (childpid == installpid) {
            doShutdown = 1;
            ioctl(0, VT_ACTIVATE, 1);
        }
    }

#ifdef  ROCKS
    /*
     * ignore child processes that throw error stati when
     * they terminate
     */
    shutdown_method = REBOOT;
#else
    if (!WIFEXITED(waitStatus) ||
        (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus))) {

        /* Restore terminal */
        cfd =  open("/dev/console", O_RDONLY);
        tcsetattr(cfd, TCSANOW, &orig_cmode);
        fcntl(cfd, F_SETFL, orig_flags);
        close(cfd);

        shutdown_method = DELAYED_REBOOT;
        printf("install exited abnormally [%d/%d] ", WIFEXITED(waitStatus),
                                                     WEXITSTATUS(waitStatus));
        if (WIFSIGNALED(waitStatus)) {
            printf("-- received signal %d", WTERMSIG(waitStatus));
        }
        printf("\n");

        /* If debug mode was requested, spawn shell */
        if(isDevelMode) {
            pid_t shellpid;

            printf("Development mode requested spawning shell...\n");

            if ((shellpid = fork()) == 0) {
                execl("/sbin/bash", "/sbin/bash", NULL);
            }
            else if (shellpid > 0) {
                waitpid(shellpid, NULL, 0);
            }
            else {
                perror("Execution of debug shell failed.");
            }

        }

    } else {
        shutdown_method = REBOOT;
    }
#endif

#ifdef  ROCKS
    while(dontReboot()) {
            sleep(10);
    }
#endif

    shutDown(doKill, shutdown_method);

    return 0;
}
예제 #2
0
int main(int argc, char *argv[])
{
    //** init Qt (graphics toolkit) - www.qtsoftware.com
    // note: environment variable parsing is done by Qt before main is entered.
    // This makes setting environment vars to modify Qt behavior impossible.
    QApplication app(argc, argv);

    //** init splash screen, do it as early in program start as possible
    QSplashScreen mySplash(QPixmap(":/title_page.png"));
    mySplash.show();
    app.processEvents();

    //** set the names to our website
    QCoreApplication::setOrganizationName("the-butterfly-effect.org");
    QCoreApplication::setOrganizationDomain("the-butterfly-effect.org");
    QCoreApplication::setApplicationName(APPNAME);

    //** parse the command line arguments
    QStringList myCmdLineList = app.arguments();
    bool isParsingSuccess = true;
    // we can skip argument zero - that's the tbe executable itself
    for (int i = 1; i < myCmdLineList.size() && isParsingSuccess; i++) {
        QString myArg = myCmdLineList[i];
        if (myArg.startsWith("-")) {
            // remove one or two dashes - we're slightly more flexible than usual
            myArg.remove(0, 1);
            if (myArg.startsWith("-"))
                myArg.remove(0, 1);

            // extract value with = if there is one
            QStringList myExp = myArg.split("=");

            // is it matching with short or long?
            int j = 0;
            bool isMatch = false;
            while (theArgsTable[j].theFunctionPtr != nullptr) {
                if (myExp[0] == theArgsTable[j].theFullCommand
                        || myExp[0] == theArgsTable[j].theShortCommand) {
                    isMatch = true;
                    QString myVal;
                    if (theArgsTable[j].needsArgument == true) {
                        // was it '='?
                        if (myExp.count() == 2)
                            myVal = myExp[1];
                        else {
                            // or is it ' ' -> which means we need to grab next arg
                            if (i + 1 < myCmdLineList.size()) {
                                myVal = myCmdLineList[i + 1];
                                i++;
                            } else {
                                isParsingSuccess = false;
                                break;
                            }
                        }
                    }
                    if (theArgsTable[j].theFunctionPtr(myVal) == false)
                        isParsingSuccess = false;
                }
                ++j;
            }
            if (isMatch == false) {
                isParsingSuccess = false;
                break;
            }
        } else {
            // if it is a single string, it probably is a file name
            theStartFileName = myArg;
        }

    }

    if (isParsingSuccess == false)
        displayHelp("");

#ifdef QT_DEBUG
    setupBacktrace();
#endif

    //** read the locale from the environment and set the output language
    if (theIsRunAsRegression) {
        DEBUG1("Regression: not loading any translators!");
    } else
        TheTranslator.init();
    //** now the i18n is set up, let's show a message in the user's language.
    mySplash.showMessage(MainWindow::getWelcomeMessage());
    app.processEvents();

    DEBUG3("SUMMARY:");
    DEBUG3("  Verbosity is: %d / Fullscreen is %d", theVerbosity, theIsMaximized);
    if (theIsRunAsRegression) {
        DEBUG3("  Regression levels: '%s'", ASCII(theStartFileName));
    } else {
        DEBUG3("  Start file name is: '%s'", ASCII(theStartFileName));
    }

    // scope limiting
    {
        QSettings mySettings;
        DEBUG3("  using settings from: '%s'", ASCII(mySettings.fileName()));
    }

    if (theIsLevelCreator) {
        // TODO: check for environment variable QT_HASH_SEED=1
        if (NULL == getenv("QT_HASH_SEED")) {
            printf("\nIMPORTANT:\n");
            printf("Please 'export QT_HASH_SEED=1' before starting the TBE level creator.\n");
            printf("This ensures that the level files will be written in a consistent order.\n");
            exit(1);
        }
        DEBUG3("  got QT_HASH_SEED environment set, xml consistent order writing enabled");
    }

    //** setup main window, shut down splash screen
    MainWindow myMain(theIsMaximized);
    myMain.show();
    mySplash.finish(&myMain);

    //** run the main display loop until oblivion
    return app.exec();
}