Beispiel #1
0
int Tdi1GetDbi(int opcode, int narg, struct descriptor *list[],
               struct descriptor_xd *out_ptr)
{
    int status = 1;
    struct descriptor_d string = { 0, DTYPE_T, CLASS_D, 0 };
    struct descriptor_xd tmp = EMPTY_XD;
    struct item *key_ptr = 0;
    int index;
    DBI_ITM lst[] = { {sizeof(index), DbiINDEX, 0, 0}
    , EOL, EOL };
    lst[0].pointer = (unsigned char *)&index;
        /**********************
        String of item to find.
        **********************/
    status = TdiData(list[0], &tmp MDS_END_ARG);
    if (status & 1)
        status = TdiUpcase(&tmp, &string MDS_END_ARG);
    if (status & 1) {
        key_ptr =
            (struct item *)bsearch(&string, table, numtab, siztab,
                                   (int (*)(const void *, const void *))
                                   compare);
        if (key_ptr == 0)
            status = TdiBAD_INDEX;
    }
    StrFree1Dx(&string);
    MdsFree1Dx(&tmp, NULL);
        /**********************************
        Somebody might want others in pool.
        **********************************/
    if (status & 1 && narg > 1)
        status = TdiGetLong(list[1], &index);
    else
        index = 0;
        /***********************
        Get the item asked for.
        Fixed length or varying.
        ***********************/
    if (status & 1) {
        lst[1].code = key_ptr->item_code;
        if ((lst[1].buffer_length = key_ptr->item_length) != 0) {
            status =
                MdsGet1DxS((unsigned short *)&lst[1].buffer_length,
                           &key_ptr->item_dtype, out_ptr);
            if (status & 1) {
                lst[1].pointer = (unsigned char *)out_ptr->pointer->pointer;
                status = TreeGetDbi(lst);
            }
        } else {
            lst[1].buffer_length = 0;
            lst[1].pointer = NULL;
            status = TreeGetDbi(lst);
            if (status & 1) {
                struct descriptor ans = { 0, DTYPE_T, CLASS_S, 0 };
                if (lst[1].pointer) {
                    ans.length = strlen((char *)lst[1].pointer);
                    ans.pointer = (char *)lst[1].pointer;
                }
                status = MdsCopyDxXd(&ans, out_ptr);
                if (ans.pointer)
                    TreeFree(ans.pointer);
            }
        }
    }
    return status;
}
Beispiel #2
0
	const char *name;
	void	(*proc)();
};

static const struct pspgl_proc proctable[] = {
#include "pspgl_proctable.h"
};
#define NPROC	(sizeof(proctable)/sizeof(proctable[0]))

static int cmp_procname(const void *a, const void *b)
{
	const char *name = a;
	const struct pspgl_proc *entry = b;

	return strcmp(name, entry->name);
}

GLAPI void (* APIENTRY eglGetProcAddress (const char *procname))()
{
	struct pspgl_proc *entry;

	entry = bsearch(procname, proctable, NPROC, sizeof(struct pspgl_proc),
			cmp_procname);

	if (entry != NULL)
		return entry->proc;

	return NULL;
}

