コード例 #1
0
void check_do_led_output(int universe) {
	int i_universe = universe - START_UNIVERSE;
	gettimeofday(&ts, NULL);
	uint32_t time = (uint32_t)(ts.tv_sec*1000000 + ts.tv_usec);
	arrival_flag[i_universe] = 1;
	arrival_time[i_universe] = time;

	int all_arrived = arrival_flag[0];
	int i;
	for (i=1; all_arrived && i<num_universes; ++i)
		all_arrived = arrival_flag[i];

	uint32_t frame_time = get_frame_time(time);

	if (all_arrived) { // All universes arrived!
		DBG("All have arrived, sending");
		if (frame_time < last_frame_time * 3 ||
			(time - last_frame_output) > (last_frame_time * 10)) {
			do_output();
		}
		else {
			DBG("Nope, timeout.");
		}
		last_frame_output = time;
		mark_frame_sent(frame_time);
	}
	else {
		if (frame_time * 3 < last_frame_time) {
			DBG("Sending the packet even though not all arrived!");
			do_output();
			last_frame_output = time;
			mark_frame_sent(frame_time);
		}
	}
}
コード例 #2
0
ファイル: format_output.cpp プロジェクト: heiher/oprofile
void cg_formatter::output(ostream & out, symbol_collection const & syms)
{
	// amount of spacing prefixing child and parent lines
	string const child_parent_prefix("  ");

	output_header(out);

	out << string(79, '-') << endl;

	symbol_collection::const_iterator it;
	symbol_collection::const_iterator end = syms.end();

	for (it = syms.begin(); it < end; ++it) {
		cg_symbol const * sym = dynamic_cast<cg_symbol const *>(*it);
		// To silence coverity (since dynamic cast can theoretically return NULL)
		if (!sym)
			continue;

		cg_symbol::children::const_iterator cit;
		cg_symbol::children::const_iterator cend = sym->callers.end();

		counts_t c;
		if (global_percent)
			c.total = counts.total;
		else
			c.total = sym->total_caller_count;

		for (cit = sym->callers.begin(); cit != cend; ++cit) {
			out << child_parent_prefix;
			do_output(out, *cit, cit->sample, c);
		}

		do_output(out, *sym, sym->sample, counts);

		c = counts_t();
		if (global_percent)
			c.total = counts.total;
		else
			c.total = sym->total_callee_count;

		cend = sym->callees.end();

		for (cit = sym->callees.begin(); cit != cend; ++cit) {
			out << child_parent_prefix;
			do_output(out, *cit, cit->sample, c);
		}

		out << string(79, '-') << endl;
	}
}
コード例 #3
0
int
main(int argc, char *argv[])
#endif
{
	const char *tablename = NULL;
	int c;

	iptables_globals.program_name = "iptables-save";
	c = xtables_init_all(&iptables_globals, NFPROTO_IPV4);
	if (c < 0) {
		fprintf(stderr, "%s/%s Failed to initialize xtables\n",
				iptables_globals.program_name,
				iptables_globals.program_version);
		exit(1);
	}
#if defined(ALL_INCLUSIVE) || defined(NO_SHARED_LIBS)
	init_extensions();
	init_extensions4();
#endif

	while ((c = getopt_long(argc, argv, "bcdt:", options, NULL)) != -1) {
		switch (c) {
		case 'b':
			show_binary = 1;
			break;

		case 'c':
			show_counters = 1;
			break;

		case 't':
			
			tablename = optarg;
			break;
		case 'M':
			xtables_modprobe_program = optarg;
			break;
		case 'd':
			do_output(tablename);
			exit(0);
		}
	}

	if (optind < argc) {
		fprintf(stderr, "Unknown arguments found on commandline\n");
		exit(1);
	}

	return !do_output(tablename);
}
コード例 #4
0
ファイル: format_output.cpp プロジェクト: heiher/oprofile
void opreport_formatter::output(ostream & out, symbol_entry const * symb)
{
	do_output(out, *symb, symb->sample, counts);

	if (need_details)
		output_details(out, symb);
}
コード例 #5
0
ファイル: viewer-pangox.c プロジェクト: nihed/magnetism
static void 
pangox_view_render (gpointer      instance,
		    gpointer      surface,
		    PangoContext *context,
		    int           width,
		    int           height,
		    gpointer      state)
{
  XViewer *x = (XViewer *) instance;
  Pixmap pixmap = (Pixmap) surface;
  GC gc;
  MyXContext x_context;

  gc = XCreateGC (x->display, pixmap, 0, NULL);

  XSetForeground(x->display, gc, WhitePixel(x->display, x->screen));
  XFillRectangle (x->display, pixmap, gc, 0, 0, width, height);

  x_context.x = x;
  x_context.drawable = pixmap;
  x_context.gc = gc;

  XSetForeground(x->display, gc, BlackPixel(x->display, x->screen));
  do_output (context, render_callback, NULL, &x_context, state, NULL, NULL);

  XFlush(x->display);

  XFreeGC (x->display, gc);
}
コード例 #6
0
void cg_formatter::output(ostream & out, cg_collection const & syms)
{
	// amount of spacing prefixing child and parent lines
	string const child_parent_prefix("  ");

	output_header(out);

	out << string(79, '-') << endl;

	cg_collection::const_iterator it;
	cg_collection::const_iterator end = syms.end();

	for (it = syms.begin(); it < end; ++it) {
		cg_symbol const & sym = *it;

		cg_symbol::children::const_iterator cit;
		cg_symbol::children::const_iterator cend = sym.callers.end();

		counts_t c;
		if (global_percent)
			c.total = counts.total;
		else
			c.total = sym.total_caller_count;

		for (cit = sym.callers.begin(); cit != cend; ++cit) {
			out << child_parent_prefix;
			do_output(out, *cit, cit->sample, c);
		}

		do_output(out, sym, sym.sample, counts);

		c = counts_t();
		if (global_percent)
			c.total = counts.total;
		else
			c.total = sym.total_callee_count;

		cend = sym.callees.end();

		for (cit = sym.callees.begin(); cit != cend; ++cit) {
			out << child_parent_prefix;
			do_output(out, *cit, cit->sample, c);
		}

		out << string(79, '-') << endl;
	}
}
コード例 #7
0
ファイル: exo_helper.c プロジェクト: going-digital/versaload
void crunch_backwards(struct membuf *inbuf,
                      struct membuf *outbuf,
                      struct crunch_options *options, /* IN */
                      struct crunch_info *info) /* OUT */
{
    static match_ctx ctx;
    encode_match_data emd;
    search_nodep snp;
    int outlen;
    int safety;
    int copy_used;

    if(options == NULL)
    {
        options = default_options;
    }

    outlen = membuf_memlen(outbuf);
    emd->out = NULL;
    optimal_init(emd);

    LOG(LOG_NORMAL,
        ("\nPhase 1: Instrumenting file"
         "\n-----------------------------\n"));
    LOG(LOG_NORMAL, (" Length of indata: %d bytes.\n", membuf_memlen(inbuf)));

    match_ctx_init(ctx, inbuf, options->max_len, options->max_offset,
                   options->use_imprecise_rle);

    LOG(LOG_NORMAL, (" Instrumenting file, done.\n"));

    emd->out = NULL;
    optimal_init(emd);

    LOG(LOG_NORMAL,
        ("\nPhase 2: Calculating encoding"
         "\n-----------------------------\n"));
    snp = do_compress(ctx, emd, options->exported_encoding,
                      options->max_passes, options->use_literal_sequences);
    LOG(LOG_NORMAL, (" Calculating encoding, done.\n"));

    LOG(LOG_NORMAL,
        ("\nPhase 3: Generating output file"
         "\n------------------------------\n"));
    LOG(LOG_NORMAL, (" Encoding: %s\n", optimal_encoding_export(emd)));
    safety = do_output(ctx, snp, emd, optimal_encode, outbuf, &copy_used);
    LOG(LOG_NORMAL, (" Length of crunched data: %d bytes.\n",
                     membuf_memlen(outbuf) - outlen));

    optimal_free(emd);
    search_node_free(snp);
    match_ctx_free(ctx);

