Example #1
0
File: align.c Project: 8l/go
void
dowidth(Type *t)
{
	int32 et;
	int64 w;
	int lno;
	Type *t1;

	if(widthptr == 0)
		fatal("dowidth without betypeinit");

	if(t == T)
		return;

	if(t->width > 0)
		return;

	if(t->width == -2) {
		lno = lineno;
		lineno = t->lineno;
		if(!t->broke) {
			t->broke = 1;
			yyerror("invalid recursive type %T", t);
		}
		t->width = 0;
		lineno = lno;
		return;
	}

	// defer checkwidth calls until after we're done
	defercalc++;

	lno = lineno;
	lineno = t->lineno;
	t->width = -2;
	t->align = 0;

	et = t->etype;
	switch(et) {
	case TFUNC:
	case TCHAN:
	case TMAP:
	case TSTRING:
		break;

	default:
		/* simtype == 0 during bootstrap */
		if(simtype[t->etype] != 0)
			et = simtype[t->etype];
		break;
	}

	w = 0;
	switch(et) {
	default:
		fatal("dowidth: unknown type: %T", t);
		break;

	/* compiler-specific stuff */
	case TINT8:
	case TUINT8:
	case TBOOL:		// bool is int8
		w = 1;
		break;
	case TINT16:
	case TUINT16:
		w = 2;
		break;
	case TINT32:
	case TUINT32:
	case TFLOAT32:
		w = 4;
		break;
	case TINT64:
	case TUINT64:
	case TFLOAT64:
	case TCOMPLEX64:
		w = 8;
		t->align = widthreg;
		break;
	case TCOMPLEX128:
		w = 16;
		t->align = widthreg;
		break;
	case TPTR32:
		w = 4;
		checkwidth(t->type);
		break;
	case TPTR64:
		w = 8;
		checkwidth(t->type);
		break;
	case TUNSAFEPTR:
		w = widthptr;
		break;
	case TINTER:		// implemented as 2 pointers
		w = 2*widthptr;
		t->align = widthptr;
		offmod(t);
		break;
	case TCHAN:		// implemented as pointer
		w = widthptr;
		checkwidth(t->type);

		// make fake type to check later to
		// trigger channel argument check.
		t1 = typ(TCHANARGS);
		t1->type = t;
		checkwidth(t1);
		break;
	case TCHANARGS:
		t1 = t->type;
		dowidth(t->type);	// just in case
		if(t1->type->width >= (1<<16))
			yyerror("channel element type too large (>64kB)");
		t->width = 1;
		break;
	case TMAP:		// implemented as pointer
		w = widthptr;
		checkwidth(t->type);
		checkwidth(t->down);
		break;
	case TFORW:		// should have been filled in
		if(!t->broke)
			yyerror("invalid recursive type %T", t);
		w = 1;	// anything will do
		break;
	case TANY:
		// dummy type; should be replaced before use.
		if(!debug['A'])
			fatal("dowidth any");
		w = 1;	// anything will do
		break;
	case TSTRING:
		if(sizeof_String == 0)
			fatal("early dowidth string");
		w = sizeof_String;
		t->align = widthptr;
		break;
	case TARRAY:
		if(t->type == T)
			break;
		if(t->bound >= 0) {
			uint64 cap;

			dowidth(t->type);
			if(t->type->width != 0) {
				cap = (MAXWIDTH-1) / t->type->width;
				if(t->bound > cap)
					yyerror("type %lT larger than address space", t);
			}
			w = t->bound * t->type->width;
			t->align = t->type->align;
		}
		else if(t->bound == -1) {
			w = sizeof_Array;
			checkwidth(t->type);
			t->align = widthptr;
		}
		else if(t->bound == -100) {
			if(!t->broke) {
				yyerror("use of [...] array outside of array literal");
				t->broke = 1;
			}
		}
		else
			fatal("dowidth %T", t);	// probably [...]T
		break;

	case TSTRUCT:
		if(t->funarg)
			fatal("dowidth fn struct %T", t);
		w = widstruct(t, t, 0, 1);
		break;

	case TFUNC:
		// make fake type to check later to
		// trigger function argument computation.
		t1 = typ(TFUNCARGS);
		t1->type = t;
		checkwidth(t1);

		// width of func type is pointer
		w = widthptr;
		break;

	case TFUNCARGS:
		// function is 3 cated structures;
		// compute their widths as side-effect.
		t1 = t->type;
		w = widstruct(t->type, *getthis(t1), 0, 0);
		w = widstruct(t->type, *getinarg(t1), w, widthreg);
		w = widstruct(t->type, *getoutarg(t1), w, widthreg);
		t1->argwid = w;
		if(w%widthreg)
			warn("bad type %T %d\n", t1, w);
		t->align = 1;
		break;
	}

	if(widthptr == 4 && w != (int32)w)
		yyerror("type %T too large", t);

	t->width = w;
	if(t->align == 0) {
		if(w > 8 || (w&(w-1)) != 0)
			fatal("invalid alignment for %T", t);
		t->align = w;
	}
	lineno = lno;

	if(defercalc == 1)
		resumecheckwidth();
	else
		--defercalc;
}
Example #2
0
/* Converts perl values to equivalent JS values */
JSBool
PJS_ReflectPerl2JS(
    pTHX_ 
    JSContext *cx,
    JSObject *pobj,
    SV *ref,
    jsval *rval
) {
    PJS_Context *pcx = PJS_GET_CONTEXT(cx);
    JSObject *newobj = NULL;

    if(++pcx->svconv % 2000 == 0) {
	JSErrorReporter older;
	ENTER; SAVETMPS; /* Scope for finalizers */
	older = JS_SetErrorReporter(cx, NULL);
	if(pcx->svconv > 10000) {
	    JS_GC(cx);
	    pcx->svconv = 0;
	} else JS_MaybeGC(cx);
	JS_SetErrorReporter(cx, older);
	FREETMPS; LEAVE;
    }
    if(SvROK(ref)) {
	MAGIC *mg;
	/* First check old jsvisitors */
	if((newobj = PJS_IsPerlVisitor(aTHX_ pcx, SvRV(ref)))) {
	    PJS_DEBUG("Old jsvisitor returns\n");
	    *rval = OBJECT_TO_JSVAL(newobj);
	    return JS_TRUE;
	}

	if(SvMAGICAL(SvRV(ref)) && (mg = mg_find(SvRV(ref), PERL_MAGIC_tied))
	   && mg->mg_obj && sv_derived_from(mg->mg_obj, PJS_BOXED_PACKAGE)) {
	    PJS_DEBUG1("A magical ref %s, shortcircuit!\n", SvPV_nolen((SV*)mg->mg_obj));
	    ref = mg->mg_obj;
	}

	if(sv_derived_from(ref, PJS_BOXED_PACKAGE)) {
	    SV **fref = av_fetch((AV *)SvRV(SvRV(ref)), 2, 0);
	    assert(sv_derived_from(*fref, PJS_RAW_JSVAL));
	    *rval = (jsval)SvIV(SvRV(*fref));
	    return JS_TRUE;
	}

	if(sv_derived_from(ref, PJS_BOOLEAN)) {
	    *rval = SvTRUE(SvRV(ref)) ? JSVAL_TRUE : JSVAL_FALSE;
	    return JS_TRUE;
	}
	
	if(sv_isobject(ref)) {
	    newobj = PJS_NewPerlObject(aTHX_ cx, pobj, ref); 
	    if(newobj) {
		*rval = OBJECT_TO_JSVAL(newobj);
		return JS_TRUE;
	    }
	    return JS_FALSE;
	}
    }

    SvGETMAGIC(ref);

    if(!SvOK(ref)) /* undef */
        *rval = JSVAL_VOID;
    else if(SvIOK(ref) || SvIOKp(ref)) {
        if(SvIV(ref) <= JSVAL_INT_MAX)
            *rval = INT_TO_JSVAL(SvIV(ref));
        else JS_NewDoubleValue(cx, (double) SvIV(ref), rval);
    }
    else if(SvNOK(ref)) 
        JS_NewDoubleValue(cx, SvNV(ref), rval);
    else if(SvPOK(ref) || SvPOKp(ref)) {
        STRLEN len;
        char *str;
	SV *temp=NULL;
	if(SvREADONLY(ref)) {
	    temp = newSVsv(ref);
	    str = PJS_SvPV(temp, len);
	} else str = PJS_SvPV(ref, len);
	JSString *jstr = ((int)len >= 0)
	    ? JS_NewStringCopyN(cx, str, len)
	    : JS_NewUCStringCopyN(cx, (jschar *)str, -(int)len);
	sv_free(temp);
	if(!jstr) return JS_FALSE;
        *rval = STRING_TO_JSVAL(jstr);
    }
    else if(SvROK(ref)) { /* Plain reference */
        I32 type = SvTYPE(SvRV(ref));

        if(type == SVt_PVHV)
	    newobj = PJS_NewPerlHash(aTHX_ cx, pobj, ref);
	else if(type == SVt_PVAV)
	    newobj = PJS_NewPerlArray(aTHX_ cx, pobj, ref);
        else if(type == SVt_PVCV)
            newobj = PJS_NewPerlSub(aTHX_ cx, pobj, ref);            
	else
	    newobj = PJS_NewPerlScalar(aTHX_ cx, pobj, ref);
	if(!newobj) return JS_FALSE;
	*rval = OBJECT_TO_JSVAL(newobj);
    }
    else {
        warn("I have no idea what perl send us (it's of type %i), I'll pretend it's undef", SvTYPE(ref));
        *rval = JSVAL_VOID;
    }

    return JS_TRUE;
}
int do_accel_calibration_mesurements(int mavlink_fd, float accel_offs[3], float accel_scale[3]) {
	const int samples_num = 2500;
	float accel_ref[6][3];
	bool data_collected[6] = { false, false, false, false, false, false };
	const char *orientation_strs[6] = { "x+", "x-", "y+", "y-", "z+", "z-" };

	/* reset existing calibration */
	int fd = open(ACCEL_DEVICE_PATH, 0);
	struct accel_scale ascale_null = {
		0.0f,
		1.0f,
		0.0f,
		1.0f,
		0.0f,
		1.0f,
	};
	int ioctl_res = ioctl(fd, ACCELIOCSSCALE, (long unsigned int)&ascale_null);
	close(fd);

	if (OK != ioctl_res) {
		warn("ERROR: failed to set scale / offsets for accel");
		return ERROR;
	}

	int sensor_combined_sub = orb_subscribe(ORB_ID(sensor_combined));
	while (true) {
		bool done = true;
		char str[80];
		int str_ptr;
		str_ptr = sprintf(str, "keep vehicle still:");
		for (int i = 0; i < 6; i++) {
			if (!data_collected[i]) {
				str_ptr += sprintf(&(str[str_ptr]), " %s", orientation_strs[i]);
				done = false;
			}
		}
		if (done)
			break;
		mavlink_log_info(mavlink_fd, str);

		int orient = detect_orientation(mavlink_fd, sensor_combined_sub);
		if (orient < 0)
			return ERROR;

		sprintf(str, "meas started: %s", orientation_strs[orient]);
		mavlink_log_info(mavlink_fd, str);
		read_accelerometer_avg(sensor_combined_sub, &(accel_ref[orient][0]), samples_num);
		str_ptr = sprintf(str, "meas result for %s: [ %.2f %.2f %.2f ]", orientation_strs[orient], accel_ref[orient][0], accel_ref[orient][1], accel_ref[orient][2]);
		mavlink_log_info(mavlink_fd, str);
		data_collected[orient] = true;
		tune_confirm();
	}
	close(sensor_combined_sub);

	/* calculate offsets and rotation+scale matrix */
	float accel_T[3][3];
	int res = calculate_calibration_values(accel_ref, accel_T, accel_offs, CONSTANTS_ONE_G);
	if (res != 0) {
		mavlink_log_info(mavlink_fd, "ERROR: calibration values calc error");
		return ERROR;
	}

	/* convert accel transform matrix to scales,
	 * rotation part of transform matrix is not used by now
	 */
	for (int i = 0; i < 3; i++) {
		accel_scale[i] = accel_T[i][i];
	}

	return OK;
}
Example #4
0
File: io.c Project: 2asoft/freebsd
void
closecal(FILE *fp)
{
	uid_t uid;
	struct stat sbuf;
	int nread, pdes[2], status;
	char buf[1024];

	if (!doall)
		return;

	rewind(fp);
	if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
		goto done;
	if (pipe(pdes) < 0)
		goto done;
	switch (fork()) {
	case -1:			/* error */
		(void)close(pdes[0]);
		(void)close(pdes[1]);
		goto done;
	case 0:
		/* child -- set stdin to pipe output */
		if (pdes[0] != STDIN_FILENO) {
			(void)dup2(pdes[0], STDIN_FILENO);
			(void)close(pdes[0]);
		}
		(void)close(pdes[1]);
		uid = geteuid();
		if (setuid(getuid()) < 0) {
			warnx("setuid failed");
			_exit(1);
		}
		if (setgid(getegid()) < 0) {
			warnx("setgid failed");
			_exit(1);
		}
		if (setuid(uid) < 0) {
			warnx("setuid failed");
			_exit(1);
		}
		execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
		    "\"Reminder Service\"", (char *)NULL);
		warn(_PATH_SENDMAIL);
		_exit(1);
	}
	/* parent -- write to pipe input */
	(void)close(pdes[0]);

	write(pdes[1], "From: \"Reminder Service\" <", 26);
	write(pdes[1], pw->pw_name, strlen(pw->pw_name));
	write(pdes[1], ">\nTo: <", 7);
	write(pdes[1], pw->pw_name, strlen(pw->pw_name));
	write(pdes[1], ">\nSubject: ", 11);
	write(pdes[1], dayname, strlen(dayname));
	write(pdes[1], "'s Calendar\nPrecedence: bulk\n\n", 30);

	while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
		(void)write(pdes[1], buf, nread);
	(void)close(pdes[1]);
