Example #1
0
/*
 * HEADER:100:fix_CFSv2_fcst:misc:3:fixes CFSv2 monthly fcst  X=daily or 00/06/12/18 Y=pert no. Z=number ens fcsts  v1.0
 */
int f_fix_CFSv2_fcst(ARG3) {

    int subcenter, n_time_ranges, fcst_time_0, fcst_time_1, i;
    int dtime, unit, id;

    int ref_year, ref_month, ref_day, ref_hour, ref_minute, ref_second;
    int fcst0_year, fcst0_month, fcst0_day, fcst0_hour, fcst0_minute, fcst0_second;
    int fcst1_year, fcst1_month, fcst1_day, fcst1_hour, fcst1_minute, fcst1_second;

    static unsigned char new_sec4[61];

    struct local_struct {
        int fixed;			// number of fields processed
	int dt;				// dt either 6 or 24
	int hour0;			// initial hour
        int pert;			// perturbation no, 0 = ctl
        int num_ensemble_members;
    };
    struct local_struct *save;

    if (mode == -1) {
	*local = save = (struct local_struct *)malloc( sizeof(struct local_struct));
	save->fixed = 0;
	save->dt = 24;
	if (strcmp(arg1,"daily") == 0) {
	    save->dt = 6;
	    save->hour0 = 0;
	}
	else if (strcmp(arg1,"00") == 0) {
	    save->hour0 = 0;
	}
	else if (strcmp(arg1,"06") == 0) {
	    save->hour0 = 6;
	}
	else if (strcmp(arg1,"12") == 0) {
	    save->hour0 = 12;
	}
	else if (strcmp(arg1,"18") == 0) {
	    save->hour0 = 1;
	}
	else fatal_error("fix_CFSv2_fcst: bad arg %s, wanted daily,00,06,12 or 18",arg1);

	save->pert = atoi(arg2);
	save->num_ensemble_members = atoi(arg2);

    }
    save = *local;

    if (mode == -2) sprintf(inv_out,"fix_CFSRv2_fcst %d fields fixed" , save->fixed);

    if (mode < 0) return 0;

    // only process NCEP CFSv2 monthly forecasts

    // must be NCEP generated
    if (GB2_Center(sec) != NCEP) return 0;

    // subcenter should be 0, 1 (reanalysis), 3 (EMC) or 4 (NCO)
    subcenter = GB2_Subcenter(sec);
    if (subcenter != 0 && subcenter != 1 && subcenter != 3 && subcenter != 4) return 0;

    // must have process id = 82 or 98
    id = analysis_or_forecast_generating_process_identifier(sec);
    if (id != 82 && id != 98) return 0;

    // product defn table must be 8 (fcst average)
    if ( code_table_4_0(sec) != 8) return 0;

    // n_time_ranges should be 1
    if ( (n_time_ranges = sec[4][41]) != 1) {
        fprintf(stderr,"unexected CFSv2 type forecast field .. pdt=8, n=%d\n", n_time_ranges);
	return 0;
    }

    // forecast time units should be months
    if (sec[4][17] != 3 || sec[4][48] != 3) return 0;

    fcst_time_0  = int4(sec[4]+18);
    fcst_time_1  = int4(sec[4]+49) + fcst_time_0;

    // get reference time
    reftime(sec, &ref_year, &ref_month, &ref_day, &ref_hour, &ref_minute, &ref_second);

    if (ref_minute != 0 || ref_second != 0) {
        fprintf(stderr,"unexected CFSv2 minute/second value != 0\n");
	return 0;
    }

    if (fcst_time_0 != 0) {	// start at day=1 hour=save->hour0 of proper month
	fcst0_year = ref_year;
	fcst0_month = ref_month + fcst_time_0;
        if (fcst0_month > 12) {
	    i = (fcst0_month - 1) / 12;
	    fcst0_year += i;
	    fcst0_month -= (i*12);
	}
	fcst0_day = 1;
	fcst0_hour = save->hour0;
	fcst0_minute = 0;
	fcst0_second= 0;
   }
   else {			// start at current month 
	fcst0_year = ref_year;
	fcst0_month = ref_month;
	fcst0_day = ref_day;
	fcst0_hour = ref_hour;
	fcst0_minute = ref_minute;
	fcst0_second= ref_second;
	if (save->dt == 24) {
	    i = save->hour0 - fcst0_hour;
	    if (i < 0) i += 24;
	    add_time(&fcst0_year, &fcst0_month, &fcst0_day, &fcst0_hour, &fcst0_minute, &fcst0_second, i, HOUR);
	}
    }

    sub_time(fcst0_year, fcst0_month, fcst0_day, fcst0_hour, fcst0_minute, fcst0_second, 
		ref_year, ref_month, ref_day, ref_hour, ref_minute, ref_second,
		&dtime, &unit);
    // set forecast time.
    if (dtime == 0) unit = MONTH;
    sec[4][17] = unit;
    int_char(dtime, sec[4]+18);

    if (fcst_time_1 == 0) fatal_error("fix-CFSv2_fcst: unexpected end_ft","");

    if (save->dt == 6) {		// ends at 18Z of last day of month
	fcst1_year = ref_year;
	fcst1_month = ref_month + fcst_time_1-1;
	if (fcst1_month > 12) {
            i = (fcst1_month - 1) / 12;
            fcst1_year += i;
            fcst1_month -= (i*12);
        }
        fcst1_day = num_days_in_month(fcst1_year, fcst1_month);
        fcst1_hour = 18;
        fcst1_minute = 0;
        fcst1_second= 0;

	// time increment = 6 hours
	sec[4][53] = (unsigned char) HOUR;
	int_char(6, sec[4]+54);
    }
    else {
	fcst1_year = ref_year;
	fcst1_month = ref_month + fcst_time_1-1;
	if (fcst1_month > 12) {
            i = (fcst1_month - 1) / 12;
            fcst1_year += i;
            fcst1_month -= (i*12);
        }
        fcst1_day = num_days_in_month(fcst1_year, fcst1_month);
        fcst1_hour = save->hour0;
        fcst1_minute = 0;
        fcst1_second= 0;

	// time increment = 24 hours
	sec[4][53] = (unsigned char)  HOUR;
	int_char(24, sec[4]+54);
    }

    // find stat processing time
    sub_time(fcst1_year, fcst1_month, fcst1_day, fcst1_hour, fcst1_minute, fcst1_second, 
		fcst0_year, fcst0_month, fcst0_day, fcst0_hour, fcst0_minute, fcst0_second, 
		&dtime, &unit);

    // change length of processing
    sec[4][48] = (unsigned char) unit;
    int_char(dtime, sec[4]+49);

// fprintf(stderr,"length of processing %d unit (%d)\n", dtime, unit);

    // save end-of-processing time
    save_time(fcst1_year, fcst1_month, fcst1_day, fcst1_hour, fcst1_minute, fcst1_second, sec[4]+34);

    // make sure that some basic info is correct
    sec[4][47] = 2;	// fcst_time++


    // now to add ensemble information
    for (i = 0; i < 34; i++) new_sec4[i] = sec[4][i];
    for (i = 34; i <= 57; i++) new_sec4[i+3] = sec[4][i];

    uint_char(61, new_sec4);			// length of new sec[4[
    new_sec4[7] = 0;				// pdt = 11
    new_sec4[8] = 11;

    // add perturbation info
    if (save->pert == 0) {			// pert == 0 means control forecast
        new_sec4[34] = 0;
        new_sec4[35] = 0;
    }
    else { 
        new_sec4[34] = 3;
        new_sec4[35] = save->pert;
    }
    new_sec4[35] = save->num_ensemble_members;
   
    sec[4] = new_sec4;
 
    save->fixed = save->fixed + 1;
    return 0;
}
int
parent(pid_t pid, unsigned long delay)
{
	pfmlib_input_param_t inp;
	pfmlib_output_param_t outp;
	pfarg_context_t ctx[1];
	pfarg_reg_t pc[NUM_PMCS];
	pfarg_reg_t pd[NUM_PMDS];
	pfarg_load_t load_args;
	struct pollfd pollfd;
	pfm_msg_t msg;
	unsigned int i, num_counters;
	int status, ret;
	int ctx_fd;
	char name[MAX_EVT_NAME_LEN];


	memset(pc, 0, sizeof(ctx));
	memset(pd, 0, sizeof(ctx));
	memset(ctx, 0, sizeof(ctx));
	memset(&inp,0, sizeof(inp));
	memset(&outp,0, sizeof(outp));
	memset(&load_args,0, sizeof(load_args));

	pfm_get_num_counters(&num_counters);

	if (pfm_get_cycle_event(&inp.pfp_events[0]) != PFMLIB_SUCCESS)
		fatal_error("cannot find cycle event\n");

	if (pfm_get_inst_retired_event(&inp.pfp_events[1]) != PFMLIB_SUCCESS)
		fatal_error("cannot find inst retired event\n");
	i = 2;

	if (num_counters < i) {
		i = num_counters;
		printf("too many events provided (max=%d events), using first %d event(s)\n", num_counters, i);
	}

	/*
	 * set the privilege mode:
	 * 	PFM_PLM3 : user level
	 * 	PFM_PLM0 : kernel level
	 */
	inp.pfp_dfl_plm   = PFM_PLM3;

	/*
	 * how many counters we use
	 */
	inp.pfp_event_count = i;

	/*
	 * let the library figure out the values for the PMCS
	 */
	if ((ret=pfm_dispatch_events(&inp, NULL, &outp, NULL)) != PFMLIB_SUCCESS) {
		fatal_error("cannot configure events: %s\n", pfm_strerror(ret));
	}
	/*
	 * now create a context. we will later attach it to the task we are creating.
	 */
	if (perfmonctl(0, PFM_CREATE_CONTEXT, ctx, 1) == -1) {
		if (errno == ENOSYS) {
			fatal_error("Your kernel does not have performance monitoring support!\n");
		}
		fatal_error("Can't create PFM context %s\n", strerror(errno));
	}
	/*
	 * extract the identifier for our context
	 */
	ctx_fd = ctx[0].ctx_fd;

	/*
	 * use our file descriptor for the poll.
	 * we are interested in read events only.
	 */
	pollfd.fd     = ctx_fd;
	pollfd.events = POLLIN;


	/*
	 * Now prepare the argument to initialize the PMDs and PMCS.
	 * We must pfp_pmc_count to determine the number of PMC to intialize.
	 * We must use pfp_event_count to determine the number of PMD to initialize.
	 * Some events causes extra PMCs to be used, so  pfp_pmc_count may be >= pfp_event_count.
	 *
	 * This step is new compared to libpfm-2.x. It is necessary because the library no
	 * longer knows about the kernel data structures.
	 */
	for (i=0; i < outp.pfp_pmc_count; i++) {
		pc[i].reg_num   = outp.pfp_pmcs[i].reg_num;
		pc[i].reg_value = outp.pfp_pmcs[i].reg_value;
	}

	/*
	 * the PMC controlling the event ALWAYS come first, that's why this loop
	 * is safe even when extra PMC are needed to support a particular event.
	 */
	for (i=0; i < inp.pfp_event_count; i++) {
		pd[i].reg_num   = pc[i].reg_num;
	}

	/*
	 * Now program the registers
	 *
	 * We don't use the save variable to indicate the number of elements passed to
	 * the kernel because, as we said earlier, pc may contain more elements than
	 * the number of events we specified, i.e., contains more thann counting monitors.
	 */

	if (perfmonctl(ctx_fd, PFM_WRITE_PMCS, pc, outp.pfp_pmc_count) == -1) {
		fatal_error("perfmonctl error PFM_WRITE_PMCS errno %d\n",errno);
	}

	if (perfmonctl(ctx_fd, PFM_WRITE_PMDS, pd, inp.pfp_event_count) == -1) {
		fatal_error("perfmonctl error PFM_WRITE_PMDS errno %d\n",errno);
	}

	ret = ptrace(PTRACE_ATTACH, pid, NULL, 0);
	if (ret == -1) {
		fatal_error("cannot attach to %d: %s\n", pid, strerror(errno));
	}

	/*
	 * wait for the child to be actually stopped
	 */
	waitpid(pid, &status, WUNTRACED);

	/*
	 * check if process exited early
	 */
	if (WIFEXITED(status)) {
		fatal_error("command process %d exited too early with status %d\n", pid, WEXITSTATUS(status));
	}

	/*
	 * the task is stopped at this point
	 */
	
	/*
	 * now we load (i.e., attach) the context to ourself
	 */
	load_args.load_pid = pid;

	if (perfmonctl(ctx_fd, PFM_LOAD_CONTEXT, &load_args, 1) == -1) {
		fatal_error("perfmonctl error PFM_LOAD_CONTEXT errno %d\n",errno);
	}

	/*
	 * activate monitoring. The task is still STOPPED at this point. Monitoring
	 * will not take effect until the execution of the task is resumed.
	 */
	if (perfmonctl(ctx_fd, PFM_START, NULL, 0) == -1) {
		fatal_error("perfmonctl error PFM_START errno %d\n",errno);
	}

	/*
	 * now resume execution of the task, effectively activating
	 * monitoring.
	 */
	ptrace(PTRACE_DETACH, pid, NULL, 0);
	printf("attached to [%d], timeout set to %lu seconds\n", pid, delay);

	/*
	 * now the task is running
	 */

	/*
	 * We cannot simply do a waitpid() because we may be attaching to a process
	 * totally unrelated to our program. Instead we use a perfmon facility that
	 * notifies us when the monitoring task is exiting.
	 *
	 * When a task with a monitoring context attached to it exits, a PFM_MSG_END
	 * is generated. It can be retrieve with a simple read() on the context's descriptor.
	 *
	 * Another reason why you might return from the read is if there was a counter
	 * overflow, unlikely in this example.
	 *
	 * To measure only for short period of time, use select or poll with a timeout,
	 * see task_attach_timeout.c
	 *
	 */
	ret = poll(&pollfd, 1, delay*1000);
	switch( ret ) {
		case -1:
			fatal_error("cannot read from descriptor: %s\n", strerror(errno));
			/* no return */
		case  1:
			/*
	 		 * there is a message, i.e., the program exited before our timeout
	 		 */
			if (ret == 1) {
				/*
		 		* extract message
		 		*/
				ret = read(ctx_fd, &msg, sizeof(msg));

				if (msg.type != PFM_MSG_END) {
					fatal_error("unexpected msg type : %d\n", msg.type);
				}
			}
			break;
		case   0:
			/*
			 * we timed out, we need to stop the task to unload
			 */
			ret = ptrace(PTRACE_ATTACH, pid, NULL, 0);
			if (ret == -1) {
				fatal_error("cannot attach to %d: %s\n", pid, strerror(errno));
			}
			/*
			 * wait for task to be actually stopped
			 */
			waitpid(pid, &status, WUNTRACED);

			/*
	 		 * check if process exited, then no need to unload
	 		 */
			if (WIFEXITED(status)) goto read_results;

			if (perfmonctl(ctx_fd, PFM_UNLOAD_CONTEXT, NULL, 0) == -1) {
				fatal_error("perfmonctl error PFM_UNLOAD_CONTEXT errno %d\n",errno);
			}

			/*
			 * let it run free again
			 */
			ptrace(PTRACE_DETACH, pid, NULL, 0);
			break;
		default:
			fatal_error("unexpected return from poll: %d\n", ret);
	}

read_results:
	/*
	 * now simply read the results.
	 */
	if (perfmonctl(ctx_fd, PFM_READ_PMDS, pd, inp.pfp_event_count) == -1) {
		fatal_error("perfmonctl error READ_PMDS errno %d\n",errno);
		return -1;
	}

	/*
	 * print the results
	 *
	 * It is important to realize, that the first event we specified may not
	 * be in PMD4. Not all events can be measured by any monitor. That's why
	 * we need to use the pc[] array to figure out where event i was allocated.
	 *
	 */
	for (i=0; i < inp.pfp_event_count; i++) {
		pfm_get_full_event_name(&inp.pfp_events[i], name, MAX_EVT_NAME_LEN);
		printf("PMD%u %20"PRIu64" %s\n",
			pd[i].reg_num,
			pd[i].reg_value,
			name);
	}
	/*
	 * free the context
	 */
	close(ctx_fd);

	return 0;
}
Example #3
0
void construct_dummies(FILE *log,rvec x[],t_nrnb *nrnb,real dt,
                       rvec *v,t_idef *idef,t_graph *graph,t_commrec *cr,
                       matrix box,t_comm_dummies *dummycomm)
{
    rvec      xd,vv;
    real      a1,b1,c1,inv_dt;
    int       i,ii,nra,nrd,tp,ftype;
    t_iatom   adum,ai,aj,ak,al;
    t_iatom   *ia;
    t_iparams *ip;

    /* Molecules always whole, but I'm not sure whether
     * the periodicity and shift are guaranteed to be consistent
     * between different nodes when running e.g. polymers in
     * parallel. In this special case we thus unshift/shift, but
     * only when necessary. This is to make sure the coordinates
     * we move don't end up a box away...
     */
    if (dummycomm) {
        unshift_self(graph,box,x);
        move_construct_x(dummycomm,x,cr);
        shift_self(graph,box,x);
    }

    ip     = idef->iparams;
    if (v)
        inv_dt = 1.0/dt;
    else
        inv_dt = 1.0;

    for(ftype=0; (ftype<F_NRE); ftype++) {
        if (interaction_function[ftype].flags & IF_DUMMY) {
            nra    = interaction_function[ftype].nratoms;
            nrd    = idef->il[ftype].nr;
            ia     = idef->il[ftype].iatoms;

            for(i=0; (i<nrd); ) {
                tp   = ia[0];
                assert(ftype == idef->functype[tp]);

                /* The dummy and constructing atoms */
                adum = ia[1];
                ai   = ia[2];
                aj   = ia[3];

                /* Constants for constructing dummies */
                a1   = ip[tp].dummy.a;

                /* Copy the old position */
                copy_rvec(x[adum],xd);

                /* Construct the dummy depending on type */
                switch (ftype) {
                case F_DUMMY2:
                    constr_dum2(x[ai],x[aj],x[adum],a1);
                    break;
                case F_DUMMY3:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    constr_dum3(x[ai],x[aj],x[ak],x[adum],a1,b1);
                    break;
                case F_DUMMY3FD:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    constr_dum3FD(x[ai],x[aj],x[ak],x[adum],a1,b1);
                    break;
                case F_DUMMY3FAD:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    constr_dum3FAD(x[ai],x[aj],x[ak],x[adum],a1,b1);
                    break;
                case F_DUMMY3OUT:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    c1 = ip[tp].dummy.c;
                    constr_dum3OUT(x[ai],x[aj],x[ak],x[adum],a1,b1,c1);
                    break;
                case F_DUMMY4FD:
                    ak = ia[4];
                    al = ia[5];
                    b1 = ip[tp].dummy.b;
                    c1 = ip[tp].dummy.c;
                    constr_dum4FD(x[ai],x[aj],x[ak],x[al],x[adum],a1,b1,c1);
                    break;
                default:
                    fatal_error(0,"No such dummy type %d in %s, line %d",
                                ftype,__FILE__,__LINE__);
                }
                if (v) {
                    /* Calculate velocity of dummy... */
                    rvec_sub(x[adum],xd,vv);
                    svmul(inv_dt,vv,v[adum]);
                }
                /* Increment loop variables */
                i  += nra+1;
                ia += nra+1;
            }
        }
    }
    if (dummycomm) {
        unshift_self(graph,box,x);
        move_dummy_xv(dummycomm,x,NULL,cr);
        shift_self(graph,box,x); /* maybe not necessary */
    }
}
/**
 * Returns 1 if the given .fst2 is OK to be used by the Locate program; 0 otherwise.
 * Conditions are:
 *
 * 1) no left recursion
 * 2) no loop that can recognize the empty word (<E> with an output or subgraph
 *    that can match the empty word).
 */
