Пример #1
0
int main(int argc, char** argv) {
  try {
    RMF_ADD_INPUT_FILE("rmf");
    process_options(argc, argv);
    if (boost::algorithm::ends_with(input, ".rmf2") &&
        boost::filesystem::exists(boost::filesystem::path(input) / "file")) {
      boost::filesystem::rename(
          boost::filesystem::path(input) / "file",
          boost::filesystem::path(input) / "file.rmf2info");
      std::cout << "Updated" << std::endl;
    } else {
      std::cout << "Nothing to do" << std::endl;
    }
  }
  catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
  return 0;
}
Пример #2
0
int main(int argc, char **argv) {
  try {
    RMF_ADD_INPUT_FILE("rmf");
    process_options(argc, argv);


    RMF::FileConstHandle rh = RMF::open_rmf_file_read_only(input);
    for (unsigned int i = 0; i < rh.get_number_of_frames(); ++i) {
      rh.set_current_frame(i);
      std::string cmt = rh.get_current_frame().get_name();
      if (!cmt.empty()) {
        std::cout << i << ": " << cmt << std::endl;
      }
    }
    return 0;
  } catch (const std::exception &e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
}
Пример #3
0
/*********************************************************
 Start here.
**********************************************************/
int main(int argc, char **argv)
{	
	TALLOC_CTX *frame = talloc_stackframe();
	int local_flags = 0;
	int ret;

#if defined(HAVE_SET_AUTH_PARAMETERS)
	set_auth_parameters(argc, argv);
#endif /* HAVE_SET_AUTH_PARAMETERS */

	if (getuid() == 0) {
		local_flags = LOCAL_AM_ROOT;
	}

	load_case_tables();

	local_flags = process_options(argc, argv, local_flags);

	setup_logging("smbpasswd", DEBUG_STDERR);

	/*
	 * Set the machine NETBIOS name if not already
	 * set from the config file. 
	 */ 

	if (!init_names())
		return 1;

	/* Check the effective uid - make sure we are not setuid */
	if (is_setuid_root()) {
		fprintf(stderr, "smbpasswd must *NOT* be setuid root.\n");
		exit(1);
	}

	if (local_flags & LOCAL_AM_ROOT) {
		secrets_init();
		ret = process_root(local_flags);
	} else {
		ret = process_nonroot(local_flags);
	}
	TALLOC_FREE(frame);
	return ret;
}
void
ltrace_init(int argc, char **argv)
{
	setlocale(LC_ALL, "");

	struct opt_p_t *opt_p_tmp;

	atexit(normal_exit);
	signal(SIGINT, signal_exit);	/* Detach processes when interrupted */
	signal(SIGTERM, signal_exit);	/*  ... or killed */

	argv = process_options(argc, argv);
	init_global_config();

	if (command) {
		/* Check that the binary ABI is supported before
		 * calling execute_program.  */
		{
			struct ltelf lte;
			if (ltelf_init(&lte, command) == 0)
				ltelf_destroy(&lte);
			else
				exit(EXIT_FAILURE);
		}

		pid_t pid = execute_program(command, argv);
		struct process *proc = open_program(command, pid);
		if (proc == NULL) {
			fprintf(stderr, "couldn't open program '%s': %s\n",
				command, strerror(errno));
			exit(EXIT_FAILURE);
		}

		trace_set_options(proc);
		continue_process(pid);
	}
	opt_p_tmp = opt_p;
	while (opt_p_tmp) {
		open_pid(opt_p_tmp->pid);
		opt_p_tmp = opt_p_tmp->next;
	}
}
Пример #5
0
/*-----------------------------------------------------------------------------
*   Parse command line, set options, including opts.files with list of
*	input files, including parsing of '@' lists
*----------------------------------------------------------------------------*/
void parse_argv( int argc, char *argv[] )
{
    int arg;

    init_module();

    if ( argc == 1 )
        exit_copyright();				/* exit if no arguments */

    process_options( &arg, argc, argv );	/* process all options, set arg to next */

    if ( arg >= argc )
        error_no_src_file();			/* no source file */

    if ( opts.verbose )
        display_options();				/* display status messages of select assembler options */

    if ( ! get_num_errors() )
        process_files( arg, argc, argv );	/* process each source file */
}
Пример #6
0
/*
 * Main program
 */
int main(int argc, char **argv)
{
	int fd;

	process_options(argc, argv);

	/* Open the input file */
	if ((fd = open(img, O_RDONLY)) == -1) {
		perror("open input file");
		exit(1);
	}
	
	// get image length
   	imglen = lseek(fd, 0, SEEK_END);
	lseek (fd, 0, SEEK_SET);

	data = malloc (imglen);
	if (!data) {
		perror("out of memory");
		close (fd);
		exit(1);
	}
	
	// read image data
	read (fd, data, imglen);
		
	// Close the input file
	close(fd);

	if (dumpcontent)
		do_dumpcontent ();

	if (convertendian)
		do_endianconvert ();
	
	// free memory
	free (data);

	// Return happy 
	exit (0);
}
Пример #7
0
Файл: main.cpp Проект: att/uwin
void process_table(table_input &in)
{
  options *opt = 0;
  format *form = 0;
  table *tbl = 0;
  if ((opt = process_options(in)) != 0 
      && (form = process_format(in, opt)) != 0
      && (tbl = process_data(in, form, opt)) != 0) {
    tbl->print();
    delete tbl;
  }
  else {
    error("giving up on this table");
    while (in.get() != EOF)
      ;
  }
  delete opt;
  delete form;
  if (!in.ended())
    error("premature end of file");
}
Пример #8
0
int main(int argc, char * const argv[])
{
	int fd;
	struct blkpg_partition part;
	struct blkpg_ioctl_arg arg;

	process_options(argc, argv);

	fd = open(mtddev, O_RDWR | O_CLOEXEC);
	if (fd == -1)
		sys_errmsg_die("Cannot open %s", mtddev);

	memset(&part, 0, sizeof(part));

	memset(&arg, 0, sizeof(arg));
	arg.datalen = sizeof(part);
	arg.data = &part;

	switch (command) {
		case COMMAND_ADD:
			part.start = start_addr;
			part.length = length;
			strncpy(part.devname, part_name, sizeof(part.devname));
			arg.op = BLKPG_ADD_PARTITION;
			break;
		case COMMAND_DEL:
			part.pno = part_no;
			arg.op = BLKPG_DEL_PARTITION;
			break;
	}

	if (ioctl(fd, BLKPG, &arg))
		sys_errmsg_die("Failed to issue BLKPG ioctl");

	close(fd);

	/* Exit happy */
	return EXIT_SUCCESS;
}
Пример #9
0
int main(int argc, char** argv) {
  try {
    RMF_ADD_INPUT_FILE("rmf");
    RMF_ADD_OUTPUT_FILE("pdb");
    RMF_ADD_FRAMES;
    process_options(argc, argv);

    RMF::FileConstHandle rh = RMF::open_rmf_file_read_only(input);
    std::ostream* out;
    std::ofstream fout;
    if (!output.empty()) {
      fout.open(output.c_str());
      if (!fout) {
        std::cerr << "Error opening file " << output << std::endl;
        return 1;
      }
      out = &fout;
    } else {
      out = &std::cout;
    }
    RMF::decorator::IntermediateParticleFactory ipf(rh);
    RMF::decorator::AtomFactory af(rh);
    RMF::decorator::ChainFactory cf(rh);
    RMF::decorator::ResidueFactory rf(rh);
    RMF::NodeConstHandle rn = rh.get_root_node();
    for (unsigned int input_frame = start_frame, output_frame = 0;
         input_frame < rh.get_number_of_frames();
         input_frame += step_frame, ++output_frame) {
      rh.set_current_frame(RMF::FrameID(input_frame));
      *out << (boost::format("MODEL%1$9d") % (output_frame + 1)) << std::endl;
      write_atoms(*out, 0, rn, ipf, af, cf, rf);
      *out << "ENDMDL" << output_frame + 1 << std::endl;
    }
    return 0;
  }
  catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
}
Пример #10
0
int
main(int argc, char *argv[])
{
    debug("ntlm_auth build " __DATE__ ", " __TIME__ " starting up...\n");
#ifdef DEBUG
    debug("changing dir to /tmp\n");
    if (chdir("/tmp") != 0) {
        debug("ERROR: (%d) failed.\n",errno);
        return 2;
    }
#endif

    my_program_name = argv[0];
    process_options(argc, argv);

    debug("options processed OK\n");

    /* initialize FDescs */
    setbuf(stdout, NULL);
    setbuf(stderr, NULL);

    /* select the first domain controller we're going to use */
    current_dc = controllers;
    if (load_balance != 0 && numcontrollers > 1) {
	int n;
	pid_t pid = getpid();
	n = pid % numcontrollers;
	debug("load balancing. Selected controller #%d\n", n);
	while (n > 0) {
	    current_dc = current_dc->next;
	    n--;
	}
    }
    while (1) {
	manage_request();
    }
    return 0;
}
Пример #11
0
/**
 * \brief Entry point.
 * \param argc The number of input parameters.
 * \param argv The input parameters.
 */
int main(int argc, char *argv[]) {
	/* the resource manager must be initialized before any
	 * further actions are implemented */
	rm_init(&resource_mgr);

	if (process_options(argc, argv) == 1) {
		rm_cleanup_resources(&resource_mgr);
		exit(EXIT_FAILURE);
	}
	printf("Input: %s\n", cc_options.input_file);
	printf("Output: %s\n", cc_options.output_file);
	printf("IR: %s\n", cc_options.ir_file);

	yyin = fopen(cc_options.input_file, "r");

	if (!yyin) {
		printf("FAIL");
		exit(1);
	}

	//  yyparse();

	do {
		yyparse();
	} while (!feof(yyin));

	fclose(yyin);
	printallstart(cc_options.output_file);
	if (cc_options.print_ir == 1) {
		FILE * ir_file = fopen(cc_options.ir_file, "w");
		ir_set_file(ir_file);
		generate_ir_code();
		fclose(ir_file);
	}

	rm_cleanup_resources(&resource_mgr);
	return 0;
}
Пример #12
0
int main(int argc, char **argv){
	pthread_t *threads;
	int i=0;
	void *ret;
	
	process_options(argc, argv);
	
	ccsm_fd = ccsm_open();
	if (ccsm_fd < 0) {
		perror("ccsm_fd");
		return 1;
	}

	ccsm_create_set(ccsm_fd, "main", 0);
		
	threads = malloc(sizeof(pthread_t) * pipeline_len);
	if (!threads){
		fprintf(stderr, "can't initialise threads\n");
		exit(1);
	}

	printf("Creating the required set of threads.....\n");
	for(i=0;i<pipeline_len;i++){
		if (pthread_create(&threads[i],NULL,&thread_function_run, (void *)i)){
		       	fprintf(stderr, "failed creating thread");
        		exit(1);
        	}
	}
	
	for(i=0;i<pipeline_len;i++){
		pthread_join(threads[i], &ret);
	}

	ccsm_destroy_set(ccsm_fd, "main");
//	ccsm_close(ccsm_fd);
	
	return 0;
}
Пример #13
0
int main(int argc, char *argv[])
{
	int i;
	signal(SIGPIPE, SIG_IGN);

	openlog("flexd", LOG_ERR , LOG_INFO);
	syslog(LOG_WARNING, "Starting flexd");

	if (ax25_config_load_ports() == 0) {
		fprintf(stderr, "flexd error: No AX25 port data configured\n");
		return 1;
	}

	process_options(argc, argv);

	if ((i = read_conf()) == -1)
		return 1;

	if ((is_daemon) && (!daemon_start(TRUE)) ) {
		fprintf(stderr, "flexd: cannot become a daemon\n");
		return 1;
	}

	if ((i = update_flex()) == -1) {
		fprintf(stderr, "\nStopping application. Restart flexd after changing the configuration\n");
		signal(SIGKILL, hup_handler);
		return (i);
	}

	signal(SIGHUP, hup_handler);
	signal(SIGALRM, alarm_handler);
	alarm(poll_time);

	for (;;)
		pause();

	return 0;
}
Пример #14
0
int main(int argc, char **argv)
{
	int ret;
	char ch;

	process_options(argc, argv);

	ret = mkfifo(STATUS_PIPE, 0666);

	if (ret == -1 && errno != EEXIST)
		errx(1, "Error creating named pipe");

	do {
		ch = action();

		if (ch == 'm')
			mem_map();
	} while (ch != 'x');

	remove(STATUS_PIPE);

	return 0;
}
Пример #15
0
/*! \addtogroup executables
 *  @{
 * \addtogroup client_FFTtoFile client_FFTtoFile
 * client_FFTtoBC_main
 * - @ref FFTProcessor with output to files
 * - configuration using command-line / XML
 * 
 * @{
 */
int main(int argc, char* argv[])
{
  boost::program_options::variables_map vm;
  try {
    vm = process_options("config/FFTProcessor.xml", argc, argv);
  } catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }

  boost::filesystem::path p(vm["config"].as<std::string>());
  LOGGER_INIT("./Log", p.stem().native());
  try {
    boost::property_tree::ptree config;
    read_xml(vm["config"].as<std::string>(), config, boost::property_tree::xml_parser::no_comments);

    const std::string stream_name("DataIQ");

    network::client::client<network::iq_adapter<repack_processor<FFTProcessorToFile<float> > > >
      c(config.get_child("FFTProcessor"));
    const std::set<std::string> streams(c.ls());
    if (streams.find(stream_name) != streams.end())
      ASSERT_THROW(c.connect_to(stream_name) == true);
    else
      throw std::runtime_error(str(boost::format("stream '%s' is not available")
                                   % stream_name));
    
    c.start();
    run_in_thread(network::get_io_service());
  } catch (const std::exception &e) {
    LOG_ERROR(e.what()); 
    std::cerr << e.what() << std::endl;
    return 1;
  }
  return 0;
}
Пример #16
0
int main(int argc, const char* argv[])
{
  FILE *log = get_log(NULL);

  switch (process_options(argc, argv, log))
    {
      case 0:
        break;
      case -1:
        exit(EXIT_SUCCESS);
      default:
        exit(EXIT_FAILURE);
    }

  install_termination_signal_handlers (log);
  install_rotate_signal_handlers (log);
  install_log_rotate_signal_handlers (log, 0, SIGUSR1);

  int r = xport_to_queue (log);

  close_log (log);

  return r;
}
Пример #17
0
static Isis_Kernel_t *allocate_std_kernel (Isis_Obs_t *o, char *options) /*{{{*/
{
   Isis_Kernel_t *k = NULL;

   (void) options;

   if (NULL == (k = isis_init_kernel (NULL, sizeof(*k), o)))
     return NULL;

   k->allows_ignoring_model_intervals = 1;

   if (-1 == process_options (k, options))
     {
        delete_kernel (k);
        return NULL;
     }

   k->delete_kernel = delete_kernel;
   k->compute_kernel = compute_kernel;
   k->compute_flux = compute_flux;
   k->print_kernel = print_kernel;

   return k;
}
Пример #18
0
int main( int   argc, char *argv[] )
{
	int used=0, NumRung;
	static int old_level ;
         bindtextdomain("linuxcnc", EMC2_PO_DIR);
         setlocale(LC_MESSAGES,"");
         setlocale(LC_CTYPE,"");
         textdomain("linuxcnc");
	old_level = rtapi_get_msg_level();
	compId=hal_init("classicladder"); //emc
	if (compId<0) return -1; //emc
	signal(SIGTERM,do_exit); //emc
	InitModbusMasterBeforeReadConf( );
	if (ClassicLadder_AllocAll())
	{
		char ProjectLoadedOk=TRUE;		
		process_options (argc, argv);
		if (nogui==TRUE)
		{
			rtapi_print(_("INFO CLASSICLADDER-   No ladder GUI requested-Realtime runs till HAL closes.\n"));
			ClassicLadder_InitAllDatas( );
			ProjectLoadedOk = LoadProjectFiles( InfosGene->CurrentProjectFileName  );
			if (pathswitch){   strcpy( InfosGene->CurrentProjectFileName, NewPath );   }
			InfosGene->LadderState = STATE_RUN;
			ClassicLadder_FreeAll(TRUE);
			hal_ready(compId);
			hal_exit(compId);	
			return 0; 
		} else {	
						
				for(NumRung=0;NumRung<NBR_RUNGS;NumRung++)   {   if ( RungArray[NumRung].Used ) used++;   }
				if((used==0) || ( (argc - optind) != 0) )
					    {	
						ClassicLadder_InitAllDatas( );
						ProjectLoadedOk = LoadProjectFiles( InfosGene->CurrentProjectFileName );
						InitGtkWindows( argc, argv );
						UpdateAllGtkWindows();
						if (pathswitch){   strcpy( InfosGene->CurrentProjectFileName, NewPath );   }
						UpdateWindowTitleWithProjectName( );
						MessageInStatusBar( ProjectLoadedOk?_("Project loaded and running"):_("Project failed to load..."));
						if (!ProjectLoadedOk) 
						{  
							   ClassicLadder_InitAllDatas( );   
							   if (modmaster) {    PrepareModbusMaster( );    }
						}
					    }else{
							   InitGtkWindows( argc, argv );
							   UpdateAllGtkWindows();
							   if (pathswitch){   strcpy( InfosGene->CurrentProjectFileName, NewPath );   }
							   UpdateWindowTitleWithProjectName( );
							   MessageInStatusBar(_("GUI reloaded with existing ladder program"));
							   if (modmaster) {    PrepareModbusMaster( );    }
							} 
							
				if (modslave)         {   InitSocketServer( 0/*UseUdpMode*/, ModbusServerPort/*PortNbr*/);  }
				InfosGene->LadderState = STATE_RUN;
				hal_ready(compId);
				gtk_main();
				rtapi_print(_("INFO CLASSICLADDER-   Ladder GUI closed. Realtime runs till HAL closes\n"));
				ClassicLadder_FreeAll(TRUE);
				hal_exit(compId);
				return 0;
			}		
	}
	 rtapi_print(_("ERROR CLASSICLADDER-   Ladder memory allocation error\n"));
	ClassicLadder_FreeAll(TRUE);
	rtapi_set_msg_level(old_level);
	hal_exit(compId);		
	return 0;
}
Пример #19
0
/****************************************************************************
 * Public Functions
 ****************************************************************************/