done:	(void)fclose(fp);
	(void)unlink(path);
	while (wait(&status) >= 0);
}
Example #5
0
static void nbodyPrintVersion()
{
    warn("<search_application>" BOINC_NBODY_APP_VERSION "</search_application>\n");
}
Example #6
0
int
main(int argc, char **argv)
{
	int ch, previous_ch;
	int rval, width;

	(void) setlocale(LC_CTYPE, "");

	width = -1;
	previous_ch = 0;
	while ((ch = getopt(argc, argv, "0123456789bsw:")) != -1) {
		switch (ch) {
		case 'b':
			bflag = 1;
			break;
		case 's':
			sflag = 1;
			break;
		case 'w':
			if ((width = atoi(optarg)) <= 0) {
				errx(1, "illegal width value");
			}
			break;
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			/* Accept a width as eg. -30. Note that a width
			 * specified using the -w option is always used prior
			 * to this undocumented option. */
			switch (previous_ch) {
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9':
				/* The width is a number with multiple digits:
				 * add the last one. */
				width = width * 10 + (ch - '0');
				break;
			default:
				/* Set the width, unless it was previously
				 * set. For instance, the following options
				 * would all give a width of 5 and not 10:
				 *   -10 -w5
				 *   -5b10
				 *   -5 -10b */
				if (width == -1)
					width = ch - '0';
				break;
			}
			break;
		default:
			usage();
		}
		previous_ch = ch;
	}
	argv += optind;
	argc -= optind;

	if (width == -1)
		width = DEFLINEWIDTH;
	rval = 0;
	if (!*argv)
		fold(width);
	else for (; *argv; ++argv)
		if (!freopen(*argv, "r", stdin)) {
			warn("%s", *argv);
			rval = 1;
		} else
			fold(width);
	exit(rval);
}
Example #7
0
int main(int argc,char ** argv)
{
    int i;

    DPRunImpl * dpri = NULL;
    GeneModelParam * gmp = NULL;
    GeneModel * gm = NULL;

    FILE * ifp;
    SeqAlign   * al;
    PairBaseSeq * pbs;

    ComplexSequenceEval * splice5;
    ComplexSequenceEval * splice3;
    ComplexSequence * cseq;


    CompMat * score_mat;
    CompProb * comp_prob;
    RandomModel * rm;

    PairBaseCodonModelScore * codon_score;
    PairBaseModelScore* nonc_score;

    PairBaseCodonModelScore * start;
    PairBaseCodonModelScore * stop;


    SyExonScore * exonscore;

    PackAln * pal;
    AlnBlock * alb;

    Genomic * genomic;
    GenomicRegion * gr;
    GenomicRegion * gr2;
    Protein * trans;

    StandardOutputOptions * std_opt;
    ShowGenomicRegionOptions * sgro;

    char * dump_packaln = NULL;
    char * read_packaln = NULL;
    FILE * packifp = NULL;

    boolean show_trans    = 1;
    boolean show_gene_raw = 0;



    ct = read_CodonTable_file(codon_table);
    /*
      score_mat = read_Blast_file_CompMat("blosum62.bla");
      comp_prob = CompProb_from_halfbit(score_mat);
    */
    rm = default_RandomModel();

    comp_prob = read_Blast_file_CompProb("wag85");

    fold_column_RandomModel_CompProb(comp_prob,rm);

    dpri = new_DPRunImpl_from_argv(&argc,argv);
    if( dpri == NULL ) {
        fatal("Unable to build DPRun implementation. Bad arguments");
    }

    gmp = new_GeneModelParam_from_argv(&argc,argv);

    std_opt = new_StandardOutputOptions_from_argv(&argc,argv);
    sgro = new_ShowGenomicRegionOptions_from_argv(&argc,argv);


    dump_packaln = strip_out_assigned_argument(&argc,argv,"dump");
    read_packaln = strip_out_assigned_argument(&argc,argv,"recover");

    strip_out_standard_options(&argc,argv,show_help,show_version);
    if( argc != 2 ) {
        show_help(stdout);
        exit(12);
    }


    if((gm=GeneModel_from_GeneModelParam(gmp)) == NULL ) {
        fatal("Could not build gene model");
    }

    codon_score = make_PairBaseCodonModelScore(comp_prob);
    nonc_score  = make_PairBaseModelScore();

    splice5 = ComplexSequenceEval_from_pwmDNAScore_splice(gm->splice5score);
    splice3 = ComplexSequenceEval_from_pwmDNAScore_splice(gm->splice3score);

    if((ifp = openfile(argv[1],"r")) == NULL ) {
        fatal("Could not open file %s",argv[1]);
    }

    al = read_fasta_SeqAlign(ifp);

    assert(al);
    assert(al->len == 2);
    assert(al->seq[0]->len > 0);
    assert(al->seq[1]->len > 0);

    /*  write_fasta_SeqAlign(al,stdout);*/


    pbs = new_PairBaseSeq_SeqAlign(al);

    if( read_packaln == NULL ) {
        cseq = ComplexSequence_from_PairBaseSeq(pbs,splice5,splice3);
    }

    start = make_start_PairBaseCodonModelScore(ct);
    stop  = make_stop_PairBaseCodonModelScore(ct);


    /*  show_PairBaseCodonModelScore(stop,ct,stdout); */

    /*
      for(i=0;i<pbs->anchor->len;i++) {
        printf("%3d  %c For %-6d %-6d %c Rev %-6d %-6d\n",i,pbs->anchor->seq[i],
    	   CSEQ_PAIR_5SS(cseq,i),CSEQ_PAIR_3SS(cseq,i),
    	   char_complement_base(pbs->anchor->seq[i]),
    	   CSEQ_REV_PAIR_5SS(cseq,i),CSEQ_REV_PAIR_3SS(cseq,i));
      }
    */


    /*  show_ComplexSequence(cseq,stdout);

    */


    exonscore = SyExonScore_flat_model(100,150,0.1,1.0);
    /*
    for(i=0;i<cseq->length;i++) {
      fprintf(stdout,"%d PairSeq is %d score %d\n",i,CSEQ_PAIR_PAIRBASE(cseq,i),nonc_score->base[CSEQ_PAIR_PAIRBASE(cseq,i)]);
    }
    exit(0);
    */

    if( read_packaln != NULL ) {
        packifp = openfile(read_packaln,"r");
        if( packifp == NULL ) {
            fatal("File %s is unopenable - ignoring dump command",dump_packaln);
        } else {
            pal = read_simple_PackAln(packifp);
        }
    } else {
        pal = PackAln_bestmemory_SyWise20(exonscore,cseq,codon_score,nonc_score,start,stop,Probability2Score(1.0/100.0),Probability2Score(1.0/10000.0),Probability2Score(1.0/10.0),NULL,dpri);
    }

    alb = convert_PackAln_to_AlnBlock_SyWise20(pal);


    if( dump_packaln != NULL ) {
        packifp = openfile(dump_packaln,"w");
        if( packifp == NULL ) {
            warn("File %s is unopenable - ignoring dump command",dump_packaln);
        } else {
            show_simple_PackAln(pal,packifp);
        }
    }

    show_score_sequence(alb,pbs,nonc_score,stdout);
    /*
      show_StandardOutputOptions(std_opt,alb,pal,"//",stdout);
    */
    genomic = Genomic_from_Sequence(al->seq[0]);
    gr = new_GenomicRegion(genomic);
    gr2 = new_GenomicRegion(genomic);

    add_Genes_to_GenomicRegion_new(gr,alb);


    show_GenomicRegionOptions(sgro,gr,ct,"//",stdout);

    return 0;
}
Example #8
0
int main (int argc, char **argv)
{
	char **text,**font,*textcolor,*boxcolor;
	float size,labelCD=0.0,labelCA,labelCW=0.0,labelCH,bigx,bigy,eps,eps2;
	float *x;
	int n,j,nsub;
	size_t nchar;

	/* Hook up getpars */
	initargs(argc,argv);
	requestdoc(0);

	/* Get parameters */
	if(!getparint("nsub",&nsub))nsub=0;
	if(!getparfloat("size",&size))size=30;
	if(!getparstring("tcolor",&textcolor))textcolor="black";
	if(!getparstring("bcolor",&boxcolor))boxcolor="white";

        checkpars();

	eps=0.25*size;
	eps2=0.1*size;
	n=countparname("t");
	if(n==0)
 	err("must enter at least one PSTEXT text stream as parameter t");

	if(n!=countparname("f")) 
		warn("suggest specify same number of values for t and f");
	text =(char **)malloc( (n+1)*sizeof(char *) );
	font =(char **)malloc( (n+1)*sizeof(char *) );
	x = (float *)malloc( (n+1)*sizeof(float) );	
	for(bigx=eps,bigy=0.,j=0;j<n;j++){
		x[j]=bigx;
		if(!getnparstring(j+1,"t",&text[j]))text[j]="hello";
		if(!getnparstring(j+1,"f",&font[j]))font[j]="Times-Bold";
		labelCH = fontheight(font[j],size);
		labelCW = fontwidth(font[j],size);
		labelCA = fontascender(font[j],size);
		labelCD = MIN(labelCD,fontdescender(font[j],size));
		nchar = strlen(text[j]);
		bigx+=0.5*(((double) nchar)*labelCW);
		bigy=MAX(bigy,labelCH+eps+0.0*labelCA);
	}
	bigx+=eps;
	bigx-=0.5*nsub*labelCW;

	/* open output eps file */
	boundingbox(-eps2,-eps2,bigx+eps2,bigy+eps2);
	begineps();
	gsave();
	rectclip(0.,0.,bigx,bigy);

	/* fill background box with background color */
	newpath();
	moveto(0.,0.);
	lineto(bigx,0.);
	lineto(bigx,bigy);
	lineto(0.,bigy);
	closepath();
	setcolor(boxcolor);
	fill();
	
	/* write out text strings */
	setcolor(textcolor);
	moveto(eps,eps-labelCD);
	for(j=0;j<n;j++) {
		setfont(font[j],size);
		show(text[j]);
	}

	/* close output stream */
	grestore();
	showpage();
	endeps();

	return EXIT_SUCCESS;
}
static
void
makeprocs(bool dowait)
{
    int i, status, failcount;
    struct usem s1, s2;
    pid_t pids[NJOBS];

    if (dowait) {
        semcreate("1", &s1);
        semcreate("2", &s2);
    }

    tprintf("Job size approximately %lu bytes\n", (unsigned long) JOBSIZE);
    tprintf("Forking %d jobs; total load %luk\n", NJOBS,
            (unsigned long) (NJOBS * JOBSIZE)/1024);

    for (i=0; i<NJOBS; i++) {
        pids[i] = fork();
        if (pids[i]<0) {
            warn("fork");
        }
        if (pids[i]==0) {
            /* child */
            if (dowait) {
                //tsay("Process %d forked\n", i);
                semopen(&s1);
                semopen(&s2);
                semV(&s1, 1);
                semP(&s2, 1);
                semclose(&s1);
                semclose(&s2);
            }
            go(i);
        }
    }

    if (dowait) {
        semopen(&s1);
        semopen(&s2);
        //tsay("Waiting for fork...\n");
        semP(&s1, NJOBS);
        //tsay("Starting computation.\n");
        semV(&s2, NJOBS);
    }

    failcount=0;
    for (i=0; i<NJOBS; i++) {
        if (pids[i]<0) {
            failcount++;
        }
        else {
            if (waitpid(pids[i], &status, 0)<0) {
                err(1, "waitpid");
            }
            if (status_is_failure(status)) {
                failcount++;
            }
        }
    }

    if (failcount>0) {
        printf("%d subprocesses failed\n", failcount);
        exit(1);
    }
    nprintf("\n");
    tprintf("Test complete\n");
    success(TEST161_SUCCESS, SECRET, "/testbin/parallelvm");

    semclose(&s1);
    semclose(&s2);
    semdestroy(&s1);
    semdestroy(&s2);
}
Example #10
0
static void
rm_file(char **argv)
{
	struct stat sb;
	int rval;
	char *f;

	/*
	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
	 * to remove a directory is an error, so must always stat the file.
	 */
	while ((f = *argv++) != NULL) {
		/* Assume if can't stat the file, can't unlink it. */
		if (lstat(f, &sb)) {
			if (Wflag) {
				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
			} else {
				if (!fflag || errno != ENOENT) {
					warn("%s", f);
					eval = 1;
				}
				continue;
			}
		} else if (Wflag) {
			warnx("%s: %s", f, strerror(EEXIST));
			eval = 1;
			continue;
		}

		if (S_ISDIR(sb.st_mode) && !dflag) {
			warnx("%s: is a directory", f);
			eval = 1;
			continue;
		}
		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
			continue;
		rval = 0;
		if (!uid && !S_ISWHT(sb.st_mode) &&
		    (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
		    !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
			rval = lchflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
		if (rval == 0) {
			if (S_ISWHT(sb.st_mode))
				rval = undelete(f);
			else if (S_ISDIR(sb.st_mode))
				rval = rmdir(f);
			else {
				if (Pflag)
					if (!rm_overwrite(f, &sb))
						continue;
				rval = unlink(f);
			}
		}
		if (rval && (!fflag || errno != ENOENT)) {
			warn("%s", f);
			eval = 1;
		}
		if (vflag && rval == 0)
			(void)printf("%s\n", f);
		if (info && rval == 0) {
			info = 0;
			(void)printf("%s\n", f);
		}
	}
}
Example #11
0
/*
 * rm_overwrite --
 *	Overwrite the file 3 times with varying bit patterns.
 *
 * XXX
 * This is a cheap way to *really* delete files.  Note that only regular
 * files are deleted, directories (and therefore names) will remain.
 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
 * System V file system).  In a logging or COW file system, you'll have to
 * have kernel support.
 */
static int
rm_overwrite(const char *file, struct stat *sbp)
{
	struct stat sb, sb2;
	struct statfs fsb;
	off_t len;
	int bsize, fd, wlen;
	char *buf = NULL;

	fd = -1;
	if (sbp == NULL) {
		if (lstat(file, &sb))
			goto err;
		sbp = &sb;
	}
	if (!S_ISREG(sbp->st_mode))
		return (1);
	if (sbp->st_nlink > 1 && !fflag) {
		warnx("%s (inode %ju): not overwritten due to multiple links",
		    file, (uintmax_t)sbp->st_ino);
		return (0);
	}
	if ((fd = open(file, O_WRONLY|O_NONBLOCK|O_NOFOLLOW, 0)) == -1)
		goto err;
	if (fstat(fd, &sb2))
		goto err;
	if (sb2.st_dev != sbp->st_dev || sb2.st_ino != sbp->st_ino ||
	    !S_ISREG(sb2.st_mode)) {
		errno = EPERM;
		goto err;
	}
	if (fstatfs(fd, &fsb) == -1)
		goto err;
	bsize = MAX(fsb.f_iosize, 1024);
	if ((buf = malloc(bsize)) == NULL)
		err(1, "%s: malloc", file);

#define	PASS(byte) {							\
	memset(buf, byte, bsize);					\
	for (len = sbp->st_size; len > 0; len -= wlen) {		\
		wlen = len < bsize ? len : bsize;			\
		if (write(fd, buf, wlen) != wlen)			\
			goto err;					\
	}								\
}
	PASS(0xff);
	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
		goto err;
	PASS(0x00);
	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
		goto err;
	PASS(0xff);
	if (!fsync(fd) && !close(fd)) {
		free(buf);
		return (1);
	}

err:	eval = 1;
	if (buf)
		free(buf);
	if (fd != -1)
		close(fd);
	warn("%s", file);
	return (0);
}
Example #12
0
static void
rm_tree(char **argv)
{
	FTS *fts;
	FTSENT *p;
	int needstat;
	int flags;
	int rval;

	/*
	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
	 */
	needstat = !uid || (!fflag && !iflag && stdin_ok);

	/*
	 * If the -i option is specified, the user can skip on the pre-order
	 * visit.  The fts_number field flags skipped directories.
	 */
#define	SKIPPED	1

	flags = FTS_PHYSICAL;
	if (!needstat)
		flags |= FTS_NOSTAT;
	if (Wflag)
		flags |= FTS_WHITEOUT;
	if (xflag)
		flags |= FTS_XDEV;
	if (!(fts = fts_open(argv, flags, NULL))) {
		if (fflag && errno == ENOENT)
			return;
		err(1, "fts_open");
	}
	while ((p = fts_read(fts)) != NULL) {
		switch (p->fts_info) {
		case FTS_DNR:
			if (!fflag || p->fts_errno != ENOENT) {
				warnx("%s: %s",
				    p->fts_path, strerror(p->fts_errno));
				eval = 1;
			}
			continue;
		case FTS_ERR:
			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
		case FTS_NS:
			/*
			 * Assume that since fts_read() couldn't stat the
			 * file, it can't be unlinked.
			 */
			if (!needstat)
				break;
			if (!fflag || p->fts_errno != ENOENT) {
				warnx("%s: %s",
				    p->fts_path, strerror(p->fts_errno));
				eval = 1;
			}
			continue;
		case FTS_D:
			/* Pre-order: give user chance to skip. */
			if (!fflag && !check(p->fts_path, p->fts_accpath,
			    p->fts_statp)) {
				(void)fts_set(fts, p, FTS_SKIP);
				p->fts_number = SKIPPED;
			}
			else if (!uid &&
				 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
				 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
				 lchflags(p->fts_accpath,
					 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
				goto err;
			continue;
		case FTS_DP:
			/* Post-order: see if user skipped. */
			if (p->fts_number == SKIPPED)
				continue;
			break;
		default:
			if (!fflag &&
			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
				continue;
		}

		rval = 0;
		if (!uid &&
		    (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
		    !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
			rval = lchflags(p->fts_accpath,
				       p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
		if (rval == 0) {
			/*
			 * If we can't read or search the directory, may still be
			 * able to remove it.  Don't print out the un{read,search}able
			 * message unless the remove fails.
			 */
			switch (p->fts_info) {
			case FTS_DP:
			case FTS_DNR:
				rval = rmdir(p->fts_accpath);
				if (rval == 0 || (fflag && errno == ENOENT)) {
					if (rval == 0 && vflag)
						(void)printf("%s\n",
						    p->fts_path);
					if (rval == 0 && info) {
						info = 0;
						(void)printf("%s\n",
						    p->fts_path);
					}
					continue;
				}
				break;

			case FTS_W:
				rval = undelete(p->fts_accpath);
				if (rval == 0 && (fflag && errno == ENOENT)) {
					if (vflag)
						(void)printf("%s\n",
						    p->fts_path);
					if (info) {
						info = 0;
						(void)printf("%s\n",
						    p->fts_path);
					}
					continue;
				}
				break;

			case FTS_NS:
				/*
				 * Assume that since fts_read() couldn't stat
				 * the file, it can't be unlinked.
				 */
				if (fflag)
					continue;
				/* FALLTHROUGH */

			case FTS_F:
			case FTS_NSOK:
				if (Pflag)
					if (!rm_overwrite(p->fts_accpath, p->fts_info ==
					    FTS_NSOK ? NULL : p->fts_statp))
						continue;
				/* FALLTHROUGH */

			default:
				rval = unlink(p->fts_accpath);
				if (rval == 0 || (fflag && errno == ENOENT)) {
					if (rval == 0 && vflag)
						(void)printf("%s\n",
						    p->fts_path);
					if (rval == 0 && info) {
						info = 0;
						(void)printf("%s\n",
						    p->fts_path);
					}
					continue;
				}
			}
		}
err:
		warn("%s", p->fts_path);
		eval = 1;
	}
	if (!fflag && errno)
		err(1, "fts_read");
	fts_close(fts);
}
Example #13
0
void processBestMulti(char *acc, struct psl *pslList, FILE *bestFile, FILE *repFile)
/* Find psl's that are best anywhere along their length. */
{
struct psl *psl;
int qSize;
int *repTrack = NULL;
int *scoreTrack = NULL;
int milliScore;
int goodAliCount = 0;
int bestAliCount = 0;
int milliMin = 1000*minAli;


if (pslList == NULL)
    return;
qSize = pslList->qSize;
AllocArray(repTrack, qSize+1);
AllocArray(scoreTrack, qSize+1);

for (psl = pslList; psl != NULL; psl = psl->next)
    {
    int blockIx;
    char strand = psl->strand[0];
    milliScore = calcMilliScore(psl);
    if (milliScore >= milliMin)
	{
	++goodAliCount;
	milliScore += sizeFactor(psl);
	for (blockIx = 0; blockIx < psl->blockCount; ++blockIx)
	    {
	    int start = psl->qStarts[blockIx];
	    int size = psl->blockSizes[blockIx];
	    int end = start+size;
	    int i;
	    if (strand == '-')
	        reverseIntRange(&start, &end, psl->qSize);
	    if (start < 0 || end > qSize)
		{
		warn("Odd: qName %s tName %s qSize %d psl->qSize %d start %d end %d",
		    psl->qName, psl->tName, qSize, psl->qSize, start, end);
		if (start < 0)
		    start = 0;
		if (end > qSize)
		    end = qSize;
		}
	    for (i=start; i<end; ++i)
		{
		repTrack[i] += 1;
		if (milliScore > scoreTrack[i])
		    scoreTrack[i] = milliScore;
		}
	    }
	}
    }
/* Print out any alignments that are within 2% of top score. */
for (psl = pslList; psl != NULL; psl = psl->next)
    {
    if(passFilters(psl, scoreTrack))
	{
	pslTabOut(psl, bestFile);
	++bestAliCount;
	}
    }


/* Print out run-length-encoded repeat info.  */
    {
    int runVal = repTrack[0];
    int curVal;
    int runSize = 1;
    int packetCount = 0;
    int *packetSize = NULL;
    int *packetVal = NULL;
    int i;

    AllocArray(packetSize, qSize);
    AllocArray(packetVal, qSize);

    repTrack[qSize] = -1;	/* Sentinal value to simplify RLC loop. */
    fprintf(repFile, "%s\t%d\t%d\t", acc, bestAliCount, goodAliCount);

    for (i=1; i<=qSize; ++i)
	{
	if ((curVal = repTrack[i]) != runVal)
	    {
	    packetSize[packetCount] = runSize;
	    packetVal[packetCount] = runVal;
	    ++packetCount;
	    runSize = 1;
	    runVal = curVal;
	    }
	else
	    {
	    ++runSize;
	    }
	}
    fprintf(repFile, "%d\t", packetCount);
    for (i=0; i<packetCount; ++i)
	fprintf(repFile, "%d,", packetSize[i]);
    fprintf(repFile, "\t");
    for (i=0; i<packetCount; ++i)
	fprintf(repFile, "%d,", packetVal[i]);
    fprintf(repFile, "\n");

    freeMem(packetSize);
    freeMem(packetVal);
    }

freeMem(repTrack);
freeMem(scoreTrack);
}
Example #14
0
Type * read_Type_line(char * line,FILE * ifp)
{
  Type * out;
  char * temp;
  char buffer[MAXLINE];

  if( strstartcmp(line,"type") != 0 ) {
    warn("Attempting to read a method with no method line!");
    return NULL;
  }


  out = Type_alloc();
  out->logical = second_word_alloc(line,spacestr);

  while( fgets(buffer,MAXLINE,ifp) != NULL ) {
    chop_newline(buffer);
    if( strstartcmp(buffer,"end") == 0 ) 
      break;
    else if( strstartcmp(buffer,"real") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->real != NULL ) { 
	warn("For type [%s], second real replacing [%s] with [%s]",out->logical,out->real,temp);
	ckfree(out->real);
      } 
      out->real = temp;
    } else if( strstartcmp(buffer,"threadsafe") == 0 ) {
      out->is_thread_safe = TRUE;
    } else if ( strstartcmp(buffer,"dbtype") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->database_type != NULL ) { 
	warn("For type [%s], second database type replacing [%s] with [%s]",out->logical,out->database_type,temp);
	ckfree(out->database_type);
      } 
      out->database_type = temp;
    } else if ( strstartcmp(buffer,"init") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->init_func != NULL ) { 
	warn("For type [%s], second init replacing [%s] with [%s]",out->logical,out->init_func,temp);
	ckfree(out->init_func);
      } 
      out->init_func = temp;
    } else if ( strstartcmp(buffer,"maxlen") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->maxlen != NULL ) { 
	warn("For type [%s], second maxlen replacing [%s] with [%s]",out->logical,out->maxlen,temp);
	ckfree(out->maxlen);
      } 
      out->maxlen = temp;
    } else if ( strstartcmp(buffer,"reload") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->reload_func != NULL ) { 
	warn("For type [%s], second reload function replacing [%s] with [%s]",out->logical,out->reload_func,temp);
	ckfree(out->reload_func);
      } 
      out->reload_func = temp;
    } else if ( strstartcmp(buffer,"addentry") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->dataentry_add != NULL ) { 
	warn("For type [%s], second dataentry_add function replacing [%s] with [%s]",out->logical,out->dataentry_add,temp);
	ckfree(out->dataentry_add);
      } 
      out->dataentry_add = temp;
    } else if ( strstartcmp(buffer,"close") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->close_func != NULL ) { 
	warn("For type [%s], second close func replacing [%s] with [%s]",out->logical,out->close_func,temp);
	ckfree(out->close_func);
      } 
      out->close_func = temp;
    } else if ( strstartcmp(buffer,"hardlink") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->hard_link_func != NULL ) { 
	warn("For type [%s], second hard_link func replacing [%s] with [%s]",out->logical,out->hard_link_func,temp);
	ckfree(out->hard_link_func);
      } 
      out->hard_link_func = temp;
    } else if ( strstartcmp(buffer,"free") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->free_func != NULL ) { 
	warn("For type [%s], second free func replacing [%s] with [%s]",out->logical,out->free_func,temp);
	ckfree(out->free_func);
      } 
      out->free_func = temp;
    } else if ( strstartcmp(buffer,"name") == 0 ) {
      temp = second_word_alloc(buffer,spacestr);
      if( out->get_id_func != NULL ) { 
	warn("For type [%s], second get name func replacing [%s] with [%s]",out->logical,out->get_id_func,temp);
	ckfree(out->get_id_func);
      } 
      out->get_id_func = temp;
    } else {
      warn("In reading type [%s] did not understand [%s]",out->logical,buffer);
    }
  }
  if( out->is_thread_safe == TRUE ) {
    if( out->hard_link_func == NULL || out->free_func == NULL ) {
      warn("Trying to make type %s threadsafe but have not supplied hardlink and free functions",out->logical);
      out->is_thread_safe = FALSE;
    }
  }

  out->is_database = is_database_type(out);
  return out;
}
Example #15
0
int
main(int argc, char *argv[])
{
	int cc;
	struct termios rtt, stt;
	struct winsize win;
	int aflg, kflg, ch, n;
	struct timeval tv, *tvp;
	time_t tvec, start;
	char obuf[BUFSIZ];
	char ibuf[BUFSIZ];
	fd_set rfd;
	int flushtime = 30;

	aflg = kflg = 0;
	while ((ch = getopt(argc, argv, "aqkt:")) != -1)
		switch(ch) {
		case 'a':
			aflg = 1;
			break;
		case 'q':
			qflg = 1;
			break;
		case 'k':
			kflg = 1;
			break;
		case 't':
			flushtime = atoi(optarg);
			if (flushtime < 0)
				err(1, "invalid flush time %d", flushtime);
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc > 0) {
		fname = argv[0];
		argv++;
		argc--;
	} else
		fname = "typescript";

	if ((fscript = fopen(fname, aflg ? "a" : "w")) == NULL)
		err(1, "%s", fname);

	if (ttyflg = isatty(STDIN_FILENO)) {
		if (tcgetattr(STDIN_FILENO, &tt) == -1)
			err(1, "tcgetattr");
		if (ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1)
			err(1, "ioctl");
		if (openpty(&master, &slave, NULL, &tt, &win) == -1)
			err(1, "openpty");
	} else {
		if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
			err(1, "openpty");
	}

	if (!qflg) {
		tvec = time(NULL);
		(void)printf("Script started, output file is %s\n", fname);
		(void)fprintf(fscript, "Script started on %s", ctime(&tvec));
		fflush(fscript);
	}
	if (ttyflg) {
		rtt = tt;
		cfmakeraw(&rtt);
		rtt.c_lflag &= ~ECHO;
		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
	}

	child = fork();
	if (child < 0) {
		warn("fork");
		done(1);
	}
	if (child == 0)
		doshell(argv);
#ifdef __APPLE__
	(void)close(slave);
#endif /* __APPLE__ */

	if (flushtime > 0)
		tvp = &tv;
	else
		tvp = NULL;

	start = time(0);
	FD_ZERO(&rfd);
	for (;;) {
		FD_SET(master, &rfd);
		FD_SET(STDIN_FILENO, &rfd);
		if (flushtime > 0) {
			tv.tv_sec = flushtime;
			tv.tv_usec = 0;
		}
		n = select(master + 1, &rfd, 0, 0, tvp);
		if (n < 0 && errno != EINTR)
			break;
		if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
			cc = read(STDIN_FILENO, ibuf, BUFSIZ);
			if (cc < 0)
				break;
			if (cc == 0)
				(void)write(master, ibuf, 0);
			if (cc > 0) {
				(void)write(master, ibuf, cc);
				if (kflg && tcgetattr(master, &stt) >= 0 &&
				    ((stt.c_lflag & ECHO) == 0)) {
					(void)fwrite(ibuf, 1, cc, fscript);
				}
			}
		}
		if (n > 0 && FD_ISSET(master, &rfd)) {
			cc = read(master, obuf, sizeof (obuf));
			if (cc <= 0)
				break;
			(void)write(STDOUT_FILENO, obuf, cc);
			(void)fwrite(obuf, 1, cc, fscript);
		}
		tvec = time(0);
		if (tvec - start >= flushtime) {
			fflush(fscript);
			start = tvec;
		}
	}
	finish();
	done(0);
}
Example #16
0
void
process(const char *name)
{
	char *cp;
	int c;
	int incomm = 0;
	int ret;

	printf("extern char\txstr[];\n");
	for (;;) {
		if (fgets(linebuf, sizeof linebuf, stdin) == NULL) {
			if (ferror(stdin))
				err(3, "%s", name);
			break;
		}
		if (linebuf[0] == '#') {
			if (linebuf[1] == ' ' && isdigit(linebuf[2]))
				printf("#line%s", &linebuf[1]);
			else
				printf("%s", linebuf);
			continue;
		}
		for (cp = linebuf; (c = *cp++);) switch (c) {

		case '"':
			if (incomm)
				goto def;
			if ((ret = (int) yankstr(&cp)) == -1)
				goto out;
			printf("(&xstr[%d])", ret);
			break;

		case '\'':
			if (incomm)
				goto def;
			putchar(c);
			if (*cp)
				putchar(*cp++);
			break;

		case '/':
			if (incomm || *cp != '*')
				goto def;
			incomm = 1;
			cp++;
			printf("/*");
			continue;

		case '*':
			if (incomm && *cp == '/') {
				incomm = 0;
				cp++;
				printf("*/");
				continue;
			}
			goto def;

def:
		default:
			putchar(c);
			break;
		}
	}
out:
	if (ferror(stdout))
		warn("x.c"), onintr(0);
}
Example #17
0
/*
 * pull in requested pieces of debug info
 */