int OK_for_Locate_write_error(const VersatileEncodingConfig* vec,const char* name,char no_empty_graph_warning,U_FILE* ferr) {
int RESULT=1;
struct FST2_free_info fst2_free;
Fst2* fst2=load_abstract_fst2(vec,name,1,&fst2_free);
if (fst2==NULL) {
	fatal_error("Cannot load graph %s\n",name);
}
u_printf("Creating condition sets...\n");
GrfCheckInfo* chk=new_GrfCheckInfo(fst2);
/* Now, we look for a fix point in the condition graphs */
struct list_int* list=NULL;
/* To do that, we start by creating a list of all the graphs we are sure about */
int unknown=0;
for (int i=1;i<fst2->number_of_graphs+1;i++) {
	if (chk->graphs_matching_E[i]!=CHK_DONT_KNOW) {
		list=new_list_int(i,list);
	} else {
		unknown++;
	}
}
/* While there is something to do for E matching */
u_printf("Checking empty word matching...\n");
while (resolve_all_conditions(chk,&list,&unknown)) {}
if (chk->graphs_matching_E[1]==CHK_MATCHES_E) {
	if (!no_empty_graph_warning) {
       error("ERROR: the main graph %S recognizes <E>\n",fst2->graph_names[1]);
       if (ferr!=NULL) {
    	   u_fprintf(ferr,"ERROR: the main graph %S recognizes <E>\n",fst2->graph_names[1]);
	   }
	}
	goto evil_goto;
}
if (!no_empty_graph_warning) {
	for (int i=2;i<fst2->number_of_graphs+1;i++) {
		if (chk->graphs_matching_E[i]==CHK_MATCHES_E) {
			error("WARNING: the graph %S recognizes <E>\n",fst2->graph_names[i]);
			if (ferr!=NULL) {
				u_fprintf(ferr,"WARNING: the graph %S recognizes <E>\n",fst2->graph_names[i]);
			}
		}
	}
}
/* Now, we look for E loops and left recursions. And to do that, we need a new version
 * of the condition graphs, because a graph that does not match E would have been emptied.
 * And obviously, we can not deduce anything from an empty graph. */
rebuild_condition_graphs(chk);
u_printf("Checking E loops...\n");
if (is_any_E_loop(chk)) {
	/* Error messages have already been printed */
	goto evil_goto;
}
u_printf("Checking left recursions...\n");
if (is_any_left_recursion(chk)) {
	/* Error messages have already been printed */
	goto evil_goto;
}
evil_goto:
/* There may be something unused in the list that we need to free */
free_list_int(list);
free_GrfCheckInfo(chk);
free_abstract_Fst2(fst2,&fst2_free);
return RESULT;
}
Example #5
0
/* event parsing loop freely stolen from Zarf's glk example code */
void debug_monitor() {
    char commandbuf[256], lastcommand[256];
    char *cx, *cmd;
    int gotline, len, monitor, match;
    event_t ev;
    char *parser = "^([cfghlnoqsx])( +([0-9a-f]+))?";
    // char *parser = "\\([cghlnqsx]\\)\\( 0\\)?";
    char *matched;
    regex_t preg;
    size_t nmatch = 4;
    regmatch_t pmatch[4];
    
    monitor = TRUE;
    while(monitor) {
        glk_put_string("\nmonitor>");
        // if (cmd)
        //     strncpy(lastcommand, cmd, 256);
        glk_request_line_event(mainwin, commandbuf, 255, 0);
        gotline = FALSE;
        while (!gotline) {
            glk_select(&ev);
            if (ev.type == evtype_LineInput)
                gotline = TRUE;
        }

        len = ev.val1;
        commandbuf[len] = '\0';

        for (cx = commandbuf; *cx; cx++) { 
            *cx = glk_char_to_lower(*cx);
        }
        
        /* strip whitespace */
        for (cx = commandbuf; *cx == ' '; cx++) { };
        cmd = cx;
        for (cx = commandbuf+len-1; cx >= cmd && *cx == ' '; cx--) { };
        *(cx+1) = '\0';
        
        if (*cmd == '\0') {
            monitor = FALSE;
            continue;
        }
        
        if ((match = regcomp(&preg, parser, REG_EXTENDED | REG_ICASE)) != 0) {
            fatal_error("Bad regex\n");
        }

        if ((match = regexec(&preg, cmd, nmatch, pmatch, 0)) != 0) {
            glk_put_string("pardon? - try 'h' for help\n");
        } else {
            if(match_command("c")) {
                monitor = FALSE;
            } else if (match_command("f")) {
                match_args_and_call(debug_print_callstack, 0xffff)
            } else if (match_command("g")) {
                match_args_and_call(debug_print_global, 0xff)
            } else if (match_command("h")) {
                debug_print_help();
            } else if (match_command("l")) {
                match_args_and_call(debug_print_local, 0xff)
            } else if (match_command("n")) {
                monitor = FALSE;                
            } else if (match_command("o")) {
                match_args_and_call(debug_print_object, 1);         
            } else if (match_command("x")) {
                match_args_and_call(debug_print_memory, 0xdeadbeef)
            } else if (match_command("")) {
                match_args_and_call(debug_print_zstring, 0)
            } else if (match_command("q")) {
                fatal_error("Debugger terminated game.");
            } else if (match_command("s")) {
                debug_print_stack();
            } else if (match_command("x")) {
                match_args_and_call(debug_print_memory, 0xdeadbeef)
            }
        }
        regfree(&preg);
    }
}
Example #6
0
File: smp.c Project: zwegner/zct
/**
initialize_smp():
Initializes the smp functionality for the given number of processes.
Created 081305; last modified 103008
**/
void initialize_smp(int procs)
{
	int x;
	int y;
	int z;

	/* Set up the default signals. This is because the child processes
		inherit all of the parent's signal handlers, and we don't want that. */
	signal(SIGINT, SIG_DFL);
	signal(SIGTERM, SIG_DFL);
//	signal(SIGCHLD, SIG_IGN);

	if (smp_data != NULL)
		smp_cleanup();
	else if (atexit(smp_cleanup) == -1 || atexit(smp_cleanup_final) == -1)
	{
		smp_cleanup();
		smp_cleanup_final();
		fatal_error("fatal error: atexit failed");
	}
	zct->process_count = procs;

	/* Allocate the shared memory to the various data structures needed. */
	split_point_size = sizeof(SPLIT_POINT) * MAX_SPLIT_POINTS;
	smp_block_size = sizeof(SMP_BLOCK) * procs;
	smp_data_size = sizeof(SMP_DATA);
	split_point = (SPLIT_POINT *)shared_alloc(split_point_size);
	smp_block = (SMP_BLOCK *)shared_alloc(smp_block_size);
	smp_data = (SMP_DATA *)shared_alloc(smp_data_size);
	
#define DBG(t,s,i) do{int p;\
		print("%s: %x\n", #t, sizeof(t));\
		for (p=0;p<i;p++){\
			print("%p",&s[p]);\
			if(p>0)\
				print(" %i",((BITBOARD)&s[p])-((BITBOARD)&s[p-1]));\
				print("\n");\
		}}while(0)

	/*
	DBG(SMP_BLOCK, smp_block, procs);
	DBG(SMP_DATA, smp_data, 1);
*/
	/* Initialize the data. */
	/* SMP data */
	smp_data->return_flag = FALSE;
	/* smp blocks */
	for (x = 0; x < procs; x++)
	{
		smp_block[x].id = x;
		smp_block[x].idle = FALSE;
		smp_block[x].last_idle_time = 0;
		smp_block[x].message_count = 0;
		smp_block[x].input = 0;
		smp_block[x].output = 0;
		
		for (y = 0; y < MAX_PLY; y++)
			initialize_split_score(&smp_block[x].tree.sb_score[y]);
//		initialize_split_score(&smp_block[x].tree.split_score);

		/* The split ID is id*MAX_CPUS+board.id, so instead of calculating
			that every time we split, we just start at board.id and increment
			by MAX_CPUS. */
		smp_block[x].split_id = x;

#ifdef ZCT_WINDOWS
		_pipe(smp_block[x].wait_pipe, 8, O_BINARY);
#else
		pipe(smp_block[x].wait_pipe);
#endif
	}

	/* split points */
	for (x = 0; x < MAX_SPLIT_POINTS; x++)
	{
		split_point[x].n = x;
		split_point[x].active = FALSE;
		split_point[x].child_count = 0;
		for (y = 0; y < MAX_CPUS; y++)
		{
			split_point[x].update[y] = FALSE;
			split_point[x].is_child[y] = FALSE;
		}
	}

	/* main processor's smp info */
	board.id = 0;
	board.split_ply = board.split_ply_stack;
	board.split_ply_stack[0] = -1;
	board.split_point = board.split_point_stack;
	board.split_point_stack[0] = NULL;

	/* Initialize the spin locks. */
	LOCK_INIT(smp_data->io_lock);
	LOCK_INIT(smp_data->lock);
	for (x = 0; x < procs; x++)
	{
		LOCK_INIT(smp_block[x].lock);
		LOCK_INIT(smp_block[x].input_lock);
	}
	for (x = 0; x < MAX_SPLIT_POINTS; x++)
	{
		LOCK_INIT(split_point[x].lock);
		LOCK_INIT(split_point[x].move_lock);
	}

	/* Now start the child processes. */
	for (x = 1; x < zct->process_count; x++)
	{
		/* Child process. */
		if ((y = fork()) == 0)
		{
			board.id = x;
			idle_loop(x);
		}
		/* Parent process. */
		else
		{
			smp_block[x].pid = y;
			smp_tell(x, SMP_INIT, 0);
		}
	}

	/* Set up the signals to use for the master processor. */
	if (board.id == 0)
	{
		signal(SIGINT, smp_cleanup_sig);
		signal(SIGTERM, smp_cleanup_sig);
//	signal(SIGCHLD, smp_cleanup_sig);
	}

	/* Now that the processors are spawned, make them idle until we start
		searching. */
	stop_child_processors();
}
/*
 * Function: parse_options()
 *
 * Description:
 *  This function parse the options
 *
 * Argument:
 *   argc:  the number of argument
 *   argv:  arguments
 *  info_p: pointer to data of multicast receiver information
 *   bg_p:  pointer to the flag of working in backgrond
 *
 * Return value:
 *  None
 */
