Esempio n. 1
0
static int 
name(void)
{
	register int t;
	register char *cp;

	for (;;) {
		t = yylex();
		if (t != WORD)
			return(-1);
		cp = yylval;
		t = yylex();
		switch (t) {
		case 0:
			nstrcat(netbuf, sizeof (netbuf), cp);
			return(0);

		case '@':
		case '%':
			if (name())
				return(-1);
			stradd(netbuf, sizeof (netbuf), '@');
			nstrcat(netbuf, sizeof (netbuf), cp);
			return(0);	
		case WORD:
			return(-1);

		default:
			nstrcat(netbuf, sizeof (netbuf), cp);
			stradd(netbuf, sizeof (netbuf), t);
		}
	}
}
// Converts a floating point number to string.
void CntrlSubGroup::ftoa(float f, char s[], int afterpoint)
{
	// Extract integer part
	int ipart = (int)f;

	// Extract floating part
	float fpart = f - (float)ipart;
	if (fpart < 0)
		fpart = -fpart;
	// convert integer part to string

	char _texti[string_length];
	itoa(ipart, _texti);

	// check for display option after point
	for (int i = 0; i < afterpoint; i++)
	{
		fpart *= 10;
	}
	// convert float part to string

	char _textf[string_length];
	itoa(fpart, _textf);
	s[0] = 0;
	stradd(s, _texti);
	stradd(s, ".");
	stradd(s, _textf);
}
Esempio n. 3
0
void exec(const char *str, char *err)
{
	// this function executes a given instruction.
	// all important functions are called from here.

	void evali(const char *str, char *err, int *eval);
	char asgn[ID]="";  /* assignment variable name container*/
	strcpy(err,"");  /* empty error container string */
	int integer=0;  /* integer to store integer evaluation results */
	double real=0;  /* double to store double evaluation results */

	if(prechar(asgn,str,"=")=='=') /* check for = operator */
	{
		if(strtrims(asgn,' '))
		{  // if assignment string is empty
			strcpy(err,"Assignment variable is not specified.");
			return;
		}
		char isid = id_check(asgn);
		if(!isid)
		{
			// assign ***************************************************
			printf("\nassgin: %s\n",asgn);
			return;
		}
		else  /* is not an identifier */
		{
			if(isid==1)  /* var name starts with a number */
			{
				strcpy(err,"Variable name cannot start with a number.");
				return;
			}
			else  /* var name has illegal chars*/
			{
				stradd(err,"Variable cannot contain [");
				straddc(err,isid);
				stradd(err,"] character");
			}
			return;
		}
	}
	else  /* there is no assigment involved */
	{
		// if there is no assignment then integer is considered
		// to be the default assignment data type for evaluation.

		evali(str,err,&integer);
		if(!strlen(err))
		{
			printf("\nint: %d\n",integer);
			return;
		}
		else
		{
			return;
		}
	}
	return;
}
Esempio n. 4
0
void runline(const char *cmd, char *err)
{
	// this function takes an instruction for execution.
	// it removes all comments and passes the statement to exec

	void exec(const char *str, char *err);
	char impurity = purity_check(cmd);
	if(*cmd==';') /* if statement is a comment. */
	return;
	if(!impurity)  /* if cmd is pure */
	{
		strcpy(err,"");
		char *statement = NULL;
		if((statement=(char *)(malloc(sizeof(char)*
		(strlen(cmd)+1))))==NULL) allocerr(); *statement='\0';
		char *spointer = statement;
		int l = 0;  /* to store length of spointer */
		l = strlen(cmd);
		int i = 0;  /* loop counter */
		char qt=0;
		for(i=0;i<l;i++,cmd++,spointer++)
		{
			if(*cmd==34||*cmd==39)  /* char["] and char['] */
			{
				if(qt==0)
				qt = 1;  /* quotation mark starts */
				else
				qt = 0;  /* quotation mark ends */
			}
			if(qt==0)
			if(*cmd==';')  /* remove comments from the statement */
			break;
			*spointer = *cmd;  /* transfer cmd to str */
		}
		*spointer='\0';  /* set termination point for string */
		strtrims(statement,' ');
		/* now run the statement */
		exec(statement,err);
		if(!strlen(err))    /* if eval was succesfull. */
		{
			free(statement);
			statement = NULL;
			return;
		}
		else    /* if eval was un-succesfull. */
		{
			free(statement);
			statement = NULL;
			return;
		}
	}
	else  /* if cmd is impure */
	{
		stradd(err,"Character [");
		straddc(err,impurity);
		stradd(err,"] is not allowed.");
		return;
	}
}
Esempio n. 5
0
void makeHttpResponse(const char *message, char *response) {
    *response = '\0';

    stradd(response, "HTTP/1.1 200 OK\r\n");
    stradd(response, "Content-length: ");
    char contentLengthStr[100];
    sprintf(contentLengthStr, "%u", strlen(message));
    stradd(response, contentLengthStr);
    stradd(response, "\r\n\r\n");
    stradd(response, message);
}
Esempio n. 6
0
void send_channel_users_info(User *user, Node *users, char *query, char *send_line) {
    Node *first = users;
    Node *p     = first;
    int sent    = 0;

    User *u = (User *) p->payload;
    if(strcmp(u->current_channel, query) == 0) {
        send_user_info(user, u, send_line);
        sent += 1;
    };
    p = p->next;
    while(p != first) {
        u = (User *) p->payload;
        if(strcmp(u->current_channel, query) == 0) {
            send_user_info(user, u, send_line);
            sent += 1;
        };
        p = p->next;
    };
    if(sent > 0) {
        send_line = strset(":");
        send_line = stradd(send_line, SERVER_NAME);
        send_line = stradd(send_line, " ");
        send_line = stradd(send_line, RPL_ENDOFWHO);
        send_line = stradd(send_line, " ");
        send_line = stradd(send_line, user->name);
        send_line = stradd(send_line, " #");
        send_line = stradd(send_line, user->current_channel);
        send_line = stradd(send_line, ENDOFWHO);

        write(user->socket, send_line, strlen(send_line));
    };
};
Esempio n. 7
0
void		single_path(t_list *list, int ant)
{
	t_list	*link;
	t_salle	*s;
	char	*str;
	int		i;

	i = 0;
	str = (char *)malloc(sizeof(char) * 1000);
	link = list;
	s = TC;
	while (TC->status != END)
	{
		link = s->link;
		while (link != NULL && (TC->way_value != 1 || s->dist > TC->dist || TC->status == START))
		{
			if (TC->status == END)
				break ;
			link = link->next;
		}
		s = TC;
		str = stradd(TC->name, str);
	}
	while (str[i])
		i++;
	single_path_norme(i, str, list, ant);
}
Esempio n. 8
0
void
oadd(Node *n, Node *res)
{
	Node l, r;

	expr(n->left, &l);
	expr(n->right, &r);
	res->nstore.fmt = l.nstore.fmt;
	res->op = OCONST;
	res->type = TFLOAT;
	switch(l.type) {
	default:
		error("bad lhs type +");
	case TINT:
		switch(r.type) {
		case TINT:
			res->type = TINT;
			res->nstore.u0.sival = l.nstore.u0.sival+r.nstore.u0.sival;
			break;
		case TFLOAT:
			res->nstore.u0.sfval = l.nstore.u0.sival+r.nstore.u0.sfval;
			break;
		default:
			error("bad rhs type +");
		}
		break;
	case TFLOAT:
		switch(r.type) {
		case TINT:
			res->nstore.u0.sfval = l.nstore.u0.sfval+r.nstore.u0.sival;
			break;
		case TFLOAT:
			res->nstore.u0.sfval = l.nstore.u0.sfval+r.nstore.u0.sfval;
			break;
		default:
			error("bad rhs type +");
		}
		break;
	case TSTRING:
		if(r.type == TSTRING) {
			res->type = TSTRING;
			res->nstore.fmt = 's';
			res->nstore.u0.sstring = stradd(l.nstore.u0.sstring, r.nstore.u0.sstring); 
			break;
		}
		error("bad rhs for +");
	case TLIST:
		res->type = TLIST;
		switch(r.type) {
		case TLIST:
			res->nstore.u0.sl = addlist(l.nstore.u0.sl, r.nstore.u0.sl);
			break;
		default:
			r.left = 0;
			r.right = 0;
			res->nstore.u0.sl = addlist(l.nstore.u0.sl, construct(&r));
			break;
		}
	}
}
Esempio n. 9
0
void
strset(char *p)
{
	if (str != NULL)
		str[0] = '\0';
	stradd(p);
}
Esempio n. 10
0
 string stradd(string& a,string& b){
     if(a.length()<b.length())
         return stradd(b,a);
     string res(a.length(),'0');
     int carry=0;
     int temp=0;
     int i=a.length()-1;
     int j=b.length()-1;
     for(;j>=0;i--,j--){
         temp=(a[i]-'0')+(b[j]-'0')+carry;
         carry=temp/10;
         temp=temp%10;
         res[i]=temp+'0';
     }
     for(;i>=0;i--){
         temp=(a[i]-'0')+carry;
         carry=temp/10;
         temp=temp%10;
         res[i]=temp+'0';
     }
     if(carry>0)
         return "1"+res;
     else
         return res;
 }
