void parse_command_line( int argc, char** argv, bool& dualize, int64_t& upper_dim, std::string& input_filename, std::string& output_filename )
{
    if( argc < 3 )
        print_help_and_exit();

    input_filename = argv[ argc - 2 ];
    output_filename = argv[ argc - 1 ];

    for( int idx = 1; idx < argc - 2; idx++ ) {
        const std::string option = argv[ idx ];
        if( option == "--help" ) {
            print_help_and_exit( );
        } else if( option == "--dual" ) {
            dualize = true;
        } else if( option == "--upper_dim" ) {
            idx++;
            if( idx >= argc - 2 )
                print_help_and_exit( );
            std::string parameter = std::string( argv[ idx ] );
            size_t pos_last_digit;
            upper_dim = std::stoll( parameter, &pos_last_digit );
            if( pos_last_digit != parameter.size( ) )
                print_help_and_exit( );
	} else print_help_and_exit( );
    }
}
Example #2
0
int main(int argc, char **argv)
{
    const char *filename;
    int fd;
    int rc;

    if (argc != 2)
      print_help_and_exit(argv);

    int result, vid, pid;
    result = sscanf(argv[1], "%x:%x", &vid, &pid);

    if(!result)
       print_help_and_exit(argv);

    libusb_init(NULL);
    libusb_device_handle *handle = libusb_open_device_with_vid_pid(NULL, vid, pid);

    if(!handle) {
        fprintf(stderr, "Couldn't open device\n");
        return 1;
    }

    result = libusb_reset_device(handle);

    if(!handle) {
        fprintf(stderr, "Couldn't reset device\n");
        return 1;
    }

    return 0;
}
Example #3
0
void parse_command_line( int argc, char** argv, bool& use_binary, Representation_type& representation, Algorithm_type& algorithm,
                         std::string& input_filename, std::string& output_filename, bool& verbose, bool& dualize) {

    if( argc < 3 ) print_help_and_exit();

    input_filename = argv[ argc - 2 ];
    output_filename = argv[ argc - 1 ];

    for( int idx = 1; idx < argc - 2; idx++ ) {
        const std::string option = argv[ idx ];

        if( option == "--ascii" ) use_binary = false;
        else if( option == "--binary" ) use_binary = true;
        else if( option == "--dualize" ) dualize = true;
        else if( option == "--vector_vector" ) representation = VECTOR_VECTOR;
        else if( option == "--vector_heap" ) representation = VECTOR_HEAP;
        else if( option == "--vector_set" ) representation = VECTOR_SET;
        else if( option == "--vector_list" ) representation = VECTOR_LIST;
        else if( option == "--full_pivot_column" )  representation = FULL_PIVOT_COLUMN;
        else if( option == "--bit_tree_pivot_column" )  representation = BIT_TREE_PIVOT_COLUMN;
        else if( option == "--sparse_pivot_column" ) representation = SPARSE_PIVOT_COLUMN;
        else if( option == "--heap_pivot_column" ) representation = HEAP_PIVOT_COLUMN;
        else if( option == "--standard" ) algorithm = STANDARD;
        else if( option == "--twist" ) algorithm = TWIST;
        else if( option == "--row" ) algorithm = ROW;
        else if( option == "--chunk" ) algorithm = CHUNK;
        else if( option == "--chunk_sequential" ) algorithm = CHUNK_SEQUENTIAL;
        else if( option == "--spectral_sequence" ) algorithm = SPECTRAL_SEQUENCE;
        else if( option == "--verbose" ) verbose = true;
        else if( option == "--help" ) print_help_and_exit();
        else print_help_and_exit();
    }
}
Example #4
0
int main(int argc, char *argv[])
{
	// Parsing args
	if(argc < 2 || argc > 3)
		print_help_and_exit(argv);
	int result, vid, pid;
	result = sscanf(argv[1], "%x:%x", &vid, &pid);
	if(!result)
		print_help_and_exit(argv);
	out = NULL;
	if(argc > 2) {
		// Opening log file
		out = fopen ( argv[2], "w" );
		if(!out) {
			perror("Couldn't open log");
			exit(-1);
		}
		setvbuf(out, NULL, _IONBF, 0);
	}

	// Dealing with libusb
	libusb_device_handle *dev_handle;
	libusb_context *ctx;
	result = libusb_init(&ctx); // Obtain libusb_context
	assert(result >= 0);
	libusb_set_debug(ctx, 3);
	libusb_device *usbdev = find_usb_device(ctx, vid, pid);
	assert(usbdev);
	bus_number = libusb_get_bus_number(usbdev); // Which bus to sniff
	device_number = libusb_get_device_address(usbdev); // Filter
	fprintf(stderr, "bus_number=%d, device_number=%d\n", bus_number, device_number);

	char pcap_if_name[10];
	#ifdef LINUX
		system("modprobe usbmon");
		sprintf(pcap_if_name, "usbmon%d", bus_number);
	#else 
		#error "Unsupported platform"
	#endif

	printf("pcap device: %s\n", pcap_if_name);
	pcap_t *handle = pcap_open_live(pcap_if_name, BUFSIZ, 1, 1000, errbuf);
	if (handle == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", pcap_if_name, errbuf);
		#ifdef LINUX
		fprintf(stderr, "Please check for modules list.\n");
		#endif
		return(2);
	}
	pcap_loop(handle, -1, process_packet, NULL);
	printf("exit\n");
	pcap_close(handle);
	if(out)
		fclose(out);
}
Example #5
0
Options::Options(int argc, char *argv[])
    : m_options()
    , m_log(LOG_TOPIC)
    , m_port(OPTION_PORT.default_value)
{
    namespace po = boost::program_options;

    po::options_description generic_options("Generic options");
    generic_options.add_options()
        (OPTION_PORT.name().c_str(),
         po::value<uint16_t>()->default_value(OPTION_PORT.default_value),
         OPTION_PORT.description);

    po::options_description command_line_options("Command line options");
    command_line_options.add_options()
        (OPTION_HELP.name().c_str(), OPTION_HELP.description)
        (OPTION_CONFIG.name().c_str(), po::value<std::string>(), OPTION_CONFIG.description);
    command_line_options.add(generic_options);

    try {
        po::store(po::parse_command_line(argc, argv, command_line_options), m_options);

        if (m_options.count(OPTION_HELP.long_opt)) {
            print_help_and_exit(command_line_options, false);
        }

        if (m_options.count(OPTION_CONFIG.long_opt)) {
            auto config_filename = m_options[OPTION_CONFIG.long_opt].as<std::string>();
            m_log.info("Loading config from file: {}", config_filename);
            std::ifstream config_file(config_filename);
            if (!config_file) {
                m_log.error("Could not open config file: {}", config_filename);
                throw std::runtime_error("Could not open file.");
            }
            po::store(po::parse_config_file(config_file, generic_options), m_options);
        }

        po::notify(m_options);

        m_port = m_options[OPTION_PORT.long_opt].as<uint16_t>();
        m_log.info("Port: {}", m_port);
    }
    catch(const po::unknown_option &e) {
        std::cerr << "Unknown option: " << e.get_option_name() << std::endl;
        print_help_and_exit(command_line_options);
    }
    catch(std::exception &e) {
        std::cerr << "Error: " << e.what() << std::endl;
        print_help_and_exit(command_line_options);
    }
}
Example #6
0
File: chat.c Project: rahpaere/tcpr
static void handle_options(int argc, char **argv)
{
    for (;;)
        switch (getopt(argc, argv, "b:c:t:B:Cdg:v?")) {
        case 'b':
            bind_address = optarg;
            break;
        case 'c':
            connect_address = optarg;
            break;
        case 't':
            tcpr_address = optarg;
            break;
        case 'B':
            buffer_size = atoi(optarg);
        case 'C':
            checkpointing = 0;
            break;
        case 'd':
            discard = 1;
            break;
        case 'g':
            generate = atoi(optarg);
            user_eof = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        case -1:
            return;
        default:
            print_help_and_exit(argv[0]);
        }
}
Example #7
0
void parse_command_line( int argc, char** argv, bool& use_binary, std::vector< std::string >& input_filenames ) {

    if( argc < 2 ) print_help_and_exit();

    int number_of_options = 0;
    for( int idx = 1; idx < argc; idx++ ) {
        const std::string argument = argv[ idx ];
        if( argument.size() > 2 && argument[ 0 ] == '-' && argument[ 1 ] == '-' ) {
            if( argument == "--ascii" ) use_binary = false;
            else if( argument == "--binary" ) use_binary = true;
            else if( argument == "--help" ) print_help_and_exit();
            else print_help_and_exit();
        } else {
            input_filenames.push_back( argument );
        }
    }
}
Example #8
0
int main(int argc, char *args[])
{
    int i = 0;
    std::unique_ptr<Command> command;

    printf("Lite3d scene objests conversion utility.\n");
    printf("Conversion from formats supports by Assimp to internal lite3d format (m).\n");
    printf("Engine version %s\n\n", LITE3D_VERSION_STRING);

    if (argc < 3)
        print_help_and_exit();

    for (i = 1; i < argc; ++i)
    {
        if (strcmp(args[i], "-p") == 0)
        {
            command.reset(new MeshInfoCommand());
            break;
        }
        else if (strcmp(args[i], "-c") == 0)
        {
            command.reset(new ConverterCommand());
            break;
        }
        else if (strcmp(args[i], "-d") == 0)
        {
            command.reset(new CreateDirsCommand());
            break;
        }
    }

    if (!command)
        print_help_and_exit();

    try
    {
        command->run(argc, args);
    }
    catch(std::exception &ex)
    {
        std::cerr << "Error: " << ex.what() << std::endl;
        print_help_and_exit();
    }

    return 0;
}
Example #9
0
/* Unless ISL_ARG_SKIP_HELP is set, check if "arg" is
 * equal to "--help" and if so call print_help_and_exit.
 */