void
parse_options(int argc, char *argv[], struct mcast_rcv_info *info_p, int *bg_p)
{
	int optc;		/* option */
	unsigned long opt_ul;	/* option value in unsigned long */
	double opt_d;		/* option value in double */
	uint32_t ifindex = 0;	/* interface index where listening multicast */
	sa_family_t family = AF_UNSPEC;	/* protocol family */
	char *maddr;		/* multicast address */
	uint32_t fmode = 0;	/* filter mode */
	char *saddrs;		/* comma separated array of source addresses */
	char *portnum;		/* listen port number in character string */

	maddr = NULL;
	saddrs = NULL;
	portnum = NULL;

	while ((optc = getopt(argc, argv, "f:I:m:F:s:p:t:bdh")) != EOF) {
		switch (optc) {
		case 'f':
			if (optarg[0] == '4')
				family = PF_INET;	/* IPv4 */
			else if (optarg[0] == '6')
				family = PF_INET6;	/* IPv6 */
			else {
				fprintf(stderr,
					"protocol family should be 4 or 6.\n");
				usage(program_name, EXIT_FAILURE);
			}
			break;

		case 'I':
			ifindex = if_nametoindex(optarg);
			if (ifindex == 0) {
				fprintf(stderr,
					"specified interface is incorrect\n");
				usage(program_name, EXIT_FAILURE);
			}
			break;

		case 'm':
			maddr = strdup(optarg);
			if (maddr == NULL)
				fatal_error("strdup()");
			break;

		case 'F':
			if (strncmp(optarg, "exclude", 8) == 0)
				fmode = MCAST_EXCLUDE;
			else if (strncmp(optarg, "include", 8) == 0)
				fmode = MCAST_INCLUDE;
			else {
				fprintf(stderr,
					"specified filter mode is incorrect\n");
				usage(program_name, EXIT_FAILURE);
			}
			break;

		case 's':
			saddrs = strdup(optarg);
			if (saddrs == NULL)
				fatal_error("strdup()");
			break;

		case 'p':
			opt_ul = strtoul(optarg, NULL, 0);
			if (opt_ul < PORTNUMMIN || PORTNUMMAX < opt_ul) {
				fprintf(stderr,
					"The range of port is from %u to %u\n",
					PORTNUMMIN, PORTNUMMAX);
				usage(program_name, EXIT_FAILURE);
			}
			portnum = strdup(optarg);
			break;

		case 't':
			opt_d = strtod(optarg, NULL);
			if (opt_d < 0.0) {
				fprintf(stderr,
					"Timeout should be positive value\n");
				usage(program_name, EXIT_FAILURE);
			}
			info_p->timeout = opt_d;
			break;

		case 'b':
			*bg_p = 1;
			break;

		case 'd':
			debug = 1;
			break;

		case 'h':
			usage(program_name, EXIT_SUCCESS);
			break;

		default:
			usage(program_name, EXIT_FAILURE);
		}
	}

	if (ifindex == 0) {
		fprintf(stderr, "specified interface seems incorrect\n");
		usage(program_name, EXIT_FAILURE);
	}

	if (maddr == NULL) {
		fprintf(stderr, "multicast address is not specified\n");
		usage(program_name, EXIT_FAILURE);
	}

	if (portnum == NULL) {
		fprintf(stderr, "listening port number is not specified\n");
		usage(program_name, EXIT_FAILURE);
	}

	info_p->mainfo = get_maddrinfo(family, maddr, portnum);
	info_p->greq = create_group_info(ifindex, info_p->mainfo);
	if (saddrs) {
		if (fmode != MCAST_EXCLUDE && fmode != MCAST_INCLUDE) {
			fprintf(stderr, "filter mode is wrong\n");
			usage(program_name, EXIT_FAILURE);
		}
		info_p->gsf =
		    create_source_filter(ifindex, info_p->mainfo, fmode,
					 saddrs);
	}

	if (maddr)
		free(maddr);
	if (saddrs)
		free(saddrs);
	if (portnum)
		free(portnum);
}
Example #8
0
int f_ncep_norm(ARG1) {

    struct local_struct {
        float *val;
        int has_val;
        unsigned char *clone_sec[9];
        FILE *output;
    };
    struct local_struct *save;

    int idx, j, fhr_1, fhr_2,  dt1, dt2, new_type, is_ave;
    unsigned int i;
    float *d1, *data_tmp;

    if (mode == -1) {			// initialization
        save_translation = decode = 1;
        // 1/2015 use_scale = 0;

	// allocate static variables

        *local = save = (struct local_struct *) malloc( sizeof(struct local_struct));
        if (save == NULL) fatal_error("memory allocation f_ncep_norm","");

        if ((save->output = ffopen(arg1, file_append ? "ab" : "wb")) == NULL) {
	    fatal_error("f_ncep_norm: could not open file %s", arg1);
	}
	save->has_val = 0;
	init_sec(save->clone_sec);
	return 0;
    }

    save = (struct local_struct *) *local;

    if (mode == -2) {			// cleanup
	ffclose(save->output);
	if (save->has_val == 1) {
	    free(save->val);
	    free_sec(save->clone_sec);
	}
	free(save);
	return 0;
    }

    if (mode >= 0) {			// processing

	idx = stat_proc_n_time_ranges_index(sec);

	// only process stat processed fields
	if (idx < 0) return 0;

	// n_time_ranges has to be one
	if (sec[4][idx] != 1) return 0;

	// only process averages or accumulations
	j = code_table_4_10(sec);
	if (mode == 99) fprintf(stderr,"\nncep_norm: code table 4.10 (ave/acc/etc)=%d\n",j);
	if (j == 0) is_ave = 1;			// average
	else if (j == 1) is_ave = 0;		// accumulation
	else return 0;				// only process average or accumulations

        fhr_2 = forecast_time_in_units(sec);		// start time
        dt2 = int4(sec[4]+idx+50-42);			// delta-time
	if (mode == 99) fprintf(stderr,"\nncep_norm: fhr_2=%d dt2=%d index of dt2=%d\n",fhr_2, dt2, idx+50-42);
	if (dt2 == 0) return 0;	 			// dt == 0

	// units of fcst and stat proc should be the same if fcst time != 0
	if (fhr_2 != 0 && code_table_4_4(sec) != sec[4][49-42+idx]) return 0;

	if (save->has_val == 0) {			// new data: write and save
            if ((data_tmp = (float *) malloc(ndata * sizeof(float))) == NULL)
                fatal_error("memory allocation - data_tmp","");
            undo_output_order(data, data_tmp, ndata);
            grib_wrt(sec, data_tmp, ndata, nx, ny, use_scale, dec_scale, bin_scale,
                wanted_bits, max_bits, grib_type, save->output);

            if (flush_mode) fflush(save->output);
            free(data_tmp);

            if (save->has_val  == 1) {			// copy data to save
                free(save->val);			// save = new field
                free_sec(save->clone_sec);
	    }
            copy_sec(sec, save->clone_sec);
            copy_data(data,ndata,&(save->val));
            save->has_val = 1;
	    if (mode == 99) fprintf(stderr," ncep_norm: saved as new field\n");
            return 0;
        }

        new_type = 0;

        fhr_1 = forecast_time_in_units(save->clone_sec);		// start_time of save message
        dt1 = int4(save->clone_sec[4]+idx+50-42);			// delta-time

	if (mode == 99) fprintf(stderr,"ncep_norm: is_ave = %d\n fhr_1 %d dt1 %d fhr_2 %d dt2 %d\n",is_ave,
		fhr_1, dt1, fhr_2, dt2);

	if (fhr_1 != fhr_2) new_type = 1;

	if (new_type == 0) {
	    if (same_sec0(sec,save->clone_sec) == 0 ||
            same_sec1(sec,save->clone_sec) == 0 ||
            same_sec3(sec,save->clone_sec) == 0 ||
            same_sec4_diff_ave_period(sec,save->clone_sec) == 0) {
	
               if (mode == 99) fprintf(stderr,"ncep_norm: new_type sec test %d %d %d %d\n",
  		same_sec0(sec,save->clone_sec), same_sec1(sec,save->clone_sec), same_sec3(sec,save->clone_sec),
	            same_sec4_diff_ave_period(sec,save->clone_sec));
                new_type = 1;
	    }
        }
	if (mode == 99) fprintf(stderr,"ncep_norm: new_type=%d write and save\n",new_type);

        if (new_type == 1) {                    // fields dont match: write and save
            if ((data_tmp = (float *) malloc(ndata * sizeof(float))) == NULL)
                fatal_error("memory allocation - data_tmp","");
            undo_output_order(data, data_tmp, ndata);
            grib_wrt(sec, data_tmp, ndata, nx, ny, use_scale, dec_scale, bin_scale,
                wanted_bits, max_bits, grib_type, save->output);

            if (flush_mode) fflush(save->output);
            free(data_tmp);

            if (save->has_val  == 1) {                  // copy data to save
                free(save->val);                        // save = new field
                free_sec(save->clone_sec);
            }
            copy_sec(sec, save->clone_sec);
            copy_data(data,ndata,&(save->val));
            save->has_val = 1;
	    if (mode == 99) fprintf(stderr," ncep_norm: saved as new type/sequence\n");
            return 0;
        }

        /* now do stuff */

	if (dt1 == dt2) return 0;			// same ending time

        // change metadata

        int_char(dt2-dt1, save->clone_sec[4]+50-42+idx);	//  dt = dt2 - dt1

        save->clone_sec[4][17] = sec[4][49-42+idx];             // new forecast time unit
        int_char(dt1+fhr_1, save->clone_sec[4]+18);             // fhr = fhr + dt1
        if (mode == 99) fprintf(stderr,"ncep_norm new fcst time %d + %d\n", dt1,fhr_1);

        for (i = idx-7; i < idx; i++) {                             // ending time from pds2
            save->clone_sec[4][i] = sec[4][i];
        }

	if (mode == 99) {
	    if (is_ave)
	        fprintf(stderr," process: factor: NEW*%g - OLD*%g\n", dt2/ (double) (dt2 - dt1),
			dt1/ (double) (dt2-dt1));
	    else fprintf(stderr," process: current-last\n");
	}

        // change floating point data

        d1= save->val;
        for (i = 0; i < ndata; i++) {
            if (!UNDEFINED_VAL(data[i]) && !UNDEFINED_VAL(*d1) ) {
		if (is_ave) {
                    *d1 = (data[i]*dt2 - *d1*dt1) / (double) (dt2 - dt1);
		}
		else {		// accumulation
                    *d1 = data[i] - *d1;
		}
	    }
            else *d1 = UNDEFINED;
            d1++;
	}

        // write grib output

        if ((data_tmp = (float *) malloc(ndata * sizeof(float))) == NULL)
                fatal_error("memory allocation - data_tmp","");
        undo_output_order(save->val, data_tmp, ndata);
        grib_wrt(save->clone_sec, data_tmp, ndata, nx, ny, use_scale, dec_scale, bin_scale,
            wanted_bits, max_bits, grib_type, save->output);

        if (flush_mode) fflush(save->output);
        free(data_tmp);

	// save data
        free(save->val);                    // save = new field
        free_sec(save->clone_sec);
        copy_sec(sec, save->clone_sec);
        copy_data(data,ndata,&(save->val));
        return 0;
    }
    return 0;
}
Example #9
0
/*
 * Function: create_listen_socket()
 * 
 * Descripton:
 *  Create a socket to listen for connections on a socket.
 *  The socket discripter is stored info_p->listen_sd.
 *
 * Argument:
 *  info_p:	pointer to a server infomation
 *
 * Return value:
 *  None
 */
void
create_listen_socket(struct server_info *info_p)
{
    int on;			/* on/off at an socket option */
    int err;			/* return value of getaddrinfo */
    struct addrinfo hints;	/* hints for getaddrinfo() */
    struct addrinfo *res;	/* pointer to addrinfo */

    /* Set the hints to addrinfo() */
    memset(&hints, '\0', sizeof(struct addrinfo));
    hints.ai_family = info_p->family;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;
    
    /* Translate the network and service information of the server */
    err = getaddrinfo(NULL, info_p->portnum, &hints, &res);
    if (err) {
	fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(err));
	exit(EXIT_FAILURE);
    }
    if (res->ai_next) {
	fprintf(stderr, "getaddrinfo(): multiple address is found.");
	exit(EXIT_FAILURE);
    }

    /* Create a socket for listening. */
    info_p->listen_sd = socket(res->ai_family,
	    res->ai_socktype, res->ai_protocol);
    if (info_p->listen_sd < 0)
	fatal_error("socket()");

#ifdef IPV6_V6ONLY
    /* Don't accept IPv4 mapped address if the protocol family is IPv6 */
    if (res->ai_family == PF_INET6) {
	on = 1;
	if (setsockopt(info_p->listen_sd,
		    IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(int))) 
	    fatal_error("setsockopt()");
    }
#endif

    /* Enable to reuse the socket */
    on = 1;
    if (setsockopt(info_p->listen_sd,
		SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int))) 
	fatal_error("setsockopt()");

    /* Disable the Nagle algorithm, when small sending mode */
    if (info_p->small_sending) {
	on = 1;
	if (setsockopt(info_p->listen_sd,
		    IPPROTO_TCP, TCP_NODELAY, &on, sizeof(int)))
	    fatal_error("setsockopt()");
	if (debug) {
	    fprintf(stderr, "small sending[on]\n");
	}
    }

    /* Maximize socket buffer, when window scaling mode */
    if (info_p->window_scaling)
	maximize_sockbuf(info_p->listen_sd);

    /* Bind to the local address */
    if (bind(info_p->listen_sd, res->ai_addr, res->ai_addrlen) < 0) 
	fatal_error("bind()");
    freeaddrinfo(res);

    /* Start to listen for connections */
    if (listen(info_p->listen_sd, 5) < 0)
	fatal_error("listen()");
}
/*
  Reads image features from file.  The file should be formatted as from
  the code provided by David Lowe:
  
  http://www.cs.ubc.ca/~lowe/keypoints/
  
  @param filename location of a file containing image features
  @param features pointer to an array in which to store features
  
  @return Returns the number of features imported from filename or -1 on error
*/
static int import_lowe_features( char* filename, struct feature** features )
{
  struct feature* f;
  int i, j, n, d;
  double x, y, s, o, dv;
  FILE* file;

  if( ! features )
    fatal_error( "NULL pointer error, %s, line %d",  __FILE__, __LINE__ );
  if( ! ( file = fopen( filename, "r" ) ) )
    {
      fprintf( stderr, "Warning: error opening %s, %s, line %d\n",
	       filename, __FILE__, __LINE__ );
      return -1;
    }

  /* read number of features and dimension */
  if( fscanf( file, " %d %d ", &n, &d ) != 2 )
    {
      fprintf( stderr, "Warning: file read error, %s, line %d\n",
	       __FILE__, __LINE__ );
      return -1;
    }
  if( d > FEATURE_MAX_D )
    {
      fprintf( stderr, "Warning: descriptor too long, %s, line %d\n",
	       __FILE__, __LINE__ );
      return -1;
    }

  f = calloc( n, sizeof(struct feature) );
  for( i = 0; i < n; i++ )
    {
      /* read affine region parameters */
      if( fscanf( file, " %lf %lf %lf %lf ", &y, &x, &s, &o ) != 4 )
	{
	  fprintf( stderr, "Warning: error reading feature #%d, %s, line %d\n",
		   i+1, __FILE__, __LINE__ );
	  free( f );
	  return -1;
	}
      f[i].img_pt.x = f[i].x = x;
      f[i].img_pt.y = f[i].y = y;
      f[i].scl = s;
      f[i].ori = o;
      f[i].d = d;
      f[i].type = FEATURE_LOWE;

      /* read descriptor */
      for( j = 0; j < d; j++ )
	{
	  if( ! fscanf( file, " %lf ", &dv ) )
	    {
	      fprintf( stderr, "Warning: error reading feature descriptor" \
		       " #%d, %s, line %d\n", i+1, __FILE__, __LINE__ );
	      free( f );
	      return -1;
	    }
	  f[i].descr[j] = dv;
	}

      f[i].a = f[i].b = f[i].c = 0;
      f[i].category = 0;
      f[i].fwd_match = f[i].bck_match = f[i].mdl_match = NULL;
      f[i].mdl_pt.x = f[i].mdl_pt.y = -1;
      f[i].feature_data = NULL;
    }

  if( fclose(file) )
    {
      fprintf( stderr, "Warning: file close error, %s, line %d\n",
	       __FILE__, __LINE__ );
      free( f );
      return -1;
    }

  *features = f;
  return n;
}
Example #11
0
int main(int argc, char **argv)
{
  char*	server_key = 0;
  char*	server_cert = 0;
  char*	client_key = 0;
  char*	client_cert = 0;
  char*	ca_file = 0;
  char*	ca_path = 0;
  int	child_pid,sv[2];
  struct st_VioSSLAcceptorFd* ssl_acceptor=0;
  struct st_VioSSLConnectorFd* ssl_connector=0; 
  Vio* client_vio=0;
  Vio* server_vio=0;
  enum enum_ssl_init_error ssl_init_error;
  unsigned long ssl_error;

  MY_INIT(argv[0]);
  DBUG_PROCESS(argv[0]);
  DBUG_PUSH(default_dbug_option);

  if (argc<5)
  {
    print_usage();
    return 1;
  }

  server_key = argv[1];
  server_cert = argv[2];
  client_key = argv[3];
  client_cert = argv[4];
  if (argc>5)
    ca_file = argv[5];
  if (argc>6)
    ca_path = argv[6];
  printf("Server key/cert : %s/%s\n", server_key, server_cert);
  printf("Client key/cert : %s/%s\n", client_key, client_cert);
  if (ca_file!=0)
    printf("CAfile          : %s\n", ca_file);
  if (ca_path!=0)
    printf("CApath          : %s\n", ca_path);


  if (socketpair(PF_UNIX, SOCK_STREAM, IPPROTO_IP, sv)==-1)
    fatal_error("socketpair");

  ssl_acceptor = new_VioSSLAcceptorFd(server_key, server_cert, ca_file,
				      ca_path);
  ssl_connector = new_VioSSLConnectorFd(client_key, client_cert, ca_file,
					ca_path, &ssl_init_error);

  client_vio = (Vio*)my_malloc(sizeof(struct st_vio),MYF(0));
  client_vio->sd = sv[0];
  sslconnect(ssl_connector,client_vio,&ssl_error);
  server_vio = (Vio*)my_malloc(sizeof(struct st_vio),MYF(0));
  server_vio->sd = sv[1];
  sslaccept(ssl_acceptor,server_vio,&ssl_error);

  printf("Socketpair: %d , %d\n", client_vio->sd, server_vio->sd);

  child_pid = fork();
  if (child_pid==-1)
  {
    my_free(ssl_acceptor);
    my_free(ssl_connector);
    fatal_error("fork");
  }
  if (child_pid==0)
  {
    /* child, therefore, client */
    char	xbuf[100];
    int	r = vio_ssl_read(client_vio,xbuf, sizeof(xbuf));
    if (r<=0) {
      my_free(ssl_acceptor);
      my_free(ssl_connector);
      fatal_error("client:SSL_read");
    }
    xbuf[r] = 0;
    printf("client:got %s\n", xbuf);
    my_free(client_vio);
    my_free(ssl_acceptor);
    my_free(ssl_connector);
    sleep(1);
  }
  else
  {
    const char*	s = "Huhuhuh";
    int		r = vio_ssl_write(server_vio,(uchar*)s, strlen(s));
    if (r<=0) {
      my_free(ssl_acceptor);
      my_free(ssl_connector);
      fatal_error("server:SSL_write");
    }
    my_free(server_vio);
    my_free(ssl_acceptor);
    my_free(ssl_connector);
    sleep(1);
  }
  return 0;
}
Example #12
0
real calc_grid(matrix box,real gr_sp,int *nx,int *ny,int *nz,int nnodes)
{
  int  d,n[DIM];
  int  i,nmin[DIM];
  rvec box_size,spacing;
  real max_spacing;
  
  if (gr_sp <= 0)
    fatal_error(0,"invalid fourier grid spacing: %g",gr_sp);
  
  for(d=0; d<DIM; d++)
    box_size[d] = box[d][d];

  n[XX] = *nx;
  n[YY] = *ny;
  n[ZZ] = *nz;

  ng = 1;
  ng_max = 1;
  for(d=0; d<DIM; d++) {
    nmin[d] = (int)(box_size[d]/gr_sp + 0.999);
    if (2*nmin[d] > ng_max)
      ng_max = 2*nmin[d];
  }
  n_list=0;
  n_list_alloc=0;
  list=NULL;
  for(i=0; i<facNR; i++)
    decomp[i]=0;
  make_list(0);

  if ((*nx<=0) || (*ny<=0) || (*nz<=0))
    fprintf(stderr,"Calculating fourier grid dimensions for%s%s%s\n",
	    *nx > 0 ? "":" X",*ny > 0 ? "":" Y",*nz > 0 ? "":" Z");

  qsort(list,n_list,sizeof(list[0]),list_comp);
  if (debug)
    for(i=0; i<n_list; i++)
      fprintf(debug,"grid: %d\n",list[i]);
  
  if (((*nx>0) && (*nx != nnodes*(*nx/nnodes))) ||
      ((*ny>0) && (*ny != nnodes*(*ny/nnodes))))
    fatal_error(0,"the x or y grid spacing (nx %d, ny %d) is not divisible by the number of nodes (%d)",*nx,*ny,nnodes);
  
  for(d=0; d<DIM; d++) {
    for(i=0; (i<n_list) && (n[d]<=0); i++)
      if ((list[i] >= nmin[d]) && 
	  ((d == ZZ) || (list[i] == nnodes*(list[i]/nnodes))))
	n[d] = list[i];
    if (n[d] <= 0)
      fatal_error(0 ,"could not find a grid spacing with nx and ny divisible by the number of nodes (%d)",nnodes);
  }
  
  max_spacing = 0;
  for(d=0; d<DIM; d++) {
    spacing[d] = box_size[d]/n[d];
    if (spacing[d] > max_spacing)
      max_spacing = spacing[d];
  }
  *nx = n[XX];
  *ny = n[YY];
  *nz = n[ZZ];
  fprintf(stderr,"Using a fourier grid of %dx%dx%d, spacing %.3f %.3f %.3f\n",
	  *nx,*ny,*nz,spacing[XX],spacing[YY],spacing[ZZ]);

  return max_spacing;
}
Example #13
0
void safe_write(int fd, void *data, ssize_t size)
{
	if(!check_write(fd,data,size))
		fatal_error("error writing fd",errno);
}
Example #14
0
void safe_close(int fd)
{
	if(close(fd) < 0)
		fatal_error("error closing fd",errno);
}
Example #15
0
static glui32 write_stackstate(dest_t *dest, int portable)
{
  glui32 res;
  glui32 lx;
  glui32 lastframe;

  /* If we're storing for the purpose of undo, we don't need to do any
     byte-swapping, because the result will only be used by this session. */
  if (!portable) {
    res = write_buffer(dest, stack, stackptr);
    if (res)
      return res;
    return 0;
  }

  /* Write a portable stack image. To do this, we have to write stack
     frames in order, bottom to top. Remember that the last word of
     every stack frame is a pointer to the beginning of that stack frame.
     (This includes the last frame, because the save opcode pushes on
     a call stub before it calls perform_save().) */

  lastframe = (glui32)(-1);
  while (1) {
    glui32 frameend, frm, frm2, frm3;
    unsigned char loctype, loccount;
    glui32 numlocals, frlen, locpos;

    /* Find the next stack frame (after the one in lastframe). Sadly,
       this requires searching the stack from the top down. We have to
       do this for *every* frame, which takes N^2 time overall. But
       save routines usually aren't nested very deep. 
       If it becomes a practical problem, we can build a stack-frame 
       array, which requires dynamic allocation. */
    for (frm = stackptr, frameend = stackptr;
         frm != 0 && (frm2 = Stk4(frm-4)) != lastframe;
         frameend = frm, frm = frm2) { };

    /* Write out the frame. */
    frm2 = frm;

    frlen = Stk4(frm2);
    frm2 += 4;
    res = write_long(dest, frlen);
    if (res)
      return res;
    locpos = Stk4(frm2);
    frm2 += 4;
    res = write_long(dest, locpos);
    if (res)
      return res;

    frm3 = frm2;

    numlocals = 0;
    while (1) {
      loctype = Stk1(frm2);
      frm2 += 1;
      loccount = Stk1(frm2);
      frm2 += 1;

      res = write_byte(dest, loctype);
      if (res)
        return res;
      res = write_byte(dest, loccount);
      if (res)
        return res;

      if (loctype == 0 && loccount == 0)
        break;

      numlocals++;
    }

    if ((numlocals & 1) == 0) {
      res = write_byte(dest, 0);
      if (res)
        return res;
      res = write_byte(dest, 0);
      if (res)
        return res;
      frm2 += 2;
    }

    if (frm2 != frm+locpos)
      fatal_error("Inconsistent stack frame during save.");

    /* Write out the locals. */
    for (lx=0; lx<numlocals; lx++) {
      loctype = Stk1(frm3);
      frm3 += 1;
      loccount = Stk1(frm3);
      frm3 += 1;
      
      if (loctype == 0 && loccount == 0)
        break;

      /* Put in up to 0, 1, or 3 bytes of padding, depending on loctype. */
      while (frm2 & (loctype-1)) {
        res = write_byte(dest, 0);
        if (res)
          return res;
        frm2 += 1;
      }

      /* Put in this set of locals. */
      switch (loctype) {

      case 1:
        do {
          res = write_byte(dest, Stk1(frm2));
          if (res)
            return res;
          frm2 += 1;
          loccount--;
        } while (loccount);
        break;

      case 2:
        do {
          res = write_short(dest, Stk2(frm2));
          if (res)
            return res;
          frm2 += 2;
          loccount--;
        } while (loccount);
        break;

      case 4:
        do {
          res = write_long(dest, Stk4(frm2));
          if (res)
            return res;
          frm2 += 4;
          loccount--;
        } while (loccount);
        break;

      }
    }

    if (frm2 != frm+frlen)
      fatal_error("Inconsistent stack frame during save.");

    while (frm2 < frameend) {
      res = write_long(dest, Stk4(frm2));
      if (res)
        return res;
      frm2 += 4;
    }

    /* Go on to the next frame. */
    if (frameend == stackptr)
      break; /* All done. */
    lastframe = frm;
  }

  return 0;
}
Example #16
0
/*
 * Function: communicate_client()
 * 
 * Descripton:
 *  Communicate with the connectted client.
 *  Currently, this function sends tcp segment in the specified second
 *  or recevie SIGHUP
 *
 * Argument:
 *  sock_fd: socket descriptor to communicate with client
 *  info_p:  pointer to a server infomation
 *
 * Return value:
 *  0:	    success
 *  other:  fail
 */