    if(info != NULL)
    {
        info->literal_sequences_used = copy_used;
        info->needed_safety_offset = safety;
    }
}
コード例 #8
0
ファイル: main.c プロジェクト: nishimotz/jagtalk
void setSave( char *rel, char *filename )
{
	if( strcmp(rel,"=")==0 )  {
		do_output( filename );
	} else {
		unknown_com();
	}
}
コード例 #9
0
ファイル: ip6tables-save.c プロジェクト: ebichu/dd-wrt
int
main(int argc, char *argv[])
#endif
{
	const char *tablename = NULL;
	int c;

	program_name = "ip6tables-save";
	program_version = IPTABLES_VERSION;

	lib_dir = getenv("IP6TABLES_LIB_DIR");
	if (!lib_dir)
		lib_dir = IP6T_LIB_DIR;

#ifdef NO_SHARED_LIBS
	init_extensions();
#endif

	while ((c = getopt_long(argc, argv, "bcdt:", options, NULL)) != -1) {
		switch (c) {
		case 'b':
			binary = 1;
			break;

		case 'c':
			counters = 1;
			break;

		case 't':
			/* Select specific table. */
			tablename = optarg;
			break;
		case 'd':
			do_output(tablename);
			exit(0);
		}
	}

	if (optind < argc) {
		fprintf(stderr, "Unknown arguments found on commandline");
		exit(1);
	}

	return !do_output(tablename);
}
コード例 #10
0
ファイル: format_output.cpp プロジェクト: heiher/oprofile
void diff_formatter::output(ostream & out, diff_collection const & syms)
{
	output_header(out);

	diff_collection::const_iterator it = syms.begin();
	diff_collection::const_iterator end = syms.end();
	for (; it != end; ++it)
		do_output(out, *it, it->sample, counts, it->diffs);
}
コード例 #11
0
int	scan_holdings_parse(int stock_offset) {
  float	cur_price=0.0;
  int	x,num_rows,rc=EXIT_SUCCESS;
  unsigned long	*lengths;
  char	msg[1024];
  char	query[1024];
  char	Today[16];
  time_t t;
  struct tm *TM=0;
  struct stocks *Stocks;
  MYSQL *mysql;
  MYSQL_RES *result;
  MYSQL_ROW row;
  
  
  x = sizeof(struct stocks) * stock_offset;
  Stocks = (struct stocks *) &holdings_table[x];
  if (debug) printf("Starting scan_holdings_parse processing for %s at offset %d\n",Stocks->SYMBOL,stock_offset);
  // get real-time price for the selected stock symbol
  if ((cur_price = get_RTquote(Stocks->SYMBOL)) == 0) exit(EXIT_FAILURE);
  if (cur_price < 1.0) { if (debug) printf("%s cur_price < 1.00, giving up\n",Stocks->SYMBOL); exit(EXIT_FAILURE); }
  if (debug) printf("%s Holding cur_price = %.2f\n",Stocks->SYMBOL,cur_price);
   
  t = time(NULL);
  TM = localtime(&t);
  if (TM == NULL) {
    perror("localtime");
    return(EXIT_FAILURE);
  }
  if (strftime(Today, sizeof(Today), "%F", TM) == 0) {
    puts("In scan_holdings -  strftime returned 0");
    return(EXIT_FAILURE);
  }

  // parse the data
  memset(msg,0,sizeof(msg));
  if (strncmp(Today,Stocks->date,10)==0 
    && cur_price <= (Stocks->PAPER_BUY_PRICE - (Stocks->PAPER_BUY_PRICE*0.02))) {
//    sprintf(msg,"Sell %s purchased at %.2f same-day 2%% StopLoss",Stocks->SYMBOL,Stocks->PAPER_BUY_PRICE); 
    sprintf(msg,"Sell %s purchased at %.2f same-day %.1f%% Loss",Stocks->SYMBOL,Stocks->PAPER_BUY_PRICE,((cur_price-Stocks->PAPER_BUY_PRICE)/Stocks->PAPER_BUY_PRICE)*100); 
  }
  if (cur_price <= (Stocks->PAPER_BUY_PRICE - (Stocks->PAPER_BUY_PRICE*0.07))) { 
//    sprintf(msg,"Sell %s purchased at %.2f 7%% StopLoss",Stocks->SYMBOL,Stocks->PAPER_BUY_PRICE); 
    sprintf(msg,"Sell %s purchased at %.2f %.1f%% StopLoss",Stocks->SYMBOL,Stocks->PAPER_BUY_PRICE,((cur_price-Stocks->PAPER_BUY_PRICE)/Stocks->PAPER_BUY_PRICE)*100); 
  }
  if (cur_price >= (Stocks->PAPER_BUY_PRICE + (Stocks->PAPER_BUY_PRICE*0.05))) { 
//    sprintf(msg,"Sell %s purchased at %.2f 5%% gain",Stocks->SYMBOL,Stocks->PAPER_BUY_PRICE); 
    sprintf(msg,"Sell %s purchased at %.2f %.1f%% gain",Stocks->SYMBOL,Stocks->PAPER_BUY_PRICE,((cur_price-Stocks->PAPER_BUY_PRICE)/Stocks->PAPER_BUY_PRICE)*100); 
  }

  // process the output message
  if (debug) printf("completed scan_holdings processing for %s\n",Stocks->SYMBOL);
  do_output(msg);
  return(EXIT_SUCCESS);
}
コード例 #12
0
ファイル: main.c プロジェクト: nishimotz/jagtalk
void setSpeak( char *rel, char *val )
{
	int error;
	long sleep_ms;

	if( strcmp(rel,"=")!=0 )  { unknown_com();  return; }

	if( strcmp(val,"NOW")==0 )  {
		strcpy( slot_Speak_stat, "SPEAKING" );
		if( prop_Speak_stat == AutoOutput )  inqSpeakStat();
		do_output(NULL);	/* 音声出力 */

	} else if( strcmp(val,"STOP")==0 )  {
		abort_output();

	} else {
		/* val = "12:34:56.789" or "+1000" */
		error = make_sleep_time( val, &sleep_ms );
		if( error )  {
			unknown_com();
		} else {
#ifdef PRINTDATA
			TmpMsg( "sleep_ms: %d\n", sleep_ms );
#endif
			if( sleep_ms > 0 ) {
#ifdef WIN32
			        Sleep( sleep_ms );
#else
			        usleep( 1000*sleep_ms );
#endif
			}
			strcpy( slot_Speak_stat, "SPEAKING" );
			if( prop_Speak_stat == AutoOutput )  inqSpeakStat();
			do_output(NULL);	/* 音声出力 */
		}
	}
/*	strcpy( slot_Speak_stat, "IDLE" );
	if( prop_Speak_stat == AutoOutput )  inqSpeakStat();
*/
}
コード例 #13
0
ファイル: viewer-pangoft2.c プロジェクト: nihed/magnetism
static void 
pangoft2_view_render (gpointer      instance,
		      gpointer      surface,
		      PangoContext *context,
		      int           width,
		      int           height,
		      gpointer      state)
{
  int pix_idx;
  FT_Bitmap *bitmap = (FT_Bitmap *) surface;

  do_output (context, render_callback, NULL, surface, state, NULL, NULL);

  for (pix_idx=0; pix_idx<bitmap->pitch * bitmap->rows; pix_idx++)
    bitmap->buffer[pix_idx] = 255 - bitmap->buffer[pix_idx];
}
コード例 #14
0
ファイル: b64_filt.cpp プロジェクト: Andrew-He/botan
/*
* Encode and send a block
*/
void Base64_Encoder::encode_and_send(const byte input[], size_t length,
                                     bool final_inputs)
   {
   while(length)
      {
      const size_t proc = std::min(length, m_in.size());

      size_t consumed = 0;
      size_t produced = base64_encode(reinterpret_cast<char*>(m_out.data()), input,
                                      proc, consumed, final_inputs);

      do_output(m_out.data(), produced);

      // FIXME: s/proc/consumed/?
      input += proc;
      length -= proc;
      }
   }
コード例 #15
0
ファイル: format_output.cpp プロジェクト: heiher/oprofile
void opreport_formatter::
output_details(ostream & out, symbol_entry const * symb)
{
	counts_t c = counts;

	if (!global_percent)
		c.total = symb->sample.counts;

	// cumulated percent are relative to current symbol.
	c.cumulated_samples = count_array_t();
	c.cumulated_percent = count_array_t();

	sample_container::samples_iterator it = profile.begin(symb);
	sample_container::samples_iterator end = profile.end(symb);
	for (; it != end; ++it) {
		out << "  ";
		do_output(out, *symb, it->second, c, diff_array_t(), true);
	}
}
コード例 #16
0
ファイル: vmod16a2drvr.c プロジェクト: bradomyn/coht
static int ioctl(struct inode *inode,
		struct file *fp,
		unsigned op,
		unsigned long arg)
{
	struct vmod_dev *devp = fp->private_data;
	struct vmod16a2_convert cvrt, *cvrtp = &cvrt;

	switch (op) {

	case VMOD16A2_IOCPUT:
		if (copy_from_user(cvrtp, (const void __user*)arg, sizeof(cvrt)) != 0)
			return -EINVAL;
		return do_output(devp, cvrtp);
		break;

	default:
		return -ENOTTY;
	}
	return -ENOTTY;
}
コード例 #17
0
int receiver(long refresh_milliseconds) {
  int s;
	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
    perror("socket");
		return 0;
	}

	struct timeval tv;
	tv.tv_sec = refresh_milliseconds / 1000;
	tv.tv_usec = (refresh_milliseconds % 1000) * 1000;
	setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(struct timeval));

	struct sockaddr_in si_me;
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(ARTNET_PORT);
	si_me.sin_addr.s_addr = htonl(INADDR_ANY);
     
	if (bind(s, (struct sockaddr*)&si_me, sizeof(si_me)) == -1) {
		return 0;
	}

	
	uint8_t buffer[1024];
	ssize_t len;
	while(1) {
		if ((len = recv(s, buffer, sizeof(buffer), 0)) == -1) {
			if (errno == EAGAIN || errno == EWOULDBLOCK) {
				do_output();
			}
			else {
				return 0;
			}
		}
		
			if (!process_packet(len, buffer)) 
				return 0;
	}
  
}
コード例 #18
0
static void
pangoxft_view_render (gpointer      instance,
		      gpointer      surface,
		      PangoContext *context,
		      int          *width,
		      int          *height,
		      gpointer      state)
{
  XViewer *x = (XViewer *) instance;
  Pixmap pixmap = (Pixmap) surface;
  MyXftContext xft_context;
  XftDraw *draw;
  XftColor color;

  draw = XftDrawCreate (x->display, pixmap,
			DefaultVisual (x->display, x->screen),
			DefaultColormap (x->display, x->screen));

  /* XftDrawRect only fills solid.
   * Flatten with white.
   */
  color.color.red = ((opt_bg_color.red * opt_bg_alpha) >> 16) + (65535 - opt_bg_alpha);
  color.color.green = ((opt_bg_color.green * opt_bg_alpha) >> 16) + (65535 - opt_bg_alpha);
  color.color.blue = ((opt_bg_color.blue * opt_bg_alpha) >> 16) + (65535 - opt_bg_alpha);
  color.color.alpha = 65535;

  XftDrawRect (draw, &color, 0, 0, *width, *height);

  color.color.red = opt_fg_color.red;
  color.color.blue = opt_fg_color.green;
  color.color.green = opt_fg_color.blue;
  color.color.alpha = opt_fg_alpha;

  xft_context.draw = draw;
  xft_context.color = color;

  do_output (context, render_callback, NULL, &xft_context, state, width, height);

  XftDrawDestroy (draw);
}
コード例 #19
0
ファイル: xtables-save.c プロジェクト: AmVPN/iptables
/* Format:
 * :Chain name POLICY packets bytes
 * rule
 */