Esempio n. 11
0
SV *
getFieldTypeFromAV ( BrokerTypeDef type_def, char * key )
{
AV * av;
int numKeys;
short type;


	av = newAV();
	key = stradd ( key, "[]" );
	gErr = awGetTypeDefFieldType ( type_def, key, &type );

	if ( gErr != AW_NO_ERROR ) {
		warn ( "ERROR %s", awErrorToCompleteString ( gErr ) );
		return ( Nullsv );
	}

	if ( type == FIELD_TYPE_STRUCT )
		av_push ( av, getFieldTypeFromHV (type_def, key) );
	else
		av_push( av, newSViv ( type ) );


	return ( newRV_noinc((SV*) av) );
}
Esempio n. 12
0
static void 
optim1(char netstr[], char name[])
{
	char path[STSIZ], rpath[STSIZ];
	register char *cp, *cp2;
	register int tp, nc;
	
	cp = netstr;
	prefer(cp);
	*name  = '\0';
	/*
	 * If the address ultimately points back to us,
	 * just return a null network path.
	 */
	if ((int)strlen(cp) > 1 && cp[strlen(cp) - 2] == LOCAL)
		return;
	while (*cp != 0) {
		*path = '\0';

		tp = ntype(cp[1]);
		nc = cp[1];
		while (*cp && tp == ntype(cp[1])) {
			stradd(path, sizeof (path), *cp++);
			cp++;
		}
		switch (netkind(tp)) {
		default:
			nstrcpy(rpath, sizeof (rpath), path);
			break;

		case IMPLICIT:
			optimimp(path, rpath);
			break;

		case EXPLICIT:
			optimex(path, rpath);
			break;
		}
		for (cp2 = rpath; *cp2 != 0; cp2++) {
			stradd(name, BUFSIZ, *cp2);
			stradd(name, BUFSIZ, nc);
		}
	}
	optiboth(name);
	prefer(name);
}
Esempio n. 13
0
/**
   Append text to clipboard (primary and default).
*/
static void clipboard_append(const char *jobinfo){
    GdkAtom atoms[2]={GDK_SELECTION_CLIPBOARD, GDK_SELECTION_PRIMARY};
    for(int iatom=0; iatom<2; iatom++){
	GtkClipboard *clip=gtk_clipboard_get(atoms[iatom]);
	if(!clip) continue;
	gchar *old=gtk_clipboard_wait_for_text(clip);
	gchar *newer=NULL;
	if(old){
	    newer=stradd(old, jobinfo, "\n", NULL);
	    g_free(old);
	}else{
	    newer=stradd(jobinfo, "\n", NULL);
	}
	gtk_clipboard_set_text(clip, newer, -1);
	free(newer);
    }
}
Esempio n. 14
0
SType SType::operator+(const SType &other) 
{
  SType sum;
  sum.strString = stradd(strString, other.strString);
  sum.iLine = -1;
  sum.bCrossesStates = bCrossesStates||other.bCrossesStates;
  return sum;
};
Esempio n. 15
0
File: skyc.c Progetto: bitursa/maos
/**
   The main(). It parses the command line, setup the parms, ask the scheduler
   for signal to proceed, and then starts skysim to do sky coverage.
 */
int main(int argc, const char *argv[]){
    dirstart=mygetcwd();
    char *scmd=argv2str(argc, argv, " ");
    ARG_S* arg=parse_args(argc,argv);
    /*In detach mode send to background and disable drawing*/
    if(arg->detach){
	daemonize();
    }else{
	redirect();
    }
    info2("%s\n", scmd);
    info2("Output folder is '%s'. %d threads\n",arg->dirout, arg->nthread);
    skyc_version();
    /*register signal handler */
    register_signal_handler(skyc_signal_handler);
    /*
      Ask job scheduler for permission to proceed. If no CPUs are available,
      will block until ones are available.  if arg->force==1, will run
      immediately.
    */
    scheduler_start(scmd,arg->nthread,0,!arg->force);
    /*setting up parameters before asking scheduler to check for any errors. */
    dirsetup=stradd("setup",NULL);
    PARMS_S * parms=setup_parms(arg);
    if(parms->skyc.dbg){
	mymkdir("%s",dirsetup);
    }
    if(!arg->force){
	info2("Waiting start signal from the scheduler ...\n");
	/*Failed to wait. fall back to own checking.*/
	int count=0;
	while(scheduler_wait()&& count<60){
	    warning_time("failed to get reply from scheduler. retry\n");
	    sleep(10);
	    count++;
	    scheduler_start(scmd,arg->nthread,0,!arg->force);
	}
	if(count>=60){
	    warning_time("fall back to own checker\n");
	    wait_cpu(arg->nthread);
	}
    }
    info2("Simulation started at %s in %s.\n",myasctime(),myhostname());
    free(scmd);
    free(arg->dirout);
    free(arg);
    THREAD_POOL_INIT(parms->skyc.nthread);
    /*Loads the main software*/
    OMPTASK_SINGLE skysim(parms);
    free_parms(parms);
    free(dirsetup);
    free(dirstart);
    rename_file(0);
    scheduler_finish(0);
    info2("End:\t%.2f MiB\n",get_job_mem()/1024.);
    info2("Simulation finished at %s in %s.\n",myasctime(),myhostname());
    return 0;
}
Esempio n. 16
0
int main (){
    FILE *input;
    input = fopen("text.txt", "r");

    char *str = strnew();

    sentence_t *currSentence = sentence_create();
    text_t *text = text_create();

    while (1) {
        char c = fgetc(input);
        if (c == EOF || isspace(c) || c == ',' || c == '.' || c == '!' || c == '?' || c == ';') {
            if (strlen(str) != 0) {
                word_t *word = word_new(str);
                sentence_add(currSentence, word);
                free (str);
                word_free (word);
                str = strnew();
            }
        }
        if (c == EOF || c == '.' || c == '!' || c == '?') {
            text_add (text, currSentence);
            sentence_free(currSentence);
            currSentence = sentence_create();
        }
        if (c == EOF) break;
        if (isalpha(c)) {
            c = tolower(c);
            char *w = stradd(str, c);
            free (str);
            str = w;
        }
    }
    fclose (input);
    FILE *output;
    output = fopen("result.txt", "w");
    input = fopen ("stopwords.txt", "r");

    int stopCount, i;
    fscanf (input, "%d", &stopCount);
    for (i = 0; i < stopCount; i++) {
        char s[15];
        fscanf (input, "%s", s);
        fprintf (output, "%s: %d\n", s, text_find (text, s));
    }

    fclose (input);
    fclose (output);
    free (str);
    sentence_free(currSentence);
    text_free(text);
    return 0;
}
Esempio n. 17
0
int exec(const char *cmd, char *err)
{
	int runline(const char *str, char *err);
	char _err[KB]=_NULL;
	if(*cmd==';') /* if statemnt is a comment. */
	return 0;
	char purity_check(const char *str);
	char impurity = purity_check(cmd);
	if(!impurity)  /* if cmd is pure */
	{
		char statement[KB]=_NULL;
		// remove comments from the statement
		int l = 0;  /* to store length of spointer */
		l = strlen(cmd);
		int i = 0;  /* loop counter */
		for(i=0;i<l;i++)
		{
			if(*cmd==';')
			break;
			statement[i] = *cmd;
			cmd++;
		}
		statement[i]='\0';
		// now run the statement
		if(!runline(statement,_err))  /* if eval was succesfull. */
		return 0;
		else  /* if eval was un-succesfull. */
		strcpy(err,_err);  /* transfer eval's err to err */
		return 1;
	}
	else  /* if cmd is impure */
	{
		stradd(err,"Character [");
		straddc(err,impurity);
		stradd(err,"] is not allowed.");
		return 1;
	}
	return 1;
}
Esempio n. 18
0
static void print_strange_sections(PE_FILE *pe)
{
	bool aux = false;

	if (!pe_get_sections(pe) || !pe->num_sections)
		return;

	if (pe->num_sections <= 2)
		snprintf(value, MAX_MSG, "%d (low)", pe->num_sections);
	else if (pe->num_sections > 8)
		snprintf(value, MAX_MSG, "%d (high)", pe->num_sections);
	else
		snprintf(value, MAX_MSG, "%d", pe->num_sections);

	output("section count", value);
	for (unsigned i=0; i < pe->num_sections && i <= 65535; i++, aux=false)
	{
		memset(&value, 0, sizeof(value));

		if (!strisprint((const char *)pe->sections_ptr[i]->Name))
			stradd(value, "suspicious name", &aux);

		if (!pe->sections_ptr[i]->SizeOfRawData)
			stradd(value, "zero length", &aux);
		else if (pe->sections_ptr[i]->SizeOfRawData <= 512)
			stradd(value, "small length", &aux);

		// rwx or writable + executable code
		if (pe->sections_ptr[i]->Characteristics & 0x80000000 &&
		(pe->sections_ptr[i]->Characteristics & 0x20 ||
		pe->sections_ptr[i]->Characteristics & 0x20000000))
			stradd(value, "self-modifying", &aux);

		if (!aux)
			strncpy(value, "normal", 7);

		output((char *)pe->sections_ptr[i]->Name, value);
	}
}
Esempio n. 19
0
 bool solve(string& num1,string& num2,string num){
     int maxLen=max(num1.length(),num2.length());
     string res=stradd(num1,num2);
     string num3=num.substr(0,maxLen);
     if(maxLen>1&&num3[0]=='0')
         return false;
     if(res==num3&&(num3==num||solve(num2,num3,num.substr(maxLen))))
         return true;
     num3=num.substr(0,maxLen+1);
     if(res==num3&&(num3==num||solve(num2,num3,num.substr(maxLen+1))))
         return true;
     return false;
 }