int
communicate_client(struct server_info *info_p, int sock_fd)
{
    char *sendmsg;		/* pointer to the message to send */
    int sndbuf_size;		/* size of the send buffer */
    int sock_optlen;		/* size of the result parameter */
    ssize_t sntbyte_size;	/* size of the sent byte */
    int ret = EXIT_SUCCESS;	/* The return value of this function */

    if (info_p->small_sending) {	/* small sending mode */
	sndbuf_size = 1;
    } else {
	sock_optlen = sizeof(sndbuf_size);
	if (getsockopt(sock_fd, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, &sock_optlen) < 0) {
	    perror("getsockopt()");
	    if (close(sock_fd))
		fatal_error("close()");
	    return EXIT_FAILURE;
	}
    }
    if(debug)
	fprintf(stderr, "sndbuf size is %d\n", sndbuf_size);

    /* Define the message */
    sendmsg = (char *)malloc(sndbuf_size);
    if (sendmsg == NULL) {
	fprintf(stderr, "malloc() is failed.\n");
	if (close(sock_fd))
	    fatal_error("close()");
	return EXIT_FAILURE;
    }

    /* Set a signal handler against SIGHUP and SIGPIPE */
    handler.sa_handler = set_signal_flag;
    if (sigaction(SIGHUP, &handler, NULL) < 0)
	fatal_error("sigaction()");
    if (sigaction(SIGPIPE, &handler, NULL) < 0)
	fatal_error("sigaction()");

    /* Send the message */
    for(;;) {
	sntbyte_size = send(sock_fd, sendmsg, sndbuf_size, 0);

	/* Catch SIGPIPE */
	if (catch_sigpipe) {
	    if (debug)
	      fprintf(stderr, "The client closed the connection.\n");
	    break;
	}

	/* Catch SIGHUP */
	if (catch_sighup)
	    break;

	if (sntbyte_size < (ssize_t)0) {
	    if (errno == EPIPE) {
	      if (debug)
		fprintf(stderr, "The client closed the connection.\n");
	    } else {
		printf ("errno=%d\n", errno);
		perror("send()");
		ret = EXIT_FAILURE;
	    }
	    break;
	}
    }

    free(sendmsg);
    if (close(sock_fd))
	fatal_error("close()");
    return ret;
}
bool request_new_sequence (pkc_state *s)
{
    register uint16_t it;                               /* Iterator */
    int sockfd, n;                                      /* Server Socket */
    struct timeval tv;                                  /* For timeout */
    struct sockaddr_in srv_addr;                        /* Server sockaddr struct */
    char * token;                                       /* For strtok */
    const char * delim = " ";                           /* Delimiter */
    char buffer [PORT_SIZE * SEQUENCE_SIZE + 1];        /* Holds new port sequence */
    
    if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
    {
        fatal_error (s, "Opening server socket.");
    }
    
    /* Set socket recv/send timeout time */
    tv.tv_sec = 10;
    tv.tv_usec = 0;
    
    /* Socket recv timeout */
    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(struct timeval)))
    {
        fatal_error (s, "Setting socket options.");
    }
    
    /* Socket send timeout */
    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(struct timeval)))
    {
        fatal_error (s, "Setting socket options.");
    }
    
    memset ((char *)&srv_addr, '\0', sizeof (srv_addr));
    srv_addr.sin_family = AF_INET;
    srv_addr.sin_port = htons (atoi (s->srv_port)); /* Assign Port Number */
    
    if (inet_aton (s->srv_address, &srv_addr.sin_addr) == 0) /* Assign IP Address */
    {
        fatal_error (s, "Invalid server address.");
    }
    
#ifdef DEBUG
    fprintf (stderr, "Requesting new sequence from server: %s\n", s->srv_address);
#endif
    
    if (connect (sockfd, (struct sockaddr *) &srv_addr, sizeof (srv_addr)) < 0)
    {
        fatal_error (s, "Connecting to server.");
    }
    
    memset (buffer, '\0', PORT_SIZE * SEQUENCE_SIZE + 1);
    
    if ((n = recv(sockfd, buffer, PORT_SIZE * SEQUENCE_SIZE + 1, MSG_DONTWAIT)) < 0)
    {
        fatal_error (s, "Reading from socket.");
    }
    
    close (sockfd);
    
    if (strlen (buffer) != 0)
    {
#ifdef DEBUG
        fprintf (stderr, "Request Accepted, new sequence: %s\n", buffer);
#endif

        /* Now lets extract the new sequence from buffer */
        token = strtok (buffer, delim);
        
        for (it = 0x0; it < SEQUENCE_SIZE; it++)
        {
            s->sequence[it] = atoi (token);
            token = strtok (NULL, delim);
        } 
        return true;
    }
    else
    {
#ifdef DEBUG
        fprintf (stderr, "New sequence request failed.\n");
#endif
        return false;
    }
}
Example #18
0
/*
 * Function: handle_client()
 * 
 * Descripton:
 *  Accept a connection from a client, then fork to communicate the client
 *
 * Argument:
 *  info_p:	pointer to a server infomation
 *
 * Return value:
 *  0:	    success
 *  other:  fail
 */
int
handle_client(struct server_info *info_p)
{
    int ret = EXIT_SUCCESS;	/* return value of this function */
    int do_accept = 1;		/* if non-zero, accept connection */
    fd_set read_fds;		/* list of file descriptor for reading */
    int max_read_fd = 0;	/* maximum number in the read fds */

    info_p->current_connection = 0;
    FD_ZERO(&read_fds);
    FD_SET(info_p->listen_sd, &read_fds);
    max_read_fd = info_p->listen_sd;

    /* Catch SIGHUP */
    handler.sa_handler = set_signal_flag;
    if (sigaction(SIGHUP, &handler, NULL) < 0)
	fatal_error("sigaction()");

    /* Loop to wait a new connection */
    for(;;) {
	if (do_accept) {
	    int data_sd;	/* socket descriptor for send/recv data */
	    socklen_t client_addr_len;	/* length of `client_addr' */
	    struct sockaddr_storage client_addr;    /* address of a client */
	    int select_ret;	/* return value of select() */
	    fd_set  active_fds;	/* list of the active file descriptor */
	    struct timeval select_timeout;	/* timeout for select() */

	    /* When catch SIGHUP, no more connection is acceptted. */
	    if (catch_sighup) {
		do_accept = 0;
		if (close(info_p->listen_sd))
		    fatal_error("close()");
		continue;
	    }

	    /* Check a connection is requested */
	    active_fds = read_fds;
	    select_timeout.tv_sec = 0;	    /* 0.5 sec */
	    select_timeout.tv_usec = 500000;

	    select_ret = select(max_read_fd + 1,
		    &active_fds, NULL, NULL, &select_timeout);
	    if (select_ret < 0) {
		do_accept = 0;
		if (!catch_sighup) {
		    perror("select()");
		    ret = EXIT_FAILURE;
		}
		if (close(info_p->listen_sd))
		    fatal_error("close()");
		continue;
	    } else if (select_ret == 0) {	    /* select() is timeout */
		if (info_p->concurrent)
		    delete_zombies(info_p);
		continue;
	    }

	    /* Accetpt a client connection */
	    if (FD_ISSET(info_p->listen_sd, &active_fds)) {
		client_addr_len = sizeof(struct sockaddr_storage);
		data_sd = accept(info_p->listen_sd,
			(struct sockaddr *)&client_addr, &client_addr_len);
		if (data_sd < 0) {
		    do_accept = 0;
		    if (!catch_sighup) {
			perror("accept()");
			ret = EXIT_FAILURE;
		    }
		    if (close(info_p->listen_sd))
			fatal_error("close()");
		    continue;
		}
		if (debug)
		    fprintf(stderr, "called accept(). data_sd=%d\n", data_sd);

		/* Handle clients */
		if (info_p->concurrent) {	/* concurrent server. */
		    pid_t child_pid;
		    child_pid = fork();
		    if (child_pid < 0) {	/* fork() is failed. */
			perror("fork()");
			if (close(data_sd))
			    fatal_error("close()");
			if (close(info_p->listen_sd))
			    fatal_error("close()");
			do_accept = 0;
			continue;
		    } else if (child_pid == 0) {	/* case of a child */
			int exit_value;
			if (close(info_p->listen_sd))
			    fatal_error("close()");
			exit_value = communicate_client(info_p, data_sd);
			if (debug)
			    fprintf(stderr, "child(%d) exits. value is %d\n",
				    getpid(), exit_value);
			exit(exit_value);
		    } else {				/* case of the parent */
			if (close(data_sd))
			    fatal_error("close()");
			
			++info_p->current_connection;
			if (info_p->max_connection < info_p->current_connection) {
			    info_p->max_connection = info_p->current_connection;
			    if (debug)
				fprintf (stderr, "The maximum connection is updated. The number is %d.\n", info_p->max_connection);
			}
			delete_zombies(info_p);
		    }
		} else {			/* repeat server */
		    ret = communicate_client(info_p, data_sd);
		    if (ret != EXIT_SUCCESS) 
		      if (close(info_p->listen_sd))
			fatal_error("close()");
		    break;
		}
	    }
	} else {
	    /* case where new connection isn't accepted. */
	    if (info_p->concurrent)
		delete_zombies(info_p);
	    if (info_p->current_connection == 0) 
		break;
	}
    }
    return ret;
}
Example #19
0
static void parse_file_list(FileData *file_data, int num_paths, const char *lsfile, const char *path_dir, AccessMethod method, int host)
{
	FileState *file_state = NULL;
	FILE *fp;
	char *path_file;
	char *temp;
	char *text;

	char *name;
	time_t time;
	off_t size;
	mode_t mode;
	int type;

	char *ssh_command;
	int num_files = 0;

	fp = fopen(lsfile, "r");
	if (fp == NULL) {
		perror("fopen");
		fprintf(stderr, _("Cannot open file `%s'.\n"), lsfile);
		fatal_error(host);
	}

	while ((text = str_fgets(fp)) != NULL) {
		if (strncmp(text, "total", 5) == 0) { /* skip */
			free(text);
			continue;
		}
		if (strncmp(text, "/bin/ls:", 8) == 0) {
			fprintf(stderr, _("Listing remote directory contents failed: %s\nThe directory doesn't exist or permission denied.\n"), path_dir);
			fatal_error(host);
		}

		switch (method) {
		case FTP:
			ftp_extract_file_status(text, &name, &size, &mode, &type, host);
			break;
		case SCP:
		case RSYNC:
			ssh_extract_file_status(text, &name, &time, &size, &mode, &type, host);
			break;
		default:
			internal_error(__FILE__, __LINE__);
		} 
		free(text);

		if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
			free(name);
			continue;
		}

		path_file = str_concat(path_dir, "/", name, NULL);

		if (type == 'l') { /* Check whether the symbolic link is directory or not. */
			switch (method) {
			case FTP:
				type = ftp_chdir(path_file) ? 'd' : '-';
				break;
			case SCP:
			case RSYNC:
				ssh_command = str_dup_printf("ssh %s@%s cd %s", config.login_name[host], config.host_name[host], path_file);
				type = (system(ssh_command) == 0) ? 'd' : '-';
				free(ssh_command);
				break;
			default:
				internal_error(__FILE__, __LINE__);
			}
		}

		if ((type == 'd' && is_match_dir(path_file, config.ignore_remote_dir[host], host)) ||
		    (type != 'd' && (is_match_file(path_file, path_dir, config.ignore_remote_file[host], host) ||
				     is_match_file(path_file, path_dir, config.ignore_file[host], host)))) {
			free(path_file);
			free(name);
			continue;
		}

		if (config.conv_to_lower[host]) {
			temp = str_tolower(name);
			free(name);
			name = temp;

			free(path_file);
			path_file = str_concat(path_dir, "/", name, NULL);
		}

		if (method == FTP) {
			if (type != 'd') {
				time = ftp_get_last_modification_time(path_file, host);
			} else {
				time = 0;
			}
		}

                file_state = str_realloc(file_state, (num_files + 1) * sizeof(FileState));
		file_state[num_files].name = name;
		file_state[num_files].time = time;
		file_state[num_files].size = size;
		file_state[num_files].mode = mode;
		file_state[num_files].isdir = (type == 'd');
		file_state[num_files].isremoved = FALSE;

		num_files++;

		free(path_file);
	}

	if (fclose(fp) != 0) {
		perror("fclose");
		fprintf(stderr, _("Cannot close file `%s'.\n"), lsfile);
		fatal_error(host);
        }

	sort_file_state(file_state, num_files);

	file_data->path_state[num_paths].num_files = num_files;
	file_data->path_state[num_paths].file_state = file_state;
}
Example #20
0
/*
 *
 *  Function: main()
 *
 */
