コード例 #1
0
ファイル: twrrd.c プロジェクト: nathanmkaya/ksh-arch
tmain()
{
	int	i;
	char	wbuf[1023];
	char	rbuf[1023];
	Sfio_t	*fp;

	for(i = 0; i < sizeof(wbuf); ++i)
		wbuf[i] = (i%26)+'a';
	wbuf[sizeof(wbuf)-1] = '\0';

	if(!(fp = sftmp(0)))
		terror("Opening temp file");

	for(i = 0; i < 256; ++i)
		if(sfwrite(fp,wbuf,sizeof(wbuf)) != sizeof(wbuf))
			terror("Writing");

	sfseek(fp,(Sfoff_t)0,0);
	sfset(fp,SF_WRITE,0);
	sfsetbuf(fp,NIL(char*),0);
	sfsetbuf(fp,NIL(char*),(size_t)SF_UNBOUND);

	for(i = 0; i < 256; ++i)
	{	if(sfread(fp,rbuf,sizeof(rbuf)) != sizeof(rbuf))
			terror("Reading");

		if(strcmp(rbuf,wbuf) != 0)
			terror("Unmatched record");
	}

	texit(0);
}
コード例 #2
0
ファイル: stdtmpfile.c プロジェクト: JOravetz/SeisUnix
Sfio_t* _stdtmpfile()
{
	Sfio_t* f;

	if((f = sftmp(0)) )
		f->flags |= SF_MTSAFE;

	return f;
}
コード例 #3
0
ファイル: tmpfile.c プロジェクト: gitpan/sfio
FILE* tmpfile()
#endif
{
	reg Sfio_t*	sp;
	reg FILE*	fp;

	if(!(sp = sftmp(0)))
		return NIL(FILE*);
	if(!(fp = _stdstream(sp)))
	{	sfclose(sp);
		return NIL(FILE*);
	}
コード例 #4
0
ファイル: tputgetr.c プロジェクト: ISLEcode/kornshell
tmain()
{
	char	buf[100];
	Sfio_t	*fp;
	int	i;
	char	*s;

	if(!(fp = sftmp(8)))
		terror("Can't open temp file");

	sfset(fp,SF_LINE,1);
	for(i = 0; i < 1000; ++i)
	{	sfsprintf(buf,sizeof(buf),"Number: %d",i);
		if(sfputr(fp,buf,'\n') <= 0)
			terror("Writing %s",buf);
	}

	sfseek(fp,(Sfoff_t)0,0);

	for(i = 0; i < 1000; ++i)
	{	sfsprintf(buf,sizeof(buf),"Number: %d",i);
		if(!(s = sfgetr(fp,'\n',1)))
			terror("Reading %s",buf);
		if(strcmp(s,buf) != 0)
			terror("Input=%s, Expect=%s",s,buf);
	}

	sfseek(fp,(Sfoff_t)0,0);
	s = sfgetr(fp,'\0',1);
	if(s)
		terror("Expecting a null string");
	s = sfgetr(fp,'\0',-1);
	if(!s)
		terror("Expecting a non-null string");
	if(sfvalue(fp) != sfsize(fp))
		terror("Wrong size");

	sfclose(fp);
	if(!(fp = sfnew(0, buf, 12, 1, SF_WRITE)) )
		terror("Opening a test stream");
	sfsetbuf(fp, buf, 12);
	sfset(fp, SF_LINE, 0);
	sfdisc(fp, &Disc);
	if(sfputr(fp, "0123456789", '\n') != 11)
		terror("Sfputr failed1");
	if(sfputr(fp, "0", -1) != 1)
		terror("Sfputr failed2");
	if(sfputr(fp, "1", -1) != 1)
		terror("Sfputr failed3");

	texit(0);
}
コード例 #5
0
ファイル: tputgetc.c プロジェクト: ISLEcode/kornshell
tmain()
{	Sfio_t	*f;
	int	i, c;

	if(!(f = sftmp(8)))
		terror("Can't open temp file");

	for(i = 0; i < 10000; ++i)
		if(sfputc(f,(i%26)+'a') < 0)
			terror("Writing %c",(i%26)+'a');

	sfseek(f,(Sfoff_t)0,0);

	for(i = 0; i < 10000; ++i)
		if((c = sfgetc(f)) != ((i%26)+'a'))
			terror("Input=%#o, Expect=%c",c,(i%26)+'a');

	texit(0);
}
コード例 #6
0
ファイル: tputgetl.c プロジェクト: ISLEcode/kornshell
tmain()
{
	int	i, r;
	Sfio_t	*fp;

	if(!(fp = sftmp(8)))
		terror("Can't open temp file");

	for(i = -5448; i <= 5448; i += 101)
		if(sfputl(fp,(long)i) < 0)
			terror("Writing %d",i);

	sfseek(fp,(Sfoff_t)0,0);

	for(i = -5448; i <= 5448; i += 101)
		if((r = (int)sfgetl(fp)) != i)
			terror("Input=%d, Expect=%d",r,i);

	texit(0);
}
コード例 #7
0
ファイル: tputgetu.c プロジェクト: ChappedSky/hancock
MAIN()
{
	unsigned int	i, r;
	Sfio_t	*fp;

	if(!(fp = sftmp(8)))
		terror("Can't open temp file\n");

	for(i = 10000; i <= 100000; i += 9)
		if(sfputu(fp,i) < 0)
			terror("Writing %u\n",i);

	sfseek(fp,(Sfoff_t)0,0);

	for(i = 10000; i <= 100000; i += 9)
		if((r = (unsigned int)sfgetu(fp)) != i)
			terror("Input=%u, Expect=%u\n",r,i);

	TSTEXIT(0);
}
コード例 #8
0
ファイル: tputgetu.c プロジェクト: att/ast
tmain() {
    UNUSED(argc);
    UNUSED(argv);
    unsigned int i, r;
    Sfio_t *fp;

    if (!(fp = sftmp(8))) terror("Can't open temp file");

    for (i = 10000; i <= 100000; i += 9) {
        if (sfputu(fp, i) < 0) terror("Writing %u", i);
    }

    sfseek(fp, (Sfoff_t)0, 0);

    for (i = 10000; i <= 100000; i += 9) {
        if ((r = (unsigned int)sfgetu(fp)) != i) terror("Input=%u, Expect=%u", r, i);
    }

    texit(0);
}
コード例 #9
0
ファイル: tputgetr.c プロジェクト: ChappedSky/hancock
MAIN()
{
	char	buf[100];
	Sfio_t	*fp;
	int	i;
	char	*s;

	if(!(fp = sftmp(8)))
		terror("Can't open temp file\n");

	sfset(fp,SF_LINE,1);
	for(i = 0; i < 1000; ++i)
	{	sfsprintf(buf,sizeof(buf),"Number: %d",i);
		if(sfputr(fp,buf,'\n') <= 0)
			terror("Writing %s\n",buf);
	}

	sfseek(fp,(Sfoff_t)0,0);

	for(i = 0; i < 1000; ++i)
	{	sfsprintf(buf,sizeof(buf),"Number: %d",i);
		if(!(s = sfgetr(fp,'\n',1)))
			terror("Reading %s\n",buf);
		if(strcmp(s,buf) != 0)
			terror("Input=%s, Expect=%s\n",s,buf);
	}

	sfseek(fp,(Sfoff_t)0,0);
	s = sfgetr(fp,'\0',1);
	if(s)
		terror("Expecting a null string\n");
	s = sfgetr(fp,'\0',-1);
	if(!s)
		terror("Expecting a non-null string\n");
	if(sfvalue(fp) != sfsize(fp))
		terror("Wrong size\n");

	TSTEXIT(0);
}
コード例 #10
0
ファイル: ed.c プロジェクト: ISLEcode/kornshell
static void
edit(void)
{
	register off_t*	mp;

	if (ed.tmp) {
		sfclose(ed.tmp);
		ed.tmp = 0;
	}
	ed.tmpoff = 0;
	if (!(ed.tmp = sftmp(BLOCK_TMP)))
		error(ERROR_SYSTEM|3, "cannot create temp file");
	for (mp = ed.marks; mp < &ed.marks[elementsof(ed.marks)]; )
		*mp++ = LINE_NONE;
	ed.marked = 0;
	ed.event++;
	ed.dot = ed.dol = ed.zero;
	if (!ed.initialized) {
		ed.initialized = 1;
		if (ed.pending)
			ed.caught = ed.pending;
	}
}
コード例 #11
0
ファイル: trestore.c プロジェクト: apprisi/illumos-gate
static struct ionod *r_redirect(Shell_t* shp)
{
	register long l;
	register struct ionod *iop=0, *iopold, *ioptop=0;
	while((l=sfgetl(infile))>=0)
	{
		iop = (struct ionod*)getnode(shp->stk,ionod);
		if(!ioptop)
			ioptop = iop;
		else
			iopold->ionxt = iop;
		iop->iofile = l;
		iop->ioname = r_string(shp->stk);
		if(iop->iodelim = r_string(shp->stk))
		{
			iop->iosize = sfgetl(infile);
			if(shp->heredocs)
				iop->iooffset = sfseek(shp->heredocs,(off_t)0,SEEK_END);
			else
			{
				shp->heredocs = sftmp(512);
				iop->iooffset = 0;
			}
			sfmove(infile,shp->heredocs, iop->iosize, -1);
		}
		iopold = iop;
		if(iop->iofile&IOVNM)
			iop->iovname = r_string(shp->stk);
		else
			iop->iovname = 0;
		iop->iofile &= ~IOVNM;
	}
	if(iop)
		iop->ionxt = 0;
	return(ioptop);
}
コード例 #12
0
/*
 * copy the lines starting at offset <start> from in <in> to <out>
 * in reverse order
 */
int rev_line(Sfio_t *in, Sfio_t *out, off_t start)
{
	register char *cp, *cpold;
	register int n, nleft=0;
	char buff[BUFSIZE];
	off_t offset;
	if(sfseek(in,(off_t)0,SEEK_CUR) < 0)
	{
		Sfio_t *tmp = sftmp(4*SF_BUFSIZE);
		if(!tmp)
			return(-1);
		if(start>0 && sfmove(in, (Sfio_t*)0, start, -1) != start)
			return(-1);
		if(sfmove(in, tmp, SF_UNBOUND, -1) < 0 || !sfeof(in) || sferror(tmp))
			return(-1);
		in = tmp;
		start=0;
	}
	if((offset = sfseek(in,(off_t)0,SEEK_END)) <= start)
		return(0);
	offset = rounddown(offset,BUFSIZE);
	while(1)
	{
		n = BUFSIZE;
		if(offset < start)
		{
			n -= (start-offset);
			offset = start;
		}
		sfseek(in, offset, SEEK_SET);
		if((n=sfread(in, buff, n)) <=0)
			break;
		cp = buff+n;
		n = *buff;
		*buff = '\n';
		while(1)
		{
			cpold = cp;
			if(nleft==0)
				cp--;
			if(cp==buff)
			{
				nleft= 1;
				break;
			}
			while(*--cp != '\n');
			if(cp==buff && n!='\n')
			{
				*cp = n;
				nleft += cpold-cp;
				break;
			}
			else
				cp++;
			if(sfwrite(out,cp,cpold-cp) < 0)
				return(-1);
			if(nleft)
			{
				if(nleft==1)
					sfputc(out,'\n');
				else if(sfmove(in,out,nleft,-1) != nleft)
					return(-1);
				nleft = 0;
			}
		}
		if(offset <= start)
			break;
		offset -= BUFSIZE;
	}
	if(nleft)
	{
		sfseek(in, start, SEEK_SET);
		if(sfmove(in,out,nleft,-1) != nleft)
			return(-1);
	}
	return(0);
}
コード例 #13
0
ファイル: texcept.c プロジェクト: att/ast
tmain() {
    UNUSED(argc);
    UNUSED(argv);
    Sfio_t *f, *f2;
    char buf[1024];
    char rbuf[4 * 1024];
    off_t o;
    int i;

    if (!(f = sfopen(NULL, tstfile("sf", 0), "w"))) terror("Can't open file");
    sfset(f, SF_IOCHECK, 1);

    Disc.exceptf = except;
    if (!sfdisc(f, &Disc)) terror("Pushing discipline failed");

    sfdisc(f, &Disc);
    if (Type != SF_DPUSH) terror("Did not get push event");

    /* this is to test sfraise(NULL,...) */
    if (!(f2 = sfopen(NULL, tstfile("sf", 0), "w"))) terror("Can't open file");
    sfdisc(f2, &Disc);

    Sfn = 0;
    if (sfraise(0, SF_WRITE, 0) < 0) terror("sfraise failed");
    if (Sfn != 2) terror("Didn't get right event count");

    sfdisc(f, NULL);
    if (Type != SF_DPOP) terror("Did not get pop event");

    sfwrite(f, "123", 3);
    sfsync(f);
    if (Type != SF_SYNC) terror("Did not get sync event");

    sfwrite(f, "123", 3);
    sfpurge(f);
    if (Type != SF_PURGE) terror("Did not get purge event");

    sfclose(f);
    if (Type != SF_CLOSING) terror("Did not get close event");

    sfclose(f);
    if (Type != SF_FINAL) terror("Did not get final event");

    if (!(f = sfopen(NULL, tstfile("sf", 0), "r"))) terror("Can't open file");
    Disc2.readf = readfunc;
    Disc2.exceptf = except3;
    sfdisc(f, &Disc2);
    if (sfgetc(f) >= 0) terror("There should be no data here");
    if (Type != SF_LOCKED) terror("Did not get lock event");

    /* test to see if sfclose() preserves seek location */
    if (!(f = sftmp(0))) terror("Can't create temp file");
    sfsetbuf(f, buf, sizeof(buf));
    for (i = 0; i < sizeof(rbuf); ++i) rbuf[i] = i;
    sfwrite(f, rbuf, sizeof(rbuf));
    sfset(f, SF_WRITE, 0);

    Disc.exceptf = except2;
    sfdisc(f, &Disc);
    sfseek(f, (Sfoff_t)0, 0);
    if (sfread(f, rbuf, 4) != 4) terror("reading 4 bytes");
    for (i = 0; i < 4; ++i) {
        if (rbuf[i] != i) terror("wrong 4 bytes");
    }

    sfsync(f);
    if ((o = lseek(sffileno(f), (off_t)0, SEEK_CUR)) != 4) {
        terror("Wrong seek location %lld", (Sfoff_t)o);
    }

    if ((i = dup(sffileno(f))) < 0) terror("Can't dup file descriptor");
    if ((o = lseek(i, (off_t)0, SEEK_CUR)) != 4) terror("Wrong seek location %lld", (Sfoff_t)o);

    sfclose(f);
    if ((o = lseek(i, (off_t)0, SEEK_CUR)) != 4) terror("Wrong seek location %lld", (Sfoff_t)o);

    texit(0);
}
コード例 #14
0
ファイル: perlio.c プロジェクト: BackupTheBerlios/wl530g-svn
PerlIO *
PerlIO_tmpfile(void)
{
 return sftmp(0);
}
コード例 #15
0
ファイル: tgetr.c プロジェクト: ISLEcode/kornshell
tmain()
{
	Sfio_t	*f;
	int	n, i;
	char	buf[50], *s, *string = "111\n222\n333";

	f = sfopen(NIL(Sfio_t*),string,"s");
	if(!(s = sfgetr(f,'\n',SF_STRING|SF_LOCKR)) || strcmp(s,"111") != 0)
		terror("sfgetr failed1");

	if(sfgetr(f,'\n',0) != NIL(char*))
		terror("sfgetr should have failed because of locking");
	sfread(f,s,1);

	if(!(s = sfgetr(f,'\n',SF_STRING)) || strcmp(s,"222") != 0)
		terror("sfgetr failed2");

	if((s = sfgetr(f,'\n',0)) != NIL(char*))
		terror("sfgetr should have failed because of partial record");

	if(!(s = sfgetr(f,0,SF_LASTR)) )
		terror("sfgetr should have succeeded getting partial record");

	/* test type == -1 and type == 1 modes */
	sfseek(f,(Sfoff_t)0,0);
	if(!(s = sfgetr(f,'\n',1)) || strcmp(s,"111") != 0)
		terror("sfgetr failed in compatible mode");

	if(!(s = sfgetr(f,'\n',SF_STRING|SF_LOCKR)) || strcmp(s,"222") != 0)
		terror("sfgetr failed3");
	if(sfgetr(f,'\n',1) )
		terror("sfgetr should have failed due to locking");
	sfread(f,s,0);

	if(sfgetr(f,'\n',1) )
		terror("sfgetr should have failed because record is incomplete");
	
	if(!(s = sfgetr(f,0,-1)) || strcmp(s,"333") != 0)
		terror("sfgetr failed in getting last partial record");

	if(!(f = sftmp(0)) )
		terror("Can't open temporary stream");
	for(n = 0; n < 10; ++n) /* each record is 100 bytes */
	{	for(i = 0; i < 100; ++i)
			sfputc(f, 'a');
		sfputc(f,'\n');
	}
	sfseek(f,(Sfoff_t)0,0);
	sfsetbuf(f, buf, 50);
	if(!(s = sfgetr(f, '\n', 1)))
		terror("Can't get a record");

	n = 80;
	sfmaxr(n, 1); /* set maximum record size */
	if((i = sfmaxr(0, 0)) != n)
		terror("maxr is %d, expected %d", i, n);
	if((s = sfgetr(f, '\n', 1)) != 0)
		terror("Shouldn't have gotten a record");

	n = 0;
	sfmaxr(n, 1); /* no record size limit */
	if((i = sfmaxr(0, 0)) != n)
		terror("maxr is %d, expected %d", i, n);
	if(!(s = sfgetr(f, '\n', 1)))
		terror("Can't get a record");
	if(!(s = sfgetr(f, '\n', 1)))
		terror("Can't get a record");

	texit(0);
}
コード例 #16
0
ファイル: args.c プロジェクト: att/ast
// This routine turns options on and off.
// The options "PDicr" are illegal from set command.
// The -o option is used to set option by name.
// This routine returns the number of non-option arguments.
int sh_argopts(int argc, char *argv[], void *context) {
    Shell_t *shp = context;
    int n, o;
    Arg_t *ap = shp->arg_context;
    Lex_t *lp = shp->lex_context;
    Shopt_t newflags;
    int setflag = 0, action = 0, trace = (int)sh_isoption(shp, SH_XTRACE);
    Namval_t *np = NULL;
    const char *sp;
    char *keylist = NULL;
    int verbose, f, unsetnp = 0;
    Optdisc_t disc;

    newflags = shp->options;
    memset(&disc, 0, sizeof(disc));
    disc.version = OPT_VERSION;
    disc.infof = infof;
    opt_info.disc = &disc;

    if (argc > 0) {
        setflag = 4;
    } else {
        argc = -argc;
    }

    while ((n = optget(argv, setflag ? sh_optset : sh_optksh))) {
        o = 0;
        f = *opt_info.option == '-' && (opt_info.num || opt_info.arg);
        switch (n) {
            case 'A': {
                np = nv_open(opt_info.arg, shp->var_tree, NV_ARRAY | NV_VARNAME);
                if (f) unsetnp = 1;
                continue;
            }
            case 'K': {
                keylist = opt_info.arg;
                continue;
            }
#if SHOPT_BASH
            case 'O': {  // shopt options, only in bash mode
                if (!sh_isoption(shp, SH_BASH)) {
                    errormsg(SH_DICT, ERROR_exit(1), e_option, opt_info.name);
                    __builtin_unreachable();
                }
            }
#endif
            // FALLTHRU
            case 'o': {  // set options
            byname:
                if (!opt_info.arg || !*opt_info.arg || *opt_info.arg == '-') {
                    action = PRINT;
                    // print style: -O => shopt options.
                    // bash => print unset options also, no heading.
                    verbose = (f ? PRINT_VERBOSE : PRINT_NO_HEADER) | (n == 'O' ? PRINT_SHOPT : 0) |
                              (sh_isoption(shp, SH_BASH) ? PRINT_ALL | PRINT_NO_HEADER : 0) |
                              ((opt_info.arg && (!*opt_info.arg || *opt_info.arg == '-'))
                                   ? (PRINT_TABLE | PRINT_NO_HEADER)
                                   : 0);
                    continue;
                }
                o = sh_lookopt(opt_info.arg, &f);
                if (o <= 0 || (!sh_isoption(shp, SH_BASH) && (o & SH_BASHEXTRA)) ||
                    ((!sh_isoption(shp, SH_BASH) || n == 'o') && (o & SH_BASHOPT))

                    || (setflag && (o & SH_COMMANDLINE))) {
                    errormsg(SH_DICT, 2, e_option, opt_info.arg);
                    error_info.errors++;
                }
                o &= 0xff;
                if (sh_isoption(shp, SH_RESTRICTED) && !f && o == SH_RESTRICTED) {
                    errormsg(SH_DICT, ERROR_exit(1), e_restricted, opt_info.arg);
                    __builtin_unreachable();
                }
                break;
            }
#if SHOPT_BASH
            case -1: {  // --rcfile
                shp->gd->rcfile = opt_info.arg;
                continue;
            }
            case -2: {  // --noediting
                if (!f) {
                    off_option(&newflags, SH_VI);
                    off_option(&newflags, SH_EMACS);
                    off_option(&newflags, SH_GMACS);
                }
                continue;
            }
            case -3: {  // --profile
                n = 'l';
                sp = strchr(optksh, n);
                if (sp) o = flagval[sp - optksh];
                break;
            }
            case -4: {  // --posix
                // Mask lower 8 bits to find char in optksh string.
                n &= 0xff;
                sp = strchr(optksh, n);
                if (sp) o = flagval[sp - optksh];
                break;
            }
            case -5: {  // --version
                sfputr(sfstdout, "ksh bash emulation, version ", -1);
                np = nv_open("BASH_VERSION", shp->var_tree, 0);
                sfputr(sfstdout, nv_getval(np), -1);
                np = nv_open("MACHTYPE", shp->var_tree, 0);
                sfprintf(sfstdout, " (%s)\n", nv_getval(np));
                sh_exit(shp, 0);
            }
#endif
            case -6: {  // --default
                const Shtable_t *tp;
                for (tp = shtab_options; (o = tp->sh_number); tp++) {
                    if (!(o & SH_COMMANDLINE) && is_option(&newflags, o & 0xff)) {
                        off_option(&newflags, o & 0xff);
                    }
                }
                continue;
            }
            case -7: {
                f = 0;
                goto byname;
            }
            case 'D': {
                on_option(&newflags, SH_NOEXEC);
                // Cppcheck doesn't recognize the "goto" in the preceding case and thus thinks we
                // might fall through and call strchr() with n == -7.  Even though this it
                // technically a bug in cppcheck it is one reason why `goto` shouldn't be used; at
                // least inside `switch` blocks.
                // cppcheck-suppress invalidFunctionArg
                sp = strchr(optksh, n);
                if (sp) o = flagval[sp - optksh];
                break;
            }
            case 'T': {
                if (opt_info.num) {
                    shp->test |= opt_info.num;
                } else {
                    shp->test = 0;
                }
                continue;
            }
            case 's': {
                if (setflag) {
                    action = SORT;
                    continue;
                }
                sp = strchr(optksh, n);
                if (sp) o = flagval[sp - optksh];
                break;
            }
            case 'R': {
                if (setflag) {
                    n = ':';
                } else {
                    ap->kiafile = opt_info.arg;
                    n = 'n';
                }
                sp = strchr(optksh, n);
                if (sp) o = flagval[sp - optksh];
                break;
            }
            case ':': {
                if (opt_info.name[0] == '-' && opt_info.name[1] == '-') {
                    opt_info.arg = argv[opt_info.index - 1] + 2;
                    f = 1;
                    goto byname;
                }
                errormsg(SH_DICT, 2, "%s", opt_info.arg);
                continue;
            }
            case '?': {
                errormsg(SH_DICT, ERROR_usage(0), "%s", opt_info.arg);
                return -1;
            }
            default: {
                sp = strchr(optksh, n);
                if (sp) o = flagval[sp - optksh];
                break;
            }
        }
        if (f) {
            if (o == SH_VI || o == SH_EMACS || o == SH_GMACS) {
                off_option(&newflags, SH_VI);
                off_option(&newflags, SH_EMACS);
                off_option(&newflags, SH_GMACS);
            }
            on_option(&newflags, o);
            off_option(&shp->offoptions, o);
        } else {
            if (o == SH_RESTRICTED && sh_isoption(shp, SH_RESTRICTED)) {
                errormsg(SH_DICT, ERROR_exit(1), e_restricted, "r");
                __builtin_unreachable();
            }
            if (o == SH_XTRACE) trace = 0;
            off_option(&newflags, o);
            if (setflag == 0) on_option(&shp->offoptions, o);
        }
    }
    if (error_info.errors) {
        errormsg(SH_DICT, ERROR_usage(2), "%s", optusage(NULL));
        __builtin_unreachable();
    }
    // Check for '-' or '+' argument.
    sp = argv[opt_info.index];
    if (sp && sp[1] == 0 && (*sp == '+' || *sp == '-') && strcmp(argv[opt_info.index - 1], "--")) {
        opt_info.index++;
        off_option(&newflags, SH_XTRACE);
        off_option(&newflags, SH_VERBOSE);
        trace = 0;
    }
    if (trace) sh_trace(shp, argv, 1);
    argc -= opt_info.index;
    argv += opt_info.index;
    if (action == PRINT) sh_printopts(shp, newflags, verbose, 0);
    if (setflag) {
        if (action == SORT) {
            int (*sortfn)(const char *, const char *) = strcoll;
            Namarr_t *arp;
            struct Value *args;
            unsigned char *bits;
            if (argc > 0) {
                strsort(argv, argc, sortfn);
            } else if (np && (arp = nv_arrayptr(np)) && (args = nv_aivec(np, &bits))) {
                char *cp;
                int i, c, keys = 0;

                if (keylist) {
                    for (cp = keylist; (c = *cp); cp++) {
                        if (c == ',') keys++;
                    }
                    keys++;
                } else {
                    keylist = "";
                }
                arp->nelem = nv_aipack(arp);
                cp = nv_name(np);
                c = strlen(cp);
                // This used to multiply by `(keys - 1)` but `keys` can be zero which means the
                // nodesize can be less than `sizeof(struct Node)` which is obviously wrong.
                // Whether multiplying by `keys` is correct is unclear.
                // See issue #824.
                size_t nodesize = sizeof(struct Node) + keys * sizeof(Namval_t *);
                struct Sort *sp =
                    malloc(sizeof(struct Sort) + strlen(keylist) + (sizeof(char *) + 1) * keys +
                           (arp->nelem + 1) * (nodesize + sizeof(void *)) + c + 3);
                sp->shp = shp;
                sp->np = np;
                if (!(sp->root = shp->last_root)) sp->root = shp->var_tree;
                sp->vp = args;
                sp->cur = 0;
                sp->nodes = (struct Node *)&sp->keys[keys + 2];
                memset(sp->nodes, 0, arp->nelem * nodesize);
                sp->nptrs = (struct Node **)((char *)sp->nodes + arp->nelem * nodesize);
                sp->flags = (char *)&sp->nptrs[arp->nelem + 1];
                memset(sp->flags, 0, keys + 1);
                sp->name = sp->flags + keys + 1;
                memcpy(sp->name, cp, c + 1);
                sp->keys[0] = sp->name + c + 1;
                strcpy(sp->keys[0], keylist);
                cp = (char *)sp->nodes;
                for (c = 0; c < arp->nelem; c++) {
                    if (*keylist && *keylist != ':') {
                        struct Namval *np = FETCH_VT(args[c], np);
                        ((struct Node *)cp)->index = strtol(np->nvname, NULL, 10);
                        ((struct Node *)cp)->bits = bits[c];
                    } else {
                        ((struct Node *)cp)->index = c;
                    }
                    ((struct Node *)cp)->vp = args[c];
                    sp->nptrs[c] = (struct Node *)cp;
                    cp += nodesize;
                }
                if (!(cp = sp->keys[0])) cp = keylist;
                for (keys = 0; (c = *cp); cp++) {
                    if (c == ',') {
                        *cp++ = 0;
                        sp->keys[++keys] = cp;
                        sp->flags[keys] = 0;
                    } else if (c == ':') {
                    again:
                        *cp++ = 0;
                        c = *cp;
                        if (c == 'r') {
                            sp->flags[keys] |= SORT_reverse;
                            c = cp[1];
                        } else if (c == 'n') {
                            sp->flags[keys] |= SORT_numeric;
                            c = cp[1];
                        }
                        if (c == 'n' || c == 'r') goto again;
                    }
                }
                sp->keys[++keys] = 0;
                Sp = sp;
                if (sp->keys[0] && *sp->keys[0]) {
                    sortfn = arraysort;
                } else if (sp->flags[0] & SORT_numeric) {
                    sortfn = numsort;
                } else {
                    sortfn = alphasort;
                }
                strsort((char **)sp->nptrs, arp->nelem, sortfn);
                cp = (char *)sp->nodes;
                for (c = 0; c < arp->nelem; c++) {
                    i = (char *)sp->nptrs[c] - (char *)&sp->nodes[0];
                    if (i / nodesize != c) {
                        args[c] = ((struct Node *)(cp + i))->vp;
                        bits[c] = ((struct Node *)(cp + i))->bits;
                    }
                }
                free(sp);
                nv_close(np);
                np = NULL;
            } else {
                strsort(shp->st.dolv + 1, shp->st.dolc, sortfn);
            }
        }
        if (np) {
            if (unsetnp) nv_unset(np);
            nv_setvec(np, 0, argc, argv);
            nv_close(np);
        } else if (argc > 0 || ((sp = argv[-1]) && strcmp(sp, "--") == 0)) {
            sh_argset(ap, argv - 1);
        }
    } else if (is_option(&newflags, SH_CFLAG)) {
        if (!(shp->comdiv = *argv++)) {
            errormsg(SH_DICT, 2, e_cneedsarg);
            errormsg(SH_DICT, ERROR_usage(2), optusage(NULL));
            __builtin_unreachable();
        }
        argc--;
    }
    // Handling SH_INTERACTIVE and SH_PRIVILEGED has been moved to
    // sh_applyopts(), so that the code can be reused from b_shopt(), too.
    sh_applyopts(shp, newflags);
    if (!ap->kiafile) return argc;

    if (!argv[0]) {
        errormsg(SH_DICT, ERROR_usage(2), "-R requires scriptname");
        __builtin_unreachable();
    }
    if (!(lp->kiafile = sfopen(NULL, ap->kiafile, "w+"))) {
        errormsg(SH_DICT, ERROR_system(3), e_create, ap->kiafile);
        __builtin_unreachable();
    }
    if (!(lp->kiatmp = sftmp(2 * SF_BUFSIZE))) {
        errormsg(SH_DICT, ERROR_system(3), e_tmpcreate);
        __builtin_unreachable();
    }
    sfputr(lp->kiafile, ";vdb;CIAO/ksh", '\n');
    lp->kiabegin = sftell(lp->kiafile);
    lp->entity_tree = dtopen(&_Nvdisc, Dtbag);
    lp->scriptname = strdup(sh_fmtq(argv[0]));
    lp->script = kiaentity(lp, lp->scriptname, -1, 'p', -1, 0, 0, 's', 0, "");
    lp->fscript = kiaentity(lp, lp->scriptname, -1, 'f', -1, 0, 0, 's', 0, "");
    lp->unknown = kiaentity(lp, "<unknown>", -1, 'p', -1, 0, 0, '0', 0, "");
    kiaentity(lp, "<unknown>", -1, 'p', 0, 0, lp->unknown, '0', 0, "");
    lp->current = lp->script;
    ap->kiafile = NULL;

    return argc;
}
コード例 #17
0
ファイル: tmpfile.c プロジェクト: ISLEcode/kornshell
Sfio_t*
tmpfile(void)
{
	return sftmp(0);
}
コード例 #18
0
ファイル: cut.c プロジェクト: jasonbking/illumos-gate
static void
cutfields(Cut_t* cut, Sfio_t* fdin, Sfio_t* fdout)
{
	register unsigned char *sp = cut->space;
	register unsigned char *cp;
	register unsigned char *wp;
	register int c, nfields;
	register const int *lp = cut->list;
	register unsigned char *copy;
	register int nodelim, empty, inword=0;
	register unsigned char *ep;
	unsigned char *bp, *first;
	int lastchar;
	wchar_t w;
	Sfio_t *fdtmp = 0;
	long offset = 0;
	unsigned char mb[8];
	/* process each buffer */
	while ((bp = (unsigned char*)sfreserve(fdin, SF_UNBOUND, -1)) && (c = sfvalue(fdin)) > 0)
	{
		cp = bp;
		ep = cp + --c;
		if((lastchar = cp[c]) != cut->eob)
			*ep = cut->eob;
		/* process each line in the buffer */
		while (cp <= ep)
		{
			first = cp;
			if (!inword)
			{
				nodelim = empty = 1;
				copy = cp;
				if (nfields = *(lp = cut->list))
					copy = 0;
				else
					nfields = *++lp;
			}
			else if (copy)
				copy = cp;
			inword = 0;
			do
			{
				/* skip over non-delimiter characters */
				if (cut->mb)
					for (;;)
					{
						switch (c = sp[*(unsigned char*)cp++])
						{
						case 0:
							continue;
						case SP_WIDE:
							wp = --cp;
							while ((c = mb2wc(w, cp, ep - cp)) <= 0)
							{
								/* mb char possibly spanning buffer boundary -- fun stuff */
								if ((ep - cp) < mbmax())
								{
									int	i;
									int	j;
									int	k;

									if (lastchar != cut->eob)
									{
										*ep = lastchar;
										if ((c = mb2wc(w, cp, ep - cp)) > 0)
											break;
									}
									if (copy)
									{
										empty = 0;
										if ((c = cp - copy) > 0 && sfwrite(fdout, (char*)copy, c) < 0)
											goto failed;
									}
									for (i = 0; i <= (ep - cp); i++)
										mb[i] = cp[i];
									if (!(bp = (unsigned char*)sfreserve(fdin, SF_UNBOUND, -1)) || (c = sfvalue(fdin)) <= 0)
										goto failed;
									cp = bp;
									ep = cp + --c;
									if ((lastchar = cp[c]) != cut->eob)
										*ep = cut->eob;
									j = i;
									k = 0;
									while (j < mbmax())
										mb[j++] = cp[k++];
									if ((c = mb2wc(w, (char*)mb, j)) <= 0)
									{
										c = i;
										w = 0;
									}
									first = bp = cp += c - i;
									if (copy)
									{
										copy = bp;
										if (w == cut->ldelim.chr)
											lastchar = cut->ldelim.chr;
										else if (w != cut->wdelim.chr)
										{
											empty = 0;
											if (sfwrite(fdout, (char*)mb, c) < 0)
												goto failed;
										}
									}
									c = 0;
								}
								else
								{
									w = *cp;
									c = 1;
								}
								break;
							}
							cp += c;
							c = w;
							if (c == cut->wdelim.chr)
							{
								c = SP_WORD;
								break;
							}
							if (c == cut->ldelim.chr)
							{
								c = SP_LINE;
								break;
							}
							continue;
						default:
							wp = cp - 1;
							break;
						}
						break;
					}
				else
				{
					while (!(c = sp[*cp++]));
					wp = cp - 1;
				}
				/* check for end-of-line */
				if (c == SP_LINE)
				{
					if (cp <= ep)
						break;
					if (lastchar == cut->ldelim.chr)
						break;
					/* restore cut->last character */
					if (lastchar != cut->eob)
						*ep = lastchar;
					inword++;
					if (!sp[lastchar])
						break;
				}
				nodelim = 0;	
				if (--nfields > 0)
					continue;
				nfields = *++lp;
				if (copy)
				{
					empty = 0;
					if ((c = wp - copy) > 0 && sfwrite(fdout, (char*)copy, c) < 0)
						goto failed;
					copy = 0;
				}
				else
					/* set to delimiter unless the first field */
					copy = empty ? cp : wp;
			} while (!inword);
			if (!inword)
			{
				if (!copy)
				{
					if (nodelim)
					{
						if (!cut->sflag)
						{
							if (offset)
							{
								sfseek(fdtmp,(Sfoff_t)0,SEEK_SET);
								sfmove(fdtmp,fdout,offset,-1);
							}
							copy = first;
						}
					}
					else
						sfputc(fdout,'\n');
				}
				if (offset)
					sfseek(fdtmp,offset=0,SEEK_SET);
			}
			if (copy && (c=cp-copy)>0 && (!nodelim || !cut->sflag) && sfwrite(fdout,(char*)copy,c)< 0)
				goto failed;
		}
		/* see whether to save in tmp file */
		if(inword && nodelim && !cut->sflag && (c=cp-first)>0)
		{
			/* copy line to tmpfile in case no fields */
			if(!fdtmp)
				fdtmp = sftmp(BLOCK);
			sfwrite(fdtmp,(char*)first,c);
			offset +=c;
		}
	}
 failed:
	if(fdtmp)
		sfclose(fdtmp);
}
コード例 #19
0
ファイル: tstack.c プロジェクト: att/ast
tmain() {
    UNUSED(argc);
    UNUSED(argv);
    Sfio_t *f1, *f2, *f3, *f;
    char *s, *s1, *s2, *s3, *s4;
    int n;
    int fd[2];

    if (!(f1 = sfopen(NULL, tstfile("sf", 0), "w+"))) terror("Opening file1");
    if (!(f2 = sfopen(NULL, tstfile("sf", 0), "w+"))) terror("Opening file2");
    Fclose = f2;
    sfdisc(f1, &Disc);
    sfdisc(f2, &Disc);
    sfstack(f1, f2);
    if ((n = sfgetc(f1)) >= 0 || !sfeof(f1)) terror("There should be no data n=%d", n);
    if (sfstacked(f1)) terror("There should be no stack");
    Fclose = f1;
    if (sfclose(f1) < 0) terror("Can't close f1");
    tcleanup();

    s1 = "1234567890";
    s2 = "abcdefghijklmnopqrstuvwxyz";
    s3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    s4 = "!@#$%^&*()_-+={}[]~`':;?/><,|";

    if (!(f1 = sfopen(NULL, s1, "s")) || !(f2 = sfopen(NULL, s2, "s")) ||
        !(f3 = sfopen(NULL, s3, "s"))) {
        terror("Opening strings");
    }

    sfdisc(sfstdin, &Disc);
    sfclose(sfstdin);
    if (sffileno(sfstdin) != 0) terror("Bad fd for stdin");

    if (!(f = sfopen(NULL, tstfile("sf", 0), "w+"))) terror("Opening file");
    if (sfwrite(f, "0123456789", 10) != 10) terror("Write file");
    if (sfseek(f, (Sfoff_t)0, 0) != 0) terror("Seek file");

    if (sfstack(sfstdin, f) != sfstdin) terror("Stacking on stdin2");
    if (sfopen(sfstdout, "/dev/null", "w") != sfstdout) terror("Opening sfstdout");
    if (sfmove(sfstdin, sfstdout, (Sfoff_t)SF_UNBOUND, -1) != 10 || !sfeof(sfstdin) ||
        sferror(sfstdout)) {
        terror("Bad sfmove");
    }

    tcleanup();

    if (!(f = sftmp(0))) terror("Opening temp file");
    if (sfputr(f, s4, -1) != (ssize_t)strlen(s4)) terror("Writing s4");
    sfseek(f, (Sfoff_t)0, 0);

#if FIX_THIS_TEST_2008_08_11
    if (sfstack(f, f3) != f) terror("Stacking s3");
    if (sfstack(f, f2) != f) terror("Stacking s2");
    if (sfstack(f, f1) != f) terror("Stacking s1");

    sfsprintf(str, sizeof(str), "%s%s%s%s", s1, s2, s3, s4);
    if ((ss = sfgetr(f, '\n', 1)))
        terror("There shouldn't have been any new-line");
    else {
        if (!(ss = sfgetr(f, '\n', -1))) terror("Reading streams");
        n = sfvalue(f);
        if (ss[n]) ss[n] = 0;
    }

    if (strcmp(ss, str) != 0) terror("Expect=%s Got=%s", str, ss);
#endif

    if (!(f1 = sfopen(NULL, s1, "s")) || !(f2 = sfopen(NULL, s2, "s")) ||
        !(f3 = sfopen(NULL, s3, "s"))) {
        terror("Opening strings2");
    }
    sfseek(f, (Sfoff_t)0, 0);

    if (sfstack(f, f3) != f || sfstack(f, f2) != f || sfstack(f, f1) != f) {
        terror("Stacking streams2");
    }

    if (!(s = sfreserve(f, SF_UNBOUND, 0)) || s != s1) terror("Sfpeek1");

    if (!(s = sfreserve(f, SF_UNBOUND, 0)) || s != s2) terror("Sfpeek2");

    if (!(s = sfreserve(f, SF_UNBOUND, 0)) || s != s3) terror("Sfpeek3");

    if (!(s = sfreserve(f, SF_UNBOUND, 0)) || strncmp(s, s4, strlen(s4)) != 0) terror("Sfpeek4");

    /* test to see if hidden read data still accessible */
    if (pipe(fd) < 0) terror("Can't create pipe");
    if (!(f1 = sfnew(0, NULL, (size_t)SF_UNBOUND, fd[0], SF_READ | SF_WRITE))) {
        terror("Can't create stream");
    }

    if (write(fd[1], "0123", 4) != 4) terror("Can't write to pipe");
    if (sfgetc(f1) != '0') terror("sfgetc failed");

    /* hack to create hidden reserved buffer */
    f1->file = fd[1];
    if (sfwrite(f1, "4", 1) != 1) terror("Can't write to stream");
    sfsync(f1);
    f1->file = fd[0];
    close(fd[1]);

    /* now stack stream */
    if (!(f2 = sfopen(0, "abcd\n", "s"))) terror("Can't open string stream");

    sfstack(f2, f1);

    if (!(s = sfgetr(f2, '\n', 1))) terror("sfgetr failed");

    if (strcmp(s, "1234abcd") != 0) terror("sfgetr got wrong data");

    texit(0);
}