static void check_help(struct isl_args *args, char *arg, char *prog, void *opt,
	unsigned flags)
{
	if (ISL_FL_ISSET(flags, ISL_ARG_SKIP_HELP))
		return;

	if (strcmp(arg, "--help") == 0)
		print_help_and_exit(args->args, prog, opt);
}
Example #10
0
int main(int argc, char **argv) {
	if(argc != 2)
		print_help_and_exit(argv);
	int result, vid, pid;
	result = sscanf(argv[1], "%x:%x", &vid, &pid);
	assert(result);
	usb_init(vid, pid);
	libusb_close(dev_handle);
}
Example #11
0
void compute_pairing( std::string input_filename, std::string output_filename, bool use_binary, bool verbose, bool dualize ) {

    phat::boundary_matrix< Representation > matrix;
    bool read_successful;

    double read_timer = omp_get_wtime();
    if( use_binary ) {
        LOG( "Reading input file " << input_filename << " in binary mode" )
        read_successful = matrix.load_binary( input_filename );
    } else {
        LOG( "Reading input file " << input_filename << " in ascii mode" )
        read_successful = matrix.load_ascii( input_filename );
    }
    double read_time = omp_get_wtime() - read_timer;
    double read_time_rounded = floor( read_time * 10.0 + 0.5 ) / 10.0;
    LOG( "Reading input file took " << std::setiosflags( std::ios::fixed ) << std::setiosflags( std::ios::showpoint ) << std::setprecision( 1 ) << read_time_rounded <<"s" )

    if( !read_successful ) {
        std::cerr << "Error opening file " << input_filename << std::endl;
        print_help_and_exit();
    }
    
    phat::index num_cols = matrix.get_num_cols();

    if( dualize ) {
        double dualize_timer = omp_get_wtime();
        LOG( "Dualizing ..." )
        phat::dualize ( matrix );
        double dualize_time = omp_get_wtime() - dualize_timer;
        double dualize_time_rounded = floor( dualize_time * 10.0 + 0.5 ) / 10.0;
        LOG( "Dualizing took " << std::setiosflags( std::ios::fixed ) << std::setiosflags( std::ios::showpoint ) << std::setprecision( 1 ) << dualize_time_rounded <<"s" )
    }
        
    double pairs_timer = omp_get_wtime();
    phat::persistence_pairs pairs;
    LOG( "Computing persistence pairs ..." )
    phat::compute_persistence_pairs < Algorithm > ( pairs, matrix );
    double pairs_time = omp_get_wtime() - pairs_timer;
    double pairs_time_rounded = floor( pairs_time * 10.0 + 0.5 ) / 10.0;
    LOG( "Computing persistence pairs took " << std::setiosflags( std::ios::fixed ) << std::setiosflags( std::ios::showpoint ) << std::setprecision( 1 ) << pairs_time_rounded <<"s" )
    
    if( dualize ) dualize_persistence_pairs( pairs, num_cols );
    

    double write_timer = omp_get_wtime();
    if( use_binary ) {
        LOG( "Writing output file " << output_filename << " in binary mode ..." )
        pairs.save_binary( output_filename );
    } else {
        LOG( "Writing output file " << output_filename << " in ascii mode ..." )
        pairs.save_ascii( output_filename );
    }
    double write_time = omp_get_wtime() - write_timer;
    double write_time_rounded = floor( write_time * 10.0 + 0.5 ) / 10.0;
    LOG( "Writing output file took " << std::setiosflags( std::ios::fixed ) << std::setiosflags( std::ios::showpoint ) << std::setprecision( 1 ) << write_time_rounded <<"s" )
}
Example #12
0
void parse_command_line( int argc, char** argv, bool& use_binary, bool& use_save_binary, bool& use_dualize, std::string& input_filename, std::string& output_filename) {

    if( argc < 3 ) print_help_and_exit();

    input_filename = argv[ argc - 2 ];
    output_filename = argv[ argc - 1 ];

    for( int idx = 1; idx < argc - 2; idx++ ) {
        const std::string option = argv[ idx ];

        if( option == "--dualize" ) use_dualize = true;
        else if( option == "--ascii" ) use_binary = false;
        else if( option == "--binary" ) use_binary = true;
        else if( option == "--save-ascii" ) use_save_binary = false;
        else if( option == "--save-binary" ) use_save_binary = true;
        else if( option == "--help" ) print_help_and_exit();
        else print_help_and_exit();
    }
}
int main(int argc, char *argv[]){
  if(argc != 8){
    fprintf(stderr, "Error: not enough arguments\n");
    print_help_and_exit(argv);
  }
  else {
    int a_start, a_stop, b_start, b_stop, c_start, c_stop, A_start, A_stop;
    int m_a_start, m_a_stop, m_b_start, m_b_stop, m_c_start, m_c_stop;
      if(
	 sscanf(argv[1], "%d-%d", &a_start, &a_stop) == 2 &&
	 sscanf(argv[2], "%d-%d", &b_start, &b_stop) == 2 &&
	 sscanf(argv[3], "%d-%d", &c_start, &c_stop) == 2 &&
	 sscanf(argv[4], "%d-%d", &A_start, &A_stop) == 2 &&
	 sscanf(argv[5], "%d-%d", &m_a_start, &m_a_stop) == 2 &&
	 sscanf(argv[6], "%d-%d", &m_b_start, &m_b_stop) == 2 &&
	 sscanf(argv[7], "%d-%d", &m_c_start, &m_c_stop) == 2){
	if(a_start >= 0 && a_stop > a_start &&
	   b_start >= 0 && b_stop > b_start &&
	   c_start >= 0 && c_stop > c_start &&
	   A_start >= 0 && A_stop > A_start &&
	   m_a_start >= 0 && m_a_stop > m_a_start &&
	   m_b_start >= 0 && m_b_stop > m_b_start &&
	   m_c_start >= 0 && m_c_stop > m_c_start){
	  start_sieve(a_start, a_stop, b_start, b_stop, c_start, c_stop, A_start, A_stop,
		      m_a_start, m_a_stop, m_b_start, m_b_stop, m_c_start, m_c_stop);
	}
	else {
	  fprintf(stderr, "Error: invalid values for ranges.\n");
	  print_help_and_exit(argv);
	}
    }
    else {
      fprintf(stderr, "Error: invalid range format\n");
      print_help_and_exit(argv);
    }
  }
  return 0;
}
Example #14
0
int main( int argc, char** argv )
{
    bool use_binary = true; // interpret inputs as binary or ascii files
    std::vector< std::string > input_filenames; // name of file that contains the boundary matrix

    parse_command_line( argc, argv, use_binary, input_filenames );

    for( int idx_input = 0; idx_input < input_filenames.size(); idx_input++ ) {
        std::string input_filename = input_filenames[ idx_input ];
        phat::boundary_matrix<> matrix;
        bool read_successful = use_binary ? matrix.load_binary( input_filename ) : matrix.load_ascii( input_filename );
        if( !read_successful ) {
            std::cerr << std::endl << " Error opening file " << input_filename << std::endl;
            print_help_and_exit();
        }

        std::cout << input_filename << ":" << std::endl;
        std::cout << "\t" << "num_cols = " << matrix.get_num_cols() << std::endl;
        std::cout << "\t" << "max_dim = " << (int)matrix.get_max_dim() << std::endl;
        std::cout << "\t" << "max_col_entries = " << matrix.get_max_col_entries() << std::endl;
        std::cout << "\t" << "max_row_entries = " << matrix.get_max_row_entries() << std::endl;
        std::cout << "\t" << "total_nr_of_entries = " << matrix.get_num_entries() << std::endl;
    }
}
int main(int argc, char* argv[]) {
	int opt;
	uint64_t c = DEFAULT_C;
	uint64_t b = DEFAULT_B;
	uint64_t s = DEFAULT_S;
	uint64_t v = DEFAULT_V;
	uint64_t k = DEFAULT_K;
	FILE* fin  = stdin;

	/* Read arguments */ 
	while(-1 != (opt = getopt(argc, argv, "c:b:s:i:v:k:h"))) {
		switch(opt) {
		case 'c':
			c = atoi(optarg);
			break;
		case 'b':
			b = atoi(optarg);
			break;
		case 's':
			s = atoi(optarg);
			break;
		case 'v':
			v = atoi(optarg);
			break;
		case 'k':
			k = atoi(optarg);
			break;
		case 'i':
			fin = fopen(optarg, "r");
			break;
		case 'h':
			/* Fall through */
		default:
			print_help_and_exit();
			break;
		}
	}

	printf("Cache Settings\n");
	printf("C: %" PRIu64 "\n", c);
	printf("B: %" PRIu64 "\n", b);
	printf("S: %" PRIu64 "\n", s);
	printf("V: %" PRIu64 "\n", v);
	printf("K: %" PRIu64 "\n", k);
	printf("\n");

	/* Setup the cache */
	setup_cache(c, b, s, v, k);

	/* Setup statistics */
	cache_stats_t stats;
	memset(&stats, 0, sizeof(cache_stats_t));

	/* Begin reading the file */ 
	char rw;
	uint64_t address;
	while (!feof(fin)) { 
		int ret = fscanf(fin, "%c %" PRIx64 "\n", &rw, &address); 
		if(ret == 2) {
			cache_access(rw, address, &stats); 
		}
	}

	complete_cache(&stats);

	print_statistics(&stats);

	return 0;
}
Example #16
0
int main(int argc, char **argv) {
  int opts = global_options(&argc, &argv);
  int data_len;

#ifdef HAVE_LIBPAPI
  int papi_counters = PAPI_num_counters();
  if (papi_counters < papi_array_len) {
    fprintf(stderr, "%s: Warning: there are only %d hardware counters available!\n", progname, papi_counters);
    papi_array_len = papi_counters;
  }
  if (papi_test(papi_events, papi_array_len))
    exit(1);

  for (int nv = 0; nv <= papi_array_len; ++nv)
    loop_calibration[nv] = 100000000;

  data_len = papi_array_len + 1;
#else
  data_len = 2;
#endif
  if (opts < 0 || argc < 2 || argc > 5) {
    print_help_and_exit();
  }

  struct elim_params params;
  params.m = atoi(argv[1]);
  if (argc >= 3)
    params.n = atoi(argv[2]);
  else
    params.n = params.m;

  if (argc >= 4)
    params.algorithm = argv[3];
  else
    params.algorithm = "ple";
  if (argc >= 5)
    params.r = atoi(argv[4]);
  else
    params.r = MIN(params.m, params.n);

  srandom(17);
  unsigned long long data[16];

  for (int i = 0; i < 4; ++i)
    run_nothing((void*)&params, data, &data_len);

  run_bench(run, (void*)&params, data, data_len);

  double cc_per_op = ((double)data[1])/ ( (double)params.m * (double)params.n * powl((double)params.r,0.807) );

  printf("m: %5d, n: %5d, last r: %5d, cpu cycles: %12llu, cc/(mnr^0.807): %.5lf, ", params.m, params.n, params.r, data[1], cc_per_op);
  print_wall_time(data[0] / 1000000.0);
  printf(", ");
  print_cpu_time(data[1] / (double)cpucycles_persecond());
  printf("\n");
#ifdef HAVE_LIBPAPI
  for (int n = 1; n < data_len; ++n) {
    double tmp = ((double)data[n]) / powl((double)params.n,2.807);
    printf("%20s (%20llu) per bit (divided by n^2.807): %15.5f\n", papi_event_name(papi_events[n - 1]), data[n], tmp);
  }
#endif
}
Example #17
0
int main(int argc , char ** argv) {
  install_SIGNALS();
  {
    bool           report_only     = false;
    bool           list_mode       = false;
    bool           include_restart = true;
    bool           print_header    = true;
    int            arg_offset      = 1;

#ifdef ERT_HAVE_GETOPT
    if (argc == 1)
      print_help_and_exit();
    else {

      static struct option long_options[] = {
        {"no-restart"  , 0 , 0 , 'n'} ,
        {"list"        , 0 , 0 , 'l'} ,
        {"report-only" , 0 , 0 , 'r'} ,
        {"no-header"   , 0 , 0 , 'x'} ,
        {"help"        , 0 , 0 , 'h'} ,
        { 0            , 0 , 0 ,   0} };

      while (1) {
        int c;
        int option_index = 0;

        c = getopt_long (argc, argv, "nlRrx", long_options, &option_index);
        if (c == -1)
          break;

        switch (c) {
        case 'n':
          include_restart = false;
          break;
        case 'r':
          report_only = true;
          break;
        case 'l':
          list_mode = true;
          break;
        case 'x':
          print_header = false;
          break;
        case 'h':
          print_help_and_exit();
          break;
        case '?':
          printf("Hmmm - unrecognized option???");
          break;
        }
      }
      arg_offset = optind;  /* External static variable in the getopt scope*/
    }
#endif

    if (arg_offset >= argc)
      print_help_and_exit();

    {
      char         * data_file = argv[arg_offset];
      ecl_sum_type * ecl_sum;
      int            num_keys  = argc - arg_offset - 1;
      const char  ** arg_list  = (const char **) &argv[arg_offset + 1];


      ecl_sum = ecl_sum_fread_alloc_case__( data_file , ":" , include_restart);
      /** If no keys have been presented the function will list available keys. */
      if (num_keys == 0)
        list_mode = true;

      if (ecl_sum != NULL) {
        if (list_mode) {
          /*
             The program is called in list mode, we only print the
             (matching) keys in a table on stdout. If no arguments
             have been given on the commandline, all internalized keys
             will be printed.
          */

          stringlist_type * keys = stringlist_alloc_new();
          if (num_keys == 0) {
            ecl_sum_select_matching_general_var_list( ecl_sum , "*" , keys);
            stringlist_sort(keys , NULL );
          } else
            build_key_list( ecl_sum , keys , num_keys , arg_list);

          {
            int columns = 5;
            int i;
            for (i=0; i< stringlist_get_size( keys );  i++) {
              printf("%-24s ",stringlist_iget( keys , i ));
              if ((i % columns) == 4)
                printf("\n");
            }
            printf("\n");
          }
          stringlist_free( keys );
        } else {
          /* Normal operation print results for the various keys on stdout. */
          ecl_sum_fmt_type fmt;
          stringlist_type * key_list = stringlist_alloc_new( );
          build_key_list( ecl_sum , key_list , num_keys , arg_list);

          if (print_header)
            ecl_sum_fmt_init_summary_x(ecl_sum , &fmt );
          else
            fmt.print_header = false;

          ecl_sum_fprintf(ecl_sum , stdout , key_list , report_only , &fmt);

          stringlist_free( key_list );
        }
        ecl_sum_free(ecl_sum);
      } else
        fprintf(stderr,"summary.x: No summary data found for case:%s\n", data_file );
    }
  }
}
Example #18
0
int main(int argc, char* argv[]) {
    int opt;
    uint64_t c = DEFAULT_C;
    uint64_t b = DEFAULT_B;
    uint64_t s = DEFAULT_S;
    char f     = DEFAULT_F;
    char r     = DEFAULT_R;

    /* Read arguments */
    while(-1 != (opt = getopt(argc, argv, "c:b:s:f:r:h"))) {
        switch(opt) {
        case 'c':
            c = atoi(optarg);
            break;
        case 'b':
            b = atoi(optarg);
            break;
        case 's':
            s = atoi(optarg);
            break;
        case 'f':
            if(optarg[0] == BLOCKING || optarg[0] == EAGER) {
                f = optarg[0];
            }
            break;
        case 'r':
            if(optarg[0] == LRU || optarg[0] == NMRU_FIFO) {
                r = optarg[0];
            }
            break;
        case 'h':
            /* Fall through */
        default:
            print_help_and_exit();
            break;
        }
    }

    printf("Cache Settings\n");
    printf("C: %llu\n", c);
    printf("B: %llu\n", b);
    printf("S: %llu\n", s);
    printf("F: %s\n", f == BLOCKING ? "BLOCKING" : "EAGER");
    printf("R: %s\n", r == LRU ? "LRU" : "NMRU_FIFO");
    printf("\n");

    /* Setup the cache */
    setup_cache(c, b, s, f, r);

    /* Setup statistics */
    cache_stats_t stats;
    memset(&stats, 0, sizeof(cache_stats_t));

    /* Begin reading the file */
    char rw;
    uint64_t address;
    while (!feof(stdin)) {
        int ret = fscanf(stdin, "%c %llx\n", &rw, &address);
        if(ret == 2) {
            cache_access(rw, address, &stats);
        }
    }

    complete_cache(&stats);

    print_statistics(&stats);

    return 0;
}
int main(int argc, char* argv[]) {
    int opt;
    uint64_t c = DEFAULT_C;
    uint64_t b = DEFAULT_B;
    uint64_t s = DEFAULT_S;
    uint64_t v = DEFAULT_V;
    char st    = DEFAULT_ST;
    char r     = DEFAULT_R;
    FILE* fin  = stdin;

    /* Read arguments */ 
    while(-1 != (opt = getopt(argc, argv, "c:b:s:t:i:v:r:h"))) {
        switch(opt) {
        case 'c':
            c = atoi(optarg);
            break;
        case 'b':
            b = atoi(optarg);
            break;
        case 's':
            s = atoi(optarg);
            break;
        case 't':
            if(optarg[0] == BLOCKING || optarg[0] == SUBBLOCKING) {
                st = optarg[0];
            }
            break;
        case 'v':
            v = atoi(optarg);
            break;
        case 'r':
            if(optarg[0] == LRU || optarg[0] == NMRU_FIFO) {
                r = optarg[0];
            }
            break;
        case 'i':
            fin = fopen(optarg, "r");
            break;
        case 'h':
            /* Fall through */
        default:
            print_help_and_exit();
            break;
        }
    }

    printf("Cache Settings\n");
    printf("C: %" PRIu64 "\n", c);
    printf("B: %" PRIu64 "\n", b);
    printf("S: %" PRIu64 "\n", s);
    printf("V: %" PRIu64 "\n", v);
    printf("F: %s\n", st == BLOCKING ? "BLOCKING" : "SUBBLOCKING");
    printf("R: %s\n", r == LRU ? "LRU" : "NMRU_FIFO");
    printf("\n");

    /* Setup the cache */
    setup_cache(c, b, s, v, st, r);

    /* Setup statistics */
    cache_stats_t stats;
    memset(&stats, 0, sizeof(cache_stats_t));

    /* Begin reading the file */ 
    char rw;
    uint64_t address;
    while (!feof(fin)) { 
        int ret = fscanf(fin, "%c %" PRIx64 "\n", &rw, &address); 
        if(ret == 2) {
            cache_access(rw, address, &stats); 
        }
    }

    complete_cache(&stats);

    print_statistics(&stats);

    return 0;
}
int main(int argc, char* argv[]) {
	int opt;
	uint64_t c = DEFAULT_C;
	uint64_t b = DEFAULT_B;
	uint64_t s = DEFAULT_S;
	uint64_t v = DEFAULT_V;
	uint64_t k = DEFAULT_K;
	FILE* fin  = stdin;
	FILE* fout = stdout;
	char inputfile[100];
	char outputfile[100];

	/* Read arguments */ 
	while(-1 != (opt = getopt(argc, argv, "c:b:s:i:v:k:h"))) {
		switch(opt) {
		case 'i':
			strcpy(inputfile, optarg);
			strcpy(outputfile, optarg);
			strcat(outputfile, ".out");
			break;
		case 'c':
			c = atoi(optarg);
			break;
		case 'b':
			b = atoi(optarg);
			break;
		case 's':
			s = atoi(optarg);
			break;
		case 'v':
			v = atoi(optarg);
			break;
		case 'k':
			k = atoi(optarg);
			break;
		case 'h':
			/* Fall through */
		default:
			print_help_and_exit();
			break;
		}
	}

	fout = fopen(outputfile, "w");
	fprintf(fout, "%s:\n\n", inputfile);

	double AAT_min = AAT_MAX;
	uint64_t AAT_min_c = DEFAULT_C;
	uint64_t AAT_min_b = DEFAULT_B;
	uint64_t AAT_min_s = DEFAULT_S;
	uint64_t AAT_min_v = DEFAULT_V;
	uint64_t AAT_min_k = DEFAULT_K;

	for (c = 12; c <= 15; ++c) {
		for (b = 3; b <= 6; ++b) {
			for (s = 0; s <= c - b; ++s) {
//				for (v = 0; v <= 4; ++v) {
//					for (k = 0; k <= 4; ++k) {

						printf("%" PRIu64 "\t%" PRIu64 "\t%" PRIu64 "\t%" PRIu64 "\t%" PRIu64 "\t", c, b, s, v, k);
						fprintf(fout, "%" PRIu64 "\t%" PRIu64 "\t%" PRIu64 "\t%" PRIu64 "\t%" PRIu64 "\t", c, b, s, v, k);

						/* calculate memory budge */
						uint64_t data_storage = (1 << b) * 8;
						//	printf("data storage: %" PRIu64 "\n", data_storage);
						uint64_t cache_memory = (1 << (c - b)) * (64 - c + s + 1 + data_storage);
						//	printf("cache memory: %" PRIu64 "\n", cache_memory);
						uint64_t vc_memory = v * (64 - b + 1 + data_storage);
						//	printf("vc memory: %" PRIu64 "\n", vc_memory);
						double total_memory_kb = (cache_memory + vc_memory) / double((1 << 10) * 8);
						printf("%f\t", total_memory_kb);
						fprintf(fout, "%f\t", total_memory_kb);

						/* skip if memory limitation exceeded */
						if (total_memory_kb > 48) {
							printf("\n");
							fprintf(fout, "\n");
							continue;
						}

						/* Setup the cache */
						setup_cache(c, b, s, v, k);

						/* Setup statistics */
						cache_stats_t stats;
						memset(&stats, 0, sizeof(cache_stats_t));

						/* Begin reading the file */
						fin = fopen(inputfile, "r");
						char rw;
						uint64_t address;
						while (!feof(fin)) {
							int ret = fscanf(fin, "%c %" PRIx64 "\n", &rw, &address);
							if (ret == 2) {
								cache_access(rw, address, &stats);
							}
						}
						fclose(fin);

						complete_cache(&stats);

						printf("%f\n", stats.avg_access_time);
						fprintf(fout, "%f\n", stats.avg_access_time);

						// update optimal setting
						if (stats.avg_access_time < AAT_min) {
							AAT_min = stats.avg_access_time;
							AAT_min_c = c;
							AAT_min_b = b;
							AAT_min_s = s;
							AAT_min_v = v;
							AAT_min_k = k;
						}

//					}
//				}
			}
		}
	}

	printf("\nBest AAT: %f\n", AAT_min);
	fprintf(fout, "\nBest AAT: %f\n", AAT_min);
	printf("Setting: %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "\n",
		AAT_min_c, AAT_min_b, AAT_min_s, AAT_min_v, AAT_min_k);
	fprintf(fout, "Setting: %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 "\n",
		AAT_min_c, AAT_min_b, AAT_min_s, AAT_min_v, AAT_min_k);
	fclose(fout);

	return 0;
}
Example #21
0
int main(int argc, char **argv) {
	char *s = NULL, *t;
	int n = 1, k = 2, b = 0;
	struct rusage r1, r2;
	struct timeval t1, t2;
	struct timeval tv;
	double u1;
	unsigned long seed;
	int i, l;

	gettimeofday(&tv, NULL);
	seed = (unsigned long) tv.tv_sec;

	for (i = 1; i < argc; i++)
		if (!strcmp(argv[i], "-s")) {
			if (i + 1 < argc && argv[i + 1][0] != '-')
				s = argv[++i];
			else
				print_help_and_exit();
		} else if (!strcmp(argv[i], "-n")) {
			if (i + 1 < argc && argv[i + 1][0] != '-')
				n = atoi(argv[++i]);
			else
				print_help_and_exit();
		} else if (!strcmp(argv[i], "-k")) {
			if (i + 1 < argc && argv[i + 1][0] != '-')
				k = atoi(argv[++i]);
			else
				print_help_and_exit();
		} else if (!strcmp(argv[i], "-seed")) {
			if (i + 1 < argc && argv[i + 1][0] != '-')
				seed = atoi(argv[++i]);
			else
				print_help_and_exit();
		} else if (!strcmp(argv[i], "-b"))
			b = 1;
	if (n <= 0 || s == NULL)
		print_help_and_exit();

	l = strlen(s);
	if ((t = malloc(l + 1)) == NULL) {
		fprintf(stderr, "malloc failed\n");
		exit(1);
	}
	t[l] = '\0';
	srandom(seed);
	set_randfunc((randfunc_t) random);
	if (b)
		getrusage(RUSAGE_SELF, &r1);
	shuffle1(s, l, k);
	for (i = 0; i < n; i++) {
		shuffle2(t);
		if (!b)
			printf("%s\n", t);
	}
	if (b) {
		getrusage(RUSAGE_SELF, &r2);
		t1 = r1.ru_utime;
		t2 = r2.ru_utime;
		u1 = (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) * 0.001;
		printf("%g\n", u1);				/* time in msec */
	}
	return 0;
}
Example #22
0
int main(int argc, char *argv[])
{
    if(debug)
        printf("IN: main:main()\n");

    int opt;
    char* d = DEFAULT_D;
    int p = DEFAULT_P;
    int r = DEFAULT_R;
    int s = DEFAULT_S;
    int f = DEFAULT_F;
    double t = DEFAULT_T;
    double w = DEFAULT_W;
    char a = DEFAULT_A;
    char c = DEFAULT_C;

    /* Read arguments */ 
    while(-1 != (opt = getopt(argc, argv, "d:p:r:s:cf:at:w:h"))) {
        switch(opt) {
        case 'd':
            d = optarg;
            break;
        case 'p':
            p = atoi(optarg);
            break;
        case 'r':
            r = atoi(optarg);
            break;
        case 's':
            s = atoi(optarg);
            break;
        case 'f':
            f = atoi(optarg);
            break;
        case 'c':
            c = 0;
            break;
        case 'a':
            a = 1;
            break;
        case 't':
            t = atof(optarg);
            break;
        case 'w':
            w = atof(optarg);
            break;
        case 'h':
            /* Fall through */
        default:
            print_help_and_exit();
            break;
        }
    }

    printf("Source Settings\n");
    printf("d: %s\n", d);
    printf("p: %d\n", p);
    printf("r: %d\n", r);
    printf("s: %d\n", s);
    printf("c: %s\n", c?"Left Channel":"Right Channel");
    printf("f: %d\n", f);
    printf("a: %s\n", a?"Off":"On");
    printf("t: %.3f\n", t);
    printf("w: %.3f\n", w);
    printf("\n");

    int sockfd, portno, n, newsockfd;
    struct sockaddr_in serv_addr, cli_addr;
    socklen_t clilen;
    // portno = 51717;
    portno = p;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
       err("ERROR opening socket");
    //server = gethostbyname(argv[1]);
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
               err("ERROR on binding");
	printf("Listening for connections..\n");
    listen(sockfd,5);
    clilen = sizeof(cli_addr);
        
	printf("Accepting connection..\n");
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
	printf("Accepted a connection..\n");
    if (newsockfd < 0)
            err("ERROR on accept");
    else 
        start_audio(newsockfd, d, r, s, f, a, t, w, c);


}
Example #23
0
/*
 *  ======== main ========
 */