int
main(int argc, char *argv[])
{
    char *program_name = argv[0];
    int optc;			/* option */
    struct server_info server;	/* server information */
    int ret = EXIT_SUCCESS;	/* exit value */
    int background = 0;	/* If non-zero work in the background */
    FILE *info_fp = stdout;	/* FILE pointer to a information file */

    debug = 0;

    /* Initilalize the server information */
    memset(&server, '\0', sizeof(struct server_info));
    server.family = PF_UNSPEC;
    server.portnum = NULL;
    
    /* Retrieve the options */
    while ((optc = getopt(argc, argv, "f:p:bcswo:dh")) != EOF) {
	switch (optc) {
	    case 'f':
		if (strncmp(optarg, "4", 1) == 0)
		    server.family = PF_INET;	/* IPv4 */
		else if (strncmp(optarg, "6", 1) == 0)
		    server.family = PF_INET6;	/* IPv6 */
		else {
		    fprintf(stderr, "protocol family should be 4 or 6.\n");
		    usage(program_name, EXIT_FAILURE);
		}
		break;

	    case 'p':
		{
		    unsigned long int num;
		    num = strtoul(optarg, NULL, 0);
		    if (num < PORTNUMMIN || PORTNUMMAX < num) {
			fprintf(stderr, "The range of port is from %u to %u\n",
				PORTNUMMIN, PORTNUMMAX);
			usage(program_name, EXIT_FAILURE);
		    }
		    server.portnum = strdup(optarg);
		}
		break;

	    case 'b':
		background = 1;
		break;

	    case 'c':
		server.concurrent = 1;
		break;

	    case 's':
		server.small_sending = 1;
		break;

	    case 'w':
		server.window_scaling = 1;
		break;

	    case 'o':
		if ((info_fp = fopen(optarg, "w")) == NULL) {
		    fprintf(stderr, "Cannot open %s\n", optarg);
		    exit(EXIT_FAILURE);
		}
		break;

	    case 'd':
		debug = 1;
		break;

	    case 'h':
		usage(program_name, EXIT_SUCCESS);
		break;

	    default:
		usage(program_name, EXIT_FAILURE);
	}
    }

    /* Check the family is spefied. */
    if (server.family == PF_UNSPEC) {
	fprintf (stderr, "protocol family should be specified.\n");
	usage(program_name, EXIT_FAILURE);
    }

    /* Check the port number is specfied. */
    if (server.portnum == NULL) {
	server.portnum = (char *)calloc(6, sizeof(char));
	sprintf(server.portnum, "%u", PORTNUMMIN);
    }

    /* If -b option is specified, work as a daemon */
    if (background) 
	if (daemon(0, 0) < 0)
	    fatal_error("daemon()");

    /* At first, SIGHUP is ignored. default with SIGPIPE */
    handler.sa_handler = SIG_IGN;
    if (sigfillset(&handler.sa_mask) < 0)
	fatal_error("sigfillset()");
    handler.sa_flags = 0;

    if (sigaction(SIGHUP, &handler, NULL) < 0)
	fatal_error("sigaction()");

    /* Create a listen socket */
    create_listen_socket(&server);

    /* Output any server information to the information file */
    fprintf(info_fp, "PID: %u\n", getpid());
    fflush(info_fp);
    if (info_fp != stdout) 
	if (fclose(info_fp))
	    fatal_error("fclose()");

    /* Handle one or more tcp clients. */
    ret = handle_client(&server);
    exit (ret);
}
Example #21
0
/* Callback for JVMTI_EVENT_DATA_DUMP_REQUEST (Ctrl-\ or at exit) */
static void JNICALL
dataDumpRequest(jvmtiEnv *jvmti)
{
    enterAgentMonitor(jvmti); {
        if ( !gdata->vmDeathCalled && !gdata->dumpInProgress ) {
            jvmtiHeapCallbacks heapCallbacks;
            ClassDetails      *details;
            jvmtiError         err;
            jclass            *classes;
            jint               totalCount;
            jint               count;
            jint               i;

            gdata->dumpInProgress = JNI_TRUE;
           
            /* Get all the loaded classes */
            err = (*jvmti)->GetLoadedClasses(jvmti, &count, &classes);
            check_jvmti_error(jvmti, err, "get loaded classes");

            /* Setup an area to hold details about these classes */
            details = (ClassDetails*)calloc(sizeof(ClassDetails), count);
            if ( details == NULL ) {
                fatal_error("ERROR: Ran out of malloc space\n");
            }
            for ( i = 0 ; i < count ; i++ ) {
                char *sig;

                /* Get and save the class signature */
                err = (*jvmti)->GetClassSignature(jvmti, classes[i], &sig, NULL);
                check_jvmti_error(jvmti, err, "get class signature");
                if ( sig == NULL ) {
                    fatal_error("ERROR: No class signature found\n");
                }
                details[i].signature = strdup(sig);
                deallocate(jvmti, sig);

                /* Tag this jclass */
                err = (*jvmti)->SetTag(jvmti, classes[i], 
                                    (jlong)(ptrdiff_t)(void*)(&details[i]));
                check_jvmti_error(jvmti, err, "set object tag");
            }
            
            /* Iterate through the heap and count up uses of jclass */
            (void)memset(&heapCallbacks, 0, sizeof(heapCallbacks));
            heapCallbacks.heap_iteration_callback = &cbHeapObject;
            totalCount = 0;
            err = (*jvmti)->IterateThroughHeap(jvmti, 
                       JVMTI_HEAP_FILTER_CLASS_UNTAGGED, NULL,
                       &heapCallbacks, (const void *)&totalCount);
            check_jvmti_error(jvmti, err, "iterate through heap");

            /* Remove tags */
            for ( i = 0 ; i < count ; i++ ) {
                /* Un-Tag this jclass */
                err = (*jvmti)->SetTag(jvmti, classes[i], (jlong)0);
                check_jvmti_error(jvmti, err, "set object tag");
            }
            
            /* Sort details by space used */
            qsort(details, count, sizeof(ClassDetails), &compareDetails);
           
            /* Print out sorted table */
            stdout_message("Heap View, Total of %d objects found.\n\n",
                         totalCount);
            
            stdout_message("Space      Count      Class Signature\n");
            stdout_message("---------- ---------- ----------------------\n");
            
            for ( i = 0 ; i < count ; i++ ) {
                if ( details[i].space == 0 || i > 20 ) {
                    break;
                }
                stdout_message("%10d %10d %s\n",
                    details[i].space, details[i].count, details[i].signature);
            }
            stdout_message("---------- ---------- ----------------------\n\n");

            /* Free up all allocated space */
            deallocate(jvmti, classes);
            for ( i = 0 ; i < count ; i++ ) {
                if ( details[i].signature != NULL ) {
                    free(details[i].signature);
                }
            }
            free(details);
            
            gdata->dumpInProgress = JNI_FALSE;
        }
    } exitAgentMonitor(jvmti);
}
Example #22
0
static int check_dir_block(ext2_filsys fs,
			   struct ext2_db_entry2 *db,
			   void *priv_data)
{
 	struct dx_dir_info	*dx_dir;
#ifdef ENABLE_HTREE
	struct dx_dirblock_info	*dx_db = 0;
#endif /* ENABLE_HTREE */
	struct ext2_dir_entry 	*dirent, *prev;
	ext2_dirhash_t		hash;
	unsigned int		offset = 0;
	int			dir_modified = 0;
	int			dot_state;
	unsigned int		rec_len;
	blk64_t			block_nr = db->blk;
	ext2_ino_t 		ino = db->ino;
	ext2_ino_t 		subdir_parent;
	__u16			links;
	struct check_dir_struct	*cd;
	char 			*buf;
	e2fsck_t		ctx;
	problem_t		problem;
	struct ext2_dx_root_info *root;
	struct ext2_dx_countlimit *limit;
	static dict_t de_dict;
	struct problem_context	pctx;
	int	dups_found = 0;
	int	ret;

	cd = (struct check_dir_struct *) priv_data;
	buf = cd->buf;
	ctx = cd->ctx;

	if (ctx->flags & E2F_FLAG_SIGNAL_MASK || ctx->flags & E2F_FLAG_RESTART)
		return DIRENT_ABORT;

	if (ctx->progress && (ctx->progress)(ctx, 2, cd->count++, cd->max))
		return DIRENT_ABORT;

	/*
	 * Make sure the inode is still in use (could have been
	 * deleted in the duplicate/bad blocks pass.
	 */
	if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino)))
		return 0;

	cd->pctx.ino = ino;
	cd->pctx.blk = block_nr;
	cd->pctx.blkcount = db->blockcnt;
	cd->pctx.ino2 = 0;
	cd->pctx.dirent = 0;
	cd->pctx.num = 0;

	if (db->blk == 0) {
		if (allocate_dir_block(ctx, db, buf, &cd->pctx))
			return 0;
		block_nr = db->blk;
	}

	if (db->blockcnt)
		dot_state = 2;
	else
		dot_state = 0;

	if (ctx->dirs_to_hash &&
	    ext2fs_u32_list_test(ctx->dirs_to_hash, ino))
		dups_found++;

#if 0
	printf("In process_dir_block block %lu, #%d, inode %lu\n", block_nr,
	       db->blockcnt, ino);
#endif

	ehandler_operation(_("reading directory block"));
	cd->pctx.errcode = ext2fs_read_dir_block3(fs, block_nr, buf, 0);
	ehandler_operation(0);
	if (cd->pctx.errcode == EXT2_ET_DIR_CORRUPTED)
		cd->pctx.errcode = 0; /* We'll handle this ourselves */
	if (cd->pctx.errcode) {
		if (!fix_problem(ctx, PR_2_READ_DIRBLOCK, &cd->pctx)) {
			ctx->flags |= E2F_FLAG_ABORT;
			return DIRENT_ABORT;
		}
		memset(buf, 0, fs->blocksize);
	}
#ifdef ENABLE_HTREE
	dx_dir = e2fsck_get_dx_dir_info(ctx, ino);
	if (dx_dir && dx_dir->numblocks) {
		if (db->blockcnt >= dx_dir->numblocks) {
			if (fix_problem(ctx, PR_2_UNEXPECTED_HTREE_BLOCK,
					&pctx)) {
				clear_htree(ctx, ino);
				dx_dir->numblocks = 0;
				dx_db = 0;
				goto out_htree;
			}
			fatal_error(ctx, _("Can not continue."));
		}
		dx_db = &dx_dir->dx_block[db->blockcnt];
		dx_db->type = DX_DIRBLOCK_LEAF;
		dx_db->phys = block_nr;
		dx_db->min_hash = ~0;
		dx_db->max_hash = 0;

		dirent = (struct ext2_dir_entry *) buf;
		(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
		limit = (struct ext2_dx_countlimit *) (buf+8);
		if (db->blockcnt == 0) {
			root = (struct ext2_dx_root_info *) (buf + 24);
			dx_db->type = DX_DIRBLOCK_ROOT;
			dx_db->flags |= DX_FLAG_FIRST | DX_FLAG_LAST;
			if ((root->reserved_zero ||
			     root->info_length < 8 ||
			     root->indirect_levels > 1) &&
			    fix_problem(ctx, PR_2_HTREE_BAD_ROOT, &cd->pctx)) {
				clear_htree(ctx, ino);
				dx_dir->numblocks = 0;
				dx_db = 0;
			}
			dx_dir->hashversion = root->hash_version;
			if ((dx_dir->hashversion <= EXT2_HASH_TEA) &&
			    (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH))
				dx_dir->hashversion += 3;
			dx_dir->depth = root->indirect_levels + 1;
		} else if ((dirent->inode == 0) &&
			   (rec_len == fs->blocksize) &&
			   (dirent->name_len == 0) &&
			   (ext2fs_le16_to_cpu(limit->limit) ==
			    ((fs->blocksize-8) /
			     sizeof(struct ext2_dx_entry))))
			dx_db->type = DX_DIRBLOCK_NODE;
	}
out_htree:
#endif /* ENABLE_HTREE */

	dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cmp);
	prev = 0;
	do {
		dgrp_t group;
		ext2_ino_t first_unused_inode;

		problem = 0;
		dirent = (struct ext2_dir_entry *) (buf + offset);
		(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
		cd->pctx.dirent = dirent;
		cd->pctx.num = offset;
		if (((offset + rec_len) > fs->blocksize) ||
		    (rec_len < 12) ||
		    ((rec_len % 4) != 0) ||
		    (((dirent->name_len & (unsigned) 0xFF)+8) > rec_len)) {
			if (fix_problem(ctx, PR_2_DIR_CORRUPTED, &cd->pctx)) {
				salvage_directory(fs, dirent, prev, &offset);
				dir_modified++;
				continue;
			} else
				goto abort_free_dict;
		}

		if (dot_state == 0) {
			if (check_dot(ctx, dirent, ino, &cd->pctx))
				dir_modified++;
		} else if (dot_state == 1) {
			ret = check_dotdot(ctx, dirent, ino, &cd->pctx);
			if (ret < 0)
				goto abort_free_dict;
			if (ret)
				dir_modified++;
		} else if (dirent->inode == ino) {
			problem = PR_2_LINK_DOT;
			if (fix_problem(ctx, PR_2_LINK_DOT, &cd->pctx)) {
				dirent->inode = 0;
				dir_modified++;
				goto next;
			}
		}
		if (!dirent->inode)
			goto next;

		/*
		 * Make sure the inode listed is a legal one.
		 */
		if (((dirent->inode != EXT2_ROOT_INO) &&
		     (dirent->inode < EXT2_FIRST_INODE(fs->super))) ||
		    (dirent->inode > fs->super->s_inodes_count)) {
			problem = PR_2_BAD_INO;
		} else if (ctx->inode_bb_map &&
			   (ext2fs_test_inode_bitmap2(ctx->inode_bb_map,
						     dirent->inode))) {
			/*
			 * If the inode is in a bad block, offer to
			 * clear it.
			 */
			problem = PR_2_BB_INODE;
		} else if ((dot_state > 1) &&
			   ((dirent->name_len & 0xFF) == 1) &&
			   (dirent->name[0] == '.')) {
			/*
			 * If there's a '.' entry in anything other
			 * than the first directory entry, it's a
			 * duplicate entry that should be removed.
			 */
			problem = PR_2_DUP_DOT;
		} else if ((dot_state > 1) &&
			   ((dirent->name_len & 0xFF) == 2) &&
			   (dirent->name[0] == '.') &&
			   (dirent->name[1] == '.')) {
			/*
			 * If there's a '..' entry in anything other
			 * than the second directory entry, it's a
			 * duplicate entry that should be removed.
			 */
			problem = PR_2_DUP_DOT_DOT;
		} else if ((dot_state > 1) &&
			   (dirent->inode == EXT2_ROOT_INO)) {
			/*
			 * Don't allow links to the root directory.
			 * We check this specially to make sure we
			 * catch this error case even if the root
			 * directory hasn't been created yet.
			 */
			problem = PR_2_LINK_ROOT;
		} else if ((dot_state > 1) &&
			   (dirent->name_len & 0xFF) == 0) {
			/*
			 * Don't allow zero-length directory names.
			 */
			problem = PR_2_NULL_NAME;
		}

		if (problem) {
			if (fix_problem(ctx, problem, &cd->pctx)) {
				dirent->inode = 0;
				dir_modified++;
				goto next;
			} else {
				ext2fs_unmark_valid(fs);
				if (problem == PR_2_BAD_INO)
					goto next;
			}
		}

		/*
		 * If the inode was marked as having bad fields in
		 * pass1, process it and offer to fix/clear it.
		 * (We wait until now so that we can display the
		 * pathname to the user.)
		 */
		if (ctx->inode_bad_map &&
		    ext2fs_test_inode_bitmap2(ctx->inode_bad_map,
					     dirent->inode)) {
			if (e2fsck_process_bad_inode(ctx, ino,
						     dirent->inode,
						     buf + fs->blocksize)) {
				dirent->inode = 0;
				dir_modified++;
				goto next;
			}
			if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
				return DIRENT_ABORT;
		}

		group = ext2fs_group_of_ino(fs, dirent->inode);
		first_unused_inode = group * fs->super->s_inodes_per_group +
					1 + fs->super->s_inodes_per_group -
					ext2fs_bg_itable_unused(fs, group);
		cd->pctx.group = group;

		/*
		 * Check if the inode was missed out because
		 * _INODE_UNINIT flag was set or bg_itable_unused was
		 * incorrect.  If so, clear the _INODE_UNINIT flag and
		 * restart e2fsck.  In the future it would be nice if
		 * we could call a function in pass1.c that checks the
		 * newly visible inodes.
		 */
		if (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT)) {
			pctx.num = dirent->inode;
			if (fix_problem(ctx, PR_2_INOREF_BG_INO_UNINIT,
					&cd->pctx)){
				ext2fs_bg_flags_clear(fs, group,
						      EXT2_BG_INODE_UNINIT);
				ext2fs_mark_super_dirty(fs);
				ctx->flags |= E2F_FLAG_RESTART_LATER;
			} else {
				ext2fs_unmark_valid(fs);
				if (problem == PR_2_BAD_INO)
					goto next;
			}
		} else if (dirent->inode >= first_unused_inode) {
			pctx.num = dirent->inode;
			if (fix_problem(ctx, PR_2_INOREF_IN_UNUSED, &cd->pctx)){
				ext2fs_bg_itable_unused_set(fs, group, 0);
				ext2fs_mark_super_dirty(fs);
				ctx->flags |= E2F_FLAG_RESTART_LATER;
			} else {
				ext2fs_unmark_valid(fs);
				if (problem == PR_2_BAD_INO)
					goto next;
			}
		}

		/* 
		 * Offer to clear unused inodes; if we are going to be
		 * restarting the scan due to bg_itable_unused being
		 * wrong, then don't clear any inodes to avoid zapping
		 * inodes that were skipped during pass1 due to an
		 * incorrect bg_itable_unused; we'll get any real
		 * problems after we restart.
		 */
		if (!(ctx->flags & E2F_FLAG_RESTART_LATER) &&
		    !(ext2fs_test_inode_bitmap2(ctx->inode_used_map,
						dirent->inode)))
			problem = PR_2_UNUSED_INODE;

		if (problem) {
			if (fix_problem(ctx, problem, &cd->pctx)) {
				dirent->inode = 0;
				dir_modified++;
				goto next;
			} else {
				ext2fs_unmark_valid(fs);
				if (problem == PR_2_BAD_INO)
					goto next;
			}
		}

		if (check_name(ctx, dirent, ino, &cd->pctx))
			dir_modified++;

		if (check_filetype(ctx, dirent, ino, &cd->pctx))
			dir_modified++;

#ifdef ENABLE_HTREE
		if (dx_db) {
			ext2fs_dirhash(dx_dir->hashversion, dirent->name,
				       (dirent->name_len & 0xFF),
				       fs->super->s_hash_seed, &hash, 0);
			if (hash < dx_db->min_hash)
				dx_db->min_hash = hash;
			if (hash > dx_db->max_hash)
				dx_db->max_hash = hash;
		}
#endif

		/*
		 * If this is a directory, then mark its parent in its
		 * dir_info structure.  If the parent field is already
		 * filled in, then this directory has more than one
		 * hard link.  We assume the first link is correct,
		 * and ask the user if he/she wants to clear this one.
		 */
		if ((dot_state > 1) &&
		    (ext2fs_test_inode_bitmap2(ctx->inode_dir_map,
					      dirent->inode))) {
			if (e2fsck_dir_info_get_parent(ctx, dirent->inode,
						       &subdir_parent)) {
				cd->pctx.ino = dirent->inode;
				fix_problem(ctx, PR_2_NO_DIRINFO, &cd->pctx);
				goto abort_free_dict;
			}
			if (subdir_parent) {
				cd->pctx.ino2 = subdir_parent;
				if (fix_problem(ctx, PR_2_LINK_DIR,
						&cd->pctx)) {
					dirent->inode = 0;
					dir_modified++;
					goto next;
				}
				cd->pctx.ino2 = 0;
			} else {
				(void) e2fsck_dir_info_set_parent(ctx,
						  dirent->inode, ino);
			}
		}

		if (dups_found) {
			;
		} else if (dict_lookup(&de_dict, dirent)) {
			clear_problem_context(&pctx);
			pctx.ino = ino;
			pctx.dirent = dirent;
			fix_problem(ctx, PR_2_REPORT_DUP_DIRENT, &pctx);
			if (!ctx->dirs_to_hash)
				ext2fs_u32_list_create(&ctx->dirs_to_hash, 50);
			if (ctx->dirs_to_hash)
				ext2fs_u32_list_add(ctx->dirs_to_hash, ino);
			dups_found++;
		} else
			dict_alloc_insert(&de_dict, dirent, dirent);

		ext2fs_icount_increment(ctx->inode_count, dirent->inode,
					&links);
		if (links > 1)
			ctx->fs_links_count++;
		ctx->fs_total_count++;
	next:
		prev = dirent;
		if (dir_modified)
			(void) ext2fs_get_rec_len(fs, dirent, &rec_len);
		offset += rec_len;
		dot_state++;
	} while (offset < fs->blocksize);
