Exemple #1
0
static void otfcc_build_bkblock(caryll_Buffer *buf, bk_Block *b, size_t *offsets) {
	for (uint32_t j = 0; j < b->length; j++) {
		switch (b->cells[j].t) {
			case b8:
				bufwrite8(buf, b->cells[j].z);
				break;
			case b16:
				bufwrite16b(buf, b->cells[j].z);
				break;
			case b32:
				bufwrite32b(buf, b->cells[j].z);
				break;
			case p16:
			case sp16:
				if (b->cells[j].p) {
					bufwrite16b(buf, getoffset(offsets, b, b->cells[j].p, 16));
				} else {
					bufwrite16b(buf, 0);
				}
				break;
			case p32:
			case sp32:
				if (b->cells[j].p) {
					bufwrite32b(buf, getoffset(offsets, b, b->cells[j].p, 32));
				} else {
					bufwrite32b(buf, 0);
				}
				break;
			default:
				break;
		}
	}
}
Exemple #2
0
// this function compares labels in label format:
//   [length] [value ...] [length] [value ...] [0]
static int matchlabel(const unsigned char *a, int asize, const unsigned char *b, int bsize, const unsigned char *ref, int refsize, int ahopsleft, int bhopsleft)
{
	int n, alen, blen, offset;

	// same pointer?
	if(a == b)
		return 1;

	if(asize < 1 || bsize < 1)
		return 0;

	// always ensure we get called without a pointer
	if(*a & 0xc0)
	{
		if(asize < 2)
			return 0;
		offset = getoffset(a, refsize, &ahopsleft);
		if(offset == -1)
			return 0;
		return matchlabel(ref + offset, refsize - offset, b, bsize, ref, refsize, ahopsleft, bhopsleft);
	}
	if(*b & 0xc0)
	{
		if(bsize < 2)
			return 0;
		offset = getoffset(b, refsize, &bhopsleft);
		if(offset == -1)
			return 0;
		return matchlabel(a, asize, ref + offset, refsize - offset, ref, refsize, ahopsleft, bhopsleft);
	}

	alen = *a & 0x3f;
	blen = *b & 0x3f;

	// must be same length
	if(alen != blen)
		return 0;

	// done?
	if(alen == 0)
		return 1;

	// length byte + length + first byte of next label
	if(asize < alen + 2)
		return 0;
	if(bsize < blen + 2)
		return 0;

	// compare the value
	for(n = 1; n < alen + 1; ++n)
	{
		if(a[n] != b[n])
			return 0;
	}

	// try next labels
	n = alen + 1;
	return matchlabel(a + n, asize - n, b + n, bsize - n, ref, refsize, ahopsleft, bhopsleft);
}
Exemple #3
0
/* putsubr - output a subr/fsubr */
LOCAL void putsubr(LVAL fptr, char *tag, LVAL val)
{
    sprintf(buf,"#<%s-%s: #",tag,funtab[getoffset(val)].fd_name);
    xlputstr(fptr,buf);
    sprintf(buf,AFMT,val);
    xlputstr(fptr,buf);
    xlputc(fptr,'>');
}
Exemple #4
0
void SCE_VStore_GetGridRegion (const SCE_SVoxelStorage *vs, SCEuint level,
                               const SCE_SIntRect3 *area_,
                               SCE_SGrid *grid, int ox, int oy, int oz)
{
    SCEuint x, y, z, x2, y2, z2;
    SCEuint w, h, d;
    int p1[3], p2[3], start[3], bleup[3];
    size_t offset1, offset2;
    SCE_SIntRect3 rect, area;
    SCE_SVoxelStorageLevel *sl = NULL;
    unsigned char *data = SCE_Grid_GetRaw (grid);

    sl = &vs->levels[level];
    SCE_VStore_GetDimensionsLevel (vs, level, &w, &h, &d);
    SCE_Rectangle3_Set (&rect, 0, 0, 0, w, h, d);

    area = *area_;
    if (!SCE_Rectangle3_IsInside (&rect, &area)) {
        /* fillup user buffer with vacuum */
        w = SCE_Rectangle3_GetWidth (area_);
        h = SCE_Rectangle3_GetHeight (area_);
        d = SCE_Rectangle3_GetDepth (area_);
        for (z = oz; z < d + oz; z++) {
            for (y = oy; y < h + oy; y++) {
                for (x = ox; x < w + ox; x++) {
                    offset1 = SCE_Grid_GetOffset (grid, x, y, z);
                    memcpy (&data[offset1], vs->vacuum, vs->data_size);
                }
            }
        }

        SCE_Rectangle3_Intersection (&rect, area_, &area);
    }

    SCE_Rectangle3_GetPointsv (&area, p1, p2);
    SCE_Rectangle3_GetPointsv (area_, start, bleup);
    ox += p1[0] - start[0];
    oy += p1[1] - start[1];
    oz += p1[2] - start[2];

    w = SCE_Grid_GetWidth (grid);
    h = SCE_Grid_GetHeight (grid);
    d = SCE_Grid_GetDepth (grid);

    for (z2 = p1[2], z = oz; z2 < p2[2] && z < d; z2++, z++) {
        for (y2 = p1[1], y = oy; y2 < p2[1] && y < h; y2++, y++) {
            for (x2 = p1[0], x = ox; x2 < p2[0] && x < w; x2++, x++) {
                offset1 = SCE_Grid_GetOffset (grid, x, y, z);
                offset2 = getoffset (vs, level, x2, y2, z2);
                memcpy (&data[offset1], &sl->data[offset2], vs->data_size);
            }
        }
    }
}
static int getarg( void )
{
    int i;

    if( *cp & 0x0F )
    {
        i = regs[ *cp & 0xF ];
        cp++; offset++;
        return(i);
    }
    return( getoffset() );
}
Exemple #6
0
void SCE_VStore_GetPoint (const SCE_SVoxelStorage *vs, SCEuint level,
                          SCEuint x, SCEuint y, SCEuint z, void *data)
{
    size_t offset = getoffset (vs, level, x, y, z);
    if (x >= vs->levels[0].width ||
        y >= vs->levels[0].height ||
        z >= vs->levels[0].depth) {
        /* just copy a 'vacuum' voxel */
        memcpy (data, vs->vacuum, vs->data_size);
    } else {
        memcpy (data, &vs->levels[level].data[offset], vs->data_size);
    }
}
Exemple #7
0
char* reg(FILE* fp,Operand h,int flag){
	if(h->kind==CONSTANT){
		fprintf(fp,"li $t%d, %d\n",flag,h->u.value);
		if(flag==1)
			return "$t1";
		else if(flag==2)
			return "$t2";
		else 
			return "$t3";
	}
	if(getoffset(h)!=-1){
		if(flag==1){
			fprintf(fp,"lw $t1, %d($sp)\n",getoffset(h));
			return "$t1";
		}
		if(flag==2){
			fprintf(fp,"lw $t2, %d($sp)\n",getoffset(h));
			return "$t2";
		}
		if(flag==3){
			fprintf(fp,"lw $t3, %d($sp)\n",getoffset(h));
			return "$t3";
		}
	}
	else{
		setoffset(h,stackoffset);
		stackoffset=stackoffset+4;
		if(flag==1)
			return "$t1";
		else if(flag==2)
			return "$t2";
		else
			return "$t3";
	}

}
Exemple #8
0
void SCE_VStore_SetPoint (SCE_SVoxelStorage *vs, SCEuint x, SCEuint y,
                          SCEuint z, const void *data)
{
    SCE_SIntRect3 r;
    size_t offset;

    if (x >= vs->levels[0].width ||
        y >= vs->levels[0].height ||
        z >= vs->levels[0].depth)
        return;

    offset = getoffset (vs, 0, x, y, z);
    memcpy (&vs->levels[0].data[offset], data, vs->data_size);
    SCE_Rectangle3_Set (&r, x, y, z, x+1, y+1, z+1);
    SCE_VStore_PushZone (vs, &r, 0);
}
Exemple #9
0
int 
get_myportion()
{
	char           *offsetfile;
	int		i = 0;
	long int	ipos;
	char           *lst;
	offsetfile = malloc(sizeof(offsetdir) + sizeof(offsetext) + sizeof(facil));
	strcpy(offsetfile, offsetdir);
	strcat(offsetfile, facil);
	strcat(offsetfile, offsetext);
	i = getoffset(offsetfile);
	lst = show_myportion(i);
	if (lst)
		putoffset(offsetfile, lst);
	free(offsetfile);
	return 0;
}
Exemple #10
0
static void SCE_VStore_ComputeLOD (SCE_SVoxelStorage *vs, SCEuint level,
                                   int x, int y, int z)
{
    unsigned char buf[28] = {0}; /* pray the Lord that data_size = 1 */
    float kernel[28] = {
        /* slice 0 */
        1.0/8.0, 1.0/4.0, 1.0/8.0,
        1.0/4.0, 1.0/2.0, 1.0/4.0,
        1.0/8.0, 1.0/4.0, 1.0/8.0,

        /* slice 1 */
        1.0/4.0, 1.0/2.0, 1.0/4.0,
        1.0/2.0, 1.0/1.0, 1.0/2.0,
        1.0/4.0, 1.0/2.0, 1.0/4.0,

        /* slice 2 */
        1.0/8.0, 1.0/4.0, 1.0/8.0,
        1.0/4.0, 1.0/2.0, 1.0/4.0,
        1.0/8.0, 1.0/4.0, 1.0/8.0,
    };
    int p1[3], p2[3];
    SCE_SIntRect3 r;
    float value = 0.0;
    size_t offset;
    int i;

    p1[0] = x * 2 - 1;
    p1[1] = y * 2 - 1;
    p1[2] = z * 2 - 1;
    p2[0] = x * 2 + 2;
    p2[1] = y * 2 + 2;
    p2[2] = z * 2 + 2;

    SCE_Rectangle3_Setv (&r, p1, p2);
    SCE_VStore_GetRegion (vs, level - 1, &r, buf);

    for (i = 0; i < 28; i++)
        value += (kernel[i] * buf[i]) / 256.0;

    value /= 8.0;

    offset = getoffset (vs, level, x, y, z);
    vs->levels[level].data[offset] = value * 256.0;
}
Exemple #11
0
appkey_t 
__appkey_getbyname(char *app, char *key)
{
    struct appkey *ak;

    if (NULL==app) {
        return os_assert_value(INVALID_APPKEY);
    }
    else if (NULL==key) {
        return os_assert_value(INVALID_APPKEY);
    }

    ak = getbyname(app, key);
    if (NULL==ak) {
        return INVALID_APPKEY;
    }
    
    return ak_make(getidx(ak), getoffset(ak));
}
Exemple #12
0
void SCE_VStore_GetRegion (const SCE_SVoxelStorage *vs, SCEuint level,
                           const SCE_SIntRect3 *area_, void *data_)
{
    SCEuint y, z, y2, z2;
    int p1[3], p2[3], start[3], bleup[3];
    int w, h, d, w2;
    SCE_SIntRect3 rect, area;
    SCE_SVoxelStorageLevel *sl = NULL;
    unsigned char *data = data_;

    sl = &vs->levels[level];
    SCE_VStore_GetDimensionsLevel (vs, level, &w, &h, &d);
    SCE_Rectangle3_Set (&rect, 0, 0, 0, w, h, d);

    w = SCE_Rectangle3_GetWidth (area_);
    h = SCE_Rectangle3_GetHeight (area_);

    area = *area_;
    if (!SCE_Rectangle3_IsInside (&rect, &area)) {
        /* fillup user buffer with vacuum */
        size_t i, num = SCE_Rectangle3_GetArea (area_);
        for (i = 0; i < num; i++)
            memcpy (&data[i * vs->data_size], vs->vacuum, vs->data_size);
        SCE_Rectangle3_Intersection (&rect, area_, &area);
    }

    w2 = SCE_Rectangle3_GetWidth (&area);
    SCE_Rectangle3_GetPointsv (&area, p1, p2);
    SCE_Rectangle3_GetPointsv (area_, start, bleup);
    start[0] = p1[0] - start[0];
    start[1] = p1[1] - start[1];
    start[2] = p1[2] - start[2];

    if (w2 > 0 && p2[0] > 0 && p2[1] > 0 && p2[2] > 0) {
        for (z = p1[2], z2 = start[2]; z < p2[2]; z++, z2++) {
            for (y = p1[1], y2 = start[1]; y < p2[1]; y++, y2++) {
                size_t offset = getoffset (vs, level, p1[0], y, z);
                size_t offset2 = w * (h * z2 + y2) + start[0];
                memcpy (&data[offset2], &sl->data[offset], vs->data_size * w2);
            }
        }
    }
}
Exemple #13
0
int
ntpd_adjtime(double d)
{
	struct timeval	tv, olddelta;
	int		synced = 0;
	static int	firstadj = 1;

	d += getoffset();
	if (d >= (double)LOG_NEGLIGIBLE_ADJTIME / 1000 ||
	    d <= -1 * (double)LOG_NEGLIGIBLE_ADJTIME / 1000)
		log_info("adjusting local clock by %fs", d);
	else
		log_debug("adjusting local clock by %fs", d);
	d_to_tv(d, &tv);
	if (adjtime(&tv, &olddelta) == -1)
		log_warn("adjtime failed");
	else if (!firstadj && olddelta.tv_sec == 0 && olddelta.tv_usec == 0)
		synced = 1;
	firstadj = 0;
	return (synced);
}
Exemple #14
0
void SCE_VStore_SetRegion (SCE_SVoxelStorage *vs, const SCE_SIntRect3 *area_,
                           const void *data_)
{
    SCEuint y, z, y2, z2;
    int p1[3], p2[3], start[3], bleup[3];
    int w, h, d, w2;
    SCE_SIntRect3 rect, area;
    const unsigned char *data = data_;

    SCE_VStore_GetDimensionsLevel (vs, 0, &w, &h, &d);
    SCE_Rectangle3_Set (&rect, 0, 0, 0, w, h, d);

    w = SCE_Rectangle3_GetWidth (area_);
    h = SCE_Rectangle3_GetHeight (area_);

    area = *area_;
    if (!SCE_Rectangle3_IsInside (&rect, &area))
        SCE_Rectangle3_Intersection (&rect, area_, &area);

    w2 = SCE_Rectangle3_GetWidth (&area);
    SCE_Rectangle3_GetPointsv (&area, p1, p2);
    SCE_Rectangle3_GetPointsv (area_, start, bleup);
    start[0] = p1[0] - start[0];
    start[1] = p1[1] - start[1];
    start[2] = p1[2] - start[2];

    for (z = p1[2], z2 = start[2]; z < p2[2]; z++, z2++) {
        for (y = p1[1], y2 = start[1]; y < p2[1]; y++, y2++) {
            size_t offset = getoffset (vs, 0, p1[0], y, z);
            size_t offset2 = w * (h * z2 + y2) + start[0];
            memcpy (&vs->levels[0].data[offset], &data[offset2],
                    vs->data_size * w2);
        }
    }

    SCE_VStore_PushZone (vs, &area, 0);
}
Exemple #15
0
int main(int argc, char **argv)
{
    int c,s;
    int ofs;
    char noheader = 0;

    FILE *d64handle, *prghandle;
    unsigned char *d64buf;
    unsigned char *ptr;

    if (argc < 4)
    {
        printf("Usage: d642prg <d64 image name> <program to extract> <dos filename for prg>\n"
               "Use _ to represent spaces in the c64 filename. Use -h switch after the\n"
               "filenames to skip the startaddress.\n");
        return 1;
    }

    if (argc > 4)
    {
        for (c = 4; c < argc; c++)
        {
            if ((argv[c][0] == '-') || (argv[c][0] == '/'))
            {
                switch(toupper(argv[c][1]))
                {
                case 'H':
                    noheader = 1;
                    break;
                }
            }
        }
    }

    d64handle = fopen(argv[1], "rb");
    if (!d64handle)
    {
        printf("Couldn't open d64 image.\n");
        return 1;
    }

    d64buf = malloc(174848);
    if (!d64buf)
    {
        printf("No memory for d64 image.\n");
        return 1;
    }

    prghandle = fopen(argv[3], "wb");
    if (!prghandle)
    {
        fclose(d64handle);
        printf("Couldn't open destination.\n");
        return 1;
    }
    fread(d64buf,174848,1,d64handle);
    fclose(d64handle);

    s = 0;
    for (c = 0; c < 35; c++)
    {
        firstsecttbl[c] = s;
        s += snumtable[c];
    }

    ptr = &d64buf[getoffset(18,1)];
    ofs = 2;

    for (;;)
    {
        for (c = 0; c<16; c++)
        {
            if (ptr[ofs+3+c] == 0xa0) ptr[ofs+3+c] = 0x5f;
            if (ptr[ofs+3+c] == 0x20) ptr[ofs+3+c] = 0x5f;
        }
        ptr[ofs+3+16] = 0;

        if ((ptr[ofs] & 0x83)==0x82)
        {
            int a;
            int err = 0;
            for (a = 0; a < strlen(argv[2]); a++)
            {
                if (toupper(ptr[ofs+3+a]) != toupper(argv[2][a]))
                {
                    err = 1;
                    break;
                }
            }
            if (!err)
            {
                printf("Found on track %d sector %d\n", ptr[ofs+1],ptr[ofs+2]);
                ptr = &d64buf[getoffset(ptr[ofs+1],ptr[ofs+2])];
                for (;;)
                {
                    if (ptr[0])
                    {
                        if (!noheader)
                        {
                            fwrite(&ptr[2], 254, 1, prghandle);
                        }
                        else
                        {
                            fwrite(&ptr[4], 252, 1, prghandle);
                            noheader = 0;
                        }
                        ptr = &d64buf[getoffset(ptr[0],ptr[1])];
                        printf(".");
                        fflush(stdout);
                    }
                    else
                    {
                        if (!noheader)
                        {
                            fwrite(&ptr[2], ptr[1]-1, 1, prghandle);
                        }
                        else
                        {
                            fwrite(&ptr[4], ptr[1]-3, 1, prghandle);
                            noheader = 0;
                        }
                        printf(".\n");
                        break;
                    }
                }
                printf("File extracted successfully.\n");
                fclose(prghandle);
                return 0;
            }
        }
        ofs += 32;
        if (ofs >= 256)
        {
            if (ptr[0])
            {
                ptr = &d64buf[getoffset(ptr[0],ptr[1])];
                ofs = 2;
            }
            else
            {
                printf("File not found.\n");
                return 1;
            }
        }
    }
}
Exemple #16
0
static int tzparse(const char *name, register struct state *const sp, const int lastditch)
{
	const char *stdname;
	const char *dstname;
	size_t stdlen;
	size_t dstlen;
	long stdoffset;
	long dstoffset;
	register time_t *atp;
	register unsigned char *typep;
	register char *cp;


	INITIALIZE(dstname);
	stdname = name;

	if (lastditch) {
		stdlen = strlen(name);	/* length of standard zone name */
		name += stdlen;
		if (stdlen >= sizeof sp->chars)
			stdlen = (sizeof sp->chars) - 1;
		stdoffset = 0;
	} else {
		name = getzname(name);
		stdlen = name - stdname;
		if (stdlen < 3)
			return -1;
		if (*name == '\0')
			return -1;
		name = getoffset(name, &stdoffset);
		if (name == NULL)
			return -1;
	}

	sp->leapcnt = 0;			/* so, we're off a little */

	if (*name != '\0') {
		dstname = name;
		name = getzname(name);
		dstlen = name - dstname;	/* length of DST zone name */
		if (dstlen < 3)
			return -1;
		if (*name != '\0' && *name != ',' && *name != ';') {
			name = getoffset(name, &dstoffset);
			if (name == NULL)
				return -1;
		} else
			dstoffset = stdoffset - SECSPERHOUR;

		/* Go parsing the daylight saving stuff */
		if (*name == ',' || *name == ';') {
			struct rule start;
			struct rule end;
			register int year;
			register time_t janfirst;
			time_t starttime;
			time_t endtime;

			++name;
			if ((name = getrule(name, &start)) == NULL)
				return -1;
			if (*name++ != ',')
				return -1;
			if ((name = getrule(name, &end)) == NULL)
				return -1;
			if (*name != '\0')
				return -1;

			sp->typecnt = 2;	/* standard time and DST */

			/*
			 ** Two transitions per year, from EPOCH_YEAR to 2037.
			 */
			sp->timecnt = 2 * (2037 - EPOCH_YEAR + 1);

			if (sp->timecnt > TZ_MAX_TIMES)
				return -1;

			sp->ttis[0].tt_gmtoff = -dstoffset;
			sp->ttis[0].tt_isdst = 1;
			sp->ttis[0].tt_abbrind = (int) (stdlen + 1);
			sp->ttis[1].tt_gmtoff = -stdoffset;
			sp->ttis[1].tt_isdst = 0;
			sp->ttis[1].tt_abbrind = 0;

			atp = sp->ats;
			typep = sp->types;
			janfirst = 0;

			for (year = EPOCH_YEAR; year <= 2037; ++year) {
				starttime = transtime(janfirst, year, &start, stdoffset);
				endtime = transtime(janfirst, year, &end, dstoffset);
				if (starttime > endtime) {
					*atp++ = endtime;
					*typep++ = 1;	/* DST ends */
					*atp++ = starttime;
					*typep++ = 0;	/* DST begins */
				} else {
					*atp++ = starttime;
					*typep++ = 0;	/* DST begins */
					*atp++ = endtime;
					*typep++ = 1;	/* DST ends */
				}

				janfirst += year_lengths[isleap(year)] * SECSPERDAY;
			}

		} else {
			register long theirstdoffset;
			register long theirdstoffset;
			register long theiroffset;
			register int isdst;
			register int i;
			register int j;

			if (*name != '\0')
				return -1;
			/*
			   Initial values of theirstdoffset and theirdstoffset.
			 */
			theirstdoffset = 0;
			for (i = 0; i < sp->timecnt; ++i) {
				j = sp->types[i];
				if (!sp->ttis[j].tt_isdst) {
					theirstdoffset = -sp->ttis[j].tt_gmtoff;
					break;
				}
			}
			theirdstoffset = 0;
			for (i = 0; i < sp->timecnt; ++i) {
				j = sp->types[i];
				if (sp->ttis[j].tt_isdst) {
					theirdstoffset = -sp->ttis[j].tt_gmtoff;
					break;
				}
			}
			/*
			 ** Initially we're assumed to be in standard time.
			 */
			isdst = FALSE;
			theiroffset = theirstdoffset;
			/*
			 ** Now juggle transition times and types
			 ** tracking offsets as you do.
			 */
			for (i = 0; i < sp->timecnt; ++i) {
				j = sp->types[i];
				sp->types[i] = (unsigned char) sp->ttis[j].tt_isdst;
				if (sp->ttis[j].tt_ttisgmt) {
					/* No adjustment to transition time */
				} else {
					/*
					 ** If summer time is in effect, and the
					 ** transition time was not specified as
					 ** standard time, add the summer time
					 ** offset to the transition time;
					 ** otherwise, add the standard time
					 ** offset to the transition time.
					 */
					/*
					 ** Transitions from DST to DDST
					 ** will effectively disappear since
					 ** POSIX provides for only one DST
					 ** offset.
					 */
					if (isdst && !sp->ttis[j].tt_ttisstd) {
						sp->ats[i] += dstoffset - theirdstoffset;
					} else {
						sp->ats[i] += stdoffset - theirstdoffset;
					}
				}
				theiroffset = -sp->ttis[j].tt_gmtoff;
				if (sp->ttis[j].tt_isdst)
					theirdstoffset = theiroffset;
				else
					theirstdoffset = theiroffset;
			}
			/*
			 ** Finally, fill in ttis.
			 ** ttisstd and ttisgmt need not be handled.
			 */
			sp->ttis[0].tt_gmtoff = -stdoffset;
			sp->ttis[0].tt_isdst = FALSE;
			sp->ttis[0].tt_abbrind = 0;
			sp->ttis[1].tt_gmtoff = -dstoffset;
			sp->ttis[1].tt_isdst = TRUE;
			sp->ttis[1].tt_abbrind = (int) (stdlen + 1);
			sp->typecnt = 2;
		}
	} else {
		dstlen = 0;
		sp->typecnt = 1;		/* only standard time */
		sp->timecnt = 0;
		sp->ttis[0].tt_gmtoff = -stdoffset;
		sp->ttis[0].tt_isdst = 0;
		sp->ttis[0].tt_abbrind = 0;
	}

	sp->charcnt = (int) (stdlen + 1);
	if (dstlen != 0)
		sp->charcnt += (int) (dstlen + 1);
	if ((size_t) sp->charcnt > sizeof sp->chars)
		return -1;
	cp = sp->chars;
	(void) strncpy(cp, stdname, stdlen);
	cp += stdlen;
	*cp++ = '\0';
	if (dstlen != 0) {
		(void) strncpy(cp, dstname, dstlen);
		*(cp + dstlen) = '\0';
	}
	return 0;
}
Exemple #17
0
int
main(int argc, char **argv)
{
    char *p, *endp;
    struct passwd *pw;
    int arglen, ch, len, readstdin;

#ifndef DEBUG
    if (geteuid())
        errx(1, "NOT super-user");
#endif

    nosync = NULL;
    readstdin = 0;

    /*
     * Test for the special case where the utility is called as
     * "poweroff", for which it runs 'shutdown -p now'.
     */
    if ((p = rindex(argv[0], '/')) == NULL)
        p = argv[0];
    else
        ++p;
    if (strcmp(p, "poweroff") == 0) {
        if (getopt(argc, argv, "") != -1)
            usage((char *)NULL);
        argc -= optind;
        argv += optind;
        if (argc != 0)
            usage((char *)NULL);
        dopower = 1;
        offset = 0;
        (void)time(&shuttime);
        goto poweroff;
    }

    while ((ch = getopt(argc, argv, "-hknopr")) != -1)
        switch (ch) {
        case '-':
            readstdin = 1;
            break;
        case 'h':
            dohalt = 1;
            break;
        case 'k':
            killflg = 1;
            break;
        case 'n':
            nosync = "-n";
            break;
        case 'o':
            oflag = 1;
            break;
        case 'p':
            dopower = 1;
            break;
        case 'r':
            doreboot = 1;
            break;
        case '?':
        default:
            usage((char *)NULL);
        }
    argc -= optind;
    argv += optind;

    if (argc < 1)
        usage((char *)NULL);

    if (killflg + doreboot + dohalt + dopower > 1)
        usage("incompatible switches -h, -k, -p and -r");

    if (oflag && !(dohalt || dopower || doreboot))
        usage("-o requires -h, -p or -r");

    if (nosync != NULL && !oflag)
        usage("-n requires -o");

    getoffset(*argv++);

poweroff:
    if (*argv) {
        for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
            arglen = strlen(*argv);
            if ((len -= arglen) <= 2)
                break;
            if (p != mbuf)
                *p++ = ' ';
            memmove(p, *argv, arglen);
            p += arglen;
        }
        *p = '\n';
        *++p = '\0';
    }

    if (readstdin) {
        p = mbuf;
        endp = mbuf + sizeof(mbuf) - 2;
        for (;;) {
            if (!fgets(p, endp - p + 1, stdin))
                break;
            for (; *p &&  p < endp; ++p);
            if (p == endp) {
                *p = '\n';
                *++p = '\0';
                break;
            }
        }
    }
    mbuflen = strlen(mbuf);

    if (offset)
        (void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
    else
        (void)printf("Shutdown NOW!\n");

    if (!(whom = getlogin()))
        whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";

#ifdef DEBUG
    (void)putc('\n', stdout);
#else
    (void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
    {
        int forkpid;

        forkpid = fork();
        if (forkpid == -1)
            err(1, "fork");
        if (forkpid)
            errx(0, "[pid %d]", forkpid);
    }
    setsid();
#endif
    openlog("shutdown", LOG_CONS, LOG_AUTH);
    loop();
    return(0);
}
Exemple #18
0
/* GQUERY -- Determine if the value of a parameter given by the user is OK.
 * Also, store the new value in the parameter; in the case of a list
 * structured parameter, the new value is the name of a new list file.
 * This routine is called by EPARAM to verify that the new parameter value
 * is inrange and set the new value if so.
 */
char *
gquery (
  struct param *pp,
  char	*string
)
{
	register char *ip;
	char	buf[SZ_LINE];
	char	*query_status, *nlp, *errmsg;
	int	arrflag, offset, bastype, batch;
	struct	operand o;
	char	*strcpy(), *index();

	bastype = pp->p_type & OT_BASIC;
	batch   = firstask->t_flags & T_BATCH;
	arrflag = pp->p_type & PT_ARRAY;

	if (arrflag)
	    offset = getoffset(pp);

	if (batch) {
	    errmsg = e1;
	    return (errmsg);
	} else
	    query_status = strcpy (buf, string);

	ip = buf;

	/* Set o to the current value of the parameter.  Beware that some
	 * of the logical branches which follow assume that struct o has
	 * been initialized to the current value of the parameter.
	 */
	if (pp->p_type & PT_LIST) {
	    setopundef (&o);
	} else if (arrflag) {
	    poffset (offset);
	    paramget (pp, FN_VALUE);
	    o = popop ();
	} else
	    o = pp->p_valo;

	/* Handle eof, a null-length line (lone carriage return),
	 * and line with more than SZ_LINE chars.  Ignore leading whitespace
	 * if basic type is not string.
	 */
	if (query_status == NULL)
	    goto testval;

	/* Ignore leading whitespace if it is not significant for this
	 * datatype.  Do this before testing for empty line, so that a
	 * return such as " \n" is equivalent to "\n".  I.e., do not
	 * penalize the user if they type the space bar by accident before
	 * typing return to accept the default value.
	 */
	if (bastype != OT_STRING || (pp->p_type & PT_LIST))
	    while (*ip == ' ' || *ip == '\t')
		ip++;

	if (*ip == '\n') {
	    /* Blank lines usually just accept the current value
	     * but if the param in a string and is undefined,
	     * it sets the string to a (defined) nullstring.
	     */
	    if (bastype == OT_STRING && opundef (&o)) {
		*ip = '\0';
		o = makeop (ip, bastype);
	    } else
		goto testval;
	}

	/* Cancel the newline. */
	if ((nlp = index (ip, '\n')) != NULL)
	    *nlp = '\0';

	/* Finally, we have handled the pathological cases.
	 */
	if (pp->p_type & PT_LIST)
	    o = makeop (string, OT_STRING);
	else
	    o = makeop (ip, bastype);

testval:   
	if (*string == '@')
	    errmsg = "OK";
	else if (pp->p_type & PT_LIST)
	    errmsg = "OK";
	else if (inrange (pp, &o))
	    errmsg = "OK";
	else {
	    errmsg = e2;
	    return (errmsg);
	}

	if (cldebug) {
	    eprintf ("changing `%s.p_val' to ", pp->p_name);
	    fprop (stderr, &o);
	    eprintf ("\n");
	}

	/* Update param with new value.
	 */
	pushop (&o);
	if (arrflag)
	    poffset (offset);

	paramset (pp, FN_VALUE);
	pp->p_flags |= P_SET;

	return ("OK");
}
Exemple #19
0
Fichier : main.c Projet : moikop/ab
int processData(tdns* dns,char** argv,char* cmd,FILE* logf) {

    tdomain data;
    tdomain td;
    char ip_origen[IP_MAX];
    char ip_destino[IP_MAX];
    char msg[300];

    if(strcmp(argv[1],CMD_SEND)==0) {
        if(urlExists(*dns,argv[2])!=RES_OK) return RES_ERROR;
        if(urlExists(*dns,argv[3])!=RES_OK) return RES_ERROR;
        getValue(dns,argv[2],&data);
        strcpy(ip_origen,data.ip);
        getValue(dns,argv[3],&data);
        strcpy(ip_destino,data.ip);
        encryptMsg(msg,data.offset);
        log(logf,CMD_SEND,argv[2],ip_origen,argv[3],ip_destino,argv[3],msg);
        printf("Mensaje encriptado: %s\n",msg);
    }
    else if(strcmp(argv[1],CMD_GETIP)==0) {
            printf("Entré en  getip\n");
        if(urlExists(*dns,argv[2])!=RES_OK) return RES_ERROR;
        if(urlExists(*dns,argv[3])!=RES_OK) return RES_ERROR;
        getValue(dns,argv[2],&data);
        strcpy(ip_origen,data.ip);
        getValue(dns,argv[3],&data);
        strcpy(ip_destino,data.ip);
        log(logf,CMD_GETIP,argv[2],ip_origen,argv[3],ip_destino,"","");
        printf("Origen: %s %s\nDestino: %s %s\n",argv[2],ip_origen,argv[3],ip_destino);
    }
    else if(strcmp(argv[1],CMD_ADDDOMAIN)==0) {
        if(urlExists(*dns,argv[2])==RES_OK) {
            printf("Ya existe %s.\n",argv[2]);
            return RES_ERROR;
        }
        strcpy(td.domain,argv[2]);
        strcpy(td.ip,argv[3]);
        genoffset(td.domain);
        getoffset(td.domain,&(td.offset));
        AB_Crear(&(td.subab),sizeof(tdomain));
        if(addDomain(dns,argv[2],&td)!=RES_OK) return RES_ERROR;
        log(logf,CMD_ADDDOMAIN,argv[2],argv[3],"","","","");
        printf("Se agrego %s con direccion ip %s.\n",argv[2],argv[3]);
    }
    else if(strcmp(argv[1],CMD_DELETEDOMAIN) == 0) {
        if(urlExists(*dns,argv[2])!=RES_OK) {
            printf("No existe %s para eliminar.\n",argv[2]);
            return RES_ERROR;
        }
        getValue(dns,argv[2],&data);
        printf("Dato obtenido: %s %s.\n",data.domain,data.ip);
        strcpy(ip_origen,data.ip);
        deleteDomain(dns,argv[2]);
        log(logf,CMD_DELETEDOMAIN,argv[2],ip_origen,"","","","");
        printf("Se elimino a %s con ip %s.\n",argv[2],ip_origen);
    } else {
        printf("Comando equivocado.\n");
        showHelp(argv[0]);
        return RES_ERROR;
    }
    return RES_OK;
}
Exemple #20
0
/* Calculate the effective mode for the given parameter, considering
 *   its own mode and the modes for the current task and the cl.
 *   Inhibit query mode if set on the command line or hidden but
 *   enable it if the param is not in range.  The range test cannot be done
 *   here for list params because we'd have to read the list to do it.
 * Return a bit-mapped code (built up of M_XXX bits) of the result.
 * Since learn mode is not defined at the parameter level, pp == NULL
 *   is used to indicate we are just interested in M_LEARN info.
 * Local variables cannot be prompted for so it is an error if their
 *   values are undefined.
 */
int 
effmode (struct param *pp)
{
	static	char	*localerr =
		"Attempt to access undefined local variable `%s'.\n";

	register int	mode, modebits;
	struct	operand o;
	int	clmode, ltmode, pkmode, offset;
	int	interactive;


	/* Check if param is a local variable.  If it is undefined
	 * this is an ERR, if defined just return mode 0 to defeat
	 * querying.
	 */
	if (pp != NULL) {
	    if (pp->p_mode & M_LOCAL) {
		if (opundef (&(pp->p_valo)))
		    cl_error (E_UERR, localerr, pp->p_name);
		return (0);
	    }
	}

	/* Determine whether or not the current task was called interactively.
	 * Menu mode is only permitted for tasks called interactively.
	 */
	interactive = 0;
	if (prevtask)
	    interactive = (prevtask->t_flags & (T_INTERACTIVE|T_BATCH));
	if (interactive)
	    modebits = (M_QUERY|M_HIDDEN|M_MENU);
	else
	    modebits = (M_QUERY|M_HIDDEN);

	clmode = scanmode (firstask->t_modep->p_val.v_s);
	ltmode = scanmode (currentask->t_modep->p_val.v_s);
	pkmode = -1;

	mode = 0;
	if (pp != NULL) {
	    /* In determining the effective mode we go up the hierarchy of
	     * parameter, task, package, cl.  The mode is taken from the first
	     * of these which is not automatic.
	     */
	    if ( (mode = (pp->p_mode & modebits)) )
		;
	    else if ( (mode = (ltmode & modebits)) )
		;
	    else {
		/* Check the mode of the package to which the ltask belongs,
		 * which need not be the "current" package.
		 */
		struct pfile *pfp;

		if ( (pfp = currentask->t_ltp->lt_pkp->pk_pfp) ) {
	 	    struct param   *ppx;
	 	    ppx = paramfind (pfp, "mode", 0, YES);
	 	    if ((ppx != NULL)  &&  (ppx != (struct param *)ERR))
	 		pkmode = scanmode (ppx->p_val.v_s);
	 	}

		if (pkmode > 0 && (mode = (pkmode & modebits)))
		    ;
		else if ( (mode = (clmode & modebits)) )
		    ;
		else
		    mode = M_AUTO;
	    }

	    /* Defeat query mode if param set on command line or it's a
	     * hidden param or if menu mode is in effect.
	     */
	    if ((pp->p_flags & P_CLSET) || (pp->p_mode & M_HIDDEN) ||
		(mode & M_MENU))
		mode &= ~M_QUERY;

	    /* Query unconditionally if param is out of range or undefined.
	     */
	    if (!(mode & M_QUERY) && !(pp->p_type & PT_LIST)) {

		/* To check whether an array element is in range we
		 * must get the appropriate element of the array.  However
		 * the stack must be reset so that the element can be accessed
		 * again by the calling routine.
		 */
		if (pp->p_type & PT_ARRAY) {
		    offset = getoffset(pp);

		    poffset (offset);
		    paramget(pp, FN_VALUE);

		    poffset (offset);

		    o = popop();
		    if (!inrange (pp, &o))
			mode |= M_QUERY;

		} else {
		    /* Use temporary scratch variable for range checking in
		     * this case; sometimes the value of an enumerated
		     * parameter would get trashed in the process.  There is
		     * probably some deeper, darker bug lurking down there,
		     * but haven't found it yet, so this will suffice for now.
		     */
		    o = pp->p_valo;
		    if (!inrange (pp, &o))
			mode |= M_QUERY;
		}
	    }
	}

	/* Enable learn mode only for tasks called interactively - don't bother
	 * to learn parameters if the task is called from a script or in batch
	 * mode.
	 */
	if (interactive)
	    mode |= (clmode & M_LEARN) | (ltmode & M_LEARN);

	return (mode);
}
Exemple #21
0
/* QUERY -- Query the user for the value of a parameter.  Prompt with the
 *  current value if any.  Keep this up until we can push a reasonable value.
 *  Also, store the new value in the parameter (except for list params, where,
 *  since the values are not kept, all that may change is P_LEOF if seen).
 * Give prompt, or name if none, current value and range if int, real or 
 *   filename.  Accept CR to leave value unchanged, else take the string
 *   entered to be the new value.  Repeat until parameter value is in range.
 * We mean to talk straight to the user here; thus, interact with the real
 *   stdio, not the effective t_stdio, so that redirections do not get in
 *   the way.  In batch mode, a forced query is handled by writing a
 *   message on the terminal of the parent cl (the original stderr), and
 *   leaving some info describing the query in a file in uparm (if there is
 *   no uparm, we abort).  We then loop, waiting for the user to run "service"
 *   in the interactive cl to service the query, leaving the answer in a
 *   another file which we read and then delete.  If we wait a long time and
 *   get no response, we timeout.
 */
void 
query (struct param *pp)
{
	static	char *oormsg =
		"ERROR: Parameter value is out of range; try again";
	register char *ip;
	char	buf[SZ_PROMPTBUF+1];
	struct	operand o;
	int	bastype, batch, arrflag, offset=0, n_ele, max_ele, fd;
	char	*index(), *nlp, *nextstr();
	char	*bkg_query(), *query_status;
	char	*abuf;

	bastype = pp->p_type & OT_BASIC;
	batch = firstask->t_flags & T_BATCH;
	arrflag = pp->p_type & PT_ARRAY;

	if (arrflag) {			/* We may access the array many     */
	    offset = getoffset (pp);	/* times, so save the offset and    */
					/* push it when necessary.	    */
	    poffset (offset);
	    max_ele = size_array (pp) - offset;
	} else
	    max_ele = 1;


	forever {
	    if (batch) {
		/* Query from a background job.
		 */
		query_status = bkg_query (buf, SZ_PROMPTBUF, pp);

	    } else if (pp->p_type & (PT_GCUR|PT_IMCUR)) {
		/* Read a graphics cursor.
		 */
		char	source[33];
		int	cursor;

		/* Determine the source of graphics cursor input, chosen from
		 * either the graphics or image cursor or the terminal.
		 */
		if (pp->p_type & PT_GCUR) {
		    if (c_envfind ("stdgcur", source, 32) <= 0)
			strcpy (source, "stdgraph");
		} else {
		    if (c_envfind ("stdimcur", source, 32) <= 0)
			strcpy (source, "stdimage");
		}

		if (strcmp (source, "stdgraph") == 0)
		    cursor = STDGRAPH;
		else if (strcmp (source, "stdimage") == 0)
		    cursor = STDIMAGE;
		else
		    goto text_query;		/* get value from terminal */

		/* Read a physical graphics cursor.
		 */
		pp->p_flags &= ~P_LEOF;
		if (cursor == STDIMAGE) {
		    /* The following is a kludge used to temporarily implement
		     * the logical image cursor read.  In the future this will
		     * be eliminated, and the c_rcursor call below (cursor
		     * mode) will be used for stdimage as well as for stdgraph.
		     * The present code (IMDRCUR) goes directly to the display
		     * server to get the cursor value, bypassing cursor mode
		     * and the (currently nonexistent) stdimage kernel.
		     */
		    char    str[SZ_LINE+1], keystr[10];
		    int     wcs, key;
		    float   x, y;

		    if (c_imdrcur ("stdimage",
			&x,&y,&wcs,&key,str,SZ_LINE, 1, 1) == EOF) {
			query_status = NULL;

		    } else {
			if (isprint(key) && !isspace(key))
			    sprintf (keystr, "%c", key);
			else
			    sprintf (keystr, "\\%03o", key);
			sprintf (buf, "%.3f %.3f %d %s %s\n",
			    x, y, wcs, keystr, str);
		        query_status = (char *) ((XINT) strlen(buf));
		    }

		} else if (c_rcursor (cursor, buf, SZ_PROMPTBUF) == EOF) {
		    query_status = NULL;
		} else
		    query_status = (char *) ((XINT) strlen(buf));

	    } else if (pp->p_type & PT_UKEY) {
		/* Read a user keystroke command from the terminal.
		 */
		pp->p_flags &= ~P_LEOF;
		if (c_rdukey (buf, SZ_PROMPTBUF) == EOF)
		    query_status = NULL;
		else
		    query_status = (char *) ((XINT) strlen(buf));

	    } else {
text_query:	fd = spf_open (buf, SZ_PROMPTBUF);
		pquery (pp, fdopen(fd,"a"));
		spf_close (fd);

		c_stgputline ((XINT)STDOUT, buf);
		if (c_stggetline ((XINT)STDIN, buf, SZ_PROMPTBUF) > 0)
		    query_status = (char *) ((XINT) strlen(buf));
		else
		    query_status = NULL;
	    }

	    ip = buf;

	    /* Set o to the current value of the parameter.  Beware that some
	     * of the logical branches which follow assume that struct o has
	     * been initialized to the current value of the parameter.
	     */
	    if (pp->p_type & PT_LIST)
		setopundef (&o);
	    else if (arrflag) {
		paramget(pp, FN_VALUE);
		poffset (offset);
		o = popop();
	    } else
		o = pp->p_valo;

	    /* Handle eof, a null-length line (lone carriage return),
	     * and line with more than SZ_LINE chars.  Ignore leading whitespace
	     * if basic type is not string.
	     */
	    if (query_status == NULL) {
		/* Typing eof will use current value (as will a lone
		 * newline) but if param is a list, it is a meaningful
		 * answer.
		 */
		if (pp->p_type & PT_LIST) {
		    closelist (pp);		/* close an existing file */
		    pp->p_flags |= P_LEOF;
		    o = makeop (eofstr, OT_STRING);
		    break;
		}
		goto testval;
	    }

	    /* Ignore leading whitespace if it is not significant for this
	     * datatype.  Do this before testing for empty line, so that a
	     * return such as " \n" is equivalent to "\n".  I.e., do not
	     * penalize the user if they type the space bar by accident before
	     * typing return to accept the default value.
	     */
	    if (bastype != OT_STRING || (pp->p_type & (PT_FILNAM|PT_PSET)))
		while (*ip == ' ' || *ip == '\t')
		    ip++;

	    if (*ip == '\n') {
		/* Blank lines usually just accept the current value
		 * but if the param is a string and is undefined,
		 * it sets the string to a (defined) nullstring.
		 */
		*ip = '\0';
		if (bastype == OT_STRING && opundef (&o))
		    o = makeop (ip, bastype);
		else
		    goto testval;
	    }

	    if ((nlp = index (ip, '\n')) != NULL)
		*nlp = '\0';			/* cancel the newline	*/
	    else
		goto testval;

	    /* Finally, we have handled the pathological cases...
	     */
	    if ((pp->p_type & PT_LIST) &&
		(!strcmp (ip,eofstr) || !strcmp (ip,"eof"))) {

		closelist (pp);
		pp->p_flags |= P_LEOF;
		o = makeop (eofstr, OT_STRING);
		break;

	    } else {
		if (arrflag) {
		    /* In querying for arrays we may set more than one
		     * element of the array in a single query.  However
		     * we must set the first element.  So we will pretend
		     * to be a scalar until that first element is set
		     * and then enter a loop where we may set other
		     * elements.
		     */
		    abuf = ip;
		    ip = nextstr(&abuf, stdin);
		    if (ip == NULL  ||  ip == (char *) ERR  ||  ip == undefval)
			goto testval;
		}

		o = makeop (ip, bastype);
	    }

testval:
	    /* If parameter value is in range, we are done.  If it is out of
	     * range and we are a batch job or an interactive terminal job,
	     * print an error message and request that the user enter a legal
	     * value.  If the CL is being run taking input from a file, abort,
	     * else we will go into a loop reading illegal values from the
	     * input file and printing out lots of error messages.
	     */
	    if (inrange (pp, &o))
		break;
	    else if (batch)
		eprintf ("\n[%d] %s", bkgno, oormsg);
	    else if (isatty (fileno (stdin)))
		eprintf ("%s\n", oormsg);
	    else
		cl_error (E_UERR, oormsg);
	}

	if (!(pp->p_type & PT_LIST)) {
	    /* update param with new value.
	     */
	    if (cldebug) {
		eprintf ("changing `%s.p_val' to ", pp->p_name);
		fprop (stderr, &o);
		eprintf ("\n");
	    }

	    pushop (&o);
	    paramset (pp, FN_VALUE);
	    pp->p_flags |= P_QUERY;
	}

	pushop (&o);

	if (arrflag  &&  query_status != NULL  &&  *ip != '\0') {
	    /* If we have an array assign values until something
	     * is used up or until we hit any error.
	     */
	    n_ele = 1;
	    forever {
		if (n_ele >= max_ele)		/* End of array. */
		    break;
		ip = nextstr(&abuf, stdin);

		if (ip == NULL)			/* End of query line. */
		    break;

		if (ip == (char *) ERR) {	/* Error on query line. */
		    eprintf("Error loading array value.\n");
		    break;
		}

		if (ip != undefval) {
		    o = makeop (ip, bastype);
		    if ( ! inrange (pp, &o) ) {	/* Not in range. */
			eprintf("Array value outside range.\n");
			break;
		    }

		    offset++;			/* Next element in array. */
		    poffset (offset);

		    pushop (&o);
		    paramset (pp, FN_VALUE);
		} else
		    offset++;

		n_ele++;
	    }
	}
Exemple #22
0
void mipscode(code* h,char* filename){
	FILE *fp=fopen(filename,"w");
	if(fp==NULL){
		printf("fail to open file\n");
		return;
	}
	fprintf(fp,".data\n");
	fprintf(fp,"_prompt: .asciiz \"Enter an integer:\"\n");
	fprintf(fp,"_ret: .asciiz \"\\n\"\n");
	fprintf(fp,".globl main\n");
	fprintf(fp,".text\n");
	fprintf(fp,"read:\n");
	fprintf(fp,"li $v0, 4\n");
	fprintf(fp,"la $a0, _prompt\n");
	fprintf(fp,"syscall\n");
	fprintf(fp,"li $v0 5\n");
	fprintf(fp,"syscall\n");
	fprintf(fp,"jr $ra\n");
	fprintf(fp,"\n");
	fprintf(fp,"write:\n");
	fprintf(fp,"li $v0, 1\n");
	fprintf(fp,"syscall\n");
	fprintf(fp,"li $v0, 4\n");
	fprintf(fp,"la $a0, _ret\n");
	fprintf(fp,"syscall\n");
	fprintf(fp,"move $v0, $0\n");
	fprintf(fp,"jr $ra\n");
	fprintf(fp,"\n");
	printf("begin hhh\n");
	code* p=h;
	code *tempcode;
	while(p!=NULL){
		switch(p->word.kind){
			case LAB:
				fprintf(fp,"%s:\n",getop(p->word.u.lab.op1));
				break;
			case ASSIGN:
				if(p->word.u.assign.right->kind==CONSTANT){
					fprintf(fp,"li %s, %d\n",reg(fp,p->word.u.assign.left,1),p->word.u.assign.right->u.value);
					save(fp,p->word.u.assign.left,1);
				}
				else{
					fprintf(fp,"move %s, %s\n",reg(fp,p->word.u.assign.left,1),reg(fp,p->word.u.assign.right,2));
					save(fp,p->word.u.assign.left,1);
				}
				break;
			case ADD:
				fprintf(fp,"add %s, %s, %s\n",reg(fp,p->word.u.calcu.result,1),reg(fp,p->word.u.calcu.op1,2),reg(fp,p->word.u.calcu.op2,3));
				save(fp,p->word.u.calcu.result,1);
				break;
			case MIN:
				fprintf(fp,"sub %s, %s, %s\n",reg(fp,p->word.u.calcu.result,1),reg(fp,p->word.u.calcu.op1,2),reg(fp,p->word.u.calcu.op2,3));
				save(fp,p->word.u.calcu.result,1);
				break;
			case MUL:
				fprintf(fp,"mul %s, %s, %s\n",reg(fp,p->word.u.calcu.result,1),reg(fp,p->word.u.calcu.op1,2),reg(fp,p->word.u.calcu.op2,3));
				save(fp,p->word.u.calcu.result,1);
				break;
			case DIVID:
				fprintf(fp,"div %s, %s\n",reg(fp,p->word.u.calcu.op1,2),reg(fp,p->word.u.calcu.op2,3));
				fprintf(fp,"mflo %s\n",reg(fp,p->word.u.calcu.result,1));
				save(fp,p->word.u.calcu.result,1);
				break;
			case ADDRTO:
				fprintf(fp,"lw %s, 0(%s)\n",reg(fp,p->word.u.assign.left,1),reg(fp,p->word.u.assign.right,2));
				save(fp,p->word.u.assign.left,1);
				break;
			case TOADD:
				fprintf(fp,"sw %s,0(%s)\n",reg(fp,p->word.u.assign.right,1),reg(fp,p->word.u.assign.left,2));
				break;
			case GOTO:
				fprintf(fp,"j %s\n",getop(p->word.u.got.op1));
				break;
			case CALL:
			case READ:
			case WRITE:
				parnum=0;
				if(p->word.kind==WRITE)
					fprintf(fp,"move $a0, %s\n",reg(fp,p->word.u.ret.op1,1));
				fprintf(fp,"addi $sp, $sp, %d\n",stackoffset+4);
				fprintf(fp,"sw $ra, -4($sp)\n");
				if(p->word.kind==CALL)
					fprintf(fp,"jal %s\n",getop(p->word.u.assign.right));
				else if(p->word.kind==READ)
					fprintf(fp,"jal read\n");
				else{
					fprintf(fp,"jal write\n");
				}
				fprintf(fp,"lw $ra, -4($sp)\n");
				fprintf(fp,"addi $sp, $sp, -%d\n",stackoffset+4);
				if(p->word.kind==CALL)
					fprintf(fp,"move %s,$v0\n",reg(fp,p->word.u.assign.left,1));
				else
					fprintf(fp,"move %s,$v0\n",reg(fp,p->word.u.ret.op1,1));
				if(p->word.kind==CALL)
					save(fp,p->word.u.assign.left,1);
				else
					save(fp,p->word.u.ret.op1,1);
				break;
			case RET:
				fprintf(fp,"move $v0, %s\n",reg(fp,p->word.u.ret.op1,1));
				fprintf(fp,"jr $ra\n");
				break;
			case IFGOTO:
				printf("%s\n",getop(p->word.u.ifgoto.op4));
				if(strcmp(getop(p->word.u.ifgoto.op2),"==")==0)
					fprintf(fp,"beq %s, %s, %s\n",reg(fp,p->word.u.ifgoto.op1,1),reg(fp,p->word.u.ifgoto.op3,2),getop(p->word.u.ifgoto.op4));
				else if(strcmp(getop(p->word.u.ifgoto.op2),"!=")==0)
					fprintf(fp,"bne %s, %s, %s\n",reg(fp,p->word.u.ifgoto.op1,1),reg(fp,p->word.u.ifgoto.op3,2),getop(p->word.u.ifgoto.op4));
				else if(strcmp(getop(p->word.u.ifgoto.op2),">")==0) 
					fprintf(fp,"bgt %s, %s, %s\n",reg(fp,p->word.u.ifgoto.op1,1),reg(fp,p->word.u.ifgoto.op3,2),getop(p->word.u.ifgoto.op4));
				else if(strcmp(getop(p->word.u.ifgoto.op2),"<")==0) 
					fprintf(fp,"blt %s, %s, %s\n",reg(fp,p->word.u.ifgoto.op1,1),reg(fp,p->word.u.ifgoto.op3,2),getop(p->word.u.ifgoto.op4));
				else if(strcmp(getop(p->word.u.ifgoto.op2),">=")==0) 
					fprintf(fp,"bge %s, %s, %s\n",reg(fp,p->word.u.ifgoto.op1,1),reg(fp,p->word.u.ifgoto.op3,2),getop(p->word.u.ifgoto.op4));
				else
					fprintf(fp,"ble %s, %s, %s\n",reg(fp,p->word.u.ifgoto.op1,1),reg(fp,p->word.u.ifgoto.op3,2),getop(p->word.u.ifgoto.op4));
				break;
			case FUNCTION:
				fprintf(fp, "\n");
				fprintf(fp,"%s:\n",getop(p->word.u.ret.op1));
				stackoffset=0;
				break;
			case ARG:
				while(p->next->word.kind == ARG)p=p->next;
				tempcode = p;
				parnum = 0;
				while(tempcode->word.kind==ARG){
					if(parnum<=3){
						fprintf(fp,"move $a%d, %s\n",parnum,reg(fp,tempcode->word.u.ret.op1,1));
						parnum++;
					}
					else{
						fprintf(fp,"sw %s, %d($sp)\n",reg(fp,tempcode->word.u.ret.op1,1),stackoffset+4+(parnum-4)*4); 
						parnum++;
					}
					tempcode = tempcode->pre;
				}
				break;
			case PARAM:
				tempcode = p;
				parnum=0;
				while(tempcode->word.kind == PARAM){
					parnum++;
					tempcode=tempcode->next;
				}
				tempcode = p;
				if(parnum<=4)
					stackoffset = 0;
				else
					stackoffset = (parnum-4)*4; 
				for(int i=0;i<parnum;i++){
					setoffset(tempcode->word.u.ret.op1,stackoffset);
					stackoffset+=4;
					tempcode=tempcode->next;
				}
				tempcode = p;
				for(int i=0;i<4 && tempcode->word.kind == PARAM;i++){
					fprintf(fp, "sw $a%d, %d($sp)\n",i,getoffset(tempcode->word.u.ret.op1));
					tempcode = tempcode->next;
				}
				if(parnum>=4){
					for(int i=4;i<=parnum;++i){
						fprintf(fp, "lw $t1, %d($sp)\n", (i-4)*4);
						fprintf(fp, "sw $t1, %d($sp)\n", getoffset(tempcode->word.u.ret.op1));
						tempcode = tempcode->next;
					}
				}
				for(;p->next->word.kind == PARAM;p=p->next);
				parnum=0;
				break;
				/*for(int i=4;i<parnum;i++){
					if(i<4)
						fprintf(fp,"sw $a%d, %d($sp)\n",i,(i+parnum-4)*4);
					else{
						fprintf(fp,"lw $t1, %d($sp)\n",(i-4)*4);
						fprintf(fp,"sw $t1, %d($sp)\n",(i+parnum-4)*4);
					}
				}
				else 
					for(int i=0;i<parnum;i++)
						fprintf(fp,"sw $a%d, %d($sp)\n",i,i*4);
				for(;p->next->word.kind==PARAM;)
					p=p->next;
					*/
			default:
				printf("not finished\n");
		}
		p=p->next;
	}
	fclose(fp);
	return;
}
Exemple #23
0
int
tzparse(const char *name, struct state * sp, int lastditch)
{
	const char *stdname;
	const char *dstname = NULL;
	size_t		stdlen;
	size_t		dstlen;
	long		stdoffset;
	long		dstoffset;
	pg_time_t  *atp;
	unsigned char *typep;
	char	   *cp;
	int			load_result;

	stdname = name;
	if (lastditch)
	{
		stdlen = strlen(name);	/* length of standard zone name */
		name += stdlen;
		if (stdlen >= sizeof sp->chars)
			stdlen = (sizeof sp->chars) - 1;
		stdoffset = 0;

		/*
		 * Unlike the original zic library, do NOT invoke tzload() here; we
		 * can't assume pg_open_tzfile() is sane yet, and we don't care about
		 * leap seconds anyway.
		 */
		load_result = -1;
	}
	else
	{
		if (*name == '<')
		{
			name++;
			stdname = name;
			name = getqzname(name, '>');
			if (*name != '>')
				return (-1);
			stdlen = name - stdname;
			name++;
		}
		else
		{
			name = getzname(name);
			stdlen = name - stdname;
		}
		if (*name == '\0')
			return -1;
		name = getoffset(name, &stdoffset);
		if (name == NULL)
			return -1;
		load_result = tzload(TZDEFRULES, NULL, sp, FALSE);
	}
	if (load_result != 0)
		sp->leapcnt = 0;		/* so, we're off a little */
	if (*name != '\0')
	{
		if (*name == '<')
		{
			dstname = ++name;
			name = getqzname(name, '>');
			if (*name != '>')
				return -1;
			dstlen = name - dstname;
			name++;
		}
		else
		{
			dstname = name;
			name = getzname(name);
			dstlen = name - dstname;	/* length of DST zone name */
		}
		if (*name != '\0' && *name != ',' && *name != ';')
		{
			name = getoffset(name, &dstoffset);
			if (name == NULL)
				return -1;
		}
		else
			dstoffset = stdoffset - SECSPERHOUR;
		if (*name == '\0' && load_result != 0)
			name = TZDEFRULESTRING;
		if (*name == ',' || *name == ';')
		{
			struct rule start;
			struct rule end;
			int			year;
			pg_time_t	janfirst;
			pg_time_t	starttime;
			pg_time_t	endtime;

			++name;
			if ((name = getrule(name, &start)) == NULL)
				return -1;
			if (*name++ != ',')
				return -1;
			if ((name = getrule(name, &end)) == NULL)
				return -1;
			if (*name != '\0')
				return -1;
			sp->typecnt = 2;	/* standard time and DST */

			/*
			 * Two transitions per year, from EPOCH_YEAR forward.
			 */
			sp->ttis[0].tt_gmtoff = -dstoffset;
			sp->ttis[0].tt_isdst = 1;
			sp->ttis[0].tt_abbrind = stdlen + 1;
			sp->ttis[1].tt_gmtoff = -stdoffset;
			sp->ttis[1].tt_isdst = 0;
			sp->ttis[1].tt_abbrind = 0;
			atp = sp->ats;
			typep = sp->types;
			janfirst = 0;
			sp->timecnt = 0;
			for (year = EPOCH_YEAR;
				 sp->timecnt + 2 <= TZ_MAX_TIMES;
				 ++year)
			{
				pg_time_t	newfirst;

				starttime = transtime(janfirst, year, &start,
									  stdoffset);
				endtime = transtime(janfirst, year, &end,
									dstoffset);
				if (starttime > endtime)
				{
					*atp++ = endtime;
					*typep++ = 1;		/* DST ends */
					*atp++ = starttime;
					*typep++ = 0;		/* DST begins */
				}
				else
				{
					*atp++ = starttime;
					*typep++ = 0;		/* DST begins */
					*atp++ = endtime;
					*typep++ = 1;		/* DST ends */
				}
				sp->timecnt += 2;
				newfirst = janfirst;
				newfirst += year_lengths[isleap(year)] *
					SECSPERDAY;
				if (newfirst <= janfirst)
					break;
				janfirst = newfirst;
			}
		}
		else
		{
			long		theirstdoffset;
			long		theirdstoffset;
			long		theiroffset;
			int			isdst;
			int			i;
			int			j;

			if (*name != '\0')
				return -1;

			/*
			 * Initial values of theirstdoffset and theirdstoffset.
			 */
			theirstdoffset = 0;
			for (i = 0; i < sp->timecnt; ++i)
			{
				j = sp->types[i];
				if (!sp->ttis[j].tt_isdst)
				{
					theirstdoffset =
						-sp->ttis[j].tt_gmtoff;
					break;
				}
			}
			theirdstoffset = 0;
			for (i = 0; i < sp->timecnt; ++i)
			{
				j = sp->types[i];
				if (sp->ttis[j].tt_isdst)
				{
					theirdstoffset =
						-sp->ttis[j].tt_gmtoff;
					break;
				}
			}

			/*
			 * Initially we're assumed to be in standard time.
			 */
			isdst = FALSE;
			theiroffset = theirstdoffset;

			/*
			 * Now juggle transition times and types tracking offsets as you
			 * do.
			 */
			for (i = 0; i < sp->timecnt; ++i)
			{
				j = sp->types[i];
				sp->types[i] = sp->ttis[j].tt_isdst;
				if (sp->ttis[j].tt_ttisgmt)
				{
					/* No adjustment to transition time */
				}
				else
				{
					/*
					 * If summer time is in effect, and the transition time
					 * was not specified as standard time, add the summer time
					 * offset to the transition time; otherwise, add the
					 * standard time offset to the transition time.
					 */

					/*
					 * Transitions from DST to DDST will effectively disappear
					 * since POSIX provides for only one DST offset.
					 */
					if (isdst && !sp->ttis[j].tt_ttisstd)
					{
						sp->ats[i] += dstoffset -
							theirdstoffset;
					}
					else
					{
						sp->ats[i] += stdoffset -
							theirstdoffset;
					}
				}
				theiroffset = -sp->ttis[j].tt_gmtoff;
				if (sp->ttis[j].tt_isdst)
					theirdstoffset = theiroffset;
				else
					theirstdoffset = theiroffset;
			}

			/*
			 * Finally, fill in ttis. ttisstd and ttisgmt need not be handled.
			 */
			sp->ttis[0].tt_gmtoff = -stdoffset;
			sp->ttis[0].tt_isdst = FALSE;
			sp->ttis[0].tt_abbrind = 0;
			sp->ttis[1].tt_gmtoff = -dstoffset;
			sp->ttis[1].tt_isdst = TRUE;
			sp->ttis[1].tt_abbrind = stdlen + 1;
			sp->typecnt = 2;
		}
	}
	else
	{
		dstlen = 0;
		sp->typecnt = 1;		/* only standard time */
		sp->timecnt = 0;
		sp->ttis[0].tt_gmtoff = -stdoffset;
		sp->ttis[0].tt_isdst = 0;
		sp->ttis[0].tt_abbrind = 0;
	}
	sp->charcnt = stdlen + 1;
	if (dstlen != 0)
		sp->charcnt += dstlen + 1;
	if ((size_t) sp->charcnt > sizeof sp->chars)
		return -1;
	cp = sp->chars;
	(void) strncpy(cp, stdname, stdlen);
	cp += stdlen;
	*cp++ = '\0';
	if (dstlen != 0)
	{
		(void) strncpy(cp, dstname, dstlen);
		*(cp + dstlen) = '\0';
	}
	return 0;
}
Exemple #24
0
int
client_dispatch(struct ntp_peer *p, u_int8_t settime)
{
    struct ntp_msg		 msg;
    struct msghdr		 somsg;
    struct iovec		 iov[1];
    struct timeval		 tv;
    char			 buf[NTP_MSGSIZE];
    union {
        struct cmsghdr	hdr;
        char		buf[CMSG_SPACE(sizeof(tv))];
    } cmsgbuf;
    struct cmsghdr		*cmsg;
    ssize_t			 size;
    double			 T1, T2, T3, T4;
    time_t			 interval;

    bzero(&somsg, sizeof(somsg));
    iov[0].iov_base = buf;
    iov[0].iov_len = sizeof(buf);
    somsg.msg_iov = iov;
    somsg.msg_iovlen = 1;
    somsg.msg_control = cmsgbuf.buf;
    somsg.msg_controllen = sizeof(cmsgbuf.buf);

    T4 = getoffset();
    if ((size = recvmsg(p->query->fd, &somsg, 0)) == -1) {
        if (errno == EHOSTUNREACH || errno == EHOSTDOWN ||
                errno == ENETUNREACH || errno == ENETDOWN ||
                errno == ECONNREFUSED || errno == EADDRNOTAVAIL ||
                errno == ENOPROTOOPT || errno == ENOENT) {
            client_log_error(p, "recvmsg", errno);
            set_next(p, error_interval());
            return (0);
        } else
            fatal("recvfrom");
    }

    if (somsg.msg_flags & MSG_TRUNC) {
        client_log_error(p, "recvmsg packet", EMSGSIZE);
        set_next(p, error_interval());
        return (0);
    }

    if (somsg.msg_flags & MSG_CTRUNC) {
        client_log_error(p, "recvmsg control data", E2BIG);
        set_next(p, error_interval());
        return (0);
    }

#ifdef HAVE_RTABLE
    if (p->rtable != -1 &&
            setsockopt(p->query->fd, SOL_SOCKET, SO_RTABLE, &p->rtable,
                       sizeof(p->rtable)) == -1)
        fatal("client_dispatch setsockopt SO_RTABLE");
#endif

    for (cmsg = CMSG_FIRSTHDR(&somsg); cmsg != NULL;
            cmsg = CMSG_NXTHDR(&somsg, cmsg)) {
        if (cmsg->cmsg_level == SOL_SOCKET &&
                cmsg->cmsg_type == SCM_TIMESTAMP) {
            memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv));
            T4 += tv.tv_sec + JAN_1970 + 1.0e-6 * tv.tv_usec;
            break;
        }
    }

    if (T4 < JAN_1970) {
        client_log_error(p, "recvmsg control format", EBADF);
        set_next(p, error_interval());
        return (0);
    }

    ntp_getmsg((struct sockaddr *)&p->addr->ss, buf, size, &msg);

    if (msg.orgtime.int_partl != p->query->msg.xmttime.int_partl ||
            msg.orgtime.fractionl != p->query->msg.xmttime.fractionl)
        return (0);

    if ((msg.status & LI_ALARM) == LI_ALARM || msg.stratum == 0 ||
            msg.stratum > NTP_MAXSTRATUM) {
        char s[16];

        if ((msg.status & LI_ALARM) == LI_ALARM) {
            strlcpy(s, "alarm", sizeof(s));
        } else if (msg.stratum == 0) {
            /* Kiss-o'-Death (KoD) packet */
            strlcpy(s, "KoD", sizeof(s));
        } else if (msg.stratum > NTP_MAXSTRATUM) {
            snprintf(s, sizeof(s), "stratum %d", msg.stratum);
        }
        interval = error_interval();
        set_next(p, interval);
        log_info("reply from %s: not synced (%s), next query %llds",
                 log_sockaddr((struct sockaddr *)&p->addr->ss), s,
                 (long long)interval);
        return (0);
    }

    /*
     * From RFC 2030 (with a correction to the delay math):
     *
     *     Timestamp Name          ID   When Generated
     *     ------------------------------------------------------------
     *     Originate Timestamp     T1   time request sent by client
     *     Receive Timestamp       T2   time request received by server
     *     Transmit Timestamp      T3   time reply sent by server
     *     Destination Timestamp   T4   time reply received by client
     *
     *  The roundtrip delay d and local clock offset t are defined as
     *
     *    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.
     */

    T1 = p->query->xmttime;
    T2 = lfp_to_d(msg.rectime);
    T3 = lfp_to_d(msg.xmttime);

    /*
     * XXX workaround: time_t / tv_sec must never wrap.
     * around 2020 we will need a solution (64bit time_t / tv_sec).
     * consider every answer with a timestamp beyond january 2030 bogus.
     */
    if (T2 > JAN_2030 || T3 > JAN_2030) {
        set_next(p, error_interval());
        return (0);
    }

    p->reply[p->shift].offset = ((T2 - T1) + (T3 - T4)) / 2;
    p->reply[p->shift].delay = (T4 - T1) - (T3 - T2);
    p->reply[p->shift].status.stratum = msg.stratum;
    if (p->reply[p->shift].delay < 0) {
        interval = error_interval();
        set_next(p, interval);
        log_info("reply from %s: negative delay %fs, "
                 "next query %llds",
                 log_sockaddr((struct sockaddr *)&p->addr->ss),
                 p->reply[p->shift].delay, (long long)interval);
        return (0);
    }
    p->reply[p->shift].error = (T2 - T1) - (T3 - T4);
    p->reply[p->shift].rcvd = getmonotime();
    p->reply[p->shift].good = 1;

    p->reply[p->shift].status.leap = (msg.status & LIMASK);
    p->reply[p->shift].status.precision = msg.precision;
    p->reply[p->shift].status.rootdelay = sfp_to_d(msg.rootdelay);
    p->reply[p->shift].status.rootdispersion = sfp_to_d(msg.dispersion);
    p->reply[p->shift].status.refid = msg.refid;
    p->reply[p->shift].status.reftime = lfp_to_d(msg.reftime);
    p->reply[p->shift].status.poll = msg.ppoll;

    if (p->addr->ss.ss_family == AF_INET) {
        p->reply[p->shift].status.send_refid =
            ((struct sockaddr_in *)&p->addr->ss)->sin_addr.s_addr;
    } else if (p->addr->ss.ss_family == AF_INET6) {
        MD5_CTX		context;
        u_int8_t	digest[MD5_DIGEST_LENGTH];

        MD5_Init(&context);
        MD5_Update(&context, ((struct sockaddr_in6 *)&p->addr->ss)->
                   sin6_addr.s6_addr, sizeof(struct in6_addr));
        MD5_Final(digest, &context);
        memcpy((char *)&p->reply[p->shift].status.send_refid, digest,
               sizeof(u_int32_t));
    } else
        p->reply[p->shift].status.send_refid = msg.xmttime.fractionl;

    if (p->trustlevel < TRUSTLEVEL_PATHETIC)
        interval = scale_interval(INTERVAL_QUERY_PATHETIC);
    else if (p->trustlevel < TRUSTLEVEL_AGGRESSIVE)
        interval = scale_interval(INTERVAL_QUERY_AGGRESSIVE);
    else
        interval = scale_interval(INTERVAL_QUERY_NORMAL);

    set_next(p, interval);
    p->state = STATE_REPLY_RECEIVED;

    /* every received reply which we do not discard increases trust */
    if (p->trustlevel < TRUSTLEVEL_MAX) {
        if (p->trustlevel < TRUSTLEVEL_BADPEER &&
                p->trustlevel + 1 >= TRUSTLEVEL_BADPEER)
            log_info("peer %s now valid",
                     log_sockaddr((struct sockaddr *)&p->addr->ss));
        p->trustlevel++;
    }

    log_debug("reply from %s: offset %f delay %f, "
              "next query %llds %s",
              log_sockaddr((struct sockaddr *)&p->addr->ss),
              p->reply[p->shift].offset, p->reply[p->shift].delay,
              (long long)interval, print_rtable(p->rtable));

    client_update(p);
    if (settime)
        priv_settime(p->reply[p->shift].offset);

    if (++p->shift >= OFFSET_ARRAY_SIZE)
        p->shift = 0;

    return (0);
}
Exemple #25
0
static int readlabel(const unsigned char *in, int insize, const unsigned char *ref, int refsize, int *_at, jdns_string_t **name)
{
	int at;
	unsigned char out[255];
	int out_size;
	const unsigned char *label, *last;
	int hopped_yet;
	int hopsleft;
	int label_size;

	at = *_at;

	// stay in range
	if(at < 0 || at >= insize)
		return 0;

	out_size = 0;
	label = in + at;
	hopped_yet = 0;
	last = in + insize;
	while(1)
	{
		// need a byte
		if(label + 1 > last)
			goto error;

		// we make this a while loop instead of an 'if', in case
		//   there's a pointer to a pointer.  as a precaution,
		//   we will hop no more than 8 times
		hopsleft = 8;
		while(*label & 0xc0)
		{
			int offset;

			// need the next byte, too
			if(label + 2 > last)
				goto error;

			offset = getoffset(label, refsize, &hopsleft);
			if(offset == -1)
				goto error;

			label = ref + offset;
			if(!hopped_yet)
			{
				at += 2;
				hopped_yet = 1;
				last = ref + refsize;
			}

			// need a byte
			if(label + 1 > last)
				goto error;
		}

		label_size = *label & 0x3f;

		// null label?  then we're done
		if(label_size == 0)
		{
			if(!hopped_yet)
				++at;
			break;
		}

		// enough source bytes? (length byte + length)
		if(label + label_size + 1 > last)
			goto error;

		// enough dest bytes? (length + dot)
		if(out_size + label_size + 1 > 255)
			goto error;

		memcpy(out + out_size, label + 1, label_size);
		out_size += label_size;
		out[out_size] = '.';
		++out_size;

		if(!hopped_yet)
			at += label_size + 1;

		label += label_size + 1;
	}

	*_at = at;
	*name = jdns_string_new();
	jdns_string_set(*name, out, out_size);
	return 1;

error:
	return 0;
}
Exemple #26
0
static int readlabel(const unsigned char *in, int insize, const unsigned char *ref, int refsize, int *_at, jdns_string_t **name)
{
	int at;
	// string format is one character smaller than dns format.  e.g.:
	//   dns:    [7] affinix [3] com [0] = 13 bytes
	//   string: "affinix.com."          = 12 bytes
	// only exception is '.' itself, but that won't influence the max.
	unsigned char out[MAX_LABEL_LENGTH - 1];
	int out_size;
	const unsigned char *label, *last;
	int hopped_yet;
	int hopsleft;
	int label_size;

	at = *_at;

	// stay in range
	if(at < 0 || at >= insize)
		return 0;

	out_size = 0;
	label = in + at;
	hopped_yet = 0;
	last = in + insize;
	while(1)
	{
		// need a byte
		if(label + 1 > last)
			goto error;

		// we make this a while loop instead of an 'if', in case
		//   there's a pointer to a pointer.  as a precaution,
		//   we will hop no more than 8 times
		hopsleft = 8;
		while(*label & 0xc0)
		{
			int offset;

			// need the next byte, too
			if(label + 2 > last)
				goto error;

			offset = getoffset(label, refsize, &hopsleft);
			if(offset == -1)
				goto error;

			label = ref + offset;
			if(!hopped_yet)
			{
				at += 2;
				hopped_yet = 1;
				last = ref + refsize;
			}

			// need a byte
			if(label + 1 > last)
				goto error;
		}

		label_size = *label & 0x3f;

		// null label?  then we're done
		if(label_size == 0)
		{
			if(!hopped_yet)
				++at;
			break;
		}

		// enough source bytes? (length byte + length)
		if(label + label_size + 1 > last)
			goto error;

		// enough dest bytes? (length + dot)
		if(out_size + label_size + 1 > MAX_LABEL_LENGTH - 1)
			goto error;

		memcpy(out + out_size, label + 1, label_size);
		out_size += label_size;
		out[out_size] = '.';
		++out_size;

		if(!hopped_yet)
			at += label_size + 1;

		label += label_size + 1;
	}

	*_at = at;
	*name = jdns_string_new();
	jdns_string_set(*name, out, out_size);
	return 1;

error:
	return 0;
}
Exemple #27
0
// Copy a node (recursively if appropriate)
LOCAL LVAL nyx_dup_value(LVAL val)
{
   LVAL nval = val;

   // Protect old and new values
   xlprot1(val);
   xlprot1(nval);

   // Copy the node
   if (val != NIL) {
      switch (ntype(val))
      {
         case FIXNUM:
            nval = cvfixnum(getfixnum(val));
         break;

         case FLONUM:
            nval = cvflonum(getflonum(val));
         break;

         case CHAR:
            nval = cvchar(getchcode(val));
         break;

         case STRING:
            nval = cvstring((char *) getstring(val));
         break;

         case VECTOR:
         {
            int len = getsize(val);
            int i;

            nval = newvector(len);
            nval->n_type = ntype(val);

            for (i = 0; i < len; i++) {
               if (getelement(val, i) == val) {
                  setelement(nval, i, val);
               }
               else {
                  setelement(nval, i, nyx_dup_value(getelement(val, i)));
               }
            }
         }
         break;

         case CONS:
            nval = nyx_dup_value(cdr(val));
            nval = cons(nyx_dup_value(car(val)), nval);
         break;

         case SUBR:
         case FSUBR:
            nval = cvsubr(getsubr(val), ntype(val), getoffset(val));
         break;

         // Symbols should never be copied since their addresses are cached
         // all over the place.
         case SYMBOL:
            nval = val;
         break;

         // Streams are not copied (although USTREAM could be) and reference
         // the original value.
         case USTREAM:
         case STREAM:
            nval = val;
         break;

         // Externals aren't copied because I'm not entirely certain they can be.
         case EXTERN:
            nval = val;
         break;

         // For all other types, just allow them to reference the original
         // value.  Probably not the right thing to do, but easier.
         case OBJECT:
         case CLOSURE:
         default:
            nval = val;
         break;
      }
   }

   xlpop();
   xlpop();

   return nval;
}
int fwengine(const unsigned char *_img, int size, void *ar)
{
    unsigned char *img = (unsigned char*)_img;
    unsigned int   crc;
    int            i;

    /* 14 is the minimal size of an empty image */
    if( ! (*img) || (*img != 0xFF) || (size <14) )
    {
        syserr("Wrong image or no image\n");
        return -1;
    }

    /* Check crc32 */
    cp = img + size - 4;

    *cp = ~(*cp) & 0xFF ; cp++;
    *cp = ~(*cp) & 0xFF ; cp++;
    *cp = ~(*cp) & 0xFF ; cp++;
    *cp = ~(*cp) & 0xFF ;

    crc = crc32( ~0, img, size );

    if( crc )
    {
        syserr("Image CRC error\n");
        return -1;
    }

    if( *(img+1) > VERSION )
    {
        syserr("Image version is newer than the driver\n");
        return -1;
    }

    /* Basic checks complete, we can print greeting and FW_ID here if desired */

    /* Get to the first opcode */

    cp     = img + 2;                            /* Skip magic and version */
    offset = 2;

    while( (offset < size) && (*cp) )
    {
        cp++;                                    /* Skip build host name */
        offset++;
    }

    cp     += 6;                                 /* Skip build date */
    offset += 6;

    while( (cp > img) && (cp < (img+size-4)) )   /* just an additional bounds check */
    {
        /* First, find out opcode class */
        switch( (*cp & 0xF0) )
        {
          case RLoad :
              ACC = getarg( );
              break;
          case Ror   :
              ACC |= getarg( );
              break;
          case Rand  :
              ACC &= getarg( );
              break;
          case Add   :
              ACC += getarg( );
              break;
          case Rstor :
              regs[ *cp & 0xF ] = ACC;
              cp++;
              offset++;
              break;
          case Shift :
              i = getarg( );
              if(i < 0)
                  ACC >>= -i;
              else
                  ACC <<= i;
              break;
          case Nneg  :
              if( *cp & 0xF )
                  regs[ *cp & 0xF ] = ~regs[ *cp & 0xF ];
              else
                  ACC = -ACC;
              cp++;
              offset++;
              break;
          case Trr   :
              ACC = get_target_reg( getarg(), ar );
              break;
          case Trw   :
              write_target_reg( getarg(), ACC , ar );
              break;
          case Trx   :
              ACC = execute_on_target( getarg(), ACC, ar );
              break;
          case Exit  :
              if( *cp & 0xF ) /* abort with code */
                  return( regs[ *cp & 0xF ] );
              else{            /* clean exit */
                  bmidone( ar );
                  return(0);
              }
              break;
          case Cmp   :
              ACC -= getarg();
              break;
          case Ldprn :
              if( ! (*cp & 0xF) ) /* register dump */
                  dumpregs();
              else
              {
                  int ret;

                  ret = load_binary(ACC, cp, ar);
                  if( ret < 0 )
                      return( -1 ); /* Error */
                  cp += ret;
                  offset += ret;
              }
              break;
          case Jump  :
              if( !(*cp & 0xF) ||
                  ((*cp == 0xE1) && (ACC)) ||
                  ((*cp == 0xE2) && !(ACC)) )

                  offset = getoffset();
                  cp     = img + offset;

                  break;
          default:
              syserr("Image format error\n");
              break;

        }
    }
Exemple #29
0
/*
** Opcode interpreter
*/
const char *match (lua_State *L, const char *o, const char *s, const char *e,
                   Instruction *op, Capture *capture, int ptop) {
  Stack stackbase[INITBACK];
  Stack *stacklimit = stackbase + INITBACK;
  Stack *stack = stackbase;  /* point to first empty slot in stack */
  int capsize = INITCAPSIZE;
  int captop = 0;  /* point to first empty slot in captures */
  int ndyncap = 0;  /* number of dynamic captures (in Lua stack) */
  const Instruction *p = op;  /* current instruction */
  stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;
  lua_pushlightuserdata(L, stackbase);
  for (;;) {
//#if defined(DEBUG)
//      printf("s: |%s| stck:%d, dyncaps:%d, caps:%d  ",
//             s, stack - getstackbase(L, ptop), ndyncap, captop);
      /*printinst(op, p);
      printcaplist(capture, capture + captop);*/
//#endif
    assert(stackidx(ptop) + ndyncap == lua_gettop(L) && ndyncap <= captop);
    switch ((Opcode)p->i.code) {
      case IEnd: {
        assert(stack == getstackbase(L, ptop) + 1);
        capture[captop].kind = Cclose;
        capture[captop].s = NULL;
        return s;
      }
      case IGiveup: {
        assert(stack == getstackbase(L, ptop));
        return NULL;
      }
      case IRet: {
        assert(stack > getstackbase(L, ptop) && (stack - 1)->s == NULL);
        p = (--stack)->p;
        continue;
      }
      case IAny: {
        if (s < e) { p++; s++; }
        else goto fail;
        continue;
      }
      case ITestAny: {
        if (s < e) p += 2;
        else p += getoffset(p);
        continue;
      }
      case IChar: {
        if ((byte)*s == p->i.aux && s < e) { p++; s++; }
        else goto fail;
        continue;
      }
      case ITestChar: {
        if ((byte)*s == p->i.aux && s < e) p += 2;
        else p += getoffset(p);
        continue;
      }
      case ISet: {
        int c = (byte)*s;
        if (testchar((p+1)->buff, c) && s < e)
          { p += CHARSETINSTSIZE; s++; }
        else goto fail;
        continue;
      }
      case ITestSet: {
        int c = (byte)*s;
        if (testchar((p + 2)->buff, c) && s < e)
          p += 1 + CHARSETINSTSIZE;
        else p += getoffset(p);
        continue;
      }
      case IBehind: {
        int n = p->i.aux;
        if (n > s - o) goto fail;
        s -= n; p++;
        continue;
      }
      case ISpan: {
        for (; s < e; s++) {
          int c = (byte)*s;
          if (!testchar((p+1)->buff, c)) break;
        }
        p += CHARSETINSTSIZE;
        continue;
      }
      case IJmp: {
        p += getoffset(p);
        continue;
      }
      case IChoice: {
        if (stack == stacklimit)
          stack = doublestack(L, &stacklimit, ptop);
        stack->p = p + getoffset(p);
        stack->s = s;
        stack->caplevel = captop;
        stack++;
        p += 2;
        continue;
      }
      case ICall: {
        if (stack == stacklimit)
          stack = doublestack(L, &stacklimit, ptop);
        stack->s = NULL;
        stack->p = p + 2;  /* save return address */
        stack++;
        p += getoffset(p);
        continue;
      }
      case ICommit: {
        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
        stack--;
        p += getoffset(p);
        continue;
      }
      case IPartialCommit: {
        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
        (stack - 1)->s = s;
        (stack - 1)->caplevel = captop;
        p += getoffset(p);
        continue;
      }
      case IBackCommit: {
        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
        s = (--stack)->s;
        captop = stack->caplevel;
        p += getoffset(p);
        continue;
      }
      case IFailTwice:
        assert(stack > getstackbase(L, ptop));
        stack--;
        /* go through */
      case IFail:
      fail: { /* pattern failed: try to backtrack */
        do {  /* remove pending calls */
          assert(stack > getstackbase(L, ptop));
          s = (--stack)->s;
        } while (s == NULL);
        if (ndyncap > 0)  /* is there matchtime captures? */
          ndyncap -= removedyncap(L, capture, stack->caplevel, captop);
        captop = stack->caplevel;
        p = stack->p;
        continue;
      }
      case ICloseRunTime: {
        CapState cs;
        int rem, res, n;
        int fr = lua_gettop(L) + 1;  /* stack index of first result */
        cs.s = o; cs.L = L; cs.ocap = capture; cs.ptop = ptop;
        n = runtimecap(&cs, capture + captop, s, &rem);  /* call function */
        captop -= n;  /* remove nested captures */
        fr -= rem;  /* 'rem' items were popped from Lua stack */
        res = resdyncaptures(L, fr, s - o, e - o);  /* get result */
        if (res == -1)  /* fail? */
          goto fail;
        s = o + res;  /* else update current position */
        n = lua_gettop(L) - fr + 1;  /* number of new captures */
        ndyncap += n - rem;  /* update number of dynamic captures */
        if (n > 0) {  /* any new capture? */
          if ((captop += n + 2) >= capsize) {
            capture = doublecap(L, capture, captop, ptop);
            capsize = 2 * captop;
          }
          /* add new captures to 'capture' list */
          adddyncaptures(s, capture + captop - n - 2, n, fr); 
        }
        p++;
        continue;
      }
      case ICloseCapture: {
        const char *s1 = s;
        assert(captop > 0);
        /* if possible, turn capture into a full capture */
        if (capture[captop - 1].siz == 0 &&
            s1 - capture[captop - 1].s < UCHAR_MAX) {
          capture[captop - 1].siz = s1 - capture[captop - 1].s + 1;
          p++;
          continue;
        }
        else {
          capture[captop].siz = 1;  /* mark entry as closed */
          capture[captop].s = s;
          goto pushcapture;
        }
      }
      case IOpenCapture:
        capture[captop].siz = 0;  /* mark entry as open */
        capture[captop].s = s;
        goto pushcapture;
      case IFullCapture:
        capture[captop].siz = getoff(p) + 1;  /* save capture size */
        capture[captop].s = s - getoff(p);
        /* goto pushcapture; */
      pushcapture: {
        capture[captop].idx = p->i.key;
        capture[captop].kind = getkind(p);
        if (++captop >= capsize) {
          capture = doublecap(L, capture, captop, ptop);
          capsize = 2 * captop;
        }
        p++;
        continue;
      }
      default: assert(0); return NULL;
    }
  }
}
Exemple #30
0
void save(FILE* fp,Operand h,int flag){
	int offset = getoffset(h);
	fprintf(fp, "sw $t%d, %d($sp)\n",flag,offset);
}