Esempio n. 20
0
static ssize_t cpu_read(struct file *filp, char __user *buf,
    size_t count, loff_t *pos)
{
	char cpu_info_str[128];
	long freq = __proc_global_info.tsc_freq, idx;

	strncpy(cpu_info_str, "cpu MHz\t\t: ", 16);
	idx = strlen(cpu_info_str);

	stradd(cpu_info_str + idx, freq / 1000000, 4);
	idx += 4;

	strncpy(cpu_info_str + idx, ".", 1);
	idx++;

	stradd(cpu_info_str + idx, freq % 1000000, 3);
	idx += 3;

	cpu_info_str[idx] = 0;

	return sysfs_read(buf, count, pos, cpu_info_str);
}
Esempio n. 21
0
int check_charset(char **filename,const char *charset) {
	char *tmppath;
	if (!strncmp(charset,"utf-8",6)) {
		*filename=strdup("utf-8");
		return 1;
	}   
	tmppath=find_file(stradd(charset,CHARSET_EXT),charset_path);
	if (tmppath&& *tmppath) {
		*filename=strdup(charset);
		free(tmppath);
		return 1;
	}
	return 0;
}
Esempio n. 22
0
static void
promptpath(char *p, int npath, int tilde)
{
    char *modp = p;
    Nameddir nd;

    if (tilde && ((nd = finddir(p))))
	modp = tricat("~", nd->node.nam, p + strlen(nd->dir));

    if (npath) {
	char *sptr;
	if (npath > 0) {
	    for (sptr = modp + strlen(modp); sptr > modp; sptr--) {
		if (*sptr == '/' && !--npath) {
		    sptr++;
		    break;
		}
	    }
	    if (*sptr == '/' && sptr[1] && sptr != modp)
		sptr++;
	    stradd(sptr);
	} else {
	    char cbu;
	    for (sptr = modp+1; *sptr; sptr++)
		if (*sptr == '/' && !++npath)
		    break;
	    cbu = *sptr;
	    *sptr = 0;
	    stradd(modp);
	    *sptr = cbu;
	}
    } else
	stradd(modp);

    if (p != modp)
	zsfree(modp);
}
Esempio n. 23
0
File: mv.c Progetto: finkler/avianos
void
cp(char *src, char *dst)
{
  char cmd[10], *p;
  int err;

  strcpy(cmd, "cp -fRPp");
  p = stradd(cmd, " ", src, " ", dst);
  err = system(p);
  free(p);
  if(err)
    return;
  if(unlink(src))
    alert("unlink %s: %m", src);
}
Esempio n. 24
0
main()
{
    char  	linebuffer[MAXINPUT];
    int  	linebuffersize = 0;
    char  	line[MAXINPUT];
    int  	linesize = 0;


    while( (linesize = getline1(line, MAXINPUT)) > 0 )
    {
        if(linesize > LINEMAX)
        {
            linesize = validateline(line, linesize);
            linebuffersize = stradd(line, linebuffer, linebuffersize);
        }
    }
    printf("%sBuffer=%d\n", linebuffer, linebuffersize);
}
Esempio n. 25
0
int file_mkfifo(const char *__name, uint32_t open_flags)
{
	bool readonly = 0;
	switch (open_flags & O_ACCMODE) {
	case O_RDONLY:
		readonly = 1;
	case O_WRONLY:
		break;
	default:
		return -E_INVAL;
	}

	int ret;
	struct file *file;
	if ((ret = filemap_alloc(NO_FD, &file)) != 0) {
		return ret;
	}

	char *name;
	const char *device = readonly ? "pipe:r_" : "pipe:w_";

	if ((name = stradd(device, __name)) == NULL) {
		ret = -E_NO_MEM;
		goto failed_cleanup_file;
	}

	if ((ret = vfs_open(name, open_flags, &(file->node))) != 0) {
		goto failed_cleanup_name;
	}
	file->pos = 0;
	file->readable = readonly, file->writable = !readonly;
	filemap_open(file);
	kfree(name);
	return file->fd;

failed_cleanup_name:
	kfree(name);
failed_cleanup_file:
	filemap_free(file);
	return ret;
}
Esempio n. 26
0
static char *generate_file_name(bgpcorsaro_t *bgpcorsaro, const char *plugin,
                                bgpcorsaro_interval_t *interval,
                                int compress_type)
{
  /* some of the structure of this code is borrowed from the
     FreeBSD implementation of strftime */

  /* the output buffer */
  /* @todo change the code to dynamically realloc this if we need more
     space */
  char buf[1024];
  char tbuf[1024];
  char *bufp = buf;
  char *buflim = buf + sizeof(buf);

  char *tmpl = bgpcorsaro->template;
  char secs[11]; /* length of UINT32_MAX +1 */
  struct timeval tv;

  for (; *tmpl; ++tmpl) {
    if (*tmpl == '.' && compress_type == WANDIO_COMPRESS_NONE) {
      if (strncmp(tmpl, BGPCORSARO_IO_ZLIB_SUFFIX,
                  strlen(BGPCORSARO_IO_ZLIB_SUFFIX)) == 0 ||
          strncmp(tmpl, BGPCORSARO_IO_BZ2_SUFFIX,
                  strlen(BGPCORSARO_IO_BZ2_SUFFIX)) == 0) {
        break;
      }
    } else if (*tmpl == '%') {
      switch (*++tmpl) {
      case '\0':
        --tmpl;
        break;

      /* BEWARE: if you add a new pattern here, you must also add it to
       * bgpcorsaro_io_template_has_timestamp */

      case BGPCORSARO_IO_MONITOR_PATTERN:
        bufp = stradd(bgpcorsaro->monitorname, bufp, buflim);
        continue;

      case BGPCORSARO_IO_PLUGIN_PATTERN:
        bufp = stradd(plugin, bufp, buflim);
        continue;

      case 's':
        if (interval != NULL) {
          snprintf(secs, sizeof(secs), "%" PRIu32, interval->time);
          bufp = stradd(secs, bufp, buflim);
          continue;
        }
      /* fall through */
      default:
        /* we want to be generous and leave non-recognized formats
           intact - especially for strftime to use */
        --tmpl;
      }
    }
    if (bufp == buflim)
      break;
    *bufp++ = *tmpl;
  }

  *bufp = '\0';

  /* now let strftime have a go */
  if (interval != NULL) {
    tv.tv_sec = interval->time;
    strftime(tbuf, sizeof(tbuf), buf, gmtime(&tv.tv_sec));
    return strdup(tbuf);
  }

  return strdup(buf);
}
Esempio n. 27
0
void evali(const char *str, char *err, int *eval)
{
	//   Mathematical Expression Evaluation Function
	//  -----------------------------------------------
	//   This functions solves mathematical equations.
	//   When a complex equation is passed via *str,
	//   the equation is broken into parts, and the
	//   simplest part is passed on recursively onto
	//   the function itself. This recurvise process is 
	//   repeated until the whole equation has been solved.
	//   Results of the evaluation are stored in int eval.

	if(!bcheck(str))
	{
		/* this is the core of eval where the calculations are done.
		at this level, the equation does not have any brackets. */

		const char symbols[]="^*/%+-&";
		const char se[]="Invalid Syntax";

		char *tmp = NULL;
		if((tmp=(char *)(malloc(sizeof(char)*
		(strlen(str)+1))))==NULL) allocerr(); *tmp='\0';
		/* check wether str has reached the absolute stage */
		if(prechar(tmp,str,symbols)==0)
		{
			printf("\n[simple]");
			if(!ncheck(str))
			{
				printf("\nequation solved!");
				*eval = strint(str);
				free(tmp);
				tmp = NULL;
				return;
			}
			else if(!id_check(str))
			{
				printf("\nit's a variable!");
				free(tmp);
				tmp = NULL;
				return;
			}
			else
			{
				strcpy(err,se);
				stradd(err,": ");
				stradd(err,str);
				free(tmp);
				tmp = NULL;
				return;
			}
		}
		else  /* there are symbols in str */
		{
			free(tmp);
			tmp = NULL;
		}

		/* now the real maths */
		printf("\n[complex]");
		char *pre = NULL; /* string preceding of operator */
		char *pos = NULL; /* string succeding the operator */
		/* now allocate the variables */
		if((pre=(char *)(malloc(sizeof(char)*
		(strlen(str)+1))))==NULL) allocerr(); *pre='\0';
		if((pos=(char *)(malloc(sizeof(char)*
		(strlen(str)+1))))==NULL) allocerr(); *pos='\0';
		char symbol = 0;
		if(prechar(pre,str,"^"))
		{ if(postchar(pos,str,"^"))
		symbol = '^'; }
		else if(prechar(pre,str,"*"))
		{ if(postchar(pos,str,"*"))
		symbol = '*'; }
		else if(prechar(pre,str,"/"))
		{ if(postchar(pos,str,"/"))
		symbol = '/'; }
		else if(prechar(pre,str,"%"))
		{ if(postchar(pos,str,"%"))
		symbol = '%'; }
		else if(prechar(pre,str,"+"))
		{ if(postchar(pos,str,"+"))
		symbol = '+'; }
		else if(prechar(pre,str,"-"))
		{ if(postchar(pos,str,"-"))
		symbol = '-'; }
		else if(prechar(pre,str,"&"))
		{ if(postchar(pos,str,"&"))
		symbol = '&'; }
		char *ax = NULL; /* value preceding of operator */
		char *bx = NULL; /* value succeding the operator */
		char *cx = NULL; /* value of ax and bx processed */
		/* now allocate the variables */
		if((ax=(char *)(malloc(sizeof(char)*
		(strlen(pre)+1))))==NULL) allocerr(); *ax='\0';
		if((bx=(char *)(malloc(sizeof(char)*
		(strlen(pos)+1))))==NULL) allocerr(); *bx='\0';
		if((cx=(char *)(malloc(sizeof(char)*
		(strlen(str)+1))))==NULL) allocerr(); *cx='\0';
		/* find out the contents of bx */
		char *ebx = NULL; /* temp string to build bx */
		if((ebx=(char *)(malloc(sizeof(char)*
		(strlen(pos)+1))))==NULL) allocerr(); *ebx='\0';
		strcpy(bx,pos);
		strcpy(ebx,bx);
		for(;;)  /* infinite loop */
		{
			if(!prechar(bx,ebx,symbols))
			{
				strcpy(bx,ebx);
				free(ebx);
				ebx = NULL;
				/* de-allocate ebx */
				break;
			}
			else /* here ebx is build */
			strcpy(ebx,bx);
		}
		/* find out the contents of ax */
		char *eax = NULL; /* temp string to build ax */
		if((eax=(char *)(malloc(sizeof(char)*
		(strlen(pre)+1))))==NULL) allocerr(); *eax='\0';
		strcpy(ax,pre);
		strcpy(eax,ax);
		for(;;)  /* infinite loop */
		{
			if(!postchar(ax,eax,symbols))
			{
				strcpy(ax,eax);
				free(eax);
				eax = NULL;
				/* de-allocate eax */
				break;
			}
			else /* here eax is build */
			strcpy(eax,ax);
		}
		/* variables to store (pre-ax) and (pre-bx) */
		char *prex = NULL;	/* string of (pre-ax) */
		char *posx = NULL;	/* string of (pos-ax) */
		/* now allocate prex and posx */
		if((prex=(char *)(malloc(sizeof(char)*
		(strlen(pre)+1))))==NULL) allocerr(); *prex='\0';
		if((posx=(char *)(malloc(sizeof(char)*
		(strlen(pos)+1))))==NULL) allocerr(); *posx='\0';
		/* find prex and posx */
		strlft(prex,pre,(strlen(pre)-strlen(ax)));
		strrht(posx,pos,(strlen(pos)-strlen(bx)));
		/* de-allocate pre & pos */
		printf("\nsym: %c",symbol);
		printf("\npre: %s",pre);
		printf("\npos: %s",pos);
		free(pre); pre = NULL;
		free(pos); pos = NULL;
		/* process ax and bx to find cx */
// *****************
		/* de-allocate ax & bx */
		printf("\n*ax: %s",ax);
		printf("\n*bx: %s",bx);
		printf("\n*cx: %s",cx);
		printf("\nprx: %s",prex);
		printf("\npox: %s",posx);
		free(ax); ax = NULL;
		free(bx); bx = NULL;
		/* variable to store one-step solved equation */
		char *ex = NULL;
		if((ex=(char *)(malloc(sizeof(char)*
		(strlen(str)+1))))==NULL) allocerr(); *ex='\0';
		/* find ex using cx in prex and posx */
// *****************
		/* now de-allocate cx, prex & posx */
		free(cx); cx = NULL;
		free(prex); cx = NULL;
		free(posx); cx = NULL;
		/* recurse ex on eval for next-step solving */
// *****************
		/* de-allocate ex & return */
		free(ex);
		ex = NULL;
		return;
	}
	else
	{
		if(!bcount(str))
		{
			printf("\nEquation has brackets.");
			return;
		}
		else
		{
			strcpy(err,"Illegal Equation, inequal number of brackets.");
			return;
		}
	}
}
Esempio n. 28
0
static int
putpromptchar(int doprint, int endchar, unsigned int *txtchangep)
{
    char *ss, *hostnam;
    int t0, arg, test, sep, j, numjobs;
    struct tm *tm;
    struct timezone dummy_tz;
    struct timeval tv;
    time_t timet;
    Nameddir nd;

    for (; *bv->fm && *bv->fm != endchar; bv->fm++) {
	arg = 0;
	if (*bv->fm == '%' && isset(PROMPTPERCENT)) {
	    int minus = 0;
	    bv->fm++;
	    if (*bv->fm == '-') {
		minus = 1;
		bv->fm++;
	    }
	    if (idigit(*bv->fm)) {
		arg = zstrtol(bv->fm, &bv->fm, 10);
		if (minus)
		    arg *= -1;
	    } else if (minus)
		arg = -1;
	    if (*bv->fm == '(') {
		int tc, otruncwidth;

		if (idigit(*++bv->fm)) {
		    arg = zstrtol(bv->fm, &bv->fm, 10);
		} else if (arg < 0) {
		    /* negative numbers don't make sense here */
		    arg *= -1;
		}
		test = 0;
		ss = pwd;
		switch (tc = *bv->fm) {
		case 'c':
		case '.':
		case '~':
		    if ((nd = finddir(ss))) {
			arg--;
			ss += strlen(nd->dir);
		    } /*FALLTHROUGH*/
		case '/':
		case 'C':
		    /* `/' gives 0, `/any' gives 1, etc. */
		    if (*ss++ == '/' && *ss)
			arg--;
		    for (; *ss; ss++)
			if (*ss == '/')
			    arg--;
		    if (arg <= 0)
			test = 1;
		    break;
		case 't':
		case 'T':
		case 'd':
		case 'D':
		case 'w':
		    timet = time(NULL);
		    tm = localtime(&timet);
		    switch (tc) {
		    case 't':
			test = (arg == tm->tm_min);
			break;
		    case 'T':
			test = (arg == tm->tm_hour);
			break;
		    case 'd':
			test = (arg == tm->tm_mday);
			break;
		    case 'D':
			test = (arg == tm->tm_mon);
			break;
		    case 'w':
			test = (arg == tm->tm_wday);
			break;
		    }
		    break;
		case '?':
		    if (lastval == arg)
			test = 1;
		    break;
		case '#':
		    if (geteuid() == (uid_t)arg)
			test = 1;
		    break;
		case 'g':
		    if (getegid() == (gid_t)arg)
			test = 1;
		    break;
		case 'j':
		    for (numjobs = 0, j = 1; j <= maxjob; j++)
			if (jobtab[j].stat && jobtab[j].procs &&
		    	    !(jobtab[j].stat & STAT_NOPRINT)) numjobs++;
		    if (numjobs >= arg)
		    	test = 1;
		    break;
		case 'l':
		    *bv->bp = '\0';
		    countprompt(bv->bufline, &t0, 0, 0);
		    if (minus)
			t0 = zterm_columns - t0;
		    if (t0 >= arg)
			test = 1;
		    break;
		case 'e':
		    {
			Funcstack fsptr = funcstack;
			test = arg;
			while (fsptr && test > 0) {
			    test--;
			    fsptr = fsptr->prev;
			}
			test = !test;
		    }
		    break;
		case 'L':
		    if (shlvl >= arg)
			test = 1;
		    break;
		case 'S':
		    if (time(NULL) - shtimer.tv_sec >= arg)
			test = 1;
		    break;
		case 'v':
		    if (arrlen(psvar) >= arg)
			test = 1;
		    break;
		case 'V':
		    if (arrlen(psvar) >= arg) {
			if (*psvar[(arg ? arg : 1) - 1])
			    test = 1;
		    }
		    break;
		case '_':
		    test = (cmdsp >= arg);
		    break;
		case '!':
		    test = privasserted();
		    break;
		default:
		    test = -1;
		    break;
		}
		if (!*bv->fm || !(sep = *++bv->fm))
		    return 0;
		bv->fm++;
		/* Don't do the current truncation until we get back */
		otruncwidth = bv->truncwidth;
		bv->truncwidth = 0;
		if (!putpromptchar(test == 1 && doprint, sep,
				   txtchangep) || !*++bv->fm ||
		    !putpromptchar(test == 0 && doprint, ')',
				   txtchangep)) {
		    bv->truncwidth = otruncwidth;
		    return 0;
		}
		bv->truncwidth = otruncwidth;
		continue;
	    }
	    if (!doprint)
		switch(*bv->fm) {
		  case '[':
		    while(idigit(*++bv->fm));
		    while(*++bv->fm != ']');
		    continue;
		  case '<':
		    while(*++bv->fm != '<');
		    continue;
		  case '>':
		    while(*++bv->fm != '>');
		    continue;
		  case 'D':
		    if(bv->fm[1]=='{')
			while(*++bv->fm != '}');
		    continue;
		  default:
		    continue;
		}
	    switch (*bv->fm) {
	    case '~':
		promptpath(pwd, arg, 1);
		break;
	    case 'd':
	    case '/':
		promptpath(pwd, arg, 0);
		break;
	    case 'c':
	    case '.':
		promptpath(pwd, arg ? arg : 1, 1);
		break;
	    case 'C':
		promptpath(pwd, arg ? arg : 1, 0);
		break;
	    case 'N':
		promptpath(scriptname ? scriptname : argzero, arg, 0);
		break;
	    case 'h':
	    case '!':
		addbufspc(DIGBUFSIZE);
		convbase(bv->bp, curhist, 10);
		bv->bp += strlen(bv->bp);
		break;
	    case 'j':
		for (numjobs = 0, j = 1; j <= maxjob; j++)
		    if (jobtab[j].stat && jobtab[j].procs &&
		    	!(jobtab[j].stat & STAT_NOPRINT)) numjobs++;
		addbufspc(DIGBUFSIZE);
		sprintf(bv->bp, "%d", numjobs);
		bv->bp += strlen(bv->bp);
		break;
	    case 'M':
		queue_signals();
		if ((hostnam = getsparam("HOST")))
		    stradd(hostnam);
		unqueue_signals();
		break;
	    case 'm':
		if (!arg)
		    arg++;
		queue_signals();
		if (!(hostnam = getsparam("HOST")))
		    break;
		if (arg < 0) {
		    for (ss = hostnam + strlen(hostnam); ss > hostnam; ss--)
			if (ss[-1] == '.' && !++arg)
			    break;
		    stradd(ss);
		} else {
		    for (ss = hostnam; *ss; ss++)
			if (*ss == '.' && !--arg)
			    break;
		    stradd(*ss ? dupstrpfx(hostnam, ss - hostnam) : hostnam);
		}
		unqueue_signals();
		break;
	    case 'S':
		txtchangeset(txtchangep, TXTSTANDOUT, TXTNOSTANDOUT);
		txtset(TXTSTANDOUT);
		tsetcap(TCSTANDOUTBEG, TSC_PROMPT);
		break;
	    case 's':
		txtchangeset(txtchangep, TXTNOSTANDOUT, TXTSTANDOUT);
		txtunset(TXTSTANDOUT);
		tsetcap(TCSTANDOUTEND, TSC_PROMPT|TSC_DIRTY);
		break;
	    case 'B':
		txtchangeset(txtchangep, TXTBOLDFACE, TXTNOBOLDFACE);
		txtset(TXTBOLDFACE);
		tsetcap(TCBOLDFACEBEG, TSC_PROMPT|TSC_DIRTY);
		break;
	    case 'b':
		txtchangeset(txtchangep, TXTNOBOLDFACE, TXTBOLDFACE);
		txtchangeset(txtchangep, TXTNOSTANDOUT, TXTSTANDOUT);
		txtchangeset(txtchangep, TXTNOUNDERLINE, TXTUNDERLINE);
		txtunset(TXTBOLDFACE);
		tsetcap(TCALLATTRSOFF, TSC_PROMPT|TSC_DIRTY);
		break;
	    case 'U':
		txtchangeset(txtchangep, TXTUNDERLINE, TXTNOUNDERLINE);
		txtset(TXTUNDERLINE);
		tsetcap(TCUNDERLINEBEG, TSC_PROMPT);
		break;
	    case 'u':
		txtchangeset(txtchangep, TXTNOUNDERLINE, TXTUNDERLINE);
		txtunset(TXTUNDERLINE);
		tsetcap(TCUNDERLINEEND, TSC_PROMPT|TSC_DIRTY);
		break;
	    case 'F':
		arg = parsecolorchar(arg, 1);
		if (arg >= 0 && !(arg & TXTNOFGCOLOUR)) {
		    txtchangeset(txtchangep, arg & TXT_ATTR_FG_ON_MASK,
				 TXTNOFGCOLOUR);
		    txtset(arg & TXT_ATTR_FG_ON_MASK);
		    set_colour_attribute(arg, COL_SEQ_FG, TSC_PROMPT);
		    break;
		}
		/* else FALLTHROUGH */
	    case 'f':
		txtchangeset(txtchangep, TXTNOFGCOLOUR, TXT_ATTR_FG_ON_MASK);
		txtunset(TXT_ATTR_FG_ON_MASK);
		set_colour_attribute(TXTNOFGCOLOUR, COL_SEQ_FG, TSC_PROMPT);
		break;
	    case 'K':
		arg = parsecolorchar(arg, 0);
		if (arg >= 0 && !(arg & TXTNOBGCOLOUR)) {
		    txtchangeset(txtchangep, arg & TXT_ATTR_BG_ON_MASK,
				 TXTNOBGCOLOUR);
		    txtset(arg & TXT_ATTR_BG_ON_MASK);
		    set_colour_attribute(arg, COL_SEQ_BG, TSC_PROMPT);
		    break;
		}
		/* else FALLTHROUGH */
	    case 'k':
		txtchangeset(txtchangep, TXTNOBGCOLOUR, TXT_ATTR_BG_ON_MASK);
		txtunset(TXT_ATTR_BG_ON_MASK);
		set_colour_attribute(TXTNOBGCOLOUR, COL_SEQ_BG, TSC_PROMPT);
		break;
	    case '[':
		if (idigit(*++bv->fm))
		    arg = zstrtol(bv->fm, &bv->fm, 10);
		if (!prompttrunc(arg, ']', doprint, endchar, txtchangep))
		    return *bv->fm;
		break;
	    case '<':
	    case '>':
		/* Test (minus) here so -0 means "at the right margin" */
		if (minus) {
		    *bv->bp = '\0';
		    countprompt(bv->bufline, &t0, 0, 0);
		    arg = zterm_columns - t0 + arg;
		    if (arg <= 0)
			arg = 1;
		}
		if (!prompttrunc(arg, *bv->fm, doprint, endchar, txtchangep))
		    return *bv->fm;
		break;
	    case '{': /*}*/
		if (!bv->dontcount++) {
		    addbufspc(1);
		    *bv->bp++ = Inpar;
		}
		if (arg <= 0)
		    break;
		/* else */
		/* FALLTHROUGH */
	    case 'G':
		if (arg > 0) {
		    addbufspc(arg);
		    while (arg--)
			*bv->bp++ = Nularg;
		} else {
		    addbufspc(1);
		    *bv->bp++ = Nularg;
		}
		break;
	    case /*{*/ '}':
		if (bv->trunccount && bv->trunccount >= bv->dontcount)
		    return *bv->fm;
		if (bv->dontcount && !--bv->dontcount) {
		    addbufspc(1);
		    *bv->bp++ = Outpar;
		}
		break;
	    case 't':
	    case '@':
	    case 'T':
	    case '*':
	    case 'w':
	    case 'W':
	    case 'D':
		{
		    char *tmfmt, *dd, *tmbuf = NULL;

		    switch (*bv->fm) {
		    case 'T':
			tmfmt = "%K:%M";
			break;
		    case '*':
			tmfmt = "%K:%M:%S";
			break;
		    case 'w':
			tmfmt = "%a %f";
			break;
		    case 'W':
			tmfmt = "%m/%d/%y";
			break;
		    case 'D':
			if (bv->fm[1] == '{' /*}*/) {
			    for (ss = bv->fm + 2; *ss && *ss != /*{*/ '}'; ss++)
				if(*ss == '\\' && ss[1])
				    ss++;
			    dd = tmfmt = tmbuf = zalloc(ss - bv->fm);
			    for (ss = bv->fm + 2; *ss && *ss != /*{*/ '}';
				 ss++) {
				if(*ss == '\\' && ss[1])
				    ss++;
				*dd++ = *ss;
			    }
			    *dd = 0;
			    bv->fm = ss - !*ss;
			    if (!*tmfmt) {
				free(tmbuf);
				continue;
			    }
			} else
			    tmfmt = "%y-%m-%d";
			break;
		    default:
			tmfmt = "%l:%M%p";
			break;
		    }
		    gettimeofday(&tv, &dummy_tz);
		    tm = localtime(&tv.tv_sec);
		    /*
		     * Hack because strftime won't say how
		     * much space it actually needs.  Try to add it
		     * a few times until it works.  Some formats don't
		     * actually have a length, so we could go on for
		     * ever.
		     */
		    for(j = 0, t0 = strlen(tmfmt)*8; j < 3; j++, t0*=2) {
			addbufspc(t0);
			if (ztrftime(bv->bp, t0, tmfmt, tm, tv.tv_usec) >= 0)
			    break;
		    }
		    /* There is enough room for this because addbufspc(t0)
		     * allocates room for t0 * 2 bytes. */
		    metafy(bv->bp, -1, META_NOALLOC);
		    bv->bp += strlen(bv->bp);
		    zsfree(tmbuf);
		    break;
		}
	    case 'n':
		stradd(get_username());
		break;
	    case 'l':
		if (*ttystrname) {
                   ss = (strncmp(ttystrname, "/dev/tty", 8) ?
                           ttystrname + 5 : ttystrname + 8);
		    stradd(ss);
		} else
		    stradd("()");
		break;
	    case 'y':
		if (*ttystrname) {
		    ss = (strncmp(ttystrname, "/dev/", 5) ?
			    ttystrname : ttystrname + 5);
		    stradd(ss);
		} else
		    stradd("()");
		break;
	    case 'L':
		addbufspc(DIGBUFSIZE);
#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD)
		sprintf(bv->bp, "%lld", shlvl);
#else
		sprintf(bv->bp, "%ld", (long)shlvl);
#endif
		bv->bp += strlen(bv->bp);
		break;
	    case '?':
		addbufspc(DIGBUFSIZE);
#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD)
		sprintf(bv->bp, "%lld", lastval);
#else
		sprintf(bv->bp, "%ld", (long)lastval);
#endif
		bv->bp += strlen(bv->bp);
		break;
	    case '%':
	    case ')':
		addbufspc(1);
		*bv->bp++ = *bv->fm;
		break;
	    case '#':
		addbufspc(1);
		*bv->bp++ = privasserted() ? '#' : '%';
		break;
	    case 'v':
		if (!arg)
		    arg = 1;
		else if (arg < 0)
		    arg += arrlen(psvar) + 1;
		if (arg > 0 && arrlen(psvar) >= arg)
		    stradd(psvar[arg - 1]);
		break;
	    case 'E':
                tsetcap(TCCLEAREOL, TSC_PROMPT);
		break;
	    case '^':
		if (cmdsp) {
		    if (arg >= 0) {
			if (arg > cmdsp || arg == 0)
			    arg = cmdsp;
			for (t0 = cmdsp - 1; arg--; t0--) {
			    stradd(cmdnames[cmdstack[t0]]);
			    if (arg) {
				addbufspc(1);
				*bv->bp++=' ';
			    }
			}
		    } else {
			arg = -arg;
			if (arg > cmdsp)
			    arg = cmdsp;
			for (t0 = arg - 1; arg--; t0--) {
			    stradd(cmdnames[cmdstack[t0]]);
			    if (arg) {
				addbufspc(1);
				*bv->bp++=' ';
			    }
			}
		    }
		}
		break;
	    case '_':
		if (cmdsp) {
		    if (arg >= 0) {
			if (arg > cmdsp || arg == 0)
			    arg = cmdsp;
			for (t0 = cmdsp - arg; arg--; t0++) {
			    stradd(cmdnames[cmdstack[t0]]);
			    if (arg) {
				addbufspc(1);
				*bv->bp++=' ';
			    }
			}
		    } else {
			arg = -arg;
			if (arg > cmdsp)
			    arg = cmdsp;
			for (t0 = 0; arg--; t0++) {
			    stradd(cmdnames[cmdstack[t0]]);
			    if (arg) {
				addbufspc(1);
				*bv->bp++=' ';
			    }
			}
		    }
		}
		break;
	    case 'r':
		if(bv->rstring)
		    stradd(bv->rstring);
		break;
	    case 'R':
		if(bv->Rstring)
		    stradd(bv->Rstring);
		break;
	    case 'e':
	    {
		int depth = 0;
		Funcstack fsptr = funcstack;
		while (fsptr) {
		    depth++;
		    fsptr = fsptr->prev;
		}
		addbufspc(DIGBUFSIZE);
		sprintf(bv->bp, "%d", depth);
		bv->bp += strlen(bv->bp);
		break;
	    }
	    case 'I':
		if (funcstack && funcstack->tp != FS_SOURCE &&
		    !IN_EVAL_TRAP()) {
		    /*
		     * We're in a function or an eval with
		     * EVALLINENO.  Calculate the line number in
		     * the file.
		     */
		    zlong flineno = lineno + funcstack->flineno;
		    /* take account of eval line nos. starting at 1 */
		    if (funcstack->tp == FS_EVAL)
			lineno--;
		    addbufspc(DIGBUFSIZE);
#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD)
		    sprintf(bv->bp, "%lld", flineno);
#else
		    sprintf(bv->bp, "%ld", (long)flineno);
#endif
		    bv->bp += strlen(bv->bp);
		    break;
		}
		/* else we're in a file and lineno is already correct */
		/* FALLTHROUGH */
	    case 'i':
		addbufspc(DIGBUFSIZE);
#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD)
		sprintf(bv->bp, "%lld", lineno);
#else
		sprintf(bv->bp, "%ld", (long)lineno);
#endif
		bv->bp += strlen(bv->bp);
		break;
	    case 'x':
		if (funcstack && funcstack->tp != FS_SOURCE &&
		    !IN_EVAL_TRAP())
		    promptpath(funcstack->filename ? funcstack->filename : "",
			       arg, 0);
		else
		    promptpath(scriptfilename ? scriptfilename : argzero,
			       arg, 0);
		break;
	    case '\0':
		return 0;
	    case Meta:
		bv->fm++;
		break;
	    }
	} else if(*bv->fm == '!' && isset(PROMPTBANG)) {
	    if(doprint) {
		if(bv->fm[1] == '!') {
		    bv->fm++;
		    addbufspc(1);
		    pputc('!');
		} else {
		    addbufspc(DIGBUFSIZE);
		    convbase(bv->bp, curhist, 10);
		    bv->bp += strlen(bv->bp);
		}
	    }
	} else {
	    char c = *bv->fm == Meta ? *++bv->fm ^ 32 : *bv->fm;

	    if (doprint) {
		addbufspc(1);
		pputc(c);
	    }
	}
    }

    return *bv->fm;
}
Esempio n. 29
0
File: expr.c Progetto: 99years/plan9
void
oadd(Node *n, Node *res)
{
	Node l, r;

	if(n->right == nil){		/* unary + */
		expr(n->left, res);
		return;
	}
	expr(n->left, &l);
	expr(n->right, &r);
	res->fmt = l.fmt;
	res->op = OCONST;
	res->type = TFLOAT;
	switch(l.type) {
	default:
		error("bad lhs type +");
	case TINT:
		switch(r.type) {
		case TINT:
			res->type = TINT;
			res->ival = l.ival+r.ival;
			break;
		case TFLOAT:
			res->fval = l.ival+r.fval;
			break;
		default:
			error("bad rhs type +");
		}
		break;
	case TFLOAT:
		switch(r.type) {
		case TINT:
			res->fval = l.fval+r.ival;
			break;
		case TFLOAT:
			res->fval = l.fval+r.fval;
			break;
		default:
			error("bad rhs type +");
		}
		break;
	case TSTRING:
		if(r.type == TSTRING) {
			res->type = TSTRING;
			res->fmt = 's';
			res->string = stradd(l.string, r.string); 
			break;
		}
		if(r.type == TINT) {
			res->type = TSTRING;
			res->fmt = 's';
			res->string = straddrune(l.string, r.ival);
			break;
		}
		error("bad rhs for +");
	case TLIST:
		res->type = TLIST;
		switch(r.type) {
		case TLIST:
			res->l = addlist(l.l, r.l);
			break;
		default:
			r.left = 0;
			r.right = 0;
			res->l = addlist(l.l, construct(&r));
			break;
		}
	}
}
Esempio n. 30
0
int main(int argc, const char * argv[])
{
    printf("CasAES_CL2 Hyperthreaded AES-256 Encryption for OpenCL 2.0 processors - compiled 4/4/2015 Rev. 3\nCarter McCardwell, Northeastern University NUCAR - http://coe.neu.edu/~cmccardw - mccardwell.net\n\nPlease Wait...\n");

    clock_t c_start, c_stop;
    c_start = clock(); //Create a clock to benchmark the time taken for execution

    FILE *infile;
    FILE *keyfile;
    FILE *outfile;
    FILE *cl_code;

    infile = fopen(argv[2], "r"); //The second argument is the infile
    if (infile == NULL) { printf("error_in"); return(1); }
    keyfile = fopen(argv[3], "rb"); //The third argument is the keyfile, it must be in hex and broken into two charactor parts (eg. AA BB CC ...)
    if (keyfile == NULL) { printf("error_key"); return(1); }
    outfile = fopen(argv[4], "w"); //The outfile, the encrypted results will be written here
    if (outfile == NULL) { printf("error (permission error: run with sudo or in directory the user owns)"); return (1); }

	int hexMode = 1; //The first argument dictates the mode the data is read in, 'h' indicates hex (AA BB CC is read in as AA BB CC), 'a' indicates ASCII/binary as the data is read verbatim
    if (strcmp(argv[1], "h") == 0) { hexMode = 1; }
    else if (strcmp(argv[1], "a") == 0) { hexMode = 0; }
    else { printf("error: first argument must be \'a\' for ASCII interpretation or \'h\' for hex interpretation\n"); return(1); }

    uint8_t key[32];

    for (int i = 0; i < 32; i++)
    {
        fscanf(keyfile, "%x", &key[i]); //Read the private key in
    }

    //Calculate expanded key on the CPU
    K_Exp(&key); //The expansion runtime is faster to execute on the CPU (no kernel startup time) and we are able to store it in constant memory (see below)

    char *append_str = "#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable\n#define Nb 4\n#define Nr 14\n#define Nk 8\n\n__constant uint eK[60]={";
    char *key_element;
    for (int i = 0; i < 60; i++) //The private key will be dynamically added to the source of the kernel before it is compiled, this means that it will be stored in constant memory
    {
        key_element = (char *)malloc(sizeof(uint32_t));
        sprintf(key_element, "%x", expanded_key[i]);
        append_str = stradd(append_str, "0x");
        append_str = stradd(append_str, key_element);
        if (i != 59) { append_str = stradd(append_str, ","); }
    }
    free(key_element);
    append_str = stradd(append_str, "};\n");

    cl_code = fopen("kernel_ocl12.cl", "r");
    if (cl_code == NULL) { printf("\nerror: clfile\n"); return(1); }
    char *source_str = (char *)malloc(MAX_SOURCE_SIZE);
    fread(source_str, 1, MAX_SOURCE_SIZE, cl_code);
    fclose(cl_code);

    append_str = stradd(append_str, source_str);
    size_t length = strlen(append_str);

    //Set OpenCL Context
    cl_int err;
    cl_platform_id platform;
    cl_context context;
    cl_command_queue queue;
    cl_device_id device;

    err = clGetPlatformIDs(1, &platform, NULL);
    if (err != CL_SUCCESS) { printf("platformid"); }

    err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
    if (err != CL_SUCCESS) { printf("getdeivceid %i", err); }

    cl_uint numberOfCores;
    clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(numberOfCores), &numberOfCores, NULL);
    printf("\nRunning with %i compute units", numberOfCores); //Utilize the maximum number of compute units

    cl_uint maxThreads;
    clGetDeviceInfo(device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(maxThreads), &maxThreads, NULL);
    printf("\nRunning with %i threads per compute units", maxThreads); //Utilize the maximum number of threads/cu

    context = clCreateContext(0, 1, &device, NULL, NULL, &err);
    if (err != CL_SUCCESS) { printf("context"); }

    queue = clCreateCommandQueue(context, device, 0, &err);
    if (err != CL_SUCCESS) { printf("queue"); }

    cl_program program = clCreateProgramWithSource(context, 1, &append_str, &length, &err); //Compile program with expanded key included in the source
    if (err != CL_SUCCESS) { printf("createprogram"); }

    err = clBuildProgram(program, 1, &device, "-I ./ -cl-std=CL2.0", NULL, NULL); //The fourth parameter is specific to OpenCL 2.0

    if (err == CL_BUILD_PROGRAM_FAILURE) {
        printf("\nBuild Error = %i", err);
        // Determine the size of the log
        size_t log_size;
        clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);

        // Allocate memory for the log
        char *log = (char *) malloc(log_size);

        // Get the log
        clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size, log, NULL);

        // Print the log
        printf("%s\n", log);
    }

    int BASIC_UNIT = 1024;
    int MAX_WORK_ITEMS = 256;
    unsigned int RUNNING_THREADS = MAX_WORK_ITEMS * BASIC_UNIT;
    printf("\nTotal states per cycle: %i", RUNNING_THREADS);
    //Generic platform-agnostic dispatch <iThreadDSP 1> <CPU/HPTCP Symol>
    uint8_t states[16 * RUNNING_THREADS];
    for (int i = 0; i < 16*RUNNING_THREADS; i++) { states[i] = 0x00; }
    int ch = 0;
    unsigned int spawn = 0;
    int end = 1;
    unsigned int currentOffset = 0;
    while (end)
    {
        spawn = 0;
        for (int i = 0; i < RUNNING_THREADS; i++) //Dispatch many control threads that will report back to main (for now 5x) - 1 worker per state
        {
            currentOffset = i*16;
            spawn++;
            for (int ix = 0; ix < 16; ix++)
            {
                if (hexMode == 1)
                {
                    if (fscanf(infile, "%x", &states[currentOffset+ix]) != EOF) { ; }
                    else
                    {
                        if (ix > 0) { for (int ixx = ix; ixx < 16; ixx++) { states[currentOffset+ixx] = 0x00; } }
                        else { spawn--; }
                        i = RUNNING_THREADS + 1;
                        end = 0;
                        break;
                    }
                }
                else
                {
                    ch = getc(infile);
                    if (ch != EOF) { states[currentOffset+ix] = ch; }
                    else
                    {
                        if (ix > 0) { for (int ixx = ix; ixx < 16; ixx++) { states[currentOffset+ixx] = 0x00; } }
                        else { spawn--; }
                        i = RUNNING_THREADS + 1;
                        end = 0;
                        break;
                    }
                }
            }
        } if (spawn == 0) { break; }
        //arrange data correctly
        for (int i = 0; i < spawn; i++)
        {
            currentOffset = i*16;
            uint8_t temp[16];
            memcpy(&temp[0], &states[currentOffset], sizeof(uint8_t));
            memcpy(&temp[4], &states[currentOffset+1], sizeof(uint8_t));
            memcpy(&temp[8], &states[currentOffset+2], sizeof(uint8_t));
            memcpy(&temp[12], &states[currentOffset+3], sizeof(uint8_t));
            memcpy(&temp[1], &states[currentOffset+4], sizeof(uint8_t));
            memcpy(&temp[5], &states[currentOffset+5], sizeof(uint8_t));
            memcpy(&temp[9], &states[currentOffset+6], sizeof(uint8_t));
            memcpy(&temp[13], &states[currentOffset+7], sizeof(uint8_t));
            memcpy(&temp[2], &states[currentOffset+8], sizeof(uint8_t));
            memcpy(&temp[6], &states[currentOffset+9], sizeof(uint8_t));
            memcpy(&temp[10], &states[currentOffset+10], sizeof(uint8_t));
            memcpy(&temp[14], &states[currentOffset+11], sizeof(uint8_t));
            memcpy(&temp[3], &states[currentOffset+12], sizeof(uint8_t));
            memcpy(&temp[7], &states[currentOffset+13], sizeof(uint8_t));
            memcpy(&temp[11], &states[currentOffset+14], sizeof(uint8_t));
            memcpy(&temp[15], &states[currentOffset+15], sizeof(uint8_t));
            for (int c = 0; c < 16; c++) { memcpy(&states[currentOffset+c], &temp[c], sizeof(uint8_t)); }
        }
        //Set data for workers----------

        cl_mem dev_states;
        cl_int status = CL_SUCCESS;

        dev_states = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, 16*spawn*sizeof(uint8_t), states, &status);
        if (status != CL_SUCCESS || dev_states == NULL) { printf("\nclCreateBuffer: %i", status); }

        //status = clEnqueueWriteBuffer(queue, dev_states, CL_TRUE, 0, 16*spawn*sizeof(uint8_t), &states, 0, NULL, NULL);
        if (status != CL_SUCCESS) { printf("\nclEnqueueWriteBuffer: %i", status); }

        cl_kernel aesKernel = clCreateKernel(program, "CLRunnerntrl", &status);
        if (status != CL_SUCCESS) { printf("\nclCreateKernel: %i", status); }
        //status = clSetKernelArg(aesKernel, 0, 16*spawn*sizeof(uint8_t), &dev_states);
        status = clSetKernelArg(aesKernel, 0, sizeof(cl_mem), &dev_states);
        if (status != CL_SUCCESS) { printf("\nclSetKernelArg: %i", status); }

        const size_t global_ws = spawn;
        size_t local_ws;
        if (spawn < BASIC_UNIT) { local_ws = 1; }
        else if (spawn % BASIC_UNIT > 0) { local_ws = (spawn/BASIC_UNIT) + 1; }
        else { local_ws = (spawn/BASIC_UNIT); }

        //printf("\nLocal: %i - Global: %i", local_ws, global_ws);
        cl_event event;
        status = clEnqueueNDRangeKernel(queue, aesKernel, 1, NULL, &global_ws, &local_ws, 0, NULL, &event);
        if (status != CL_SUCCESS) { printf("\nclEnqueueNDRangeKernel: %i", status); }

        clWaitForEvents(1, &event);

        status = clEnqueueReadBuffer(queue, dev_states, CL_TRUE, 0, 16*spawn*sizeof(uint8_t), &states, 0, NULL, NULL);
        if (status != CL_SUCCESS) { printf("\nclEnqueueReadBuffer: %i", status); }

        clReleaseMemObject(dev_states);

        for (int i = 0; i < spawn; i++)
        {
            currentOffset = i*16;
            for (int ix = 0; ix < 4; ix++)
            {
                char hex[3];
                sprintf(hex, "%02x", states[currentOffset+ix]);
                for (int i = 0; i < 3; i++) { putc(hex[i], outfile); }
                sprintf(hex, "%02x", states[currentOffset+ix+4]);
                for (int i = 0; i < 3; i++) { putc(hex[i], outfile); }
                sprintf(hex, "%02x", states[currentOffset+ix+8]);
                for (int i = 0; i < 3; i++) { putc(hex[i], outfile); }
                sprintf(hex, "%02x", states[currentOffset+ix+12]);
                for (int i = 0; i < 3; i++) { putc(hex[i], outfile); }
            }
        }
    }
    c_stop = clock();
    float diff = (((float)c_stop - (float)c_start) / CLOCKS_PER_SEC ) * 1000;

    printf("Done - Time taken: %f ms\n", diff);
    fclose(infile);
    fclose(outfile);
    fclose(keyfile);
    free(source_str);
    clReleaseContext(context);
    clReleaseCommandQueue(queue);
    return 0;
}