Example #1
0
// -------------------------------------------------------------
// Function exit event
// -------------------------------------------------------------
VOID PIN_FAST_ANALYSIS_CALL A_ProcessReturn(ADDRINT sp, THREADID threadid) {

    _STool_TThreadRec* tdata = getTLS(threadid);

    // roll back stack in case of longjmp
    AdjustStack(tdata, sp);

    if ( tdata->stackTop < 1 ) 
        graceful_exit(threadid, "Internal error: stack bottomed out");

    // call routine exit callback (if any was specified by the analysis tool)
    if (gSetup.rtnExit)
        gSetup.rtnExit(tdata + 1);

    // pop activation
    tdata->stackTop--;

    #if DEBUG
    printf("[TID=%u] Leaving %s\n", 
        threadid,
        Target2RtnName(tdata->activationStack[tdata->stackTop].target).c_str());
    #endif

    #if DEBUG
    if (tdata->stackTop > 0)
        printf("[TID=%u] Back to %s - # activations = %d - stack size = %d\n", 
            threadid, 
            Target2RtnName(tdata->activationStack[tdata->stackTop-1].target).c_str(), 
            tdata->stackTop, 
            tdata->stackSize);
    else printf("[TID=%u] Back to stack bottom\n", threadid);
    #endif
}
Example #2
0
void individual_evaluate(
        const fitness_function_s fitness_function,
        individual_s * const individual )
{
    if( individual == NULL )
    {
        fprintf( stderr, "bad parameter in individual_evaluate\n");
        graceful_exit( EXIT_FAILURE );
    }


    double output;


    individual->fitness = 0;

    for( unsigned long idx = 0; idx < fitness_function.data_point_count; ++idx )
    {
        // evaluate function on each input point
        output = node_evaluate(
                individual->tree_root_node,
                fitness_function.input[ idx ] );

        // outputs array holds correct values
        individual->fitness += pow( ( output - fitness_function.output[ idx ] ), 2 );
    }

    individual->fitness = sqrt( individual->fitness );
            + TREE_SIZE_PENALTY(individual->tree_node_count);

    if( individual->tree_node_count > MAX_TREE_NODE_COUNT )
    {
        individual->fitness += individual->tree_node_count;
    }
}
Example #3
0
unsigned long individual_calc_size(
        individual_s * const individual )
{
    if( individual == NULL )
    {
        fprintf( stderr, "bad parameter in individual_calc_size\n");
        graceful_exit( EXIT_FAILURE );
    }

    individual->tree_node_count = 0; // at least a root node
    individual->tree_terminal_count = 0;
    individual->tree_nonterminal_count = 0;

    unsigned long terminal_nodes = 0;
    unsigned long nonterminal_nodes = 0;

    node_calc_size(
            individual->tree_root_node,
            &terminal_nodes,
            &nonterminal_nodes );

    individual->tree_node_count += terminal_nodes + nonterminal_nodes;
    individual->tree_terminal_count = terminal_nodes;
    individual->tree_nonterminal_count = nonterminal_nodes;

    return individual->tree_node_count;
}
Example #4
0
// -------------------------------------------------------------
// Function direct call event (with calling site info)
// -------------------------------------------------------------
VOID PIN_FAST_ANALYSIS_CALL A_ProcessDirectCallCSBuf(ADDRINT ip, ADDRINT target, ADDRINT sp, THREADID threadid, CONTEXT *ctxt) {

    // get thread local data
    _STool_TThreadRec* tdata = getTLS(threadid);

    // roll back stack in case of longjmp
    AdjustStackBuf(tdata, sp, ctxt);

    // possibly expand stack
    if (tdata->stackTop >= tdata->stackMaxSize) {

        // double stack size
        tdata->stackMaxSize <<= 1;

        // expand activation stack
        tdata->activationStack = 
            (_STool_TActivationRec*)realloc(tdata->activationStack, 
                                            tdata->stackMaxSize*sizeof(_STool_TActivationRec)); 
        if (tdata->activationStack == NULL) 
            graceful_exit(threadid, "Can't expand activation stack");

        // expand user stack (if any is needed)
        if (tdata->userStack) {
            tdata->userStack = (char*)realloc(tdata->userStack, 
                                              tdata->stackMaxSize*gSetup.activationRecSize); 
            if (tdata->userStack == NULL)
                graceful_exit(threadid, "Can't expand user stack");
        }
    }    

    // push current activation record to stack
    _ActivationAt(tdata, tdata->stackTop).currentSP = sp;
    _ActivationAt(tdata, tdata->stackTop).target    = target;

    // increase activations counter
    tdata->stackTop++;

    #if DEBUG
    printf("[TID=%u] Entering %s - # activations = %d - stack size = %d\n", 
        threadid, Target2RtnName(target).c_str(), tdata->stackTop, tdata->stackSize);
    #endif
 
    // call routine enter callback (if any was specified by the analysis tool)
    if (gSetup.rtnEnter)
        gSetup.rtnEnter(tdata + 1, ip);
}
Example #5
0
void individual_mutate(
        individual_s * const individual )
{
    if( individual == NULL )
    {
        fprintf( stderr, "bad parameter in individual_mutate\n");
        graceful_exit( EXIT_FAILURE );
    }

    node_mutate( individual->tree_root_node );
}
Example #6
0
individual_s * individual_alloc( )
{
    individual_s *individual = (individual_s*)calloc( 1, sizeof(individual_s) );

    if( individual == NULL )
    {
        fprintf( stderr, "calloc failed in individual_alloc\n");
        graceful_exit( EXIT_FAILURE );
    }

    return individual;
}
Example #7
0
void individual_copy(
        const individual_s * const in,
        individual_s * const out )
{
    if( (in == NULL) || (out == NULL) )
    {
        fprintf( stderr, "bad param in individual_copy" );
        graceful_exit( EXIT_FAILURE );
    }

    out->tree_root_node = node_alloc();

    node_copy( in->tree_root_node, out->tree_root_node, NULL );

    out->tree_node_count = in->tree_node_count;
    out->fitness = in->fitness;
    out->tree_terminal_count = in->tree_terminal_count;
    out->tree_nonterminal_count = in->tree_nonterminal_count;
}
Example #8
0
// -------------------------------------------------------------
// Function exit event
// -------------------------------------------------------------
VOID PIN_FAST_ANALYSIS_CALL A_ProcessReturnBuf(ADDRINT sp, THREADID threadid, CONTEXT *ctxt) {
    
    _STool_TThreadRec* tdata = getTLS(threadid);

    // roll back stack in case of longjmp
    AdjustStackBuf(tdata, sp, ctxt);

    if ( tdata->stackTop < 1 )
        graceful_exit(threadid, "Internal error: stack bottomed out");
        
    // if using memory operations buffering, call trace buffer processing callback 
    // and reset buffer
    if (gSetup.memBuf) {
    	void * curr_buf_pointer = PIN_GetBufferPointer(ctxt, buf_id);
    	UINT64 numElements = ((ADDRINT)curr_buf_pointer - (ADDRINT)tdata->buf_addr) / sizeof(STool_TMemRec);
    	gSetup.memBuf(tdata+1, static_cast<STool_TMemRec*>(tdata->buf_addr), numElements);
    	tdata->buf_addr = curr_buf_pointer;
    }
    
    // call routine exit callback (if any was specified by the analysis tool)
    if (gSetup.rtnExit)
        gSetup.rtnExit(tdata + 1);

    // pop activation
    tdata->stackTop--;

    #if DEBUG
    printf("[TID=%u] Leaving %s\n", 
        threadid,
        Target2RtnName(tdata->activationStack[tdata->stackTop].target).c_str());
    #endif

    #if DEBUG
    if (tdata->stackTop > 0)
        printf("[TID=%u] Back to %s - # activations = %d - stack size = %d\n", 
            threadid, 
            Target2RtnName(tdata->activationStack[tdata->stackTop-1].target).c_str(), 
            tdata->stackTop, 
            tdata->stackSize);
    else printf("[TID=%u] Back to stack bottom\n", threadid);
    #endif
}
void
done ()
{
  time_t tvec, time ();
  char *ctime ();

  if (subchild)
    {
      tvec = time ((time_t *) NULL);
      (void) fclose (fscript);
      (void) close (master);
    }
  else
    {
      (void) tcsetattr (0, TCSAFLUSH, &tt);
    }

  remove_ipfile();
  graceful_exit (0);
}
Example #10
0
unsigned long long int disk_space_free(string path) {
	unsigned long long int dsf = 0; // default to saying the disk is full
	struct statvfs sfs;
	if (statvfs(path.c_str(), &sfs) != -1) {
		dsf = (unsigned long long) sfs.f_bsize * sfs.f_bfree;
	}
	fprintf(debug, "%llu bytes free\n", dsf);
	if (dsf < MINIMUM_DISK_SPACE_FREE_BEFORE_QUITTING) {
		fprintf(error, "FATAL ERROR:  %s bytes free on disk\n", insert_interstitial_commas(dsf).c_str());
		//fprintf(error, "ERROR:  %llu bytes free on disk\n", dsf);
		graceful_exit();
	} else if (dsf < MINIMUM_DISK_SPACE_FREE_BEFORE_SHOWING_AN_ERROR) {
		fprintf(error, "ERROR:  %s bytes free on disk\n", insert_interstitial_commas(dsf).c_str());
		//fprintf(error, "ERROR:  %llu bytes free on disk\n", dsf);
	} else if (dsf < MINIMUM_DISK_SPACE_FREE_BEFORE_SHOWING_A_WARNING) {
		fprintf(warning, "WARNING:  %s bytes free on disk\n", insert_interstitial_commas(dsf).c_str());
		//fprintf(warning, "WARNING:  %llu bytes free on disk\n", dsf);
	}
	return dsf;
}
Example #11
0
void individual_spawn(
        individual_s * const individual )
{
    if( individual == NULL )
    {
        fprintf( stderr, "bad parameter in individual_spawn\n");
        graceful_exit( EXIT_FAILURE );
    }

    individual->tree_root_node = node_alloc();
    individual->fitness = 0;
    individual->tree_node_count = 1;
    individual->tree_nonterminal_count = 0;
    individual->tree_terminal_count = 0;

    node_s *parent = NULL;
    unsigned long current_depth = 0;

    generate_full_tree(
            individual->tree_root_node,
            current_depth,
            parent );
}
Example #12
0
void
create_config ()
{
    FILE *config_file = NULL;
    int tmp;

    if (!globalconfig.allow_registration) globalconfig.allow_registration = 1;
    globalconfig.menulist = NULL;
    globalconfig.banner_var_list = NULL;
    globalconfig.locale = NULL;
    globalconfig.defterm = NULL;

    globalconfig.shed_uid = (uid_t)-1;
    globalconfig.shed_gid = (gid_t)-1;

    globalconfig.sortmode = SORTMODE_USERNAME;
    globalconfig.utf8esc = 0;
    globalconfig.flowctrl = -1; /* undefined, don't touch it */

    if (config)
    {
        if ((config_file = fopen(config, "r")) != NULL)
        {
            yyin = config_file;
            yyparse();
            fclose(config_file);
            free (config);
        }
        else
        {
            fprintf(stderr, "ERROR: can't find or open %s for reading\n", config);
            debug_write("cannot read config file");
            graceful_exit(104);
            return;
        }
    }
    else
    {
#ifdef DEFCONFIG
        config = DEFCONFIG;
        if ((config_file = fopen(DEFCONFIG, "r")) != NULL)
        {
            yyin = config_file;
            yyparse();
            fclose(config_file);
        } else {
            fprintf(stderr, "ERROR: can't find or open %s for reading\n", config);
            debug_write("cannot read default config file");
            graceful_exit(105);
            return;
        }
#else
        num_games = 0;
        myconfig = calloc(1, sizeof(myconfig[0]));
        myconfig[0] = &defconfig;
        return;
#endif
    }

    if (!myconfig) /* a parse error occurred */
    {
        fprintf(stderr, "ERROR: configuration parsing failed\n");
        debug_write("config file parsing failed");
        graceful_exit(113);
    }

    if (!globalconfig.chroot) globalconfig.chroot = "/var/lib/dgamelaunch/";

    if (globalconfig.max == 0) globalconfig.max = 64000;
    if (globalconfig.max_newnick_len == 0) globalconfig.max_newnick_len = DGL_PLAYERNAMELEN;
    if (!globalconfig.dglroot) globalconfig.dglroot = "/dgldir/";
    if (!globalconfig.banner)  globalconfig.banner = "/dgl-banner";

#ifndef USE_SQLITE3
    if (!globalconfig.passwd) globalconfig.passwd = "/dgl-login";
#else
    if (!globalconfig.passwd) globalconfig.passwd = USE_SQLITE_DB;
#endif
    if (!globalconfig.lockfile) globalconfig.lockfile = "/dgl-lock";
    if (!globalconfig.shed_user && globalconfig.shed_uid == (uid_t)-1)
    {
        struct passwd *pw;
        if ((pw = getpwnam("games")))
            globalconfig.shed_uid = pw->pw_uid;
        else
            globalconfig.shed_uid = 5; /* games uid in debian */
    }

    if (!globalconfig.shed_group && globalconfig.shed_gid == (gid_t)-1)
    {
        struct group *gr;
        if ((gr = getgrnam("games")))
            globalconfig.shed_gid = gr->gr_gid;
        else
            globalconfig.shed_gid = 60; /* games gid in debian */
    }

}
Example #13
0
int
dgl_exec_cmdqueue(struct dg_cmdpart *queue, int game, struct dg_user *me)
{
    int i;
    struct dg_cmdpart *tmp = queue;
    char *p1;
    char *p2;
    int played = 0;

    if (!queue) return 1;

    p1 = (char *)malloc(1024);
    p2 = (char *)malloc(1024);

    if (!p1 || !p2) return 1;

    return_from_submenu = 0;

    while (tmp && !return_from_submenu) {
        if (tmp->param1) strcpy(p1, dgl_format_str(game, me, tmp->param1, NULL));
        if (tmp->param2) strcpy(p2, dgl_format_str(game, me, tmp->param2, NULL));

        switch (tmp->cmd) {
        default:
            break;
        case DGLCMD_RAWPRINT:
            if (p1) fprintf(stdout, "%s", p1);
            break;
        case DGLCMD_MKDIR:
            if (p1 && (access(p1, F_OK) != 0)) mkdir(p1, 0755);
            break;
        case DGLCMD_UNLINK:
            if (p1 && (access(p1, F_OK) == 0)) unlink(p1);
            break;
        case DGLCMD_CHDIR:
            if (p1) {
                if (chdir(p1) == -1) {
                    debug_write("chdir-command failed");
                    graceful_exit(123);
                }
            }
            break;
        case DGLCMD_IF_NX_CP:
            if (p1 && p2) {
                FILE *tmpfile;
                tmpfile = fopen(p2, "r");
                if (tmpfile) {
                    fclose(tmpfile);
                    break;
                }
            }
        /* else fall through to cp */
        case DGLCMD_CP:
            if (p1 && p2) {
                FILE *cannedf, *newfile;
                char buf[1024];
                size_t bytes;
                /* FIXME: use nethack-themed error messages here, as per write_canned_rcfile() */
                if (!(cannedf = fopen (p1, "r"))) break;
                if (!(newfile = fopen (p2, "w"))) break;
                while ((bytes = fread (buf, 1, 1024, cannedf)) > 0) {
                    if (fwrite (buf, 1, bytes, newfile) != bytes) {
                        if (ferror (newfile)) {
                            fclose (cannedf);
                            fclose (newfile);
                            break;
                        }
                    }
                }
                fclose (cannedf);
                fclose (newfile);
                chmod (p2, default_fmode);
            }
            break;
        case DGLCMD_EXEC:
            if (p1 && p2) {
                pid_t child;
                char *myargv[3];

                myargv[0] = p1;
                myargv[1] = p2;
                myargv[2] = 0;

                clear();
                refresh();
                endwin();
                idle_alarm_set_enabled(0);
                child = fork();
                if (child == -1) {
                    perror("fork");
                    debug_write("exec-command fork failed");
                    graceful_exit(114);
                } else if (child == 0) {
                    execvp(p1, myargv);
                    exit(0);
                } else
                    waitpid(child, NULL, 0);
                idle_alarm_set_enabled(1);
                initcurses();
                check_retard(1);
            }
            break;
        case DGLCMD_SETENV:
            if (p1 && p2) mysetenv(p1, p2, 1);
            break;
        case DGLCMD_CHPASSWD:
            if (loggedin) changepw(1);
            break;
        case DGLCMD_CHMAIL:
            if (loggedin) change_email();
            break;
        case DGLCMD_WATCH_MENU:
            inprogressmenu(-1);
            break;
        case DGLCMD_LOGIN:
            if (!loggedin) loginprompt(0);
            if (loggedin) runmenuloop(dgl_find_menu(get_mainmenu_name()));
            break;
        case DGLCMD_REGISTER:
            if (!loggedin && globalconfig.allow_registration) newuser();
            break;
        case DGLCMD_QUIT:
            debug_write("command: quit");
            graceful_exit(0);
        /* break; */
        case DGLCMD_SUBMENU:
            if (p1)
                runmenuloop(dgl_find_menu(p1));
            break;
        case DGLCMD_RETURN:
            return_from_submenu = 1;
            break;
        case DGLCMD_PLAY_IF_EXIST:
            if (!(loggedin && me && p1 && p2)) break;
            {
                FILE *tmpfile;
                tmpfile = fopen(p2, "r");
                if (tmpfile) {
                    fclose(tmpfile);
                } else break;
            }
        /* else fall through to playgame */
        case DGLCMD_PLAYGAME:
            if (loggedin && me && p1 && !played) {
                int userchoice, i;
                char *tmpstr;
                for (userchoice = 0; userchoice < num_games; userchoice++) {
                    if (!strcmp(myconfig[userchoice]->game_id, p1) || !strcmp(myconfig[userchoice]->game_name, p1) || !strcmp(myconfig[userchoice]->shortname, p1)) {
                        if (purge_stale_locks(userchoice)) {
                            if (myconfig[userchoice]->rcfile) {
                                if (access (dgl_format_str(userchoice, me, myconfig[userchoice]->rc_fmt, NULL), R_OK) == -1)
                                    write_canned_rcfile (userchoice, dgl_format_str(userchoice, me, myconfig[userchoice]->rc_fmt, NULL));
                            }

                            setproctitle("%s [playing %s]", me->username, myconfig[userchoice]->shortname);

                            clear();
                            refresh();
                            endwin ();

                            /* first run the generic "do these when a game is started" commands */
                            dgl_exec_cmdqueue(globalconfig.cmdqueue[DGLTIME_GAMESTART], userchoice, me);
                            /* then run the game-specific commands */
                            dgl_exec_cmdqueue(myconfig[userchoice]->cmdqueue, userchoice, me);

                            /* fix the variables in the arguments */
                            for (i = 0; i < myconfig[userchoice]->num_args; i++) {
                                tmpstr = strdup(dgl_format_str(userchoice, me, myconfig[userchoice]->bin_args[i], NULL));
                                free(myconfig[userchoice]->bin_args[i]);
                                myconfig[userchoice]->bin_args[i] = tmpstr;
                            }

                            signal(SIGWINCH, SIG_DFL);
                            signal(SIGINT, SIG_DFL);
                            signal(SIGQUIT, SIG_DFL);
                            signal(SIGTERM, SIG_DFL);
                            idle_alarm_set_enabled(0);
                            /* launch program */
                            ttyrec_main (userchoice, me->username,
                                         dgl_format_str(userchoice, me, myconfig[userchoice]->ttyrecdir, NULL),
                                         gen_ttyrec_filename());
                            idle_alarm_set_enabled(1);
                            played = 1;
                            /* lastly, run the generic "do these when a game is left" commands */
                            signal (SIGHUP, catch_sighup);
                            signal (SIGINT, catch_sighup);
                            signal (SIGQUIT, catch_sighup);
                            signal (SIGTERM, catch_sighup);
                            signal(SIGWINCH, sigwinch_func);

                            dgl_exec_cmdqueue(myconfig[userchoice]->postcmdqueue, userchoice, me);

                            dgl_exec_cmdqueue(globalconfig.cmdqueue[DGLTIME_GAMEEND], userchoice, me);

                            setproctitle ("%s", me->username);
                            initcurses ();
                            check_retard(1); /* reset retard counter */
                        }
                        break;
                    }
                }
            }
            break;
        }
        tmp = tmp->next;
    }

    free(p1);
    free(p2);

    return 0;
}
Example #14
0
void individual_crossover(
        individual_s * const individual_a,
        individual_s * const individual_b )
{
    if( (individual_a == NULL) || (individual_b == NULL) )
    {
        fprintf( stderr, "bad parameter in individual_crossover\n" );
        graceful_exit( EXIT_FAILURE );
    }

    node_s *temp = NULL;

    temp = node_alloc();

    node_s *crossover_node_1 = NULL;
    node_s *crossover_node_2 = NULL;

    unsigned long step_range = 0;

    GLOBAL_LAST_STEP = 0;
    GLOBAL_STEP_COUNT = 0;

    step_range = individual_a->tree_terminal_count - 1;

    if( random_unsigned_long( 100 ) < 90 )
    {
        GLOBAL_LAST_STEP
                = (int)random_unsigned_long_in_range( 2, step_range );

        node_walk_nonterminals( individual_a->tree_root_node, &crossover_node_1 );
    }
    else
    {
        GLOBAL_LAST_STEP
                = (int)random_unsigned_long_in_range( 2, step_range );

        node_walk_terminals( individual_a->tree_root_node, &crossover_node_1 );
    }

    GLOBAL_STEP_COUNT = 0;

    step_range = individual_b->tree_nonterminal_count - 1;

    if( random_unsigned_long( 100 ) < 90 )
    {
        GLOBAL_LAST_STEP
                = (int)random_unsigned_long_in_range( 2, step_range );

        node_walk_nonterminals( individual_b->tree_root_node, &crossover_node_2 );
    }
    else
    {
        GLOBAL_LAST_STEP
                = (int)random_unsigned_long_in_range( 2, step_range );

        node_walk_terminals( individual_b->tree_root_node, &crossover_node_2 );
    }

    if( crossover_node_1 == NULL )
    {
        fprintf( stderr,
                "bad crossover_node_1 pointer in individual_crossover\n" );
        graceful_exit( EXIT_FAILURE );
    }

    node_copy( crossover_node_1, temp, crossover_node_1->parent );

    if( crossover_node_2 == NULL )
    {
        fprintf( stderr, "bad "
                "crossover_node_2 pointer in individual_crossover\n" );
        graceful_exit( EXIT_FAILURE );
    }

    node_copy( crossover_node_2, crossover_node_1, crossover_node_2->parent );

    node_copy( temp, crossover_node_2, temp->parent );

    crossover_node_1 = NULL;
    crossover_node_2 = NULL;

    node_free( &temp );
}
Example #15
0
int nrnopt_parse(int argc, const char* argv[]) {
    opt = new ez::ezOptionParser;

    for (int i = 0; param_int_args[i].names; ++i) {
        struct param_int& p = param_int_args[i];
        nrnopt_add_int(p.names, p.usage, p.dflt, p.low, p.high);
    }

    for (int i = 0; param_str_args[i].names; ++i) {
        struct param_str& p = param_str_args[i];
        nrnopt_add_str(p.names, p.usage, p.dflt);
    }

    for (int i = 0; param_dbl_args[i].names; ++i) {
        struct param_dbl& p = param_dbl_args[i];
        nrnopt_add_dbl(p.names, p.usage, p.dflt, p.low, p.high);
    }

    for (int i = 0; param_flag_args[i].names; ++i) {
        struct param_flag& p = param_flag_args[i];
        nrnopt_add_flag(p.names, p.usage);
    }

    // note earliest takes precedence.

    // first the command line arguments
    opt->parse(argc, argv);

    // then any specific configuration files mentioned in the command line
    if (opt->isSet("--read-config")) {
        // Import one or more files that use # as comment char.
        std::vector<std::vector<std::string> > files;
        opt->get("--read-config")->getMultiStrings(files);

        for (size_t j = 0; j < files.size(); ++j) {
            if (!opt->importFile(files[j][0].c_str(), '#')) {
                if (nrnmpi_myid == 0)
                    std::cerr << "ERROR: Failed to read configuration file " << files[j][0]
                              << std::endl;
                graceful_exit(1);
            }
        }
    }

    std::string usage;
    std::vector<std::string> badOptions;

    if (!opt->gotExpected(badOptions)) {
        for (size_t i = 0; i < badOptions.size(); ++i) {
            if (nrnmpi_myid)
                std::cerr << "ERROR: Got unexpected number of arguments for option "
                          << badOptions[i] << ".\n\n";
        }

        opt->getUsage(usage);
        if (nrnmpi_myid == 0)
            std::cout << usage;
        graceful_exit(1);
    }

    if (opt->isSet("-h")) {
        opt->getUsage(usage);
        if (nrnmpi_myid == 0)
            std::cout << usage;
        graceful_exit(0);
    }

    if (opt->firstArgs.size() > 1 || opt->lastArgs.size() > 0 || opt->unknownArgs.size() > 0) {
        std::cerr << "ERROR: Unknown arguments"
                  << "\n";
        for (size_t i = 1; i < opt->firstArgs.size(); ++i) {
            if (nrnmpi_myid == 0)
                std::cerr << "   " << opt->firstArgs[i]->c_str() << "\n";
        }
        for (size_t i = 0; i < opt->unknownArgs.size(); ++i) {
            if (nrnmpi_myid == 0)
                std::cerr << "   " << opt->unknownArgs[i]->c_str() << "\n";
        }
        for (size_t i = 0; i < opt->lastArgs.size(); ++i) {
            if (nrnmpi_myid == 0)
                std::cerr << "   " << opt->lastArgs[i]->c_str() << "\n";
        }
        graceful_exit(1);
    }

    std::vector<std::string> badArgs;
    if (!opt->gotValid(badOptions, badArgs)) {
        for (size_t i = 0; i < badOptions.size(); ++i) {
            if (nrnmpi_myid == 0)
                std::cerr << "ERROR: Got invalid argument \"" << badArgs[i] << "\" for option "
                          << badOptions[i] << ".\n";
        }
        graceful_exit(1);
    }

    if (opt->isSet("--write-config")) {
        std::string file;
        opt->get("--write-config")->getString(file);
        // Exports all options if second param is true; unset options will just use their default
        // values.
        if (!opt->exportFile(file.c_str(), true)) {
            if (nrnmpi_myid == 0)
                std::cerr << "ERROR: Failed to write to configuration file " << file.c_str()
                          << std::endl;
            graceful_exit(1);
        }
    }

    if (opt->isSet("--show")) {
        nrnopt_show();
    }

    return 0;
}
Example #16
0
int main(int argc, const char *argv[]) {
	// Pick up configuration parameters
	boost::program_options::variables_map vm;

	bool bTest, bBuild, bPackage;
	bTest = bBuild = bPackage = false;
	unsigned int iLogRotationSize;
	std::string sWorkingDir;
	std::string sStageDir;
	std::string sInstallPrefix;
	std::string sPackageName;
	std::string sPackageControlFile;
	std::string sArchitecture;
	std::string sSection;
	std::string sCfgfile;
	std::string sRosVersion;
	std::string sPriority;
	std::string sLogFile;
	std::string sLogFilter;
	std::string sLogFormat;
	std::string sDebianLocation;
	std::string sDebianType;
	std::string sDBHost;
	std::string sDBDatabase;
	uint32_t uiDBPort;
	std::string sDBUser;
	std::string sDBPassword;

	boost::filesystem::path idir;
	// capture the directory from which urpackager was run.
	// we return the user to this directory when we exit.
	idir = boost::filesystem::initial_path();

	// work is run out of the users home directory
	sWorkingDir = getenv("HOME");
	if (sWorkingDir.empty()) // not a  popular linux version configuration
		sWorkingDir = getenv("USERPROFILE");
	if (sWorkingDir.empty()) {
		std::cout << "The user running this utility must have a home directory" << std::endl;
		return (ERROR_FILESYSTEM);
	}

	// If this is the first time run, configuration file and control files will not exist
	sWorkingDir += "/.urpackager";
	boost::filesystem::path wdir(sWorkingDir);
	if (!boost::filesystem::is_directory(wdir)) { // First time the utility was run by this user.
		if (!boost::filesystem::create_directory(wdir)) {
			std::cout << "Unable to write to the user's home directory" << std::endl;
			return (ERROR_FILESYSTEM);
		}
		boost::filesystem::current_path(wdir);
		boost::filesystem::create_directory("./pkgcontrol");
		boost::filesystem::create_directory("./log");
		urpackagerConfFileCreate();
		std::cout << "This is the first time you have run \"urpackager.\"" << std::endl;
		std::cout << "Edit the file '~/.urpackager/urpackager.conf'" << std::endl;
		return (EXEC_SUCCESS);
	}
	boost::filesystem::current_path(wdir);

	// get run parameters
	try {
		/** Define and parse the program options */
		boost::program_options::options_description generic("Generic Options", 255); // command line only options
		generic.add_options()
				("help,h", "Print help messages")
				("version,v", "Version 1.0.0");

		boost::program_options::options_description config("Configuration Options"); // command line or configuration file and environment
		config.add_options()
		("package", boost::program_options::value<std::string>(),
				"The name of the package for which to create a debian")
		("architecture", boost::program_options::value<std::string>(),
				"Architecture for which you wish to create a debian file")
		("section", boost::program_options::value<std::string>()->default_value("amd64"),
				"repository section for which you wish to create a debian file")
		("test", boost::program_options::value<bool>()->default_value(false),
				"prints out variables but does no work")
		("stagedir", boost::program_options::value<std::string>()->default_value("unique_path"),
				"The directory under which the debian manifest will be temporarily created")
		("installprefix", boost::program_options::value<std::string>()->default_value("/opt/magni/v4"),
				"Prefix directory into which files will be (default) installed")
		("config", boost::program_options::value<std::string>()->default_value("./urpackager.conf"),
				"The configuration file")
		("log.file", boost::program_options::value<std::string>()->default_value("./log/urpackager.log"),
				"The log file")
		("log.filter", boost::program_options::value<std::string>()->default_value("INFO"),
				"The log level")
		("log.rotationsize", boost::program_options::value<int>()->default_value(100),
				"The maximum size for the log file in MB")
		("log.format", boost::program_options::value<std::string>()->default_value("[%TimeStamp%]: %Message%"),
				"The format log messages take")
		("ros.version", boost::program_options::value<std::string>()->default_value("indigo"),
				"The version of ROS this build - appended to <run_depend> package names")
		("debian.type", boost::program_options::value<std::string>()->default_value("deb"),
				"Package either a binary (type = \"deb\") or a micro binary (type = \"udeb\")")
		("debian.location", boost::program_options::value<std::string>(),
				"Directory into which to place the debian file")
    ("database.host", boost::program_options::value<std::string>(),
	      "The host where the urpackage db is running")
    ("database.database", boost::program_options::value<std::string>(),
        "The mysql schema")
    ("database.port", boost::program_options::value<int>(),
        "The port on which the database is listening")
    ("database.user", boost::program_options::value<std::string>(),
        "The user of the database")
    ("database.password", boost::program_options::value<std::string>(),
        "Password to log into the database");
		boost::program_options::options_description hidden("Hidden"); // command line or configuration file/environment but not shown

		hidden.add_options()("administrator", boost::program_options::value<std::string>(),
				"Administration capabilities");

		boost::program_options::options_description cmdline_options;
		cmdline_options.add(generic).add(config).add(hidden);

		boost::program_options::options_description cfgfile_options;
		cfgfile_options.add(config).add(hidden);

		boost::program_options::options_description visible("Allowed options");
		visible.add(generic).add(config);

    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, cmdline_options), vm); // can throw

		/* --help option */
		if (vm.count("help")) {
			std::cout << "Foo help...." << std::endl
					<< config << std::endl;
			graceful_exit(idir, EXEC_SUCCESS);
		}

		if (vm.count("version")) {
			std::cout << "urpackager Version 1.0.0" << std::endl
					<< config << std::endl;
			graceful_exit(idir, EXEC_SUCCESS);
		}

		if (vm.count("package")) {
			sPackageName = vm["package"].as<std::string>();
		}

		if (vm.count("architecture")) {
			sArchitecture = vm["architecture"].as<std::string>();
		}

		if (vm.count("section")) {
			sSection = vm["section"].as<std::string>();
		}

		if (vm.count("test")) {
			bTest = vm["test"].as<bool>();
		}

		if (vm.count("stagedir")) {
			sStageDir = vm["stagedir"].as<std::string>();
		}

		if (vm.count("installprefix")) {
			sInstallPrefix = vm["installprefix"].as<std::string>();
		}

		if (vm.count("config"))
			sCfgfile = (const std::string&) vm["config"].as<std::string>();

		std::ifstream cfgfile(sCfgfile.c_str(), std::ios::in);
		if (cfgfile.fail())
			std::cout << "Config file failed to open" << std::endl;

		boost::program_options::store(parse_config_file(cfgfile, cfgfile_options, true), vm);
		cfgfile.close();

		boost::program_options::notify(vm); // throws on error, so do after help in case
		// there are any problems
	} catch (boost::program_options::error& e) {
		std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
		graceful_exit(idir, ERROR_COMMAND_LINE);
	}

	try {
		if (vm.count("log.file"))
			sLogFile = (const std::string&) vm["log.file"].as<std::string>();

		if (vm.count("log.filter"))
			sLogFilter = (const std::string&) vm["log.filter"].as<std::string>();

		if (vm.count("log.rotationsize"))
			iLogRotationSize = (int) vm["log.rotationsize"].as<int>();

		if (vm.count("log.format"))
			sLogFormat = (const std::string&) vm["log.format"].as<std::string>();

		if (vm.count("debian.location"))
			sDebianLocation = (const std::string&) vm["debian.location"].as<std::string>();

		if (vm.count("debian.type"))
			sDebianType = (const std::string&) vm["debian.type"].as<std::string>();

		if (vm.count("ros.version"))
			sRosVersion = (const std::string&) vm["ros.version"].as<std::string>();

		if (sPackageName.empty()) {
			std::cout << "Execution of this utility requires a package name" << std::endl;
			graceful_exit(idir, ERROR_COMMAND_LINE);
		}

		if (sArchitecture.empty()) {
			sPackageControlFile = sWorkingDir + "/pkgcontrol/"
					              + sPackageName + ".pkgctl";
		} else {
			sPackageControlFile = sWorkingDir + "/pkgcontrol/" + sPackageName +
					              "." + sArchitecture + ".pkgctl";
		}
    if (vm.count("database.host"))
      sDBHost = (const std::string&) vm["database.host"].as<std::string>();

    if (vm.count("database.database"))
      sDBDatabase = (const std::string&) vm["database.database"].as<std::string>();

    if (vm.count("database.port"))
      uiDBPort = (unsigned int) vm["database.port"].as<int>();

    if (vm.count("database.user"))
      sDBUser = (const std::string&) vm["database.user"].as<std::string>();

    if (vm.count("database.password"))
      sDBPassword = (const std::string&) vm["database.password"].as<std::string>();

	} catch (std::exception& e) {
		std::cerr << "Unhandled Exception reached after applying all options: "
				<< e.what() << ", application will now exit" << std::endl;
		graceful_exit(idir, ERROR_UNHANDLED_EXCEPTION);
	}

	/* Ready to run the utility
	 *
	 */
	ur::PackageControl pc(sPackageControlFile);
	pc.readControlFile();
	pc.setStageBase(sStageDir);
	ur::PackageXML px;
	px.readFile(pc.getPackageXML());

	if(bTest) {
		graceful_exit(idir, EXEC_SUCCESS);
	}

	ur::DebianPackage pkg(pc, px,
			              sArchitecture,
					      sSection,
					      sDebianType,
					      sDebianLocation,
					      sDBHost,
					      sDBDatabase,
					      sDBUser,
					      sDBPassword,
					      uiDBPort);

	pkg.createStageDirectory();
	pkg.stageManifest();
	pkg.writeDebianControleFile();
	pkg.generateChecksums();
	pkg.generateDebianPackage();
	pkg.moveDebianPackage();
	pkg.deleteStaging();

	return (EXEC_SUCCESS);
}