int mqtt_client_sub_task(void *arg)
{
	int result = -1;
	int ret = 0;
	int argc;
	char **argv;

	argc = ((struct mqtt_sub_input *)arg)->argc;
	argv = ((struct mqtt_sub_input *)arg)->argv;
	if (argc == 1) {
		print_usage();
		return 0;
	}

	/* set  the seed of a new sequence of random values */
	mqtt_set_srand();

	/* check options and set variables */
	init_variables();
	ret = process_options(argc, argv);
	if (ret != 0) {
		if (ret == 2) {
			print_usage();
			result = 0;
		}
		goto done;
	}

	/* check and do options when a client is running */
	ret = check_option_on_client_running();
	if (ret == CHECK_OPTION_RESULT_CHECKED_OK) {
		result = 0;
		goto done;
	} else if (ret == CHECK_OPTION_RESULT_CHECKED_ERROR) {
		goto done;
	}

	/* make mqtt subscriber client config */
	if (make_client_config() != 0) {
		goto done;
	}

	/* create mqtt subscriber client */
	if (g_debug) {
		printf("initialize MQTT client context.\n");
	}
	g_mqtt_client_handle = mqtt_init_client(&g_mqtt_client_config);
	if (g_mqtt_client_handle == NULL) {
		fprintf(stderr, "Error: mqtt_init_client() failed.\n");
		clean_client_config();
		goto done;
	}

	/* connect to a mqtt broker */
	if (g_debug) {
		printf("connect to a MQTT broker (%s : %d).\n", g_host_addr, g_port);
	}
	if (mqtt_connect(g_mqtt_client_handle, g_host_addr, g_port, g_keepalive) != 0) {
		fprintf(stderr, "Error: mqtt_connect() failed.\n");

		if (mqtt_deinit_client(g_mqtt_client_handle) != 0) {
			fprintf(stderr, "Error: mqtt_deinit_client() failed.\n");
		} else {
			g_mqtt_client_handle = NULL;
		}
		clean_client_config();
		goto done;
	}

	if (g_debug) {
		printf("MQTT subscriber has started successfully.\n");
	}

	/* result is success */
	result = 0;

done:
	deinit_variables();

	return result;
}
Пример #20
0
/*
 * Main program
 */