static int
xtables_save_main(int family, const char *progname, int argc, char *argv[])
{
	const char *tablename = NULL;
	bool dump = false;
	struct nft_handle h = {
		.family	= family,
	};
	int c;

	xtables_globals.program_name = progname;
	c = xtables_init_all(&xtables_globals, family);
	if (c < 0) {
		fprintf(stderr, "%s/%s Failed to initialize xtables\n",
				xtables_globals.program_name,
				xtables_globals.program_version);
		exit(1);
	}
#if defined(ALL_INCLUSIVE) || defined(NO_SHARED_LIBS)
	init_extensions();
	init_extensions4();
#endif
	if (nft_init(&h, xtables_ipv4) < 0) {
		fprintf(stderr, "%s/%s Failed to initialize nft: %s\n",
				xtables_globals.program_name,
				xtables_globals.program_version,
				strerror(errno));
		exit(EXIT_FAILURE);
	}

	while ((c = getopt_long(argc, argv, "bcdt:M:46", options, NULL)) != -1) {
		switch (c) {
		case 'b':
			fprintf(stderr, "-b/--binary option is not implemented\n");
			break;
		case 'c':
			show_counters = true;
			break;

		case 't':
			/* Select specific table. */
			tablename = optarg;
			break;
		case 'M':
			xtables_modprobe_program = optarg;
			break;
		case 'd':
			dump = true;
			break;
		case '4':
			h.family = AF_INET;
			break;
		case '6':
			h.family = AF_INET6;
			xtables_set_nfproto(AF_INET6);
			break;
		}
	}

	if (optind < argc) {
		fprintf(stderr, "Unknown arguments found on commandline\n");
		exit(1);
	}

	if (dump) {
		do_output(&h, tablename, show_counters);
		exit(0);
	}

	return !do_output(&h, tablename, show_counters);
}
コード例 #20
0
void goto_convertt::do_function_call_symbol(
  const exprt &lhs,
  const symbol_exprt &function,
  const exprt::operandst &arguments,
  goto_programt &dest)
{
  if(function.get_bool("#invalid_object"))
    return; // ignore

  // lookup symbol
  const irep_idt &identifier=function.get_identifier();

  const symbolt *symbol;
  if(ns.lookup(identifier, symbol))
  {
    err_location(function);
    throw "error: function `"+id2string(identifier)+"' not found";
  }

  if(symbol->type.id()!=ID_code)
  {
    err_location(function);
    throw "error: function `"+id2string(identifier)+"' type mismatch: expected code";
  }
  
  if(identifier==CPROVER_PREFIX "assume" ||
     identifier=="__VERIFIER_assume")
  {
    if(arguments.size()!=1)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have one argument";
    }

    goto_programt::targett t=dest.add_instruction(ASSUME);
    t->guard=arguments.front();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    
    // let's double-check the type of the argument
    if(t->guard.type().id()!=ID_bool)
      t->guard.make_typecast(bool_typet());

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(identifier=="__VERIFIER_error")
  {
    if(!arguments.empty())
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have no arguments";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(has_prefix(id2string(identifier), "java::java.lang.AssertionError.<init>:"))
  {
    // insert function call anyway
    code_function_callt function_call;
    function_call.lhs()=lhs;
    function_call.function()=function;
    function_call.arguments()=arguments;
    function_call.add_source_location()=function.source_location();

    copy(function_call, FUNCTION_CALL, dest);

    if(arguments.size()!=1 && arguments.size()!=2)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have one or two arguments";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);    
    t->source_location.set_comment("assertion at "+function.source_location().as_string());
  }
  else if(identifier=="assert" &&
          !ns.lookup(identifier).location.get_function().empty())
  {
    if(arguments.size()!=1)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have one argument";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=arguments.front();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment("assertion "+id2string(from_expr(ns, "", t->guard)));
    
    // let's double-check the type of the argument
    if(t->guard.type().id()!=ID_bool)
      t->guard.make_typecast(bool_typet());

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(identifier==CPROVER_PREFIX "assert")
  {
    if(arguments.size()!=2)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have two arguments";
    }
    
    const irep_idt description=
      get_string_constant(arguments[1]);

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=arguments[0];
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    
    // let's double-check the type of the argument
    if(t->guard.type().id()!=ID_bool)
      t->guard.make_typecast(bool_typet());

    if(lhs.is_not_nil())
    {
      err_location(function);
      throw id2string(identifier)+" expected not to have LHS";
    }
  }
  else if(identifier==CPROVER_PREFIX "printf")
  {
    do_printf(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "scanf")
  {
    do_scanf(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "input" ||
          identifier=="__CPROVER::input")
  {
    do_input(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "output" ||
          identifier=="__CPROVER::output")
  {
    do_output(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "atomic_begin" ||
          identifier=="__CPROVER::atomic_begin" ||
          identifier=="__VERIFIER_atomic_begin")
  {
    do_atomic_begin(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "atomic_end" ||
          identifier=="__CPROVER::atomic_end" ||
          identifier=="__VERIFIER_atomic_end")
  {
    do_atomic_end(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "prob_biased_coin")
  {
    do_prob_coin(lhs, function, arguments, dest);
  }
  else if(has_prefix(id2string(identifier), CPROVER_PREFIX "prob_uniform_"))
  {
    do_prob_uniform(lhs, function, arguments, dest);
  }
  else if(has_prefix(id2string(identifier), "nondet_") ||
          has_prefix(id2string(identifier), "__VERIFIER_nondet_"))
  {
    // make it a side effect if there is an LHS
    if(lhs.is_nil()) return;
    
    exprt rhs;
    
    // We need to special-case for _Bool, which
    // can only be 0 or 1.
    if(lhs.type().id()==ID_c_bool)
    {
      rhs=side_effect_expr_nondett(bool_typet());
      rhs.add_source_location()=function.source_location();
      rhs.set(ID_C_identifier, identifier);
      rhs=typecast_exprt(rhs, lhs.type());
    } 
    else
    {
      rhs=side_effect_expr_nondett(lhs.type());
      rhs.add_source_location()=function.source_location();
      rhs.set(ID_C_identifier, identifier);
    }

    code_assignt assignment(lhs, rhs);
    assignment.add_source_location()=function.source_location();
    copy(assignment, ASSIGN, dest);
  }
  else if(has_prefix(id2string(identifier), CPROVER_PREFIX "uninterpreted_"))
  {
    // make it a side effect if there is an LHS
    if(lhs.is_nil()) return;

    function_application_exprt rhs;
    rhs.type()=lhs.type();
    rhs.add_source_location()=function.source_location();
    rhs.function()=function;
    rhs.arguments()=arguments;

    code_assignt assignment(lhs, rhs);
    assignment.add_source_location()=function.source_location();
    copy(assignment, ASSIGN, dest);
  }
  else if(has_prefix(id2string(identifier), CPROVER_PREFIX "array_set"))
  {
    do_array_set(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "array_equal" ||
          identifier=="__CPROVER::array_equal")
  {
    do_array_equal(lhs, function, arguments, dest);
  }
  else if(identifier==CPROVER_PREFIX "array_copy" ||
          identifier=="__CPROVER::array_equal")
  {
    do_array_copy(lhs, function, arguments, dest);
  }
  else if(identifier=="printf")
  /*
          identifier=="fprintf" ||
          identifier=="sprintf" ||
          identifier=="snprintf")
  */
  {
    do_printf(lhs, function, arguments, dest);
  }
  else if(identifier=="__assert_fail" ||
          identifier=="_assert" ||
          identifier=="__assert_c99" ||
          identifier=="_wassert")
  {
    // __assert_fail is Linux
    // These take four arguments:
    // "expression", "file.c", line, __func__
    // klibc has __assert_fail with 3 arguments
    // "expression", "file.c", line

    // MingW has
    // void _assert (const char*, const char*, int);
    // with three arguments:
    // "expression", "file.c", line

    // This has been seen in Solaris 11.
    // Signature:
    // void __assert_c99(const char *desc, const char *file, int line, const char *func);

    // _wassert is Windows. The arguments are
    // L"expression", L"file.c", line

    if(arguments.size()!=4 &&
       arguments.size()!=3)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have four arguments";
    }
    
    const irep_idt description=
      "assertion "+id2string(get_string_constant(arguments[0]));

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    // we ignore any LHS
  }
  else if(identifier=="__assert_rtn" ||
          identifier=="__assert")
  {
    // __assert_rtn has been seen on MacOS;
    // __assert is FreeBSD and Solaris 11.
    // These take four arguments:
    // __func__, "file.c", line, "expression"
    // On Solaris 11, it's three arguments:
    // "expression", "file", line
    
    irep_idt description;
    
    if(arguments.size()==4)
    {
      description=
        "assertion "+id2string(get_string_constant(arguments[3]));
    }
    else if(arguments.size()==3)
    {
      description=
        "assertion "+id2string(get_string_constant(arguments[1]));
    }
    else
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have four arguments";
    }

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    // we ignore any LHS
  }
  else if(identifier=="__assert_func")
  {
    // __assert_func is newlib (used by, e.g., cygwin)
    // These take four arguments:
    // "file.c", line, __func__, "expression"
    if(arguments.size()!=4)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have four arguments";
    }

    const irep_idt description=
      "assertion "+id2string(get_string_constant(arguments[3]));

    goto_programt::targett t=dest.add_instruction(ASSERT);
    t->guard=false_exprt();
    t->source_location=function.source_location();
    t->source_location.set("user-provided", true);
    t->source_location.set_property_class(ID_assertion);
    t->source_location.set_comment(description);
    // we ignore any LHS
  }
  else if(identifier==CPROVER_PREFIX "fence")
  {
    if(arguments.size()<1)
    {
      err_location(function);
      throw "`"+id2string(identifier)+"' expected to have at least one argument";
    }

    goto_programt::targett t=dest.add_instruction(OTHER);
    t->source_location=function.source_location();
    t->code.set(ID_statement, ID_fence);

    forall_expr(it, arguments)
    {
      const irep_idt kind=get_string_constant(*it);
      t->code.set(kind, true);
    }
  }
  else if(identifier=="__builtin_prefetch")
コード例 #21
0
int main(int argc, char **argv)
{
   int i, retval, EventSet = PAPI_NULL;
   int bins = 100;
   int show_dist = 0, show_std_dev = 0;
   long long totcyc, values[2];
   long long *array;


   tests_quiet(argc, argv);     /* Set TESTS_QUIET variable */

   for (i = 0; i < argc; i++) {
      if (argv[i]) {
         if (strstr(argv[i], "-b")) {
            bins = atoi(argv[i+1]);
            if (bins) i++;
            else {
               printf ("-b requires a bin count!\n");
               exit(1);
            }
         }
         if (strstr(argv[i], "-d"))
            show_dist = 1;
         if (strstr(argv[i], "-h")) {
            print_help();
            exit(1);
         }
         if (strstr(argv[i], "-s"))
            show_std_dev = 1;
         if (strstr(argv[i], "-t")) {
            num_iters = atol(argv[i+1]);
            if (num_iters) i++;
            else {
               printf ("-t requires a threshold value!\n");
               exit(1);
            }
         }
      }
   }

   printf("Cost of execution for PAPI start/stop, read and accum.\n");
   printf("This test takes a while. Please be patient...\n");

   if ((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT)
      test_fail(__FILE__, __LINE__, "PAPI_library_init", retval);
   if ((retval = PAPI_set_debug(PAPI_VERB_ECONT)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_set_debug", retval);
   if ((retval = PAPI_query_event(PAPI_TOT_CYC)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_query_event", retval);
   if ((retval = PAPI_query_event(PAPI_TOT_INS)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_query_event", retval);
   if ((retval = PAPI_create_eventset(&EventSet)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_create_eventset", retval);

   if ((retval = PAPI_add_event(EventSet, PAPI_TOT_CYC)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_add_event", retval);

   if ((retval = PAPI_add_event(EventSet, PAPI_TOT_INS)) != PAPI_OK)
      if ((retval = PAPI_add_event(EventSet, PAPI_TOT_IIS)) != PAPI_OK)
         test_fail(__FILE__, __LINE__, "PAPI_add_event", retval);

   /* Make sure no errors and warm up */

   totcyc = PAPI_get_real_cyc();
   if ((retval = PAPI_start(EventSet)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);
   if ((retval = PAPI_stop(EventSet, NULL)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

   array = (long long *)malloc(num_iters*sizeof(long long));
   if (array == NULL ) 
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

   /* Determine clock latency */

   printf("\nPerforming loop latency test...\n");

   for (i = 0; i < num_iters; i++) {
      totcyc = PAPI_get_real_cyc();
      totcyc = PAPI_get_real_cyc() - totcyc;
      array[i] = totcyc;
   }

   do_output(0, array, bins, show_std_dev, show_dist);

   /* Start the start/stop eval */

   printf("\nPerforming start/stop test...\n");

   for (i = 0; i < num_iters; i++) {
      totcyc = PAPI_get_real_cyc();
      PAPI_start(EventSet);
      PAPI_stop(EventSet, values);
      totcyc = PAPI_get_real_cyc() - totcyc;
      array[i] = totcyc;
   }

   do_output(1, array, bins, show_std_dev, show_dist);

   /* Start the read eval */
   printf("\nPerforming read test...\n");

   if ((retval = PAPI_start(EventSet)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);
   PAPI_read(EventSet, values);

   for (i = 0; i < num_iters; i++) {
      totcyc = PAPI_get_real_cyc();
      PAPI_read(EventSet, values);
      totcyc = PAPI_get_real_cyc() - totcyc;
      array[i] = totcyc;
   }
   if ((retval = PAPI_stop(EventSet, values)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

   do_output(2, array, bins, show_std_dev, show_dist);

   /* Start the read with timestamp eval */
   printf("\nPerforming read with timestamp test...\n");

   if ((retval = PAPI_start(EventSet)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);
   PAPI_read_ts(EventSet, values, &totcyc);

   for (i = 0; i < num_iters; i++) {
      PAPI_read_ts(EventSet, values, &array[i]);
   }
   if ((retval = PAPI_stop(EventSet, values)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

   /* post-process the timing array */
   for (i = num_iters - 1; i > 0 ; i--) {
      array[i] -= array[i-1];
   }
   array[0] -= totcyc;

   do_output(3, array, bins, show_std_dev, show_dist);

   /* Start the accum eval */
   printf("\nPerforming accum test...\n");

   if ((retval = PAPI_start(EventSet)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);
   PAPI_accum(EventSet, values);

   for (i = 0; i < num_iters; i++) {
      totcyc = PAPI_get_real_cyc();
      PAPI_accum(EventSet, values);
      totcyc = PAPI_get_real_cyc() - totcyc;
      array[i] = totcyc;
   }
   if ((retval = PAPI_stop(EventSet, values)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

   do_output(4, array, bins, show_std_dev, show_dist);

   /* Start the reset eval */
   printf("\nPerforming reset test...\n");

   if ((retval = PAPI_start(EventSet)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);

   for (i = 0; i < num_iters; i++) {
      totcyc = PAPI_get_real_cyc();
      PAPI_reset(EventSet);
      totcyc = PAPI_get_real_cyc() - totcyc;
      array[i] = totcyc;
   }
   if ((retval = PAPI_stop(EventSet, values)) != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

   do_output(5, array, bins, show_std_dev, show_dist);

   free(array);
   test_pass(__FILE__, NULL, 0);
   exit(1);
}
コード例 #22
0
ファイル: prompt.c プロジェクト: ris21/yoda
int do_dictionary_prompt(bool all, const char *msg, char *str)
{
    s_list l;
    s_node *p;
    int ok = -2, width = 16;
    const char *yesstr;		/* String of Yes characters accepted. */
    const char *nostr;		/* Same for No. */
    const char *allstr;		/* And All, surprise! */
    int u;
    char **thisarray = (char **)malloc(sizeof(char)*5);
	for(u = 0; u < 5; u++)
		thisarray[u] = (char *)malloc(sizeof(char)*16);
    thisarray = thisfunc(str);
    int oldmenu = currmenu;
    char but[16];
    int i, j = 0;
    int count = 0;
    int t = 0;
    int bs = 0;
    char buf[16];
    strcpy(buf, str);
    int tp;
    int we = 0, wc = 0;
    
    tp = typepos();
    
    assert(msg != NULL);
    
    s_init(&l);
    u = 0;
    while(u < 5) {
	s_append(&l, thisarray[u]);
	u++;
    }
    /*Now partial matched list is prepared*/
           p = l.head;
           

    if(str == NULL){
 
        count = 0;

        
        while(p){
            count++;
            p = p->next;
        }
    }
    
    //count=5;

    p = l.head;


    do {
	int kbinput;
	functionptrtype func;
        i = 0;
#ifndef DISABLE_MOUSE
	int mouse_x, mouse_y;
#endif

	if (!ISSET(NO_HELP)) {
	    char shortstr[3];
		/* Temporary string for (translated) " Y", " N" and " A". */

	    if (COLS < 32)
		width = COLS / 2;

	    /* Clear the shortcut list from the bottom of the screen. */
	    blank_bottombars();

	    /* Now show the ones for "Yes", "No", "Cancel" and maybe "All". */


	    if (all) {
		shortstr[1] = allstr[0];
		wmove(bottomwin, 1, width);
		onekey(shortstr, _("All"), width);
	    }

            for(i = 0; i < count && i < 5; i++){
                sprintf(but, "%d", i + 1);
                if(i == 0) wmove(bottomwin, 1, 0);
                else wmove(bottomwin, 1, i * width);
                if(p){
                    onekey(but, p->word, width);
                    p = p->next;
                }
                j++;
            }

	    wmove(bottomwin, 1, i * width);
	    onekey("^C", _("Cancel"), width);
	}

	if (interface_color_pair[TITLE_BAR].bright)
	    wattron(bottomwin, A_BOLD);
	wattron(bottomwin, interface_color_pair[TITLE_BAR].pairnum);

	blank_statusbar();
	mvwaddnstr(bottomwin, 0, 0, msg, actual_x(msg, COLS - 1));

	wattroff(bottomwin, A_BOLD);
	wattroff(bottomwin, interface_color_pair[TITLE_BAR].pairnum);

	/* Refresh edit window and statusbar before getting input. */
	wnoutrefresh(edit);
	wnoutrefresh(bottomwin);

	currmenu = MYESNO;
	kbinput = get_kbinput(bottomwin);

#ifndef NANO_TINY
	if (kbinput == KEY_WINCH)
	    continue;
#endif
        /*49 is 1, 50 is 2 and so on*/

	func = func_from_key(&kbinput);

	if (func == do_cancel){
	    ok = 0;
            return ok;
        }
  
        if(kbinput == 's'){
            if(i == 5) {
                continue;
            }
        }
        if(kbinput <= '0' || kbinput > '0' + count) return -1;
        
        if(kbinput > '0' && kbinput <= '0' + count){
            p = l.head;
            i = kbinput - '0' - 1;
            if(j > 5) t = j - 5 + i;
            else t = i;

            while(t--) if(p){
                        p = p->next;
                        }
            
            if(tp == 1 || tp == 2){
                bs = strlen(str);
                while(bs--) do_backspace();
            }
            

            if(tp == 6 || tp == 7){
                if(str != NULL){


                    we = openfile->current_x;

                    while(openfile->current->data[we] != ' ' && openfile->current->data[we] != '\00'){
                     we++;
                        wc++;
                        do_right();
                    }

                    we--;
                    while(openfile->current->data[we] != ' ' && openfile->current->data[we] != '\00'){

                        do_backspace();
                        we--;
                    }
                }
            }
            
            
            do_output(p->word, strlen(p->word), FALSE);
            return tp;
        }


	else if (func == total_refresh) {
	    total_redraw();
	    continue;
	} else {
		/* Look for the kbinput in the Yes, No and (optionally)
		 * All strings. */
		if (strchr(yesstr, kbinput) != NULL)
		    ok = 1;
		else if (strchr(nostr, kbinput) != NULL)
		    ok = 0;
		else if (all && strchr(allstr, kbinput) != NULL)
		    ok = 2;
	}
        i = 0;
        p = l.head;
        
    } while (ok == -2);

    currmenu = oldmenu;
    return ok;
}
コード例 #23
0
ファイル: lensmass.c プロジェクト: jpcoles/jcode
/*============================================================================
 *                                  main
 *
 *==========================================================================*/
int main(int argc, char **argv)
{
    int i;
    char *infile = NULL;
    char *outfile = NULL;
    char *line;

    int dim=0;
    float *M = NULL;
    float *M0 = NULL;

    float *mean = NULL;

    float *eigen_values_r = NULL;
    float *eigen_values_i = NULL;
    float *eigen_vectors_r = NULL;
    float *eigen_vectors_l = NULL;

    eigen_t *eigen = NULL;

    int num_models  = 0;
    int models_size = 0;
    float **models  = NULL;
    
    int num_xs  = 0;
    int xs_size = 0;
    float *xs   = NULL;

    float start_time=0, end_time=0, total_time=0;

    int in_model = 0;
    int in_ensem = 0;
    int in_input = 0;

    int nev = 5;

    in  = stdin;
    out = stdout;
    err = stderr;

    static struct option long_options[] = {
        {"show", optional_argument, 0, 's'},
        {"scale", required_argument, 0, 0},
        {"sort", required_argument, 0, 0},
        {"nev", required_argument, 0, 0},
        {"mo", required_argument, 0, 0},
        {"proj", optional_argument, 0, 'p'},
        {"help", no_argument, 0, 'h'},
        {"format", no_argument, 0, 0},
        {"header", no_argument, 0, 0},
        {"interp", no_argument, 0, 0},
        {"add-back-mean", no_argument, 0, 0},
        {0, 0, 0, 0}
    };

    /*========================================================================
     * Capture commandline arguments for write_header()
     *======================================================================*/

    if (argc != 1)
    {
        int c=0;
        for (i=1; i < argc; i++) c += strlen(argv[i]) + 1;
        commandline = (char *)calloc(c + 1, sizeof(char));
        for (i=1; i < argc; i++)
        {
            strcat(commandline, argv[i]);
            strcat(commandline, " ");
        }
    }

    /*========================================================================
     * Process the command line flags
     *======================================================================*/
    while (1)
    {
        int option_index = 0;
        int c = getopt_long(argc, argv, "p::i:o:v::s::hc", 
                            long_options, &option_index);

        if (c == -1) break;

        switch (c)
        {
            case 0:
                if (!strcmp("mo", long_options[option_index].name))
                {
                    opt_multi_out = 1;
                    mo_prefix = optarg;
                }
                if (!strcmp("interp", long_options[option_index].name))
                {
                    opt_interp_proj = 1;
                }
                else if (!strcmp("scale", long_options[option_index].name))
                {
                    if (!strcmp("mult", optarg))
                        opt_scale = SCALE_MULT;
                    else if (!strcmp("diag", optarg))
                        opt_scale = SCALE_DIAG;
                    else if (!strcmp("none", optarg))
                        opt_scale = SCALE_NONE;
                    else
                        error("Unrecognized scale type.");
                }
                else if (!strcmp("sort", long_options[option_index].name))
                {
                    if (!strcmp("ev", optarg))
                        opt_sort = SORT_EV;
                    else if (!strcmp("lc", optarg))
                        opt_sort = SORT_LC;
                    else
                        error("Unrecognized sort type.");
                }
                else if (!strcmp("header", long_options[option_index].name))
                {
                    write_header(err);
                    exit(0);
                }
                else if (!strcmp("add-back-mean", long_options[option_index].name))
                {
                    opt_add_back_mean = 1;
                }
                else if (!strcmp("format", long_options[option_index].name))
                {
fprintf(err, 
"\n"
"#BEGIN INPUT\n"
"<PixeLens input text line 0>\n"
"<PixeLens input text line 1>\n"
"  ...\n"
"<PixeLens input text line n>\n"
"#END INPUT\n"
"#BEGIN ENSEM \n"
"#BEGIN MODEL\n"
"<point 0>\n"
"<point 1>\n"
"  ...\n"
"<point m>\n"
"#END MODEL\n"
"  ...\n"
"#END ENSEM\n"
"\n"
"Blank lines are allowed and any line beginning with a '#' that is\n"
"not mentioned above is interpretted as a comment. It may be the case\n"
"that there are no models. \n"
"\n"
);
                    exit(0);

                }
                break;

            case 's':
                opt_show = 0;
                if (optarg == NULL)
                {
                    opt_show = SHOW_DEFAULT;
                }
                else
                {
                    if (strchr(optarg, 'm')) opt_show |= SHOW_MATRIX_FLAT;
                    if (strchr(optarg, 'M')) opt_show |= SHOW_MATRIX;
                    if (strchr(optarg, 'e')) opt_show |= SHOW_EIGEN_VALUES;
                    if (strchr(optarg, 'r')) opt_show |= SHOW_EIGEN_VECTORS_R;
                    if (strchr(optarg, 'l')) opt_show |= SHOW_EIGEN_VECTORS_L;
                }
                break;

            case 'v':
                if (optarg == NULL) verbosity++;
                else                verbosity = atoi(optarg);
                break;

            case 'i': 
                fprintf(err, "%s\n", optarg);
            infile = optarg; break;
            case 'o': outfile = optarg; break;
            case 'p': 
                fprintf(err, "%s\n", optarg);
                opt_proj = 1;
                if (optarg != NULL) nev = atoi(optarg);
                break;

            case 'h': help(); break;
            case '?': exit(2);
        }
    }

    if (opt_multi_out && !opt_proj)
    {
        fprintf(err, "--mo needs -p\n");
        exit(2);
    }

    if (!opt_show && !opt_proj)
        opt_show = SHOW_DEFAULT;

    if (infile != NULL) 
    {
        in = fopen(infile, "r");
        if (in == NULL)
        {
            fprintf(err, "%s", strerror(errno));
            exit(EXIT_FAILURE);
        }
    }

    if (outfile != NULL) 
    {
        out = fopen(outfile, "w");
        if (out == NULL)
        {
            fprintf(err, "%s", strerror(errno));
            exit(EXIT_FAILURE);
        }
    }


    /*========================================================================
     * Read commands or numerical input from the command line and update
     * the matrix accordingly, until there is no more input. The file we 
     * expect to read has the following structure:
     *
     * #BEGIN INPUT
     * #END INPUT
     * #BEGIN ENSEM 
     * #BEGIN MODEL
     * <point 0>
     * <point 1>
     *   ...
     * <point dim-1>
     * #END MODEL
     *   ...
     * #END ENSEM
     *
     * Blank lines are allowed and any line beginning with a '#' that is
     * not mentioned above is interpretted as a comment. It may be the case
     * that there are no models. 
     *
     *======================================================================*/

    rl_instream = in;
    rl_outstream = out;
    while (1)
    {
        line = readline(NULL);
        if (line == NULL) break;            /* EOF */
        if (strlen(line) == 0) continue;    /* Blank line */

        if (strstr(line, "#BEGIN INPUT") == line)
        {
            if (num_input_lines == input_size)
            {
                input_size += 5;
                input = (char **)realloc(input, input_size * sizeof(char *));
            }
            input[num_input_lines++] = line;

            in_input = 1;

            line = NULL; // prevent deallocation of line by free()

        }
        else if (strstr(line, "#END INPUT") == line)
        {
            in_input = 0;
            num_input_lines++;

            if (num_input_lines-1 == input_size)
            {
                input_size += 5;
                input = (char **)realloc(input, input_size * sizeof(char *));
            }
            input[num_input_lines-1] = line;

            line = NULL; // prevent deallocation of line by free()
        }
        else if (strstr(line, "#BEGIN LENS") == line) /*Backward compatibility*/
        {
            int q;
            sscanf(line, "#BEGIN LENS dim %i omega %f lambda %f", 
                &q, &omega, &lambda);

            in_ensem = 1;
        }
        else if (strstr(line, "#BEGIN ENSEM") == line)
        {
            in_ensem = 1;
        }
        else if (strstr(line, "#END LENS")  == line 
             ||  strstr(line, "#END ENSEM") == line)
        {
            in_ensem = 0;
            in_model = 0;
        }
        else if (in_ensem && strstr(line, "#BEGIN MODEL") == line)
        {
            num_xs = 0;
            xs = NULL;

            start_time = CPUTIME;

            if (in_model)
            {
                error("File inconsistency. "
                      "#BEGIN MODEL found before #END MODEL.\n");
            }

            in_model = 1;
        }
        else if (in_model && strstr(line, "#END MODEL") == line)
        {
            /*================================================================
             * Now that the x's have been read, update the matrix.
             *==============================================================*/
            if (!in_model)
            {
                error("File inconsistency. "
                      "#END MODEL found before #BEGIN MODEL.\n");
            }

            if (num_models == models_size)
            {
                models_size += 100;
                models = (float **)realloc(models, 
                                           models_size * sizeof(float *));
            }
            models[num_models++] = xs;


            if (verbosity > 1)
            {
                end_time = CPUTIME;
                total_time += end_time - start_time;

                fprintf(err, "[%ix%i matrix; %i models; %fs; %fs]\n", 
                        dim, dim, num_models, 
                        end_time - start_time, total_time);
            }

            in_model = 0;
        }
        else if (line[0] == '#') 
        {
            continue;
        }
        else if (in_model)
        {
            /*================================================================
             * Read the input values.
             *==============================================================*/

            if (num_models == 0)
            {
                if (num_xs == xs_size)
                {
                    xs_size += 100;
                    xs = (float *)realloc(xs, xs_size * sizeof(float));
                }

                dim = num_xs+1;
            }
            else if (num_xs > dim)
            {
                error("Model sizes differ!");
            }
            else if (xs == NULL)
            {
                xs = (float *)malloc(dim * sizeof(float));
            }

            xs[num_xs++] = atof(line);
        }
        else if (in_input)
        {
            num_input_lines++;

            if (num_input_lines-1 == input_size)
            {
                input_size += 5;
                input = (char **)realloc(input, input_size * sizeof(char *));
            }
            input[num_input_lines-1] = line;

            line = NULL; // prevent deallocation of line by free()
        }


        free(line);
    }


    if (verbosity > 0)
        fprintf(err, "[%ix%i matrix; %i models]\n", dim, dim, num_models);

    if (!opt_multi_out) 
    {
        write_header(out);
        write_input(out);
    }

    /*========================================================================
     *------------------------------------------------------------------------
     *======================================================================*/

    if (dim > 0)
    {
        /*====================================================================
         * Center the data points to the origin.
         *==================================================================*/

        /* Find the average of the models. */
        mean = (float *)calloc(dim, sizeof(float));
        for (i=0; i < num_models; i++)
            vecvecadd(mean, models[i], dim, mean);
        vecdiv(mean, num_models, dim, mean);

        /* Subtract off the mean from each of the models. */
        if (verbosity > 0) fprintf(err, "Normalizing models...\n");
        for (i=0; i < num_models; i++)
            vecvecsub(models[i], mean, dim, models[i]);

        /*====================================================================
         * Optionally apply a general multiplicative scaling.
         *==================================================================*/
        if (opt_scale & SCALE_MULT)
        {
            if (verbosity > 0) fprintf(err, "Applying multiply scaling...\n");
            scale(models[i], dim, NULL);
        }

        /*====================================================================
         * Now with the normalized data, generate the inertia matrix.
         *==================================================================*/
        if (verbosity > 0) fprintf(err, "Creating matrix...\n");
        M = (float *)calloc(dim * dim, sizeof(float));
        if (M == NULL) error("Can't allocate memory for matrix.");

        for (i=0; i < num_models; i++)
            update_matrix(M, models[i], dim);

        /*====================================================================
         * Optionally apply a diagonalization scaling.
         *==================================================================*/
        if (opt_scale & SCALE_DIAG)
        {
            M0 = (float *)malloc(dim * dim * sizeof(float));
            float *t;

            int i, j;
            if (verbosity > 0) fprintf(err, "Applying diagonal scaling...\n");
            for (i=0; i < dim; i++)
                for (j=0; j < dim; j++)
                    M0[i*dim+j] = M[i*dim+j] / sqrt(M[i*dim+i] * M[j*dim+j]);

            for (i=0; i < num_models; i++)
                scale(models[i], dim, M);

            t = M;
            M = M0;
            M0 = t;
        }
        else
        {
            M0 = M;
        }

        /*====================================================================
         * Compute the eigen values (and vectors) of the matrix we built. 
         *==================================================================*/
        if (verbosity>0) fprintf(err, "Calculating eigenvalues(/vectors)...\n");
        eigen_values_r = (float *)malloc(dim * sizeof(float)); assert(eigen_values_r != NULL);
        eigen_values_i = (float *)malloc(dim * sizeof(float)); assert(eigen_values_i != NULL);

        if (opt_proj || (opt_show & SHOW_EIGEN_VECTORS_R))
        {
            eigen_vectors_r = (float *)malloc(dim * dim * sizeof(float)); assert(eigen_vectors_r != NULL);
        }

        if (opt_show & SHOW_EIGEN_VECTORS_L)
        {
            eigen_vectors_l = (float *)malloc(dim * dim * sizeof(float)); assert(eigen_vectors_r != NULL);
        }

        if (get_eigen_values(M, eigen_values_r, eigen_values_i, 
                                eigen_vectors_l, eigen_vectors_r, dim,
                                0))
        {
            error("Library call failed for given inputs.");
        }


        /*====================================================================
         * Now place the results in a nice array which we can sort. The array
         * is sorted by the real part of the eigenvalues, largest to smallest.
         *==================================================================*/
        eigen = (eigen_t *)calloc(dim, sizeof(eigen_t));

        for (i=0; i < dim; i++)
        {
            if (eigen_values_r[i] == -0) eigen_values_r[i] = 0;
            if (eigen_values_i[i] == -0) eigen_values_i[i] = 0;

            eigen[i].re   = eigen_values_r[i];
            eigen[i].im   = eigen_values_i[i];
            eigen[i].dim  = dim;

            if (eigen_vectors_l) eigen[i].lvec = &(eigen_vectors_l[i * dim]);
            if (eigen_vectors_r) eigen[i].rvec = &(eigen_vectors_r[i * dim]);
        }

        /*====================================================================
         * Optionally add back the mean model.
         *==================================================================*/
        if (opt_add_back_mean)
        {
            if (verbosity>0) fprintf(err, "Adding back mean...\n");
            /* add back mean */
            if (eigen_vectors_r)
                for (i=0; i < dim; i++)
                    vecvecadd(eigen[i].rvec, mean, dim, eigen[i].rvec);

            if (eigen_vectors_l)
                for (i=0; i < dim; i++)
                    vecvecadd(eigen[i].lvec, mean, dim, eigen[i].lvec);
        }

        /*====================================================================
         * Sort.
         *==================================================================*/
        if (!opt_sort || (opt_sort & SORT_EV))
        {
            qsort(eigen, dim, sizeof(eigen_t), eigen_compar_rev);
        }
        else if (opt_sort & SORT_LC)
        {
            qsort(eigen, dim, sizeof(eigen_t), largest_ev_last_component);
        }

        /*====================================================================
         *--------------------------------------------------------------------
         *==================================================================*/

        if (opt_proj)
            do_eigen_projections(nev, M0, models, mean, num_models, eigen, dim);

    }


    do_output(M, omega, lambda, eigen, dim);


    if (M == M0) 
    {
        free(M);
    }
    else
    {
        free(M);
        free(M0);
    }
    free(eigen_values_r);
    free(eigen_values_i);
    free(eigen_vectors_l);
    free(eigen_vectors_r);
    free(eigen);
    free(mean);
    free(commandline);

    for (i=0; i < num_input_lines; i++) free(input[i]);
    free(input);

    for (i=0; i < num_models; i++) free(models[i]); 
    free(models);

    if (in  != stdin)  fclose(in);
    if (out != stdout) fclose(out);

    return 0;
}
コード例 #24
0
ファイル: main.c プロジェクト: debmartin/fiuba-orga-tps
static void
parse_cmdline(int argc, char * const argv[])
{
	int ch;
	int index = 0;

	struct option options[] = {
		{"help", no_argument, NULL, 'h'},
		{"version", no_argument, NULL, 'V'},
		{"geometry", required_argument, NULL, 'g'},
		{"resolution", required_argument, NULL, 'r'},
		{"center", required_argument, NULL, 'c'},
		{"width", required_argument, NULL, 'w'},
		{"height", required_argument, NULL, 'H'},
		{"method", required_argument, NULL, 'm'},
		{"nthreads", required_argument, NULL, 'n'},
		{"output", required_argument, NULL, 'o'},
	};

	while ((ch = getopt_long(argc, argv, 
	                         "hc:H:m:n:o:r:w:g:V", options, &index)) != -1) {
		switch (ch) {
		case 'h':
			do_usage(argv[0], 0);
			break;
		case 'V':
			do_version(argv[0]);
			break;
		case 'g':
			do_geometry(argv[0], optarg);
			break;
		case 'r':
			do_resolution(argv[0], optarg);
			break;
		case 'c':
			do_center(argv[0], optarg);
			break;
		case 'w':
			do_width(argv[0], optarg);
			break;
		case 'H':
			do_height(argv[0], optarg);
			break;
		case 'm':
			do_method(argv[0], optarg);
			break;
		case 'n':
			do_nthreads(argv[0], optarg);
			break;
		case 'o':
			do_output(argv[0], optarg);
			break;
		default:
			do_usage(argv[0], 1);
		}
	}

	if (plot == NULL)
		do_method(argv[0], "generic");
	if (!output) {
		fprintf(stderr, "no output file.\n");
		exit(1);
	}
}
コード例 #25
0
ファイル: jcontrol.c プロジェクト: Bun-chan/JuliusForAndroid
/** 
 * <JA>
 * @brief メインイベントループ
 * 
 * サーバからのメッセージ受信イベントおよびキーボードからのユーザ入力
 * イベントを 監視し,対応する処理を行うメイン関数.
 * 
 * @param sd [in] 送信ソケット
 * </JA>
 * <EN>
 * @brief Main event loop
 *
 * This is main loop to watch events from server (message of recognition
 * results etc.) and tty (user keyboard input), catch and process them.
 * 
 * @param sd [in] socket to send data
 * </EN>
 */
void
command_loop(int sd)
{
#if defined(_WIN32) && !defined(__CYGWIN32__)
  /* win32 version: read console input using conio.h */
  fd_set readfds;
  struct timeval tv;
  int status;
  int i, nfd;
  int ch;
  int slen;

  slen = 0;

  for(;;) {

    /* watch socket by select() and check keyboard input by _kbhit() if timeout */
    FD_ZERO(&readfds);
    FD_SET(sd, &readfds);
    tv.tv_sec = 0;
    tv.tv_usec = 50000;

    nfd = select(sd+1, &readfds, NULL, NULL, &tv);

    if (nfd < 0) { /* winsock error */
      switch(WSAGetLastError()) {
      case WSANOTINITIALISED: printf(" A successful WSAStartup must occur before using this function. \n"); break;
      case WSAEFAULT: printf(" The Windows Sockets implementation was unable to allocate needed resources for its internal operations, or the readfds, writefds, exceptfds, or timeval parameters are not part of the user address space.  \n"); break;
      case WSAENETDOWN: printf(" The network subsystem has failed.  \n"); break;
      case WSAEINVAL: printf(" The timeout value is not valid, or all three descriptor parameters were NULL.  \n"); break;
      case WSAEINTR: printf(" A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.  \n"); break;
      case WSAEINPROGRESS: printf(" A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.  \n"); break;
      case WSAENOTSOCK: printf(" One of the descriptor sets contains an entry that is not a socket.  \n"); break;
      }
      perror("Error: select");
      exit(1);
    }
    if (FD_ISSET(sd, &readfds)) {      /* from server */
      do_output(sd);
    } else {  /* timeout, check for keyboard input */
      if (_kbhit()) {
	ch = _getche();
	if (ch == '\r') ch = '\n';
	sbuf[slen] = (char)ch;
	slen++;
	if (ch == '\n') {
	  sbuf[slen] = '\0';
	  do_command(sd);	/* execute command */
	  slen = 0;
	}
      }
    }
  }

#else

  /* unix version: watch both stdin and socket */
  fd_set readfds;
  int nfd;

  for(;;) {

    /* watch socket (fd = sd) and stdin (fd = 0) */
    FD_ZERO(&readfds);
    FD_SET(sd, &readfds);
    FD_SET(0, &readfds);

    nfd = select(sd+1, &readfds, NULL, NULL, NULL);

    if (nfd < 0) {
      perror("Error: select");
      exit(1);
    }
    if (FD_ISSET(0, &readfds)) {
      /* stdin */
      if (fgets(sbuf, MAXLINELEN, stdin) != NULL) {
	do_command(sd);
      }
    }
    if (FD_ISSET(sd, &readfds)) {
      /* from server */
      do_output(sd);
    }
  }
  
#endif /* WIN32 */

}
コード例 #26
0
ファイル: test_wb_aes_inv.c プロジェクト: logostream/wbaes
void test_decryption()
{
	gf2matrix *mix_columns_mixing_bijection, *inv_mix_columns_mixing_bijection;
	tbox_mixing_bijections_t tbox_mixing_bijections, inv_tbox_mixing_bijections;
	gf2matrix *initial_encoding, *initial_decoding;
	gf2matrix *final_encoding, *final_decoding;
	tbox_t tbox;
	typeIA_t typeIAs;
	typeII_t typeIIs;
	typeIII_t typeIIIs;
	typeIB_t typeIBs;
	typeIV_IA_t typeIV_IAs;
	typeIV_IB_t typeIV_IBs;
	typeIV_II_round_t typeIV_IIs[NR - 1];
	typeIV_III_round_t typeIV_IIIs[NR - 1];
	uint32_t mixed_key_schedule[4 * (NR + 1)];
	uint8_t key[KEY_SIZE] = {
			0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
			0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c};
	sboxes_8bit_t typeIA_input_sbox, typeIA_input_sbox_inv;
	sboxes_128bit_t typeIA_interim_sbox, typeIA_interim_sbox_inv;
	sboxes_8bit_t typeII_input_sbox[NR], typeII_input_sbox_inv[NR];
	sboxes_32bit_t typeII_interim_sbox[NR - 1], typeII_interim_sbox_inv[NR - 1];
	sboxes_8bit_t typeII_output_sbox[NR - 1], typeII_output_sbox_inv[NR - 1];
	sboxes_32bit_t typeIII_interim_sbox[NR - 1], typeIII_interim_sbox_inv[NR
			- 1];
	sboxes_128bit_t typeIB_interim_sbox, typeIB_interim_sbox_inv;
	sboxes_8bit_t typeIB_output_sbox, typeIB_output_sbox_inv;
	uint8_t state[4][4];
	uint8_t in[16];
	uint8_t out[16], out2[16];
	_4bit_strip32_t strips32;
	_4bit_strip128_t strips128;
	int round, row, col, i;

	int tries = 3;
	for (; tries != 0; --tries) {
		randomize_key(key);
		make_block_invertible_matrix_pair(&mix_columns_mixing_bijection,
				&inv_mix_columns_mixing_bijection, 32);
/* 		mix_columns_mixing_bijection = make_identity_matrix(32); */
/* 		inv_mix_columns_mixing_bijection = make_identity_matrix(32); */
		make_tbox_mixing_bijections(tbox_mixing_bijections,
				inv_tbox_mixing_bijections);
/* 		make_identity_tbox_mixing_bijections(tbox_mixing_bijections); */
/* 		make_identity_tbox_mixing_bijections(inv_tbox_mixing_bijections); */

		make_block_invertible_matrix_pair(&initial_encoding, &initial_decoding, 128);
/* 		initial_encoding = make_identity_matrix(128); */
/* 		initial_decoding = make_identity_matrix(128); */
		make_block_invertible_matrix_pair(&final_encoding, &final_decoding, 128);
/* 		final_encoding = make_identity_matrix(128); */
/* 		final_decoding = make_identity_matrix(128); */

		expand_key(key, SBox, mixed_key_schedule, 4);
		mix_expanded_key(mixed_key_schedule);
		make_inv_tbox(tbox, ISBox, mixed_key_schedule, tbox_mixing_bijections);

		make_sbox_pair_8(typeIA_input_sbox, typeIA_input_sbox_inv);
/* 		make_identity_sboxes8(typeIA_input_sbox); */
/* 		make_identity_sboxes8(typeIA_input_sbox_inv); */
		make_sbox_pair_128(typeIA_interim_sbox, typeIA_interim_sbox_inv);
/* 		make_identity_sboxes128(typeIA_interim_sbox); */
/* 		make_identity_sboxes128(typeIA_interim_sbox_inv); */
		make_rounds_sbox_pair_8(typeII_input_sbox, typeII_input_sbox_inv, NR);
/* 		for(i =0; i < NR; ++i) { */
/* 			make_identity_sboxes8(typeII_input_sbox[i]); */
/* 			make_identity_sboxes8(typeII_input_sbox_inv[i]); */
/* 		} */
		make_rounds_sbox_pair_32(typeII_interim_sbox, typeII_interim_sbox_inv,
				NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes32(typeII_interim_sbox[i]); */
/* 			make_identity_sboxes32(typeII_interim_sbox_inv[i]); */
/* 		} */
		make_rounds_sbox_pair_8(typeII_output_sbox, typeII_output_sbox_inv, NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes8(typeII_output_sbox[i]); */
/* 			make_identity_sboxes8(typeII_output_sbox_inv[i]); */
/* 		} */

		make_rounds_sbox_pair_32(typeIII_interim_sbox, typeIII_interim_sbox_inv,
				NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes32(typeIII_interim_sbox[i]); */
/* 			make_identity_sboxes32(typeIII_interim_sbox_inv[i]); */
/* 		} */
		make_sbox_pair_128(typeIB_interim_sbox, typeIB_interim_sbox_inv);
/* 		make_identity_sboxes128(typeIB_interim_sbox); */
/* 		make_identity_sboxes128(typeIB_interim_sbox_inv); */
		make_sbox_pair_8(typeIB_output_sbox, typeIB_output_sbox_inv);
/* 		make_identity_sboxes8(typeIB_output_sbox); */
/* 		make_identity_sboxes8(typeIB_output_sbox_inv); */


		make_typeIA(typeIAs, inv_tbox_mixing_bijections[NR - 1], initial_decoding,
				typeIA_input_sbox_inv, typeIA_interim_sbox);
		make_typeIV_IA(typeIV_IAs, typeIA_interim_sbox_inv,
				typeII_input_sbox[NR - 1], typeII_input_sbox_inv[NR-1]);
		make_inv_typeII(typeIIs, tbox, mix_columns_mixing_bijection,
				&typeII_input_sbox_inv[1], typeII_interim_sbox);
		make_typeIV_II(typeIV_IIs, typeII_interim_sbox_inv, typeII_output_sbox,
				typeII_output_sbox_inv);
		make_typeIII(typeIIIs, inv_mix_columns_mixing_bijection,
				inv_tbox_mixing_bijections, typeII_output_sbox_inv,
				typeIII_interim_sbox);
		make_typeIV_III(typeIV_IIIs, typeIII_interim_sbox_inv,
				typeII_input_sbox, typeII_input_sbox_inv);
		make_inv_typeIB(typeIBs, tbox[0], final_encoding,
				typeII_input_sbox_inv[0], typeIB_interim_sbox);
		make_typeIV_IB(typeIV_IBs, typeIB_interim_sbox_inv, typeIB_output_sbox,
				typeIB_output_sbox_inv);

		for (i = 0; i < 16; ++i) {
			in[i] = rand();
		}
		dump_hex("input: ", in, 16);
		printf("White-box inverse cipher:\n");
		do_input(state, in, initial_encoding, typeIA_input_sbox);

		dump_state("State before ", state);
		do_typeIA(strips128, state, typeIAs);
		do_typeIV_IA(state, strips128, typeIV_IAs);
		for (round = NR - 2; round != -1; --round) {
			printf("round %d: ", round + 2);
			dump_state("", state);
			inv_shift_rows(state);
			do_typeII(strips32, state, typeIIs[round]);
			do_typeIV_II(state, strips32, typeIV_IIs[round]);
			do_typeIII(strips32, state, typeIIIs[round]);
			do_typeIV_III(state, strips32, typeIV_IIIs[round]);
		}
		inv_shift_rows(state);
		dump_state("rounds 1 and 0: ", state);
		do_typeIB(strips128, state, typeIBs);
		do_typeIV_IB(state, strips128, typeIV_IBs);

		do_output(out, state, final_decoding, typeIB_output_sbox_inv);

		printf("Original AES Equivalent Inverse Cipher on same input using same key:\n");
		eqv_decipher(in, out2, ISBox, mixed_key_schedule);
		dump_hex("WB Output ", out, 16);
		dump_hex("AES Output ", out2, 16);
		ASSERT(memcmp(out, out2, 16) == 0);
		free_matrix(mix_columns_mixing_bijection);
		free_matrix(inv_mix_columns_mixing_bijection);
		free_tbox_mixing_bijections(tbox_mixing_bijections);
		free_tbox_mixing_bijections(inv_tbox_mixing_bijections);
		free_matrix(final_decoding);
		free_matrix(final_encoding);
		free_matrix(initial_decoding);
		free_matrix(initial_encoding);
	}
}
コード例 #27
0
ファイル: process.c プロジェクト: OpenSC/openct
int ifdhandler_process(ct_socket_t * sock, ifd_reader_t * reader,
		       ct_buf_t * argbuf, ct_buf_t * resbuf)
{
	unsigned char cmd, unit;
	ct_tlv_parser_t args;
	ct_tlv_builder_t resp;
	int rc;

	/* Get command and target unit */
	if (ct_buf_get(argbuf, &cmd, 1) < 0 || ct_buf_get(argbuf, &unit, 1) < 0)
		return IFD_ERROR_INVALID_MSG;

	ifd_debug(1, "ifdhandler_process(cmd=%s, unit=%u)",
		  get_cmd_name(cmd), unit);

	/* First, handle commands that don't do TLV encoded
	 * arguments - currently this is only CT_CMD_TRANSACT. */
	if (cmd == CT_CMD_TRANSACT_OLD) {
		/* Security - deny any APDUs if there's an
		 * exclusive lock held by some other client. */
		if ((rc =
		     ifdhandler_check_lock(sock, unit, IFD_LOCK_EXCLUSIVE)) < 0)
			return rc;
		return do_transact_old(reader, unit, argbuf, resbuf);
	}

	if ((rc = do_before_command(reader)) < 0) {
		return rc;
	}

	memset(&args, 0, sizeof(args));
	if (ct_tlv_parse(&args, argbuf) < 0)
		return IFD_ERROR_INVALID_MSG;
	if (args.use_large_tags)
		sock->use_large_tags = 1;

	ct_tlv_builder_init(&resp, resbuf, sock->use_large_tags);

	switch (cmd) {
	case CT_CMD_STATUS:
		rc = do_status(reader, unit, &args, &resp);
		break;

	case CT_CMD_OUTPUT:
		rc = do_output(reader, unit, &args, &resp);
		break;

	case CT_CMD_RESET:
	case CT_CMD_REQUEST_ICC:
		rc = do_reset(reader, unit, &args, &resp);
		break;

	case CT_CMD_EJECT_ICC:
		rc = do_eject(reader, unit, &args, &resp);
		break;

	case CT_CMD_PERFORM_VERIFY:
		rc = do_verify(reader, unit, &args, &resp);
		break;

	case CT_CMD_LOCK:
		rc = do_lock(sock, reader, unit, &args, &resp);
		break;

	case CT_CMD_UNLOCK:
		rc = do_unlock(sock, reader, unit, &args, &resp);
		break;

	case CT_CMD_MEMORY_READ:
		rc = do_memory_read(reader, unit, &args, &resp);
		break;

	case CT_CMD_MEMORY_WRITE:
		rc = do_memory_write(reader, unit, &args, &resp);
		break;

	case CT_CMD_TRANSACT:
		rc = do_transact(reader, unit, &args, &resp);
		break;
	case CT_CMD_SET_PROTOCOL:
		rc = do_set_protocol(reader, unit, &args, &resp);
		break;
	default:
		return IFD_ERROR_INVALID_CMD;
	}

	if (rc >= 0)
		rc = resp.error;

	/*
	 * TODO consider checking error
	 */
	do_after_command(reader);

	return rc;
}
コード例 #28
0
int
main (int argc, char *argv[])
{
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEBASEDIR);
  textdomain (PACKAGE);

  enum { HELP_OPTION = CHAR_MAX + 1 };

  static const char *options = "a:c:d:hlvVx";
  static const struct option long_options[] = {
    { "add", 1, 0, 'a' },
    { "all", 0, 0, 0 },
    { "blkdevs", 0, 0, 0 },
    { "block-devices", 0, 0, 0 },
    { "connect", 1, 0, 'c' },
    { "csv", 0, 0, 0 },
    { "domain", 1, 0, 'd' },
    { "echo-keys", 0, 0, 0 },
    { "extra", 0, 0, 0 },
    { "filesystems", 0, 0, 0 },
    { "format", 2, 0, 0 },
    { "help", 0, 0, HELP_OPTION },
    { "human-readable", 0, 0, 'h' },
    { "keys-from-stdin", 0, 0, 0 },
    { "logical-volumes", 0, 0, 0 },
    { "logvols", 0, 0, 0 },
    { "long", 0, 0, 'l' },
    { "long-options", 0, 0, 0 },
    { "lvs", 0, 0, 0 },
    { "no-title", 0, 0, 0 },
    { "parts", 0, 0, 0 },
    { "partitions", 0, 0, 0 },
    { "physical-volumes", 0, 0, 0 },
    { "physvols", 0, 0, 0 },
    { "pvs", 0, 0, 0 },
    { "uuid", 0, 0, 0 },
    { "uuids", 0, 0, 0 },
    { "verbose", 0, 0, 'v' },
    { "version", 0, 0, 'V' },
    { "vgs", 0, 0, 0 },
    { "volgroups", 0, 0, 0 },
    { "volume-groups", 0, 0, 0 },
    { 0, 0, 0, 0 }
  };
  struct drv *drvs = NULL;
  struct drv *drv;
  const char *format = NULL;
  int c;
  int option_index;
  int no_title = 0;             /* --no-title */
  int long_mode = 0;            /* --long|-l */
  int uuid = 0;                 /* --uuid */
  int title;

  g = guestfs_create ();
  if (g == NULL) {
    fprintf (stderr, _("guestfs_create: failed to create handle\n"));
    exit (EXIT_FAILURE);
  }

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, &option_index);
    if (c == -1) break;

    switch (c) {
    case 0:			/* options which are long only */
      if (STREQ (long_options[option_index].name, "long-options"))
        display_long_options (long_options);
      else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
        keys_from_stdin = 1;
      } else if (STREQ (long_options[option_index].name, "echo-keys")) {
        echo_keys = 1;
      } else if (STREQ (long_options[option_index].name, "format")) {
        if (!optarg || STREQ (optarg, ""))
          format = NULL;
        else
          format = optarg;
      } else if (STREQ (long_options[option_index].name, "all")) {
        output = OUTPUT_ALL;
      } else if (STREQ (long_options[option_index].name, "blkdevs") ||
                 STREQ (long_options[option_index].name, "block-devices")) {
        output |= OUTPUT_BLOCKDEVS;
      } else if (STREQ (long_options[option_index].name, "csv")) {
        csv = 1;
      } else if (STREQ (long_options[option_index].name, "extra")) {
        output |= OUTPUT_FILESYSTEMS;
        output |= OUTPUT_FILESYSTEMS_EXTRA;
      } else if (STREQ (long_options[option_index].name, "filesystems")) {
        output |= OUTPUT_FILESYSTEMS;
      } else if (STREQ (long_options[option_index].name, "logical-volumes") ||
                 STREQ (long_options[option_index].name, "logvols") ||
                 STREQ (long_options[option_index].name, "lvs")) {
        output |= OUTPUT_LVS;
      } else if (STREQ (long_options[option_index].name, "no-title")) {
        no_title = 1;
      } else if (STREQ (long_options[option_index].name, "parts") ||
                 STREQ (long_options[option_index].name, "partitions")) {
        output |= OUTPUT_PARTITIONS;
      } else if (STREQ (long_options[option_index].name, "physical-volumes") ||
                 STREQ (long_options[option_index].name, "physvols") ||
                 STREQ (long_options[option_index].name, "pvs")) {
        output |= OUTPUT_PVS;
      } else if (STREQ (long_options[option_index].name, "uuid") ||
                 STREQ (long_options[option_index].name, "uuids")) {
        uuid = 1;
      } else if (STREQ (long_options[option_index].name, "vgs") ||
                 STREQ (long_options[option_index].name, "volgroups") ||
                 STREQ (long_options[option_index].name, "volume-groups")) {
        output |= OUTPUT_VGS;
      } else {
        fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
                 program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'a':
      OPTION_a;
      break;

    case 'c':
      OPTION_c;
      break;

    case 'd':
      OPTION_d;
      break;

    case 'h':
      human = 1;
      break;

    case 'l':
      long_mode = 1;
      break;

    case 'v':
      OPTION_v;
      break;

    case 'V':
      OPTION_V;
      break;

    case 'x':
      OPTION_x;
      break;

    case HELP_OPTION:
      usage (EXIT_SUCCESS);

    default:
      usage (EXIT_FAILURE);
    }
  }

  /* These are really constants, but they have to be variables for the
   * options parsing code.  Assert here that they have known-good
   * values.
   */
  assert (read_only == 1);
  assert (inspector == 0);
  assert (live == 0);

  /* Must be no extra arguments on the command line. */
  if (optind != argc)
    usage (EXIT_FAILURE);

  /* -h and --csv doesn't make sense.  Spreadsheets will corrupt these
   * fields.  (RHBZ#600977).
   */
  if (human && csv) {
    fprintf (stderr, _("%s: you cannot use -h and --csv options together.\n"),
             program_name);
    exit (EXIT_FAILURE);
  }

  /* Nothing selected for output, means --filesystems is implied. */
  if (output == 0)
    output = OUTPUT_FILESYSTEMS;

  /* What columns will be displayed? */
  columns = COLUMN_NAME;
  if (long_mode) {
    columns |= COLUMN_TYPE;
    columns |= COLUMN_SIZE;
    if ((output & OUTPUT_FILESYSTEMS)) {
      columns |= COLUMN_VFS_TYPE;
      columns |= COLUMN_VFS_LABEL;
    }
    columns |= COLUMN_PARENTS;
    if ((output & OUTPUT_PARTITIONS))
      columns |= COLUMN_MBR;
    if (uuid)
      columns |= COLUMN_UUID;
  }

  /* Display title by default only in long mode. */
  title = long_mode;
  if (no_title)
    title = 0;

  /* User must have specified some drives. */
  if (drvs == NULL)
    usage (EXIT_FAILURE);

  /* Add drives. */
  add_drives (drvs, 'a');

  if (guestfs_launch (g) == -1)
    exit (EXIT_FAILURE);

  /* Free up data structures, no longer needed after this point. */
  free_drives (drvs);

  if (title)
    do_output_title ();
  do_output ();
  do_output_end ();

  free_pvs ();

  guestfs_close (g);

  exit (EXIT_SUCCESS);
}
コード例 #29
0
ファイル: main.c プロジェクト: rashadkm/grass_cmake
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *quant, *perc, *slots, *basemap, *covermap, *output;
    } opt;
    struct {
	struct Flag *r, *p;
    } flag;
    const char *basemap, *covermap;
    char **outputs;
    int reclass, print;
    int cover_fd, base_fd;
    struct Range range;
    struct FPRange fprange;
    int i;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("statistics"));
    module->description = _("Compute category quantiles using two passes.");

    opt.basemap = G_define_standard_option(G_OPT_R_BASE);

    opt.covermap = G_define_standard_option(G_OPT_R_COVER);

    opt.quant = G_define_option();
    opt.quant->key = "quantiles";
    opt.quant->type = TYPE_INTEGER;
    opt.quant->required = NO;
    opt.quant->description = _("Number of quantiles");

    opt.perc = G_define_option();
    opt.perc->key = "percentiles";
    opt.perc->type = TYPE_DOUBLE;
    opt.perc->multiple = YES;
    opt.perc->description = _("List of percentiles");
    opt.perc->answer = "50";

    opt.slots = G_define_option();
    opt.slots->key = "bins";
    opt.slots->type = TYPE_INTEGER;
    opt.slots->required = NO;
    opt.slots->description = _("Number of bins to use");
    opt.slots->answer = "1000";

    opt.output = G_define_standard_option(G_OPT_R_OUTPUT);
    opt.output->description = _("Resultant raster map(s)");
    opt.output->required = NO;
    opt.output->multiple = YES;

    flag.r = G_define_flag();
    flag.r->key = 'r';
    flag.r->description =
	_("Create reclass map with statistics as category labels");

    flag.p = G_define_flag();
    flag.p->key = 'p';
    flag.p->description =
	_("Do not create output maps; just print statistics");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    basemap = opt.basemap->answer;
    covermap = opt.covermap->answer;
    outputs = opt.output->answers;
    reclass = flag.r->answer;
    print = flag.p->answer;

    if (!print && !opt.output->answers)
	G_fatal_error(_("Either -%c or %s= must be given"),
			flag.p->key, opt.output->key);

    if (print && opt.output->answers)
	G_fatal_error(_("-%c and %s= are mutually exclusive"),
			flag.p->key, opt.output->key);

    num_slots = atoi(opt.slots->answer);

    if (opt.quant->answer) {
	num_quants = atoi(opt.quant->answer) - 1;
	quants = G_calloc(num_quants, sizeof(DCELL));
	for (i = 0; i < num_quants; i++)
	    quants[i] = 1.0 * (i + 1) / (num_quants + 1);
    }
    else {
	for (i = 0; opt.perc->answers[i]; i++)
	    ;
	num_quants = i;
	quants = G_calloc(num_quants, sizeof(DCELL));
	for (i = 0; i < num_quants; i++)
	    quants[i] = atof(opt.perc->answers[i]) / 100;
	qsort(quants, num_quants, sizeof(DCELL), compare_dcell);
    }

    if (opt.output->answer) {
	for (i = 0; opt.output->answers[i]; i++)
	    ;
	if (i != num_quants)
	    G_fatal_error(_("Number of quantiles (%d) does not match number of output maps (%d)"),
			  num_quants, i);
    }

    base_fd = Rast_open_old(basemap, "");

    cover_fd = Rast_open_old(covermap, "");

    if (Rast_map_is_fp(basemap, "") != 0)
	G_fatal_error(_("The base map must be an integer (CELL) map"));

    if (Rast_read_range(basemap, "", &range) < 0)
	G_fatal_error(_("Unable to read range of base map <%s>"), basemap);

    Rast_get_range_min_max(&range, &min, &max);
    num_cats = max - min + 1;
    if (num_cats > MAX_CATS)
	G_fatal_error(_("Base map <%s> has too many categories (max: %d)"),
		      basemap, MAX_CATS);

    Rast_read_fp_range(covermap, "", &fprange);
    Rast_get_fp_range_min_max(&fprange, &f_min, &f_max);
    slot_size = (f_max - f_min) / num_slots;

    basecats = G_calloc(num_cats, sizeof(struct basecat));

    for (i = 0; i < num_cats; i++)
	basecats[i].slots = G_calloc(num_slots, sizeof(unsigned int));

    rows = Rast_window_rows();
    cols = Rast_window_cols();

    get_slot_counts(base_fd, cover_fd);

    initialize_bins();
    fill_bins(base_fd, cover_fd);


    sort_bins();
    compute_quantiles();

    if (print)
	print_quantiles();
    else if (reclass)
	do_reclass(basemap, outputs);
    else
	do_output(base_fd, outputs, covermap);

    Rast_close(cover_fd);
    Rast_close(base_fd);

    return (EXIT_SUCCESS);
}
コード例 #30
0
/* Execute a list of actions against 'skb'. */
static int do_execute_actions(struct datapath *dp, struct sk_buff *skb,
			const struct nlattr *attr, int len, bool keep_skb)
{
	/* Every output action needs a separate clone of 'skb', but the common
	 * case is just a single output action, so that doing a clone and
	 * then freeing the original skbuff is wasteful.  So the following code
	 * is slightly obscure just to avoid that. */
	int prev_port = -1;
	const struct nlattr *a;
	int rem;

	for (a = attr, rem = len; rem > 0;
	     a = nla_next(a, &rem)) {
		int err = 0;

		if (prev_port != -1) {
			do_output(dp, skb_clone(skb, GFP_ATOMIC), prev_port);
			prev_port = -1;
		}

		switch (nla_type(a)) {
		case OVS_ACTION_ATTR_OUTPUT:
			prev_port = nla_get_u32(a);
			break;

		case OVS_ACTION_ATTR_USERSPACE:
			output_userspace(dp, skb, a);
			break;

		case OVS_ACTION_ATTR_PUSH_VLAN:
			err = push_vlan(skb, nla_data(a));
			if (unlikely(err)) /* skb already freed. */
				return err;
			break;

		case OVS_ACTION_ATTR_POP_VLAN:
			err = pop_vlan(skb);
			break;

		case OVS_ACTION_ATTR_SET:
			err = execute_set_action(skb, nla_data(a));
			break;

		case OVS_ACTION_ATTR_SAMPLE:
			err = sample(dp, skb, a);
			break;
		}

		if (unlikely(err)) {
			kfree_skb(skb);
			return err;
		}
	}

	if (prev_port != -1) {
		if (keep_skb)
			skb = skb_clone(skb, GFP_ATOMIC);

		do_output(dp, skb, prev_port);
	} else if (!keep_skb)
		consume_skb(skb);

	return 0;
}