#if 0
	printf("\n");
#endif
#ifdef ENABLE_HTREE
	if (dx_db) {
#ifdef DX_DEBUG
		printf("db_block %d, type %d, min_hash 0x%0x, max_hash 0x%0x\n",
		       db->blockcnt, dx_db->type,
		       dx_db->min_hash, dx_db->max_hash);
#endif
		cd->pctx.dir = cd->pctx.ino;
		if ((dx_db->type == DX_DIRBLOCK_ROOT) ||
		    (dx_db->type == DX_DIRBLOCK_NODE))
			parse_int_node(fs, db, cd, dx_dir, buf);
	}
#endif /* ENABLE_HTREE */
	if (offset != fs->blocksize) {
		cd->pctx.num = rec_len - fs->blocksize + offset;
		if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) {
			dirent->rec_len = cd->pctx.num;
			dir_modified++;
		}
	}
	if (dir_modified) {
		cd->pctx.errcode = ext2fs_write_dir_block3(fs, block_nr, buf, 0);
		if (cd->pctx.errcode) {
			if (!fix_problem(ctx, PR_2_WRITE_DIRBLOCK,
					 &cd->pctx))
				goto abort_free_dict;
		}
		ext2fs_mark_changed(fs);
	}
	dict_free_nodes(&de_dict);
	return 0;
abort_free_dict:
	ctx->flags |= E2F_FLAG_ABORT;
	dict_free_nodes(&de_dict);
	return DIRENT_ABORT;
}
Example #23
0
tree
gfc_conv_constant_to_tree (gfc_expr * expr)
{
    tree res;

    gcc_assert (expr->expr_type == EXPR_CONSTANT);

    /* If it is has a prescribed memory representation, we build a string
       constant and VIEW_CONVERT to its type.  */

    switch (expr->ts.type)
    {
    case BT_INTEGER:
        if (expr->representation.string)
            return fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
                                    gfc_get_int_type (expr->ts.kind),
                                    gfc_build_string_const (expr->representation.length,
                                            expr->representation.string));
        else
            return gfc_conv_mpz_to_tree (expr->value.integer, expr->ts.kind);

    case BT_REAL:
        if (expr->representation.string)
            return fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
                                    gfc_get_real_type (expr->ts.kind),
                                    gfc_build_string_const (expr->representation.length,
                                            expr->representation.string));
        else
            return gfc_conv_mpfr_to_tree (expr->value.real, expr->ts.kind, expr->is_snan);

    case BT_LOGICAL:
        if (expr->representation.string)
        {
            tree tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
                                        gfc_get_int_type (expr->ts.kind),
                                        gfc_build_string_const (expr->representation.length,
                                                expr->representation.string));
            if (!integer_zerop (tmp) && !integer_onep (tmp))
                gfc_warning ("Assigning value other than 0 or 1 to LOGICAL"
                             " has undefined result at %L", &expr->where);
            return fold_convert (gfc_get_logical_type (expr->ts.kind), tmp);
        }
        else
            return build_int_cst (gfc_get_logical_type (expr->ts.kind),
                                  expr->value.logical);

    case BT_COMPLEX:
        if (expr->representation.string)
            return fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
                                    gfc_get_complex_type (expr->ts.kind),
                                    gfc_build_string_const (expr->representation.length,
                                            expr->representation.string));
        else
        {
            tree real = gfc_conv_mpfr_to_tree (mpc_realref (expr->value.complex),
                                               expr->ts.kind, expr->is_snan);
            tree imag = gfc_conv_mpfr_to_tree (mpc_imagref (expr->value.complex),
                                               expr->ts.kind, expr->is_snan);

            return build_complex (gfc_typenode_for_spec (&expr->ts),
                                  real, imag);
        }

    case BT_CHARACTER:
        res = gfc_build_wide_string_const (expr->ts.kind,
                                           expr->value.character.length,
                                           expr->value.character.string);
        return res;

    case BT_HOLLERITH:
        return gfc_build_string_const (expr->representation.length,
                                       expr->representation.string);

    default:
        fatal_error ("gfc_conv_constant_to_tree(): invalid type: %s",
                     gfc_typename (&expr->ts));
    }
}
Example #24
0
/* perform_save():
   Write the state to the output stream. This returns 0 on success,
   1 on failure.
*/
glui32 perform_save(strid_t str)
{
  dest_t dest;
  int ix;
  glui32 res, lx, val;
  glui32 memstart, memlen, stackstart, stacklen, heapstart, heaplen;
  glui32 filestart=0, filelen;

  stream_get_iosys(&val, &lx);
  if (val != 2) {
    /* Not using the Glk I/O system, so bail. This function only
       knows how to write to a Glk stream. */
    fatal_error("Streams are only available in Glk I/O system.");
  }

  if (str == 0)
    return 1;

  dest.ismem = FALSE;
  dest.size = 0;
  dest.pos = 0;
  dest.ptr = NULL;
  dest.str = str;

  res = 0;

  /* Quetzal header. */
  if (res == 0) {
    res = write_long(&dest, IFFID('F', 'O', 'R', 'M'));
  }
  if (res == 0) {
    res = write_long(&dest, 0); /* space for file length */
    filestart = dest.pos;
  }

  if (res == 0) {
    res = write_long(&dest, IFFID('I', 'F', 'Z', 'S')); /* ### ? */
  }

  /* Header chunk. This is the first 128 bytes of memory. */
  if (res == 0) {
    res = write_long(&dest, IFFID('I', 'F', 'h', 'd'));
  }
  if (res == 0) {
    res = write_long(&dest, 128);
  }
  for (ix=0; res==0 && ix<128; ix++) {
    res = write_byte(&dest, Mem1(ix));
  }
  /* Always even, so no padding necessary. */
  
  /* Memory chunk. */
  if (res == 0) {
    res = write_long(&dest, IFFID('C', 'M', 'e', 'm'));
  }
  if (res == 0) {
    res = write_long(&dest, 0); /* space for chunk length */
  }
  if (res == 0) {
    memstart = dest.pos;
    res = write_memstate(&dest);
    memlen = dest.pos - memstart;
  }
  if (res == 0 && (memlen & 1) != 0) {
    res = write_byte(&dest, 0);
  }

  /* Heap chunk. */
  if (res == 0) {
    res = write_long(&dest, IFFID('M', 'A', 'l', 'l'));
  }
  if (res == 0) {
    res = write_long(&dest, 0); /* space for chunk length */
  }
  if (res == 0) {
    heapstart = dest.pos;
    res = write_heapstate(&dest, TRUE);
    heaplen = dest.pos - heapstart;
  }
  /* Always even, so no padding necessary. */

  /* Stack chunk. */
  if (res == 0) {
    res = write_long(&dest, IFFID('S', 't', 'k', 's'));
  }
  if (res == 0) {
    res = write_long(&dest, 0); /* space for chunk length */
  }
  if (res == 0) {
    stackstart = dest.pos;
    res = write_stackstate(&dest, TRUE);
    stacklen = dest.pos - stackstart;
  }
  if (res == 0 && (stacklen & 1) != 0) {
    res = write_byte(&dest, 0);
  }

  filelen = dest.pos - filestart;

  /* Okay, fill in all the lengths. */
  if (res == 0) {
    res = reposition_write(&dest, memstart-4);
  }
  if (res == 0) {
    res = write_long(&dest, memlen);
  }
  if (res == 0) {
    res = reposition_write(&dest, heapstart-4);
  }
  if (res == 0) {
    res = write_long(&dest, heaplen);
  }
  if (res == 0) {
    res = reposition_write(&dest, stackstart-4);
  }
  if (res == 0) {
    res = write_long(&dest, stacklen);
  }
  if (res == 0) {
    res = reposition_write(&dest, filestart-4);
  }
  if (res == 0) {
    res = write_long(&dest, filelen);
  }

  /* All done. */
    
  return res;
}
static int progress_one_device(mca_bcol_iboffload_device_t *device)
{
    int ne, rc, count = 0;

    mca_bcol_iboffload_collfrag_t *coll_frag;
    mca_bcol_iboffload_collreq_t *coll_request;

    struct ibv_wc wc;
    memset(&wc, 0, sizeof(struct ibv_wc));

    /*
     * poll for collective completion - does not mean resources can
     * be freed, as incomplete network level sends may still be pending
     */

    /* Poll for completion on completion on wait MQEs */
    if(0 != (ne = ibv_poll_cq(device->ib_mq_cq, 1, &wc))) {
        do {
            if (OPAL_UNLIKELY(0 > ne)) {
                IBOFFLOAD_ERROR(("Device %s: "
                                 "failed to poll MQ completion queue\n",
                                 ibv_get_device_name(device->dev.ib_dev)));
                fatal_error("failed to poll MQ completion queue\n");
                return count;
            }

            if (OPAL_UNLIKELY(IBV_WC_SUCCESS != wc.status)) {
                IBOFFLOAD_ERROR(("Device %s: "
                                 "the completion with error on wait was gotten, status %d, opcode %d, "
                                 "vendor_err 0x%x, qp %x, id 0x%x\n", ibv_get_device_name(device->dev.ib_dev),
                                 wc.status, wc.opcode, wc.vendor_err, wc.qp_num, wc.wr_id));
                fatal_error("wc.status \n");
                return count;
            }

            IBOFFLOAD_VERBOSE(10, ("The MQ completion was polled.\n"));

            ++count;

            /* get pointer to mca_bcol_iboffload_collfrag_t */
            coll_frag = (mca_bcol_iboffload_collfrag_t*)
                        (uint64_t) (uintptr_t) wc.wr_id;

            /* Only last MQ task of collective frag
               sends completion signal, so if we got it =>
               all MQEs were done. */
            coll_frag->complete = true;

            IBOFFLOAD_VERBOSE(10, ("MQ completion for algorithm %d coll_frag_addr %p ml buffer index %d",
                                   coll_frag->alg, (void *)coll_frag, coll_frag->coll_full_req->ml_buffer_index));

            /* full request descriptor */
            coll_request = coll_frag->coll_full_req;

            coll_request->n_frag_mpi_complete++;

            /*
             * at this stage all receives have been completed, so
             * unpack the data to user buffer, the resources will be released when we will done with all
             * element in the task list
             */

            if (NULL != coll_request->completion_cb_fn) {
                if (OMPI_SUCCESS !=
                        coll_request->completion_cb_fn(coll_frag)) {
                    fatal_error("coll_request->completion_cb_fn\n");
                    return count;
                }
            }

            if (coll_request->n_frag_mpi_complete ==
                    coll_request->n_fragments) {
                coll_request->super.req_complete = true;
                opal_condition_broadcast(&ompi_request_cond);
                IBOFFLOAD_VERBOSE(10, ("After opal_condition_broadcast.\n"));
            }

            rc = handle_collfrag_done(coll_frag, coll_request, device);
            if (0 != rc) {
                return count;
            }
        } while(0 != (ne = ibv_poll_cq(device->ib_mq_cq, 1, &wc)));

        return count;
    }

    /* poll the send completion queue */
    do {
        ne = ibv_poll_cq(device->ib_cq, 1, &wc);
        if (0 < ne) {
            if (OPAL_UNLIKELY(IBV_WC_SUCCESS != wc.status)) {
                IBOFFLOAD_ERROR(("Device %s, "
                                 "the completion with error on send was gotten, status %d, opcode %d, "
                                 "vendor_err 0x%x, qp %x, id 0x%x\n", ibv_get_device_name(device->dev.ib_dev),
                                 wc.status, wc.opcode, wc.vendor_err, wc.qp_num, wc.wr_id));

#if OPAL_ENABLE_DEBUG
                {
                    mca_bcol_iboffload_module_t *iboffload;
                    int i, qp_index, num_qps = mca_bcol_iboffload_component.num_qps;

                    coll_frag = (mca_bcol_iboffload_collfrag_t*)
                                (uint64_t) (uintptr_t) wc.wr_id;

                    iboffload = coll_frag->coll_full_req->module;

                    for (i = 0; i < iboffload->num_endpoints; ++i) {
                        mca_bcol_iboffload_endpoint_t *ep = iboffload->endpoints[i];

                        for (qp_index = 0; qp_index < num_qps; ++qp_index) {
                            if (NULL != ep->qps[qp_index].qp->lcl_qp &&
                                    wc.qp_num == ep->qps[qp_index].qp->lcl_qp->qp_num) {
                                IBOFFLOAD_ERROR(("Module - %p, coll_frag - %p, "
                                                 "destination %d, qp index - %d.",
                                                 iboffload, coll_frag, i, qp_index));
                            }
                        }
                    }
                }
#endif
                fatal_error("Failed to ibv_poll_cq\n");
                return count;
            }

            ++count;

            /* get pointer to mca_bcol_iboffload_collfrag_t */
            coll_frag = (mca_bcol_iboffload_collfrag_t*)
                        (uint64_t) (uintptr_t) wc.wr_id;

            /* update the number of completed sends */
            coll_frag->n_sends_completed++;

            IBOFFLOAD_VERBOSE(10, ("Send CQ completion for algorithm %d coll_frag_addr %p ml buffer index %d",
                                   coll_frag->alg, (void *)coll_frag, coll_frag->coll_full_req->ml_buffer_index));

            IBOFFLOAD_VERBOSE(10, ("Alg %d coll_frag_addr %p: n_sends_completed - %d, n_sends - %d.\n",
                                   coll_frag->alg, (void *)coll_frag,
                                   coll_frag->n_sends_completed,
                                   coll_frag->n_sends));

            assert(coll_frag->n_sends_completed <= coll_frag->n_sends);

            /* full message descriptor */
            coll_request = coll_frag->coll_full_req;

            /* check to see if all sends are complete from the network
             * perspective */
            rc = handle_collfrag_done(coll_frag, coll_request, device);
            if (0 != rc) {
                return count;
            }
        } else if (OPAL_UNLIKELY(0 > ne)) {
            IBOFFLOAD_ERROR(("Device %s: "
                             "failed to poll send completion queue\n",
                             ibv_get_device_name(device->dev.ib_dev)));
            fatal_error("failed to poll send completion queue\n");
            return count;
        }
    } while (0 != ne);

    return count;
}
Example #26
0
/* perform_restore():
   Pull a state pointer from a stream. This returns 0 on success,
   1 on failure. Note that if it succeeds, the frameptr, localsbase,
   and valstackbase registers are invalid; they must be rebuilt from
   the stack.
 
   If fromshell is true, the restore is being invoked by the library
   shell (an autorestore of some kind). This currently happens only in
   iosglk.
*/
glui32 perform_restore(strid_t str, int fromshell)
{
  dest_t dest;
  int ix;
  glui32 lx, res, val;
  glui32 filestart, filelen;
  glui32 heapsumlen = 0;
  glui32 *heapsumarr = NULL;

  stream_get_iosys(&val, &lx);
  if (val != 2 && !fromshell) {
    /* Not using the Glk I/O system, so bail. This function only
       knows how to read from a Glk stream. (But in the autorestore
       case, iosys hasn't been set yet, so ignore this test.) */
    fatal_error("Streams are only available in Glk I/O system.");
  }

  if (str == 0)
    return 1;

  dest.ismem = FALSE;
  dest.size = 0;
  dest.pos = 0;
  dest.ptr = NULL;
  dest.str = str;

  res = 0;

  /* ### the format errors checked below should send error messages to
     the current stream. */

  if (res == 0) {
    res = read_long(&dest, &val);
  }
  if (res == 0 && val != IFFID('F', 'O', 'R', 'M')) {
    /* ### bad header */
    return 1;
  }
  if (res == 0) {
    res = read_long(&dest, &filelen);
  }
  filestart = dest.pos;

  if (res == 0) {
    res = read_long(&dest, &val);
  }
  if (res == 0 && val != IFFID('I', 'F', 'Z', 'S')) { /* ### ? */
    /* ### bad header */
    return 1;
  }

  while (res == 0 && dest.pos < filestart+filelen) {
    /* Read a chunk and deal with it. */
    glui32 chunktype=0, chunkstart=0, chunklen=0;
    unsigned char dummy;

    if (res == 0) {
      res = read_long(&dest, &chunktype);
    }
    if (res == 0) {
      res = read_long(&dest, &chunklen);
    }
    chunkstart = dest.pos;

    if (chunktype == IFFID('I', 'F', 'h', 'd')) {
      for (ix=0; res==0 && ix<128; ix++) {
        res = read_byte(&dest, &dummy);
        if (res == 0 && Mem1(ix) != dummy) {
          /* ### non-matching header */
          return 1;
        }
      }
    }
    else if (chunktype == IFFID('C', 'M', 'e', 'm')) {
      res = read_memstate(&dest, chunklen);
    }
    else if (chunktype == IFFID('M', 'A', 'l', 'l')) {
      res = read_heapstate(&dest, chunklen, TRUE, &heapsumlen, &heapsumarr);
    }
    else if (chunktype == IFFID('S', 't', 'k', 's')) {
      res = read_stackstate(&dest, chunklen, TRUE);
    }
    else {
      /* Unknown chunk type. Skip it. */
      for (lx=0; res==0 && lx<chunklen; lx++) {
        res = read_byte(&dest, &dummy);
      }
    }

    if (chunkstart+chunklen != dest.pos) {
      /* ### funny chunk length */
      return 1;
    }

    if ((chunklen & 1) != 0) {
      if (res == 0) {
        res = read_byte(&dest, &dummy);
      }
    }
  }

  if (res == 0) {
    if (heapsumarr) {
      /* The summary might have come from any interpreter, so it could
         be out of order. We'll sort it. */
      glulx_sort(heapsumarr+2, (heapsumlen-2)/2, 2*sizeof(glui32),
        &sort_heap_summary);
      res = heap_apply_summary(heapsumlen, heapsumarr);
    }
  }

  if (res)
    return 1;

  return 0;
}
/**
 * Process mondoarchive's command-line switches.
 * @param bkpinfo The backup information structure to populate.
 * @param flag_val An array of the argument passed to each switch (the letter is the index).
 * If a switch is not set or has no argument, the field in @p flag_val doesn't matter.
 * @param flag_set An array of <tt>bool</tt>s indexed by switch letter: TRUE if it's set,
 * FALSE if it's not.
 * @return The number of problems with the switches, or 0 for success.
 * @bug Maybe include a list of all switches (inc. intentionally undocumented ones not in the manual!) here?
 */