int main(int argc, char **argv)
{
    unsigned long ofs, end_addr = 0;
    unsigned long long blockstart = 1;
    int i, fd, ofd, bs, badblock = 0;
    //struct mtd_oob_buf oob = {0, 16, oobbuf};
    mtd_info_t meminfo;
    char pretty_buf[80];

    struct mtd_data_oob DataOobLocal;

    process_options(argc, argv);

    /* Open MTD device */
    if ((fd = open(mtddev, O_RDONLY)) == -1) {
        perror("open flash");
        exit (1);
    }

    /* Fill in MTD device capability structure */
    if (ioctl(fd, MEMGETINFO, &meminfo) != 0) {
        perror("MEMGETINFO");
        close(fd);
        exit (1);
    }

    /* Make sure device page sizes are valid */
    if (!(meminfo.oobsize == 64 && meminfo.oobblock == 2048) &&
            !(meminfo.oobsize == 16 && meminfo.oobblock == 512) &&
            !(meminfo.oobsize == 8 && meminfo.oobblock == 256)) {
        fprintf(stderr, "Unknown flash (not normal NAND)\n");
        close(fd);
        exit(1);
    }
    /* Read the real oob length */
    DataOobLocal.rtk_oob.length = meminfo.oobsize;

    /* Open output file for writing. If file name is "-", write to standard output. */
    if (!dumpfile) {
        ofd = STDOUT_FILENO;
    } else if ((ofd = open(dumpfile, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
        perror ("open outfile");
        close(fd);
        exit(1);
    }

    /* Initialize start/end addresses and block size */
    if (length)
        end_addr = start_addr + length;
    if (!length || end_addr > meminfo.size)
        end_addr = meminfo.size;

    bs = meminfo.oobblock;

    /* Print informative message */
    fprintf(stderr, "Block size %u, page size %u, OOB size %u\n", meminfo.erasesize, meminfo.oobblock, meminfo.oobsize);
    fprintf(stderr, "Dumping data starting at 0x%08x and ending at 0x%08x...\n",
            (unsigned int) start_addr, (unsigned int) end_addr);

    /* Dump the flash contents */
    for (ofs = start_addr; ofs < end_addr ; ofs+=bs) {
        // new eraseblock , check for bad block
        if (blockstart != (ofs & (~meminfo.erasesize + 1))) {
            blockstart = ofs & (~meminfo.erasesize + 1);
            if ((badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart)) < 0) {
                perror("ioctl(MEMGETBADBLOCK)");
                goto closeall;
            }
        }

        if (badblock) {
            if (omitbad)
                continue;
            memset (readbuf, 0xff, bs);
        } else {
            /* Read page data and exit on failure */
            /*
            if (pread(fd, readbuf, bs, ofs) != bs) {
            	perror("pread");
            	goto closeall;
            }
            */
        }

        //Ken, 20081005
        DataOobLocal.rtk_data.start = DataOobLocal.rtk_oob.start = ofs;
        DataOobLocal.rtk_data.length = meminfo.oobblock;
        DataOobLocal.rtk_data.ptr = readbuf;
        //DataOobLocal.rtk_oob.length = meminfo.oobsize;
        DataOobLocal.rtk_oob.ptr = oobbuf;

        if (ioctl(fd, MEMREADDATAOOB, &DataOobLocal) != 0) {
            perror("ioctl(MEMREADDATAOOB)");
            goto closeall;
        }

        /* Write out page data */
        if (pretty_print) {
            for (i = 0; i < bs; i += 16) {
                sprintf(pretty_buf,
                        "0x%08x: %02x %02x %02x %02x %02x %02x %02x "
                        "%02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
                        (unsigned int) (ofs + i),  readbuf[i],
                        readbuf[i+1], readbuf[i+2],
                        readbuf[i+3], readbuf[i+4],
                        readbuf[i+5], readbuf[i+6],
                        readbuf[i+7], readbuf[i+8],
                        readbuf[i+9], readbuf[i+10],
                        readbuf[i+11], readbuf[i+12],
                        readbuf[i+13], readbuf[i+14],
                        readbuf[i+15]);
                write(ofd, pretty_buf, 60);
            }
        } else
            write(ofd, readbuf, bs);

        if (omitoob)
            continue;

        if (badblock) {
            memset (readbuf, 0xff, meminfo.oobsize);
        } else {
            /* Read OOB data and exit on failure */
            /*
            oob.start = ofs;
            if (ioctl(fd, MEMREADOOB, &oob) != 0) {
            	perror("ioctl(MEMREADOOB)");
            	goto closeall;
            }
            */
        }

        /* Write out OOB data */
        if (pretty_print) {
            if (meminfo.oobsize < 16) {
                sprintf(pretty_buf, "  OOB Data: %02x %02x %02x %02x %02x %02x "
                        "%02x %02x\n",
                        oobbuf[0], oobbuf[1], oobbuf[2],
                        oobbuf[3], oobbuf[4], oobbuf[5],
                        oobbuf[6], oobbuf[7]);
                write(ofd, pretty_buf, 48);
                continue;
            }

            for (i = 0; i < meminfo.oobsize; i += 16) {
                sprintf(pretty_buf, "  OOB Data: %02x %02x %02x %02x %02x %02x "
                        "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
                        oobbuf[i], oobbuf[i+1], oobbuf[i+2],
                        oobbuf[i+3], oobbuf[i+4], oobbuf[i+5],
                        oobbuf[i+6], oobbuf[i+7], oobbuf[i+8],
                        oobbuf[i+9], oobbuf[i+10], oobbuf[i+11],
                        oobbuf[i+12], oobbuf[i+13], oobbuf[i+14],
                        oobbuf[i+15]);
                write(ofd, pretty_buf, 60);
            }
        } else
            write(ofd, oobbuf, meminfo.oobsize);
    }

    /* Close the output file and MTD device */
    close(fd);
    close(ofd);

    /* Exit happy */
    return 0;

closeall:
    close(fd);
    close(ofd);
    exit(1);

}
Пример #21
0
int main(int argc, char **argv) {
  int status;
  int idx;
  int active_last = 0;
  int active = 0;

  struct redir_t *redir;

  int keep_going = 1;
  int reload_config = 0;

  uint8_t hwaddr[6];
  struct ifreq ifr;

  int selfpipe;
  
  int fd = socket(AF_INET, SOCK_DGRAM, 0);

  options_init();

  chilli_signals(&keep_going, &reload_config);
  
  process_options(argc, argv, 1);
  
  safe_strncpy(ifr.ifr_name, _options.dhcpif, sizeof(ifr.ifr_name));

#ifdef SIOCGIFHWADDR  
  if (ioctl(fd, SIOCGIFHWADDR, (caddr_t)&ifr) == 0) {
    memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, PKT_ETH_ALEN);
  } else {
    log_err(errno, "could not get MAC address");
    return -1;
  }
#endif  

  close(fd);
  
  /* create an instance of redir */
  if (redir_new(&redir, &_options.uamlisten, _options.uamport, 
#ifdef ENABLE_UAMUIPORT
		_options.uamuiport
#else
		0
#endif
		)) {
    log_err(0, "Failed to create redir");
    return -1;
  }
  
  if (redir_listen(redir)) {
    log_err(0, "Failed to create redir listen");
    return -1;
  }

  redir_set(redir, hwaddr, (_options.debug));
  redir_set_cb_getstate(redir, sock_redir_getstate);
  
  redir->cb_handle_url = redir_handle_url;

  if (net_select_init(&sctx))
    log_err(errno, "select init");

  selfpipe = selfpipe_init();

  /* epoll */
  net_select_addfd(&sctx, selfpipe, SELECT_READ);
  net_select_addfd(&sctx, redir->fd[0], SELECT_READ);
  net_select_addfd(&sctx, redir->fd[1], SELECT_READ);

  if (_options.gid && setgid(_options.gid)) {
    log_err(errno, "setgid(%d) failed while running with gid = %d\n", 
	    _options.gid, getgid());
  }
  
  if (_options.uid && setuid(_options.uid)) {
    log_err(errno, "setuid(%d) failed while running with uid = %d\n", 
	    _options.uid, getuid());
  }

  while (keep_going) {

    /* select/poll */
    net_select_zero(&sctx);
    net_select_fd(&sctx, selfpipe, SELECT_READ);
    net_select_fd(&sctx, redir->fd[0], SELECT_READ);
    net_select_fd(&sctx, redir->fd[1], SELECT_READ);
  
    active = 0;

    if (reload_config) {
      reload_options(argc, argv);
      reload_config = 0;

      redir_set(redir, hwaddr, _options.debug);
    }

    for (idx=0; idx < max_requests; idx++) {

      conn_select_fd(&requests[idx].conn, &sctx);

      if (requests[idx].inuse && requests[idx].socket_fd) {
	time_t now = mainclock_tick();
	int fd = requests[idx].socket_fd;
	int timeout = 60;

	if (now - requests[idx].last_active > timeout) {
	  log_dbg("timeout connection %d", idx);
	  redir_conn_finish(&requests[idx].conn, &requests[idx]);
	} else {
	  int evt = SELECT_READ;
	  timeout = 0;
	  if (conn_write_remaining(&requests[idx].conn))
	    evt |= SELECT_WRITE;
	  net_select_fd(&sctx, fd, evt);
	  active++;
	}
	
#if(_debug_ > 1)
	if (_options.debug) {
	  struct sockaddr_in address;
	  socklen_t addrlen = sizeof(address);
	  
	  if (getpeername(fd, (struct sockaddr *)&address, 
			  &addrlen) >= 0) {
	    char line[512];
	    
	    safe_snprintf(line, sizeof(line),
			  "#%d (%d) %d connection from %s %d",
			  timeout ? -1 : active, fd, 
			  (int) requests[idx].last_active,
			  inet_ntoa(address.sin_addr),
			  ntohs(address.sin_port));
	    
	    if (requests[idx].conn.sock) {
	      addrlen = sizeof(address);
	      if (getpeername(requests[idx].conn.sock,
			      (struct sockaddr *)&address,
			      &addrlen) >= 0) {
		safe_snprintf(line+strlen(line),
			      sizeof(line)-strlen(line),
			      " to %s %d",
			      inet_ntoa(address.sin_addr),
			      ntohs(address.sin_port));
	      }
	    }
	    
	    if (timeout) {
	      safe_snprintf(line+strlen(line), 
			    sizeof(line)-strlen(line),
			    " (timeout)");
	    }

	    log_dbg("%s", line);
	  }
	}
#endif
      }
    }

    if (active != active_last) {
      log_dbg("active connections: %d", active);
      active_last = active;
    }
    
    status = net_select(&sctx);
    
#if defined(USING_POLL) && defined(HAVE_SYS_EPOLL_H) && (_debug_ > 1)
    if (_options.debug && status > 0) {
      int i;
      log_dbg("epoll %d", status);
      for (i=0; i < status; i++) {
	log_dbg("epoll fd %d %d", 
		sctx.events[i].data.fd, 
		sctx.events[i].events);
      }
    }
#endif

    switch (status) {
    case -1:
      log_err(errno, "select() returned -1!");
      break;  

    default:
      if (status > 0) {

	if (net_select_read_fd(&sctx, selfpipe)==1) {
	  chilli_handle_signal(0, 0);
	}
	
	if (redir->fd[0])
	  if (net_select_read_fd(&sctx, redir->fd[0])==1 && 
	      redir_accept2(redir, 0) < 0)
	    log_err(0, "redir_accept() failed!");
	
	if (redir->fd[1])
	  if (net_select_read_fd(&sctx, redir->fd[1])==1 && 
	      redir_accept2(redir, 1) < 0)
	    log_err(0, "redir_accept() failed!");
      
	for (idx=0; idx < max_requests; idx++) {

	  /*
	   *  Update remote connections with activity
	   */
	  conn_select_update(&requests[idx].conn, &sctx);

	  /*
	   *  Check client connections with activity
	   */
	  if (requests[idx].inuse && requests[idx].socket_fd) {
	    int fd = requests[idx].socket_fd;
	    
#ifdef HAVE_SSL
	    if (requests[idx].sslcon) {
	      if (openssl_check_accept(requests[idx].sslcon, 0) < 0) {
		log_dbg("ssl error %d", errno);
		redir_conn_finish(&requests[idx].conn, &requests[idx]);
		continue;
	      }
	    }
#endif

	    switch (net_select_write_fd(&sctx, fd)) {
	    case 1:
	      log_dbg("client writeable");
	      redir_cli_rewrite(&requests[idx], &requests[idx].conn);
	      break;
	    }
	    
	    switch (net_select_read_fd(&sctx, fd)) {
	    case -1:
	      log_dbg("EXCEPTION");
	      redir_conn_finish(&requests[idx].conn, 
				&requests[idx]);
	      break;

	    case 1:
	      {
		if (requests[idx].proxy) {
		  char b[PKT_MAX_LEN];
		  int r;
		  
#ifdef HAVE_SSL
		  if (requests[idx].sslcon) {
		    /*
		      log_dbg("proxy_read_ssl");
		    */
		    r = openssl_read(requests[idx].sslcon, 
				     b, sizeof(b)-1, 0);
		  } else
#endif
		    r = safe_read(fd, b, sizeof(b)-1);
		  
		  /*
		    log_dbg("proxy_read: %d %d", fd, r);
		  */
		  
		  if (r <= 0) {

		    log_dbg("recv %d %d %d", r, 
			    requests[idx].conn.read_buf->slen -
			    requests[idx].conn.read_pos,
			    errno);

		    if (!(r == -1 && 
			  (errno == EWOULDBLOCK || errno == EAGAIN))) {
		      if (redir_cli_rewrite(&requests[idx], 
					    &requests[idx].conn) == 0) {
			log_dbg("done reading and writing");
			redir_conn_finish(&requests[idx].conn, 
					  &requests[idx]);
		      }
		    }
		    
		  } else if (r > 0) {

		    int w;
		    requests[idx].last_active = mainclock_tick();
		    w = net_write(requests[idx].conn.sock, b, r);
		    
		    /*
		      log_dbg("proxy_write: %d", w);
		    */
		    if (r != w) {
		      log_err(errno, "problem writing what we read from client");
		      redir_conn_finish(&requests[idx].conn, 
					&requests[idx]);
		    }
		  }
		  
		} else {
#ifdef HAVE_SSL
		go_again:
#endif
		  switch (redir_main(redir, fd, fd, 
				     &requests[idx].conn.peer,
				     &requests[idx].baddr, 
				     requests[idx].uiidx, 
				     &requests[idx])) {
		  case 1:
		    /*log_dbg("redir cont'ed");*/
#ifdef HAVE_SSL
		    if (requests[idx].sslcon && 
			openssl_pending(requests[idx].sslcon) > 0) {
		      log_dbg("ssl_pending, trying again");
		      goto go_again;
		    }
#endif
		  break;
		  case -1: 
		    log_dbg("redir error");
		  default:
		    log_dbg("redir completed");
		    redir_conn_finish(&requests[idx].conn, 
				      &requests[idx]);
		    break;
		  }
		}
	      }
	      break;
	    }
	  }
	}
      }
      
      break;
    }
  }

  redir_free(redir);

  child_killall(SIGKILL);

  selfpipe_finish();
  
  return 0;
}
Пример #22
0
cl_int
compile_and_link_program(int compile_program,
                         int link_program,
                         cl_program program,
                         cl_uint num_devices,
                         const cl_device_id *device_list,
                         const char *options,
                         cl_uint num_input_headers,
                         const cl_program *input_headers,
                         const char **header_include_names,
                         cl_uint num_input_programs,
                         const cl_program *input_programs,
                         void (CL_CALLBACK *pfn_notify) (cl_program program,
                                                         void *user_data),
                         void *user_data)
{
  char program_bc_path[POCL_FILENAME_LENGTH];
  char link_options[512];
  int errcode, error;
  int create_library = 0;
  int requires_cr_sqrt_div = 0;
  int spir_build = 0;
  unsigned flush_denorms = 0;
  uint64_t fsize;
  cl_device_id *unique_devlist = NULL;
  char *binary = NULL;
  unsigned device_i = 0, actually_built = 0;
  size_t i, j;
  char *temp_options = NULL;
  const char *extra_build_options =
    pocl_get_string_option ("POCL_EXTRA_BUILD_FLAGS", NULL);
  int build_error_code
      = (link_program ? CL_BUILD_PROGRAM_FAILURE : CL_COMPILE_PROGRAM_FAILURE);

  POCL_GOTO_LABEL_COND (PFN_NOTIFY, (program == NULL), CL_INVALID_PROGRAM);

  POCL_GOTO_LABEL_COND (PFN_NOTIFY, (num_devices > 0 && device_list == NULL),
                        CL_INVALID_VALUE);
  POCL_GOTO_LABEL_COND (PFN_NOTIFY, (num_devices == 0 && device_list != NULL),
                        CL_INVALID_VALUE);

  POCL_GOTO_LABEL_COND (PFN_NOTIFY, (pfn_notify == NULL && user_data != NULL),
                        CL_INVALID_VALUE);

  POCL_GOTO_LABEL_ON (PFN_NOTIFY, program->kernels, CL_INVALID_OPERATION,
                      "Program already has kernels\n");

  POCL_GOTO_LABEL_ON (PFN_NOTIFY,
                      (program->source == NULL && program->binaries == NULL),
                      CL_INVALID_PROGRAM,
                      "Program doesn't have sources or binaries! You need "
                      "to call clCreateProgramWith{Binary|Source} first\n");

  POCL_GOTO_LABEL_ON (PFN_NOTIFY,
                      ((program->source == NULL) && (link_program == 0)),
                      CL_INVALID_OPERATION,
                      "Cannot clCompileProgram when program has no source\n");

  POCL_LOCK_OBJ (program);

  program->main_build_log[0] = 0;

  /* TODO this should be somehow utilized at linking */
  POCL_MEM_FREE (program->compiler_options);

  if (extra_build_options)
    {
      size_t len = (options != NULL) ? strlen (options) : 0;
      len += strlen (extra_build_options) + 2;
      temp_options = (char *)malloc (len);

      temp_options[0] = 0;
      if (options != NULL)
        {
          strcpy (temp_options, options);
          strcat (temp_options, " ");
        }
      strcat (temp_options, extra_build_options);
    }
  else
    temp_options = (char*) options;

  if (temp_options)
    {
      i = strlen (temp_options);
      size_t size = i + 512; /* add some space for pocl-added options */
      program->compiler_options = (char *)malloc (size);
      errcode = process_options (temp_options, program->compiler_options,
                                 link_options, program, compile_program,
                                 link_program, &create_library, &flush_denorms,
                                 &requires_cr_sqrt_div, &spir_build, size);
      if (errcode != CL_SUCCESS)
        goto ERROR_CLEAN_OPTIONS;
    }

  POCL_MSG_PRINT_LLVM ("building program with options %s\n",
                       program->compiler_options);


  program->flush_denorms = flush_denorms;
#if !(defined(__x86_64__) && defined(__GNUC__))
  if (flush_denorms)
    {
      POCL_MSG_WARN ("flush to zero is currently only implemented for "
                     "x86-64 & gcc/clang, ignoring flag\n");
    }
#endif

  /* DEVICE LIST */
  if (num_devices == 0)
    {
      num_devices = program->num_devices;
      device_list = program->devices;
    }
  else
    {
      // convert subdevices to devices and remove duplicates
      cl_uint real_num_devices = 0;
      unique_devlist = pocl_unique_device_list (device_list, num_devices,
                                                &real_num_devices);
      num_devices = real_num_devices;
      device_list = unique_devlist;
    }

  clean_program_on_rebuild (program);

  /* Build the fully linked non-parallel bitcode for all
         devices. */
  for (device_i = 0; device_i < program->num_devices; ++device_i)
    {
      cl_device_id device = program->devices[device_i];

      /* find the device in the supplied devices-to-build-for list */
      int found = 0;
      for (i = 0; i < num_devices; ++i)
          if (device_list[i] == device) found = 1;
      if (!found) continue;

      if (requires_cr_sqrt_div
          && !(device->single_fp_config & CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT))
        {
          APPEND_TO_MAIN_BUILD_LOG (REQUIRES_CR_SQRT_DIV_ERR);
          POCL_GOTO_ERROR_ON (1, build_error_code,
                              REQUIRES_CR_SQRT_DIV_ERR " %s\n",
                              device->short_name);
        }
      actually_built++;

      /* clCreateProgramWithSource */
      if (program->source)
        {
#ifdef OCS_AVAILABLE
          if (device->compiler_available == CL_TRUE)
            {
              POCL_MSG_PRINT_INFO ("building from sources for device %d\n",
                                   device_i);
              error = pocl_llvm_build_program (
                  program, device_i, program->compiler_options,
                  program_bc_path, num_input_headers, input_headers,
                  header_include_names, (create_library ? 0 : link_program));
              POCL_GOTO_ERROR_ON ((error != 0), build_error_code,
                                  "pocl_llvm_build_program() failed\n");
            }
          else
#endif
            {
              APPEND_TO_MAIN_BUILD_LOG (
                  "Cannot build a program from sources with pocl "
                  "that does not have online compiler support\n");
              POCL_GOTO_ERROR_ON (1, CL_COMPILER_NOT_AVAILABLE, "%s",
                                  program->main_build_log);
            }
        }
      /* clCreateProgramWithBinaries */
      else if (program->binaries[device_i]
               && (program->pocl_binaries[device_i] == NULL))
        {
#ifdef OCS_AVAILABLE
          /* bitcode is now either plain LLVM IR or SPIR IR */
          int spir_binary = bitcode_is_spir ((char*)program->binaries[device_i],
                                             program->binary_sizes[device_i]);
          if (spir_binary)
            POCL_MSG_PRINT_LLVM ("LLVM-SPIR binary detected\n");
          else
            POCL_MSG_PRINT_LLVM ("building from a BC binary for device %d\n",
                                 device_i);

          if (spir_binary)
            {
#ifdef ENABLE_SPIR
              if (!strstr (device->extensions, "cl_khr_spir"))
                {
                  APPEND_TO_MAIN_BUILD_LOG (REQUIRES_SPIR_SUPPORT);
                  POCL_GOTO_ERROR_ON (1, build_error_code,
                                      REQUIRES_SPIR_SUPPORT " %s\n",
                                      device->short_name);
                }
              if (!spir_build)
                POCL_MSG_WARN (
                    "SPIR binary provided, but no spir in build options\n");
              /* SPIR binaries need to be explicitly linked to the kernel
               * library. for non-SPIR binaries this happens as part of build
               * process when program.bc is generated. */
              error
                  = pocl_llvm_link_program (program, device_i, program_bc_path,
                                            0, NULL, NULL, NULL, 0, 1);

              POCL_GOTO_ERROR_ON (error, CL_LINK_PROGRAM_FAILURE,
                                  "Failed to link SPIR program.bc\n");
#else
              APPEND_TO_MAIN_BUILD_LOG (REQUIRES_SPIR_SUPPORT);
              POCL_GOTO_ERROR_ON (1, build_error_code,
                                  REQUIRES_SPIR_SUPPORT " %s\n",
                                  device->short_name);
#endif
            }

#else
          APPEND_TO_MAIN_BUILD_LOG (
              "Cannot build program from LLVM IR binaries with "
              "pocl that does not have online compiler support\n");
          POCL_GOTO_ERROR_ON (1, CL_COMPILER_NOT_AVAILABLE, "%s",
                              program->main_build_log);
#endif
        }
      else if (program->pocl_binaries[device_i])
        {
          POCL_MSG_PRINT_INFO("having a poclbinary for device %d\n", device_i);
#ifdef OCS_AVAILABLE
          if (program->binaries[device_i] == NULL)
            {
              POCL_MSG_WARN (
                  "pocl-binary for this device doesn't contain "
                  "program.bc - you won't be able to rebuild/link it\n");
              /* do not try to read program.bc or LLVM IRs
               * TODO maybe read LLVM IRs ?*/
              continue;
            }
#else
          continue;
#endif
        }
      else if (link_program && (num_input_programs > 0))
        {
#ifdef OCS_AVAILABLE
          /* just link binaries. */
          unsigned char *cur_device_binaries[num_input_programs];
          size_t cur_device_binary_sizes[num_input_programs];
          void *cur_llvm_irs[num_input_programs];
          for (j = 0; j < num_input_programs; j++)
            {
              assert (device == input_programs[j]->devices[device_i]);
              cur_device_binaries[j] = input_programs[j]->binaries[device_i];

              assert (cur_device_binaries[j]);
              cur_device_binary_sizes[j]
                  = input_programs[j]->binary_sizes[device_i];

              if (input_programs[j]->llvm_irs[device_i] == NULL)
                pocl_update_program_llvm_irs (input_programs[j], device_i);

              cur_llvm_irs[j] = input_programs[j]->llvm_irs[device_i];
              assert (cur_llvm_irs[j]);
            }
          error = pocl_llvm_link_program (
              program, device_i, program_bc_path, num_input_programs,
              cur_device_binaries, cur_device_binary_sizes, cur_llvm_irs,
              create_library, 0);
          POCL_GOTO_ERROR_ON ((error != CL_SUCCESS), CL_LINK_PROGRAM_FAILURE,
                              "pocl_llvm_link_program() failed\n");
#else
          POCL_GOTO_ERROR_ON ((1), CL_LINK_PROGRAM_FAILURE,
                              "clCompileProgram/clLinkProgram/clBuildProgram"
                              " require a pocl built with LLVM\n");

#endif
        }
      else
        {
          POCL_GOTO_ERROR_ON (1, CL_INVALID_BINARY,
                              "No sources nor binaries for device %s - can't "
                              "build the program\n", device->short_name);
        }

#ifdef OCS_AVAILABLE
      /* Read binaries from program.bc to memory */
      if (program->binaries[device_i] == NULL)
        {
          errcode = pocl_read_file(program_bc_path, &binary, &fsize);
          POCL_GOTO_ERROR_ON(errcode, CL_BUILD_ERROR,
                             "Failed to read binaries from program.bc to "
                             "memory: %s\n", program_bc_path);

          program->binary_sizes[device_i] = (size_t)fsize;
          program->binaries[device_i] = (unsigned char *)binary;
        }

      if (program->llvm_irs[device_i] == NULL)
        {
          pocl_update_program_llvm_irs(program, device_i);
        }
      /* Maintain a 'last_accessed' file in every program's
       * cache directory. Will be useful for cache pruning script
       * that flushes old directories based on LRU */
      pocl_cache_update_program_last_access(program, device_i);
#endif

    }

  POCL_GOTO_ERROR_ON ((actually_built < num_devices), build_error_code,
                      "Some of the devices on the argument-supplied list are"
                      "not available for the program, or do not exist\n");

  program->build_status = CL_BUILD_SUCCESS;
  program->binary_type = CL_PROGRAM_BINARY_TYPE_EXECUTABLE;
  /* if program will be compiled using clCompileProgram its binary_type
   * will be set to CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT.
   *
   * if program was created by clLinkProgram which is called
   * with the –createlibrary link option its binary_type will be set to
   * CL_PROGRAM_BINARY_TYPE_LIBRARY.
   */
  if (create_library)
    program->binary_type = CL_PROGRAM_BINARY_TYPE_LIBRARY;
  if (compile_program && !link_program)
    program->binary_type = CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT;

  assert(program->num_kernels == 0);

  /* get non-device-specific kernel metadata. We can stop after finding
   * the first method that works.*/
  for (device_i = 0; device_i < program->num_devices; device_i++)
    {
#ifdef OCS_AVAILABLE
      if (program->binaries[device_i])
        {
          program->num_kernels
              = pocl_llvm_get_kernel_count (program, device_i);
          if (program->num_kernels)
            {
              program->kernel_meta = calloc (program->num_kernels,
                                             sizeof (pocl_kernel_metadata_t));
              pocl_llvm_get_kernels_metadata (program, device_i);
            }
          break;
        }
#endif
      if (program->pocl_binaries[device_i])
        {
          program->num_kernels
              = pocl_binary_get_kernel_count (program, device_i);
          if (program->num_kernels)
            {
              program->kernel_meta = calloc (program->num_kernels,
                                             sizeof (pocl_kernel_metadata_t));
              pocl_binary_get_kernels_metadata (program, device_i);
            }
          break;
        }
    }

  POCL_GOTO_ERROR_ON ((device_i >= program->num_devices), CL_INVALID_BINARY,
                      "Could find kernel metadata in the built program\n");

  /* calculate device-specific kernel hashes. */
  for (j = 0; j < program->num_kernels; ++j)
    {
      program->kernel_meta[j].build_hash
          = calloc (program->num_devices, sizeof (pocl_kernel_hash_t));

      for (device_i = 0; device_i < program->num_devices; device_i++)
        {
          pocl_calculate_kernel_hash (program, j, device_i);
        }
    }

  errcode = CL_SUCCESS;
  goto FINISH;

ERROR:
  free_meta (program);

  program->kernels = NULL;

  for (device_i = 0; device_i < program->num_devices; device_i++)
    {
      if (program->source)
        {
          POCL_MEM_FREE (program->binaries[device_i]);
          program->binary_sizes[device_i] = 0;
        }
    }

ERROR_CLEAN_OPTIONS:
  if (temp_options != options)
    free (temp_options);

  program->build_status = CL_BUILD_ERROR;

FINISH:
  POCL_UNLOCK_OBJ (program);
  POCL_MEM_FREE (unique_devlist);

PFN_NOTIFY:
  if (pfn_notify)
    pfn_notify (program, user_data);

  return errcode;
}
Пример #23
0
void write_tcp( tcp_t *tcp, int len )
{
	if(len < sizeof(tcp_t)) {
	  D(bug("<%d> Too small tcp packet(%d) on unknown slot, dropped\r\n", -1, len));
		return;
	}
	uint16 src_port = ntohs(tcp->src_port);
	uint16 dest_port = ntohs(tcp->dest_port);

	BOOL ok = true;
	BOOL handle_data = false;
	BOOL initiate_read = false;

	EnterCriticalSection( &tcp_section );

	int t = find_socket( src_port, dest_port );

	if(t < 0) {
		t = alloc_new_socket( src_port, dest_port, ntohl(tcp->ip.dest) );
		ok = t >= 0;
	}

	if(ok) {
		D(bug("<%d> write_tcp %d bytes from port %d to port %d\r\n", t, len, src_port, dest_port));
	} else {
		D(bug("<%d> FAILED write_tcp %d bytes from port %d to port %d\r\n", t, len, src_port, dest_port));
	}

	if( ok && ISSET(tcp->flags,RST) ) {
		D(bug("<%d> RST set, resetting socket\r\n", t));
		if( sockets[t].s != INVALID_SOCKET ) {
			D(bug("<%d> doing an extra shutdown (ie4)\r\n", t));
			_shutdown( sockets[t].s, SD_BOTH );
		}
		free_socket( t );
		ok = false;
	}

	if(ok) {
		D(bug("<%d> State machine start = %s\r\n", t, STATENAME(sockets[t].state)));

		// always update receive window
		sockets[t].mac_window = ntohs(tcp->window);

		int header_len = tcp->header_len >> 2;
		int option_bytes = header_len - 20;
		char *data = (char *)tcp + sizeof(tcp_t) + option_bytes;
		int dlen = len - sizeof(tcp_t) - option_bytes;

		if( !ISSET(tcp->flags,ACK) ) {
			D(bug("<%d> ACK not set\r\n", t));
		}
		if( ISSET(tcp->flags,SYN) ) {
			D(bug("<%d> SYN set\r\n", t));

			// Note that some options are valid even if there is no SYN.
			// I don't care about those however.

			uint32 new_mss;
			process_options( t, (uint8 *)data - option_bytes, option_bytes, new_mss );
			if(new_mss) {
				sockets[t].mac_mss = (int)new_mss;
				if( new_mss < sockets[t].buffers_read[0].len ) {
					sockets[t].buffers_read[0].len = new_mss;
				}
				D(bug("<%d> Max segment size set to %d\r\n", t, new_mss));
			}
		}
		if( ISSET(tcp->flags,FIN) ) {
			D(bug("<%d> FIN set\r\n", t));
		}

		// The sequence number Mac expects to see next time.
		sockets[t].mac_ack = ntohl(tcp->ack);

		D(bug("<%d> From Mac: Seq=%d, Ack=%d, window=%d, router Seq=%d\r\n", t, ntohl(tcp->seq), sockets[t].mac_ack, sockets[t].mac_window, sockets[t].seq_out));

		if( sockets[t].stream_to_mac_stalled_until && 
				sockets[t].mac_ack == sockets[t].seq_out &&
				(sockets[t].state == ESTABLISHED || sockets[t].state == CLOSE_WAIT) )
		{
			if( has_mac_read_space(t) ) {
				initiate_read = true;
				sockets[t].stream_to_mac_stalled_until = 0;
				D(bug("<%d> read resumed, mac can accept more data\r\n", t));
			}
		}

		switch( sockets[t].state ) {
			case CLOSED:
				sockets[t].src_port = src_port;
				sockets[t].dest_port = dest_port;
				sockets[t].ip_src = ntohl(tcp->ip.src);
				sockets[t].ip_dest = ntohl(tcp->ip.dest);

				if( ISSET(tcp->flags,SYN) ) {

					sockets[t].seq_out = 0x00000001;
					sockets[t].seq_in = ntohl(tcp->seq) + 1;

					_WSAResetEvent( sockets[t].ev );
					if( SOCKET_ERROR == _WSAEventSelect( sockets[t].s, sockets[t].ev, FD_CONNECT | FD_CLOSE ) ) {
						D(bug("<%d> WSAEventSelect() failed with error code %d\r\n", t, _WSAGetLastError()));
					}

				  D(bug("<%d> connecting local port %d to remote %s:%d\r\n", t, src_port, _inet_ntoa(sockets[t].from.sin_addr), dest_port));

					sockets[t].state = LISTEN;
					if( _WSAConnect(
						sockets[t].s,
						(const struct sockaddr *)&sockets[t].from,
						sockets[t].from_len,
						NULL, NULL,
						NULL, NULL
					) == SOCKET_ERROR )
					{
						int connect_error = _WSAGetLastError();
						if( connect_error == WSAEWOULDBLOCK ) {
							D(bug("<%d> WSAConnect() i/o pending.\r\n", t));
						} else {
							D(bug("<%d> WSAConnect() failed with error %d.\r\n", t, connect_error));
						}
					} else {
						D(bug("<%d> WSAConnect() ok.\r\n", t));
					}
				} else {
					if( ISSET(tcp->flags,FIN) ) {
						D(bug("<%d> No SYN but FIN on a closed socket.\r\n", t));
						free_socket(t);
					} else {
						D(bug("<%d> No SYN on a closed socket. resetting.\r\n", t));
						free_socket(t);
					}
				}
				break;
			case LISTEN:
				// handled in connect callback
				break;
			case SYN_SENT:
				if( ISSET(tcp->flags,SYN) && ISSET(tcp->flags,ACK) ) {
					sockets[t].seq_in = ntohl(tcp->seq) + 1;
					tcp_reply( ACK, t );
					sockets[t].state = ESTABLISHED;
					initiate_read = true;
					sockets[t].accept_more_data_from_mac = true;
					sockets[t].time_wait = 0;
				} else if( ISSET(tcp->flags,SYN) ) {
					sockets[t].seq_in = ntohl(tcp->seq) + 1;
					tcp_reply( ACK|SYN, t );
					sockets[t].seq_out++;
					sockets[t].state = SYN_RCVD;
					sockets[t].time_wait = 0;
				} else if( ISSET(tcp->flags,ACK) ) {
					// What was the bright idea here.
					D(bug("<%d> State is SYN_SENT, but got only ACK from Mac??\r\n", t));
					sockets[t].state = FINWAIT_2;
					sockets[t].time_wait = 0;
				}
				break;
			case SYN_RCVD:
				if( ISSET(tcp->flags,ACK) ) {
					sockets[t].state = ESTABLISHED;
					handle_data = true;
					initiate_read = true;
					sockets[t].accept_more_data_from_mac = true;
				}
				break;
			case ESTABLISHED:
				if( ISSET(tcp->flags,FIN) ) {
					sockets[t].seq_in++;
					tcp_reply( ACK, t );
					_shutdown( sockets[t].s, SD_SEND );
					sockets[t].state = CLOSE_WAIT;
				}
				handle_data = true;
				break;
			case CLOSE_WAIT:
				// handled in tcp_read_completion
				break;
			case LAST_ACK:
				if( ISSET(tcp->flags,ACK) ) {
					D(bug("<%d> LAST_ACK received, socket closed\r\n", t));
					free_socket( t );
				}
				break;
			case FINWAIT_1:
				if( ISSET(tcp->flags,FIN) && ISSET(tcp->flags,ACK) ) {
					sockets[t].seq_in++;
					tcp_reply( ACK, t );
					if(sockets[t].remote_closed) {
						_closesocket(sockets[t].s);
						sockets[t].s = INVALID_SOCKET;
					} else {
						_shutdown( sockets[t].s, SD_SEND );
					}
					sockets[t].state = TIME_WAIT;
					sockets[t].time_wait = GetTickCount() + 2 * sockets[t].msl;
				} else if( ISSET(tcp->flags,FIN) ) {
					sockets[t].seq_in++;
					tcp_reply( ACK, t );
					if(sockets[t].remote_closed) {
						_closesocket(sockets[t].s);
						sockets[t].s = INVALID_SOCKET;
					} else {
						_shutdown( sockets[t].s, SD_SEND );
					}
					sockets[t].state = CLOSING;
				} else if( ISSET(tcp->flags,ACK) ) {
					sockets[t].state = FINWAIT_2;
				}
				break;
			case FINWAIT_2:
				if( ISSET(tcp->flags,FIN) ) {
					sockets[t].seq_in++;
					tcp_reply( ACK, t );
					if(sockets[t].remote_closed) {
						_closesocket(sockets[t].s);
						sockets[t].s = INVALID_SOCKET;
					} else {
						_shutdown( sockets[t].s, SD_SEND );
					}
					sockets[t].state = TIME_WAIT;
					sockets[t].time_wait = GetTickCount() + 2 * sockets[t].msl;
				}
				break;
			case CLOSING:
				if( ISSET(tcp->flags,ACK) ) {
					sockets[t].state = TIME_WAIT;
					sockets[t].time_wait = GetTickCount() + 2 * sockets[t].msl;
				}
				break;
			case TIME_WAIT:
				// Catching stray packets: wait MSL * 2 seconds, -> CLOSED
				// Timer already set since we might not get here at all.
				// I'm using exceptionally low MSL value (5 secs).
				D(bug("<%d> time wait, datagram discarded\r\n", t));
				break;
		}

		// The "t" descriptor may already be freed. However, it's safe
		// to peek the state value inside the critical section.
		D(bug("<%d> State machine end = %s\r\n", t, STATENAME(sockets[t].state)));

		D(bug("<%d> handle_data=%d, initiate_read=%d\r\n", t, handle_data, initiate_read));

		if( handle_data && dlen && sockets[t].accept_more_data_from_mac ) {
			if( sockets[t].seq_in != ntohl(tcp->seq) ) {
				D(bug("<%d> dropping duplicate datagram seq=%d, expected=%d\r\n", t, ntohl(tcp->seq), sockets[t].seq_in));
			} else {
				set_ttl( t, tcp->ip.ttl );

				struct sockaddr_in to;
				memset( &to, 0, sizeof(to) );
				to.sin_family = AF_INET;
				to.sin_port = tcp->dest_port;
				to.sin_addr.s_addr = tcp->ip.dest;

				D(bug("<%d> sending %d bytes to remote host\r\n", t, dlen));

				sockets[t].accept_more_data_from_mac = false;

				if( dlen > MAX_SEGMENT_SIZE ) {
					D(bug("<%d> IMPOSSIBLE: b_send() dropped %d bytes! \r\n", t, dlen-MAX_SEGMENT_SIZE));
					dlen = MAX_SEGMENT_SIZE;
				}

				memcpy( sockets[t].buffers_write[0].buf, data, dlen );

				sockets[t].buffers_write[0].len = dlen;
				sockets[t].bytes_remaining_to_send = dlen;
				sockets[t].bytes_to_send = dlen;

				bool send_now = false;
				if( ISSET(tcp->flags,PSH) ) {
					send_now = true;
				} else {
					// todo -- delayed send
					send_now = true;
				}
				
				if(send_now) {

					// Patch ftp server or client address if needed.

					int lst = 1;
					bool is_pasv;
					uint16 ftp_data_port = 0;

					if(ftp_is_ftp_port(sockets[t].src_port)) {
						// Local ftp server may be entering to passive mode.
						is_pasv = true;
						ftp_parse_port_command( 
							sockets[t].buffers_write[0].buf,
							dlen,
							ftp_data_port,
							is_pasv
						);
					} else if(ftp_is_ftp_port(sockets[t].dest_port)) {
						// Local ftp client may be using port command.
						is_pasv = false;
						ftp_parse_port_command( 
							sockets[t].buffers_write[0].buf,
							dlen,
							ftp_data_port,
							is_pasv
						);
					}

					if(ftp_data_port) {
						D(bug("<%d> ftp %s command detected, port %d\r\n", t, (is_pasv ? "SERVER PASV REPLY" : "CLIENT PORT"), ftp_data_port ));

						// Note: for security reasons, only allow incoming connection from sockets[t].ip_dest
						lst = alloc_listen_socket( ftp_data_port, sockets[t].ip_dest, 0/*iface*/, true );

						if(lst < 0) {
							D(bug("<%d> no more free slots\r\n", t));
						} else {
							// First start listening (need to know the local name later)
							tcp_start_listen( lst );

							// When t is closed, lst must be closed too.
							sockets[t].child = lst;
							l_sockets[lst].parent = t;

							// Find out the local name
							struct sockaddr_in name;
							int namelen = sizeof(name);
							memset( &name, 0, sizeof(name) );
							if( _getsockname( sockets[t].s, (struct sockaddr *)&name, &namelen ) == SOCKET_ERROR ) {
								D(bug("_getsockname() failed, error=%d\r\n", _WSAGetLastError() ));
							}

							ftp_modify_port_command( 
								sockets[t].buffers_write[0].buf,
								dlen,
								MAX_SEGMENT_SIZE,
								ntohl(name.sin_addr.s_addr),
								ftp_data_port,
								is_pasv
							);

							sockets[t].buffers_write[0].len = dlen;
							sockets[t].bytes_remaining_to_send = dlen;
							// Do not change "bytes_to_send" field as it is used for ack calculation
						}
					} // end of ftp patch

					if(!b_send(t)) {
						// on error, close the ftp data listening socket if one was created
						if(lst >= 0) {
							D(bug("[%d] closing listening port %d after write error\r\n", t, l_sockets[lst].port));
							_closesocket( l_sockets[lst].s );
							l_sockets[lst].s = INVALID_SOCKET;
							l_sockets[lst].port = 0;
							l_sockets[lst].ip = 0;
							l_sockets[lst].parent = -1;
							sockets[t].child = -1;
						}
					}
				}
			}
		}

		if(initiate_read) {
			if(!b_recfrom(t)) {
				// post icmp error message
			}
		}
	}

	LeaveCriticalSection( &tcp_section );
}
Пример #24
0
int main(int argc, char **argv)
{
	sigset_t sigset;
	int signum = SIGALRM;
	int mode;
	struct thread_param *par;
	struct thread_stat *stat;
	pthread_attr_t thattr;
	int i, ret = -1;

#ifndef __XENO__
	if (geteuid()) {
		printf("need to run as root!\n");
		exit(-1);
	}
#endif

	mlockall(MCL_CURRENT | MCL_FUTURE);

	if (CONFIG_XENO_DEFAULT_PERIOD > 1000000)
		interval = CONFIG_XENO_DEFAULT_PERIOD;
	else
		interval = 1000000;
	distance = interval / 2;

	process_options(argc, argv);

	mode = use_nanosleep + use_system;

       	sigemptyset(&sigset);
       	sigaddset(&sigset, signum);
   	sigprocmask (SIG_BLOCK, &sigset, NULL);

	signal(SIGINT, sighand);
	signal(SIGTERM, sighand);

	par = calloc(num_threads, sizeof(struct thread_param));
	if (!par)
		goto out;
	stat = calloc(num_threads, sizeof(struct thread_stat));
	if (!stat)
		goto outpar;

	clock_gettime(clocksources[clocksel], &start);

	for (i = 0; i < num_threads; i++) {
		if (verbose) {
			stat[i].values = calloc(VALBUF_SIZE, sizeof(long));
			if (!stat[i].values)
				goto outall;
			par[i].bufmsk = VALBUF_SIZE - 1;
		}

		par[i].prio = priority;
		if (priority)
			priority--;
		par[i].clock = clocksources[clocksel];
		par[i].mode = mode;
		par[i].timermode = timermode;
		par[i].signal = signum;
		par[i].interval = interval;
		interval += distance;
		par[i].max_cycles = max_cycles;
		par[i].stats = &stat[i];
		stat[i].min = 1000000;
		stat[i].max = -1000000;
		stat[i].avg = 0.0;
		pthread_attr_init(&thattr);
		pthread_attr_setstacksize(&thattr, 131072);
		pthread_create(&stat[i].thread, &thattr, timerthread, &par[i]);
		stat[i].threadstarted = 1;
		stat[i].traced = (i == 0 && IPIPE_TRACE > 0);
	}

	while (!test_shutdown) {
		char lavg[256];
		int fd, len, allstopped;

		if (!verbose && !quiet) {
			fd = open("/proc/loadavg", O_RDONLY, 0666);
			len = read(fd, &lavg, 255);
			close(fd);
			lavg[len-1] = 0x0;
			printf("%s          \n\n", lavg);
		}

		allstopped = max_cycles ? 1 : 0;

		for (i = 0; i < num_threads; i++) {
			print_stat(&par[i], i, verbose);
			if (stat[i].cycles < max_cycles)
				allstopped = 0;
		}
		usleep(10000);
		if (test_shutdown || allstopped == num_threads)
			break;
		if (!verbose && !quiet)
			printf("\033[%dA", num_threads + 2);
	}
	if (quiet) {
		quiet = 0; /* Now we want to output the statistics */
		for (i = 0; i < num_threads; i++) {
			print_stat(&par[i], i, verbose);
		}
	}
	ret = 0;
 outall:
	test_shutdown = 1;
	for (i = 0; i < num_threads; i++) {
		if (stat[i].threadstarted > 0)
			pthread_kill(stat[i].thread, SIGTERM);
		if (stat[i].threadstarted)
			pthread_join(stat[i].thread, NULL);
		if (stat[i].values)
			free(stat[i].values);
	}
	free(stat);
 outpar:
	free(par);
 out:
	exit(ret);
}
Пример #25
0
int
main (int argc, char *argv[])
{
    int i, numprocs, rank, size;
    int skip;
    double latency = 0.0, t_start = 0.0, t_stop = 0.0;
    double timer=0.0;
    double avg_time = 0.0, max_time = 0.0, min_time = 0.0;
    char * sendbuf = NULL, * recvbuf = NULL;
    int po_ret;
    size_t bufsize;

    set_header(HEADER);
    set_benchmark_name("osu_gather");
    enable_accel_support();
    po_ret = process_options(argc, argv);

    if (po_okay == po_ret && none != options.accel) {
        if (init_accel()) {
            fprintf(stderr, "Error initializing device\n");
            exit(EXIT_FAILURE);
        }
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    switch (po_ret) {
        case po_bad_usage:
            print_bad_usage_message(rank);
            MPI_Finalize();
            exit(EXIT_FAILURE);
        case po_help_message:
            print_help_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_version_message:
            print_version_message(rank);
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_okay:
            break;
    }

    if(numprocs < 2) {
        if (rank == 0) {
            fprintf(stderr, "This test requires at least two processes\n");
        }

        MPI_Finalize();
        exit(EXIT_FAILURE);
    }

    if ((options.max_message_size * numprocs) > options.max_mem_limit) {
        options.max_message_size = options.max_mem_limit / numprocs;
    }

    if (0 == rank) {
        bufsize = options.max_message_size * numprocs;
        if (allocate_buffer((void**)&recvbuf, bufsize, options.accel)) {
            fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
            MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
        }
        set_buffer(recvbuf, options.accel, 1, bufsize);
    }

    if (allocate_buffer((void**)&sendbuf, options.max_message_size,
                options.accel)) {
        fprintf(stderr, "Could Not Allocate Memory [rank %d]\n", rank);
        MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
    }
    set_buffer(sendbuf, options.accel, 0, options.max_message_size);

    print_preamble(rank);

    for (size=1; size <= options.max_message_size; size *= 2) {
        if (size > LARGE_MESSAGE_SIZE) {
            skip = SKIP_LARGE;
            options.iterations = options.iterations_large;
        } else {
            skip = SKIP;
        }

        MPI_Barrier(MPI_COMM_WORLD);
        timer=0.0;

        for (i=0; i < options.iterations + skip ; i++) {
            t_start = MPI_Wtime();
            MPI_Gather(sendbuf, size, MPI_CHAR, recvbuf, size, MPI_CHAR, 0,
                    MPI_COMM_WORLD);
            t_stop = MPI_Wtime();

            if (i >= skip) {
                timer+=t_stop-t_start;
            }
            MPI_Barrier(MPI_COMM_WORLD);
        }
        latency = (double)(timer * 1e6) / options.iterations;

        MPI_Reduce(&latency, &min_time, 1, MPI_DOUBLE, MPI_MIN, 0,
                MPI_COMM_WORLD);
        MPI_Reduce(&latency, &max_time, 1, MPI_DOUBLE, MPI_MAX, 0,
                MPI_COMM_WORLD);
        MPI_Reduce(&latency, &avg_time, 1, MPI_DOUBLE, MPI_SUM, 0,
                MPI_COMM_WORLD);
        avg_time = avg_time/numprocs;

        print_stats(rank, size, avg_time, min_time, max_time);
        MPI_Barrier(MPI_COMM_WORLD);
    }

    if (0 == rank) {
        free_buffer(recvbuf, options.accel);
    }
    free_buffer(sendbuf, options.accel);

    MPI_Finalize();

    if (none != options.accel) {
        if (cleanup_accel()) {
            fprintf(stderr, "Error cleaning up device\n");
            exit(EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}
Пример #26
0
int
impl::app::run(int argc, char* const* argv)
{
    PRE(argc > 0);
    PRE(argv != NULL);

    m_argc = argc;
    m_argv = argv;

    m_argv0 = m_argv[0];

    m_prog_name = std::strrchr(m_argv[0], '/');
    if (m_prog_name == NULL)
        m_prog_name = m_argv[0];
    else
        m_prog_name++;

    // Libtool workaround: if running from within the source tree (binaries
    // that are not installed yet), skip the "lt-" prefix added to files in
    // the ".libs" directory to show the real (not temporary) name.
    if (std::strncmp(m_prog_name, "lt-", 3) == 0)
        m_prog_name += 3;

    const std::string bug =
        std::string("This is probably a bug in ") + m_prog_name +
        " or one of the libraries it uses.  Please report this problem to "
        PACKAGE_BUGREPORT " and provide as many details as possible "
        "describing how you got to this condition.";

    int errcode;
    try {
        int oldargc = m_argc;

        process_options();

        if (m_hflag) {
            INV(m_use_ui);
            if (oldargc != 2)
                throw usage_error("-h must be given alone.");

            usage(std::cout);
            errcode = EXIT_SUCCESS;
        } else
            errcode = main();
    } catch (const usage_error& e) {
        if (m_use_ui) {
            std::cerr << ui::format_error(m_prog_name, e.what()) << "\n"
                      << ui::format_info(m_prog_name, std::string("Type `") +
                                         m_prog_name + " -h' for more details.")
                      << "\n";
        } else {
            std::cerr << m_prog_name << ": ERROR: " << e.what() << "\n";
            std::cerr << m_prog_name << ": See " << m_manpage << " for usage "
                "details.\n";
        }
        errcode = EXIT_FAILURE;
    } catch (const std::runtime_error& e) {
        if (m_use_ui) {
            std::cerr << ui::format_error(m_prog_name, std::string(e.what()))
                      << "\n";
        } else {
            std::cerr << m_prog_name << ": ERROR: " << e.what() << "\n";
        }
        errcode = EXIT_FAILURE;
    } catch (const std::exception& e) {
        if (m_use_ui) {
            std::cerr << ui::format_error(m_prog_name, std::string("Caught "
                "unexpected error: ") + e.what() + "\n" + bug) << "\n";
        } else {
            std::cerr << m_prog_name << ": ERROR: Caught unexpected error: "
                      << e.what() << "\n";
        }
        errcode = EXIT_FAILURE;
    } catch (...) {
        if (m_use_ui) {
            std::cerr << ui::format_error(m_prog_name, std::string("Caught "
                "unknown error\n") + bug) << "\n";
        } else {
            std::cerr << m_prog_name << ": ERROR: Caught unknown error\n";
        }
        errcode = EXIT_FAILURE;
    }
    return errcode;
}
Пример #27
0
int
main (int argc, char *argv[])
{
    int myid, numprocs, i, j;
    int size;
    char *s_buf, *r_buf;
    double t_start = 0.0, t_end = 0.0, t = 0.0;
    int loop = 100;
    int window_size = 64;
    int skip = 10;
    int po_ret = process_options(argc, argv);

    if (po_okay == po_ret && cuda == options.accel) {
        if (init_cuda_context()) {
            fprintf(stderr, "Error initializing cuda context\n");
            exit(EXIT_FAILURE);
        }
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);

    if (0 == myid) {
        switch (po_ret) {
            case po_cuda_not_avail:
                fprintf(stderr, "CUDA support not enabled.  Please recompile "
                        "benchmark with CUDA support.\n");
                break;
            case po_openacc_not_avail:
                fprintf(stderr, "OPENACC support not enabled.  Please "
                        "recompile benchmark with OPENACC support.\n");
                break;
            case po_bad_usage:
            case po_help_message:
                usage();
                break;
        }
    }

    switch (po_ret) {
        case po_cuda_not_avail:
        case po_openacc_not_avail:
        case po_bad_usage:
            MPI_Finalize();
            exit(EXIT_FAILURE);
        case po_help_message:
            MPI_Finalize();
            exit(EXIT_SUCCESS);
        case po_okay:
            break;
    }

    if(numprocs != 2) {
        if(myid == 0) {
            fprintf(stderr, "This test requires exactly two processes\n");
        }

        MPI_Finalize();
        exit(EXIT_FAILURE);
    }

    if (allocate_memory(&s_buf, &r_buf, myid)) {
        /* Error allocating memory */
        MPI_Finalize();
        exit(EXIT_FAILURE);
    }

    print_header(myid);

    /* Bandwidth test */
    for(size = 1; size <= MAX_MSG_SIZE; size *= 2) {
        touch_data(s_buf, r_buf, myid, size);

        if(size > LARGE_MESSAGE_SIZE) {
            loop = LOOP_LARGE;
            skip = SKIP_LARGE;
            window_size = WINDOW_SIZE_LARGE;
        }

        if(myid == 0) {
            for(i = 0; i < loop + skip; i++) {
                if(i == skip) {
                    t_start = MPI_Wtime();
                }

                for(j = 0; j < window_size; j++) {
                    MPI_Isend(s_buf, size, MPI_CHAR, 1, 100, MPI_COMM_WORLD,
                            request + j);
                }

                MPI_Waitall(window_size, request, reqstat);
                MPI_Recv(r_buf, 4, MPI_CHAR, 1, 101, MPI_COMM_WORLD,
                        &reqstat[0]);
            }

            t_end = MPI_Wtime();
            t = t_end - t_start;
        }

        else if(myid == 1) {
            for(i = 0; i < loop + skip; i++) {
                for(j = 0; j < window_size; j++) {
                    MPI_Irecv(r_buf, size, MPI_CHAR, 0, 100, MPI_COMM_WORLD,
                            request + j);
                }

                MPI_Waitall(window_size, request, reqstat);
                MPI_Send(s_buf, 4, MPI_CHAR, 0, 101, MPI_COMM_WORLD);
            }
        }

        if(myid == 0) {
            double tmp = size / 1e6 * loop * window_size;

            fprintf(stdout, "%-*d%*.*f\n", 10, size, FIELD_WIDTH,
                    FLOAT_PRECISION, tmp / t);
            fflush(stdout);
        }
    }

    free_memory(s_buf, r_buf, myid);
    MPI_Finalize();

    if (cuda == options.accel) {
        if (destroy_cuda_context()) {
            fprintf(stderr, "Error destroying cuda context\n");
            exit(EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}
Пример #28
0
int
main (int argc, char *argv[])
{
    char *p, *t;
    char buf[BUFSIZE];
    char *username;
    char *group;
    int err = 0;
    const char *groups[512];
    int n;

    if (argc > 0) {	/* should always be true */
	myname=strrchr(argv[0],'/');
	if (myname==NULL)
	    myname=argv[0];
    } else {
        myname="(unknown)";
    }
    mypid=getpid();

    /* make standard output line buffered */
    setvbuf (stdout, NULL, _IOLBF, 0);

    /* Check Command Line */
    process_options(argc, argv);

    debug("External ACL winbindd group helper build " __DATE__ ", " __TIME__
    " starting up...\n");
    if (use_case_insensitive_compare)
        debug("Warning: running in case insensitive mode !!!\n");
 
    check_winbindd();

    /* Main Loop */
    while (fgets (buf, BUFSIZE, stdin))
    {
	if (NULL == strchr(buf, '\n')) {
	    err = 1;
	    continue;
	}
	if (err) {
	    warn("Oversized message\n");
	    goto error;
	}
	
	if ((p = strchr(buf, '\n')) != NULL)
	    *p = '\0';		/* strip \n */
	if ((p = strchr(buf, '\r')) != NULL)
	    *p = '\0';		/* strip \r */

	debug("Got '%s' from Squid (length: %d).\n",buf,strlen(buf));
	
	if (buf[0] == '\0') {
	    warn("Invalid Request\n");
	    goto error;
	}

	username = strwordtok(buf, &t);
	for (n = 0; (group = strwordtok(NULL, &t)) != NULL; n++)
	    groups[n] = group;
	groups[n] = NULL;

        if (NULL == username) {
            warn("Invalid Request\n");
            goto error;
        }

	if (Valid_Groups(username, groups)) {
	    printf ("OK\n");
	} else {
error:
	    printf ("ERR\n");
	}
	err = 0;
    }
    return 0;
}
Пример #29
0
int main(int argc, char* argv[])
{
   /* Scanner_p       in;     */
   CLState_p       state;
   Scanner_p       in; 
   PCLProt_p       prot;
   long            steps, proof_steps, neg_steps;
   int             i;

   assert(argv[0]);

   InitIO(NAME);
   ESignalSetup(SIGTERM);
   ESignalSetup(SIGINT);
   
   /* We need consistent name->var mappings here because we
      potentially read the compressed input format. */
   ClausesHaveLocalVariables = false;

   state = process_options(argc, argv);

   GlobalOut = OutOpen(outname);
   OpenGlobalOut(outname);
   prot = PCLProtAlloc();

   if(state->argc ==  0)
   {
      CLStateInsertArg(state, "-");
   }
   steps = 0;
   for(i=0; state->argv[i]; i++)
   {
      in = CreateScanner(StreamTypeFile, state->argv[i], true, NULL);
      ScannerSetFormat(in, TPTPFormat);
      steps+=PCLProtParse(in, prot);
      CheckInpTok(in, NoToken);
      DestroyScanner(in); 
   }
   VERBOUT2("PCL input read\n");

   PCLProtStripFOF(prot);
   PCLProtResetTreeData(prot, false);
   PCLProtMarkProofClauses(prot);
   PCLProtProofDistance(prot);
   PCLProtUpdateGRefs(prot);
   proof_steps = PCLProtCountProp(prot, PCLIsProofStep);
   neg_steps = proof_steps?neg_proportion*proof_steps:neg_examples;
   PCLProtSelectExamples(prot, neg_steps);
   fprintf(GlobalOut, "# Axioms:\n");
   PCLProtPrintPropClauses(GlobalOut, prot, PCLIsInitial, lop_format);  
   fprintf(GlobalOut, ".\n\n# Examples:\n");  
   PCLProtPrintExamples(GlobalOut, prot);

   PCLProtFree(prot);
   
   CLStateFree(state);
   
   fflush(GlobalOut);
   OutClose(GlobalOut);
   ExitIO();
   
#ifdef CLB_MEMORY_DEBUG
   MemFlushFreeList();
   MemDebugPrintStats(stdout);
#endif
   
   return EXIT_SUCCESS;
}
/*
 * Main program
 */
int main(int argc, char * const argv[])
{
	unsigned long ofs, end_addr = 0;
	unsigned long long blockstart = 1;
	int ret, i, fd, ofd, bs, badblock = 0;
	struct mtd_oob_buf oob = {0, 16, oobbuf};
	mtd_info_t meminfo;
	char pretty_buf[80];
	int oobinfochanged = 0 ;
	struct nand_oobinfo old_oobinfo;
	struct mtd_ecc_stats stat1, stat2;
	bool eccstats = false;

	process_options(argc, argv);

	/* Open MTD device */
	if ((fd = open(mtddev, O_RDONLY)) == -1) {
		perror(mtddev);
		exit (EXIT_FAILURE);
	}

	/* Fill in MTD device capability structure */
	if (ioctl(fd, MEMGETINFO, &meminfo) != 0) {
		perror("MEMGETINFO");
		close(fd);
		exit (EXIT_FAILURE);
	}

	/* Make sure device page sizes are valid */
	if (!(meminfo.oobsize == 128 && meminfo.writesize == 4096) &&
			!(meminfo.oobsize == 64 && meminfo.writesize == 2048) &&
			!(meminfo.oobsize == 32 && meminfo.writesize == 1024) &&
			!(meminfo.oobsize == 16 && meminfo.writesize == 512) &&
			!(meminfo.oobsize == 8 && meminfo.writesize == 256)) {
		fprintf(stderr, "Unknown flash (not normal NAND)\n");
		close(fd);
		exit(EXIT_FAILURE);
	}
	/* Read the real oob length */
	oob.length = meminfo.oobsize;

	if (noecc)  {
		ret = ioctl(fd, MTDFILEMODE, (void *) MTD_MODE_RAW);
		if (ret == 0) {
			oobinfochanged = 2;
		} else {
			switch (errno) {
			case ENOTTY:
				if (ioctl (fd, MEMGETOOBSEL, &old_oobinfo) != 0) {
					perror ("MEMGETOOBSEL");
					close (fd);
					exit (EXIT_FAILURE);
				}
				if (ioctl (fd, MEMSETOOBSEL, &none_oobinfo) != 0) {
					perror ("MEMSETOOBSEL");
					close (fd);
					exit (EXIT_FAILURE);
				}
				oobinfochanged = 1;
				break;
			default:
				perror ("MTDFILEMODE");
				close (fd);
				exit (EXIT_FAILURE);
			}
		}
	} else {

		/* check if we can read ecc stats */
		if (!ioctl(fd, ECCGETSTATS, &stat1)) {
			eccstats = true;
			if (!quiet) {
				fprintf(stderr, "ECC failed: %d\n", stat1.failed);
				fprintf(stderr, "ECC corrected: %d\n", stat1.corrected);    
				fprintf(stderr, "Number of bad blocks: %d\n", stat1.badblocks);    
				fprintf(stderr, "Number of bbt blocks: %d\n", stat1.bbtblocks);    
			}
		} else
			perror("No ECC status information available");
	}

	/* Open output file for writing. If file name is "-", write to standard
	 * output. */
	if (!dumpfile) {
		ofd = STDOUT_FILENO;
	} else if ((ofd = open(dumpfile, O_WRONLY | O_TRUNC | O_CREAT, 0644))== -1) {
		perror (dumpfile);
		close(fd);
		exit(EXIT_FAILURE);
	}

	/* Initialize start/end addresses and block size */
	if (length)
		end_addr = start_addr + length;
	if (!length || end_addr > meminfo.size)
		end_addr = meminfo.size;

	bs = meminfo.writesize;

	/* Print informative message */

	if (!quiet) {
		fprintf(stderr, "Block size %u, page size %u, OOB size %u\n",
				meminfo.erasesize, meminfo.writesize, meminfo.oobsize);
		fprintf(stderr,
				"Dumping data starting at 0x%08x and ending at 0x%08x...\n",
				(unsigned int) start_addr, (unsigned int) end_addr);
	}
	/* Dump the flash contents */
	for (ofs = start_addr; ofs < end_addr ; ofs+=bs) {

		// new eraseblock , check for bad block
		if (blockstart != (ofs & (~meminfo.erasesize + 1))) {
			blockstart = ofs & (~meminfo.erasesize + 1);
			if ((badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart)) < 0) {
				perror("ioctl(MEMGETBADBLOCK)");
				goto closeall;
			}
		}

		if (badblock) {
			if (omitbad)
				continue;
			memset (readbuf, 0xff, bs);
		} else {
			/* Read page data and exit on failure */
			if (pread(fd, readbuf, bs, ofs) != bs) {
				perror("pread");
				goto closeall;
			}
		}

		/* ECC stats available ? */
		if (eccstats) {
			if (ioctl(fd, ECCGETSTATS, &stat2)) {
				perror("ioctl(ECCGETSTATS)");
				goto closeall;
			}
			if (stat1.failed != stat2.failed)
				fprintf(stderr, "ECC: %d uncorrectable bitflip(s)"
						" at offset 0x%08lx\n",
						stat2.failed - stat1.failed, ofs);
			if (stat1.corrected != stat2.corrected)
				fprintf(stderr, "ECC: %d corrected bitflip(s) at"
						" offset 0x%08lx\n",
						stat2.corrected - stat1.corrected, ofs);
			stat1 = stat2;
		}

		/* Write out page data */
		if (pretty_print) {
			for (i = 0; i < bs; i += 16) {
				sprintf(pretty_buf,
						"0x%08x: %02x %02x %02x %02x %02x %02x %02x "
						"%02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
						(unsigned int) (ofs + i),  readbuf[i],
						readbuf[i+1], readbuf[i+2],
						readbuf[i+3], readbuf[i+4],
						readbuf[i+5], readbuf[i+6],
						readbuf[i+7], readbuf[i+8],
						readbuf[i+9], readbuf[i+10],
						readbuf[i+11], readbuf[i+12],
						readbuf[i+13], readbuf[i+14],
						readbuf[i+15]);
				write(ofd, pretty_buf, 60);
			}
		} else
			write(ofd, readbuf, bs);



		if (omitoob)
			continue;

		if (badblock) {
			memset (readbuf, 0xff, meminfo.oobsize);
		} else {
			/* Read OOB data and exit on failure */
			oob.start = ofs;
			if (ioctl(fd, MEMREADOOB, &oob) != 0) {
				perror("ioctl(MEMREADOOB)");
				goto closeall;
			}
		}

		/* Write out OOB data */
		if (pretty_print) {
			if (meminfo.oobsize < 16) {
				sprintf(pretty_buf, "  OOB Data: %02x %02x %02x %02x %02x %02x "
						"%02x %02x\n",
						oobbuf[0], oobbuf[1], oobbuf[2],
						oobbuf[3], oobbuf[4], oobbuf[5],
						oobbuf[6], oobbuf[7]);
				write(ofd, pretty_buf, 48);
				continue;
			}

			for (i = 0; i < meminfo.oobsize; i += 16) {
				sprintf(pretty_buf, "  OOB Data: %02x %02x %02x %02x %02x %02x "
						"%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
						oobbuf[i], oobbuf[i+1], oobbuf[i+2],
						oobbuf[i+3], oobbuf[i+4], oobbuf[i+5],
						oobbuf[i+6], oobbuf[i+7], oobbuf[i+8],
						oobbuf[i+9], oobbuf[i+10], oobbuf[i+11],
						oobbuf[i+12], oobbuf[i+13], oobbuf[i+14],
						oobbuf[i+15]);
				write(ofd, pretty_buf, 60);
			}
		} else
			write(ofd, oobbuf, meminfo.oobsize);
	}

	/* reset oobinfo */
	if (oobinfochanged == 1) {
		if (ioctl (fd, MEMSETOOBSEL, &old_oobinfo) != 0) {
			perror ("MEMSETOOBSEL");
			close(fd);
			close(ofd);
			return EXIT_FAILURE;
		}
	}
	/* Close the output file and MTD device */
	close(fd);
	close(ofd);

	/* Exit happy */
	return EXIT_SUCCESS;

closeall:
	/* The new mode change is per file descriptor ! */
	if (oobinfochanged == 1) {
		if (ioctl (fd, MEMSETOOBSEL, &old_oobinfo) != 0)  {
			perror ("MEMSETOOBSEL");
		}
	}
	close(fd);
	close(ofd);
	exit(EXIT_FAILURE);
}