Beispiel #3
0
static void
pax_options(int argc, char **argv)
{
	int c;
	size_t i;
	unsigned int flg = 0;
	unsigned int bflg = 0;
	char *pt;
	FSUB tmp;

	/*
	 * process option flags
	 */
	while ((c=getopt(argc,argv,"ab:cdf:iklno:p:rs:tuvwx:zB:DE:G:HLPT:U:XYZ"))
	    != -1) {
		switch (c) {
		case 'a':
			/*
			 * append
			 */
			flg |= AF;
			break;
		case 'b':
			/*
			 * specify blocksize
			 */
			flg |= BF;
			if ((wrblksz = (int)str_offt(optarg)) <= 0) {
				paxwarn(1, "Invalid block size %s", optarg);
				pax_usage();
			}
			break;
		case 'c':
			/*
			 * inverse match on patterns
			 */
			cflag = 1;
			flg |= CF;
			break;
		case 'd':
			/*
			 * match only dir on extract, not the subtree at dir
			 */
			dflag = 1;
			flg |= DF;
			break;
		case 'f':
			/*
			 * filename where the archive is stored
			 */
			arcname = optarg;
			flg |= FF;
			break;
		case 'i':
			/*
			 * interactive file rename
			 */
			iflag = 1;
			flg |= IF;
			break;
		case 'k':
			/*
			 * do not clobber files that exist
			 */
			kflag = 1;
			flg |= KF;
			break;
		case 'l':
			/*
			 * try to link src to dest with copy (-rw)
			 */
			lflag = 1;
			flg |= LF;
			break;
		case 'n':
			/*
			 * select first match for a pattern only
			 */
			nflag = 1;
			flg |= NF;
			break;
		case 'o':
			/*
			 * pass format specific options
			 */
			flg |= OF;
			if (opt_add(optarg) < 0)
				pax_usage();
			break;
		case 'p':
			/*
			 * specify file characteristic options
			 */
			for (pt = optarg; *pt != '\0'; ++pt) {
				switch(*pt) {
				case 'a':
					/*
					 * do not preserve access time
					 */
					patime = 0;
					break;
				case 'e':
					/*
					 * preserve user id, group id, file
					 * mode, access/modification times
					 */
					pids = 1;
					pmode = 1;
					patime = 1;
					pmtime = 1;
					break;
				case 'm':
					/*
					 * do not preserve modification time
					 */
					pmtime = 0;
					break;
				case 'o':
					/*
					 * preserve uid/gid
					 */
					pids = 1;
					break;
				case 'p':
					/*
					 * preserver file mode bits
					 */
					pmode = 1;
					break;
				default:
					paxwarn(1, "Invalid -p string: %c", *pt);
					pax_usage();
					break;
				}
			}
			flg |= PF;
			break;
		case 'r':
			/*
			 * read the archive
			 */
			flg |= RF;
			break;
		case 's':
			/*
			 * file name substitution name pattern
			 */
			if (rep_add(optarg) < 0) {
				pax_usage();
				break;
			}
			flg |= SF;
			break;
		case 't':
			/*
			 * preserve access time on file system nodes we read
			 */
			tflag = 1;
			flg |= TF;
			break;
		case 'u':
			/*
			 * ignore those older files
			 */
			uflag = 1;
			flg |= UF;
			break;
		case 'v':
			/*
			 * verbose operation mode
			 */
			vflag = 1;
			flg |= VF;
			break;
		case 'w':
			/*
			 * write an archive
			 */
			flg |= WF;
			break;
		case 'x':
			/*
			 * specify an archive format on write
			 */
			tmp.name = optarg;
			if ((frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
			    sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt)) != NULL) {
				flg |= XF;
				break;
			}
			paxwarn(1, "Unknown -x format: %s", optarg);
			(void)fputs("pax: Known -x formats are:", stderr);
			for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
				(void)fprintf(stderr, " %s", fsub[i].name);
			(void)fputs("\n\n", stderr);
			pax_usage();
			break;
		case 'z':
			/*
			 * use gzip.  Non standard option.
			 */
			gzip_program = GZIP_CMD;
			break;
		case 'B':
			/*
			 * non-standard option on number of bytes written on a
			 * single archive volume.
			 */
			if ((wrlimit = str_offt(optarg)) <= 0) {
				paxwarn(1, "Invalid write limit %s", optarg);
				pax_usage();
			}
			if (wrlimit % BLKMULT) {
				paxwarn(1, "Write limit is not a %d byte multiple",
				    BLKMULT);
				pax_usage();
			}
			flg |= CBF;
			break;
		case 'D':
			/*
			 * On extraction check file inode change time before the
			 * modification of the file name. Non standard option.
			 */
			Dflag = 1;
			flg |= CDF;
			break;
		case 'E':
			/*
			 * non-standard limit on read faults
			 * 0 indicates stop after first error, values
			 * indicate a limit, "NONE" try forever
			 */
			flg |= CEF;
			if (strcmp(NONE, optarg) == 0)
				maxflt = -1;
			else if ((maxflt = atoi(optarg)) < 0) {
				paxwarn(1, "Error count value must be positive");
				pax_usage();
			}
			break;
		case 'G':
			/*
			 * non-standard option for selecting files within an
			 * archive by group (gid or name)
			 */
			if (grp_add(optarg) < 0) {
				pax_usage();
				break;
			}
			flg |= CGF;
			break;
		case 'H':
			/*
			 * follow command line symlinks only
			 */
			Hflag = 1;
			flg |= CHF;
			break;
		case 'L':
			/*
			 * follow symlinks
			 */
			Lflag = 1;
			flg |= CLF;
			break;
		case 'P':
			/*
			 * do NOT follow symlinks (default)
			 */
			Lflag = 0;
			flg |= CPF;
			break;
		case 'T':
			/*
			 * non-standard option for selecting files within an
			 * archive by modification time range (lower,upper)
			 */
			if (trng_add(optarg) < 0) {
				pax_usage();
				break;
			}
			flg |= CTF;
			break;
		case 'U':
			/*
			 * non-standard option for selecting files within an
			 * archive by user (uid or name)
			 */
			if (usr_add(optarg) < 0) {
				pax_usage();
				break;
			}
			flg |= CUF;
			break;
		case 'X':
			/*
			 * do not pass over mount points in the file system
			 */
			Xflag = 1;
			flg |= CXF;
			break;
		case 'Y':
			/*
			 * On extraction check file inode change time after the
			 * modification of the file name. Non standard option.
			 */
			Yflag = 1;
			flg |= CYF;
			break;
		case 'Z':
			/*
			 * On extraction check modification time after the
			 * modification of the file name. Non standard option.
			 */
			Zflag = 1;
			flg |= CZF;
			break;
		default:
			pax_usage();
			break;
		}
	}

	/*
	 * figure out the operation mode of pax read,write,extract,copy,append
	 * or list. check that we have not been given a bogus set of flags
	 * for the operation mode.
	 */
	if (ISLIST(flg)) {
		act = LIST;
		listf = stdout;
		bflg = flg & BDLIST;
	} else if (ISEXTRACT(flg)) {
		act = EXTRACT;
		bflg = flg & BDEXTR;
	} else if (ISARCHIVE(flg)) {
		act = ARCHIVE;
		bflg = flg & BDARCH;
	} else if (ISAPPND(flg)) {
		act = APPND;
		bflg = flg & BDARCH;
	} else if (ISCOPY(flg)) {
		act = COPY;
		bflg = flg & BDCOPY;
	} else
		pax_usage();
	if (bflg) {
		printflg(flg);
		pax_usage();
	}

	/*
	 * if we are writing (ARCHIVE) we use the default format if the user
	 * did not specify a format. when we write during an APPEND, we will
	 * adopt the format of the existing archive if none was supplied.
	 */
	if (!(flg & XF) && (act == ARCHIVE))
		frmt = &(fsub[DEFLT]);

	/*
	 * process the args as they are interpreted by the operation mode
	 */
	switch (act) {
	case LIST:
	case EXTRACT:
		for (; optind < argc; optind++)
			if (pat_add(argv[optind], NULL) < 0)
				pax_usage();
		break;
	case COPY:
		if (optind >= argc) {
			paxwarn(0, "Destination directory was not supplied");
			pax_usage();
		}
		--argc;
		dirptr = argv[argc];
		/* FALLTHROUGH */
	case ARCHIVE:
	case APPND:
		for (; optind < argc; optind++)
			if (ftree_add(argv[optind], 0) < 0)
				pax_usage();
		/*
		 * no read errors allowed on updates/append operation!
		 */
		maxflt = 0;
		break;
	}
}
Beispiel #4
0
static void populateVars(Context ctx,const char *key,void *value,int type,int elems){
    int ret,ncgid,cnt;
    DimRef dr;
    double *pdDepth=NULL;
    char *pstrSource=NULL;
    size_t dep,*basei=NULL,*endi=NULL;
    size_t i=0;
    if(ctx.ncid<=0)return;
    if(type==LUA_TTABLE){//any other type at this level will be disgarded
	if(NC_NOERR!=(ret=nc_def_grp(ctx.ncid,key,&ncgid)))
	    nc_error(ret,__LINE__);
	ctx.ncid=ncgid;
	ctx.pfunCallback=populateAttrs;
	loopTable(&ctx,NULL,0);
	if(NC_NOERR!=(ret=nc_def_dim(ctx.ncid,VAR_FEATURE_TYPE_INSTANCE,1,&(dr.dim1[0]))))
	    nc_error(ret,__LINE__);
	if(NC_NOERR!=(ret=nc_def_dim(ctx.ncid,VAR_TIME,NC_UNLIMITED,&(dr.dim2[1]))))
	    nc_error(ret,__LINE__);
	pdDepth=(double*)queryTableValue(ctx.L,LUA_VARS_ROOT,VAR_Z,DEPTH_LEVEL);
	if(pdDepth){
	    dep=(size_t)*pdDepth;
            if(NC_NOERR!=(ret=nc_def_dim(ctx.ncid,VAR_Z,dep,&(dr.dim3[2]))))
	        nc_error(ret,__LINE__);
	    free(pdDepth);
	}
	dr.dim2[0]=dr.dim3[0]=dr.dim1[0];
	dr.dim1t[0]=dr.dim3[1]=dr.dim2[1];
	dr.dim1z[0]=dr.dim3[2];
	ctx.pfunCallback=defineVars;
	ctx.param=(void*)&dr;
	loopTable(&ctx,LUA_VARS_ROOT,0);
	pstrSource=(char*)queryTableValue(ctx.L,LUA_VARS_ROOT,NULL,DATA_SOURCE);
	if(pstrSource&&dep>0){
	    pdDepth=(double*)queryTableValue(ctx.L,LUA_VARS_ROOT,VAR_META,OBS_COUNT);
	    if(dep>1){
		basei=(size_t*)queryTableValue(ctx.L,LUA_VARS_ROOT,VAR_META,TS_MIN);
		endi=(size_t*)queryTableValue(ctx.L,LUA_VARS_ROOT,VAR_META,TS_MAX);
	    }
	    if(pdDepth){//dpDepth represents tscount here
		cnt=(int)(*pdDepth)*dep;
		free(pdDepth);
		ctx.obs=(double*)malloc(sizeof(double)*cnt);
		ctx.time=(double*)malloc(sizeof(double)*cnt);
		FILE *f=fopen(pstrSource,"r");
    		if(f){
		    double f1,f2,f3;
		    int ret=2;
		    if(1==dep){
		        while(!feof(f)&&ret==2&&cnt--){
			    ret=fscanf(f,"%lf,%lf",&f1,&f2);
	    		    ctx.time[i]=f1;
			    ctx.obs[i++]=f2;
			}
		    }else{
			if(basei&&endi&&*endi>=*basei){
			    double *pdKey=(double*)malloc(sizeof(double)*(*pdDepth));
			    ctx.height=(double*)malloc(sizeof(double)*cnt);
			    if(populateArray(ctx.L,VAR_Z,DEPTHS,LUA_TNUMBER,ctx.height,cnt)){
				qsort(ctx.height,dep,sizeof(double),compareDoubles);
				for(;i<cnt;++i)
				    *(ctx.obs+i)=ctx.missingval;
			        while(!feof(f)&&ret==2&&cnt--){
			            ret=fscanf(f,"%lf,%lf,%lf",&f1,&f2,&f3);
				    bsearch(f3,ctx.height,dep,sizeof(double),compareDoubles);
	    		            ctx.time[i]=f1;
			            ctx.obs[i++]=f2;
			        }
			    }
			    else{
				free(ctx.height,dep,sizeof(double),);
			  	ctx.height=NULL;
			    }
			    if(pdKey)free(pdKey);
			}
			else{
			    free(ctx.obs);
			    free(ctx.time);
			    ctx.obs=ctx.time=NULL;
			}
			
		    }
		    fclose(f);
		    ctx.pfunCallback=putVars;
		    ctx.len=i;
	            loopTable(&ctx,LUA_VARS_ROOT,0);
    		}
		if(basei)free(basei);
		if(endi)free(endi);
		if(ctx.height)free(ctx.height);
		if(ctx.time)free(ctx.time);
		if(ctx.obs)free(ctx.obs);
		free(pstrSource);
	    }
Beispiel #5
0
/*! The 'append' mode for this function is special. Yes, it adds 
	new data to the file, but it also <i>replaces</i> old data of 
	the same name. Yes, this is proper procedure and should happen 
	in the others as well, but it's just easier in a binary 
	environment. The header file will still have double definitions,
	though.
	\todo	Code is inconsistent with the C/asm exporters. Rectify.
*/
bool grit_xp_gbfs(GritRec *gr)
{
	int ii, jj;

	// for new data
	int gr_count;
	BYTE *gr_data[4];
	GBFS_ENTRY gr_gben[4];

	// for total data
	int gb_count;
	GBFS_ENTRY *gbenL= gr_gben, *gbenD= NULL;

	ii= 0;

	// --- register the various fields ---

	// Graphics
	if(gr->gfxProcMode == GRIT_EXPORT)
	{
		grit_gbfs_entry_init(&gr_gben[ii], &gr->_gfxRec, 
			gr->symName, (gr->isTiled() ? E_AFX_TILE : E_AFX_BMP));
		gr_data[ii++]= gr->_gfxRec.data;
	}

	// Map
	if(gr->mapProcMode == GRIT_EXPORT)
	{
		grit_gbfs_entry_init(&gr_gben[ii], &gr->_mapRec, 
			gr->symName, (gr->isMetaTiled() ? E_AFX_MTILE :E_AFX_MAP));
		gr_data[ii++]= gr->_mapRec.data;

		// Meta map
		if(gr->isMetaTiled())
		{
			grit_gbfs_entry_init(&gr_gben[ii], &gr->_metaRec, 
				gr->symName, E_AFX_MMAP);
			gr_data[ii++]= gr->_metaRec.data;
		}
	}

	// Palette
	if(gr->palProcMode == GRIT_EXPORT)
	{
		grit_gbfs_entry_init(&gr_gben[ii], &gr->_palRec, 
			gr->symName, E_AFX_PAL);
		gr_data[ii++]= gr->_palRec.data;
	}

	gb_count= gr_count= ii;

	// --- create header and finish entries ---
	// Create basic header
	GBFS_FILE gbhdr;
	memcpy(gbhdr.magic, GBFS_magic, sizeof(GBFS_magic));
	gbhdr.dir_off= GBFL_SIZE;

	char name[MAXPATHLEN];
	strcpy(name, gr->dstPath);
	path_fix_sep(name);

	lprintf(LOG_STATUS, "Export to GBFS: %s into %s .\n", 
		gr->symName, name);


	FILE *fout= fopen("gbfs.tmp", "wb");
	if(fout == NULL)
		return false;

	u32 fpos= GBFL_SIZE + gr_count*GBEN_SIZE;
	fseek(fout, fpos, SEEK_SET);	// skip directory

	// Insert mode
	// Replace old with same name; insert new
	if(gr->bAppend)
	{
		FILE *fin= fopen(name, "rb");
		do
		{
			if(fin == NULL)
				break;

			GBFS_FILE oldhdr;
			// read and check file's header
			if(fread(&oldhdr, GBFL_SIZE, 1, fin) < 1)
			{	break;	}
			if(memcmp(oldhdr.magic, GBFS_magic, 16))
				break;

			// if we're here, we have a valid GBFS

			int old_count= oldhdr.dir_nmemb;
			gbenD= (GBFS_ENTRY*)malloc(old_count*GBEN_SIZE);
			if(gbenD==NULL)
				break;

			// Read directory
			fread(gbenD, GBEN_SIZE, old_count, fin);
			// check for obsoletes
			for(ii=0; ii<gr_count; ii++)
			{
				gbenL= (GBFS_ENTRY*)bsearch(&gr_gben[ii], gbenD, 
					old_count, GBEN_SIZE, gbfs_namecmp);
				if(gbenL == NULL)
					continue;
				// Obsolete found; remove from list;
				jj= (gbenL-gbenD);
				old_count--;
				memmove(gbenL, gbenL+1, (old_count-jj)*GBEN_SIZE);
			}
			// NOTE: old_count may have been modified
			gb_count= gr_count+old_count;

			// obsoletes are removed; write the rest to fout
			BYTE buf[1024];
			fpos= GBFL_SIZE + gb_count*GBEN_SIZE;
			fseek(fout, fpos, SEEK_SET);

			for(ii=0; ii<old_count; ii++)
			{
				fseek(fin, gbenD[ii].data_offset, SEEK_SET);
				gbenD[ii].data_offset= fpos;
				
				jj= gbenD[ii].len >> 10;
				while(jj--)
				{
					fread(buf, 1024, 1, fin);
					fwrite(buf, 1024, 1, fout);
				}
				if((jj= gbenD[ii].len & 1023) != 0)
				{
					fread(buf, jj, 1, fin);
					fwrite(buf, jj, 1, fout);
				}

				// pad to 16byte boundary
				for(fpos=ftell(fout); fpos & 0x0F; fpos++)
					fputc(0, fout);
			}

			// Combine lists
			gbenL= (GBFS_ENTRY*)malloc(gb_count*GBEN_SIZE);
			memcpy(gbenL, gr_gben, gr_count*GBEN_SIZE);
			memcpy(&gbenL[gr_count], gbenD, old_count*GBEN_SIZE);
			free(gbenD);
			gbenD= gbenL;
		} while(0);

		if(fin)
			fclose(fin);
	}
Beispiel #6
0
void *
parray_bsearch(parray *array, const void *key, int(*compare)(const void *, const void *))
{
    return bsearch(&key, array->data, array->used, sizeof(void *), compare);
}
Beispiel #7
0
asn_enc_rval_t
NativeEnumerated_encode_uper(asn_TYPE_descriptor_t *td,
	asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) {
	asn_INTEGER_specifics_t *specs = (asn_INTEGER_specifics_t *)td->specifics;
	asn_enc_rval_t er;
	long native, value;
	asn_per_constraint_t *ct;
	int inext = 0;
	asn_INTEGER_enum_map_t key;
	asn_INTEGER_enum_map_t *kf;

	if(!sptr) _ASN_ENCODE_FAILED;
	if(!specs) _ASN_ENCODE_FAILED;

	if(constraints) ct = &constraints->value;
	else if(td->per_constraints) ct = &td->per_constraints->value;
	else _ASN_ENCODE_FAILED;	/* Mandatory! */

	ASN_DEBUG("Encoding %s as NativeEnumerated", td->name);

	er.encoded = 0;

	native = *(long *)sptr;
	if(native < 0) _ASN_ENCODE_FAILED;

	key.nat_value = native;
	kf = bsearch(&key, specs->value2enum, specs->map_count,
		sizeof(key), NativeEnumerated__compar_value2enum);
	if(!kf) {
		ASN_DEBUG("No element corresponds to %ld", native);
		_ASN_ENCODE_FAILED;
	}
	value = kf - specs->value2enum;

	if(ct->range_bits >= 0) {
		int cmpWith = specs->extension
				? specs->extension - 1 : specs->map_count;
		if(value >= cmpWith)
			inext = 1;
	}
	if(ct->flags & APC_EXTENSIBLE) {
		if(per_put_few_bits(po, inext, 0))
			_ASN_ENCODE_FAILED;
		ct = 0;
	} else if(inext) {
		_ASN_ENCODE_FAILED;
	}

	if(ct && ct->range_bits >= 0) {
		if(per_put_few_bits(po, value, ct->range_bits))
			_ASN_ENCODE_FAILED;
		_ASN_ENCODED_OK(er);
	}

	if(!specs->extension)
		_ASN_ENCODE_FAILED;

	/*
	 * X.691, #10.6: normally small non-negative whole number;
	 */
	if(uper_put_nsnnwn(po, value - (specs->extension - 1)))
		_ASN_ENCODE_FAILED;

	_ASN_ENCODED_OK(er);
}
Beispiel #8
0
/* Execute escape sequence. */
int
input_esc_dispatch(struct input_ctx *ictx)
{
	struct screen_write_ctx		*sctx = &ictx->ctx;
	struct screen			*s = sctx->s;
	struct input_table_entry	*entry;

	if (ictx->flags & INPUT_DISCARD)
		return (0);
	log_debug("%s: '%c', %s", __func__, ictx->ch, ictx->interm_buf);

	entry = bsearch(ictx, input_esc_table, nitems(input_esc_table),
	    sizeof input_esc_table[0], input_table_compare);
	if (entry == NULL) {
		log_debug("%s: unknown '%c'", __func__, ictx->ch);
		return (0);
	}

	switch (entry->type) {
	case INPUT_ESC_RIS:
		input_reset_cell(ictx);
		screen_write_reset(sctx);
		break;
	case INPUT_ESC_IND:
		screen_write_linefeed(sctx, 0);
		break;
	case INPUT_ESC_NEL:
		screen_write_carriagereturn(sctx);
		screen_write_linefeed(sctx, 0);
		break;
	case INPUT_ESC_HTS:
		if (s->cx < screen_size_x(s))
			bit_set(s->tabs, s->cx);
		break;
	case INPUT_ESC_RI:
		screen_write_reverseindex(sctx);
		break;
	case INPUT_ESC_DECKPAM:
		screen_write_mode_set(sctx, MODE_KKEYPAD);
		break;
	case INPUT_ESC_DECKPNM:
		screen_write_mode_clear(sctx, MODE_KKEYPAD);
		break;
	case INPUT_ESC_DECSC:
		memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell);
		ictx->old_cx = s->cx;
		ictx->old_cy = s->cy;
		break;
	case INPUT_ESC_DECRC:
		memcpy(&ictx->cell, &ictx->old_cell, sizeof ictx->cell);
		screen_write_cursormove(sctx, ictx->old_cx, ictx->old_cy);
		break;
	case INPUT_ESC_DECALN:
		screen_write_alignmenttest(sctx);
		break;
	case INPUT_ESC_SCSG0_ON:
		ictx->cell.g0set = 1;
		break;
	case INPUT_ESC_SCSG0_OFF:
		ictx->cell.g0set = 0;
		break;
	case INPUT_ESC_SCSG1_ON:
		ictx->cell.g1set = 1;
		break;
	case INPUT_ESC_SCSG1_OFF:
		ictx->cell.g1set = 0;
		break;
	}

	return (0);
}
Beispiel #9
0
/* Execute control sequence. */
int
input_csi_dispatch(struct input_ctx *ictx)
{
	struct screen_write_ctx	       *sctx = &ictx->ctx;
	struct screen		       *s = sctx->s;
	struct input_table_entry       *entry;
	int				n, m;
	u_int				cx;

	if (ictx->flags & INPUT_DISCARD)
		return (0);
	if (input_split(ictx) != 0)
		return (0);
	log_debug("%s: '%c' \"%s\" \"%s\"",
	    __func__, ictx->ch, ictx->interm_buf, ictx->param_buf);

	entry = bsearch(ictx, input_csi_table, nitems(input_csi_table),
	    sizeof input_csi_table[0], input_table_compare);
	if (entry == NULL) {
		log_debug("%s: unknown '%c'", __func__, ictx->ch);
		return (0);
	}

	switch (entry->type) {
	case INPUT_CSI_CBT:
		/* Find the previous tab point, n times. */
		cx = s->cx;
		if (cx > screen_size_x(s) - 1)
			cx = screen_size_x(s) - 1;
		n = input_get(ictx, 0, 1, 1);
		while (cx > 0 && n-- > 0) {
			do
				cx--;
			while (cx > 0 && !bit_test(s->tabs, cx));
		}
		s->cx = cx;
		break;
	case INPUT_CSI_CUB:
		screen_write_cursorleft(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_CUD:
		screen_write_cursordown(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_CUF:
		screen_write_cursorright(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_CUP:
		n = input_get(ictx, 0, 1, 1);
		m = input_get(ictx, 1, 1, 1);
		screen_write_cursormove(sctx, m - 1, n - 1);
		break;
	case INPUT_CSI_WINOPS:
		input_csi_dispatch_winops(ictx);
		break;
	case INPUT_CSI_CUU:
		screen_write_cursorup(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_CNL:
		screen_write_carriagereturn(sctx);
		screen_write_cursordown(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_CPL:
		screen_write_carriagereturn(sctx);
		screen_write_cursorup(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_DA:
		switch (input_get(ictx, 0, 0, 0)) {
		case 0:
			input_reply(ictx, "\033[?1;2c");
			break;
		default:
			log_debug("%s: unknown '%c'", __func__, ictx->ch);
			break;
		}
		break;
	case INPUT_CSI_DA_TWO:
		switch (input_get(ictx, 0, 0, 0)) {
		case 0:
			input_reply(ictx, "\033[>84;0;0c");
			break;
		default:
			log_debug("%s: unknown '%c'", __func__, ictx->ch);
			break;
		}
		break;
	case INPUT_CSI_ECH:
		screen_write_clearcharacter(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_DCH:
		screen_write_deletecharacter(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_DECSTBM:
		n = input_get(ictx, 0, 1, 1);
		m = input_get(ictx, 1, 1, screen_size_y(s));
		screen_write_scrollregion(sctx, n - 1, m - 1);
		break;
	case INPUT_CSI_DL:
		screen_write_deleteline(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_DSR:
		switch (input_get(ictx, 0, 0, 0)) {
		case 5:
			input_reply(ictx, "\033[0n");
			break;
		case 6:
			input_reply(ictx, "\033[%u;%uR", s->cy + 1, s->cx + 1);
			break;
		default:
			log_debug("%s: unknown '%c'", __func__, ictx->ch);
			break;
		}
		break;
	case INPUT_CSI_ED:
		switch (input_get(ictx, 0, 0, 0)) {
		case 0:
			screen_write_clearendofscreen(sctx);
			break;
		case 1:
			screen_write_clearstartofscreen(sctx);
			break;
		case 2:
			screen_write_clearscreen(sctx);
			break;
		case 3:
			switch (input_get(ictx, 1, 0, 0)) {
			case 0:
				/*
				 * Linux console extension to clear history
				 * (for example before locking the screen).
				 */
				screen_write_clearhistory(sctx);
				break;
			}
			break;
		default:
			log_debug("%s: unknown '%c'", __func__, ictx->ch);
			break;
		}
		break;
	case INPUT_CSI_EL:
		switch (input_get(ictx, 0, 0, 0)) {
		case 0:
			screen_write_clearendofline(sctx);
			break;
		case 1:
			screen_write_clearstartofline(sctx);
			break;
		case 2:
			screen_write_clearline(sctx);
			break;
		default:
			log_debug("%s: unknown '%c'", __func__, ictx->ch);
			break;
		}
		break;
	case INPUT_CSI_HPA:
		n = input_get(ictx, 0, 1, 1);
		screen_write_cursormove(sctx, n - 1, s->cy);
		break;
	case INPUT_CSI_ICH:
		screen_write_insertcharacter(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_IL:
		screen_write_insertline(sctx, input_get(ictx, 0, 1, 1));
		break;
	case INPUT_CSI_RCP:
		memcpy(&ictx->cell, &ictx->old_cell, sizeof ictx->cell);
		screen_write_cursormove(sctx, ictx->old_cx, ictx->old_cy);
		break;
	case INPUT_CSI_RM:
		input_csi_dispatch_rm(ictx);
		break;
	case INPUT_CSI_RM_PRIVATE:
		input_csi_dispatch_rm_private(ictx);
		break;
	case INPUT_CSI_SCP:
		memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell);
		ictx->old_cx = s->cx;
		ictx->old_cy = s->cy;
		break;
	case INPUT_CSI_SGR:
		input_csi_dispatch_sgr(ictx);
		break;
	case INPUT_CSI_SM:
		input_csi_dispatch_sm(ictx);
		break;
	case INPUT_CSI_SM_PRIVATE:
		input_csi_dispatch_sm_private(ictx);
		break;
	case INPUT_CSI_TBC:
		switch (input_get(ictx, 0, 0, 0)) {
		case 0:
			if (s->cx < screen_size_x(s))
				bit_clear(s->tabs, s->cx);
			break;
		case 3:
			bit_nclear(s->tabs, 0, screen_size_x(s) - 1);
			break;
		default:
			log_debug("%s: unknown '%c'", __func__, ictx->ch);
			break;
		}
		break;
	case INPUT_CSI_VPA:
		n = input_get(ictx, 0, 1, 1);
		screen_write_cursormove(sctx, s->cx, n - 1);
		break;
	case INPUT_CSI_DECSCUSR:
		n = input_get(ictx, 0, 0, 0);
		screen_set_cursor_style(s, n);
		break;
	}

	return (0);
}
Beispiel #10
0
/**
 * \brief Add new IPFIX element to a proper group
 *
 * Find a group of elements with same Enteprise ID and insert new element inside
 * it. If Enterprise group does not exists, it will create new one.
 * \warning Dupliticity of elements is not check. Groups must be sorted before
 * next usage for searching for elements.
 * \param[in,out] groups Structure with groups of IPFIX elements.
 * \param[in] elem New IPFIX element
 * \return O on success. Otherwise returns non-zero value.
 */
static int elem_add_element(struct elem_groups* groups, ipfix_element_t *elem)
{
	struct elem_en_group *key_ptr, *en_group = NULL;
	struct elem_en_group **aux_ptr;
	
	struct elem_en_group key;
	key.en_id = elem->en;
	key_ptr = &key;
	
	// Find the group with same Enterprise ID
	aux_ptr = bsearch(&key_ptr, groups->groups, groups->elem_used,
		sizeof(struct elem_en_group *), cmp_groups);
	if (aux_ptr) {
		en_group = *aux_ptr;
	}
	
	if (!en_group) {
		// Group not found -> create new one
		if (groups->elem_used == groups->elem_max) {
			// Array is full -> realloc
			struct elem_en_group **new_ptr;
			new_ptr = (struct elem_en_group **) realloc(groups->groups,
				2 * groups->elem_max * sizeof(struct elem_en_group *));
			if (!new_ptr) {
				MSG_ERROR(msg_module, "REALLOC FAILED! (%s:%d)", __FILE__,
					__LINE__);
				return 1;
			}
			
			groups->elem_max *= 2;
			groups->groups = new_ptr;
		}
		
		en_group = (struct elem_en_group *) calloc(1, sizeof(struct elem_en_group));
		if (!en_group) {
			MSG_ERROR(msg_module, "CALLOC FAILED! (%s:%d)", __FILE__, __LINE__);
			return 1;
		}
		
		en_group->en_id = elem->en;
		groups->groups[groups->elem_used++] = en_group;
		
		// We use binary search for searching for groups -> sort
		qsort(groups->groups, groups->elem_used, sizeof(struct elem_en_group *),
			cmp_groups);
	}

	// Add element to the group
	if (en_group->elem_used == en_group->elem_max) {
		// Array is empty or full -> realloc
		size_t new_size = (en_group->elem_max == 0)
			? ELEM_DEF_COUNT : (2 * en_group->elem_max);
		
		ipfix_element_t **new_ptr;
		new_ptr = (ipfix_element_t **) realloc(en_group->elements,
			new_size * sizeof(ipfix_element_t *));
		if (!new_ptr) {
			MSG_ERROR(msg_module, "CALLOC FAILED! (%s:%d)", __FILE__, __LINE__);
			return 1;
		}
		
		en_group->elements = new_ptr;
		en_group->elem_max = new_size;
	}
	
	// Success
	en_group->elements[en_group->elem_used++] = elem;
	return 0;
}
Beispiel #11
0
tuning_db_entry_t *tuning_db_search (hashcat_ctx_t *hashcat_ctx, const char *device_name, const cl_device_type device_type, int attack_mode, const int hash_type)
{
  tuning_db_t *tuning_db = hashcat_ctx->tuning_db;

  static tuning_db_entry_t s;

  // first we need to convert all spaces in the device_name to underscore

  char *device_name_nospace = hcstrdup (device_name);

  int device_name_length = strlen (device_name_nospace);

  int i;

  for (i = 0; i < device_name_length; i++)
  {
    if (device_name_nospace[i] == ' ') device_name_nospace[i] = '_';
  }

  // find out if there's an alias configured

  tuning_db_alias_t a;

  a.device_name = device_name_nospace;

  char *alias_name = NULL;

  for (i = device_name_length; i >= 1; i--)
  {
    device_name_nospace[i] = 0;

    tuning_db_alias_t *alias = bsearch (&a, tuning_db->alias_buf, tuning_db->alias_cnt, sizeof (tuning_db_alias_t), sort_by_tuning_db_alias);

    if (alias == NULL) continue;

    alias_name = alias->alias_name;

    break;
  }

  // attack-mode 6 and 7 are attack-mode 1 basically

  if (attack_mode == 6) attack_mode = 1;
  if (attack_mode == 7) attack_mode = 1;

  // bsearch is not ideal but fast enough

  s.device_name = device_name_nospace;
  s.attack_mode = attack_mode;
  s.hash_type   = hash_type;

  tuning_db_entry_t *entry = NULL;

  // this will produce all 2^3 combinations required

  for (i = 0; i < 8; i++)
  {
    s.device_name = (i & 1) ? "*" : device_name_nospace;
    s.attack_mode = (i & 2) ?  -1 : attack_mode;
    s.hash_type   = (i & 4) ?  -1 : hash_type;

    entry = bsearch (&s, tuning_db->entry_buf, tuning_db->entry_cnt, sizeof (tuning_db_entry_t), sort_by_tuning_db_entry);

    if (entry != NULL) break;

    // in non-wildcard mode do some additional checks:

    if ((i & 1) == 0)
    {
      // in case we have an alias-name

      if (alias_name != NULL)
      {
        s.device_name = alias_name;

        entry = bsearch (&s, tuning_db->entry_buf, tuning_db->entry_cnt, sizeof (tuning_db_entry_t), sort_by_tuning_db_entry);

        if (entry != NULL) break;
      }

      // or by device type

      if (device_type & CL_DEVICE_TYPE_CPU)
      {
        s.device_name = "DEVICE_TYPE_CPU";
      }
      else if (device_type & CL_DEVICE_TYPE_GPU)
      {
        s.device_name = "DEVICE_TYPE_GPU";
      }
      else if (device_type & CL_DEVICE_TYPE_ACCELERATOR)
      {
        s.device_name = "DEVICE_TYPE_ACCELERATOR";
      }

      entry = bsearch (&s, tuning_db->entry_buf, tuning_db->entry_cnt, sizeof (tuning_db_entry_t), sort_by_tuning_db_entry);

      if (entry != NULL) break;
    }
  }

  // free converted device_name

  hcfree (device_name_nospace);

  return entry;
}
Beispiel #12
0
bool mbox_sync_parse_match_mail(struct mbox_mailbox *mbox,
				struct mail_index_view *view, uint32_t seq)
{
        struct mbox_sync_mail_context ctx;
	struct message_header_parser_ctx *hdr_ctx;
	struct message_header_line *hdr;
	struct header_func *func;
	struct mbox_md5_context *mbox_md5_ctx;
	const void *data;
	bool expunged;
	uint32_t uid;
	int ret;

	/* we only wish to be sure that this mail actually is what we expect
	   it to be. If there's X-UID header and it matches our UID, we use it.
	   Otherwise it could mean that the X-UID header is invalid and it's
	   just not yet been rewritten. In that case use MD5 sum, if it
	   exists. */

	mail_index_lookup_uid(view, seq, &uid);
	i_zero(&ctx);
        mbox_md5_ctx = mbox->md5_v.init();

	hdr_ctx = message_parse_header_init(mbox->mbox_stream, NULL, 0);
	while ((ret = message_parse_header_next(hdr_ctx, &hdr)) > 0) {
		if (hdr->eoh)
			break;

		func = bsearch(hdr->name, header_funcs,
			       N_ELEMENTS(header_funcs), sizeof(*header_funcs),
			       mbox_sync_bsearch_header_func_cmp);
		if (func != NULL) {
			if (strcasecmp(hdr->name, "X-UID") == 0) {
				if (hdr->continues) {
					hdr->use_full_value = TRUE;
					continue;
				}
				(void)parse_x_uid(&ctx, hdr);

				if (ctx.mail.uid == uid)
					break;
			}
		} else {
			mbox->md5_v.more(mbox_md5_ctx, hdr);
		}
	}
	i_assert(ret != 0);
	message_parse_header_deinit(&hdr_ctx);

	mbox->md5_v.finish(mbox_md5_ctx, ctx.hdr_md5_sum);

	if (ctx.mail.uid == uid)
		return TRUE;

	/* match by MD5 sum */
	mbox->mbox_save_md5 = TRUE;

	mail_index_lookup_ext(view, seq, mbox->md5hdr_ext_idx,
			      &data, &expunged);
	return data == NULL ? 0 :
		memcmp(data, ctx.hdr_md5_sum, 16) == 0;
}
Beispiel #13
0
int mbox_sync_parse_next_mail(struct istream *input,
			      struct mbox_sync_mail_context *ctx)
{
	struct mbox_sync_context *sync_ctx = ctx->sync_ctx;
	struct message_header_parser_ctx *hdr_ctx;
	struct message_header_line *hdr;
	struct mbox_sync_header_func *func;
	struct mbox_md5_context *mbox_md5_ctx;
	size_t line_start_pos;
	int i, ret;

	ctx->hdr_offset = ctx->mail.offset;
	ctx->mail.flags = MAIL_RECENT; /* default to having recent flag */

        ctx->header_first_change = (size_t)-1;
	ctx->header_last_change = 0;

	for (i = 0; i < MBOX_HDR_COUNT; i++)
		ctx->hdr_pos[i] = (size_t)-1;

	ctx->content_length = (uoff_t)-1;
	str_truncate(ctx->header, 0);

        mbox_md5_ctx = ctx->sync_ctx->mbox->md5_v.init();

        line_start_pos = 0;
	hdr_ctx = message_parse_header_init(input, NULL, 0);
	while ((ret = message_parse_header_next(hdr_ctx, &hdr)) > 0) {
		if (hdr->eoh) {
			ctx->have_eoh = TRUE;
			break;
		}

		if (!hdr->continued) {
			line_start_pos = str_len(ctx->header);
			str_append(ctx->header, hdr->name);
			str_append_data(ctx->header, hdr->middle, hdr->middle_len);
		}

		func = bsearch(hdr->name, header_funcs,
			       N_ELEMENTS(header_funcs), sizeof(*header_funcs),
			       mbox_sync_bsearch_header_func_cmp);

		if (func != NULL) {
			if (hdr->continues) {
				hdr->use_full_value = TRUE;
				continue;
			}

			if (!func->func(ctx, hdr)) {
				/* this header is broken, remove it */
				ctx->need_rewrite = TRUE;
				str_truncate(ctx->header, line_start_pos);
				if (ctx->header_first_change == (size_t)-1) {
					ctx->header_first_change =
						line_start_pos;
				}
				continue;
			}
			buffer_append(ctx->header, hdr->full_value,
				      hdr->full_value_len);
		} else {
			ctx->sync_ctx->mbox->md5_v.more(mbox_md5_ctx, hdr);
			buffer_append(ctx->header, hdr->value,
				      hdr->value_len);
		}
		if (!hdr->no_newline) {
			if (hdr->crlf_newline)
				str_append_c(ctx->header, '\r');
			str_append_c(ctx->header, '\n');
		}
	}
	i_assert(ret != 0);
	message_parse_header_deinit(&hdr_ctx);

	ctx->sync_ctx->mbox->md5_v.finish(mbox_md5_ctx, ctx->hdr_md5_sum);

	if ((ctx->seq == 1 && !ctx->seen_imapbase) ||
	    (ctx->seq > 1 && sync_ctx->dest_first_mail)) {
		/* missing X-IMAPbase */
		ctx->need_rewrite = TRUE;
		if (sync_ctx->base_uid_validity == 0) {
			/* figure out a new UIDVALIDITY for us. */
			sync_ctx->base_uid_validity =
				sync_ctx->hdr->uid_validity != 0 &&
				!sync_ctx->renumber_uids ?
				sync_ctx->hdr->uid_validity :
				I_MAX((uint32_t)ioloop_time, 1);
		}
	}

	ctx->body_offset = input->v_offset;
	if (input->stream_errno != 0) {
		mbox_sync_set_critical(ctx->sync_ctx, "read(%s) failed: %s",
			i_stream_get_name(input), i_stream_get_error(input));
		return -1;
	}
	return 0;
}
Beispiel #14
0
gboolean pharse_search(char *s)
{
  return bsearch(&s, phrase, phraseN, sizeof(char *), qcmp_str) != NULL;
}
Beispiel #15
0
void cliProcess(void)
{
    if (!cliMode) {
        cliEnter();
    }

    while (serialTotalBytesWaiting(cliPort)) {
        uint8_t c = serialRead(cliPort);
        if (c == '\t' || c == '?') {
            // do tab completion
            const clicmd_t *cmd, *pstart = NULL, *pend = NULL;
            uint32_t i = bufferIndex;
            for (cmd = cmdTable; cmd < cmdTable + CMD_COUNT; cmd++) {
                if (bufferIndex && (strncasecmp(cliBuffer, cmd->name, bufferIndex) != 0))
                    continue;
                if (!pstart)
                    pstart = cmd;
                pend = cmd;
            }
            if (pstart) {    /* Buffer matches one or more commands */
                for (; ; bufferIndex++) {
                    if (pstart->name[bufferIndex] != pend->name[bufferIndex])
                        break;
                    if (!pstart->name[bufferIndex] && bufferIndex < sizeof(cliBuffer) - 2) {
                        /* Unambiguous -- append a space */
                        cliBuffer[bufferIndex++] = ' ';
                        cliBuffer[bufferIndex] = '\0';
                        break;
                    }
                    cliBuffer[bufferIndex] = pstart->name[bufferIndex];
                }
            }
            if (!bufferIndex || pstart != pend) {
                /* Print list of ambiguous matches */
                cliPrint("\r\033[K");
                for (cmd = pstart; cmd <= pend; cmd++) {
                    cliPrint(cmd->name);
                    cliWrite('\t');
                }
                cliPrompt();
                i = 0;    /* Redraw prompt */
            }
            for (; i < bufferIndex; i++)
                cliWrite(cliBuffer[i]);
        } else if (!bufferIndex && c == 4) {
            cliExit(cliBuffer);
            return;
        } else if (c == 12) {
            // clear screen
            cliPrint("\033[2J\033[1;1H");
            cliPrompt();
        } else if (bufferIndex && (c == '\n' || c == '\r')) {
            // enter pressed
            clicmd_t *cmd = NULL;
            clicmd_t target;
            cliPrint("\r\n");
            cliBuffer[bufferIndex] = 0; // null terminate

            target.name = cliBuffer;
            target.param = NULL;

            cmd = bsearch(&target, cmdTable, CMD_COUNT, sizeof cmdTable[0], cliCompare);
            if (cmd)
                cmd->func(cliBuffer + strlen(cmd->name) + 1);
            else
                cliPrint("Unknown command, try 'help'");

            memset(cliBuffer, 0, sizeof(cliBuffer));
            bufferIndex = 0;

            // 'exit' will reset this flag, so we don't need to print prompt again
            if (!cliMode)
                return;
            cliPrompt();
        } else if (c == 127) {
            // backspace
            if (bufferIndex) {
                cliBuffer[--bufferIndex] = 0;
                cliPrint("\010 \010");
            }
        } else if (bufferIndex < sizeof(cliBuffer) && c >= 32 && c <= 126) {
            if (!bufferIndex && c == 32)
                continue;
            cliBuffer[bufferIndex++] = c;
            cliWrite(c);
        }
    }
}
Beispiel #16
0
void StdlibBsearch(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs)
{
	ReturnValue->Val->Pointer = bsearch(Param[0]->Val->Pointer, Param[1]->Val->Pointer, Param[2]->Val->Integer, Param[3]->Val->Integer, (int (*)())Param[4]->Val->Pointer);
}
Beispiel #17
0
static readstat_error_t dta_handle_rows(dta_ctx_t *ctx) {
    readstat_io_t *io = ctx->io;
    char *buf = NULL;
    char  str_buf[2048];
    int i;
    readstat_error_t retval = READSTAT_OK;

    if ((buf = malloc(ctx->record_len)) == NULL) {
        retval = READSTAT_ERROR_MALLOC;
        goto cleanup;
    }

    for (i=0; i<ctx->row_limit; i++) {
        if (io->read(buf, ctx->record_len, io->io_ctx) != ctx->record_len) {
            retval = READSTAT_ERROR_READ;
            goto cleanup;
        }
        int j;
        off_t offset = 0;
        for (j=0; j<ctx->nvar; j++) {
            size_t max_len;
            readstat_value_t value;
            memset(&value, 0, sizeof(readstat_value_t));

            value.type = dta_type_info(ctx->typlist[j], &max_len, ctx);

            if (value.type == READSTAT_TYPE_STRING) {
                readstat_convert(str_buf, sizeof(str_buf), &buf[offset], max_len, ctx->converter);
                value.v.string_value = str_buf;
            } else if (value.type == READSTAT_TYPE_STRING_REF) {
                dta_strl_t key;
                dta_interpret_strl_vo_bytes(ctx, (unsigned char *)&buf[offset], &key);

                dta_strl_t **found = bsearch(&key, ctx->strls, ctx->strls_count, sizeof(dta_strl_t *), &dta_compare_strls);

                if (found) {
                    value.v.string_value = (*found)->data;
                }
                value.type = READSTAT_TYPE_STRING;
            } else if (value.type == READSTAT_TYPE_INT8) {
                int8_t byte = buf[offset];
                if (ctx->machine_is_twos_complement) {
                    byte = ones_to_twos_complement1(byte);
                }
                if (byte > ctx->max_int8) {
                    if (ctx->supports_tagged_missing && byte > DTA_113_MISSING_INT8) {
                        value.tag = 'a' + (byte - DTA_113_MISSING_INT8_A);
                        value.is_tagged_missing = 1;
                    } else {
                        value.is_system_missing = 1;
                    }
                }
                value.v.i8_value = byte;
            } else if (value.type == READSTAT_TYPE_INT16) {
                int16_t num = *((int16_t *)&buf[offset]);
                if (ctx->machine_needs_byte_swap) {
                    num = byteswap2(num);
                }
                if (ctx->machine_is_twos_complement) {
                    num = ones_to_twos_complement2(num);
                }
                if (num > ctx->max_int16) {
                    if (ctx->supports_tagged_missing && num > DTA_113_MISSING_INT16) {
                        value.tag = 'a' + (num - DTA_113_MISSING_INT16_A);
                        value.is_tagged_missing = 1;
                    } else {
                        value.is_system_missing = 1;
                    }
                }
                value.v.i16_value = num;
            } else if (value.type == READSTAT_TYPE_INT32) {
                int32_t num = *((int32_t *)&buf[offset]);
                if (ctx->machine_needs_byte_swap) {
                    num = byteswap4(num);
                }
                if (ctx->machine_is_twos_complement) {
                    num = ones_to_twos_complement4(num);
                }
                if (num > ctx->max_int32) {
                    if (ctx->supports_tagged_missing && num > DTA_113_MISSING_INT32) {
                        value.tag = 'a' + (num - DTA_113_MISSING_INT32_A);
                        value.is_tagged_missing = 1;
                    } else {
                        value.is_system_missing = 1;
                    }
                }
                value.v.i32_value = num;
            } else if (value.type == READSTAT_TYPE_FLOAT) {
                int32_t num = *((int32_t *)&buf[offset]);
                float f_num = NAN;
                if (ctx->machine_needs_byte_swap) {
                    num = byteswap4(num);
                }
                if (num > ctx->max_float) {
                    if (ctx->supports_tagged_missing && num > DTA_113_MISSING_FLOAT) {
                        value.tag = 'a' + ((num - DTA_113_MISSING_FLOAT_A) >> 11);
                        value.is_tagged_missing = 1;
                    } else {
                        value.is_system_missing = 1;
                    }
                } else {
Beispiel #18
0
static struct sym *symget(const wchar_t *name)
{
    struct sym symkey = { .name = name };
    return bsearch(&symkey, symtab, sizeof symtab / sizeof symtab[0], sizeof symtab[0], symcmp);
}
Beispiel #19
0
/*
 * args -- parse JCL syntax of dd.
 */
void
jcl(char **argv)
{
	struct arg *ap, tmp;
	char *arg;

	in.dbsz = out.dbsz = 512;

	while ((oper = *++argv) != NULL) {
		if ((oper = strdup(oper)) == NULL)
			errx(1, "out of memory");
		if ((arg = strchr(oper, '=')) == NULL)
			errx(1, "unknown operand %s", oper);
		*arg++ = '\0';
		if (!*arg)
			errx(1, "no value specified for %s", oper);
		tmp.name = oper;
		if (!(ap = (struct arg *)bsearch(&tmp, args,
		    sizeof(args)/sizeof(struct arg), sizeof(struct arg),
		    c_arg)))
			errx(1, "unknown operand %s", tmp.name);
		if (ddflags & ap->noset)
			errx(1, "%s: illegal argument combination or already set",
			    tmp.name);
		ddflags |= ap->set;
		ap->f(arg);
	}

	/* Final sanity checks. */

	if (ddflags & C_BS) {
		/*
		 * Bs is turned off by any conversion -- we assume the user
		 * just wanted to set both the input and output block sizes
		 * and didn't want the bs semantics, so we don't warn.
		 */
		if (ddflags & (C_BLOCK|C_LCASE|C_SWAB|C_UCASE|C_UNBLOCK))
			ddflags &= ~C_BS;

		/* Bs supersedes ibs and obs. */
		if (ddflags & C_BS && ddflags & (C_IBS|C_OBS))
			warnx("bs supersedes ibs and obs");
	}

	/*
	 * Ascii/ebcdic and cbs implies block/unblock.
	 * Block/unblock requires cbs and vice-versa.
	 */
	if (ddflags & (C_BLOCK|C_UNBLOCK)) {
		if (!(ddflags & C_CBS))
			errx(1, "record operations require cbs");
		if (cbsz == 0)
			errx(1, "cbs cannot be zero");
		cfunc = ddflags & C_BLOCK ? block : unblock;
	} else if (ddflags & C_CBS) {
		if (ddflags & (C_ASCII|C_EBCDIC)) {
			if (ddflags & C_ASCII) {
				ddflags |= C_UNBLOCK;
				cfunc = unblock;
			} else {
				ddflags |= C_BLOCK;
				cfunc = block;
			}
		} else
			errx(1, "cbs meaningless if not doing record operations");
		if (cbsz == 0)
			errx(1, "cbs cannot be zero");
	} else
		cfunc = def;

	if (in.dbsz == 0 || out.dbsz == 0)
		errx(1, "buffer sizes cannot be zero");

	/*
	 * Read and write take size_t's as arguments.  Lseek, however,
	 * takes an off_t (quad).
	 */
	if (cbsz > SSIZE_MAX || in.dbsz > SSIZE_MAX || out.dbsz > SSIZE_MAX)
		errx(1, "buffer sizes cannot be greater than %zd",
		    (ssize_t)SSIZE_MAX);
	if (in.offset > QUAD_MAX / in.dbsz || out.offset > QUAD_MAX / out.dbsz)
		errx(1, "seek offsets cannot be larger than %qd", QUAD_MAX);
}
Beispiel #20
0
static struct api *apiget(const wchar_t *name)
{
    struct api apikey = { .name = name };
    return bsearch(&apikey, apitab, sizeof apitab / sizeof apitab[0], sizeof apitab[0], apicmp);
}
Beispiel #21
0
bool wxEncodingConverter::Init(wxFontEncoding input_enc, wxFontEncoding output_enc, int method)
{
    unsigned i;
    const wxUint16 *in_tbl;
    const wxUint16 *out_tbl = NULL;

    wxDELETEA(m_Table);

    if (input_enc == output_enc) {m_JustCopy = true; return true;}

    m_UnicodeOutput = (output_enc == wxFONTENCODING_UNICODE);
    m_JustCopy = false;

    if (input_enc == wxFONTENCODING_UNICODE)
    {
        if ((out_tbl = GetEncTable(output_enc)) == NULL) return false;

        m_Table = new wchar_t[65536];
        for (i = 0; i < 128; i++)  m_Table[i] = (wchar_t)i; // 7bit ASCII
        for (i = 128; i < 65536; i++)  m_Table[i] = (wchar_t)0;

        if (method == wxCONVERT_SUBSTITUTE)
        {
            for (i = 0; i < encoding_unicode_fallback_count; i++)
                m_Table[encoding_unicode_fallback[i].c] = (wchar_t) encoding_unicode_fallback[i].s;
        }

        for (i = 0; i < 128; i++)
            m_Table[out_tbl[i]] = (wchar_t)(128 + i);

        m_UnicodeInput = true;
    }
    else // input !Unicode
    {
        if ((in_tbl = GetEncTable(input_enc)) == NULL) return false;
        if (output_enc != wxFONTENCODING_UNICODE)
            if ((out_tbl = GetEncTable(output_enc)) == NULL) return false;

        m_UnicodeInput = false;

        m_Table = new wchar_t[256];
        for (i = 0; i < 128; i++)  m_Table[i] = (wchar_t)i; // 7bit ASCII

        if (output_enc == wxFONTENCODING_UNICODE)
        {
            for (i = 0; i < 128; i++)  m_Table[128 + i] = (wchar_t)in_tbl[i];
            return true;
        }
        else // output !Unicode
        {
            CharsetItem *rev = BuildReverseTable(out_tbl);
            CharsetItem *item;
            CharsetItem key;

            for (i = 0; i < 128; i++)
            {
                key.u = in_tbl[i];
                item = (CharsetItem*) bsearch(&key, rev, 128, sizeof(CharsetItem), CompareCharsetItems);
                if (item == NULL && method == wxCONVERT_SUBSTITUTE)
                    item = (CharsetItem*) bsearch(&key, encoding_unicode_fallback,
                                encoding_unicode_fallback_count, sizeof(CharsetItem), CompareCharsetItems);
                if (item)
                    m_Table[128 + i] = (wchar_t)item -> c;
                else
                    m_Table[128 + i] = (wchar_t)(128 + i);
            }

            delete[] rev;
        }
    }

    return true;
}
Beispiel #22
0
static struct err *errget(DWORD value)
{
    struct err errkey = { .value = value };
    return bsearch(&errkey, errtab, sizeof errtab / sizeof errtab[0], sizeof errtab[0], errcmp);
}
Beispiel #23
0
ERRORCODE FileListRecord::do_find_file(LPCSTR name, DB_RECORD_NUMBER far *lprecord, FILE_SEARCH_KEY *key)
{
#if 0
	od("Dump: ");
	for (int i = 0; i < m_file_array.count(); i++)
	{
		FILE_ARRAY_ELEMENT_PTR elem = m_file_array.get_file(i);
		od("(h:%x, r:%ld)", elem->hash, elem->record_number);
	}
	od("\r\n");
#endif
/*
// We want to perform a binary search on the array.
// The search key will be the hash value.
*/

	key->this_record = this;
	key->search_name = name;
	key->search_hash = hash_name(name);
	key->last_searched_element = NULL;

//	od("Look for file name '%s' (hash: %x)\r\n", name, key->search_hash);

	SHORT count;

	if ((count = m_file_array.count()) != 0)
	{
	/*
	// Get the first entry.
	// All entries in the array have the same selector.
	*/
		FILE_ARRAY_ELEMENT_PTR elem = m_file_array.get_file(0);

	/* Do the search. */

		void *ret = bsearch(key, elem, count,
								  sizeof(FILE_ARRAY_ELEMENT),
								  file_element_compare);

	/* Did we find it? */

		if (ret != NULL)
		{
			if (key->last_result != 0)
			{
			/* This is actually an error. */
				return (ERRORCODE)key->last_result;
			}

		/* Found it! */

			elem = (FILE_ARRAY_ELEMENT_PTR)ret;

		/* Update our time stamp. */

			elem->last_access = (DWORD)time(NULL);

			if (lprecord != NULL)
			{
				*lprecord = elem->record_number;
			}

			return ERRORCODE_None;
		}
	}

/* Not found. */

	return ERRORCODE_DoesNotExist;
}
Beispiel #24
0
void ON_InstanceDefinition::UpdateLinkedIdefReferenceFileLayerSettings( unsigned int layer_count, ON_Layer** layer_settings )
{
  ON__IDefLayerSettingsUserData* ud;

  if ( layer_count <= 0 || 0 == layer_settings )
  {
    // delete linked idef layer settings
    ud = ON__IDefLayerSettingsUserData::FindOrCreate(*this,false);
    if ( 0 != ud )
      delete ud;
    return;
  }

  // Create an index_map[] into the layer_settings[] array that is sorted
  // by layer_settings[]->m_layer_id
  ON_Workspace ws;
  int* index_map = (int*)ws.GetMemory(layer_count*sizeof(index_map[0]));
  ON_Sort(ON::quick_sort,index_map,layer_settings,layer_count,sizeof(layer_settings[0]),compareLayerPtrId);

  // Use index_map[] to get a unique list of layers with valid ids
  ON_UuidIndex* iddex = (ON_UuidIndex*)ws.GetMemory(layer_count*sizeof(iddex[0]));
  unsigned int iddex_count = 0;
  unsigned int i;
  ON_Layer* layer;
  for ( i = 0; i < layer_count; i++ )
  {
    layer = layer_settings[index_map[i]];
    if ( 0 == layer )
      continue;
    layer->SaveSettings(0,false); // remove any saved settings on input layers
    if ( ON_UuidIsNil(layer->m_layer_id) )
      continue;
    if ( iddex_count > 0 && iddex[iddex_count-1].m_id == layer->m_layer_id )
      continue;
    iddex[iddex_count].m_i = index_map[i];
    iddex[iddex_count].m_id = layer->m_layer_id;
    iddex_count++;
  }

  if ( iddex_count <= 0 )
  {
    // delete settings
    UpdateLinkedIdefReferenceFileLayerSettings(0,0);
    return;
  }

  // Create or get user data where the saved layer settings
  // are stored.
  ud = ON__IDefLayerSettingsUserData::FindOrCreate(*this,true);
  if ( 0 == ud )
    return;
    
  // Go through the saved settings that were previously
  // on this idef apply those settings to the layer_settings[]
  // list. Then delete the information from ud->m_layers[].
  ON_UuidIndex idx;
  idx.m_i = 0;
  unsigned int settings;
  for ( i = 0; i < ud->m_layers.UnsignedCount(); i++ )
  {
    if ( 0 == ud->m_layers[i] )
      continue;
    layer = ud->m_layers[i];
    ud->m_layers[i] = 0;
    for(;;)
    {
      settings = layer->SavedSettings();
      if ( 0 == settings )
        break; // no settings were modified
      idx.m_id = layer->m_layer_id;
      const ON_UuidIndex* idx0 = (const ON_UuidIndex*)bsearch(&idx,iddex,iddex_count,sizeof(iddex[0]),compareUuidIndexId);
      if ( 0 == idx0)
        break; // this layer is not in the current layer_settings[] list
      layer_settings[idx0->m_i]->SaveSettings(settings,false); // saves the layer settings found in linked file
      layer_settings[idx0->m_i]->Set(settings,*layer);   // applies modifications found on idef
      break;
    }
    delete layer;
  }

  // Save a copy of this information on the user data
  // so it will persist in the file containing the idef.
  ud->m_layers.SetCount(0);
  ud->m_layers.Reserve(iddex_count);
  for ( i = 0; i < iddex_count; i++ )
  {
    layer = new ON_Layer( *layer_settings[iddex[i].m_i] );
    ud->m_layers.Append(layer);
  }
}
Beispiel #25
0
int isPrime(int n){
	return (bsearch(0, np-1, n) >= 0);
}
Beispiel #26
0
/**
 * This function searches for a transistor by size
 * - lower: (Return value) The lower-bound matching transistor
 * - upper: (Return value) The upper-bound matching transistor
 * - type: The transistor type to search for
 * - size: The transistor size to search for (size = W/L)
 */
boolean power_find_transistor_info(t_transistor_size_inf ** lower,
		t_transistor_size_inf ** upper, e_tx_type type, float size) {
	char msg[1024];
	t_transistor_size_inf key;
	t_transistor_size_inf * found;
	t_transistor_inf * trans_info;
	float min_size, max_size;
	boolean error = FALSE;

	key.size = size;

	/* Find the appropriate global transistor records */
	if (type == NMOS) {
		trans_info = &g_power_tech->NMOS_inf;
	} else if (type == PMOS) {
		trans_info = &g_power_tech->PMOS_inf;
	} else {
		assert(0);
	}

	/* No transistor data exists */
	if (trans_info->size_inf == NULL) {
		power_log_msg(POWER_LOG_ERROR,
				"No transistor information exists.  Cannot determine transistor properties.");
		error = TRUE;
		return error;
	}

	/* Make note of the transistor record we are searching in, and the bounds */
	g_transistor_last_searched = trans_info;
	min_size = trans_info->size_inf[0].size;
	max_size = trans_info->size_inf[trans_info->num_size_entries - 1].size;

	found = (t_transistor_size_inf*) bsearch(&key, trans_info->size_inf,
			trans_info->num_size_entries, sizeof(t_transistor_size_inf),
			&power_compare_transistor_size);
	assert(found);

	if (size < min_size) {
		/* Too small */
		assert(found == &trans_info->size_inf[0]);
		sprintf(msg,
				"Using %s transistor of size '%f', which is smaller than the smallest modeled transistor (%f) in the technology behavior file.",
				transistor_type_name(type), size, min_size);
		power_log_msg(POWER_LOG_WARNING, msg);
		*lower = NULL;
		*upper = found;
	} else if (size > max_size) {
		/* Too large */
		assert(
				found == &trans_info->size_inf[trans_info->num_size_entries - 1]);
		sprintf(msg,
				"Using %s transistor of size '%f', which is larger than the largest modeled transistor (%f) in the technology behavior file.",
				transistor_type_name(type), size, max_size);
		power_log_msg(POWER_LOG_WARNING, msg);
		*lower = found;
		*upper = NULL;
	} else {
		*lower = found;
		*upper = found + 1;
	}

	return error;
}
Beispiel #27
0
static void
cpio_options(int argc, char **argv)
{
	int c;
	size_t i;
	char *str;
	FSUB tmp;
	FILE *fp;

	kflag = 1;
	pids = 1;
	pmode = 1;
	pmtime = 0;
	arcname = NULL;
	dflag = 1;
	act = -1;
	nodirs = 1;
	while ((c=getopt(argc,argv,"abcdfiklmoprstuvzABC:E:F:H:I:LO:SZ6")) != -1)
		switch (c) {
			case 'a':
				/*
				 * preserve access time on files read
				 */
				tflag = 1;
				break;
			case 'b':
				/*
				 * swap bytes and half-words when reading data
				 */
				break;
			case 'c':
				/*
				 * ASCII cpio header
				 */
				frmt = &(fsub[F_ACPIO]);
				break;
			case 'd':
				/*
				 * create directories as needed
				 */
				nodirs = 0;
				break;
			case 'f':
				/*
				 * invert meaning of pattern list
				 */
				cflag = 1;
				break;
			case 'i':
				/*
				 * restore an archive
				 */
				act = EXTRACT;
				break;
			case 'k':
				break;
			case 'l':
				/*
				 * use links instead of copies when possible
				 */
				lflag = 1;
				break;
			case 'm':
				/*
				 * preserve modification time
				 */
				pmtime = 1;
				break;
			case 'o':
				/*
				 * create an archive
				 */
				act = ARCHIVE;
				frmt = &(fsub[F_CPIO]);
				break;
			case 'p':
				/*
				 * copy-pass mode
				 */
				act = COPY;
				break;
			case 'r':
				/*
				 * interactively rename files
				 */
				iflag = 1;
				break;
			case 's':
				/*
				 * swap bytes after reading data
				 */
				break;
			case 't':
				/*
				 * list contents of archive
				 */
				act = LIST;
				listf = stdout;
				break;
			case 'u':
				/*
				 * replace newer files
				 */
				kflag = 0;
				break;
			case 'v':
				/*
				 * verbose operation mode
				 */
				vflag = 1;
				break;
			case 'z':
				/*
				 * use gzip.  Non standard option.
				 */
				gzip_program = GZIP_CMD;
				break;
			case 'A':
				/*
				 * append mode
				 */
				act = APPND;
				break;
			case 'B':
				/*
				 * Use 5120 byte block size
				 */
				wrblksz = 5120;
				break;
			case 'C':
				/*
				 * set block size in bytes
				 */
				wrblksz = atoi(optarg);
				break;
			case 'E':
				/*
				 * file with patterns to extract or list
				 */
				if ((fp = fopen(optarg, "r")) == NULL) {
					paxwarn(1, "Unable to open file '%s' for read", optarg);
					cpio_usage();
				}
				while ((str = getline(fp)) != NULL) {
					pat_add(str, NULL);
				}
				fclose(fp);
				if (getline_error) {
					paxwarn(1, "Problem with file '%s'", optarg);
					cpio_usage();
				}
				break;
			case 'F':
			case 'I':
			case 'O':
				/*
				 * filename where the archive is stored
				 */
				if ((optarg[0] == '-') && (optarg[1]== '\0')) {
					/*
					 * treat a - as stdin
					 */
					arcname = NULL;
					break;
				}
				arcname = optarg;
				break;
			case 'H':
				/*
				 * specify an archive format on write
				 */
				tmp.name = optarg;
				if ((frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
				    sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt)) != NULL)
					break;
				paxwarn(1, "Unknown -H format: %s", optarg);
				(void)fputs("cpio: Known -H formats are:", stderr);
				for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
					(void)fprintf(stderr, " %s", fsub[i].name);
				(void)fputs("\n\n", stderr);
				cpio_usage();
				break;
			case 'L':
				/*
				 * follow symbolic links
				 */
				Lflag = 1;
				break;
			case 'S':
				/*
				 * swap halfwords after reading data
				 */
				break;
			case 'Z':
				/*
				 * use compress.  Non standard option.
				 */
				gzip_program = COMPRESS_CMD;
				break;
			case '6':
				/*
				 * process Version 6 cpio format
				 */
				frmt = &(fsub[F_OCPIO]);
				break;
			case '?':
			default:
				cpio_usage();
				break;
		}
	argc -= optind;
	argv += optind;

	/*
	 * process the args as they are interpreted by the operation mode
	 */
	switch (act) {
		case LIST:
		case EXTRACT:
			while (*argv != NULL)
				if (pat_add(*argv++, NULL) < 0)
					cpio_usage();
			break;
		case COPY:
			if (*argv == NULL) {
				paxwarn(0, "Destination directory was not supplied");
				cpio_usage();
			}
			dirptr = *argv;
			if (mkpath(dirptr) < 0)
				cpio_usage();
			--argc;
			++argv;
			/* FALLTHROUGH */
		case ARCHIVE:
		case APPND:
			if (*argv != NULL)
				cpio_usage();
			/*
			 * no read errors allowed on updates/append operation!
			 */
			maxflt = 0;
			while ((str = getline(stdin)) != NULL) {
				ftree_add(str, 0);
			}
			if (getline_error) {
				paxwarn(1, "Problem while reading stdin");
				cpio_usage();
			}
			break;
		default:
			cpio_usage();
			break;
	}
}
Beispiel #28
0
static readstat_error_t sav_read_value_label_record(sav_ctx_t *ctx) {
    int32_t label_count;
    readstat_error_t retval = READSTAT_OK;
    readstat_io_t *io = ctx->io;
    int32_t *vars = NULL;
    int32_t rec_type;
    int32_t var_count;
    readstat_type_t value_type = READSTAT_TYPE_STRING;
    char label_buf[256];
    value_label_t *value_labels = NULL;

    if (io->read(&label_count, sizeof(int32_t), io->io_ctx) < sizeof(int32_t)) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }
    if (ctx->bswap)
        label_count = byteswap4(label_count);
    
    if ((value_labels = malloc(label_count * sizeof(value_label_t))) == NULL) {
        retval = READSTAT_ERROR_MALLOC;
        goto cleanup;
    }
    
    int i;
    for (i=0; i<label_count; i++) {
        value_label_t *vlabel = &value_labels[i];
        if (io->read(vlabel, 9, io->io_ctx) < 9) {
            retval = READSTAT_ERROR_READ;
            goto cleanup;
        }
        size_t label_len = (vlabel->label_len + 8) / 8 * 8 - 1;
        if (io->read(label_buf, label_len, io->io_ctx) < label_len) {
            retval = READSTAT_ERROR_READ;
            goto cleanup;
        }
        retval = readstat_convert(vlabel->label, sizeof(vlabel->label), label_buf, label_len, ctx->converter);
        if (retval != READSTAT_OK)
            goto cleanup;
    }

    if (io->read(&rec_type, sizeof(int32_t), io->io_ctx) < sizeof(int32_t)) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }
    if (ctx->bswap)
        rec_type = byteswap4(rec_type);
    
    if (rec_type != 4) {
        retval = READSTAT_ERROR_PARSE;
        goto cleanup;
    }
    if (io->read(&var_count, sizeof(int32_t), io->io_ctx) < sizeof(int32_t)) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }
    if (ctx->bswap)
        var_count = byteswap4(var_count);
    
    if ((vars = malloc(var_count * sizeof(int32_t))) == NULL) {
        retval = READSTAT_ERROR_MALLOC;
        goto cleanup;
    }
    if (io->read(vars, var_count * sizeof(int32_t), io->io_ctx) < var_count * sizeof(int32_t)) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }
    for (i=0; i<var_count; i++) {
        int var_offset = vars[i];
        if (ctx->bswap)
            var_offset = byteswap4(var_offset);

        var_offset--; // Why subtract 1????
        spss_varinfo_t *var = bsearch(&var_offset, ctx->varinfo, ctx->var_index, sizeof(spss_varinfo_t),
                &spss_varinfo_compare);
        if (var) {
            var->labels_index = ctx->value_labels_count;

            value_type = var->type;
        }
    }
    if (ctx->value_label_handler) {
        sav_submit_value_labels(value_labels, label_count, value_type, ctx);
    }
    ctx->value_labels_count++;
cleanup:
    if (vars)
        free(vars);
    if (value_labels)
        free(value_labels);
    
    return retval;
}
Beispiel #29
0
static int should_filter_query(ns_msg msg, struct in_addr dns_addr) {
  ns_rr rr;
  int rrnum, rrmax;
  void *r;
  // TODO cache result for each dns server
  int dns_is_chn = 0;
  int dns_is_foreign = 0;
  if (chnroute_file && (dns_servers_len > 1)) {
    dns_is_chn = test_ip_in_list(dns_addr, &chnroute_list);
    dns_is_foreign = !dns_is_chn;
  }
  rrmax = ns_msg_count(msg, ns_s_an);
  if (rrmax == 0) {
    if (compression) {
      // Wait for foreign dns
      if (dns_is_chn) {
        return 1;
      } else {
        return 0;
      }
    }
    return -1;
  }
  for (rrnum = 0; rrnum < rrmax; rrnum++) {
    if (local_ns_parserr(&msg, ns_s_an, rrnum, &rr)) {
      ERR("local_ns_parserr");
      return 0;
    }
    u_int type;
    const u_char *rd;
    type = ns_rr_type(rr);
    rd = ns_rr_rdata(rr);
    if (type == ns_t_a) {
      if (verbose)
        printf("%s, ", inet_ntoa(*(struct in_addr *)rd));
      if (!compression) {
        r = bsearch(rd, ip_list.ips, ip_list.entries, sizeof(struct in_addr),
                    cmp_in_addr);
        if (r) {
          return 1;
        }
      }
      if (test_ip_in_list(*(struct in_addr *)rd, &chnroute_list)) {
        // result is chn
        if (dns_is_foreign) {
          if (bidirectional) {
            // filter DNS result from foreign dns if result is inside chn
            return 1;
          }
        }
      } else {
        // result is foreign
        if (dns_is_chn) {
          // filter DNS result from chn dns if result is outside chn
          return 1;
        }
      }
    } else if (type == ns_t_aaaa) {
      if (dns_is_chn) {
        // filter DNS result from chn dns if dns is inside chn
        return 1;
      }
    } else if (type == type == ns_t_ptr) {
      // if we've got a PTR result, pass
      return 0;
    }
  }
  if (rrmax == 1) {
    if (compression) {
      return 0;
    } else {
      return -1;
    }
  }
  return 0;
}
GCC_INLINE int fc_solve_check_and_add_state(
    fc_solve_soft_thread_t * soft_thread,
    fcs_state_extra_info_t * new_state_val,
    fcs_state_extra_info_t * * existing_state_val
    )
{
#if (FCS_STATE_STORAGE == FCS_STATE_STORAGE_INTERNAL_HASH)
#ifdef FCS_ENABLE_SECONDARY_HASH_VALUE
    SFO_hash_value_t hash_value_int;
#endif
#endif
#if (FCS_STATE_STORAGE == FCS_STATE_STORAGE_INDIRECT)
    fcs_standalone_state_ptrs_t * pos_ptr;
    int found;
#endif
    fc_solve_hard_thread_t * hard_thread = soft_thread->hard_thread;
    fc_solve_instance_t * instance = hard_thread->instance;
    fcs_state_t * new_state_key = new_state_val->key;

    int is_state_new;

    if (check_if_limits_exceeded())
    {
        return FCS_STATE_BEGIN_SUSPEND_PROCESS;
    }

    if ((instance->max_depth >= 0) &&
        (new_state_val->depth >= instance->max_depth))
    {
        return FCS_STATE_EXCEEDS_MAX_DEPTH;
    }


    fc_solve_cache_stacks(hard_thread, new_state_key, new_state_val);

    fc_solve_canonize_state(new_state_val,
            INSTANCE_FREECELLS_NUM,
            INSTANCE_STACKS_NUM
            );

/*
    The objective of this part of the code is:
    1. To check if new_state_key / new_state_val is already in the prev_states
       collection.
    2. If not, to add it and to set check to true.
    3. If so, to set check to false.
  */

#if (FCS_STATE_STORAGE == FCS_STATE_STORAGE_INTERNAL_HASH)
#ifdef FCS_ENABLE_SECONDARY_HASH_VALUE
    {
        const char * s_ptr = (char*)new_state_key;
        const char * s_end = s_ptr+sizeof(*new_state_key);
        hash_value_int = 0;
        while (s_ptr < s_end)
        {
            hash_value_int += (hash_value_int << 5) + *(s_ptr++);
        }
        hash_value_int += (hash_value_int>>5);
    }
    if (hash_value_int < 0)
    {
        /*
         * This is a bit mask that nullifies the sign bit of the
         * number so it will always be positive
         * */
        hash_value_int &= (~(1<<((sizeof(hash_value_int)<<3)-1)));
    }
#endif
    {
        void * existing_key_void, * existing_val_void;
    is_state_new = (fc_solve_hash_insert(
        &(instance->hash),
        new_state_key,
        new_state_val,
        &existing_key_void,
        &existing_val_void,
        perl_hash_function(
            (ub1 *)new_state_key,
            sizeof(*new_state_key)
            )
#ifdef FCS_ENABLE_SECONDARY_HASH_VALUE
        , hash_value_int
#endif
        ) == 0);
        if (! is_state_new)
        {
            *existing_state_val = existing_val_void;
        }
    }
#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_GOOGLE_DENSE_HASH)
    {
        void * existing_key_void, * existing_val_void;

        is_state_new = (fc_solve_states_google_hash_insert(
            instance->hash,
            new_state_key,
            new_state_val,
            &existing_key_void,
            &existing_val_void
            ) == 0);

        if (! is_state_new)
        {
            *existing_state_val = existing_val_void;
        }
    }
#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_INDIRECT)
    /* Try to see if the state is found in indirect_prev_states */
    if ((pos_ptr = (fcs_standalone_state_ptrs_t *)bsearch(&new_state_key,
                instance->indirect_prev_states,
                instance->num_indirect_prev_states,
                sizeof(instance->indirect_prev_states[0]),
                fc_solve_state_compare_indirect)) == NULL)
    {
        /* It isn't in prev_states, but maybe it's in the sort margin */
        pos_ptr = (fcs_standalone_state_ptrs_t *)fc_solve_bsearch(
            &new_state_key,
            instance->indirect_prev_states_margin,
            instance->num_prev_states_margin,
            sizeof(instance->indirect_prev_states_margin[0]),
            fc_solve_state_compare_indirect_with_context,
            NULL,
            &found);

        if (found)
        {
            is_state_new = 0;
            *existing_state_val = pos_ptr->val;
        }
        else
        {
            /* Insert the state into its corresponding place in the sort
             * margin */
            memmove((void*)(pos_ptr+1),
                    (void*)pos_ptr,
                    sizeof(*pos_ptr) *
                    (instance->num_prev_states_margin-
                      (pos_ptr-instance->indirect_prev_states_margin)
                    ));
            pos_ptr->key = new_state_key;
            pos_ptr->val = new_state_val;

            instance->num_prev_states_margin++;

            if (instance->num_prev_states_margin >= PREV_STATES_SORT_MARGIN)
            {
                /* The sort margin is full, let's combine it with the main array */

                instance->indirect_prev_states = 
                    realloc(
                        instance->indirect_prev_states,
                        sizeof(instance->indirect_prev_states[0])
                        * (instance->num_indirect_prev_states
                            + instance->num_prev_states_margin
                        )
                    );

                fc_solve_merge_large_and_small_sorted_arrays(
                    instance->indirect_prev_states,
                    instance->num_indirect_prev_states,
                    instance->indirect_prev_states_margin,
                    instance->num_prev_states_margin,
                    sizeof(instance->indirect_prev_states[0]),
                    fc_solve_state_compare_indirect_with_context,
                    NULL
                );

                instance->num_indirect_prev_states += instance->num_prev_states_margin;

                instance->num_prev_states_margin=0;
            }
            is_state_new = 1;
        }

    }
    else
    {
        *existing_state_val = pos_ptr->val;
        is_state_new = 0;
    }

#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_LIBREDBLACK_TREE)
    *existing_state_val = (fcs_state_extra_info_t *)rbsearch(new_state_val,
            instance->tree
            );
    is_state_new = ((*existing_state_val) == new_state_val);

#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_LIBAVL2_TREE)

    *existing_state_val = (fcs_state_extra_info_t *)
        fcs_libavl2_states_tree_insert(instance->tree, new_state_val);
    is_state_new = ((*existing_state_val) == NULL);

#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_GLIB_TREE)
    *existing_state_val = g_tree_lookup(instance->tree, (gpointer)new_state_key);
    if (*existing_state_val == NULL)
    {
        /* The new state was not found. Let's insert it.
         * The value must be the same as the key, so g_tree_lookup()
         * will return it. */
        g_tree_insert(
            instance->tree,
            (gpointer)new_state_key,
            (gpointer)new_state_val
            );
        is_state_new = 1;
    }
    else
    {
        is_state_new = 0;
    }



#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_GLIB_HASH)
    *existing_state_val = g_hash_table_lookup(instance->hash, 
            (gpointer)new_state_key);
    if (*existing_state_val == NULL)
    {
        /* The new state was not found. Let's insert it.
         * The value must be the same as the key, so g_tree_lookup()
         * will return it. */
        g_hash_table_insert(
            instance->hash,
            (gpointer)new_state_key,
            (gpointer)new_state_val

            );
        is_state_new = 1;
    }
    else
    {
        is_state_new = 0;
    }

#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_DB_FILE)
    {
        DBT key, value;
        key.data = new_state;
        key.size = sizeof(*new_state);
        if (instance->db->get(
            instance->db,
            NULL,
            &key,
            &value,
            0
            ) == 0)
        {
            /* The new state was not found. Let's insert it.
             * The value must be the same as the key, so g_tree_lookup()
             * will return it. */

            value.data = key.data;
            value.size = key.size;
            instance->db->put(
                instance->db,
                NULL,
                &key,
                &value,
                0);
            is_state_new = 1;
        }
        else
        {
            is_state_new = 0;
        }
    }
#elif (FCS_STATE_STORAGE == FCS_STATE_STORAGE_JUDY)
    {
        PWord_t * PValue;

        JHSI(PValue, instance->judy_array, new_state_key, sizeof(*new_state_key));

        /* later_todo : Handle out-of-memory. */
        if (*PValue == 0)
        {
            /* A new state. */
            is_state_new = 1;
            *PValue = (PWord_t)(*existing_state_val = new_state_val);
        }
        else
        {
            /* Already exists. */
            is_state_new = 0;
            *existing_state_val = (fcs_state_extra_info_t *)(*PValue);
        }
    }
#else
#error no define
#endif
    if (is_state_new)
    {
        /* The new state was not found in the cache, and it was already inserted */
        if (new_state_val->parent_val)
        {
            new_state_val->parent_val->num_active_children++;
        }
        instance->num_states_in_collection++;

        if (new_state_val->moves_to_parent != NULL)
        {
            new_state_val->moves_to_parent =
                fc_solve_move_stack_compact_allocate(
                    hard_thread,
                    new_state_val->moves_to_parent
                    );
        }

        return FCS_STATE_DOES_NOT_EXIST;
    }
    else
    {
        return FCS_STATE_ALREADY_EXISTS;
    }
}