int main(int argc, char * argv[])
{
    int status = 0;
    struct stat st;
    u32 size = 0;
    int i, j, o;
    char *elf_files[] = {NULL, NULL, NULL};
    int num_files = sizeof(elf_files) / sizeof(elf_files[0]);
    char *tokenstr;

    printf("###############################################################\n");
    printf("                     GENCMBELF : %s    \n", VERSION);
    printf("###############################################################\n");

    /* process arguments */
    while ((o = getopt (argc, argv, ":s:a:o:")) != -1) {
        switch (o) {
            case 's':
                elf_files[0] = optarg;
                break;
            case 'a':
                elf_files[1] = optarg;
                break;
            case 'o':
                elf_files[2] = optarg;
                break;
            case ':':
                status = -1;
                printf("Option -%c requires an operand\n", optopt);
                break;
            case '?':
                status = -1;
                printf("Unrecognized option: -%c\n", optopt);
                break;
        }
    }

    for (i = 0, j = optind; j < argc; j++) {
        while (i < num_files && elf_files[i]) {
            i++;
        }
        if (strstr(argv[j], ".xem3")) {
            if (i == num_files) {
                print_help_and_exit();
            }
            elf_files[i++] = argv[j];
        }
        else {
            if (num_tags == MAX_TAGS) {
                print_help_and_exit();
            }
            tag_name[num_tags] = strtok(argv[j], ":");
            tokenstr = strtok(NULL, ":");
            if (!tokenstr) {
                print_help_and_exit();
            }
            tag_addr[num_tags] = strtoll(tokenstr, NULL, 16);
            tokenstr = strtok(NULL, ":");
            if (!tokenstr) {
                print_help_and_exit();
            }
            tag_size[num_tags] = strtoll(tokenstr, NULL, 16);

            DEBUG_PRINT("found tag %d: name '%s' addr 0x%x size %d\n", num_tags,
                    tag_name[num_tags], tag_addr[num_tags], tag_size[num_tags]);
            num_tags++;
        }
    }

    if (status || !elf_files[0] || !elf_files[1] || !elf_files[2]) {
        print_help_and_exit();
    }

    if ((!strcmp(elf_files[0], elf_files[1])) ||
        (!strcmp(elf_files[0], elf_files[2])) ||
        (!strcmp(elf_files[1], elf_files[2]))) {
        print_help_and_exit();
    }

    DEBUG_PRINT("\nCore0 File: %s, Core1 File: %s, Output File: %s\n",
                                    elf_files[0], elf_files[1], elf_files[2]);
    status = prepare_file(elf_files[0], INPUT_FILE, &core0_info);
    if (status) {
        printf("\nError preparing file: %s\n", elf_files[0]);
        goto finish0;
    }

    status = prepare_file(elf_files[1], INPUT_FILE, &core1_info);
    if (status) {
        printf("\nError preparing file: %s\n", elf_files[1]);
        goto finish1;
    }

    status = prepare_file(elf_files[2], OUTPUT_FILE, &cores_info);
    if (status) {
        printf("\nError preparing file: %s\n", elf_files[2]);
        goto done;
    }

    status = process_image();
    if (status) {
        printf("\nError generating output file: %s\n", elf_files[2]);
        goto done;
    }
    rewind(cores_info.fp);
    fstat(fileno(cores_info.fp), &st);
    size = st.st_size;

done:
    fclose(cores_info.fp);
    if (cores_info.data) {
        free(cores_info.data);
    }
    cores_info.fp = NULL;
    cores_info.data = NULL;
finish1:
    printf("\nFinalizing input ELF file: %s of size: %d\n", elf_files[1],
                core1_info.size);
    finalize_file(&core1_info, status);
    status = 0;
finish0:
    printf("Finalizing input ELF file: %s of size: %d\n", elf_files[0],
                core0_info.size);
    finalize_file(&core0_info, status);

    if (size) {
        printf("\nProcessed Output ELF file: %s of size: %d\n\n", elf_files[2],
                        size);
    }

    return status;
}
Example #24
0
int main(int argc, char* argv[]) {
    int opt;
    int f = DEFAULT_F;
    int m = DEFAULT_M;
    int k0 = DEFAULT_K0;
    int k1 = DEFAULT_K1;
    int k2 = DEFAULT_K2;
    int d = DEFAULT_D;

    /* Read arguments */ 
    while(-1 != (opt = getopt(argc, argv, "d:i:j:k:l:f:m:h"))) {
        switch(opt) {
        case 'd':
            d = atoi(optarg);
            break;
        case 'j':
            k0 = atoi(optarg);
            break;
        case 'k':
            k1 = atoi(optarg);
            break;
        case 'l':
            k2 = atoi(optarg);
            break;
        case 'm':
            m = atoi(optarg);
            break;
        case 'f':
            f = atoi(optarg);
            break;
        case 'i':
            inFile = fopen(optarg, "r");
            if (inFile == NULL)
            {
                fprintf(stderr, "Failed to open %s for reading\n", optarg);
                print_help_and_exit();
            }
            break;
        case 'h':
            /* Fall through */
        default:
            print_help_and_exit();
            break;
        }
    }

    dout("Processor Settings\n");
    dout("D: %i\n", d);
    dout("k0: %i\n", k0);
    dout("k1: %i\n", k1);
    dout("k2: %i\n", k2);
    dout("F: %i\n", f);
    dout("M: %i\n", m);
    dout("\n");

    /* Setup the processor */
    setup_proc(inFile, d, k0, k1, k2, f, m);

    /* Setup statistics */
    proc_stats_t stats;
    memset(&stats, 0, sizeof(proc_stats_t));

    /* Run the processor */
    run_proc(&stats);

    /* Finalize stats */
    complete_proc(&stats);

    print_statistics(&stats);

    return 0;
}
Example #25
0
static void
decode_options (int argc, char **argv)
{
  alternate_editor = egetenv ("ALTERNATE_EDITOR");

  while (1)
    {
      int opt = getopt_long_only (argc, argv,
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
			     "VHneqa:s:f:d:F:tc",
#else
			     "VHneqa:f:d:F:tc",
#endif
			     longopts, 0);

      if (opt == EOF)
	break;

      switch (opt)
	{
	case 0:
	  /* If getopt returns 0, then it has already processed a
	     long-named option.  We should do nothing.  */
	  break;

	case 'a':
	  alternate_editor = optarg;
	  break;

#ifndef NO_SOCKETS_IN_FILE_SYSTEM
	case 's':
	  socket_name = optarg;
	  break;
#endif

	case 'f':
	  server_file = optarg;
	  break;

	  /* We used to disallow this argument in w32, but it seems better
	     to allow it, for the occasional case where the user is
	     connecting with a w32 client to a server compiled with X11
	     support.  */
	case 'd':
	  display = optarg;
	  break;

	case 'n':
	  nowait = 1;
	  break;

	case 'e':
	  eval = 1;
	  break;

	case 'q':
	  quiet = 1;
	  break;

	case 'V':
	  message (FALSE, "emacsclient %s\n", VERSION);
	  exit (EXIT_SUCCESS);
	  break;

        case 't':
          tty = 1;
	  current_frame = 0;
          break;

        case 'c':
          current_frame = 0;
          break;

	case 'p':
	  parent_id = optarg;
          current_frame = 0;
	  break;

	case 'H':
	  print_help_and_exit ();
	  break;

        case 'F':
          frame_parameters = optarg;
          break;

	default:
	  message (TRUE, "Try `%s --help' for more information\n", progname);
	  exit (EXIT_FAILURE);
	  break;
	}
    }

  /* If the -c option is used (without -t) and no --display argument
     is provided, try $DISPLAY.
     Without the -c option, we used to set `display' to $DISPLAY by
     default, but this changed the default behavior and is sometimes
     inconvenient.  So we force users to use "--display $DISPLAY" if
     they want Emacs to connect to their current display.

     Some window systems have a notion of default display not
     reflected in the DISPLAY variable.  If the user didn't give us an
     explicit display, try this platform-specific after trying the
     display in DISPLAY (if any).  */
  if (!current_frame && !tty && !display)
    {
      /* Set these here so we use a default_display only when the user
         didn't give us an explicit display.  */
#if defined (NS_IMPL_COCOA)
      alt_display = "ns";
#elif defined (HAVE_NTGUI)
      alt_display = "w32";
#endif

      display = egetenv ("DISPLAY");
    }

  if (!display)
    {
      display = alt_display;
      alt_display = NULL;
    }

  /* A null-string display is invalid.  */
  if (display && strlen (display) == 0)
    display = NULL;

  /* If no display is available, new frames are tty frames.  */
  if (!current_frame && !display)
    tty = 1;

#ifdef WINDOWSNT
  /* Emacs on Windows does not support graphical and text terminal
     frames in the same instance.  So, treat the -t and -c options as
     equivalent, and open a new frame on the server's terminal.
     Ideally, we would only set tty = 1 when the serve is running in a
     console, but alas we don't know that.  As a workaround, always
     ask for a tty frame, and let server.el figure it out.  */
  if (!current_frame)
    {
      display = NULL;
      tty = 1;
    }

  if (alternate_editor && alternate_editor[0] == '\0')
    {
      message (TRUE, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
an empty string");
      exit (EXIT_FAILURE);
    }
Example #26
0
int main(int argc, char* argv[]) {
    int opt;
    uint64_t c = DEFAULT_C;
    uint64_t b = DEFAULT_B;
    uint64_t s = DEFAULT_S;
    FILE* fin  = stdin;

    /* Read arguments */ 
    while(-1 != (opt = getopt(argc, argv, "c:b:s:i:h"))) {
        switch(opt) {
        case 'c':
            c = atoi(optarg);
            break;
        case 'b':
            b = atoi(optarg);
            break;
        case 's':
            s = atoi(optarg);
            break;
        case 'i':
            fin = fopen(optarg, "r");
            break;
        case 'h':
        default:
            print_help_and_exit();
            break;
        }
    }

    printf("Cache Settings\n");
    printf("C: %" PRIu64 "\n", c);
    printf("B: %" PRIu64 "\n", b);
    printf("S: %" PRIu64 "\n", s);
    printf("\n");

    /* Setup the cache */
    cache_init(c, s, b);

    /* Setup statistics */
    struct cache_stats_t stats;
    memset(&stats, 0, sizeof(struct cache_stats_t));
    stats.miss_penalty = 100;
    stats.access_time = 2;

    /* Begin reading the file */ 
    char rw;
    uint64_t address;
    while (!feof(fin)) { 
        int ret = fscanf(fin, "%c %" PRIx64 "\n", &rw, &address); 
        if(ret == 2) {
            cache_access(rw, address, &stats); 
        }
    }

    /* Make sure to free up memory here */
    cache_cleanup(&stats);

    print_statistics(&stats);
    fclose(fin);
    return 0;
}
Example #27
0
int main (int argc, char** argv) {
  struct BenchmarkContext context = { NULL, NULL, NULL, 0 };
  int opt;
  int optc = 0;
  SquashCodec* codec = NULL;
  SquashOptions* opts = NULL;

  setvbuf (stdout, NULL, _IONBF, 0);

  while ( (opt = getopt(argc, argv, "hc:o:t:")) != -1 ) {
    switch ( opt ) {
      case 'h':
        print_help_and_exit (argv[0], 0);
        break;
      case 'o':
        context.csv = fopen (optarg, "w+b");
        if (context.csv == NULL) {
          perror ("Unable to open output file");
          return -1;
        }
        setbuf (context.csv, NULL);
        break;
      case 'c':
	codec = benchmark_parse_codec (optarg, &opts);
        if (codec == NULL) {
          fprintf (stderr, "Unable to find codec.\n");
          return -1;
        }
        break;
      case 't':
	min_exec_time = strtod (optarg, NULL);
	break;
    }

    optc++;
  }

  if ( optind >= argc ) {
    fputs ("No input files specified.\n", stderr);
    return -1;
  }

  if (context.csv != NULL)
    fprintf (context.csv, "dataset,plugin,codec,level,compressed_size,compress_cpu,compress_wall,decompress_cpu,decompress_wall\r\n");

  while ( optind < argc ) {
    context.input_name = argv[optind];
    context.input = fopen (context.input_name, "rb");
    if (context.input == NULL) {
      perror ("Unable to open input data");
      return -1;
    }

    if (fseek (context.input, 0, SEEK_END) != 0) {
      perror ("Unable to seek to end of input file");
      exit (-1);
    }
    context.input_size = ftell (context.input);

    fprintf (stdout, "Using %s:\n", context.input_name);

    if (opts != NULL) {
      benchmark_codec_with_options (&context, codec, opts);
    } else if (codec == NULL) {
      squash_foreach_plugin (benchmark_plugin, &context);
    } else {
      benchmark_codec (codec, &context);
    }

    optind++;
  }

  if (context.csv != NULL) {
    fclose (context.csv);
  }
  fclose (context.input);

  return 0;
}
Example #28
0
int main (int argc, char** argv) {
  SquashStatus res;
  SquashCodec* codec = NULL;
  SquashOptions* options = NULL;
  SquashStreamType direction = SQUASH_STREAM_COMPRESS;
  FILE* input = NULL;
  FILE* output = NULL;
  char* input_name = NULL;
  char* output_name = NULL;
  bool list_codecs = false;
  bool list_plugins = false;
  char** option_keys = NULL;
  char** option_values = NULL;
  bool keep = false;
  bool force = false;
  int opt;
  int optc = 0;
  char* tmp_string;
  int retval = EXIT_SUCCESS;
  struct parg_state ps;
  int optend;
  const struct parg_option squash_options[] = {
    {"keep", PARG_NOARG, NULL, 'k'},
    {"option", PARG_REQARG, NULL, 'o'},
    {"codec", PARG_REQARG, NULL, 'c'},
    {"list-codecs", PARG_NOARG, NULL, 'L'},
    {"list-plugins", PARG_NOARG, NULL, 'P'},
    {"force", PARG_NOARG, NULL, 'f'},
    {"decompress", PARG_NOARG, NULL, 'd'},
    {"version", PARG_NOARG, NULL, 'V'},
    {"help", PARG_NOARG, NULL, 'h'},
    {NULL, 0, NULL, 0}
  };

  option_keys = (char**) malloc (sizeof (char*));
  option_values = (char**) malloc (sizeof (char*));
  *option_keys = NULL;
  *option_values = NULL;

  optend = parg_reorder (argc, argv, "c:ko:123456789LPfdhb:V", squash_options);

  parg_init(&ps);

  while ( (opt = parg_getopt_long (&ps, optend, argv, "c:ko:123456789LPfdhb:V", squash_options, NULL)) != -1 ) {
    switch ( opt ) {
      case 'c':
        codec = squash_get_codec (ps.optarg);
        if ( codec == NULL ) {
          fprintf (stderr, "Unable to find codec '%s'\n", ps.optarg);
          retval = exit_failure ();
          goto cleanup;
        }
        break;
      case 'k':
        keep = true;
        break;
      case 'o':
        parse_option (&option_keys, &option_values, ps.optarg);
        break;
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        tmp_string = malloc (8);
        snprintf (tmp_string, 8, "level=%c", (char) opt);
        parse_option (&option_keys, &option_values, tmp_string);
        free (tmp_string);
        break;
      case 'L':
        list_codecs = true;
        break;
      case 'P':
        list_plugins = true;
        break;
      case 'f':
        force = true;
        break;
      case 'h':
        print_help_and_exit (argc, argv, EXIT_SUCCESS);
        break;
      case 'd':
        direction = SQUASH_STREAM_DECOMPRESS;
        break;
      case 'V':
        print_version_and_exit (argc, argv, EXIT_SUCCESS);
        break;
    }

    optc++;
  }

  if (list_plugins) {
    if (list_codecs)
      squash_foreach_plugin (list_plugins_and_codecs_foreach_cb, NULL);
    else
      squash_foreach_plugin (list_plugins_foreach_cb, NULL);

    goto cleanup;
  } else if (list_codecs) {
    squash_foreach_codec (list_codecs_foreach_cb, NULL);
    goto cleanup;
  }

  if ( ps.optind < argc ) {
    input_name = argv[ps.optind++];

    if ( (direction == SQUASH_STREAM_DECOMPRESS) && codec == NULL ) {
      char* extension;

      extension = strrchr (input_name, '.');
      if (extension != NULL)
        extension++;

      if (extension != NULL)
        codec = squash_get_codec_from_extension (extension);
    }
  } else {
    fprintf (stderr, "You must provide an input file name.\n");
    retval = exit_failure ();
    goto cleanup;
  }

  if ( ps.optind < argc ) {
    output_name = strdup (argv[ps.optind++]);

    if ( codec == NULL && direction == SQUASH_STREAM_COMPRESS ) {
      const char* extension = strrchr (output_name, '.');
      if (extension != NULL)
        extension++;

      if (extension != NULL)
        codec = squash_get_codec_from_extension (extension);
    }
  } else {
    if ( codec != NULL ) {
      const char* extension = squash_codec_get_extension (codec);
      if (extension != NULL) {
        if (strcmp (input_name, "-") == 0) {
          output_name = strdup ("-");
        } else {
          size_t extension_length = strlen (extension);
          size_t input_name_length = strlen (input_name);

          if ( (extension_length + 1) < input_name_length &&
               input_name[input_name_length - (1 + extension_length)] == '.' &&
               strcasecmp (extension, input_name + (input_name_length - (extension_length))) == 0 ) {
            output_name = squash_strndup (input_name, input_name_length - (1 + extension_length));
          }
        }
      }
    }
  }

  if ( ps.optind < argc ) {
    fprintf (stderr, "Too many arguments.\n");
  }

  if ( codec == NULL ) {
    fprintf (stderr, "Unable to determine codec.  Please pass -c \"codec\", or -L to see a list of available codecs.\n");
    retval = exit_failure ();
    goto cleanup;
  }

  if ( output_name == NULL ) {
    fprintf (stderr, "Unable to determine output file.\n");
    retval = exit_failure ();
    goto cleanup;
  }

  if ( strcmp (input_name, "-") == 0 ) {
    input = stdin;
  } else {
    input = fopen (input_name, "rb");
    if ( input == NULL ) {
      perror ("Unable to open input file");
      retval = exit_failure ();
      goto cleanup;
    }
  }

  if ( strcmp (output_name, "-") == 0 ) {
    output = stdout;
  } else {
    int output_fd = open (output_name,
#if !defined(_WIN32)
                          O_RDWR | O_CREAT | (force ? O_TRUNC : O_EXCL),
                          S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
#else
                          O_RDWR | O_CREAT | (force ? O_TRUNC : O_EXCL) | O_BINARY,
                          S_IREAD | S_IWRITE
#endif
    );
    if ( output_fd < 0 ) {
      perror ("Unable to open output file");
      retval = exit_failure ();
      goto cleanup;
    }
    output = fdopen (output_fd, "wb");
    if ( output == NULL ) {
      perror ("Unable to open output");
      retval = exit_failure ();
      goto cleanup;
    }
  }

  options = squash_options_newa (codec, (const char * const*) option_keys, (const char * const*) option_values);

  res = squash_splice_with_options (codec, direction, output, input, 0, options);

  if ( res != SQUASH_OK ) {
    fprintf (stderr, "Failed to %s: %s\n",
             (direction == SQUASH_STREAM_COMPRESS) ? "compress" : "decompress",
             squash_status_to_string (res));
    retval = exit_failure ();
    goto cleanup;
  }

  if ( !keep && input != stdin ) {
    fclose (input);
    if ( unlink (input_name) != 0 ) {
      perror ("Unable to remove input file");
    }
    input = NULL;
  }

 cleanup:

  if (input != stdin && input != NULL)
    fclose (stdin);

  if (output != stdout)
    fclose (stdout);

  if (option_keys != NULL) {
    for (opt = 0 ; option_keys[opt] != NULL ; opt++) {
      free(option_keys[opt]);
    }
    free (option_keys);
  }

  if (option_values != NULL) {
    for (opt = 0 ; option_values[opt] != NULL ; opt++) {
      free(option_values[opt]);
    }
    free (option_values);
  }

  free (output_name);

  return retval;
}
Example #29
0
void parse_cmdline(int argc, char **argv) {
	char c;
	memset(&cmdopts, 0, sizeof(cmdopts));

	while((c = getopt(argc, argv, "leuPvyqr:w:p:c:iI")) != -1) {
		switch(c) {
			case 'l':
				print_devices_and_exit();
				break;

			case 'e':
				cmdopts.erase=1;  // 1= do not erase
				break;

			case 'u':
				cmdopts.protect_off=1;  // 1= do not disable write protect
				break;

			case 'P':
				cmdopts.protect_on=1;  // 1= do not enable write protect
				break;

			case 'v':
				cmdopts.verify=1;  // 1= do not verify
				break;

			case 'y':
				cmdopts.idcheck_continue=1;  // 1= do not stop on id mismatch
				break;

			case 'p':
				if(!strcmp(optarg, "help"))
					print_devices_and_exit();
				cmdopts.device = get_device_by_name(optarg);
				if(!cmdopts.device)
					ERROR("Unknown device");
				break;

			case 'c':
				if(!strcmp(optarg, "code"))
					cmdopts.page = CODE;
				if(!strcmp(optarg, "data"))
					cmdopts.page = DATA;
				if(!strcmp(optarg, "config"))
					cmdopts.page = CONFIG;
				if(!cmdopts.page)
					ERROR("Unknown memory type");
				break;

			case 'q':
				cmdopts.query_device_id=8;  // 8= query for 8 bit device id
				cmdopts.device = get_device_by_name("M25P80 @SOIC8");  // prime with canonical 8 bit part
				break;

			case 'r':
				cmdopts.action = action_read;
				cmdopts.filename = optarg;
				break;

			case 'w':
				cmdopts.action = action_write;
				cmdopts.filename = optarg;
				break;

			case 'i':
				cmdopts.icsp = MP_ICSP_ENABLE | MP_ICSP_VCC;
				break;

			case 'I':
				cmdopts.icsp = MP_ICSP_ENABLE;
				break;

			default:
				print_help_and_exit(argv[0]);
				break;
		}
	}
}
Example #30
0
int main(int argc, char **argv) {
	unsigned int start;
	int bytes_count = 0;
	char filename[256];
	memset(filename, 0, sizeof(filename));
	// Parsing command line
	char c;
	action_t action = NONE;
	bool start_addr_specified = false,
		pgm_specified = false,
		part_specified = false,
        bytes_count_specified = false;
	memtype_t memtype = FLASH;
	int i;
	programmer_t *pgm = NULL;
	const stm8_device_t *part = NULL;
	while((c = getopt (argc, argv, "r:w:v:nc:p:s:b:luV")) != (char)-1) {
		switch(c) {
			case 'c':
				pgm_specified = true;
				for(i = 0; pgms[i].name; i++) {
					if(!strcmp(optarg, pgms[i].name))
						pgm = &pgms[i];
				}
				break;
			case 'p':
				part_specified = true;
				part = get_part(optarg);
				break;
			case 'l':
				for(i = 0; stm8_devices[i].name; i++)
					printf("%s ", stm8_devices[i].name);
				printf("\n");
				exit(0);
			case 'r':
				action = READ;
				strcpy(filename, optarg);
				break;
			case 'w':
				action = WRITE;
				strcpy(filename, optarg);
				break;
			case 'v':
				action = VERIFY;
				strcpy(filename, optarg);
				break;
                        case 'u':
				action = UNLOCK;
				start  = 0x4800;
				memtype = OPT;
				strcpy(filename, "Workaround");
				break;
			case 's':
                // Start addr is depending on MCU type
				if(strcasecmp(optarg, "flash") == 0) {
					memtype = FLASH;
                } else if(strcasecmp(optarg, "eeprom") == 0) {
					memtype = EEPROM;
                } else if(strcasecmp(optarg, "ram") == 0) {
					memtype = RAM;
                } else if(strcasecmp(optarg, "opt") == 0) {
					memtype = OPT;
				} else {
					// Start addr is specified explicitely
					memtype = UNKNOWN;
					int success = sscanf(optarg, "%x", &start);
					assert(success);
                    start_addr_specified = true;
				}
				break;
			case 'b':
				bytes_count = atoi(optarg);
                bytes_count_specified = true;
				break;
			case 'V':
                                print_version_and_exit( (bool)0);
				break;
			case '?':
                                print_help_and_exit(argv[0], false);
			default:
				print_help_and_exit(argv[0], true);
		}
	}
	if(argc <= 1)
		print_help_and_exit(argv[0], true);
	if(pgm_specified && !pgm) {
		fprintf(stderr, "No valid programmer specified. Possible values are:\n");
		dump_pgms( (programmer_t *) &pgms);
		exit(-1);
	}
	if(!pgm)
		spawn_error("No programmer has been specified");
	if(part_specified && !part) {
		fprintf(stderr, "No valid part specified. Use -l to see the list of supported devices.\n");
		exit(-1);
	}
	if(!part)
		spawn_error("No part has been specified");

    // Try define memory type by address
	if(memtype == UNKNOWN) {
        if((start >= 0x4800) && (start < 0x4880)) {
            memtype = OPT;
        }
        if((start >= part->ram_start) && (start < part->ram_start + part->ram_size)) {
            memtype = RAM;
        }
        else if((start >= part->flash_start) && (start < part->flash_start + part->flash_size)) {
            memtype = FLASH;
        }
        else if((start >= part->eeprom_start) && (start < part->eeprom_start + part->eeprom_size)) {
            memtype = EEPROM;
        }
    }

	if(memtype != UNKNOWN) {
		// Selecting start addr depending on
		// specified part and memtype
		switch(memtype) {
			case RAM:
                if(!start_addr_specified) {
                    start = part->ram_start;
                }
                if(!bytes_count_specified || bytes_count > part->ram_size) {
                    bytes_count = part->ram_size;
                }
                fprintf(stderr, "Determine RAM area\r\n");
				break;
			case EEPROM:
                if(!start_addr_specified) {
                    start = part->eeprom_start;
                }
                if(!bytes_count_specified || bytes_count > part->eeprom_size) {
                    bytes_count = part->eeprom_size;
                }
                fprintf(stderr, "Determine EEPROM area\r\n");
				break;
			case FLASH:
                if(!start_addr_specified) {
                    start = part->flash_start;
                }
                if(!bytes_count_specified || bytes_count > part->flash_size) {
                    bytes_count = part->flash_size;
                }
                fprintf(stderr, "Determine FLASH area\r\n");
				break;
			case OPT:
                if(!start_addr_specified) {
                    start = 0x4800;
                }
                size_t opt_size = (part->flash_size <= 8*1024 ? 0x40 : 0x80);
                if(!bytes_count_specified || bytes_count > opt_size) {
                    bytes_count = opt_size;
                }
                fprintf(stderr, "Determine OPT area\r\n");
                break;
		}
		start_addr_specified = true;
	}
	if(!action)
		spawn_error("No action has been specified");
	if(!start_addr_specified)
		spawn_error("No memtype or start_addr has been specified");
	if (!strlen(filename))
		spawn_error("No filename has been specified");
	if(!action || !start_addr_specified || !strlen(filename))
		print_help_and_exit(argv[0], true);
	if(!usb_init(pgm, pgm->usb_vid, pgm->usb_pid))
		spawn_error("Couldn't initialize stlink");
	if(!pgm->open(pgm))
		spawn_error("Error communicating with MCU. Please check your SWIM connection.");


	FILE *f;
	if(action == READ) {
		fprintf(stderr, "Reading %d bytes at 0x%x... ", bytes_count, start);
		fflush(stderr);
        int bytes_count_align = ((bytes_count-1)/256+1)*256; // Reading should be done in blocks of 256 bytes
		unsigned char *buf = malloc(bytes_count_align);
		if(!buf) spawn_error("malloc failed");
		int recv = pgm->read_range(pgm, part, buf, start, bytes_count_align);
        if(recv < bytes_count_align) {
            fprintf(stderr, "\r\nRequested %d bytes but received only %d.\r\n", bytes_count_align, recv);
			spawn_error("Failed to read MCU");
        }
		if(!(f = fopen(filename, "w")))
			spawn_error("Failed to open file");
		if(is_ext(filename, ".ihx") || is_ext(filename, ".hex"))
		{
			fprintf(stderr, "Reading from Intel hex file ");
			ihex_write(f, buf, start, start+bytes_count);
		}
		else if(is_ext(filename, ".s19") || is_ext(filename, ".s8") || is_ext(filename, ".srec"))
		{
			printf("Reading from Motorola S-record files are not implemented (yet)\n");
      printf("Exiting...\n");
			exit(-1);

			//TODO Remove the above message and exit, and implement reading from S-record.
			fprintf(stderr, "Reading from Motorola S-record file ");
			srec_write(f, buf, start, start+bytes_count);
		}
		else
		{
			fwrite(buf, 1, bytes_count, f);
		}
		fclose(f);
		fprintf(stderr, "OK\n");
		fprintf(stderr, "Bytes received: %d\n", bytes_count);
    } else if (action == VERIFY) {
		fprintf(stderr, "Verifing %d bytes at 0x%x... ", bytes_count, start);
		fflush(stderr);

        int bytes_count_align = ((bytes_count-1)/256+1)*256; // Reading should be done in blocks of 256 bytes
		unsigned char *buf = malloc(bytes_count_align);
		if(!buf) spawn_error("malloc failed");
		int recv = pgm->read_range(pgm, part, buf, start, bytes_count_align);
        if(recv < bytes_count_align) {
            fprintf(stderr, "\r\nRequested %d bytes but received only %d.\r\n", bytes_count_align, recv);
			spawn_error("Failed to read MCU");
        }

		if(!(f = fopen(filename, "r")))
			spawn_error("Failed to open file");
		unsigned char *buf2 = malloc(bytes_count);
		if(!buf2) spawn_error("malloc failed");
		int bytes_to_verify;
		/* reading bytes to RAM */
		if(is_ext(filename, ".ihx") || is_ext(filename, ".hex")) {
			bytes_to_verify = ihex_read(f, buf, start, start + bytes_count);
		} else {
			fseek(f, 0L, SEEK_END);
			bytes_to_verify = ftell(f);
            if(bytes_count_specified) {
                bytes_to_verify = bytes_count;
            } else if(bytes_count < bytes_to_verify) {
                bytes_to_verify = bytes_count;
            }
			fseek(f, 0, SEEK_SET);
			fread(buf2, 1, bytes_to_verify, f);
		}
		fclose(f);

        if(memcmp(buf, buf2, bytes_to_verify) == 0) {
            fprintf(stderr, "OK\n");
            fprintf(stderr, "Bytes verified: %d\n", bytes_to_verify);
        } else {
            fprintf(stderr, "FAILED\n");
            exit(-1);
        }


	} else if (action == WRITE) {
		if(!(f = fopen(filename, "r")))
			spawn_error("Failed to open file");
        int bytes_count_align = ((bytes_count-1)/part->flash_block_size+1)*part->flash_block_size;
		unsigned char *buf = malloc(bytes_count_align);
		if(!buf) spawn_error("malloc failed");
        memset(buf, 0, bytes_count_align); // Clean aligned buffer
		int bytes_to_write;

		/* reading bytes to RAM */
		if(is_ext(filename, ".ihx") || is_ext(filename, ".hex")) {
			fprintf(stderr, "Writing Intel hex file ");
			bytes_to_write = ihex_read(f, buf, start, start + bytes_count);
		} else if (is_ext(filename, ".s19") || is_ext(filename, ".s8") || is_ext(filename, ".srec")) {
			fprintf(stderr, "Writing Motorola S-record file ");
			bytes_to_write = srec_read(f, buf, start, start + bytes_count);
		} else {
			fprintf(stderr, "Writing binary file ");
			fseek(f, 0L, SEEK_END);
			bytes_to_write = ftell(f);
            if(bytes_count_specified) {
                bytes_to_write = bytes_count;
            } else if(bytes_count < bytes_to_write) {
                bytes_to_write = bytes_count;
            }
			fseek(f, 0, SEEK_SET);
			fread(buf, 1, bytes_to_write, f);
		}
		fprintf(stderr, "%d bytes at 0x%x... ", bytes_to_write, start);

		/* flashing MCU */
		int sent = pgm->write_range(pgm, part, buf, start, bytes_to_write, memtype);
		if(pgm->reset) {
			// Restarting core (if applicable)
			pgm->reset(pgm);
		}
		fprintf(stderr, "OK\n");
		fprintf(stderr, "Bytes written: %d\n", sent);
		fclose(f);
	} else if (action == UNLOCK) {
		int bytes_to_write=part->option_bytes_size;

		if (part->read_out_protection_mode==ROP_UNKNOWN) spawn_error("No unlocking mode defined for this device. You may need to edit the file stm8.c");

		unsigned char *buf=malloc(bytes_to_write);
		if(!buf) spawn_error("malloc failed");

		if (part->read_out_protection_mode==ROP_STM8S_STD) {
			for (int i=0; i<bytes_to_write;i++) {
				buf[i]=0;
				if ((i>0)&&((i&1)==0)) buf[i]=0xff;
			}
		}

		/* flashing MCU */
		int sent = pgm->write_range(pgm, part, buf, start, bytes_to_write, memtype);
		if(pgm->reset) {
			// Restarting core (if applicable)
			pgm->reset(pgm);
		}
		fprintf(stderr, "Unlocked device. Option bytes reset to default state.\n");
		fprintf(stderr, "Bytes written: %d\n", sent);
	}
	return(0);
}