int
process_switches(struct s_bkpinfo *bkpinfo,
				 char flag_val[128][MAX_STR_LEN], bool flag_set[128])
{

	/*@ ints *** */
	int i = 0;
	int retval = 0;
	int percent = 0;

	/*@ buffers ** */
	char *tmp;
	char *psz;

	long itbs;

	struct stat buf;

	malloc_string(tmp);
	malloc_string(psz);

	assert(bkpinfo != NULL);
	assert(flag_val != NULL);
	assert(flag_set != NULL);

	bkpinfo->internal_tape_block_size = DEFAULT_INTERNAL_TAPE_BLOCK_SIZE;

/* compulsory */
	i = flag_set['c'] + flag_set['i'] + flag_set['n'] +
		flag_set['t'] + flag_set['u'] + flag_set['r'] +
		flag_set['w'] + flag_set['C'];
	if (i == 0) {
		retval++;
		log_to_screen("You must specify the media type\n");
	}
	if (i > 1) {
		retval++;
		log_to_screen("Please specify only one media type\n");
	}
	if (flag_set['K']) {
		g_loglevel = atoi(flag_val['K']);
		if (g_loglevel < 3) {
			g_loglevel = 3;
		}
	}
	if (flag_set['L'] && flag_set['0']) {
		retval++;
		log_to_screen("You cannot have 'no compression' _and_ LZOP.\n");
	}
	bkpinfo->backup_data = flag_set['O'];
	bkpinfo->verify_data = flag_set['V'];
	if (flag_set['I'] && !bkpinfo->backup_data) {
		log_to_screen("-I switch is ignored if just verifying");
	}
	if (flag_set['E'] && !bkpinfo->backup_data) {
		log_to_screen("-E switch is ignored if just verifying");
	}

	if (!find_home_of_exe("afio")) {
		if (find_home_of_exe("star")) {
			flag_set['R'] = TRUE;
			log_msg(1, "Using star instead of afio");
		} else {
			fatal_error
				("Neither afio nor star is installed. Please install at least one.");
		}
	}

	if (flag_set['R']) {
		bkpinfo->use_star = TRUE;
		if (flag_set['L']) {
			fatal_error("You may not use star and lzop at the same time.");
		}
		if (!find_home_of_exe("star")) {
			fatal_error
				("Please install 'star' RPM or tarball if you are going to use -R. Thanks.");
		}
	}
	if (flag_set['W']) {
		bkpinfo->nonbootable_backup = TRUE;
		log_to_screen("Warning - you have opted for non-bootable backup");
		if (flag_set['f'] || flag_set['l']) {
			log_to_screen
				("You don't need to specify bootloader or bootdevice");
		}
	}
	if (flag_set['t'] && flag_set['H']) {
		fatal_error
			("Sorry, you may not nuke w/o warning from tape. Drop -H, please.");
	}
	if (flag_set['I']) {
		if (!strcmp(bkpinfo->include_paths, "/")) {
			log_msg(2, "'/' is pleonastic.");
			bkpinfo->include_paths[0] = '\0';
		}
		if (bkpinfo->include_paths[0]) {
			strcat(bkpinfo->include_paths, " ");
		}
		if (stat(flag_val['I'], &buf) != 0) {
			log_msg("ERROR ! %s doesn't exist", flag_val['I']);
			fatal_error("ERROR ! You specified a directory to include which doesn't exist");
		}
		strncpy(bkpinfo->include_paths + strlen(bkpinfo->include_paths),
				flag_val['I'],
				MAX_STR_LEN - strlen(bkpinfo->include_paths));
		log_msg(1, "include_paths is now '%s'", bkpinfo->include_paths);
		if (bkpinfo->include_paths[0] == '-') {
			retval++;
			log_to_screen("Please supply a sensible value with '-I'\n");
		}
	}

	if (g_kernel_version >= 2.6 && !flag_set['d']
		&& (flag_set['c'] || flag_set['w'])) {
		fatal_error
			("If you are using the 2.6.x kernel, please specify the CD-R(W) device.");
	}


	if (flag_set['J']) {
		if (flag_set['I']) {
			retval++;
			log_to_screen
				("Please do not use -J in combination with -I. If you want to make a list of files to backup, that's fine, use -J <filename> but please don't muddy the waters by combining -J with -I. Thanks. :-)");
		}
		bkpinfo->make_filelist = FALSE;
		strcpy(bkpinfo->include_paths, flag_val['J']);
	}
	if (flag_set['c'] || flag_set['w'] || flag_set['C'] || flag_set['r']) {
		if (!flag_set['r'] && g_kernel_version <= 2.5
			&& strstr(flag_val['d'], "/dev/")) {
			fatal_error
				("Please don't give a /dev entry. Give a SCSI node for the parameter of the -d flag.");
		}
		if (flag_set['r'] && g_kernel_version <= 2.5
			&& !strstr(flag_val['d'], "/dev/")) {
			fatal_error
				("Please give a /dev entry, not a SCSI node, as the parameter of the -d flag.");
		}
		if (g_kernel_version >= 2.6 && !strstr(flag_val['d'], "/dev/")) {
			log_to_screen
				("Linus says 2.6 has a broken ide-scsi module. Proceed at your own risk...");
		}

		if (system("which cdrecord > /dev/null 2> /dev/null")
			&& system("which dvdrecord > /dev/null 2> /dev/null")) {
			fatal_error
				("Please install dvdrecord/cdrecord and try again.");
		}
		if (flag_set['C']) {
			bkpinfo->cdrw_speed = atoi(flag_val['C']);
			if (bkpinfo->cdrw_speed < 1) {
				fatal_error
					("You specified a silly speed for a CD-R[W] drive");
			}
			if (!flag_set['L']) {
				log_to_screen
					("You must use -L with -C. Therefore I am setting it for you.");
				flag_set['L'] = 1;
				flag_val['L'][0] = '\0';
			}
		} else {
			log_msg(3, "flag_val['c'] = %s", flag_val['c']);
			log_msg(3, "flag_val['w'] = %s", flag_val['w']);
//    log_msg(3, "flag_set['r'] = %i", flag_set['r'] );
			if (flag_set['c']) {
				bkpinfo->cdrw_speed = atoi(flag_val['c']);
			} else if (flag_set['w']) {
				bkpinfo->cdrw_speed = atoi(flag_val['w']);
			} else if (flag_set['r']) {
				bkpinfo->cdrw_speed = 1;	/*atoi(flag_val['r']); */
			}

			if (bkpinfo->cdrw_speed < 1) {
				fatal_error
					("You specified a silly speed for a CD-R[W] drive");
			}
		}
	}
	if (flag_set['t'] && !flag_set['d']) {
		log_it("Hmm! No tape drive specified. Let's see what we can do.");
		if (find_tape_device_and_size(flag_val['d'], tmp)) {
			fatal_error
				("Tape device not specified. I couldn't find it either.");
		}
		flag_set['d'] = TRUE;
		sprintf(tmp,
				"You didn't specify a tape streamer device. I'm assuming %s",
				flag_val['d']);
		log_to_screen(tmp);
		percent = 0;
	}

	if (flag_set['r'])			// DVD
	{
		if (flag_set['m']) {
			fatal_error
				("Manual CD tray (-m) not yet supported in conjunction w/ DVD drives. Drop -m.");
		}
		if (!flag_set['d']) {
			if (!find_dvd_device(flag_val['d'], FALSE)) {
				flag_set['d'] = TRUE;
				log_to_screen("I guess DVD drive is at %s", flag_val['d']);
			}
		}
		if (!find_home_of_exe("growisofs")) {
			fatal_error
				("Please install growisofs (probably part of dvd+rw-tools). If you want DVD support, you need it.");
		}
		if (!find_home_of_exe("dvd+rw-format")) {
			fatal_error
				("Please install dvd+rw-format (probably part of dvd+rw-tools). If you want DVD support, you need it.");
		}
		if (strchr(flag_val['d'], ',')) {
			fatal_error
				("Please don't give a SCSI node. Give a _device_, preferably a /dev entry, for the parameter of the -d flag.");
		}
		if (!flag_set['s']) {
			sprintf(flag_val['s'], "%d", DEFAULT_DVD_DISK_SIZE);	// 4.7 salesman's GB = 4.482 real GB = 4582 MB
			strcat(flag_val['s'], "m");
			log_to_screen
				("You did not specify a size (-s) for DVD. I'm guessing %s.",
				 flag_val['s']);
			flag_set['s'] = 1;
		}
/*
      if (flag_set['Z']) {
	  bkpinfo->blank_dvd_first = TRUE;
      }
*/
	}

	if (flag_set['t'] || flag_set['u']) {	/* tape size */
		if (strchr(flag_val['d'], ',')) {
			fatal_error
				("Please don't give a SCSI node. Give a _device_, preferably a /dev entry, for the parameter of the -d flag.");
		}
		if (flag_set['O']) {
			if (flag_set['s']) {
				if (flag_set['t']) {
					fatal_error
						("For the moment, please don't specify a tape size. Mondo should handle end-of-tape gracefully anyway.");
				}
				if (process_the_s_switch(bkpinfo, flag_val['s'])) {
					fatal_error("Bad -s switch");
				}
			} else if (flag_set['u'] || flag_set['t']) {
				for (i = 0; i <= MAX_NOOF_MEDIA; i++) {
					bkpinfo->media_size[i] = 0;
				}
			} else {
				retval++;
				log_to_screen("Tape size not specified.\n");
			}
		}
	} else {					/* CD size */
		if (flag_set['s']) {
			if (process_the_s_switch(bkpinfo, flag_val['s'])) {
				fatal_error("Bad -s switch");
			}
		}
		if (flag_set['w']) {
			bkpinfo->wipe_media_first = TRUE;
		}						/* CD-RW */
	}
	if (flag_set['n']) {
		strncpy(bkpinfo->nfs_mount, flag_val['n'], MAX_STR_LEN);
		if (!flag_set['d']) {
			strncpy(bkpinfo->nfs_remote_dir, "/", MAX_STR_LEN);
		}
		sprintf(tmp, "mount | grep -x \"%s .*\" | cut -d' ' -f3",
				bkpinfo->nfs_mount);
		strncpy(bkpinfo->isodir,
				call_program_and_get_last_line_of_output(tmp),
				MAX_STR_LEN / 4);
		if (strlen(bkpinfo->isodir) < 3) {
			retval++;
			log_to_screen("NFS share is not mounted. Please mount it.\n");
		}
		log_msg(3, "mount = %s", bkpinfo->nfs_mount);
		log_msg(3, "isodir= %s", bkpinfo->isodir);
	}
	if (flag_set['c']) {
		bkpinfo->backup_media_type = cdr;
	}
	if (flag_set['C']) {
		bkpinfo->backup_media_type = cdstream;
	}
	if (flag_set['i']) {
		bkpinfo->backup_media_type = iso;
	}
	if (flag_set['n']) {
		bkpinfo->backup_media_type = nfs;
	}
	if (flag_set['r']) {
		bkpinfo->backup_media_type = dvd;
	}
	if (flag_set['t']) {
		bkpinfo->backup_media_type = tape;
	}
	if (flag_set['u']) {
		bkpinfo->backup_media_type = udev;
	}
	if (flag_set['w']) {
		bkpinfo->backup_media_type = cdrw;
	}

/* optional, popular */
	if (flag_set['g']) {
		g_text_mode = FALSE;
	}
	if (flag_set['E']) {
		if (bkpinfo->exclude_paths[0]) {
			strcat(bkpinfo->exclude_paths, " ");
		}
		if (stat(flag_val['E'], &buf) != 0) {
			log_msg(1, "WARNING ! %s doesn't exist", flag_val['E']);
		}
		strncpy(bkpinfo->exclude_paths + strlen(bkpinfo->exclude_paths),
				flag_val['E'],
				MAX_STR_LEN - strlen(bkpinfo->exclude_paths));
	}
	if (flag_set['e']) {
		bkpinfo->please_dont_eject = TRUE;
	}
	if (flag_set['N'])			// exclude NFS mounts & devices
	{
//      strncpy(psz, list_of_NFS_devices_and_mounts(), MAX_STR_LEN);
		strncpy(psz, list_of_NFS_mounts_only(), MAX_STR_LEN);
		if (bkpinfo->exclude_paths[0]) {
			strncat(bkpinfo->exclude_paths, " ", MAX_STR_LEN);
		}
		strncat(bkpinfo->exclude_paths, psz, MAX_STR_LEN);
		log_msg(3, "-N means we're now excluding %s",
				bkpinfo->exclude_paths);
	}
	if (strlen(bkpinfo->exclude_paths) >= MAX_STR_LEN) {
		fatal_error
			("Your '-E' parameter is too long. Please use '-J'. (See manual.)");
	}
	if (flag_set['b']) {
		strcpy(psz, flag_val['b']);
		log_msg(1, "psz = '%s'", psz);
		if (psz[strlen(psz) - 1] == 'k') {
			psz[strlen(psz) - 1] = '\0';
			itbs = atol(psz) * 1024L;
		} else {
			itbs = atol(psz);
		}
		log_msg(1, "'%s' --> %ld", flag_val['b'], itbs);
		log_msg(1, "Internal tape block size is now %ld bytes", itbs);
		if (itbs % 512 != 0 || itbs < 256 || itbs > 1024L * 1024) {
			fatal_error
				("Are you nuts? Silly, your internal tape block size is. Abort, I shall.");
		}
		bkpinfo->internal_tape_block_size = itbs;
	}
	if (flag_set['D']) {
		bkpinfo->differential = 1;
//      bkpinfo->differential = atoi (flag_val['D']);
		if ((bkpinfo->differential < 1) || (bkpinfo->differential > 9)) {
			fatal_error
				("The D option should be between 1 and 9 inclusive");
		}
	}
	if (flag_set['x']) {
		strncpy(bkpinfo->image_devs, flag_val['x'], MAX_STR_LEN / 4);
		if (run_program_and_log_output("which ntfsclone", 2)) {
			fatal_error("Please install ntfsprogs package/tarball.");
		}
	}
	if (flag_set['m']) {
		bkpinfo->manual_cd_tray = TRUE;
	}
	if (flag_set['k']) {
		strncpy(bkpinfo->kernel_path, flag_val['k'], MAX_STR_LEN);
		if (!strcmp(bkpinfo->kernel_path, "failsafe")) {
			strcpy(bkpinfo->kernel_path, "FAILSAFE");
		}
		if (strcmp(bkpinfo->kernel_path, "FAILSAFE")
			&& !does_file_exist(bkpinfo->kernel_path)) {
			retval++;
			sprintf(tmp,
					"You specified kernel '%s', which does not exist\n",
					bkpinfo->kernel_path);
			log_to_screen(tmp);
		}
	}
	if (flag_set['p']) {
		strncpy(bkpinfo->prefix, flag_val['p'], MAX_STR_LEN / 4);
	}


	if (flag_set['d']) {		/* backup directory (if ISO/NFS) */
		if (flag_set['i']) {
			strncpy(bkpinfo->isodir, flag_val['d'], MAX_STR_LEN / 4);
			sprintf(tmp, "ls -l %s", bkpinfo->isodir);
			if (run_program_and_log_output(tmp, FALSE)) {
				fatal_error
					("output folder does not exist - please create it");
			}
		} else if (flag_set['n']) {
			strncpy(bkpinfo->nfs_remote_dir, flag_val['d'], MAX_STR_LEN);
		} else {				/* backup device (if tape/CD-R/CD-RW) */

			strncpy(bkpinfo->media_device, flag_val['d'], MAX_STR_LEN / 4);
		}
	}

	if (flag_set['n']) {
		sprintf(tmp, "echo hi > %s/%s/.dummy.txt", bkpinfo->isodir,
				bkpinfo->nfs_remote_dir);
		if (run_program_and_log_output(tmp, FALSE)) {
			retval++;
			sprintf(tmp,
					"Are you sure directory '%s' exists in remote dir '%s'?\nIf so, do you have rights to write to it?\n",
					bkpinfo->nfs_remote_dir, bkpinfo->nfs_mount);
			log_to_screen(tmp);
		}
	}

	if (!flag_set['d']
		&& (flag_set['c'] || flag_set['w'] || flag_set['C'])) {
		if (g_kernel_version >= 2.6) {
			if (popup_and_get_string
				("Device", "Please specify the device",
				 bkpinfo->media_device, MAX_STR_LEN / 4)) {
				retval++;
				log_to_screen("User opted to cancel.");
			}
		} else if (find_cdrw_device(bkpinfo->media_device)) {
			retval++;
			log_to_screen
				("Tried and failed to find CD-R[W] drive automatically.\n");
		} else {
			flag_set['d'] = TRUE;
			strncpy(flag_val['d'], bkpinfo->media_device, MAX_STR_LEN / 4);
		}
	}

	if (!flag_set['d'] && !flag_set['n'] && !flag_set['C']) {
		retval++;
		log_to_screen("Please specify the backup device/directory.\n");
		fatal_error
			("You didn't use -d to specify the backup device/directory.");
	}
/* optional, obscure */
	for (i = '0'; i <= '9'; i++) {
		if (flag_set[i]) {
			bkpinfo->compression_level = i - '0';
		}						/* not '\0' but '0' */
	}
	if (flag_set['S']) {
		sprintf(bkpinfo->scratchdir, "%s/mondo.scratch.%ld", flag_val['S'],
				random() % 32768);
	}
	if (flag_set['T']) {
		sprintf(bkpinfo->tmpdir, "%s/tmp.mondo.%ld", flag_val['T'],
				random() % 32768);
		sprintf(tmp, "touch %s/.foo.dat", flag_val['T']);
		if (run_program_and_log_output(tmp, 1)) {
			retval++;
			log_to_screen
				("Please specify a tempdir which I can write to. :)");
			fatal_error("I cannot write to the tempdir you specified.");
		}
		sprintf(tmp, "ln -sf %s/.foo.dat %s/.bar.dat", flag_val['T'],
				flag_val['T']);
		if (run_program_and_log_output(tmp, 1)) {
			retval++;
			log_to_screen
				("Please don't specify a SAMBA or VFAT or NFS tmpdir.");
			fatal_error("I cannot write to the tempdir you specified.");
		}
	}
	if (flag_set['A']) {
		strncpy(bkpinfo->call_after_iso, flag_val['A'], MAX_STR_LEN);
	}
	if (flag_set['B']) {
		strncpy(bkpinfo->call_before_iso, flag_val['B'], MAX_STR_LEN);
	}
	if (flag_set['F']) {
		g_skip_floppies = TRUE;
	}
	if (flag_set['H']) {
		g_cd_recovery = TRUE;
	}
	if (flag_set['l']) {
#ifdef __FreeBSD__
#  define BOOT_LOADER_CHARS "GLBMR"
#else
#  ifdef __IA64__
#    define BOOT_LOADER_CHARS "GER"
#  else
#    define BOOT_LOADER_CHARS "GLR"
#  endif
#endif
		if (!strchr
			(BOOT_LOADER_CHARS,
			 (bkpinfo->boot_loader = flag_val['l'][0]))) {
			log_msg(1, "%c? WTF is %c? I need G, L, E or R.",
					bkpinfo->boot_loader, bkpinfo->boot_loader);
			fatal_error
				("Please specify GRUB, LILO, ELILO  or RAW with the -l switch");
		}
#undef BOOT_LOADER_CHARS
	}
	if (flag_set['f']) {
		strncpy(bkpinfo->boot_device,
				resolve_softlinks_to_get_to_actual_device_file(flag_val
															   ['f']),
				MAX_STR_LEN / 4);
	}
	if (flag_set['P']) {
		strncpy(bkpinfo->postnuke_tarball, flag_val['P'], MAX_STR_LEN);
	}
	if (flag_set['Q']) {
		i = which_boot_loader(tmp);
		log_msg(3, "boot loader is %c, residing at %s", i, tmp);
		printf("boot loader is %c, residing at %s\n", i, tmp);
		finish(0);
	}
	if (flag_set['L']) {
		bkpinfo->use_lzo = TRUE;
		if (run_program_and_log_output("which lzop", FALSE)) {
			retval++;
			log_to_screen
				("Please install LZOP. You can't use '-L' until you do.\n");
		}
	}

	if (!flag_set['o']
		&&
		!run_program_and_log_output
		("grep -i suse /etc/issue.net | grep 64", TRUE)) {
		bkpinfo->make_cd_use_lilo = TRUE;
		log_to_screen
			("Forcing you to use LILO. SuSE 9.0 (64-bit) has a broken mkfs.vfat binary.");
	}
	if (flag_set['o']) {
		bkpinfo->make_cd_use_lilo = TRUE;
	}
#ifndef __FreeBSD__
	else {
		if (!is_this_a_valid_disk_format("vfat")) {
			bkpinfo->make_cd_use_lilo = TRUE;
			log_to_screen
				("Your kernel appears not to support vfat filesystems. I am therefore");
			log_to_screen
				("using LILO instead of SYSLINUX as the CD/floppy's boot loader.");
		}
		if (run_program_and_log_output("which mkfs.vfat", FALSE)) {
			bkpinfo->make_cd_use_lilo = TRUE;
#ifdef __IA32__
			log_to_screen
				("Your filesystem is missing 'mkfs.vfat', so I cannot use SYSLINUX as");
			log_to_screen
				("your boot loader. I shall therefore use LILO instead.");
#endif
#ifdef __IA64__
			log_to_screen
				("Your filesystem is missing 'mkfs.vfat', so I cannot prepare the EFI");
			log_to_screen("environment correctly. Please install it.");
			fatal_error("Aborting");
#endif
		}
#ifdef __IA64__
		/* We force ELILO usage on IA64 */
		bkpinfo->make_cd_use_lilo = TRUE;
#endif
	}
#endif

	if (bkpinfo->make_cd_use_lilo && !does_file_exist("/boot/boot.b")) {
		paranoid_system("touch /boot/boot.b");
	}

	i = flag_set['O'] + flag_set['V'];
	if (i == 0) {
		retval++;
		log_to_screen("Specify backup (-O), verify (-V) or both (-OV).\n");
	}

/* and finally... */

	paranoid_free(tmp);
	paranoid_free(psz);
	return (retval);
}
Example #28
0
static glui32 read_memstate(dest_t *dest, glui32 chunklen)
{
  glui32 chunkend = dest->pos + chunklen;
  glui32 newlen;
  glui32 res, pos;
  int val;
  int runlen;
  unsigned char ch, ch2;

  heap_clear();

  res = read_long(dest, &newlen);
  if (res)
    return res;

  res = change_memsize(newlen, FALSE);
  if (res)
    return res;

  runlen = 0;
  glk_stream_set_position(gamefile, gamefile_start+ramstart, seekmode_Start);

  for (pos=ramstart; pos<endmem; pos++) {
    if (pos < endgamefile) {
      val = glk_get_char_stream(gamefile);
      if (val == -1) {
        fatal_error("The game file ended unexpectedly while restoring.");
      }
      ch = (unsigned char)val;
    }
    else {
      ch = 0;
    }

    if (dest->pos >= chunkend) {
      /* we're into the final, unstored run. */
    }
    else if (runlen) {
      runlen--;
    }
    else {
      res = read_byte(dest, &ch2);
      if (res)
        return res;
      if (ch2 == 0) {
        res = read_byte(dest, &ch2);
        if (res)
          return res;
        runlen = (glui32)ch2;
      }
      else {
        ch ^= ch2;
      }
    }

    if (pos >= protectstart && pos < protectend)
      continue;

    MemW1(pos, ch);
  }

  return 0;
}
Example #29
0
void spread_dummy_f(FILE *log,rvec x[],rvec f[],t_nrnb *nrnb,t_idef *idef,
                    t_comm_dummies *dummycomm,t_commrec *cr)
{
    real      a1,b1,c1;
    int       i,m,nra,nrd,tp,ftype;
    int       nd2,nd3,nd3FD,nd3FAD,nd3OUT,nd4FD;
    t_iatom   adum,ai,aj,ak,al;
    t_iatom   *ia;
    t_iparams *ip;

    /* We only move forces here, and they are independent of shifts */
    if (dummycomm)
        move_dummy_f(dummycomm,f,cr);

    ip     = idef->iparams;

    nd2    = 0;
    nd3    = 0;
    nd3FD  = 0;
    nd3FAD = 0;
    nd3OUT = 0;
    nd4FD  = 0;

    /* this loop goes backwards to be able to build *
     * higher type dummies from lower types         */
    for(ftype=F_NRE-1; (ftype>=0); ftype--) {
        if (interaction_function[ftype].flags & IF_DUMMY) {
            nra    = interaction_function[ftype].nratoms;
            nrd    = idef->il[ftype].nr;
            ia     = idef->il[ftype].iatoms;

            for(i=0; (i<nrd); ) {
                tp   = ia[0];
                assert(ftype == idef->functype[tp]);

                /* The dummy and constructing atoms */
                adum = ia[1];
                ai   = ia[2];
                aj   = ia[3];

                /* Constants for constructing */
                a1   = ip[tp].dummy.a;

                /* Construct the dummy depending on type */
                switch (ftype) {
                case F_DUMMY2:
                    spread_dum2(f[ai],f[aj],f[adum],a1);
                    nd2++;
                    break;
                case F_DUMMY3:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    spread_dum3(f[ai],f[aj],f[ak],f[adum],a1,b1);
                    nd3++;
                    break;
                case F_DUMMY3FD:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    spread_dum3FD(x[ai],x[aj],x[ak],f[ai],f[aj],f[ak],f[adum],a1,b1);
                    nd3FD++;
                    break;
                case F_DUMMY3FAD:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    spread_dum3FAD(x[ai],x[aj],x[ak],f[ai],f[aj],f[ak],f[adum],a1,b1);
                    nd3FAD++;
                    break;
                case F_DUMMY3OUT:
                    ak = ia[4];
                    b1 = ip[tp].dummy.b;
                    c1 = ip[tp].dummy.c;
                    spread_dum3OUT(x[ai],x[aj],x[ak],f[ai],f[aj],f[ak],f[adum],a1,b1,c1);
                    nd3OUT++;
                    break;
                case F_DUMMY4FD:
                    ak = ia[4];
                    al = ia[5];
                    b1 = ip[tp].dummy.b;
                    c1 = ip[tp].dummy.c;
                    spread_dum4FD(x[ai],x[aj],x[ak],x[al],
                                  f[ai],f[aj],f[ak],f[al],f[adum],a1,b1,c1);
                    nd4FD++;
                    break;
                default:
                    fatal_error(0,"No such dummy type %d in %s, line %d",
                                ftype,__FILE__,__LINE__);
                }
                clear_rvec(f[adum]);

                /* Increment loop variables */
                i  += nra+1;
                ia += nra+1;
            }
        }
    }

    inc_nrnb(nrnb,eNR_DUM2,   nd2   );
    inc_nrnb(nrnb,eNR_DUM3,   nd3   );
    inc_nrnb(nrnb,eNR_DUM3FD, nd3FD );
    inc_nrnb(nrnb,eNR_DUM3FAD,nd3FAD);
    inc_nrnb(nrnb,eNR_DUM3OUT,nd3OUT);
    inc_nrnb(nrnb,eNR_DUM4FD, nd4FD );

    /* We only move forces here, and they are independent of shifts */
    if(dummycomm)
        move_construct_f(dummycomm,f,cr);
}
Example #30
0
int main(int argc, char **argv)  {

        int arg,ret;
	char *configfile;
	char pcapfile[256];

	// Load default config
	init_config();

        // Set the signal handlers
        signal(SIGHUP, sighup_handler);
        signal(SIGINT, sigquit_handler);
        signal(SIGQUIT,sigquit_handler);


        // Parse command-line options
        while ((arg = getopt(argc, argv, "IP:i:c:f:DqvdTsr:l:u:S:")) != -1){
                switch (arg){
                        case 'f':
                                strncpy(CONFIG_PCAP_FILTER,optarg,CONFIG_MAX_CHAR);
                                break;
			case 'r':
				strncpy(pcapfile,optarg,256);
				mode_offline=1;
				break;
			case 'c':
				configfile = optarg;
				read_config(configfile);
				//dump_config();
				break;
                        case 'i':
				// Start the pcap thread
                                strncpy(CONFIG_PCAP_DEV,optarg,CONFIG_MAX_CHAR);
                                break;
                        case 'P':
				CONFIG_DIVERT_PORT=atoi(optarg);
				break;
			case 'I':
				CONFIG_DIVERT_ENABLE=1;
                                break;
                        case 'q':
                                CONFIG_LOG_STDOUT = 0;
                                break;
                        case 'u':
				strncpy(CONFIG_USER,optarg,CONFIG_MAX_CHAR);
                                break;
                        case 'l':
                                strncpy(CONFIG_LOGDIR,optarg,CONFIG_MAX_CHAR);
				if(strlen(CONFIG_LOGDIR) > 64) {
					fatal_error("Log directory is too long!");
				}
				if (access(CONFIG_LOGDIR, F_OK) == -1){
					fatal_error("Log directory does not exist");
				}
                                break;
                        case 's':
                                CONFIG_LOG_SYSLOG = 1;
                                break;
			case 'S':
                                strncpy(CONFIG_SIGFILE,optarg,CONFIG_MAX_CHAR);
				break;
			case 'T':
				CONFIG_TCP_STRICT = 0;
				break;
                        case 'v':
                                CONFIG_LOG_VERBOSE++;
                                break;
			case 'd':
				CONFIG_SHOW_TRAFFIC = 1;
				break;
                        case 'D':
				fork_to_background(); 
                                break;
                        default:
				usage();
				exit(1);
                                break;
                }
        }

	// Initialize the stats structure and the streams
	stats_init();

        // Create the list, this is to store the IP packets in which can then
        // be read by another thread. TODO: add maximum list size
        trafficlist = getRingBuffer(CONFIG_RINGBUFFER_SIZE);

        // Register the destructor
        registerListDestructor(destructor_callback,trafficlist);
        registerListIterator(traffic_analyzer,trafficlist);

	// Create the control thread first for message logging
        pthread_create(&t_control,NULL,(void*)control_loop,NULL);

	//Initialize the detection hooks
	detect_hook_init();
	tcp_stream_init();

	//Initialize the timers
	timer_init();
	timer_register_function(CONFIG_TIMER_STATS,"Stats printer",stats_show_cnt_line,NULL);
	timer_register_function(CONFIG_TIMER_TCP_CLEANER,"TCP session cleaner", tcp_clean_sessions,NULL);
	timer_register_function(CONFIG_TIMER_IPFRAG_CLEANER,"IP fragment cleaner", ip_frag_cleaner,NULL);

	//Load the signatures
	if(load_signatures(CONFIG_SIGFILE) == 1){
		usage();
		exit(1);
	}

	// Make signature index;
	init_signature_indexes();

	log_info("Signatures loaded: %d, not loaded: %d", stat_get(CNT_SIG_LOADED), stat_get(CNT_SIG_NOT_LOADED));


	// Check if root privileges are required
	if(mode_offline == 0 && getuid() != 0) {
		fprintf(stderr, "Root privileges are required, unless you specify a\n");
		fprintf(stderr, "pcap file with the '-r' option..\n");
		exit(1);
	}

	if(CONFIG_DIVERT_ENABLE) {
		log_info("Opening DIVERT socket port: %d\n",CONFIG_DIVERT_PORT);
		divert_open_socket(CONFIG_DIVERT_PORT);

		// Start the divert_listen loop
		pthread_create(&t_listener,NULL,(void*)divert_listen_loop,handle);
	} else if(mode_offline != 1) {

		// If no device was specified AND not configured then the only
		// option is to pick one using the cap library (not recommended)
		if(*CONFIG_PCAP_DEV == '0') {
			if(pcap_return_device() != NULL) {
				log_info("Picking random interface (overrule -i)");
				strncpy(CONFIG_PCAP_DEV,pcap_return_device(),CONFIG_MAX_CHAR);
			} else {
					usage();
					exit(1);
			}
		}

		// Start the sniffer thread
		handle = pcap_open_device(CONFIG_PCAP_DEV,CONFIG_PCAP_FILTER);
		pthread_create(&t_listener,NULL,(void*)pcap_listen_loop,handle);
	} else {

		// Open the file
		handle = pcap_open_file(pcapfile,CONFIG_PCAP_FILTER);
		pthread_create(&t_listener,NULL,(void*)pcap_listen_loop,handle);
	}

	// Chroot if needed
	if(CONFIG_CHROOT_ENABLE == 1) {
		if((ret = chroot(CONFIG_CHROOT_DIR)) != 0) {
			fatal_error("Chroot to \"%s\" failed: %s !",CONFIG_CHROOT_DIR, strerror(errno));
		} else {
			log_info("Chroot to directory: \"%s\" done",CONFIG_CHROOT_DIR);
		}
	}

	// Drop privileges if needed
	if(*CONFIG_USER != '0' && drop_privileges(CONFIG_USER) != 0) {
		fatal_error("Unable to drop privileges, quitting for security reasons",CONFIG_USER);
	}

	// Set the time
	gettimeofday(&startuptime,NULL);
        pthread_create(&t_analyzer,NULL,(void*)pcap_analyzer,NULL);

	if(mode_offline == 1) {
		pthread_join(t_analyzer, NULL);
	} else {
		pthread_join(t_listener,NULL);
	}

	// Control thread
	loop_control = 0;
	pthread_join(t_control, NULL);

	// And bail out
	dump_stats(stdout);
        return 0;
}