struct dwarf_nebula *
elf_dwarfnebula(const char *name, FILE *fp, off_t foff, const Elf_Ehdr *eh,
    int flags)
{
	struct dwarf_nebula *dn = NULL;
	Elf_Shdr *shdr = NULL, *sh;
	char *shstr = NULL;
	char *names = NULL;
	char *lines = NULL;
	char *str = NULL;
	char *abbrv = NULL;
	char *info = NULL;

	if (!flags)
		return NULL;

	if (!(shdr = elf_load_shdrs(name, fp, foff, eh)))
		return NULL;

	elf_fix_shdrs(eh, shdr);
	if (!(shstr = elf_shstrload(name, fp, foff, eh, shdr)))
		return NULL;

	if (!(dn = calloc(1, sizeof *dn))) {
		warn("calloc");
		free(shstr);
		free(shdr);
		return NULL;
	}

	dn->name = name;
	dn->elfdata = eh->e_ident[EI_DATA];

	if (!(sh = elf_scan_shdrs(eh, shdr, shstr,
	    elf_lines_cmp, DWARF_INFO))) {
		warnx("%s: no " DWARF_INFO " section", name);
		goto kaput;
	}

	if (!(info = elf_sld(name, fp, foff, sh)))
		goto kaput;
	dn->ninfo = (ssize_t)sh->sh_size;

	if (!(sh = elf_scan_shdrs(eh, shdr, shstr,
	    elf_lines_cmp, DWARF_ABBREV))) {
		warnx("%s: no " DWARF_ABBREV " section", name);
		goto kaput;
	}

	if (!(abbrv = elf_sld(name, fp, foff, sh)))
		goto kaput;
	dn->nabbrv = (ssize_t)sh->sh_size;

	if (!(sh = elf_scan_shdrs(eh, shdr, shstr,
	    elf_lines_cmp, DWARF_STR))) {
		warnx("%s: no " DWARF_STR " section", name);
		goto kaput;
	}

	if (!(str = elf_sld(name, fp, foff, sh)))
		goto kaput;
	dn->nstr = (ssize_t)sh->sh_size;

	if (flags & ELF_DWARF_LINES) {
		if (!(sh = elf_scan_shdrs(eh, shdr, shstr,
		    elf_lines_cmp, DWARF_LINE))) {
			warnx("%s: no " DWARF_LINE " section", name);
			goto kaput;
		}

		if (!(lines = elf_sld(name, fp, foff, sh)))
			goto kaput;

		dn->nlines = (ssize_t)sh->sh_size;
	}

	if (flags & ELF_DWARF_NAMES) {
		if (!(sh = elf_scan_shdrs(eh, shdr, shstr,
		    elf_lines_cmp, DWARF_PUBNAMES))) {
			warnx("%s: no " DWARF_PUBNAMES " section", name);
			goto kaput;
		}

		if (!(names = elf_sld(name, fp, foff, sh)))
			goto kaput;

		dn->nnames = (ssize_t)sh->sh_size;
	}

	free(shstr);
	shstr = NULL;
	free(shdr);
	shdr = NULL;

	dn->names = names;
	dn->lines = lines;
	dn->str = str;
	dn->abbrv = abbrv;
	dn->info = info;
	if ((dn->nunits = dwarf_info_count(dn)) > 0) {
	    	if (flags & ELF_DWARF_LINES) {
			if (dwarf_info_lines(dn))
				goto kaput;
		}
	    	if (flags & ELF_DWARF_NAMES) {
			if (!dwarf_names_index(dn))
				return dn;
		} else
			return dn;
	}
 kaput:
	free(shstr);
	free(shdr);
	free(names);
	free(lines);
	free(str);
	free(abbrv);
	free(info);
	free(dn);
	return NULL;
}
Example #18
0
void Printer_options_REDEFINED( Handle self) { warn("Invalid call of Printer::options"); }
Example #19
0
static int system_cmd(const char *cmd, char *output_buffer, int length)
{
    debug("system_cmd '%s'", cmd);
    int pipefd[2];
    if (pipe(pipefd) < 0) {
        warn("pipe");
        return -1;
    }

    pid_t pid = fork();
    if (pid == 0) {
        // child
        int devnull = open("/dev/null", O_RDWR);
        if (devnull < 0) {
            warn("Couldn't open /dev/null");
            exit(EXIT_FAILURE);
        }

        close(pipefd[0]); // no reads from the pipe
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        if (dup2(devnull, STDIN_FILENO) < 0)
            warn("dup2 devnull");
        if (dup2(pipefd[1], STDOUT_FILENO) < 0)
            warn("dup2 pipe");
        close(devnull);

        char *cmd_copy = strdup(cmd);
        char *exec_path = strtok(cmd_copy, " ");
        char *exec_argv[16];
        int arg = 0;

        exec_argv[arg++] = exec_path;
        while ((exec_argv[arg] = strtok(NULL, " ")) != NULL)
            arg++;
        exec_argv[arg] = 0;
        if (exec_path)
            execvp(exec_path, exec_argv);

        // Not supposed to reach here.
        warn("execvp '%s' failed", cmd);
        exit(EXIT_FAILURE);
    } else {
        // parent
        close(pipefd[1]); // No writes to the pipe

        length--; // Save room for a '\0'
        int index = 0;
        int amt;
        while (index != length &&
               (amt = read(pipefd[0], &output_buffer[index], length - index)) > 0)
            index += amt;
        output_buffer[index] = '\0';
        close(pipefd[0]);

        int status;
        if (waitpid(pid, &status, 0) != pid) {
            warn("waitpid");
            return -1;
        }
        return status;
    }
}
Example #20
0
void
dovmstat(u_int interval, int reps)
{
	time_t uptime, halfuptime;
	struct clockinfo clkinfo;
	struct vmtotal total;
	size_t size;
	int mib[2];

	uptime = getuptime();
	halfuptime = uptime / 2;
	(void)signal(SIGCONT, needhdr);

	mib[0] = CTL_KERN;
	mib[1] = KERN_CLOCKRATE;
	size = sizeof(clkinfo);
	if (sysctl(mib, 2, &clkinfo, &size, NULL, 0) < 0) {
		warn("could not read kern.clockrate");
		return;
	}
	hz = clkinfo.stathz;

	for (hdrcnt = 1;;) {
		/* Read new disk statistics */
		dkreadstats();
		if (!--hdrcnt || last.dk_ndrive != cur.dk_ndrive)
			printhdr();
		if (nlistf == NULL && memf == NULL) {
			size = sizeof(struct uvmexp);
			mib[0] = CTL_VM;
			mib[1] = VM_UVMEXP;
			if (sysctl(mib, 2, &uvmexp, &size, NULL, 0) < 0) {
				warn("could not get vm.uvmexp");
				bzero(&uvmexp, sizeof(struct uvmexp));
			}
		} else {
			kread(X_UVMEXP, &uvmexp, sizeof(struct uvmexp));
		}
		size = sizeof(total);
		mib[0] = CTL_VM;
		mib[1] = VM_METER;
		if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
			warn("could not read vm.vmmeter");
			bzero(&total, sizeof(total));
		}
		(void)printf(" %u %u %u ",
		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
#define	rate(x)	((unsigned)((((unsigned)x) + halfuptime) / uptime)) /* round */
#define pgtok(a) ((a) * ((unsigned int)uvmexp.pagesize >> 10))
		(void)printf("%6u %7u ",
		    pgtok(uvmexp.active + uvmexp.swpginuse),
		    pgtok(uvmexp.free));
		(void)printf("%4u ", rate(uvmexp.faults - ouvmexp.faults));
		(void)printf("%3u ", rate(uvmexp.pdreact - ouvmexp.pdreact));
		(void)printf("%3u ", rate(uvmexp.pageins - ouvmexp.pageins));
		(void)printf("%3u %3u ",
		    rate(uvmexp.pdpageouts - ouvmexp.pdpageouts), 0);
		(void)printf("%3u ", rate(uvmexp.pdscans - ouvmexp.pdscans));
		dkstats();
		(void)printf("%4u %5u %4u ",
		    rate(uvmexp.intrs - ouvmexp.intrs),
		    rate(uvmexp.syscalls - ouvmexp.syscalls),
		    rate(uvmexp.swtch - ouvmexp.swtch));
		cpustats();
		(void)printf("\n");
		(void)fflush(stdout);
		if (reps >= 0 && --reps <= 0)
			break;
		ouvmexp = uvmexp;
		uptime = interval;
		/*
		 * We round upward to avoid losing low-frequency events
		 * (i.e., >= 1 per interval but < 1 per second).
		 */
		halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
		(void)sleep(interval);
	}
}
Example #21
0
int main( int argc, char *argv[] )
{
        int ntr=0;                /* number of traces                     */
        int ntrv=0;               /* number of traces                     */
	int ns=0;
	int nsv=0;
	float dt;
	float dtv;
	
	cwp_String fs;
	cwp_String fv;
	FILE *fps;
	FILE *fpv;
	FILE *headerfp;
		
	float *data;		/* data matrix of the migration volume */
	float *vel;		/* velocity matrix */
	float *velfi;		/* velocity function interpolated to ns values*/
	float *velf;		/* velocity function */
	float *vdt;
	float *ddt;
	float *ap;		/* array of apperture values in m */
	float apr;		/* array of apperture values in m */
	int *apt=NULL;		/* array of apperture time limits in mig. gath*/
	float   r;		/* maximum radius with a given apperture */
	float ir2;		/* r/d2 */
	float ir3;		/* r/d3 */
	float d2;		/* spatial sampling int. in dir 2. */
	float d3;		/* spatial sampling int. in dir 3. */
	float **mgd=NULL;	/* migration gather data */
	float *migt;		/* migrated data trace */
	int **mgdnz=NULL;		/* migration gather data non zero samples*/
	float dm;		/* migration gather spatial sample int. */
	int im;			/* number of traces in migration gather */
	int *mtnz;		/* migrated trace data non zero smaples */
	char **dummyi;		/* index array that the trace contains zeros only */
	float fac;		/* velocity scale factor */
	int sphr;		/* spherical divergence flag */
	int imt;		/* mute time sample of trace */
	float tmp;
	int imoff;
	int **igtr=NULL;
	int nigtr;
	int n2;
	int n3;

	int verbose;
	
	/* phase shift filter stuff */
        float power;            /* power of i omega applied to data     */
        float amp;              /* amplitude associated with the power  */
        float arg;              /* argument of power                    */
        float phasefac;         /* phase factor                         */
        float phase;            /* phase shift = phasefac*PI            */
        complex exparg;         /* cexp(I arg)                          */
        register float *rt;     /* real trace                           */
        register complex *ct;   /* complex transformed trace            */
        complex *filt;          /* complex power                        */
        float omega;            /* circular frequency                   */
        float domega;           /* circular frequency spacing (from dt) */
        float sign;             /* sign in front of i*omega default -1  */
        int nfft;               /* number of points in nfft             */
        int nf;                 /* number of frequencies (incl Nyq)     */
        float onfft;            /* 1 / nfft                             */
        size_t nzeros;          /* number of padded zeroes in bytes     */
	
	initargs(argc, argv);
   	requestdoc(1);
	
        MUSTGETPARSTRING("fs",&fs);
        MUSTGETPARSTRING("fv",&fv);
        MUSTGETPARINT("n2",&n2);
        MUSTGETPARINT("n3",&n3);
        MUSTGETPARFLOAT("d2",&d2);
        MUSTGETPARFLOAT("d3",&d3);
	
	if (!getparfloat("dm", &dm))	dm=(d2+d3)/2.0;
	
	/* open datafile */
        fps = efopen(fs,"r");
	fpv = efopen(fv,"r");
	
	/* Open tmpfile for headers */
	headerfp = etmpfile();

	/* get information from the first data trace */
	ntr = fgettra(fps,&tr,0);
	if(n2*n3!=ntr) err(" Number of traces in file %d not equal to n2*n3 %d \n",
			     ntr,n2*n3);
	ns=tr.ns;
	if (!getparfloat("dt", &dt))	dt = ((float) tr.dt)/1000000.0;
	if (!dt) {
		dt = .002;
		warn("dt not set, assumed to be .002");
	}

	/* get information from the first velocity trace */
	ntrv = fgettra(fpv,&trv,0);
	if(ntrv!=ntr) err(" Number of traces in velocity file %d differ from %d \n",
			     ntrv,ntr);
	nsv=trv.ns;
	if (!getparfloat("dtv", &dtv))	dtv = ((float) trv.dt)/1000000.0;
	if (!dtv) {
		dtv = .002;
		warn("dtv not set, assumed to be .002 for velocity");
	}
	
	if (!getparfloat("fac", &fac))	fac=2.0;
	if (!getparint("verbose", &verbose))	verbose=0;
	if (!getparint("sphr", &sphr))	sphr=0;
	
	if (!getparfloat("apr", &apr))	apr=75;
	apr*=3.141592653/180;

	/* allocate arrays */
	data = bmalloc(sizeof(float),ns,ntr);
	vel = bmalloc(sizeof(float),nsv,ntr);
	velf = ealloc1float(nsv); 
	velfi = ealloc1float(ns);
	migt = ealloc1float(ns);
	vdt = ealloc1float(nsv);
	ddt = ealloc1float(ns);
	ap = ealloc1float(ns);
	mtnz = ealloc1int(ns);
	dummyi = (char **) ealloc2(n2,n3,sizeof(char));
	
	/* Times to do interpolation of velocity from sparse sampling */
	/* to fine sampling of the data */
	{ register int it;
		for(it=0;it<nsv;it++) vdt[it]=it*dtv;
		for(it=0;it<ns;it++)  ddt[it]=it*dt;
	}
	
	/* Read traces into data */
        /* Store headers in tmpfile */
        ntr=0;
	erewind(fps);
	erewind(fpv);
		
	{ register int i2,i3;
	for(i3=0;i3<n3;i3++) 
		for(i2=0;i2<n2;i2++) {
			fgettr(fps,&tr);
			fgettr(fpv,&trv);
			if(tr.trid > 2) dummyi[i3][i2]=1;
			else dummyi[i3][i2]=0;	
			efwrite(&tr, 1, HDRBYTES, headerfp);
		 	bmwrite(data,1,0,i3*n2+i2,ns,tr.data);
		 	bmwrite(vel,1,0,i3*n2+i2,nsv,trv.data);
		}
	erewind(headerfp);

	/* set up the phase filter */
	power = 1.0;sign = 1.0;phasefac = 0.5;
	phase = phasefac * PI;
         
	/* Set up for fft */
        nfft = npfaro(ns, LOOKFAC * ns);
        if (nfft >= SU_NFLTS || nfft >= PFA_MAX)
                err("Padded nt=%d -- too big", nfft);

        nf = nfft/2 + 1;
        onfft = 1.0 / nfft;
        nzeros = (nfft - ns) * FSIZE;
        domega = TWOPI * onfft / dt;
        
	/* Allocate fft arrays */
        rt   = ealloc1float(nfft);
        ct   = ealloc1complex(nf);
        filt = ealloc1complex(nf);
        
	/* Set up args for complex power evaluation */
        arg = sign * PIBY2 * power + phase;
        exparg = cexp(crmul(I, arg));
        {       
		register int i;
                for (i = 0 ; i < nf; ++i) {

                        omega = i * domega;
		
		        /* kludge to handle omega=0 case for power < 0 */
                        if (power < 0 && i == 0) omega = FLT_MAX;

                        /* calculate filter */
                        amp = pow(omega, power) * onfft;
			filt[i] = crmul(exparg, amp);
                }
        }
	
	/* set up constants for migration */ 
	if(verbose) fprintf(stderr," Setting up constants....\n");
	r=0;
	for(i3=0;i3<n3;i3++) 
	    for(i2=0;i2<n2;i2++) {
		if(dummyi[i3][i2] < 1) {
			
			/* get the velocity function */
			bmread(vel,1,0,i3*n2+i2,nsv,velf);
			
			/* linear interpolation from nsv to ns values */  
			intlin(nsv,vdt,velf,velf[0],velf[nsv-1],ns,ddt,velfi);
			
			/* Apply scale factor to velocity */
			{ register int it;
				for(it=0;it<ns;it++) velfi[it] *=fac;
			}
			
			/* compute maximum radius from apperture and velocity */
			{ register int it;
				for(it=0;it<ns;it++) 
				ap[it] = ddt[it]*velfi[it]*tan(apr)/2.0;
			}
			tmp = ap[isamax(ns,ap,1)];
			if(tmp>r) r=tmp;
		}
	}
	r=MIN(r,sqrt(SQR((n2-1)*d2)+SQR((n3-1)*d3)));
	ir2 =  (int)(2*r/d2)+1;
	ir3 =  (int)(2*r/d3)+1;
	im = (int)(r/dm)+1;
		
	/*  allocate migration gather */
	mgd = ealloc2float(ns,im);
	mgdnz = ealloc2int(ns,im);
	apt = ealloc1int(im);
	/* set up the stencil for selecting traces */
	igtr = ealloc2int(ir2*ir3,2);
	stncl(r, d2, d3,igtr,&nigtr);
	
	if(verbose) {
		fprintf(stderr," Maximum radius %f\n",r);
		fprintf(stderr," Maximum offset %f\n",
			sqrt(SQR((n2-1)*d2)+SQR((n3-1)*d3)));
	}

	/* main processing loop */
	for(i3=0;i3<n3;i3++) 
	    for(i2=0;i2<n2;i2++) {
		memset( (void *) tr.data, (int) '\0',ns*FSIZE);
		if(dummyi[i3][i2] < 1) {
			memset( (void *) mgd[0], (int) '\0',ns*im*FSIZE);
			memset( (void *) mgdnz[0], (int) '\0',ns*im*ISIZE);
			/* get the velocity function */
			bmread(vel,1,0,i3*n2+i2,nsv,velf);
		
			/* linear interpolation from nsv to ns values */  
			intlin(nsv,vdt,velf,velf[0],velf[nsv-1],ns,ddt,velfi);
		
			/* Apply scale factor to velocity */
			{ register int it;
				for(it=0;it<ns;it++) velfi[it] *=fac;
			}

			/* create the migration gather */
			{ register int itr,ist2,ist3;
				for(itr=0;itr<nigtr;itr++) {
					ist2=i2+igtr[0][itr];
					ist3=i3+igtr[1][itr];
					if(ist2 >= 0 && ist2 <n2) 
						if(ist3 >= 0 && ist3 <n3) {
							if(dummyi[ist3][ist2] <1) {
								imoff = (int) ( 
								sqrt(SQR(igtr[0][itr]*d2)
							     	    +SQR(igtr[1][itr]*d3))/dm+0.5);
								bmread(data,1,0,ist3*n2+ist2,ns,tr.data);
								imoff=MIN(imoff,im-1);
								{ register int it;									
									/* get the mute time for this 
									  offset, apperture and velocity */
									xindex(ns,ap,imoff*dm,&imt);
									for(it=imt;it<ns;it++)
										if(tr.data[it]!=0) {
											mgd[imoff][it]+=tr.data[it];
											mgdnz[imoff][it]+=1;
									}	
								}
							}
						}
				}
			}

			/* normalize the gather */
				{ register int ix,it;
				for(ix=0;ix<im;ix++)
					for(it=0;it<ns;it++) 
						if(mgdnz[ix][it] > 1) mgd[ix][it] /=(float) mgdnz[ix][it];
			}
			memset( (void *) tr.data, (int) '\0',ns*FSIZE);
			memset( (void *) mtnz, (int) '\0',ns*ISIZE);
		
			/* do a knmo */
			{ register int ix,it;
				for(ix=0;ix<im;ix++) {
					/* get the mute time for this 
					offset, apperture and velocity */
					xindex(ns,ap,ix*dm,&imt);
					knmo(mgd[ix],migt,ns,velfi,0,ix*dm,dt,imt,sphr);
					/* stack the gather */
						for(it=0;it<ns;it++) { 
						if(migt[it]!=0.0) { 
								tr.data[it] += migt[it];
								mtnz[it]++;
						}
/*						tr.data[it] += mgd[ix][it]; */
					}
				}

			}
			{ register int it;
				for(it=0;it<ns;it++) 
					if(mtnz[it]>1) tr.data[it] /=(float)mtnz[it];
			}
		
			/*Do the phase filtering before the trace is released*/
                	/* Load trace into rt (zero-padded) */
               		memcpy( (void *) rt, (const void *) tr.data, ns*FSIZE);
               		memset((void *) (rt + ns), (int) '\0', nzeros);

         		pfarc(1, nfft, rt, ct);
        		{ register int i;
        			for (i = 0; i < nf; ++i)  ct[i] = cmul(ct[i], filt[i]);
        		}
         		pfacr(-1, nfft, ct, rt);
     			memcpy( (void *) tr.data, (const void *) rt, ns*FSIZE);
			
		} /* end of dummy if */
		/* spit out the gather */
		efread(&tr, 1, HDRBYTES, headerfp);
		puttr(&tr);
		if(verbose) fprintf(stderr," %d %d\n",i2,i3);
	    }   /* end of i2 loop */
	}	/* end of i3 loop */
	/* This should be the last thing */
	efclose(headerfp);
	/* Free memory */
	free2int(igtr);
	free2float(mgd);
	free2int(mgdnz);
	free1int(apt);
	bmfree(data);
	bmfree(vel);
	free1float(velfi);
	free1float(velf);
	free1float(ddt);
	free1float(vdt);
	free1float(ap);
	free1int(mtnz);
	free1float(migt);
	free1float(rt);
	free1complex(ct);
	free1complex(filt);
	free2((void **) dummyi);
	
	return EXIT_SUCCESS;
}
Example #22
0
void
dosum(void)
{
	struct nchstats nchstats;
	int mib[2], nselcoll;
	long long nchtotal;
	size_t size;

	if (nlistf == NULL && memf == NULL) {
		size = sizeof(struct uvmexp);
		mib[0] = CTL_VM;
		mib[1] = VM_UVMEXP;
		if (sysctl(mib, 2, &uvmexp, &size, NULL, 0) < 0) {
			warn("could not read vm.uvmexp");
			bzero(&uvmexp, sizeof(struct uvmexp));
		}
	} else {
		kread(X_UVMEXP, &uvmexp, sizeof(struct uvmexp));
	}

	/* vm_page constants */
	(void)printf("%11u bytes per page\n", uvmexp.pagesize);

	/* vm_page counters */
	(void)printf("%11u pages managed\n", uvmexp.npages);
	(void)printf("%11u pages free\n", uvmexp.free);
	(void)printf("%11u pages active\n", uvmexp.active);
	(void)printf("%11u pages inactive\n", uvmexp.inactive);
	(void)printf("%11u pages being paged out\n", uvmexp.paging);
	(void)printf("%11u pages wired\n", uvmexp.wired);
	(void)printf("%11u pages zeroed\n", uvmexp.zeropages);
	(void)printf("%11u pages reserved for pagedaemon\n",
		     uvmexp.reserve_pagedaemon);
	(void)printf("%11u pages reserved for kernel\n",
		     uvmexp.reserve_kernel);

	/* swap */
	(void)printf("%11u swap pages\n", uvmexp.swpages);
	(void)printf("%11u swap pages in use\n", uvmexp.swpginuse);
	(void)printf("%11u total anon's in system\n", uvmexp.nanon);
	(void)printf("%11u free anon's\n", uvmexp.nfreeanon);

	/* stat counters */
	(void)printf("%11u page faults\n", uvmexp.faults);
	(void)printf("%11u traps\n", uvmexp.traps);
	(void)printf("%11u interrupts\n", uvmexp.intrs);
	(void)printf("%11u cpu context switches\n", uvmexp.swtch);
	(void)printf("%11u fpu context switches\n", uvmexp.fpswtch);
	(void)printf("%11u software interrupts\n", uvmexp.softs);
	(void)printf("%11u syscalls\n", uvmexp.syscalls);
	(void)printf("%11u pagein operations\n", uvmexp.pageins);
	(void)printf("%11u forks\n", uvmexp.forks);
	(void)printf("%11u forks where vmspace is shared\n",
		     uvmexp.forks_sharevm);
	(void)printf("%11u kernel map entries\n", uvmexp.kmapent);

	/* daemon counters */
	(void)printf("%11u number of times the pagedaemon woke up\n",
		     uvmexp.pdwoke);
	(void)printf("%11u revolutions of the clock hand\n", uvmexp.pdrevs);
	(void)printf("%11u pages freed by pagedaemon\n", uvmexp.pdfreed);
	(void)printf("%11u pages scanned by pagedaemon\n", uvmexp.pdscans);
	(void)printf("%11u pages reactivated by pagedaemon\n", uvmexp.pdreact);
	(void)printf("%11u busy pages found by pagedaemon\n", uvmexp.pdbusy);

	if (nlistf == NULL && memf == NULL) {
		size = sizeof(nchstats);
		mib[0] = CTL_KERN;
		mib[1] = KERN_NCHSTATS;
		if (sysctl(mib, 2, &nchstats, &size, NULL, 0) < 0) {
			warn("could not read kern.nchstats");
			bzero(&nchstats, sizeof(nchstats));
		}
	} else {
		kread(X_NCHSTATS, &nchstats, sizeof(nchstats));
	}

	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
	    nchstats.ncs_miss + nchstats.ncs_long;
	(void)printf("%11lld total name lookups\n", nchtotal);
	(void)printf("%11s cache hits (%d%% pos + %d%% neg) system %d%% "
	    "per-directory\n",
	    "", pct(nchstats.ncs_goodhits, nchtotal),
	    pct(nchstats.ncs_neghits, nchtotal),
	    pct(nchstats.ncs_pass2, nchtotal));
	(void)printf("%11s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
	    pct(nchstats.ncs_badhits, nchtotal),
	    pct(nchstats.ncs_falsehits, nchtotal),
	    pct(nchstats.ncs_long, nchtotal));

	if (nlistf == NULL && memf == NULL) {
		size = sizeof(nselcoll);
		mib[0] = CTL_KERN;
		mib[1] = KERN_NSELCOLL;
		if (sysctl(mib, 2, &nselcoll, &size, NULL, 0) < 0) {
			warn("could not read kern.nselcoll");
			nselcoll = 0;
		}
	} else {
		kread(X_NSELCOLL, &nselcoll, sizeof(nselcoll));
	}
	(void)printf("%11d select collisions\n", nselcoll);
}
Example #23
0
static int midoflus_init(void *arg)
{
    int ret;
    char *sfont;
    char *def_sfonts[] = {
	"/usr/share/soundfonts/default.sf2",		// fedora
	"/usr/share/soundfonts/FluidR3_GM.sf2",		// fedora
	"/usr/share/sounds/sf2/FluidR3_GM.sf2.flac",	// ubuntu
	"/usr/share/sounds/sf2/FluidR3_GM.sf2",		// debian
	NULL };
    int use_defsf = 0;

    settings = new_fluid_settings();
    fluid_settings_setint(settings, "synth.lock-memory", 0);
    fluid_settings_setnum(settings, "synth.gain", flus_gain);
    ret = fluid_settings_setint(settings, "synth.threadsafe-api", 1);
    if (ret == 0) {
	warn("fluidsynth: no threadsafe API\n");
	goto err1;
    }
    ret = fluid_settings_getnum(settings, "synth.sample-rate", &flus_srate);
    if (ret == 0) {
	warn("fluidsynth: cannot get samplerate\n");
	goto err1;
    }
    ret = fluid_settings_getstr(settings, "synth.default-soundfont", &sfont);
    if (ret == 0) {
	int i = 0;
	warn("Your fluidsynth is too old\n");
	while (def_sfonts[i]) {
	    if (access(def_sfonts[i], R_OK) == 0) {
		sfont = def_sfonts[i];
		use_defsf = 1;
		break;
	    }
	    i++;
	}
	if (!use_defsf) {
	    error("Your fluidsynth is too old and soundfonts not found\n");
	    goto err1;
	}
    }

    synth = new_fluid_synth(settings);
    ret = fluid_synth_sfload(synth, sfont, TRUE);
    if (ret == FLUID_FAILED) {
	warn("fluidsynth: cannot load soundfont %s\n", sfont);
	if (use_defsf)
	    error("Your fluidsynth is too old\n");
	goto err2;
    }
    fluid_settings_setstr(settings, "synth.midi-bank-select", "gm");
    S_printf("fluidsynth: loaded soundfont %s ID=%i\n", sfont, ret);
    sequencer = new_fluid_sequencer2(0);
    synthSeqID = fluid_sequencer_register_fluidsynth2(sequencer, synth);

    sem_init(&syn_sem, 0, 0);
    pthread_create(&syn_thr, NULL, synth_thread, NULL);
#ifdef HAVE_PTHREAD_SETNAME_NP
    pthread_setname_np(syn_thr, "dosemu: fluid");
#endif
    pcm_stream = pcm_allocate_stream(FLUS_CHANNELS, "MIDI",
	    (void*)MC_MIDI);

    return 1;

err2:
    delete_fluid_synth(synth);
err1:
    delete_fluid_settings(settings);
    return 0;
}
Example #24
0
void
domem(void)
{
	struct kmembuckets buckets[MINBUCKET + 16], *kp;
	struct kmemstats kmemstats[M_LAST], *ks;
	int i, j, len, size, first, mib[4];
	u_long totuse = 0, totfree = 0;
	char buf[BUFSIZ], *bufp, *ap;
	quad_t totreq = 0;
	const char *name;
	size_t siz;

	if (memf == NULL && nlistf == NULL) {
		mib[0] = CTL_KERN;
		mib[1] = KERN_MALLOCSTATS;
		mib[2] = KERN_MALLOC_BUCKETS;
		siz = sizeof(buf);
		if (sysctl(mib, 3, buf, &siz, NULL, 0) < 0) {
			warnx("could not read kern.malloc.buckets");
			return;
		}

		bufp = buf;
		mib[2] = KERN_MALLOC_BUCKET;
		siz = sizeof(struct kmembuckets);
		i = 0;
		while ((ap = strsep(&bufp, ",")) != NULL) {
			mib[3] = atoi(ap);

			if (sysctl(mib, 4, &buckets[MINBUCKET + i], &siz,
			    NULL, 0) < 0) {
				warn("could not read kern.malloc.bucket.%d", mib[3]);
				return;
			}
			i++;
		}
	} else {
		kread(X_KMEMBUCKETS, buckets, sizeof(buckets));
	}

	for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
	     i++, kp++) {
		if (kp->kb_calls == 0 && !verbose)
			continue;
		if (first) {
			(void)printf("Memory statistics by bucket size\n");
			(void)printf(
		"    Size   In Use   Free           Requests  HighWater  Couldfree\n");
			first = 0;
		}
		size = 1 << i;
		(void)printf("%8d %8llu %6llu %18llu %7llu %10llu\n", size,
			(unsigned long long)(kp->kb_total - kp->kb_totalfree),
			(unsigned long long)kp->kb_totalfree,
			(unsigned long long)kp->kb_calls,
			(unsigned long long)kp->kb_highwat,
			(unsigned long long)kp->kb_couldfree);
		totfree += size * kp->kb_totalfree;
	}

	/*
	 * If kmem statistics are not being gathered by the kernel,
	 * first will still be 1.
	 */
	if (first) {
		printf(
		    "Kmem statistics are not being gathered by the kernel.\n");
		return;
	}

	if (memf == NULL && nlistf == NULL) {
		bzero(kmemstats, sizeof(kmemstats));
		for (i = 0; i < M_LAST; i++) {
			mib[0] = CTL_KERN;
			mib[1] = KERN_MALLOCSTATS;
			mib[2] = KERN_MALLOC_KMEMSTATS;
			mib[3] = i;
			siz = sizeof(struct kmemstats);

			/*
			 * Skip errors -- these are presumed to be unallocated
			 * entries.
			 */
			if (sysctl(mib, 4, &kmemstats[i], &siz, NULL, 0) < 0)
				continue;
		}
	} else {
		kread(X_KMEMSTAT, kmemstats, sizeof(kmemstats));
	}

	(void)printf("\nMemory usage type by bucket size\n");
	(void)printf("    Size  Type(s)\n");
	kp = &buckets[MINBUCKET];
	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
		if (kp->kb_calls == 0)
			continue;
		first = 1;
		len = 8;
		for (i = 0, ks = &kmemstats[0]; i < M_LAST; i++, ks++) {
			if (ks->ks_calls == 0)
				continue;
			if ((ks->ks_size & j) == 0)
				continue;
			name = kmemnames[i] ? kmemnames[i] : "undefined";
			len += 2 + strlen(name);
			if (first)
				printf("%8d  %s", j, name);
			else
				printf(",");
			if (len >= 80) {
				printf("\n\t ");
				len = 10 + strlen(name);
			}
			if (!first)
				printf(" %s", name);
			first = 0;
		}
		printf("\n");
	}

	(void)printf(
	   "\nMemory statistics by type                           Type  Kern\n");
	(void)printf(
"          Type InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
	for (i = 0, ks = &kmemstats[0]; i < M_LAST; i++, ks++) {
		if (ks->ks_calls == 0)
			continue;
		(void)printf("%14s%6ld%6ldK%7ldK%6ldK%9ld%5u%6u",
		    kmemnames[i] ? kmemnames[i] : "undefined",
		    ks->ks_inuse, (ks->ks_memuse + 1023) / 1024,
		    (ks->ks_maxused + 1023) / 1024,
		    (ks->ks_limit + 1023) / 1024, ks->ks_calls,
		    ks->ks_limblocks, ks->ks_mapblocks);
		first = 1;
		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
			if ((ks->ks_size & j) == 0)
				continue;
			if (first)
				printf("  %d", j);
			else
				printf(",%d", j);
			first = 0;
		}
		printf("\n");
		totuse += ks->ks_memuse;
		totreq += ks->ks_calls;
	}
	(void)printf("\nMemory Totals:  In Use    Free    Requests\n");
	(void)printf("              %7luK %6luK    %8qu\n",
	     (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
}
Example #25
0
/* Read the command line arguments, and do the inital parsing of the parameter file. */
static mwbool readParameters(const int argc, const char* argv[], NBodyFlags* nbf)
{
    int argRead;
    poptContext context;
    const char** rest = NULL;   /* Leftover arguments */
    mwbool failed = FALSE;

    unsigned int numParams = 0, params = 0;

    /* FIXME: There's a small leak of the inputFile from use of
       poptGetNextOpt(). Some mailing list post suggestst that this
       is some kind of semi-intended bug to work around something or other */
    const struct poptOption options[] =
    {
        {
            "input-file", 'f',
            POPT_ARG_STRING, &nbf->inputFile,
            0, "Input Lua file to read", NULL
        },

        {
            "histoout-file", 'z',
            POPT_ARG_STRING, &nbf->histoutFileName,
            0, "Output histogram file", NULL
        },

        {
            "histogram-file", 'h',
            POPT_ARG_STRING, &nbf->histogramFileName,
            0, "Histogram file", NULL
        },

        {
            "output-file", 'o',
            POPT_ARG_STRING, &nbf->outFileName,
            0, "Output file", NULL
        },

        {
            "output-cartesian", 'x',
            POPT_ARG_NONE, &nbf->outputCartesian,
            0, "Output Cartesian coordinates instead of lbR", NULL
        },

        {
            "timing", 't',
            POPT_ARG_NONE, &nbf->printTiming,
            0, "Print timing of actual run", NULL
        },

        {
            "verify-file", 'v',
            POPT_ARG_NONE, &nbf->verifyOnly,
            0, "Check that the input file is valid only; perform no calculation.", NULL
        },

        {
            "checkpoint", 'c',
            POPT_ARG_STRING, &nbf->checkpointFileName,
            0, "Checkpoint file to use", NULL
        },

        {
            "clean-checkpoint", 'k',
            POPT_ARG_NONE, &nbf->cleanCheckpoint,
            0, "Cleanup checkpoint after finishing run", NULL
        },

        {
            "checkpoint-interval", 'w',
            POPT_ARG_INT, &nbf->checkpointPeriod,
            0, "Period (in seconds) to checkpoint. -1 to disable", NULL
        },

        {
            "debug-boinc", 'g',
            POPT_ARG_NONE, &nbf->debugBOINC,
            0, "Init BOINC with debugging. No effect if not built with BOINC_APPLICATION", NULL
        },

        {
            "lua-debug-libraries", 'a',
            POPT_ARG_NONE, &nbf->debugLuaLibs,
            0, "Load extra Lua libraries not normally allowed (e.g. io) ", NULL
        },

        {
            "visualizer", 'u',
            POPT_ARG_NONE, &nbf->visualizer,
            0, "Try to run N-body visualization", NULL
        },

        {
            "visualizer-args", '\0',
            POPT_ARG_STRING, &nbf->visArgs,
            0, "Command line to pass on to visualizer", NULL
        },

        {
            "ignore-checkpoint", 'i',
            POPT_ARG_NONE, &nbf->ignoreCheckpoint,
            0, "Ignore the checkpoint file", NULL
        },

        {
            "print-bodies", 'b',
            POPT_ARG_NONE, &nbf->printBodies,
            0, "Print bodies", NULL
        },

        {
            "print-histogram", 'm',
            POPT_ARG_NONE, &nbf->printHistogram,
            0, "Print histogram", NULL
        },

      #ifdef _OPENMP
        {
            "nthreads", 'n',
            POPT_ARG_INT, &nbf->numThreads,
            0, "BOINC argument for number of threads", NULL
        },
      #endif /* _OPENMP */

        {
            "p", 'p',
            POPT_ARG_NONE, &params,
            0, "Unused dummy argument to satisfy primitive arguments the server sends", NULL
        },

        {
            "np", '\0',
            POPT_ARG_INT | POPT_ARGFLAG_ONEDASH, &numParams,
            0, "Unused dummy argument to satisfy primitive arguments the server sends", NULL
        },

        {
            "seed", 'e',
            POPT_ARG_INT, &nbf->setSeed,
            'e', "seed for PRNG", NULL
        },

        POPT_AUTOHELP
        POPT_TABLEEND
    };

    context = poptGetContext(argv[0], argc, argv, options, 0);

    if (argc < 2)
    {
        poptPrintUsage(context, stderr, 0);
        poptFreeContext(context);
        return TRUE;
    }

    /* Check for invalid options, and must have the input file or a
     * checkpoint to resume from */
    argRead = mwReadArguments(context);
    if (argRead < 0 || (!nbf->inputFile && !nbf->checkpointFileName))
    {
        poptPrintHelp(context, stderr, 0);
        failed = TRUE;
    }

    rest = poptGetArgs(context);
    if ((params || numParams) && !rest)
    {
        warn("Expected arguments to follow, got 0\n");
        failed = TRUE;
    }
    else
    {
        setForwardedArguments(nbf, rest);
    }

    poptFreeContext(context);

    return failed;
}
Example #26
0
void
print_periphs(int session_id)
{
	union ccb ccb;
	int bufsize, fd;
	unsigned int i;
	int skip_bus, skip_device;

	if ((fd = open(XPT_DEVICE, O_RDWR)) == -1) {
		warn("couldn't open %s", XPT_DEVICE);
		return;
	}

	/*
	 * First, iterate over the whole list to find the bus.
	 */

	bzero(&ccb, sizeof(union ccb));

	ccb.ccb_h.path_id = CAM_XPT_PATH_ID;
	ccb.ccb_h.target_id = CAM_TARGET_WILDCARD;
	ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;

	ccb.ccb_h.func_code = XPT_DEV_MATCH;
	bufsize = sizeof(struct dev_match_result) * 100;
	ccb.cdm.match_buf_len = bufsize;
	ccb.cdm.matches = (struct dev_match_result *)malloc(bufsize);
	if (ccb.cdm.matches == NULL) {
		warnx("can't malloc memory for matches");
		close(fd);
		return;
	}
	ccb.cdm.num_matches = 0;

	/*
	 * We fetch all nodes, since we display most of them in the default
	 * case, and all in the verbose case.
	 */
	ccb.cdm.num_patterns = 0;
	ccb.cdm.pattern_buf_len = 0;

	skip_bus = 1;
	skip_device = 1;

	/*
	 * We do the ioctl multiple times if necessary, in case there are
	 * more than 100 nodes in the EDT.
	 */
	do {
		if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
			warn("error sending CAMIOCOMMAND ioctl");
			break;
		}

		if ((ccb.ccb_h.status != CAM_REQ_CMP)
		 || ((ccb.cdm.status != CAM_DEV_MATCH_LAST)
		    && (ccb.cdm.status != CAM_DEV_MATCH_MORE))) {
			warnx("got CAM error %#x, CDM error %d\n",
			      ccb.ccb_h.status, ccb.cdm.status);
			break;
		}

		for (i = 0; i < ccb.cdm.num_matches; i++) {
			switch (ccb.cdm.matches[i].type) {
			case DEV_MATCH_BUS: {
				struct bus_match_result *bus_result;

				bus_result = &ccb.cdm.matches[i].result.bus_result;

				skip_bus = 1;

				if (strcmp(bus_result->dev_name, "iscsi") != 0) {
					//printf("not iscsi\n");
					continue;
				}

				if ((int)bus_result->unit_number != session_id) {
					//printf("wrong unit, %d != %d\n", bus_result->unit_number, session_id);
					continue;
				}

				skip_bus = 0;
			}
			case DEV_MATCH_DEVICE: {
				skip_device = 1;

				if (skip_bus != 0)
					continue;

				skip_device = 0;

				break;
			}
			case DEV_MATCH_PERIPH: {
				struct periph_match_result *periph_result;

				periph_result =
				      &ccb.cdm.matches[i].result.periph_result;

				if (skip_device != 0)
					continue;

				if (strcmp(periph_result->periph_name, "pass") == 0)
					continue;

				fprintf(stdout, "%s%d ",
					periph_result->periph_name,
					periph_result->unit_number);

				break;
			}
			default:
				fprintf(stdout, "unknown match type\n");
				break;
			}
		}

	} while ((ccb.ccb_h.status == CAM_REQ_CMP)
		&& (ccb.cdm.status == CAM_DEV_MATCH_MORE));

	close(fd);
}
Example #27
0
int sdlog_thread_main(int argc, char *argv[])
{
	mavlink_fd = open(MAVLINK_LOG_DEVICE, 0);

	if (mavlink_fd < 0) {
		warnx("ERROR: Failed to open MAVLink log stream, start mavlink app first.\n");
	}

	/* log every n'th value (skip three per default) */
	int skip_value = 3;

	/* work around some stupidity in task_create's argv handling */
	argc -= 2;
	argv += 2;
	int ch;

	while ((ch = getopt(argc, argv, "s:r")) != EOF) {
		switch (ch) {
		case 's':
			{
			/* log only every n'th (gyro clocked) value */
			unsigned s = strtoul(optarg, NULL, 10);

			if (s < 1 || s > 250) {
				errx(1, "Wrong skip value of %d, out of range (1..250)\n", s);
			} else {
				skip_value = s;
			}
			}
			break;

		case 'r':
			/* log only on request, disable logging per default */
			logging_enabled = false;
			break;

		case '?':
			if (optopt == 'c') {
				warnx("Option -%c requires an argument.\n", optopt);
			} else if (isprint(optopt)) {
				warnx("Unknown option `-%c'.\n", optopt);
			} else {
				warnx("Unknown option character `\\x%x'.\n", optopt);
			}

		default:
			usage("unrecognized flag");
			errx(1, "exiting.");
		}
	}

	if (file_exist(mountpoint) != OK) {
		errx(1, "logging mount point %s not present, exiting.", mountpoint);
	}

	char folder_path[64];

	if (create_logfolder(folder_path))
		errx(1, "unable to create logging folder, exiting.");

	FILE *gpsfile;
	FILE *blackbox_file;

	/* string to hold the path to the sensorfile */
	char path_buf[64] = "";

	/* only print logging path, important to find log file later */
	warnx("logging to directory %s\n", folder_path);

	/* set up file path: e.g. /mnt/sdcard/session0001/actuator_controls0.bin */
	sprintf(path_buf, "%s/%s.bin", folder_path, "sysvector");

	if (0 == (sysvector_file = open(path_buf, O_CREAT | O_WRONLY | O_DSYNC))) {
		errx(1, "opening %s failed.\n", path_buf);
	}

	/* set up file path: e.g. /mnt/sdcard/session0001/gps.txt */
	sprintf(path_buf, "%s/%s.txt", folder_path, "gps");

	if (NULL == (gpsfile = fopen(path_buf, "w"))) {
		errx(1, "opening %s failed.\n", path_buf);
	}

	int gpsfile_no = fileno(gpsfile);

	/* set up file path: e.g. /mnt/sdcard/session0001/blackbox.txt */
	sprintf(path_buf, "%s/%s.txt", folder_path, "blackbox");

	if (NULL == (blackbox_file = fopen(path_buf, "w"))) {
		errx(1, "opening %s failed.\n", path_buf);
	}

	// XXX for fsync() calls
	int blackbox_file_no = fileno(blackbox_file);

	/* --- IMPORTANT: DEFINE NUMBER OF ORB STRUCTS TO WAIT FOR HERE --- */
	/* number of messages */
	const ssize_t fdsc = 25;
	/* Sanity check variable and index */
	ssize_t fdsc_count = 0;
	/* file descriptors to wait for */
	struct pollfd fds[fdsc];


	struct {
		struct sensor_combined_s raw;
		struct vehicle_attitude_s att;
		struct vehicle_attitude_setpoint_s att_sp;
		struct actuator_outputs_s act_outputs;
		struct actuator_controls_s act_controls;
		struct actuator_controls_effective_s act_controls_effective;
		struct vehicle_command_s cmd;
		struct vehicle_local_position_s local_pos;
		struct vehicle_global_position_s global_pos;
		struct vehicle_gps_position_s gps_pos;
		struct vehicle_vicon_position_s vicon_pos;
		struct optical_flow_s flow;
		struct battery_status_s batt;
		struct differential_pressure_s diff_pres;
		struct airspeed_s airspeed;
	} buf;
	memset(&buf, 0, sizeof(buf));

	struct {
		int cmd_sub;
		int sensor_sub;
		int att_sub;
		int spa_sub;
		int act_0_sub;
		int controls_0_sub;
		int controls_effective_0_sub;
		int local_pos_sub;
		int global_pos_sub;
		int gps_pos_sub;
		int vicon_pos_sub;
		int flow_sub;
		int batt_sub;
		int diff_pres_sub;
		int airspeed_sub;
	} subs;

	/* --- MANAGEMENT - LOGGING COMMAND --- */
	/* subscribe to ORB for vehicle command */
	subs.cmd_sub = orb_subscribe(ORB_ID(vehicle_command));
	fds[fdsc_count].fd = subs.cmd_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- GPS POSITION --- */
	/* subscribe to ORB for global position */
	subs.gps_pos_sub = orb_subscribe(ORB_ID(vehicle_gps_position));
	fds[fdsc_count].fd = subs.gps_pos_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- SENSORS RAW VALUE --- */
	/* subscribe to ORB for sensors raw */
	subs.sensor_sub = orb_subscribe(ORB_ID(sensor_combined));
	fds[fdsc_count].fd = subs.sensor_sub;
	/* do not rate limit, instead use skip counter (aliasing on rate limit) */
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- ATTITUDE VALUE --- */
	/* subscribe to ORB for attitude */
	subs.att_sub = orb_subscribe(ORB_ID(vehicle_attitude));
	fds[fdsc_count].fd = subs.att_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- ATTITUDE SETPOINT VALUE --- */
	/* subscribe to ORB for attitude setpoint */
	/* struct already allocated */
	subs.spa_sub = orb_subscribe(ORB_ID(vehicle_attitude_setpoint));
	fds[fdsc_count].fd = subs.spa_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/** --- ACTUATOR OUTPUTS --- */
	subs.act_0_sub = orb_subscribe(ORB_ID(actuator_outputs_0));
	fds[fdsc_count].fd = subs.act_0_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- ACTUATOR CONTROL VALUE --- */
	/* subscribe to ORB for actuator control */
	subs.controls_0_sub = orb_subscribe(ORB_ID_VEHICLE_ATTITUDE_CONTROLS);
	fds[fdsc_count].fd = subs.controls_0_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- ACTUATOR CONTROL EFFECTIVE VALUE --- */
	/* subscribe to ORB for actuator control */
	subs.controls_effective_0_sub = orb_subscribe(ORB_ID_VEHICLE_ATTITUDE_CONTROLS_EFFECTIVE);
	fds[fdsc_count].fd = subs.controls_effective_0_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- LOCAL POSITION --- */
	/* subscribe to ORB for local position */
	subs.local_pos_sub = orb_subscribe(ORB_ID(vehicle_local_position));
	fds[fdsc_count].fd = subs.local_pos_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- GLOBAL POSITION --- */
	/* subscribe to ORB for global position */
	subs.global_pos_sub = orb_subscribe(ORB_ID(vehicle_global_position));
	fds[fdsc_count].fd = subs.global_pos_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- VICON POSITION --- */
	/* subscribe to ORB for vicon position */
	subs.vicon_pos_sub = orb_subscribe(ORB_ID(vehicle_vicon_position));
	fds[fdsc_count].fd = subs.vicon_pos_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- FLOW measurements --- */
	/* subscribe to ORB for flow measurements */
	subs.flow_sub = orb_subscribe(ORB_ID(optical_flow));
	fds[fdsc_count].fd = subs.flow_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- BATTERY STATUS --- */
	/* subscribe to ORB for flow measurements */
	subs.batt_sub = orb_subscribe(ORB_ID(battery_status));
	fds[fdsc_count].fd = subs.batt_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- DIFFERENTIAL PRESSURE --- */
	/* subscribe to ORB for flow measurements */
	subs.diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));
	fds[fdsc_count].fd = subs.diff_pres_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;

	/* --- AIRSPEED --- */
	/* subscribe to ORB for airspeed */
	subs.airspeed_sub = orb_subscribe(ORB_ID(airspeed));
	fds[fdsc_count].fd = subs.airspeed_sub;
	fds[fdsc_count].events = POLLIN;
	fdsc_count++;	

	/* WARNING: If you get the error message below,
	 * then the number of registered messages (fdsc)
	 * differs from the number of messages in the above list.
	 */
	if (fdsc_count > fdsc) {
		warn("WARNING: Not enough space for poll fds allocated. Check %s:%d.\n", __FILE__, __LINE__);
		fdsc_count = fdsc;
	}

	/*
	 * set up poll to block for new data,
	 * wait for a maximum of 1000 ms (1 second)
	 */
	// const int timeout = 1000;

	thread_running = true;

	/* initialize log buffer with a size of 10 */
	sdlog_logbuffer_init(&lb, 10);

	/* initialize thread synchronization */
	pthread_mutex_init(&sysvector_mutex, NULL);
  	pthread_cond_init(&sysvector_cond, NULL);

	/* start logbuffer emptying thread */
	pthread_t sysvector_pthread = sysvector_write_start(&lb);

	starttime = hrt_absolute_time();

	/* track skipping */
	int skip_count = 0;

	while (!thread_should_exit) {

		/* only poll for commands, gps and sensor_combined */
		int poll_ret = poll(fds, 3, 1000);

		/* handle the poll result */
		if (poll_ret == 0) {
			/* XXX this means none of our providers is giving us data - might be an error? */
		} else if (poll_ret < 0) {
			/* XXX this is seriously bad - should be an emergency */
		} else {

			int ifds = 0;

			/* --- VEHICLE COMMAND VALUE --- */
			if (fds[ifds++].revents & POLLIN) {
				/* copy command into local buffer */
				orb_copy(ORB_ID(vehicle_command), subs.cmd_sub, &buf.cmd);

				/* always log to blackbox, even when logging disabled */
				blackbox_file_bytes += fprintf(blackbox_file, "[%10.4f\tVCMD] CMD #%d [%f\t%f\t%f\t%f\t%f\t%f\t%f]\n", hrt_absolute_time()/1000000.0d,
					buf.cmd.command, (double)buf.cmd.param1, (double)buf.cmd.param2, (double)buf.cmd.param3, (double)buf.cmd.param4,
					(double)buf.cmd.param5, (double)buf.cmd.param6, (double)buf.cmd.param7);

				handle_command(&buf.cmd);
			}

			/* --- VEHICLE GPS VALUE --- */
			if (fds[ifds++].revents & POLLIN) {
				/* copy gps position into local buffer */
				orb_copy(ORB_ID(vehicle_gps_position), subs.gps_pos_sub, &buf.gps_pos);

				/* if logging disabled, continue */
				if (logging_enabled) {

				/* write KML line */
				}
			}

			/* --- SENSORS RAW VALUE --- */
			if (fds[ifds++].revents & POLLIN) {

				// /* copy sensors raw data into local buffer */
				// orb_copy(ORB_ID(sensor_combined), subs.sensor_sub, &buf.raw);
				// /* write out */
				// sensor_combined_bytes += write(sensorfile, (const char*)&(buf.raw), sizeof(buf.raw));

				/* always copy sensors raw data into local buffer, since poll flags won't clear else */
				orb_copy(ORB_ID(sensor_combined), subs.sensor_sub, &buf.raw);
				orb_copy(ORB_ID_VEHICLE_ATTITUDE_CONTROLS, subs.controls_0_sub, &buf.act_controls);
				orb_copy(ORB_ID_VEHICLE_ATTITUDE_CONTROLS_EFFECTIVE, subs.controls_effective_0_sub, &buf.act_controls_effective);
				orb_copy(ORB_ID(actuator_outputs_0), subs.act_0_sub, &buf.act_outputs);
				orb_copy(ORB_ID(vehicle_attitude_setpoint), subs.spa_sub, &buf.att_sp);
				orb_copy(ORB_ID(vehicle_gps_position), subs.gps_pos_sub, &buf.gps_pos);
				orb_copy(ORB_ID(vehicle_local_position), subs.local_pos_sub, &buf.local_pos);
				orb_copy(ORB_ID(vehicle_global_position), subs.global_pos_sub, &buf.global_pos);
				orb_copy(ORB_ID(vehicle_attitude), subs.att_sub, &buf.att);
				orb_copy(ORB_ID(vehicle_vicon_position), subs.vicon_pos_sub, &buf.vicon_pos);
				orb_copy(ORB_ID(optical_flow), subs.flow_sub, &buf.flow);
				orb_copy(ORB_ID(differential_pressure), subs.diff_pres_sub, &buf.diff_pres);
				orb_copy(ORB_ID(airspeed), subs.airspeed_sub, &buf.airspeed);
				orb_copy(ORB_ID(battery_status), subs.batt_sub, &buf.batt);

				/* if skipping is on or logging is disabled, ignore */
				if (skip_count < skip_value || !logging_enabled) {
					skip_count++;
					/* do not log data */
					continue;
				} else {
					/* log data, reset */
					skip_count = 0;
				}

				struct sdlog_sysvector sysvect = {
					.timestamp = buf.raw.timestamp,
					.gyro = {buf.raw.gyro_rad_s[0], buf.raw.gyro_rad_s[1], buf.raw.gyro_rad_s[2]},
					.accel = {buf.raw.accelerometer_m_s2[0], buf.raw.accelerometer_m_s2[1], buf.raw.accelerometer_m_s2[2]},
					.mag = {buf.raw.magnetometer_ga[0], buf.raw.magnetometer_ga[1], buf.raw.magnetometer_ga[2]},
					.baro = buf.raw.baro_pres_mbar,
					.baro_alt = buf.raw.baro_alt_meter,
					.baro_temp = buf.raw.baro_temp_celcius,
					.control = {buf.act_controls.control[0], buf.act_controls.control[1], buf.act_controls.control[2], buf.act_controls.control[3]},
					.actuators = {
						buf.act_outputs.output[0], buf.act_outputs.output[1], buf.act_outputs.output[2], buf.act_outputs.output[3],
						buf.act_outputs.output[4], buf.act_outputs.output[5], buf.act_outputs.output[6], buf.act_outputs.output[7]
					},
					.vbat = buf.batt.voltage_v,
					.bat_current = buf.batt.current_a,
					.bat_discharged = buf.batt.discharged_mah,
					.adc = {buf.raw.adc_voltage_v[0], buf.raw.adc_voltage_v[1], buf.raw.adc_voltage_v[2], buf.raw.adc_voltage_v[3]},
					//.local_position = {buf.local_pos.x, buf.local_pos.y, buf.local_pos.z},
                    .local_position = {buf.att_sp.pitch_body, buf.att_sp.roll_body, buf.att_sp.yaw_body},
					.gps_raw_position = {buf.gps_pos.lat, buf.gps_pos.lon, buf.gps_pos.alt},
					.attitude = {buf.att.pitch, buf.att.roll, buf.att.yaw},
					.rotMatrix = {buf.att.R[0][0], buf.att.R[0][1], buf.att.R[0][2], buf.att.R[1][0], buf.att.R[1][1], buf.att.R[1][2], buf.att.R[2][0], buf.att.R[2][1], buf.att.R[2][2]},
					.vicon = {buf.vicon_pos.x, buf.vicon_pos.y, buf.vicon_pos.z, buf.vicon_pos.roll, buf.vicon_pos.pitch, buf.vicon_pos.yaw},
					.control_effective = {buf.act_controls_effective.control_effective[0], buf.act_controls_effective.control_effective[1], buf.act_controls_effective.control_effective[2], buf.act_controls_effective.control_effective[3]},
					.flow = {buf.flow.flow_raw_x, buf.flow.flow_raw_y, buf.flow.flow_comp_x_m, buf.flow.flow_comp_y_m, buf.flow.ground_distance_m, buf.flow.quality},
					.diff_pressure = buf.diff_pres.differential_pressure_pa,
					.ind_airspeed = buf.airspeed.indicated_airspeed_m_s,
					.true_airspeed = buf.airspeed.true_airspeed_m_s
				};

				/* put into buffer for later IO */
				pthread_mutex_lock(&sysvector_mutex);
				sdlog_logbuffer_write(&lb, &sysvect);
				/* signal the other thread new data, but not yet unlock */
				if ((unsigned)lb.count > (lb.size / 2)) {
					/* only request write if several packets can be written at once */
					pthread_cond_signal(&sysvector_cond);
				}
				/* unlock, now the writer thread may run */
				pthread_mutex_unlock(&sysvector_mutex);
			}

		}

	}

	print_sdlog_status();

	/* wake up write thread one last time */
	pthread_mutex_lock(&sysvector_mutex);
	pthread_cond_signal(&sysvector_cond);
	/* unlock, now the writer thread may return */
	pthread_mutex_unlock(&sysvector_mutex);

	/* wait for write thread to return */
	(void)pthread_join(sysvector_pthread, NULL);

  	pthread_mutex_destroy(&sysvector_mutex);
  	pthread_cond_destroy(&sysvector_cond);

	warnx("exiting.\n\n");

	/* finish KML file */
	// XXX
	fclose(gpsfile);
	fclose(blackbox_file);

	thread_running = false;

	return 0;
}
Example #28
0
int
exec_add(int argc, char **argv)
{
	struct pkgdb *db = NULL;
	struct sbuf *failedpkgs = NULL;
	char path[MAXPATHLEN + 1];
	char *file;
	int retcode = EPKG_OK;
	int i;
	int failedpkgcount = 0;
	struct pkg *p = NULL;

	if (argc < 2) {
		usage_add();
		return (EX_USAGE);
	}

	if (geteuid() != 0) {
		warnx("Adding packages can only be done as root");
		return (EX_NOPERM);
	}

	if (pkgdb_open(&db, PKGDB_DEFAULT) != EPKG_OK) {
		return (EX_IOERR);
	}

	failedpkgs = sbuf_new_auto();
	for (i = 1; i < argc; i++) {
		if (is_url(argv[i]) == EPKG_OK) {
			snprintf(path, sizeof(path), "./%s", basename(argv[i]));
			if ((retcode = pkg_fetch_file(argv[i], path, 0)) != EPKG_OK)
				break;

			file = path;
		} else {
			file = argv[i];
			if (access(file, F_OK) != 0) {
				warn("%s",file);
				if (errno == ENOENT)
					warnx("Did you mean 'pkg install %s'?", file);
				sbuf_cat(failedpkgs, argv[i]);
				if (i != argc - 1)
					sbuf_printf(failedpkgs, ", ");
				failedpkgcount++;
				continue;
			}

		}
			
		pkg_open(&p, file);

		if ((retcode = pkg_add(db, file, 0)) != EPKG_OK) {
			sbuf_cat(failedpkgs, argv[i]);
			if (i != argc - 1)
				sbuf_printf(failedpkgs, ", ");
			failedpkgcount++;
		}

	}

	pkgdb_close(db);
	
	if(failedpkgcount > 0) {
		sbuf_finish(failedpkgs);
		printf("\nFailed to install the following %d package(s): %s\n", failedpkgcount, sbuf_data(failedpkgs));
	}
	sbuf_delete(failedpkgs);

	if (messages != NULL) {
		sbuf_finish(messages);
		printf("%s", sbuf_data(messages));
	}

	return (retcode == EPKG_OK ? EX_OK : EX_SOFTWARE);
}
void do_accel_calibration(int status_pub, struct vehicle_status_s *status, int mavlink_fd) {
	/* announce change */
	mavlink_log_info(mavlink_fd, "accel calibration started");
	/* set to accel calibration mode */
	status->flag_preflight_accel_calibration = true;
	state_machine_publish(status_pub, status, mavlink_fd);

	/* measure and calculate offsets & scales */
	float accel_offs[3];
	float accel_scale[3];
	int res = do_accel_calibration_mesurements(mavlink_fd, accel_offs, accel_scale);

	if (res == OK) {
		/* measurements complete successfully, set parameters */
		if (param_set(param_find("SENS_ACC_XOFF"), &(accel_offs[0]))
			|| param_set(param_find("SENS_ACC_YOFF"), &(accel_offs[1]))
			|| param_set(param_find("SENS_ACC_ZOFF"), &(accel_offs[2]))
			|| param_set(param_find("SENS_ACC_XSCALE"), &(accel_scale[0]))
			|| param_set(param_find("SENS_ACC_YSCALE"), &(accel_scale[1]))
			|| param_set(param_find("SENS_ACC_ZSCALE"), &(accel_scale[2]))) {
			mavlink_log_critical(mavlink_fd, "ERROR: setting offs or scale failed");
		}

		int fd = open(ACCEL_DEVICE_PATH, 0);
		struct accel_scale ascale = {
			accel_offs[0],
			accel_scale[0],
			accel_offs[1],
			accel_scale[1],
			accel_offs[2],
			accel_scale[2],
		};

		if (OK != ioctl(fd, ACCELIOCSSCALE, (long unsigned int)&ascale))
			warn("WARNING: failed to set scale / offsets for accel");

		close(fd);

		/* auto-save to EEPROM */
		int save_ret = param_save_default();

		if (save_ret != 0) {
			warn("WARNING: auto-save of params to storage failed");
		}

		mavlink_log_info(mavlink_fd, "accel calibration done");
		tune_confirm();
		sleep(2);
		tune_confirm();
		sleep(2);
		/* third beep by cal end routine */
	} else {
		/* measurements error */
		mavlink_log_info(mavlink_fd, "accel calibration aborted");
		tune_error();
		sleep(2);
	}

	/* exit accel calibration mode */
	status->flag_preflight_accel_calibration = false;
	state_machine_publish(status_pub, status, mavlink_fd);
}
Example #30
0
void *
AbstractMenu_new_menu( Handle self, SV * sv, int level)
{
	AV * av;
	int i, count;
	int n;
	PMenuItemReg m    = nil;
	PMenuItemReg curr = nil;
	Bool rightAdjust = false;

	if ( level == 0)
	{
		if ( SvTYPE( sv) == SVt_NULL) return nil; /* null menu */
	}

	if ( !SvROK( sv) || ( SvTYPE( SvRV( sv)) != SVt_PVAV)) {
		warn("menu build error: menu is not an array");
		return nil;
	}
	av = (AV *) SvRV( sv);
	n = av_len( av);
	
	if ( n == -1) {
		if ( level == 0) return nil; /* null menu */
		warn("menu build error: empty array passed");
		return nil;
	}

	/* cycling the list of items */
	for ( i = 0; i <= n; i++)
	{
		SV **itemHolder = av_fetch( av, i, 0);
		AV *item;
		SV *subItem;
		PMenuItemReg r;
		SV **holder;

		int l_var   = -1;
		int l_text  = -1;
		int l_sub   = -1;
		int l_accel = -1;
		int l_key   = -1;
		int l_data  = -1;

		if ( itemHolder == nil)
		{
			warn("menu build error: array panic");
			my-> dispose_menu( self, m);
			return nil;
		}
		if ( !SvROK( *itemHolder) || ( SvTYPE( SvRV( *itemHolder)) != SVt_PVAV)) {
			warn("menu build error: submenu is not an array");
			my-> dispose_menu( self, m);
			return nil;
		}
		/* entering item description */
		item = ( AV *) SvRV( *itemHolder);
		count = av_len( item) + 1;
		if ( count > 6) {
			warn("menu build error: extra declaration");
			count = 5;
		}
		if ( !( r = alloc1z( MenuItemReg))) {
			warn( "Not enough memory");
			my-> dispose_menu( self, m);
			return nil;
		}
		r-> key = kbNoKey;

		if ( count < 2) {          /* empty or 1 means line divisor, no matter of text */
			r-> flags. divider = true;
			rightAdjust = (( level == 0) && ( var-> anchored));
			if ( count == 1) l_var = 0;
		} else if ( count == 2) {
			l_text = 0;
			l_sub  = 1;
		} else if ( count == 3) {
			l_var  = 0;
			l_text = 1;
			l_sub  = 2;
		} else if ( count == 4) {
			l_text  = 0;
			l_accel = 1;
			l_key   = 2;
			l_sub   = 3;
		} else if ( count == 5) {
			l_var   = 0;
			l_text  = 1;
			l_accel = 2;
			l_key   = 3;
			l_sub   = 4;
		} else {
			l_var   = 0;
			l_text  = 1;
			l_accel = 2;
			l_key   = 3;
			l_sub   = 4;
			l_data  = 5;
		}

		if ( m) curr = curr-> next = r; else curr = m = r; /* adding to list */

		r-> flags. rightAdjust = rightAdjust ? 1 : 0;
		r-> id = ++(var-> autoEnum);

#define a_get( l_, fl_, num) \
	if ( num >= 0 ) {                                                     \
		holder = av_fetch( item, num, 0);                             \
		if ( holder) {                                                \
			if ( SvTYPE(*holder) != SVt_NULL) {                   \
				l_ = duplicate_string( SvPV_nolen( *holder)); \
				fl_ = prima_is_utf8_sv(*holder);              \
			}                                                     \
		} else {                                                      \
			warn("menu build error: array panic");                \
			my-> dispose_menu( self, m);                          \
			return nil;                                           \
		}                                                             \
	}
		a_get( r-> accel   , r-> flags. utf8_accel,    l_accel);
		a_get( r-> variable, r-> flags. utf8_variable, l_var);
		if ( l_key >= 0) {
			holder = av_fetch( item, l_key, 0);
			if ( !holder) {
				warn("menu build error: array panic");
				my-> dispose_menu( self, m);
				return nil;
			}
			r-> key = key_normalize( SvPV_nolen( *holder));
		}

		if ( r-> variable)
		{
			#define s r-> variable
			int i, decr = 0;
			for ( i = 0; i < 2; i++) {
				switch ( s[i]) {
				case '-':
					r-> flags. disabled = 1;
					decr++;
					break;
				case '*':
					r-> flags. checked = 1;
					decr++;
					break;
				case '@':
					if ( r-> flags. divider )
						warn("warning: auto-toggle flag @ ignored on a divider menu");
					else
						r-> flags. autotoggle = 1;
					decr++;
					break;
				default:
					break;
				}
			}
			if ( decr) memmove( s, s + decr, strlen( s) + 1 - decr);
			if ( strlen( s) == 0 || is_var_id_name( s) != 0) {
				free( r-> variable);
				r-> variable = nil;
			}
			#undef s
		}

		/* parsing text */
		if ( l_text >= 0)
		{
			holder = av_fetch( item, l_text, 0);
			if ( !holder) {
				warn("menu build error: array panic");
				my-> dispose_menu( self, m);
				return nil;
			}
			subItem = *holder;

			if ( SvROK( subItem)) {
				Handle c_object = gimme_the_mate( subItem);
				if (( c_object == nilHandle) || !( kind_of( c_object, CImage)))
				{
					warn("menu build error: not an image passed");
					goto TEXT;
				}
				if (((( PImage) c_object)-> w == 0)
					|| ((( PImage) c_object)-> h == 0))
				{
					warn("menu build error: invalid image passed");
					goto TEXT;
				}
				protect_object( r-> bitmap = c_object);
				SvREFCNT_inc( SvRV(( PObject( r-> bitmap))-> mate));
			} else {
			TEXT:
				r-> text = duplicate_string( SvPV_nolen( subItem));
				r-> flags. utf8_text = prima_is_utf8_sv( subItem);
			}
		}

		/* parsing sub */
		if ( l_sub >= 0)
		{
			holder = av_fetch( item, l_sub, 0);
			if ( !holder) {
				warn("menu build error: array panic");
				my-> dispose_menu( self, m);
				return nil;
			}
			subItem = *holder;

			if ( SvROK( subItem))
			{
				if ( SvTYPE( SvRV( subItem)) == SVt_PVCV)
				{
					r-> code = newSVsv( subItem);
				} else {
					r-> down = ( PMenuItemReg) my-> new_menu( self, subItem, level + 1);
					if ( r-> down == nil)
					{
						/* seems error was occured inside this call */
						my-> dispose_menu( self, m);
						return nil;
					}
				}
			} else {
				if ( SvPOK( subItem)) {
					r-> perlSub = duplicate_string( SvPV_nolen( subItem));
					r-> flags. utf8_perlSub = prima_is_utf8_sv( subItem);
				} else {
					warn("menu build error: invalid sub name passed");
				}
			}
		}

		/* parsing data */
		if ( l_data >= 0)
		{
			holder = av_fetch( item, l_data, 0);
			if ( !holder) {
				warn("menu build error: array panic");
				my-> dispose_menu( self, m);
				return nil;
			}
			r-> data = newSVsv( *holder);
		}
	}
	return m;
}