Esempio n. 1
0
void
parsefile(char *const *argv, const char *cwd, const char *root, const char *dbpath, int db)
{
	int count = 0;
	int flags = 0;
	STRBUF *sb = strbuf_open(0);
	char *langmap;
	const char *plugin_parser, *av;
	char path[MAXPATHLEN];
	struct parsefile_data data;

	flags = 0;
	if (vflag)
		flags |= PARSER_VERBOSE;
	if (debug)
		flags |= PARSER_DEBUG;
	/*
	if (wflag)
		flags |= PARSER_WARNING;
	*/
	if (db == GRTAGS + GSYMS)
		data.target = TARGET_REF|TARGET_SYM;
	else
		data.target = 1 << db;
	data.extractmethod = getconfb("extractmethod");
	if (getconfs("langmap", sb))
		langmap = check_strdup(strbuf_value(sb));
	else
		langmap = NULL;
	strbuf_reset(sb);
	if (getconfs("gtags_parser", sb))
		plugin_parser = strbuf_value(sb);
	else
		plugin_parser = NULL;
	data.cv = convert_open(type, format, root, cwd, dbpath, stdout, db);
	if (gpath_open(dbpath, 0) < 0)
		die("GPATH not found.");
	if (data.target == TARGET_REF || data.target == TARGET_SYM) {
		data.dbop = dbop_open(makepath(dbpath, dbname(GTAGS), NULL), 0, 0, 0);
		if (data.dbop == NULL)
			die("%s not found.", dbname(GTAGS));
	} else {
		data.dbop = NULL;
	}
	data.fid = NULL;
	parser_init(langmap, plugin_parser);
	if (langmap != NULL)
		free(langmap);

	if (*argv && file_list)
		args_open_both(argv, file_list);
	else if (*argv)
		args_open(argv);
	else if (file_list)
		args_open_filelist(file_list);
	else
		args_open_nop();
	while ((av = args_read()) != NULL) {
		/*
		 * convert the path into relative to the root directory of source tree.
		 */
		if (normalize(av, get_root_with_slash(), cwd, path, sizeof(path)) == NULL) {
			if (!qflag)
				die("'%s' is out of the source project.", av);
			continue;
		}
		if (!test("f", makepath(root, path, NULL))) {
			if (!qflag) {
				if (test("d", NULL))
					die("'%s' is not a source file.", av);
				else
					die("'%s' not found.", av);
			}
			continue;
		}
		/*
		 * Memorize the file id of the path. This is used in put_syms().
		 */
		{
			static char s_fid[MAXFIDLEN];
			int type = 0;
			const char *p = gpath_path2fid(path, &type);

			if (!p || type != GPATH_SOURCE) {
				if (!qflag)
					die("'%s' is not a source file.", av);
				continue;
			}
			strlimcpy(s_fid, p, sizeof(s_fid));
			data.fid = s_fid;
		}
		if (Sflag && !locatestring(path, localprefix, MATCH_AT_FIRST))
			continue;
		data.count = 0;
		parse_file(path, flags, put_syms, &data);
		count += data.count;
	}
	args_close();
	parser_exit();
	/*
	 * Settlement
	 */
	if (data.dbop != NULL)
		dbop_close(data.dbop);
	gpath_close();
	convert_close(data.cv);
	strbuf_close(sb);
	if (vflag) {
		print_count(count);
		fprintf(stderr, " (no index used).\n");
	}
}
Esempio n. 2
0
static int
parse_conf(struct config_t *config, char *filename)
{
	int status, i;
	long num;
	char *key, *value, *endptr = NULL;
	
	/* parser storage */
	static struct parser_t parser;
	
	/* initialize parser */
	parser_init(&parser);
	
	/* pre-allocate 5 key/value pairs */
	parser_grow(&parser, 5);
	
	/* parse config file */
	status = parser_parse(&parser, filename);
	if (status != 0) {
		if (errno)
			warn("%s: parse failed", filename);
		else
			warnx("%s: parse error on line %i", filename, status);
		return -1;
	}
	
	/* for each option in config file */
	for (i = 0; i < parser.keys; ++i)
	{
		/* easier on the eyes */
		key = parser.items[i].key;
		value = parser.items[i].value;
		
		/* process options */
		if (strcmp(key, "username") == 0)
		{
			/* set if not set */
			if (!config->username)
				config->username = value;
		}
		else if (strcmp(key, "password") == 0)
		{
			/* set if not set */
			if (!config->password)
				config->password = value;
		}
		else if (strcmp(key, "proxy-host") == 0)
		{
			/* set if not set */
			if (!config->proxyname)
				config->proxyname = value;
		}
		else if (strcmp(key, "proxy-port") == 0)
		{
			/* skip if set */
			if (config->proxyport)
				continue;
			
			num = strtol(value, &endptr, 10);
			if (STRTOL_INVALID_PORT(num, value, endptr)) {
				warn("invalid proxy port: %s", value);
				return -1;
			}
			config->proxyport = (int)num;
		}
		else if (strcmp(key, "input-fd") == 0)
		{
			/* skip if set */
			if (config->ifd != UNDEFINED_FD)
				continue;
			
			num = strtol(value, &endptr, 10);
			if (STRTOL_INVALID_FD(num, value, endptr)) {
				warnx("invalid input fd: %s", value);
				return -1;
			}
			config->ifd = (int)num;
		}
		else if (strcmp(key, "output-fd") == 0)
		{
			/* skip if set */
			if (config->ofd != UNDEFINED_FD)
				continue;
			
			num = strtol(value, &endptr, 10);
			if (STRTOL_INVALID_FD(num, value, endptr)) {
				warnx("invalid output fd: %s", value);
				return -1;
			}
			config->ofd = (int)num;
		}
		else
		{
			warnx("%s: invalid keyword: %s", filename, key);
			return -1;
		}
	}
	
	/* all ok */
	return 0;
}
int main(int argc, char **argv)
{
  char *filename;
  FILE *datafile;
  struct stat fstat;

  long int bufcount;
  char *buff;
  int max_bufsz = DEFMAX_BUFSZ;
  int bufsz;

  //Kluge stuff, count total num samps
  //  long int totsampcount;

  //TCP stuff
  struct tcp_header *tcp_hdr;
  struct tcp_parser *parser;
  //  bool careful_strip = true; //ensures things are where they say they are before junking them
  //  FILE *stripfile;
  char tcp_str[16] = { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 
			0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

  struct dewe_chan *chan[MAX_NUMCHANS];
  char *chanbuff[MAX_NUMCHANS];
  char *chantimestamps[MAX_NUMCHANS];
  char combfname[] = "combined_chans.data";
  FILE *combfile; //File for combining upper 10, lower 6 bits of two different channels
                  //to accommodate the strange 10-bit TM data at Wallops
  
  signal(SIGINT, do_depart);

  //Kluge stuff, init total num samps
  //  totsampcount = 0;

  //tcp header stuff
  tcp_hdr = tcp_header_init();

  //tcp parser stuff
  parser = parser_init();

  parser->hdrsz = 32 + STARTSTR_SZ; //per DEWESoft NET interface docs

  //copy in start and tail string for use by parse_tcp_header() and strip_tcp_packet()
  if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] Start string:\t");
  for (int i = 0; i < STARTSTR_SZ; i ++){
    strncpy(&(parser->startstr[i]),&(tcp_str[8+i]),1);
    if ( DEF_VERBOSE ) printf("%x",parser->startstr[i]);
  }
  if( DEF_VERBOSE ) printf("\n");
  parser->startstr_sz = STARTSTR_SZ;

  if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] Tail string:\t");
  strncpy(parser->tlstr,tcp_str,STARTSTR_SZ); 
  if (DEF_VERBOSE ){
    for (int i = 0; i < STARTSTR_SZ; i ++){
      printf("%x",parser->tlstr[i]);
    }
    printf("\n");
  }
  parser->tailsz = STARTSTR_SZ;

  parser->oldhpos = -(parser->hdrsz + parser->tailsz); //Needs to be initialized thusly so that 
                                                       //parse_tcp_header doesn't complain that 
                                                       //the first header isn't where predicted
  parser->do_predict = true;
  parser->isfile = true;

  parser->verbose = DEF_VERBOSE;

  //Handle command line  
  if(argc == 2) {
    filename = strdup(argv[1]);
  }
  else if ( argc == 3 ){
    filename = strdup(argv[1]);
    max_bufsz = atoi(argv[2]);
  }
  else if( ( argc == 4 ) || ( argc == 5) ){

    filename = strdup(argv[1]);
    max_bufsz = atoi(argv[2]);

    //Strip packet modes
    if( atoi(argv[3]) <= 2){ 
      parser->strip_packet = atoi(argv[3]);
      parser->strip_fname = malloc(sizeof(char) * 128);
      parser->strip_fname = "stripped.data";
      //    sprintf(parser->strip_fname,"stripped-%s",filename);
      parser->oldt_in_this_buff = 0;
      parser->t_in_this_buff = 0;
    }
    //Channel modes
    else if( ( atoi(argv[3]) == 4 ) ||  ( atoi(argv[3]) == 5 ) || ( atoi(argv[3]) == 6 ) || ( atoi(argv[3]) == 7 ) ){ // only parse chan info 
      parser->do_chans = atoi(argv[3]) - 3;
      if( argc ==5 ){ //channel num provided
	parser->nchans = atoi(argv[4]);
      }
      else {
	parser->nchans = DEF_NUMCHANS;
      }
      if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] parser->nchans\t=\t%i\n",parser->nchans);
    }
    else {
      printf("You fool!!! You expect this program to clean your room as well?\n");
      return EXIT_FAILURE;
    }
  }
  else {
    printf("%s <tcp data file> <optional max readbuffer size> <run_mode> [for run_mode 4/5: NUM_CHANS]\n",argv[0]);
    printf("RUN MODES:\n");
    printf("\tFOR STRIPPING PACKETS\n");
    printf("\t0: No stripping of data is done. Prints packet headers to stdout.\n");
    printf("\t1: The packet header and footer are stripped from the data for RTD, but left in the data file\n");
    printf("\t2: The packet header and footer are stripped from the data for RTD AND the saved data file\n");
    printf("\t3: Stripped data are saved and RTDed, and bad packets are output to an error file, badpack.data (NOT YET IMPLEMENTED)\n");
    printf("\n");
    printf("\tFOR DOING CHANNEL TRICKERY\n");
    printf("\t4: Channel information is parsed and printed to stdout, but no files are created.\n");
    printf("\t5: A data file is created for each channel.\n");
    printf("\t6: A data file is created for each channel, AND the first and second channel are combined with"
	   "\n\t   join_upper10_lower6() and outputted as joinupper10lower6.data.\n");
    printf("\t7: Just for RxDSPs! A data file is created for each channel (always assumed asynchronous)"
	   "\n\t   but only the timestamp associated with a Dartmouth header is kept, instead of keeping all timestamps."
	   "\n\t   (Precludes digitizer mode, -g)\n");
    return(EXIT_SUCCESS);
  }

  //Open data file
  printf("Opening TCP data file %s\n",filename);
  if( ( datafile = fopen(filename,"r") ) == NULL ){
    fprintf(stderr,"Gerrorg. Couldn't open file %s.\n",filename);
    return(EXIT_FAILURE);
  }
  stat(filename,&fstat);
  parser->filesize = fstat.st_size;

  //Prepare buffers
  buff = malloc(sizeof(char) * max_bufsz);
  if( DEF_VERBOSE ) printf("Max buffer size:\t%i\n", max_bufsz);
 
  //tcp chan stuff
  if( parser->do_chans ){
    for (int i = 0; i < parser->nchans; i ++) {

      chan[i] = chan_init( i, 3, true, false); //channel num, data type 3 (16-bit unsigned int), async, not singleval

      if( ( parser->do_chans == 2 ) || ( parser->do_chans == 3 ) ){ //open files for chandata
	sprintf(chan[i]->outfname,"chan%i.data",i);
	chan[i]->outfile = fopen(chan[i]->outfname,"w");
	if (chan[i]->outfile == NULL) {
	  fprintf(stderr,"Gerrorg. Couldn't open %s for channel %i.\n", chan[i]->outfname, chan[i]->num );
	  return(EXIT_FAILURE);
	}
	if( DEF_VERBOSE ){
	  printf("Channel %i file:\t\t%p\n", i, chan[i]->outfile );
	  printf("Channel %i filename:\t\t%s\n", i, chan[i]->outfname);
	}
	
	//tstamp files
	if( chan[i]->is_asynchr ){

	  sprintf(chan[i]->ts_fname,"chan%i_tstamps.data",i);
	  chan[i]->ts_file = fopen(chan[i]->ts_fname,"w");
	  if (chan[i]->ts_file == NULL) {
	    fprintf(stderr,"Gerrorg. Couldn't open %s for channel %i.\n", chan[i]->ts_fname, chan[i]->num );
	    return(EXIT_FAILURE);
	  }
	  if( DEF_VERBOSE ){
	    printf("Channel %i timestamp file:\t\t%p\n", i, chan[i]->ts_file );
	    printf("Channel %i timestamp filename:\t\t%s\n", i, chan[i]->ts_fname);
	  }
	}
      }
    }

    //chan buffs
    for(int i = 0; i < parser->nchans; i++){
      chanbuff[i] = malloc( chan[i]->bufsize );
      chan[i]->d.type3 = chanbuff[i];
      chan[i]->packaddr = chan[i]->d.type3;
      chan[i]->oldpackaddr = chan[i]->d.type3;
      if( chan[i]->is_asynchr ){
	chantimestamps[i] = malloc( MAXNUMSAMPS * 8);
	chan[i]->oldtstamps_addr = chan[i]->tstamps_addr = chan[i]->timestamps = chantimestamps[i];
	if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] Malloc'ed %i bytes for channel %u timestamps buffer...\n", MAXNUMSAMPS * 8, chan[i]->num );
      }
    }
    if( parser->do_chans == 3){ //doing join_upper10_lower6
      combfile = fopen(combfname,"w");
      if (combfile == NULL) {
	fprintf(stderr,"Gerrorg. Couldn't open %s.\n", combfname );
	return(EXIT_FAILURE);
      }
      if( DEF_VERBOSE ){
	printf("Combined data filename: %s\n", combfname);
	printf("Combined data file: %p\n", combfile );
      }
    }
    else {
      combfile = NULL;
    }	
  }  

  //If stripping data, set up file for stripped data
  if(parser->strip_packet == 2){
    printf("stripfname: %s\n",parser->strip_fname);
    parser->stripfile = fopen(parser->strip_fname,"w");
    printf("Stripfile: %p\n",parser->stripfile);
    if (parser->stripfile == NULL) {
      fprintf(stderr,"Gerrorg. Couldn't open stripfile %s.\n",parser->strip_fname);
      return(EXIT_FAILURE);
    }
  }

  if( DEF_VERBOSE ) print_header_memberszinfo(tcp_hdr);

  //Prediction stuff
  if(parser->do_predict){
    parser->hprediction = 0; //At the beginning, we predict that the header will be right at the beginning!
    parser->num_badp = 0;
  }

  //Start looping through file
  printf("Parsing TCP data file %s...\n",filename);
  bufsz = max_bufsz;
  int i = 0;
  int count = 0;
  running = true;
  while( ( bufcount = fread(buff, 1, bufsz, datafile) ) > 0 && running ) {
    
    printf("\n***\nBuffer #%i\n***\n",i+1);

    parser->bufrem = bufcount;
    parser->bufpos = 0;
    parser->delbytes = 0;

    while(  parser->bufpos < parser->bufrem ){

      if(parser->strip_packet) { usleep(4000); }
	else { usleep(6000); }

      parse_tcp_header(parser, buff, tcp_hdr);       //get new header_addr here

      update_after_parse_header(parser, buff, tcp_hdr);       //new hpos, bufpos, packetpos, if applicable 

    
      if( parser->parse_ok ){
	
	printf("*****Packet #%u*****\n",parser->numpackets);
	print_tcp_header(tcp_hdr);

	// Kluge stuff--total num samps
	parser->totsampcount += tcp_hdr->chan0_numsamps;
	printf("Total samples rec'd so far:\t%"PRIi64"\n", parser->totsampcount);
	//	if( DEF_VERBOSE ) print_raw_tcp_header(tcp_hdr);
	
	//Current header not where predicted?
	if( parser->do_predict) {
	  
	  if( parser->hpos != parser->hprediction ) {
	    parser->num_badp +=1;
	    printf("***Header position not where predicted by previous packet size!\n");
	    printf("***Header position relative to beginning of buffer:\t%li\n",parser->hpos);
	    printf("***Predicted position relative to beginning of buffer:\t%li\n",parser->hprediction);
	    printf("***Missed by %li bytes... Try again, Hank.\n",parser->hprediction-parser->hpos);
	  }
	  else {

	    printf("***Header %i was found where predicted: %li\n",parser->hc,parser->hprediction);
	    parser->tc +=1; //Since the prediction was correct, there must have been a tail

	  }

	  //predicted position of the next header
	  parser->hprediction = parser->hpos + tcp_hdr->pack_sz + parser->tailsz + parser->startstr_sz;

	} 	
      }	

      //Strip packet modes
      if( parser->strip_packet ){

	prep_for_strip(parser, buff, tcp_hdr); 	//determines whether there are footers to kill
	strip_tcp_packet(parser, buff, tcp_hdr); 	//do the deed

	if( parser->do_predict ) { 	//update our prediction accordingly	  
	  parser->hprediction -= ( ( (int)parser->oldtkill + (int)parser->tkill) * parser->tailsz +
				   parser->hkill * parser->hdrsz );	  
	}	
	post_strip(parser, buff, tcp_hdr); 	//finish the job	
      } //end strip_packet

      //Channel modes
      if( parser->do_chans ){

      	bool moresamps = true;      
      	long int tmp_buf_pos = parser->bufpos;

  	if( parser->parse_ok ){

	  //get new packet stuff, if applicable
	  for(int i = 0; i < parser->nchans; i++){
	    update_chans_post_parse( chan[i], tcp_hdr, parser, buff );
	    //tell me about it
	    print_chan_info( chan[i] );
	  }

	  //temp set to zero because we want everything in the buffer BEHIND the new header
	  if( parser->oldhpos < 0 ) {
	    parser->bufpos = 0; 
	  }
	  else {
	    parser->bufpos = parser->oldhpos; 
	  }
	    
	  //wrap up old channel data, which will only be here if we got a new header
	  for(int i = 0; i < parser->nchans; i++){
	    //	    if( chan[i]->oldnumsampbytes != chan[i]->oldnumbytes_received && parser->bufpos < parser->hpos  ){
	    if( ( chan[i]->oldnumsampbytes != chan[i]->oldnumbytes_received || 
		  chan[i]->oldnumtbytes != chan[i]->oldtbytes_received) && parser->bufpos < parser->hpos  ){
	      if( DEBUG ) {
		printf("tcp_fileparse.c [main()] CH%i: Doing old samples\n", i );
		printf("tcp_fileparse.c [main()] CH%i: Bufpos = %li\n", i, parser->bufpos );
		printf("tcp_fileparse.c [main()] CH%i: hpos = %li\n", i, parser->hpos );
	      }
	      get_chan_samples( chan[i], buff, parser, tcp_hdr, true);
	    }
	  }
	  if( DEBUG ) {
	    printf("tcp_fileparse.c [main()] Finished oldsamps. Bufpos should be right behind hpos!\n");
	    //	    printf("tcp_fileparse.c [main()] hpos = %li, bufpos == %li\n", parser->hpos, parser->bufpos);
	  }
	  if( (parser->bufpos += parser->tailsz ) != parser->hpos && parser->oldhpos > 0 ) {
	    printf("Channels read incorrectly!!!\n");
	    printf("tcp_fileparse.c [main()] hpos = %li, bufpos == %li\n", parser->hpos, parser->bufpos);
	  }
	  parser->bufpos =  parser->hpos + parser->hdrsz - 4; //skip header for next get_chan_samples
	}  
	  
	moresamps = true; //reset for next bit
      

	for(int j = 0; j < parser->nchans; j++ ){
	  if( moresamps ) {
	    moresamps = get_chan_samples( chan[j], buff, parser, tcp_hdr, false);
	  } else { break; }
	}
	
      	parser->bufpos = tmp_buf_pos; //set it to what it was before channels messed with it

	if( parser->do_chans > 1 ){ //time to write chan data
	  
	  int npacks_ready = 0;
	  int noldpacks_ready = 0;
	  
	  for(int i = 0; i < 2; i ++){
	    noldpacks_ready += (int) chan[i]->oldpack_ready;
	    npacks_ready += (int) chan[i]->pack_ready;
	    
	    if( DEF_VERBOSE ){ 
	      printf("Chan %i old packet ready to combine: %i\n", i, chan[i]->oldpack_ready);
	      printf("Chan %i new packet ready to combine: %i\n", i, chan[i]->pack_ready);
	    }
	  }
	  if( parser-> do_chans >= 2 ){
	    if( npacks_ready == 2 ) {
	      
	      if( parser->do_chans == 3 )combine_and_write_chandata( chan[0], chan[1], 0, parser, combfile );
	      for(int i = 0; i < 2; i ++){
		write_chan_samples( chan[i], false, parser, true );
	      }

	      if( noldpacks_ready == 2 ){
		if( parser->do_chans == 3 )combine_and_write_chandata( chan[0], chan[1], 1, parser, combfile );
		for(int i = 0; i < 2; i ++){
		  write_chan_samples( chan[i], true, parser, true );
		}
	      }
	      for( int i = 0; i < 2; i++ ) {
		clean_chan_buffer( chan[i], true );
	      }
	    }
	    else if( noldpacks_ready == 2 ){
	      if( parser->do_chans == 3 )combine_and_write_chandata( chan[0], chan[1], 1, parser, combfile );
	      for(int i = 0; i < 2; i ++){
		write_chan_samples( chan[i], true, parser, true );
		clean_chan_buffer( chan[i], false );
	      }
	    }
	    else {
	      printf ("Not all channels are prepared to do data combination!\n");
	    }
	  } //end combine channel data
	} //end write chan data
	else { //just clean up, nothing to write
	  for(int i = 0; i < parser->nchans; i++){
	    clean_chan_buffer( chan[i] , chan[i]->pack_ready );
	  }
	}	
      } //end do_chans
    
      update_end_of_loop(parser, buff, tcp_hdr);       //new bufpos, packetpos happens here
      
    } //end of current buffer

    //Update all stuff outside last buffer
    parser->total += bufcount;
    printf("Read %li bytes so far\n", parser->total);
    
    if(parser->strip_packet){

      parser->deltotal += parser->delbytes;
      printf("Killed %li bytes so far\n",parser->deltotal);
      if( parser-> strip_packet == 2 ) { 

}

      if( parser->strip_packet == 2){//Up the ante

	printf("Writing %li bytes to %s\n",parser->bufrem, parser->strip_fname);     	

	count = fwrite(buff, 1, parser->bufrem, parser->stripfile);
    	if( count == 0){
    	  printf("Gerrorg writing to %s\n",parser->strip_fname);
    	}
    	parser->wcount += count;

    	printf("count = %i\n",count);

      }
    }
    printf("Oldhpos BEFORE subtraction:\t%li\n", parser->oldhpos);
    parser->hprediction -= parser->bufrem;
    parser->oldhpos -= parser->bufrem;
    printf("Oldhpos AFTER subtraction:\t%li\n", parser->oldhpos);
    i++;

  }

  //print stats
  print_stats(parser);
  /* if( parser->do_chans ) { for(int i = 0; i < p->nchans; i++ ){ print_chan_stats(chan, p); } } */

  //Clean up shop
  if(datafile != NULL) fclose(datafile);
  free(filename);
  free(tcp_hdr);
  if( parser->do_chans ){
    for(int i = 0; i < parser->nchans; i++ ){
      /* if( ( parser->do_chans == 2 ) || ( parser->do_chans == 3 ) ){ //open files for chandata */
      /* 	free( chan[i]->outfile ); */
      /* }	 */
      //      free_chan( chan[i] );
      free( chan[i] );
    }
    //chan buffs
    /* for(int i = 0; i < parser->nchans; i++){ */
    /*   free ( chanbuff[i] ); */
    /*   if( chan[i]->is_asynchr ){ */
    /* 	free ( chantimestamps[i] ); */
    /*   } */
    /* } */
    
    
    if( parser->do_chans == 3){ //doing join_upper10_lower6
      free( combfile );
    }
  }
  //  free_parser(parser);
  free(parser);
  free(buff);
 
  return(EXIT_SUCCESS);
}
/**
 * Parses a notification and creates the r_notification object
 * @param xml - the XML data
 * @returns the new r_notification* or NULL on error
 */
r_notification* r_notification_parse(str xml)
{
	r_notification *n;
	r_registration *r;
	r_regcontact *rc;
	xmlDocPtr doc=0;
	xmlNodePtr root=0,child=0,nephew=0,node=0;
	xmlChar *reginfo_state=0,*x;
	char c=0;
	
	n = pkg_malloc(sizeof(r_notification));
	if (!n) {
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse: Error allocating %d bytes\n",
			sizeof(r_notification));
		goto error;
	}
	memset(n,0,sizeof(r_notification));

	if (!dtd) parser_init(pcscf_reginfo_dtd);
	doc=0;
	c = xml.s[xml.len];
	xml.s[xml.len]=0;
	doc = xmlParseDoc((unsigned char *)xml.s);
	if (!doc){
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse:  This is not a valid XML <%.*s>\n",
			xml.len,xml.s);
		goto error;
	}
	if (xmlValidateDtd(&cvp,doc,dtd)!=1){
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse:  Verification of XML against DTD failed <%.*s>\n",
			xml.len,xml.s);
		goto error;
	}
	root = xmlDocGetRootElement(doc);
	if (!root){
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse:  Empty XML <%.*s>\n",
			xml.len,xml.s);
		goto error;
	}

	reginfo_state = xmlGetProp(root,(xmlChar*)"state");
	LOG(L_DBG,"DBG:"M_NAME":r_notification_parse: reginfo_state <%s>\n",
			reginfo_state);
	if (reginfo_state[0]=='f'||reginfo_state[0]=='F')
		n->state = IMS_REGINFO_FULL;
	else 
		n->state = IMS_REGINFO_PARTIAL;
	
	for(child = root->children; child; child = child->next)
		if (child->type == XML_ELEMENT_NODE)
	{
		r = pkg_malloc(sizeof(r_registration));
		if (!r){
			LOG(L_ERR,"ERR:"M_NAME":r_notification_parse: Error allocating %d bytes\n",
				sizeof(r_registration));
			goto error;
		}
		memset(r,0,sizeof(r_registration));
		
		x = xmlGetProp(child,(xmlChar*)"id");
		space_trim_dup(&(r->id),(char*)x);
		xmlFree(x);

		x = xmlGetProp(child,(xmlChar*)"aor");
		space_trim_dup(&(r->aor),(char*)x);
		xmlFree(x);
		
		x = xmlGetProp(child,(xmlChar*)"state");
		
		if (x[0]=='a'||x[0]=='A') 
			r->state = IMS_REGINFO_ACTIVE;
		else 
			r->state = IMS_REGINFO_TERMINATED;
		xmlFree(x);

		for(nephew = child->children; nephew; nephew = nephew->next)
				if (nephew->type == XML_ELEMENT_NODE)
		{
			rc = pkg_malloc(sizeof(r_regcontact));
			if (!rc){
				LOG(L_ERR,"ERR:"M_NAME":r_notification_parse: Error allocating %d bytes\n",
					sizeof(r_regcontact));
				goto error;
			}
			memset(rc,0,sizeof(r_regcontact));
			
			x = xmlGetProp(nephew,(xmlChar*)"id");
			space_trim_dup(&(rc->id),(char*)x);
			xmlFree(x);
				
			x = xmlGetProp(nephew,(xmlChar*)"state");
			if (x[0]=='a'||x[0]=='A') 
				rc->state = IMS_REGINFO_ACTIVE;
			else 
				rc->state = IMS_REGINFO_TERMINATED;
			xmlFree(x);
			
			x = xmlGetProp(nephew,(xmlChar*)"event");
			switch(x[0]){
				case 'r':case 'R':
					switch (x[2]){
						case 'g': case 'G':
							rc->event = IMS_REGINFO_CONTACT_REGISTERED;
							break;
						case 'f': case 'F':
							rc->event = IMS_REGINFO_CONTACT_REFRESHED;
							break;						
						case 'j': case 'J':
							rc->event = IMS_REGINFO_CONTACT_REJECTED;
							break;						
						default:
							rc->event = IMS_REGINFO_NONE;
					}
					break;
				case 'c':case 'C':
					rc->event = IMS_REGINFO_CONTACT_CREATED;	
					break;
				case 's':case 'S':
					rc->event = IMS_REGINFO_CONTACT_SHORTENED;	
					break;
				case 'e':case 'E':
					rc->event = IMS_REGINFO_CONTACT_EXPIRED;	
					break;
				case 'd':case 'D':
					rc->event = IMS_REGINFO_CONTACT_DEACTIVATED;	
					break;
				case 'p':case 'P':
					rc->event = IMS_REGINFO_CONTACT_PROBATION;	
					break;
				case 'u':case 'U':
					rc->event = IMS_REGINFO_CONTACT_UNREGISTERED;	
					break;
				default:
					rc->event = IMS_REGINFO_NONE;	
			}
			xmlFree(x);

			x = xmlGetProp(nephew,(xmlChar*)"expires");			
			if (x) {
				rc->expires = atoi((char*)x);
				xmlFree(x);
			}
			
			node = nephew->children;
			while(node && node->type!=XML_ELEMENT_NODE)
				node =node->next;
			if (node) {
				x = xmlNodeGetContent(node);
				space_trim_dup(&(rc->uri),(char*)x);
				xmlFree(x);
			}
			
			rc->next = r->contact;
			r->contact = rc;
		}
		
		r->next = n->registration;
		n->registration = r;
					
	}
			
	if (reginfo_state) xmlFree(reginfo_state);		
	
	if (doc) xmlFreeDoc(doc);
	xml.s[xml.len]=c;
	return n;
error:	
	if (reginfo_state) xmlFree(reginfo_state);		

	if (doc) xmlFreeDoc(doc);
	xml.s[xml.len]=c;
	if (n) r_notification_free(n);
	return 0;
}
Esempio n. 5
0
int parser(char* url, char* doc, char* buf, int blen, int maxlen)
{
	char *p, *purl, *word, *ptag, *pbuf;
	char ch, back_tag, intag, inscript;
	unsigned tag_flag;
	int ret;

	p = parser_init(doc);
	if (p == NULL)
		return 0;
	pbuf = buf;

/* parsing URL */
	purl = url;
	while (*purl != '\0')
	{
		if (!xl_isindexable(*purl))
		{
			purl++;
			continue;
		}

		word = purl;
		while (xl_isindexable(*purl))
		{
			if (xl_isupper(*purl))
				xl_tolower(*purl);
			purl++;
		}

		ch = *purl;
		*purl = '\0';

		if (pbuf-buf+purl-word+3 > blen-1)
			return -1;
		sprintf(pbuf, "%s U\n", word);
		pbuf += (purl-word)+3;

		*purl = ch;
	}

/* parsing page */
	tag_flag = 0;
	intag = 0;
	inscript = 0;

	while ((p - doc) < maxlen)
	{
		if (!xl_isindexable(*p))
		{
			if (*p != '>' )
			{
				if (*p == '<')
				{
					ptag = p;
					intag = 1;
				}
				p++;
				continue;
			}

			if (intag == 0)
			{
				p++;
				continue;
			}

			*p = ' ';
			ret = tag_parser(ptag+1, p-ptag, &back_tag);
			switch (ret)
			{
				case PTAG_B:

					if (back_tag == 0)
						xlbit_set(tag_flag, _B_TAG);
					else
						xlbit_unset(tag_flag, _B_TAG);
					break;

				case PTAG_I:

					if (back_tag == 0)
						xlbit_set(tag_flag, _I_TAG);
					else
						xlbit_unset(tag_flag, _I_TAG);
					break;

				case PTAG_H:

				if (back_tag == 0)
					xlbit_set(tag_flag, _H_TAG);
				else
					xlbit_unset(tag_flag, _H_TAG);
				break;

				case PTAG_TITLE:

					if (back_tag == 0)
						xlbit_set(tag_flag, _TITLE_TAG);
					else
						xlbit_unset(tag_flag, _TITLE_TAG);
					break;

				case PTAG_SCRIPT:

					if (back_tag == 0)
						inscript = 1;
					else
						inscript = 0;

				default:
					break;
			}

			intag = 0;
			p++;
			continue;
		}

		if (inscript || intag)
		{
			p++;
			continue;
		}

		word = p;
		while (xl_isindexable(*p))
		{
			if (xl_isupper(*p))
				xl_tolower(*p);
			p++;
		}

		ch = *p;
		*p = '\0';

		if (pbuf-buf+p-word+1 > blen-1)
			return -1;
		sprintf(pbuf, "%s ", word);
		pbuf += (p-word)+1;

		if (xlbit_check(tag_flag, _B_TAG))
		{
			if (pbuf-buf+1> blen-1)
				return -1;
			*pbuf = 'B';
			pbuf++;
		}

		if (xlbit_check(tag_flag, _H_TAG))
		{
			if (pbuf-buf+1> blen-1)
				return -1;
			*pbuf = 'H';
			pbuf++;
		}

		if (xlbit_check(tag_flag, _I_TAG))
		{
			if (pbuf-buf+1> blen-1)
				return -1;
			*pbuf = 'I';
			pbuf++;
		}

		if (xlbit_check(tag_flag, _TITLE_TAG))
		{
			if (pbuf-buf+1> blen-1)
				return -1;
			*pbuf = 'T';
			pbuf++;
		}

		if (tag_flag == 0)
		{
			if (pbuf-buf+1> blen-1)
				return -1;
			*pbuf = 'P';
			pbuf++;
		}

		if (pbuf-buf+1> blen-1)
			return -1;
		*pbuf = '\n';
		pbuf++;
		*p = ch;
	}

	*pbuf = '\0';
	return pbuf-buf;
}
Esempio n. 6
0
File: test.c Progetto: blaine/node
/* SCAN through every possible breaking to make sure the
 * parser can handle getting the content in any chunks that
 * might come from the socket
 */
void
test_scan (const struct message *r1, const struct message *r2, const struct message *r3)
{
  char total[80*1024] = "\0";
  char buf1[80*1024] = "\0";
  char buf2[80*1024] = "\0";
  char buf3[80*1024] = "\0";

  strcat(total, r1->raw);
  strcat(total, r2->raw);
  strcat(total, r3->raw);

  size_t read;

  int total_len = strlen(total);

  int total_ops = (total_len - 1) * (total_len - 2) / 2;
  int ops = 0 ;

  size_t buf1_len, buf2_len, buf3_len;

  int i,j;
  for (j = 2; j < total_len; j ++ ) {
    for (i = 1; i < j; i ++ ) {

      if (ops % 1000 == 0)  {
        printf("\b\b\b\b%3.0f%%", 100 * (float)ops /(float)total_ops);
        fflush(stdout);
      }
      ops += 1;

      parser_init(r1->type);

      buf1_len = i;
      strncpy(buf1, total, buf1_len);
      buf1[buf1_len] = 0;

      buf2_len = j - i;
      strncpy(buf2, total+i, buf2_len);
      buf2[buf2_len] = 0;

      buf3_len = total_len - j;
      strncpy(buf3, total+j, buf3_len);
      buf3[buf3_len] = 0;

      read = parse(buf1, buf1_len);
      if (read != buf1_len) {
        print_error(buf1, read);
        goto error;
      }

      read = parse(buf2, buf2_len);
      if (read != buf2_len) {
        print_error(buf2, read);
        goto error;
      }

      read = parse(buf3, buf3_len);
      if (read != buf3_len) {
        print_error(buf3, read);
        goto error;
      }

      parse(NULL, 0);

      if (3 != num_messages) {
        fprintf(stderr, "\n\nParser didn't see 3 messages only %d\n", num_messages);
        goto error;
      }

      if (!message_eq(0, r1)) {
        fprintf(stderr, "\n\nError matching messages[0] in test_scan.\n");
        goto error;
      }

      if (!message_eq(1, r2)) {
        fprintf(stderr, "\n\nError matching messages[1] in test_scan.\n");
        goto error;
      }

      if (!message_eq(2, r3)) {
        fprintf(stderr, "\n\nError matching messages[2] in test_scan.\n");
        goto error;
      }

      parser_free();
    }
  }
  puts("\b\b\b\b100%");
  return;

error:
  fprintf(stderr, "i=%d  j=%d\n", i, j);
  fprintf(stderr, "buf1 (%d) %s\n\n", buf1_len, buf1);
  fprintf(stderr, "buf2 (%d) %s\n\n", buf2_len , buf2);
  fprintf(stderr, "buf3 (%d) %s\n", buf3_len, buf3);
  exit(1);
}
Esempio n. 7
0
int
main (int argc, char **argv)
{
  int success = 1;

  int verbose = 0;              /* 1: verbose, 0 (or nothing: not verbose) */
  int clone = 0;                /* 1: verbose, 0 (or nothing: not verbose) */
  int binary = 0;
  FILE *torture_file;
  char *msg;
  int pos;
  int len;

  for (pos = 3; pos < argc; pos++) {
    if (0 == strncmp (argv[pos], "-v", 2))
      verbose = 1;
    else if (0 == strncmp (argv[pos], "-c", 2))
      clone = 1;
    else if (0 == strncmp (argv[pos], "-b", 2))
      binary = 1;
    else
      usage ();
  }

  if (argc < 3) {
    usage ();
  }

  torture_file = fopen (argv[1], "r");
  if (torture_file == NULL) {
    usage ();
  }

  /* initialize parser */
  parser_init ();

  if (binary) {
    if (read_binary (&msg, &len, torture_file) < 0)
      return -1;
  }
  else {
    msg = read_text (atoi (argv[2]), torture_file);
    if (!msg)
      return -1;
    len = strlen (msg);
  }

  success = test_message (msg, len, verbose, clone);
  if (verbose) {
    fprintf (stdout, "test %s : ============================ \n", argv[2]);
    fwrite (msg, 1, len, stdout);

    if (0 == success)
      fprintf (stdout, "test %s : ============================ OK\n", argv[2]);
    else
      fprintf (stdout, "test %s : ============================ FAILED\n", argv[2]);
  }

  osip_free (msg);
  fclose (torture_file);
#ifdef __linux
  if (success)
    exit (EXIT_FAILURE);
  else
    exit (EXIT_SUCCESS);
#endif
  return success;
}
Esempio n. 8
0
int32_t main(int32_t argc, char *argv[])
{
    int res =0;
    uint8_t *eventbuf = NULL;
    uint8_t *dbgbuf = NULL;
    int32_t c;
    struct dbglog_slot *slot;
    int cnss_intf_len = strlen(CNSS_INTF) +  1;
    pthread_t thd_id;

    progname = argv[0];
    uint16_t diag_type = 0;
    int32_t option_index = 0;
    static struct option long_options[] = {
        {"logfile", 1, NULL, 'f'},
        {"reclimit", 1, NULL, 'r'},
        {"console", 0, NULL, 'c'},
        {"qxdm", 0, NULL, 'q'},
        {"silent", 0, NULL, 's'},
        {"debug", 0, NULL, 'd'},
        { 0, 0, 0, 0}
    };

    while (1) {
        c = getopt_long (argc, argv, "f:scqdr:", long_options, &option_index);
        if (c == -1) break;

        switch (c) {
            case 'f':
                memset(dbglogoutfile, 0, PATH_MAX);
                memcpy(dbglogoutfile, optarg, strlen(optarg));
                optionflag |= LOGFILE_FLAG;
            break;

            case 'c':
                optionflag |= CONSOLE_FLAG;
            break;

            case 'q':
                optionflag |= QXDM_FLAG;
            break;

            case 'r':
                rec_limit = strtoul(optarg, NULL, 0);
            break;

            case 's':
                optionflag |= SILENT_FLAG;
            break;

            case 'd':
                optionflag |= DEBUG_FLAG;
            break;
            default:
                usage();
        }
    }

    if (!(optionflag & (LOGFILE_FLAG | CONSOLE_FLAG | QXDM_FLAG | SILENT_FLAG
           | DEBUG_FLAG))) {
        usage();
        return -1;
    }

    if (optionflag & QXDM_FLAG) {
        /* Intialize the fd required for diag APIs */
        if (TRUE != Diag_LSM_Init(NULL))
        {
             perror("Failed on Diag_LSM_Init\n");
             return -1;
        }
         /* Register CALLABACK for QXDM input data */
        DIAGPKT_DISPATCH_TABLE_REGISTER(DIAG_SUBSYS_WLAN, cnss_wlan_tbl);
#ifdef ANDROID
        if(cnssdiagservice_cap_handle()) {
            printf("Cap bouncing failed EXIT!!!");
            exit(1);
        }
#endif
    }

    pthread_create(&thd_id, NULL, &cnss_intf_wait_receive, NULL);

    sock_fd = create_nl_socket();
    if (sock_fd < 0) {
        fprintf(stderr, "Socket creation failed sock_fd 0x%x \n", sock_fd);
        return -1;
    }

    if (is_interface(CNSS_INTF, cnss_intf_len)) {
        initialize(sock_fd);
        cnssdiag_register_kernel_logging(sock_fd, nlh);
    }

    signal(SIGINT, stop);
    signal(SIGTERM, stop);

    if (optionflag & LOGFILE_FLAG) {

        if (rec_limit < RECLEN) {
            fprintf(stderr, "Too small maximum length (has to be >= %d)\n",
                    RECLEN);
            close(sock_fd);
            free(nlh);
            return -1;
        }
        max_records = rec_limit;
        printf("Storing last %d records\n", max_records);

        log_out = fopen(dbglogoutfile, "w");
        if (log_out == NULL) {
            perror("Failed to create output file");
            close(sock_fd);
            free(nlh);
            return -1;
        }

        fwlog_res_file = "./reorder";
    }


    parser_init();

    while ( 1 )  {
        if ((res = recvmsg(sock_fd, &msg, 0)) < 0)
                  continue;
        if ((res >= (int)sizeof(struct dbglog_slot)) ||
                  (nlh->nlmsg_type == WLAN_NL_MSG_CNSS_HOST_EVENT_LOG)) {
            process_cnss_diag_msg((tAniNlHdr *)nlh);
            memset(nlh,0,NLMSG_SPACE(MAX_MSG_SIZE));
        } else {
            /* Ignore other messages that might be broadcast */
            continue;
        }
    }
    /* Release the handle to Diag*/
    Diag_LSM_DeInit();
    if (optionflag & LOGFILE_FLAG)
        cleanup();
    close(sock_fd);
    free(nlh);
    return 0;
}
Esempio n. 9
0
void http_rx_tx(struct net_context *net_ctx, struct net_pkt *rx, int status,
		void *user_data)
{
	struct http_server_ctx *http_ctx = NULL;
	struct net_buf *data = NULL;
	u16_t rcv_len;
	u16_t offset;
	int parsed_len;
	int rc;

	if (status) {
		printf("[%s:%d] Status code: %d, <%s>\n",
			__func__, __LINE__, status, RC_STR(status));
		goto lb_exit;
	}

	if (!user_data) {
		printf("[%s:%d] User data is null\n", __func__, __LINE__);
		goto lb_exit;
	}

	http_ctx = (struct http_server_ctx *)user_data;
	if (http_ctx->net_ctx != net_ctx) {
		printf("[%s:%d] Wrong network context received\n",
		       __func__, __LINE__);
		goto lb_exit;
	}

	if (!rx) {
		printf("[%s:%d] Connection closed by peer\n",
		       __func__, __LINE__);
		goto lb_exit;
	}

	rcv_len = net_pkt_appdatalen(rx);
	if (rcv_len == 0) {
		/* don't print info about zero-length app data buffers */
		goto lb_exit;
	}

	data = net_buf_alloc(&http_msg_pool, APP_SLEEP_MSECS);
	if (data == NULL) {
		printf("[%s:%d] Data buffer alloc error\n", __func__, __LINE__);
		goto lb_exit;
	}

	offset = net_pkt_get_len(rx) - rcv_len;
	rc = net_frag_linear_copy(data, rx->frags, offset, rcv_len);
	if (rc != 0) {
		printf("[%s:%d] Linear copy error\n", __func__, __LINE__);
		goto lb_exit;
	}

	data->data[min(data->size - 1, rcv_len)] = 0;

	parser_init(http_ctx);
	parsed_len = parser_parse_request(http_ctx, data);
	if (parsed_len <= 0) {
		printf("[%s:%d] Received: %u bytes, only parsed: %d bytes\n",
		       __func__, __LINE__, rcv_len, parsed_len);
	}

	if (http_ctx->parser.http_errno != HPE_OK) {
		http_response_400(http_ctx, NULL);
	} else {
		http_tx(http_ctx);
	}

lb_exit:
	net_pkt_frag_unref(data);
	net_pkt_unref(rx);

	http_ctx_release(http_ctx);
}
Esempio n. 10
0
File: main.c Progetto: aressky/TDR
int main(int32_t argc, char *argv[])
{
	int opt;
	int32_t i;
	int make_rule = FALSE;

	parser_init(&parser);
	while((opt = getopt_long (argc, argv, short_options, long_options, NULL)) != -1)
	{
		switch(opt)
		{
		case 'v':
			version();
			goto done;
		case 'h':
			help();
			goto done;
		case 'I':
			if(g_include_dir_num >= INCLUDE_DIR_NUM)
			{
				fprintf(stderr, "Too many include directories.\n");
				goto ERROR_RET;
			}
			g_include_dir[g_include_dir_num] = optarg;
			++g_include_dir_num;
			break;
		case 'o':
			g_output_dir = optarg;
			break;
		case 'M':
			make_rule = TRUE;
			break;
		case 'g':
			{
				const char *arg = optarg;
				if(strcmp(arg, "types_h") == 0)
				{
					generator_types_h_init(&tlibc_types_generator, &parser.symbols);
					generator = &tlibc_types_generator.super;
				}
				else if(strcmp(arg, "reader_h") == 0)
				{
					generator_reader_h_init(&tlibc_reader_header_generator, &parser.symbols);
					generator = &tlibc_reader_header_generator.super;
				}
				else if(strcmp(arg, "reader_c") == 0)
				{
					generator_reader_c_init(&tlibc_reader_generator, &parser.symbols);
					generator = &tlibc_reader_generator.super;
				}			
				else if(strcmp(arg, "writer_h") == 0)
				{
					generator_writer_h_init(&tlibc_writer_header_generator, &parser.symbols);
					generator = &tlibc_writer_header_generator.super;
				}
				else if(strcmp(arg, "writer_c") == 0)
				{
					generator_writer_c_init(&tlibc_writer_generator, &parser.symbols);
					generator = &tlibc_writer_generator.super;
				}
				else if(strcmp(arg, "cs") == 0)
				{
					generator_cs_init(&tlibc_cs_generator, &parser.symbols);
					generator = &tlibc_cs_generator.super;
				}
				else if(strcmp(arg, "sql") == 0)
				{
					generator_sql_init(&tlibc_sql_generator, &parser.symbols);
					generator = &tlibc_sql_generator.super;
				}
			}
			break;
		default:
			goto ERROR_RET;
		}
	}
	
	if(generator == NULL)
	{
		fprintf(stderr, "Missing --gen=types\n");
		usage();
		goto ERROR_RET;
	}

	for(i = optind; i < argc; ++i)
	{
		if(parser_parse(&parser, argv[i], generator, make_rule) != E_TD_NOERROR)
		{
			goto ERROR_RET;
		}
	}

done:
	return 0;
ERROR_RET:
	return 1;
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
  parser_init();
  parse_commandline(argc,argv);

  int nthreads=MapReduceRunner::num_threads(param_set.nthreads.value);
  param_infile.nthreads.set_value(nthreads);
  param_outfile.nthreads.set_value(nthreads);
  assert(param_infile.nthreads.value==nthreads);
  assert(param_outfile.nthreads.value==nthreads);
  if (param_set.verbose.value>=2) {
    cerr << " using up to " << nthreads << " threads" << endl;
  }
  
  DataSetFlt input;
  
  cerr << "loading input data ..." <<endl;
  param_infile.print_parameters(cerr);
  input.append(param_infile);
  cerr << endl<<endl;

  DataDiscretizationDisc disc;
  if (param_modelfile.load_filename.value.size()==0) {
    cerr << "training using input data ..." <<endl;
    param_disc_dense.print_parameters(cerr);
    param_disc_sparse.print_parameters(cerr);
    disc.train(input,param_disc_dense,param_disc_sparse,nthreads,param_set.verbose.value);
    disc.set_convert(param_outfile.convert_type.value);
  }
  else {
    cerr << "loading discretization model from <" << param_modelfile.load_filename.value <<">" <<endl;
    ifstream is(param_modelfile.load_filename.value);
    if (!is.good()) {
      cerr << "cannot open <" << param_modelfile.load_filename.value <<">" <<endl;
    }
    disc.read(is);
    is.close();
  }
  if (param_modelfile.save_filename.value.size()>0) {
    cerr << "writing discretization model to <" << param_modelfile.save_filename.value << ">" <<endl;
    ofstream os(param_modelfile.save_filename.value);
    if (!os.good()) {
      cerr << "cannot open <" << param_modelfile.save_filename.value <<">" <<endl;
    }
    os.precision(10);
    disc.write(os);
    os.close();
  }

  DataSetDisc output;
  bool discretized=false;
  if (param_outfile.fn_x.value.size()>0) {
    cerr << "applying discretization to input data" <<endl;
    disc.apply(input,output,nthreads);
    discretized=true;
    cerr << "writing discretized data to <" << param_outfile.fn_x.value <<">"
	 << " with file-format=" << param_outfile.xfile_format.value <<endl;
    output.write(param_outfile);
  }
  if (param_outfile.output_feature.value.size()>0) {
    if (!discretized) {
      cerr << "applying discretization to input data" <<endl;
      disc.apply(input,output,nthreads);
      discretized=true;
    }
    cerr << "writing discretized features to <" << param_outfile.output_feature.value <<">"
	 << endl;

    class DiscFeatWriterMR : public DataSetWriterMapReduce<DISC_TEMPLATE> {
    public:
      
      vector<size_t>offset;
      
      vector<size_t> offset0;
      DataDiscretizationDisc * disc_ptr;
      
      DiscFeatWriterMR(DataDiscretizationDisc & disc) {
	disc_ptr=&disc;
	
	size_t j,k;
	size_t v=0;
	offset.push_back(v);
	for (j=0; j<disc.disc_dense.size(); j++) {
	  offset0.push_back(j);
	  v+=disc.disc_dense[j].size();
	  offset.push_back(v);
	}
	for (j=0; j<disc.disc_sparse.size(); j++) {
	  offset0.push_back(offset.size()-1);
	  for (k=0; k<disc.disc_sparse[j].size(); k++) {
	    v+= disc.disc_sparse[j][k]->size();
	    offset.push_back(v);
	  }
	}
      }
      
      virtual void write_datapoint(ostream & os, DataSetDisc & ds, size_t i)
      {
	DataPointDisc dp=ds[i];
	int j;
	bool first=true;
	for (j=0; j<dp.dim_dense; j++) {
	  int v=dp.x_dense[j];
	  int_t feat=j;
	  int_t sparse_index=0;
	  if (!first) os << " ";
	  first=false;
	  if (v != 0) os << offset[offset0[feat]+sparse_index]+v;
	}
	for (j=0; j<dp.dim_sparse; j++) {
	  for (int k=0; k<dp.x_sparse[j].size(); k++) {
	    if (!first) os << " ";
	    first=false;
	    int_t feat=j+dp.dim_dense;
	    int_t sparse_index=dp.x_sparse[j][k].index;
	    if (sparse_index<0) sparse_index=0;
	    int v=(int)dp.x_sparse[j][k].value;
	    if (v !=0) os << offset[offset0[feat]+sparse_index]+v;
	  }
	}
      }
    } mr(disc);

    
    ofstream os(param_outfile.output_feature.value);
    mr.write(os,output, nthreads);
    os.close();
  }
  
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
	pthread_t parser_thread;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s <input file> <m2m device>\n", argv[0]);
		return 1;
	}

	if (input_open(argv[1]) < 0)
		return -1;
	
	if (m2m_open(argv[2]) < 0)
		return -1;

	if (subscribe_source_change() < 0)
		return -1;

	/* Setup flow based on ELCE2014 slides and Nicolas Dufresne's knowledge:
	 * S_FMT(OUT)
	 * S_FMT(CAP) to suggest a fourcc for the raw format; may be changed later
	 * G_CTRL(MIN_BUF_FOR_OUTPUT)
	 * REQBUFS(OUT)
	 * QBUF (the header)
	 * STREAMON(OUT)
	 * QBUF/DQBUF frames on OUT
	 * source change event, DQEVENT
	 * G_FMT(CAP)
	 * ENUM_FMT(CAP)
	 * S_FMT(CAP) to set fourcc chosen from ENUM_FMT; also get resolution from returned values?
	 * G_SELECTION to get visible size
	 * G_CTRL(MIN_BUF_FOR_CAPTURE)
	 * REQBUFS(CAP)
	 * STREAMON(CAP)
	 */


	if (output_set_format() < 0)
		return -1;

	// FIXME capture S_FMT

	// FIXME G_CTRL(MIN_BUF_FOR_OUTPUT)

	if (output_request_buffers() < 0)
		return -1;

	map_output();

	//if (parse_and_queue_header() < 0)
	//	return -1;

	parse_one_nal();
	stream(V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, VIDIOC_STREAMON);

	parser_init();
	if (pthread_create(&parser_thread, NULL, parser_thread_func, NULL)) {
		fprintf(stderr, "Failed to launch parser thread\n");
		return -1;
	}

	if (wait_for_source_change() < 0)
		return -1;

	if (setup_capture() < 0)
		return -1;

	map_capture();
	queue_capture();
	stream(V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, VIDIOC_STREAMON);
	capture();

	pthread_join(parser_thread, 0);
	return 0;
}
Esempio n. 13
0
int main(int argc, char** argv) {
    if(argc != 2 && argc != 3) {
        c_print_format("Usage: %s FILE [cartridge/folder]\n", argv[0]);
        return 0;
    }
    Arena arena = arena_create(MB(512));

    String cartridge_folder_path_name = (argc > 2)
        ? string_from_c_string(argv[2])
        : L("SuperMarioWorld.sfc");
    Path cartridge_folder_path;
    path_init(&cartridge_folder_path, cartridge_folder_path_name);
    Path manifest_path;
    path_init_from_c(&manifest_path, &cartridge_folder_path, "manifest.bml");
    Buffer manifest_buffer = path_read_file(&manifest_path, &arena);

    Wdc65816MapperBuilder rom_builder = { };
    
    char name[256];
    Buffer name_buffer = buffer(name, 256);
    Buffer rom_buffer;
    for(Wdc65816RomLoader loader = wdc65816_rom_loader_begin(&rom_builder,
                                                             string_from_buffer(manifest_buffer));
        wdc65816_rom_loader_end(&loader);
        wdc65816_rom_loader_next(&loader)) {
        Wdc65816MemoryBufferRequest request = wdc65816_rom_loader_get_buffer_request(&loader,
                                                                                     name_buffer);
        Buffer file_buffer = buffer(arena_alloc_array(&arena, request.size, u8), request.size);
        if(string_equal(request.name, L("program.rom")) &&
           request.type == WDC65816_MEMORY_ROM) {
            rom_buffer = file_buffer;
        }
        wdc65816_rom_loader_set_buffer(&loader, file_buffer);
    }

    uint mapper_buffer_size = wdc65816_mapper_get_buffer_size();
    u8* work_buffer = arena_alloc_array(&arena, mapper_buffer_size, u8);
    Wdc65816Mapper rom;
    wdc65816_mapper_init(&rom, &rom_builder, (u8**)work_buffer);

    nuts_global_init();

    Path working_dir;
    path_init_working_directory(&working_dir);
    FreeList sentinel;
    free_list_init(&sentinel);
    ErrorList error_list;
    error_list_init(&error_list, arena_subarena(&arena, MB(10)));


    AST ast;
    ast_init(&ast, &arena);
    String file_name = string_from_c_string(argv[1]); 
    /* struct timespec lex_start,      lex_end,      lex_time = { 0 }; */
    /* struct timespec parse_start,    parse_end,    parse_time = { 0 }; */
    /* struct timespec assemble_start, assemble_end, assemble_time = { 0 }; */
    /* struct timespec all_start,      all_end,      all_time; */
    

    /* clock_gettime(CLOCK_REALTIME, &all_start); */
    Parser parser;
    parser_init(&parser, &arena, &sentinel, &error_list, &ast);
    int error_num = 0;
    while(1) {
        Path file;
        path_init(&file, file_name);
        Buffer file_buffer = path_read_file(&file, &arena);
        TokenList token_list;
        //c_print_format("read %.*s\n", file_name.length, file_name.data);
        Text file_text = {
            .buffer = file_buffer,
            .name   = file_name
        };
        /* clock_gettime(CLOCK_REALTIME, &lex_start); */
        Result result = lex(file_text, &token_list, &arena, &error_list, &ast.identifier_map);
        if(result == RESULT_ERROR) {
            for(;error_num < error_list.length; error_num++) {
                describe_error(error_list.errors[error_num]);
            }
        }
        /* clock_gettime(CLOCK_REALTIME, &lex_end); */
        /* lex_time = timespec_add(lex_time, timespec_sub(lex_start, lex_end)); */
        /* clock_gettime(CLOCK_REALTIME, &parse_start); */
        /* result = parse(&parser, token_list); */
        /* clock_gettime(CLOCK_REALTIME, &parse_end); */
        /* parse_time = timespec_add(parse_time, timespec_sub(parse_start, parse_end)); */

        if(result == RESULT_NEED_TOKEN_STREAM) {
            file_name = parser.needed_token_stream_file_name;
            continue;
        } else if(result == RESULT_OK) {
            break;
        } else if(result == RESULT_ERROR) {
            for(;error_num < error_list.length; error_num++) {
                describe_error(error_list.errors[error_num]);
            }
            return 1;
        } else {
            invalid_code_path;
        }
    }

    /* clock_gettime(CLOCK_REALTIME, &assemble_start); */
    Assembler assembler;
    assembler_init(&assembler, &error_list, &ast, &rom);
    Result result = RESULT_ERROR;
    while(result != RESULT_OK) {
        result = assemble(&assembler);
        if(result == RESULT_NEED_FILE) {
            String file_name = assembler_get_file_name(&assembler);
            Path file;
            path_init(&file, file_name);
            Buffer file_buffer = path_read_file(&file, &arena);
            assembler_give_buffer(&assembler, file_buffer);
        } else if(result == RESULT_ERROR) {
            break;
        }
    }
    /* clock_gettime(CLOCK_REALTIME, &assemble_end); */
    /* assemble_time = timespec_add(assemble_time, timespec_sub(assemble_start, assemble_end)); */

    for(int i = 0; i < error_list.length; i++) {
        describe_error(error_list.errors[i]);
    }

    /* parser_deinit(&parser); */
    /* clock_gettime(CLOCK_REALTIME, &all_end); */
    /* all_time = timespec_sub(all_start, all_end); */
    /* c_print_format("Lex:      %li.%06lims\n",      lex_time.tv_sec * 1000 +      lex_time.tv_nsec / 1000000,      lex_time.tv_nsec % 1000000); */
    /* c_print_format("Parse:    %li.%06lims\n",    parse_time.tv_sec * 1000 +    parse_time.tv_nsec / 1000000,    parse_time.tv_nsec % 1000000); */
    /* c_print_format("Assemble: %li.%06lims\n", assemble_time.tv_sec * 1000 + assemble_time.tv_nsec / 1000000, assemble_time.tv_nsec % 1000000); */
    /* c_print_format("All:      %li.%06lims\n",      all_time.tv_sec * 1000 +      all_time.tv_nsec / 1000000,      all_time.tv_nsec % 1000000); */

    Path rom_path;
    path_create_from(&rom_path, &cartridge_folder_path, L("program.rom"));
    path_write_file(&rom_path, rom_buffer);
    
    return 0;
}
Esempio n. 14
0
int
main(int argc, char **argv)
{
    int ret_status;

    /* Initialize some global values */
/*    fprintf(stderr,"hyper:main:entered\n");*/
    gArgc = argc;
    gArgv = argv;
    gIsEndOfOutput = 1;

/*    fprintf(stderr,"hyper:main:calling  check_arguments\n");*/
    check_arguments();
/*    fprintf(stderr,"hyper:main:returned check_arguments\n");*/

    /*
     * initialize the hash tables for the files and the windows and images
     */
/*    fprintf(stderr,"hyper:main:calling  init_hash\n");*/
    init_hash();
/*    fprintf(stderr,"hyper:main:returned init_hash\n");*/

    /*
     * initialize the parser keyword hash table
     */
/*    fprintf(stderr,"hyper:main:calling  parser_init\n");*/
    parser_init();
/*    fprintf(stderr,"hyper:main:returned parser_init\n");*/

/*    fprintf(stderr,"hyper:main:calling  read_ht_db\n");*/
    read_ht_db(&init_page_hash, &init_macro_hash, &init_patch_hash);
/*    fprintf(stderr,"hyper:main:returned read_ht_db\n");*/

    /*
     * Now initialize x. This includes opening the display, setting the
     * screen and display global values, and also gets all the fonts and
     * colors we will need.
     */

    if (!make_input_file && !gmake_record_file && !gverify_record_file) {
/*        fprintf(stderr,"hyper:main:calling  initializeWindowSystem\n");*/
        initializeWindowSystem();
/*        fprintf(stderr,"hyper:main:returned initializeWindowSystem\n");*/

        /*
         * Initialize some of the global values used by the input string
         * routines
         */
/*        fprintf(stderr,"hyper:main:calling  init_keyin\n");*/
        init_keyin();
/*        fprintf(stderr,"hyper:main:returned init_keyin\n");*/

        /*
         * regardless of what else happened, we should always pop up an
         * initial window.
         */

/*        fprintf(stderr,"hyper:main:calling  init_top_window\n");*/
        ret_status = init_top_window("RootPage");
/*        fprintf(stderr,"hyper:main:returned init_top_window\n");*/
        gParentWindow = gWindow;
        if (ret_status == -1) {
            fprintf(stderr,
               "(HyperDoc) Could not find RootPage for top-level window.\n");
            exit(-1);
        }

        /*
         * Tell it how to handle the user defined signals I may get
         */
        bsdSignal(SIGUSR2, sigusr2_handler,RestartSystemCalls);
        bsdSignal(SIGUSR1, SIG_IGN,RestartSystemCalls);
#if defined(BSDplatform) || defined(MACOSXplatform)
        bsdSignal(SIGCHLD, sigcld_handler,RestartSystemCalls);
#else
        bsdSignal(SIGCLD, sigcld_handler,RestartSystemCalls);
#endif
        bsdSignal(SIGINT, SIG_IGN,RestartSystemCalls);

        /*
         * Now go to the main event loop. I will never return, so just end
         * the main routine after that
         */

        /*
         * make an input file if requested
         */
    }
    else {

        /*
         * Try to establish all the socket connections I need. If I am an
         * is_fricas_server and the routine fails, it will exit for me
         */
/*        fprintf(stderr,"hyper:main:in else case\n");*/
/*        fprintf(stderr,"hyper:main:calling  make_server_connections\n");*/
        make_server_connections();
/*        fprintf(stderr,"hyper:main:returned make_server_connections\n");*/


        if (make_input_file) ht2_input();
        if (gmake_record_file) make_record();
        if (gverify_record_file) verify_record();
        exit(0);
    }

    /*
     * Try to establish all the socket connections I need. If I am an
     * is_fricas_server and the routine fails, it will exit for me
     */
/*    fprintf(stderr,"hyper:main:calling  make_server_connections\n");*/
    make_server_connections();
/*    fprintf(stderr,"hyper:main:returned make_server_connections\n");*/


/*    fprintf(stderr,"hyper:main:calling  mainEventLoop\n");*/
    mainEventLoop();
/*    fprintf(stderr,"hyper:main:returned mainEventLoop\n");*/

    return 0;
}
Esempio n. 15
0
/*
 * mod_init
 * Called by kamailio at init time
 */
static int mod_init(void) {

	int argc = 1;
	char *argt[] = { MOD_NAME, NULL };
	char **argv;
	struct timeval t1;
	struct timeval t2;

	if(register_mi_mod(exports.name, mi_cmds)!=0)
	{
		LM_ERR("failed to register MI commands\n");
		return -1;
	}

	if(ap_init_rpc()<0)
	{
		LM_ERR("failed to register RPC commands\n");
		return -1;
	}

	if (!filename) {
		LM_ERR("insufficient module parameters. Module not loaded.\n");
		return -1;
	}

	/* bind the SL API */
	if (sl_load_api(&slb)!=0) {
		LM_ERR("cannot bind to SL API\n");
		return -1;
	}

	_ap_reset_cycles = shm_malloc(sizeof(int));
	if(_ap_reset_cycles == NULL) {
		LM_ERR("no more shared memory\n");
		return -1;
	}
	*_ap_reset_cycles = _ap_reset_cycles_init;

	argv = argt;
	PERL_SYS_INIT3(&argc, &argv, &environ);

	gettimeofday(&t1, NULL);
	my_perl = parser_init();
	gettimeofday(&t2, NULL);

	if (my_perl==NULL)
		goto error;

	LM_INFO("perl interpreter has been initialized (%d.%06d => %d.%06d)\n",
				(int)t1.tv_sec, (int)t1.tv_usec,
				(int)t2.tv_sec, (int)t2.tv_usec);

#ifdef PERL_EXIT_DESTRUCT_END
	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
#else
	PL_exit_flags |= PERL_EXIT_EXPECTED;
#endif
	return 0;

error:
	if(_ap_reset_cycles!=NULL)
		shm_free(_ap_reset_cycles);
	_ap_reset_cycles = NULL;
	return -1;
}
Esempio n. 16
0
int fmt_load_string( char *buf, size_t size, fmt_t *obj )
{
	int err = 0;
	int add_tokens = 2;

	if(!buf || !obj || (size < 2))
		return LIBFMT_ERR_GENERIC;

	obj->js = NULL; // seg.fault protection

	err = parser_init( obj, LIBFMT_TOK_COUNT_MIN );
	if( err )
		return err;

	/* TODO: move memory allocation to fmt_load_normalized() ? */
	obj->js = (char *)malloc(size + 1);
	if( obj->js == NULL ) {
		err = LIBFMT_ERR_MALLOC;
		goto error;
	}

	memcpy(obj->js, buf, size);
	err = fmt_load_normalized_new(obj->js, size);
	if(err)
		goto error;

	/* try to parse */
	while((err = jsmn_parse(&obj->parser, obj->js,
	       obj->tok, obj->num_tokens)) == JSMN_ERROR_NOMEM)
	{
		/* allocate more tokens and try to parse again */
		obj->num_tokens += add_tokens;
		obj->tok = (fmt_tok_t *)realloc( obj->tok,
					obj->num_tokens * sizeof(fmt_tok_t) );
		if ( obj->tok == NULL ) {
			err = LIBFMT_ERR_REALLOC_TOK;
			goto error;
		}

		/* initialize tokens, otherwise valgrind complains */
		mark_token_unused( obj->tok + obj->num_tokens - add_tokens,
								add_tokens );
	}

	if( err != JSMN_SUCCESS ) {
		obj->js[0] = '\0';
		err =  LIBFMT_ERR_PARSER;
		goto error;
	}

	/* jsmn doesn't return an error when parsing empty string/file */
	if( fmt_dump_len( obj ) < 2 ) {
		obj->js[0] = '\0';
		err = LIBFMT_ERR_PARSER;
		goto error;
	}

	if( obj->js[0] != '[' && obj->js[0] != '{' ) {
		err = LIBFMT_ERR_PARSER;
		goto error;
	}

	if( obj->js[0] == '[' )
		obj->tok->type = JSMN_ARRAY;
	else
		obj->tok->type = JSMN_OBJECT;

	return LIBFMT_ERR_NONE;
error:
	fmt_free(obj);
	return err;
}
Esempio n. 17
0
int set_fiducial(
    struct file_content * pfc,
    ErrorMsg errmsg) {

    int i;
    char format[100];
    /* all parameters for which we don't want to keep default values
       should be passed to the code through a file_content
       structure. Create such a structure with the size you need: 9 in
       this exemple */
    parser_init(pfc,16,errmsg);
    i=0;

    /* assign values to these 9 parameters. Some will be fixed, some
       will be varied in the loop. */


    /* the following is the parameters varied, indices help for-looping, otherwise,
     * use names, eg. pfc->h or pfc->omega_b */
    strcpy(pfc->name[i],"omega_b");
    sprintf(pfc->value[i],"%e",0.0220);
    i++;

    strcpy(pfc->name[i],"n_s");
    sprintf(pfc->value[i],"%e",0.9617);
    i++;

    strcpy(pfc->name[i],"h");
    sprintf(pfc->value[i],"%e",0.6927);
    i++;

    strcpy(pfc->name[i],"omega_cdm");
    sprintf(pfc->value[i],"%e",0.1207);
    i++;
/*
    strcpy(pfc->name[i], "Omega_k");
    sprintf(pfc->value[i], "%e", 0.);
    i++;
*/
    strcpy(pfc->name[i], "w0_fld");
    sprintf(pfc->value[i], "%e", -1.007);
    //here is the only place original class need to 
    //be modified: you need to comment out the range 
    //check for w0_fld in source/input.c.
    i++;

    strcpy(pfc->name[i], "wa_fld");
    sprintf(pfc->value[i], "%e", -0.29);
    i++;

    /*end of varying parameter-------------------*/

    strcpy(pfc->name[i], "Omega_fld"); //note that curved space is not supported
    sprintf(pfc->value[i], "%e", 0.6825);
    i++;

    /*
      strcpy(pfc->name[i],"m_ncdm");
      sprintf(pfc->value[i],"%e",0.04);
    i++;

      strcpy(pfc->name[i],"N_ncdm");
      sprintf(pfc->value[i],"%d",1);
    i++;
    */
    strcpy(pfc->name[i],"output");
    strcpy(pfc->value[i],"tCl,pCl,lCl,mPk");
    i++;
    /*
      strcpy(pfc->name[i],"selection_num");
      sprintf(pfc->value[i],"%d",NREDSHIFT);

      format = " "
      for(i=0;i<NREDSHIFT;i++) strcat(format, "%f,")
      strcpy(pfc->name[8],"selection_mean");
      sprintf(pfc->value[8],format, 0.5, 0.7, 0.9,  \
                                    1.1, 1.3, 1.5,  \
                                    1.7, 1.9);

      strcpy(pfc->name[i],"selection_width");
      sprintf(pfc->value[i],"%e",0.01);
    */
    strcpy(pfc->name[i],"z_max_pk");
    sprintf(pfc->value[i],"%e", ZMAX);
    i++;

    strcpy(pfc->name[i],"l_max_scalars");
    sprintf(pfc->value[i],"%d", 3000);
    i++;

    strcpy(pfc->name[i],"modes");
    sprintf(pfc->value[i],"%s","s");
    i++;

    strcpy(pfc->name[i],"ic");
    sprintf(pfc->value[i],"%s","ad");
    i++;

//  strcpy(pfc->name[12], "background_verbose");
//  sprintf(pfc->value[12], "%d", 1);
}
Esempio n. 18
0
int fmt_load_fp( FILE **fp, fmt_t **obj )
{
	if( *fp == NULL )
		return LIBFMT_ERR_GENERIC;

	int rb;
	long long acc = 0;
	int add_tokens = 2;
	int err = 0;
	char buf[LIBFMT_FILE_READ_BLOCK] = {0};

	err = parser_init(*obj, LIBFMT_TOK_COUNT_MIN);
	if(err)
		return err;

	(*obj)->js = NULL;
	while((rb = fread(buf, 1, LIBFMT_FILE_READ_BLOCK, *fp)) > 0)
	{
		(*obj)->js = (char *)realloc( (*obj)->js, acc + rb + 1);

		if( (*obj)->js == NULL ) {
			err = LIBFMT_ERR_REALLOC_JS;
			break;
		}

		memcpy((*obj)->js + acc, buf, rb);

		acc += (long long )rb;
	}

	if(acc < 2) {
		err = LIBFMT_ERR_PARSER;
		goto error;
	}

	err = fmt_load_normalized_new((*obj)->js, acc);
	if(err)
		goto error;

	if(err < 0 && err != LIBFMT_ERR_NULLMET)
		goto error;

	/* try to parse */
	while((err = jsmn_parse( &(*obj)->parser, (*obj)->js, (*obj)->tok,
				(*obj)->num_tokens )) == JSMN_ERROR_NOMEM)
	{
		/* allocate more tokens and try to parse again */
		(*obj)->num_tokens += add_tokens;
		(*obj)->tok = (fmt_tok_t *)realloc((*obj)->tok,
				(*obj)->num_tokens * sizeof(fmt_tok_t));

		if((*obj)->tok == NULL) {
			err = LIBFMT_ERR_REALLOC_TOK;
			goto error;
		}

		/* initialize tokens, otherwise valgrind complains */
		mark_token_unused((*obj)->tok + (*obj)->num_tokens - add_tokens,
								add_tokens);
	}
	if( err != JSMN_SUCCESS ) {
		(*obj)->js[0] = '\0';
		err = LIBFMT_ERR_PARSER;
		goto error;
	}

	/* jsmn doesn't return an error when parsing empty string/file */
	if( fmt_dump_len( *obj ) < 2 ) {
		(*obj)->js[0] = '\0';
		err =  LIBFMT_ERR_PARSER;
		goto error;
	}

	if((*obj)->js[0] == '[')
		(*obj)->tok->type = JSMN_ARRAY;
	else
		(*obj)->tok->type = JSMN_OBJECT;

	return LIBFMT_ERR_NONE;
error:
	fmt_free(*obj);
	return err;
}
Esempio n. 19
0
int
main(int argc, char **argv)
{
    char dbpath[MAXPATHLEN];
    char cwd[MAXPATHLEN];
    STRBUF *sb = strbuf_open(0);
    int optchar;
    int option_index = 0;
    STATISTICS_TIME *tim;

    /*
     * Setup GTAGSCONF and GTAGSLABEL environment variable
     * according to the --gtagsconf and --gtagslabel option.
     */
    preparse_options(argc, argv);
    /*
     * Get the project root directory.
     */
    if (!vgetcwd(cwd, MAXPATHLEN))
        die("cannot get current directory.");
    canonpath(cwd);
    /*
     * Load configuration file.
     */
    openconf(cwd);
    configuration();
    setenv_from_config();
    {
        char *env = getenv("GTAGS_OPTIONS");
        if (env && *env)
            argv = prepend_options(&argc, argv, env);
    }
    logging_arguments(argc, argv);
    while ((optchar = getopt_long(argc, argv, "cd:f:iIn:oOqvwse", long_options, &option_index)) != EOF) {
        switch (optchar) {
        case 0:
            /* already flags set */
            break;
        case OPT_CONFIG:
            show_config = 1;
            if (optarg)
                config_name = optarg;
            break;
        case OPT_GTAGSCONF:
        case OPT_GTAGSLABEL:
            /* These options are already parsed in preparse_options() */
            break;
        case OPT_SINGLE_UPDATE:
            iflag++;
            single_update = optarg;
            break;
        case OPT_ACCEPT_DOTFILES:
            set_accept_dotfiles();
            break;
        case 'c':
            cflag++;
            break;
        case 'd':
            dump_target = optarg;
            break;
        case 'f':
            file_list = optarg;
            break;
        case 'i':
            iflag++;
            break;
        case 'I':
            Iflag++;
            break;
        case 'o':
            /*
             * Though the -o(--omit-gsyms) was removed, this code
             * is left for compatibility.
             */
            break;
        case 'O':
            Oflag++;
            break;
        case 'q':
            qflag++;
            setquiet();
            break;
        case 'w':
            wflag++;
            break;
        case 'v':
            vflag++;
            setverbose();
            break;
        default:
            usage();
            break;
        }
    }
    if (qflag)
        vflag = 0;
    if (show_version)
        version(NULL, vflag);
    if (show_help)
        help();

    argc -= optind;
    argv += optind;

    /* If dbpath is specified, -O(--objdir) option is ignored. */
    if (argc > 0)
        Oflag = 0;
    if (show_config) {
        openconf(setupdbpath(0) == 0 ? get_root() : NULL);
        if (config_name)
            printconf(config_name);
        else
            fprintf(stdout, "%s\n", getconfline());
        exit(0);
    } else if (dump_target) {
        /*
         * Dump a tag file.
         */
        DBOP *dbop = NULL;
        const char *dat = 0;
        int is_gpath = 0;

        if (!test("f", dump_target))
            die("file '%s' not found.", dump_target);
        if ((dbop = dbop_open(dump_target, 0, 0, DBOP_RAW)) == NULL)
            die("file '%s' is not a tag file.", dump_target);
        /*
         * The file which has a NEXTKEY record is GPATH.
         */
        if (dbop_get(dbop, NEXTKEY))
            is_gpath = 1;
        for (dat = dbop_first(dbop, NULL, NULL, 0); dat != NULL; dat = dbop_next(dbop)) {
            const char *flag = is_gpath ? dbop_getflag(dbop) : "";

            if (*flag)
                printf("%s\t%s\t%s\n", dbop->lastkey, dat, flag);
            else
                printf("%s\t%s\n", dbop->lastkey, dat);
        }
        dbop_close(dbop);
        exit(0);
    } else if (Iflag) {
#define REQUIRED_MKID_VERSION "4.5"
        char *p;

        if (!usable("mkid"))
            die("mkid not found.");
        if (read_first_line("mkid --version", sb))
            die("mkid cannot executed.");
        p = strrchr(strbuf_value(sb), ' ');
        if (p == NULL)
            die("invalid version string of mkid: %s", strbuf_value(sb));
        switch (check_version(p + 1, REQUIRED_MKID_VERSION)
#ifdef _WIN32
                || strcmp(p + 1, "3.2.99") == 0
#endif
               )  {
        case 1:
            break;	/* OK */
        case 0:
            die("mkid version %s or later is required.", REQUIRED_MKID_VERSION);
        default:
            die("invalid version string of mkid: %s", strbuf_value(sb));
        }
    }

    /*
     * If 'gtags.files' exists, use it as a file list.
     * If the file_list other than "-" is given, it must be readable file.
     */
    if (file_list == NULL && test("f", GTAGSFILES))
        file_list = GTAGSFILES;
    if (file_list && strcmp(file_list, "-")) {
        if (test("d", file_list))
            die("'%s' is a directory.", file_list);
        else if (!test("f", file_list))
            die("'%s' not found.", file_list);
        else if (!test("r", file_list))
            die("'%s' is not readable.", file_list);
    }
    /*
     * Regularize the path name for single updating (--single-update).
     */
    if (single_update) {
        static char regular_path_name[MAXPATHLEN];
        char *p = single_update;

        if (!test("f", p))
            die("'%s' not found.", p);
#if _WIN32 || __DJGPP__
        for (; *p; p++)
            if (*p == '\\')
                *p = '/';
        p = single_update;
#define LOCATEFLAG MATCH_AT_FIRST|IGNORE_CASE
#else
#define LOCATEFLAG MATCH_AT_FIRST
#endif
        if (isabspath(p)) {
            char *q = locatestring(p, cwd, LOCATEFLAG);

            if (q && *q == '/')
                snprintf(regular_path_name, MAXPATHLEN, "./%s", q + 1);
            else
                die("path '%s' is out of the project.", p);

        } else {
            if (p[0] == '.' && p[1] == '/')
                snprintf(regular_path_name, MAXPATHLEN, "%s", p);
            else
                snprintf(regular_path_name, MAXPATHLEN, "./%s", p);
        }
        single_update = regular_path_name;
    }
    /*
     * Decide directory (dbpath) in which gtags make tag files.
     *
     * Gtags create tag files at current directory by default.
     * If dbpath is specified as an argument then use it.
     * If the -i option specified and both GTAGS and GRTAGS exists
     * at one of the candidate directories then gtags use existing
     * tag files.
     */
    if (iflag) {
        if (argc > 0)
            realpath(*argv, dbpath);
        else if (!gtagsexist(cwd, dbpath, MAXPATHLEN, vflag))
            strlimcpy(dbpath, cwd, sizeof(dbpath));
    } else {
        if (argc > 0)
            realpath(*argv, dbpath);
        else if (Oflag) {
            char *objdir = getobjdir(cwd, vflag);

            if (objdir == NULL)
                die("Objdir not found.");
            strlimcpy(dbpath, objdir, sizeof(dbpath));
        } else
            strlimcpy(dbpath, cwd, sizeof(dbpath));
    }
    if (iflag && (!test("f", makepath(dbpath, dbname(GTAGS), NULL)) ||
                  !test("f", makepath(dbpath, dbname(GRTAGS), NULL)) ||
                  !test("f", makepath(dbpath, dbname(GPATH), NULL)))) {
        if (wflag)
            warning("GTAGS, GRTAGS or GPATH not found. -i option ignored.");
        iflag = 0;
    }
    if (!test("d", dbpath))
        die("directory '%s' not found.", dbpath);
    if (vflag)
        fprintf(stderr, "[%s] Gtags started.\n", now());
    /*
     * initialize parser.
     */
    if (vflag && gtags_parser)
        fprintf(stderr, " Using plug-in parser.\n");
    parser_init(langmap, gtags_parser);
    if (vflag && file_list)
        fprintf(stderr, " Using '%s' as a file list.\n", file_list);
    /*
     * Start statistics.
     */
    init_statistics();
    /*
     * incremental update.
     */
    if (iflag) {
        /*
         * Version check. If existing tag files are old enough
         * gtagsopen() abort with error message.
         */
        GTOP *gtop = gtags_open(dbpath, cwd, GTAGS, GTAGS_MODIFY, 0);
        gtags_close(gtop);
        /*
         * GPATH is needed for incremental updating.
         * Gtags check whether or not GPATH exist, since it may be
         * removed by mistake.
         */
        if (!test("f", makepath(dbpath, dbname(GPATH), NULL)))
            die("Old version tag file found. Please remake it.");
        (void)incremental(dbpath, cwd);
        print_statistics(statistics);
        exit(0);
    }
    /*
     * create GTAGS and GRTAGS
     */
    createtags(dbpath, cwd);
    /*
     * create idutils index.
     */
    if (Iflag) {
        FILE *op;
        GFIND *gp;
        const char *path;

        tim = statistics_time_start("Time of creating ID");
        if (vflag)
            fprintf(stderr, "[%s] Creating indexes for idutils.\n", now());
        strbuf_reset(sb);
        /*
         * Since idutils stores the value of PWD in ID file, we need to
         * force idutils to follow our style.
         */
#if _WIN32 || __DJGPP__
        strbuf_puts(sb, "mkid --files0-from=-");
#else
        strbuf_sprintf(sb, "PWD=%s mkid --files0-from=-", quote_shell(cwd));
#endif
        if (vflag)
            strbuf_puts(sb, " -v");
        strbuf_sprintf(sb, " --file=%s/ID", quote_shell(dbpath));
        if (vflag) {
#ifdef __DJGPP__
            if (is_unixy())	/* test for 4DOS as well? */
#endif
                strbuf_puts(sb, " 1>&2");
        } else {
            strbuf_puts(sb, " >" NULL_DEVICE);
#ifdef __DJGPP__
            if (is_unixy())	/* test for 4DOS as well? */
#endif
                strbuf_puts(sb, " 2>&1");
        }
        if (debug)
            fprintf(stderr, "executing mkid like: %s\n", strbuf_value(sb));
        op = popen(strbuf_value(sb), "w");
        if (op == NULL)
            die("cannot execute '%s'.", strbuf_value(sb));
        gp = gfind_open(dbpath, NULL, GPATH_BOTH);
        while ((path = gfind_read(gp)) != NULL) {
            fputs(path, op);
            fputc('\0', op);
        }
        gfind_close(gp);
        if (pclose(op) != 0)
            die("terminated abnormally '%s' (errno = %d).", strbuf_value(sb), errno);
        if (test("f", makepath(dbpath, "ID", NULL)))
            if (chmod(makepath(dbpath, "ID", NULL), 0644) < 0)
                die("cannot chmod ID file.");
        statistics_time_end(tim);
    }
    if (vflag)
        fprintf(stderr, "[%s] Done.\n", now());
    closeconf();
    strbuf_close(sb);
    print_statistics(statistics);

    return 0;
}
Esempio n. 20
0
int
server_config_parse_example(const struct config_parser *parser,
			    void *input)
{
  struct parser_state state;
  struct group *group;
  int err;

  err = parser_init(&state, parser, input);
  if (err)
    return err;

  for (group = state.egroup - 1; group >= state.groups; group--)
    {
      const struct config_parser *parser= group->parser; 
      const struct config_option *option;

      for (option = parser->options; option->type != CONFIG_TYPE_NONE; option++)
	if (option->example)
	  {
	    uint32_t value = 0;
	    const uint8_t *data = NULL;

	    unsigned length = strlen(option->example);

	    switch (option->type)
	      {
	      default:
		fatal("Internal error.\n");

	      case CONFIG_TYPE_LIST:
		{
		  struct config_tokenizer tokenizer;
		  uint8_t *list;
		  
		  config_tokenizer_init(&tokenizer, "example fragment",
					length, option->example);

		  err = parse_value_list(&value, &list, &tokenizer);
		  data = list;
		  break;
		}
	      case CONFIG_TYPE_BOOL:
		err = parse_value_bool(&value, length, option->example);
		break;

	      case CONFIG_TYPE_NUMBER:
		err = parse_value_unsigned(&value, length, option->example);
		break;

	      case CONFIG_TYPE_STRING:
		value = length;
		data = option->example;
		break;
	      }
	  
	    if (err)
	      fatal("Bad example value for configuration option `%z'\n",
		    option->name);
	    else
	      err = group->parser->handler(option->key, value, data, &group->state);

	  }
    }
  parser_finalize(&state);
  return err;
}
Esempio n. 21
0
int
main(int argc, char **argv)
{
	char dbpath[MAXPATHLEN];
	char cwd[MAXPATHLEN];
	STRBUF *sb = strbuf_open(0);
	int optchar;
	int option_index = 0;
	STATISTICS_TIME *tim;

	while ((optchar = getopt_long(argc, argv, "cd:f:iuIn:oOqvwse", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			/* already flags set */
			break;
		case OPT_CONFIG:
			show_config = 1;
			if (optarg)
				config_name = optarg;
			break;
		case OPT_GTAGSCONF:
			gtagsconf = optarg;
			break;
		case OPT_GTAGSLABEL:
			gtagslabel = optarg;
			break;
		case OPT_PATH:
			do_path = 1;
			if (!strcmp("absolute", optarg))
				convert_type = PATH_ABSOLUTE;
			else if (!strcmp("relative", optarg))
				convert_type = PATH_RELATIVE;
			else if (!strcmp("through", optarg))
				convert_type = PATH_THROUGH;
			else
				die("Unknown path type.");
			break;
		case OPT_SINGLE_UPDATE:
			iflag++;
			single_update = optarg;
			break;
		case OPT_ENCODE_PATH:
			if (strlen(optarg) > 255)
				die("too many encode chars.");
			if (strchr(optarg, '/') || strchr(optarg, '.'))
				die("cannot encode '/' and '.' in the path.");
			set_encode_chars((unsigned char *)optarg);
			break;
		case 'c':
			cflag++;
			break;
		case 'd':
			dump_target = optarg;
			break;
		case 'f':
			file_list = optarg;
			break;
		case 'i':
			iflag++;
			break;
		case 'u':
			uflag++;
			iflag++;
			break;
		case 'I':
			Iflag++;
			break;
		case 'o':
			/*
			 * Though the -o(--omit-gsyms) was removed, this code
			 * is left for compatibility.
			 */
			break;
		case 'O':
			Oflag++;
			break;
		case 'q':
			qflag++;
			setquiet();
			break;
		case 'w':
			wflag++;
			break;
		case 'v':
			vflag++;
			setverbose();
			break;
		default:
			usage();
			break;
		}
	}
	if (gtagsconf) {
		char path[MAXPATHLEN];

		if (realpath(gtagsconf, path) == NULL)
			die("%s not found.", gtagsconf);
		set_env("GTAGSCONF", path);
	}
	if (gtagslabel) {
		set_env("GTAGSLABEL", gtagslabel);
	}
	if (qflag)
		vflag = 0;
	if (show_version)
		version(NULL, vflag);
	if (show_help)
		help();

	argc -= optind;
        argv += optind;

	/* If dbpath is specified, -O(--objdir) option is ignored. */
	if (argc > 0)
		Oflag = 0;
	if (show_config) {
		if (config_name)
			printconf(config_name);
		else
			fprintf(stdout, "%s\n", getconfline());
		exit(0);
	} else if (do_path) {
		/*
		 * This is the main body of path filter.
		 * This code extract path name from tag line and
		 * replace it with the relative or the absolute path name.
		 *
		 * By default, if we are in src/ directory, the output
		 * should be converted like follws:
		 *
		 * main      10 ./src/main.c  main(argc, argv)\n
		 * main      22 ./libc/func.c   main(argc, argv)\n
		 *		v
		 * main      10 main.c  main(argc, argv)\n
		 * main      22 ../libc/func.c   main(argc, argv)\n
		 *
		 * Similarly, the --path=absolute option specified, then
		 *		v
		 * main      10 /prj/xxx/src/main.c  main(argc, argv)\n
		 * main      22 /prj/xxx/libc/func.c   main(argc, argv)\n
		 */
		STRBUF *ib = strbuf_open(MAXBUFLEN);
		CONVERT *cv;
		char *ctags_x;

		if (argc < 3)
			die("gtags --path: 3 arguments needed.");
		cv = convert_open(convert_type, FORMAT_CTAGS_X, argv[0], argv[1], argv[2], stdout);
		while ((ctags_x = strbuf_fgets(ib, stdin, STRBUF_NOCRLF)) != NULL)
			convert_put(cv, ctags_x);
		convert_close(cv);
		strbuf_close(ib);
		exit(0);
	} else if (dump_target) {
		/*
		 * Dump a tag file.
		 */
		DBOP *dbop = NULL;
		const char *dat = 0;
		int is_gpath = 0;

		char* target_file = NULL;
		if (!test("f", dump_target)) {
			target_file = strchr(dump_target, ':');
			if (target_file == NULL) 
				die("file '%s' not found", dump_target);

			*target_file++ = 0; //move to the next char, which starts the target file.
			if (!test("f", dump_target)) {
				die("file '%s' not found.", dump_target);
			}
		}

		if ((dbop = dbop_open(dump_target, 0, 0, DBOP_RAW)) == NULL)
			die("file '%s' is not a tag file.", dump_target);
		/*
		 * The file which has a NEXTKEY record is GPATH.
		 */
		if (dbop_get(dbop, NEXTKEY))
			is_gpath = 1;

		if (target_file && !is_gpath) {
			die("dump target_file can only be used with GPATH");
		}

		if (target_file) {
			dat = dbop_get(dbop, target_file);
			if (dat == NULL) {
				die("target_file %s not found in GPATH", target_file);
			}
			time_t t = gpath_mtime(dbop, target_file);
			printf("%d\n", t);
		} else {
			for (dat = dbop_first(dbop, NULL, NULL, 0); dat != NULL; dat = dbop_next(dbop)) {
				const char *flag = is_gpath ? dbop_getflag(dbop) : "";

				if (*flag)
					if (is_gpath) {
						time_t t = gpath_mtime(dbop, dbop->lastkey);
						printf("%s\t%s\t%s\t%s\n", dbop->lastkey, dat, flag, ctime(&t));
					} else
						printf("%s\t%s\t%s\n", dbop->lastkey, dat, flag);
				else
					printf("%s\t%s\n", dbop->lastkey, dat);
			}
		}
		dbop_close(dbop);
		exit(0);
	} else if (Iflag) {
		if (!usable("mkid"))
			die("mkid not found.");
	}

	/*
	 * If 'gtags.files' exists, use it as a file list.
	 * If the file_list other than "-" is given, it must be readable file.
	 */
	if (file_list == NULL && test("f", GTAGSFILES))
		file_list = GTAGSFILES;
	if (file_list && strcmp(file_list, "-")) {
		if (test("d", file_list))
			die("'%s' is a directory.", file_list);
		else if (!test("f", file_list))
			die("'%s' not found.", file_list);
		else if (!test("r", file_list))
			die("'%s' is not readable.", file_list);
	}
	/*
	 * Regularize the path name for single updating (--single-update).
	 */
	if (single_update) {
		static char regular_path_name[MAXPATHLEN];
		char *p = single_update;
		
		if (!test("f", p))
			die("'%s' not found.", p);
		if (isabspath(p))
			die("--single-update requires relative path name.");
		if (!(p[0] == '.' && p[1] == '/')) {
			snprintf(regular_path_name, MAXPATHLEN, "./%s", p);
			p = regular_path_name;
		}
		single_update = p;
	}
	if (!getcwd(cwd, MAXPATHLEN))
		die("cannot get current directory.");
	canonpath(cwd);
	/*
	 * Decide directory (dbpath) in which gtags make tag files.
	 *
	 * Gtags create tag files at current directory by default.
	 * If dbpath is specified as an argument then use it.
	 * If the -i option specified and both GTAGS and GRTAGS exists
	 * at one of the candidate directories then gtags use existing
	 * tag files.
	 */
	if (iflag) {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (!gtagsexist(cwd, dbpath, MAXPATHLEN, vflag))
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	} else {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (Oflag) {
			char *objdir = getobjdir(cwd, vflag);

			if (objdir == NULL)
				die("Objdir not found.");
			strlimcpy(dbpath, objdir, sizeof(dbpath));
		} else
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	}
	if (iflag && (!test("f", makepath(dbpath, dbname(GTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GRTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GPATH), NULL)))) {
		if (wflag)
			warning("GTAGS, GRTAGS or GPATH not found. -i option ignored.");
		iflag = 0;
	}
	if (!test("d", dbpath))
		die("directory '%s' not found.", dbpath);
	if (vflag)
		fprintf(stderr, "[%s] Gtags started.\n", now());
	/*
	 * load configuration file.
	 */
	openconf();
	if (getconfb("extractmethod"))
		extractmethod = 1;
	strbuf_reset(sb);
	if (getconfs("langmap", sb))
		langmap = check_strdup(strbuf_value(sb));
	strbuf_reset(sb);
	if (getconfs("gtags_parser", sb))
		gtags_parser = check_strdup(strbuf_value(sb));
	/*
	 * initialize parser.
	 */
	if (vflag && gtags_parser)
		fprintf(stderr, " Using plug-in parser.\n");
	parser_init(langmap, gtags_parser);
	if (vflag && file_list)
		fprintf(stderr, " Using '%s' as a file list.\n", file_list);
	/*
	 * Start statistics.
	 */
	init_statistics();
	/*
	 * incremental update.
	 */
	if (iflag) {
		/*
		 * Version check. If existing tag files are old enough
		 * gtagsopen() abort with error message.
		 */
		GTOP *gtop = gtags_open(dbpath, cwd, GTAGS, GTAGS_MODIFY, 0);
		gtags_close(gtop);
		/*
		 * GPATH is needed for incremental updating.
		 * Gtags check whether or not GPATH exist, since it may be
		 * removed by mistake.
		 */
		if (!test("f", makepath(dbpath, dbname(GPATH), NULL)))
			die("Old version tag file found. Please remake it.");
		(void)incremental(dbpath, cwd);
		print_statistics(statistics);
		exit(0);
	}
	/*
	 * create GTAGS and GRTAGS
	 */
	createtags(dbpath, cwd);
	/*
	 * create idutils index.
	 */
	if (Iflag) {
		tim = statistics_time_start("Time of creating ID");
		if (vflag)
			fprintf(stderr, "[%s] Creating indexes for idutils.\n", now());
		strbuf_reset(sb);
		strbuf_puts(sb, "mkid");
		if (vflag)
			strbuf_puts(sb, " -v");
		strbuf_sprintf(sb, " --file='%s/ID'", dbpath);
		if (vflag) {
#ifdef __DJGPP__
			if (is_unixy())	/* test for 4DOS as well? */
#endif
			strbuf_puts(sb, " 1>&2");
		} else {
			strbuf_puts(sb, " >/dev/null");
		}
		if (debug)
			fprintf(stderr, "executing mkid like: %s\n", strbuf_value(sb));
		if (system(strbuf_value(sb)))
			die("mkid failed: %s", strbuf_value(sb));
		if (chmod(makepath(dbpath, "ID", NULL), 0644) < 0)
			die("cannot chmod ID file.");
		statistics_time_end(tim);
	}
	if (vflag)
		fprintf(stderr, "[%s] Done.\n", now());
	closeconf();
	strbuf_close(sb);
	print_statistics(statistics);

	return 0;
}
Esempio n. 22
0
int main(int argc, char *argv[])
{
     World *w;
     View *view;
     Intent *intent;
     Graphics_info *ginfo;
     Tcl_Interp *interp;
     Object *me;
     Boolean quit = False;
#if PROFILE
     int fps_count = 0;
     double total_time = 0.0;
     double start_time;
#endif


     interp = Tcl_CreateInterp();
     updater = updater_create(interp);

     if (argc != 2) {
	  fprintf(stderr, "Usage:  %s <world file>\n", argv[0]);
	  exit(EXIT_FAILURE);
     }

     ginfo = init_graphics();
#define TRUECOLOR
#ifdef TRUECOLOR
     set_texture_trans(32, ginfo->palette.color_lookup);
#else
     set_texture_trans(ginfo->palette.rgb_cube_size,
		       ginfo->palette.color_lookup);
#endif
     init_renderer(ginfo->width, ginfo->height);
     init_input_devices();

     /* Initialize the view */
     view = new_view(FLOAT_TO_FIXED(3.14159265 / 2.0));

     w = new_world();

     parser_init(interp, w);
     if (Tcl_EvalFile(interp, WT_INIT_FILENAME) != TCL_OK) {
	  fprintf(stderr, "%s\n", Tcl_GetVar(interp, "errorCode", 0));
	  fprintf(stderr, "%s\n", Tcl_GetVar(interp, "errorInfo", 0));
	  exit(1);
     }

     if (Tcl_EvalFile(interp, argv[1]) != TCL_OK) {
	  fprintf(stderr, "%s\n", Tcl_GetVar(interp, "errorCode", 0));
	  fprintf(stderr, "%s\n", Tcl_GetVar(interp, "errorInfo", 0));
	  exit(1);
     }


     while (!quit) {
	  double sin_facing, cos_facing;
	  double fx, fy, fz, torque;
	  Framebuffer *fb;
	  int i;


	  start_time = current_time();

	  intent = read_input_devices();
	  
	  me = get_controlled_object();
	  if (me == NULL)
	       fatal_error("No controlled object");

	  for (i = 0; i < intent->n_special; i++) {

	       switch (intent->special[i]) {
		  case INTENT_END_GAME:
		    quit = True;
		    (void) Tcl_Eval(interp, "action_quit");
		    break;

		  case INTENT_JUMP:
		    (void) Tcl_Eval(interp, "action_jump");
		    break;

		  case INTENT_ACTION1:
		    (void) Tcl_Eval(interp, "action_1");
		    break;

		  case INTENT_ACTION2:
		    (void) Tcl_Eval(interp, "action_2");
		    break;

		  case INTENT_ACTION3:
		    (void) Tcl_Eval(interp, "action_3");
		    break;

		  case INTENT_ACTION4:
		    (void) (Tcl_Eval(interp, "action_4") != TCL_OK);
		    break;

		  case INTENT_ACTION5:
		    (void) Tcl_Eval(interp, "action_5");
		    break;

		  default:
		    break;
	       }
	  }

	  /* Determine forces on viewer. */
	  sin_facing = sin(me->angle);
	  cos_facing = cos(me->angle);
	  fx = cos_facing * intent->force_x - sin_facing * intent->force_y;
	  fy = sin_facing * intent->force_x + cos_facing * intent->force_y;
 	  fz = -0.05 * me->mass;  /* gravity */
	  torque = intent->force_rotate;

	  /* Apply the forces. */
	  object_apply_force(me, fx, fy, fz);
	  object_apply_torque(me, torque);
	  object_update(me);
	  if (me->z <= 0.0 && me->dz <= 0.0) {
	       me->z = 0.0;
	       me->dz = 0.0;
	  }

	  /* Determine the view. */
	  me = get_viewpoint_object();
	  if (me == NULL)
	       fatal_error("No viewpoint object");
	  object_view(me, view);

	  updater_run(updater);

	  /* Display the world. */
	  fb = render(w, view);
	  update_screen(fb);
#if PROFILE
	  fps_count++;
	  total_time += current_time() - start_time;
	  if (fps_count == 100) {
	       printf("fps = %3.2f\n", (double) fps_count / total_time);
	       fps_count = 0;
	       total_time = 0.0;
	  }
#endif
     }

     end_input_devices();
     end_graphics();

     return EXIT_SUCCESS;
}
Esempio n. 23
0
int main (int argc, char *argv[]) 
{
   int sts;
   int i;
   int buflen;
   int access;
   char buff [BUFFER_SIZE];
   sip_ticket_t ticket;

   extern char *optarg;         /* Defined in libc getopt and unistd.h */
   int ch1;
   
   char configfile[64]="siproxd";       /* basename of configfile */
   int  config_search=1;                /* search the config file */
   int  cmdline_debuglevel=0;
   char *pidfilename=NULL;
   struct sigaction act;

   log_set_stderr(1);

/*
 * setup signal handlers
 */
   act.sa_handler=sighandler;
   sigemptyset(&act.sa_mask);
   act.sa_flags=SA_RESTART;
   if (sigaction(SIGTERM, &act, NULL)) {
      ERROR("Failed to install SIGTERM handler");
   }
   if (sigaction(SIGINT, &act, NULL)) {
      ERROR("Failed to install SIGINT handler");
   }
   if (sigaction(SIGUSR2, &act, NULL)) {
      ERROR("Failed to install SIGUSR2 handler");
   }


/*
 * prepare default configuration
 */
   make_default_config();

   log_set_pattern(configuration.debuglevel);

/*
 * parse command line
 */
{
#ifdef  HAVE_GETOPT_LONG
   int option_index = 0;
   static struct option long_options[] = {
      {"help", no_argument, NULL, 'h'},
      {"config", required_argument, NULL, 'c'},
      {"debug", required_argument, NULL, 'd'},
      {"pid-file", required_argument, NULL,'p'},
      {0,0,0,0}
   };

    while ((ch1 = getopt_long(argc, argv, "hc:d:p:",
                  long_options, &option_index)) != -1) {
#else   /* ! HAVE_GETOPT_LONG */
    while ((ch1 = getopt(argc, argv, "hc:d:p:")) != -1) {
#endif
      switch (ch1) {
      case 'h': /* help */
         DEBUGC(DBCLASS_CONFIG,"option: help");
         fprintf(stderr,str_helpmsg);
         exit(0);
         break;

      case 'c': /* load config file */
         DEBUGC(DBCLASS_CONFIG,"option: config file=%s",optarg);
         i=sizeof(configfile)-1;
         strncpy(configfile,optarg,i-1);
         configfile[i]='\0';
         config_search=0;
         break; 

      case 'd': /* set debug level */
         DEBUGC(DBCLASS_CONFIG,"option: set debug level: %s",optarg);
         cmdline_debuglevel=atoi(optarg);
         log_set_pattern(cmdline_debuglevel);
         break;

      case 'p':
         pidfilename = optarg;
         break;

      default:
         DEBUGC(DBCLASS_CONFIG,"no command line options");
         break; 
      }
   }
}

/*
 * Init stuff
 */
   INFO(PACKAGE"-"VERSION"-"BUILDSTR" "UNAME" starting up");

   /* read the config file */
   if (read_config(configfile, config_search) == STS_FAILURE) exit(1);

   /* if a debug level > 0 has been given on the commandline use its
      value and not what is in the config file */
   if (cmdline_debuglevel != 0) {
      configuration.debuglevel=cmdline_debuglevel;
   }

/*
 * open a the pwfile instance, so we still have access after
 * we possibly have chroot()ed to somewhere.
 */
   if (configuration.proxy_auth_pwfile) {
      siproxd_passwordfile = fopen(configuration.proxy_auth_pwfile, "r");
   } else {
      siproxd_passwordfile = NULL;
   }

   /* set debug level as desired */
   log_set_pattern(configuration.debuglevel);
   log_set_listen_port(configuration.debugport);

   /* change user and group IDs */
   secure_enviroment();

   /* daemonize if requested to */
   if (configuration.daemonize) {
      DEBUGC(DBCLASS_CONFIG,"daemonizing");
      if (fork()!=0) exit(0);
      setsid();
      if (fork()!=0) exit(0);

      log_set_stderr(0);
      INFO("daemonized, pid=%i", getpid());
   }

   /* write PID file of main thread */
   if (pidfilename == NULL) pidfilename = configuration.pid_file;
   if (pidfilename) {
      FILE *pidfile;
      DEBUGC(DBCLASS_CONFIG,"creating PID file [%s]", pidfilename);
      sts=unlink(configuration.pid_file);
      if ((sts==0) ||(errno == ENOENT)) {
         if ((pidfile=fopen(pidfilename, "w"))) {
            fprintf(pidfile,"%i\n",(int)getpid());
            fclose(pidfile);
         } else {
            WARN("couldn't create new PID file: %s", strerror(errno));
         }
      } else {
         WARN("couldn't delete old PID file: %s", strerror(errno));
      }
   }

   /* initialize the RTP proxy */
   sts=rtpproxy_init();
   if (sts != STS_SUCCESS) {
      ERROR("unable to initialize RTP proxy - aborting"); 
      exit(1);
   }

   /* init the oSIP parser */
   parser_init();

   /* listen for incoming messages */
   sts=sipsock_listen();
   if (sts == STS_FAILURE) {
      /* failure to allocate SIP socket... */
      ERROR("unable to bind to SIP listening socket - aborting"); 
      exit(1);
   }

   /* initialize the registration facility */
   register_init();

/*
 * silence the log - if so required...
 */
   log_set_silence(configuration.silence_log);

   INFO(PACKAGE"-"VERSION"-"BUILDSTR" "UNAME" started");

/*****************************
 * Main loop
 *****************************/
   while (!exit_program) {

      DEBUGC(DBCLASS_BABBLE,"going into sipsock_wait\n");
      while (sipsock_wait()<=0) {
         /* got no input, here by timeout. do aging */
         register_agemap();

         /* TCP log: check for a connection */
         log_tcp_connect();

         /* dump memory stats if requested to do so */
         if (dmalloc_dump) {
            dmalloc_dump=0;
#ifdef DMALLOC
            INFO("SIGUSR2 - DMALLOC statistics is dumped");
            dmalloc_log_stats();
            dmalloc_log_unfreed();
#else
            INFO("SIGUSR2 - DMALLOC support is not compiled in");
#endif
         }

         if (exit_program) goto exit_prg;
      }

      /*
       * got input, process
       */
      DEBUGC(DBCLASS_BABBLE,"back from sipsock_wait");
      ticket.direction=0;

      buflen=sipsock_read(&buff, sizeof(buff)-1, &ticket.from,
                           &ticket.protocol);
      buff[buflen]='\0';

      /*
       * evaluate the access lists (IP based filter)
       */
      access=accesslist_check(ticket.from);
      if (access == 0) {
         DEBUGC(DBCLASS_ACCESS,"access for this packet was denied");
         continue; /* there are no resources to free */
      }

      /*
       * integrity checks
       */
      sts=security_check_raw(buff, buflen);
      if (sts != STS_SUCCESS) {
         DEBUGC(DBCLASS_SIP,"security check (raw) failed");
         continue; /* there are no resources to free */
      }

      /*
       * init sip_msg
       */
      sts=osip_message_init(&ticket.sipmsg);
      ticket.sipmsg->message=NULL;
      if (sts != 0) {
         ERROR("osip_message_init() failed... this is not good");
         continue; /* skip, there are no resources to free */
      }

      /*
       * RFC 3261, Section 16.3 step 1
       * Proxy Behavior - Request Validation - Reasonable Syntax
       * (parse the received message)
       */
      sts=sip_message_parse(ticket.sipmsg, buff, buflen);
      if (sts != 0) {
         ERROR("sip_message_parse() failed... this is not good");
         DUMP_BUFFER(-1, buff, buflen);
         goto end_loop; /* skip and free resources */
      }

      /*
       * integrity checks - parsed buffer
       */
      sts=security_check_sip(&ticket);
      if (sts != STS_SUCCESS) {
         ERROR("security_check_sip() failed... this is not good");
         DUMP_BUFFER(-1, buff, buflen);
         goto end_loop; /* skip and free resources */
      }

      /*
       * RFC 3261, Section 16.3 step 2
       * Proxy Behavior - Request Validation - URI scheme
       * (check request URI and refuse with 416 if not understood)
       */
      /* NOT IMPLEMENTED */

      /*
       * RFC 3261, Section 16.3 step 3
       * Proxy Behavior - Request Validation - Max-Forwards check
       * (check Max-Forwards header and refuse with 483 if too many hops)
       */
      {
         osip_header_t *max_forwards;
         int forwards_count = DEFAULT_MAXFWD;

         osip_message_get_max_forwards(ticket.sipmsg, 0, &max_forwards);
         if (max_forwards && max_forwards->hvalue) {
            forwards_count = atoi(max_forwards->hvalue);
         }

         DEBUGC(DBCLASS_PROXY,"checking Max-Forwards (=%i)",forwards_count);
         if (forwards_count <= 0) {
            DEBUGC(DBCLASS_SIP, "Forward count reached 0 -> 483 response");
            sip_gen_response(&ticket, 483 /*Too many hops*/);
            goto end_loop; /* skip and free resources */
         }
      }

      /*
       * RFC 3261, Section 16.3 step 4
       * Proxy Behavior - Request Validation - Loop Detection check
       * (check for loop and return 482 if a loop is detected)
       */
      if (check_vialoop(&ticket) == STS_TRUE) {
         /* make sure we don't end up in endless loop when detecting
          * an loop in an "loop detected" message - brrr */
         if (MSG_IS_RESPONSE(ticket.sipmsg) && 
             MSG_TEST_CODE(ticket.sipmsg, 482)) {
            DEBUGC(DBCLASS_SIP,"loop in loop-response detected, ignoring");
         } else {
            DEBUGC(DBCLASS_SIP,"via loop detected, ignoring request");
            sip_gen_response(&ticket, 482 /*Loop detected*/);
         }
         goto end_loop; /* skip and free resources */
      }

      /*
       * RFC 3261, Section 16.3 step 5
       * Proxy Behavior - Request Validation - Proxy-Require check
       * (check Proxy-Require header and return 420 if unsupported option)
       */
      /* NOT IMPLEMENTED */

      /*
       * RFC 3261, Section 16.5
       * Proxy Behavior - Determining Request Targets
       */
      /* NOT IMPLEMENTED */

      DEBUGC(DBCLASS_SIP,"received SIP type %s:%s",
             (MSG_IS_REQUEST(ticket.sipmsg))? "REQ" : "RES",
             (MSG_IS_REQUEST(ticket.sipmsg) ?
                ((ticket.sipmsg->sip_method)?
                   ticket.sipmsg->sip_method : "NULL") :
                ((ticket.sipmsg->reason_phrase) ? 
                   ticket.sipmsg->reason_phrase : "NULL")));

      /*********************************
       * The message did pass all the
       * tests above and is now ready
       * to be proxied.
       * Before we do so, we apply some
       * additional preprocessing
       *********************************/
      /* Dial shortcuts */
      if (configuration.pi_shortdial) {
         sts = plugin_shortdial(&ticket);
         if (sts == STS_SIP_SENT) goto end_loop;
      }


      /*********************************
       * finally proxy the message.
       * This includes the masquerading
       * of the local UA and starting/
       * stopping the RTP proxy for this
       * call
       *********************************/

      /*
       * if a REQ REGISTER, check if it is directed to myself,
       * or am I just the outbound proxy but no registrar.
       * - If I'm the registrar, register & generate answer
       * - If I'm just the outbound proxy, register, rewrite & forward
       */
      if (MSG_IS_REGISTER(ticket.sipmsg) && 
          MSG_IS_REQUEST(ticket.sipmsg)) {
         if (access & ACCESSCTL_REG) {
            osip_uri_t *url;
            struct in_addr addr1, addr2, addr3;
            int dest_port;

            url = osip_message_get_uri(ticket.sipmsg);
            dest_port= (url->port)?atoi(url->port):SIP_PORT;

            if ( (get_ip_by_host(url->host, &addr1) == STS_SUCCESS) &&
                 (get_interface_ip(IF_INBOUND,&addr2) == STS_SUCCESS) &&
                 (get_interface_ip(IF_OUTBOUND,&addr3) == STS_SUCCESS)) {

               if ((configuration.sip_listen_port == dest_port) &&
                   ((memcmp(&addr1, &addr2, sizeof(addr1)) == 0) ||
                    (memcmp(&addr1, &addr3, sizeof(addr1)) == 0))) {
                  /* I'm the registrar, send response myself */
                  sts = register_client(&ticket, 0);
                  sts = register_response(&ticket, sts);
               } else {
                  /* I'm just the outbound proxy */
                  DEBUGC(DBCLASS_SIP,"proxying REGISTER request to:%s",
                         url->host);
                  sts = register_client(&ticket, 1);
                  if (sts == STS_SUCCESS) {
                     sts = proxy_request(&ticket);
                  }
               }
            } else {
               sip_gen_response(&ticket, 408 /*request timeout*/);
            }
         } else {
            WARN("non-authorized registration attempt from %s",
                 utils_inet_ntoa(ticket.from.sin_addr));
         }

      /*
       * check if outbound interface is UP.
       * If not, send back error to UA and
       * skip any proxying attempt
       */
      } else if (get_interface_ip(IF_OUTBOUND,NULL) !=
                 STS_SUCCESS) {
         DEBUGC(DBCLASS_SIP, "got a %s to proxy, but outbound interface "
                "is down", (MSG_IS_REQUEST(ticket.sipmsg))? "REQ" : "RES");

         if (MSG_IS_REQUEST(ticket.sipmsg))
            sip_gen_response(&ticket, 408 /*request timeout*/);
      
      /*
       * MSG is a request, add current via entry,
       * do a lookup in the URLMAP table and
       * send to the final destination
       */
      } else if (MSG_IS_REQUEST(ticket.sipmsg)) {
         if (access & ACCESSCTL_SIP) {
            sts = proxy_request(&ticket);
         } else {
            INFO("non-authorized request received from %s",
                 utils_inet_ntoa(ticket.from.sin_addr));
         }

      /*
       * MSG is a response, remove current via and
       * send to the next VIA in chain
       */
      } else if (MSG_IS_RESPONSE(ticket.sipmsg)) {
         if (access & ACCESSCTL_SIP) {
            sts = proxy_response(&ticket);
         } else {
            INFO("non-authorized response received from %s",
                 utils_inet_ntoa(ticket.from.sin_addr));
         }
         
      /*
       * unsupported message
       */
      } else {
         ERROR("received unsupported SIP type %s %s",
               (MSG_IS_REQUEST(ticket.sipmsg))? "REQ" : "RES",
               ticket.sipmsg->sip_method);
      }

      /*********************************
       * Done with proxying. Message
       * has been sent to its destination.
       *********************************/
/*
 * free the SIP message buffers
 */
      end_loop:
      osip_message_free(ticket.sipmsg);

   } /* while TRUE */
   exit_prg:

   /* save current known SIP registrations */
   register_save();
   INFO("properly terminating siproxd");

   /* remove PID file */
   if (pidfilename) {
      DEBUGC(DBCLASS_CONFIG,"deleting PID file [%s]", pidfilename);
      sts=unlink(pidfilename);
      if (sts != 0) {
         WARN("couldn't delete old PID file: %s", strerror(errno));
      }
   }

   /* END */
   return 0;
} /* main */

/*
 * Signal handler
 *
 * this one is called asynchronously whevener a registered
 * signal is applied. Just set a flag and don't do any funny
 * things here.
 */
static void sighandler(int sig) {
   if (sig==SIGTERM) exit_program=1;
   if (sig==SIGINT)  exit_program=1;
   if (sig==SIGUSR2) dmalloc_dump=1;
   return;
}
Esempio n. 24
0
NODE* parse(char **exp) {
    if (!sym_map) parser_init();
    debug("Parse List: %s\n",*exp);
    NODE *head = NIL;
    while (**exp) {
        switch (*((*exp)++)) {
            case '\'': {
                debug("to quote: %s\n",*exp);
                NODE *quoted = parse(exp);
                debugVal(quoted->data,"quoted: ");
                list_push(newNODE(newPRIMFUNC(SPEC_QUOTE,l_quote),newNODE(quoted->data,NIL)),&head);
                if (quoted->addr) head = list_join(list_reverse((NODE*)quoted->addr),head);
                head = list_reverse(head);
                debugVal(head,"expression: ");
                return head;
            }
            case '(':
                list_push(parse(exp),&head);
                break;
            case ')':
                head = list_reverse(head);
                debugVal(head,"expression: ");
                return head;
            case ';':
                while (**exp != '\0' && **exp != '\r' && **exp != '\n') (*exp)++;
                break;
            case '\n':
            case '\r':
            case '\t':
            case ' ':
                break;
            default: {
                char *sym = *exp-1;
                debug("origin: %s\n",sym);
                while (**exp && **exp != ' ' && **exp != ')' && **exp != '\n' && **exp != '\r' && **exp != '\t') (*exp)++;
                char old = **exp;
                **exp = 0;
                debug("literal: %s\n",sym);
                switch (sym[0]) {
                    case '+':
                    case '-':
                        if (!isdigit(sym[1])) {
                            list_push(newSYMBOL(intern(sym)),&head);
                            break;
                        }  
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                        {
                            bool real = false;
                            char *scn = sym+1;
                            while (*scn) {
                                if (*scn == '.') { 
                                    real = true;
                                } else if (!isdigit(*scn)) {
                                    error("Malformed number character %c",*scn);
                                }
                                scn++;
                            }
                            if (real) {
                                list_push(newREAL(atof(sym)),&head);
                            } else {
                                list_push(newINTEGER(atoi(sym)),&head);
                            }
                        }
                        break;
                    default:
                        list_push(newSYMBOL(intern(sym)),&head);
                        break;
                 }
                 **exp = old;
                 if (head->data->type == ID_SYMBOL) {
                    NODE *literal;
                    if ((literal = binmap_find(head->data,literal_map))) {
                        NODE *last = (NODE*)head->addr;
                        incRef(last);
                        decRef(head);
                        incRef(literal->addr);
                        head = last;
                        list_push(literal->addr,&head);
                        decRef(literal);
                    }
                 }
                 debugVal(head,"parsed: ");
             }
        }
    }
    head = list_reverse(head);
    debugVal(head,"dangling: ");
    return head;
}
Esempio n. 25
0
syntax_error *lang_CPP::definitionsModified(const char* wscode, const char* targetYaml)
{
  cout << "Parsing settings..." << endl;
    parse_ide_settings(targetYaml);
  
  cout << targetYaml << endl;
  
  cout << "Creating swap." << endl;
  delete main_context;
  main_context = new jdi::context();
  
  cout << "Dumping whiteSpace definitions..." << endl;
  FILE *of = wscode ? fopen((makedir +"Preprocessor_Environment_Editable/IDE_EDIT_whitespace.h").c_str(),"wb") : NULL;
  if (of) fputs(wscode,of), fclose(of);
  
  cout << "Opening ENIGMA for parse..." << endl;
  
  llreader f("ENIGMAsystem/SHELL/SHELLmain.cpp");
  int res = 1;
  DECLARE_TIME();
  if (f.is_open()) {
    START_TIME();
    res = main_context->parse_C_stream(f, "SHELLmain.cpp");
    STOP_TIME();
  }
  
  jdi::definition *d;
  if ((d = main_context->get_global()->look_up("variant"))) {
    enigma_type__variant = d;   
    if (!(d->flags & jdi::DEF_TYPENAME))
      cerr << "ERROR! ENIGMA's variant is not a type!" << endl;
    else
      cout << "Successfully loaded builtin variant type" << endl;
  } else cerr << "ERROR! No variant type found!" << endl;
  if ((d = main_context->get_global()->look_up("var"))) {
    enigma_type__var = d;
    if (!(d->flags & jdi::DEF_TYPENAME))
      cerr << "ERROR! ENIGMA's var is not a type!" << endl;
    else
      cout << "Successfully loaded builtin var type" << endl;
  } else cerr << "ERROR! No var type found!" << endl;
  if ((d = main_context->get_global()->look_up("enigma"))) {
    if (d->flags & jdi::DEF_NAMESPACE) {
      if ((d = ((jdi::definition_scope*)d)->look_up("varargs"))) {
        enigma_type__varargs = d;
        if (!(d->flags & jdi::DEF_TYPENAME))
          cerr << "ERROR! ENIGMA's varargs is not a type!" << endl;
        else
          cout << "Successfully loaded builtin varargs type" << endl;
      } else cerr << "ERROR! No varargs type found!" << endl;
    } else cerr << "ERROR! Namespace enigma is... not a namespace!" << endl;
  } else cerr << "ERROR! Namespace enigma not found!" << endl;
  
  if (res) {
    cout << "ERROR in parsing engine file: The parser isn't happy. Don't worry, it's never happy.\n";
    cout << heaping_pile_of_dog_shit;
    
    ide_passback_error.set(0,0,0,"Parse failed; details in stdout. Bite me.");
    cout << "Continuing anyway." << endl;
    // return &ide_passback_error;
  } else {    
    cout << "Successfully parsed ENIGMA's engine (" << PRINT_TIME() << "ms)\n"
    << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
    //cout << "Namespace std contains " << global_scope.members["std"]->members.size() << " items.\n";
  }
  
  cout << "Creating dummy primitives for old ENIGMA" << endl;
  for (jdip::tf_iter it = jdip::builtin_declarators.begin(); it != jdip::builtin_declarators.end(); ++it) {
    main_context->get_global()->members[it->first] = new jdi::definition(it->first, main_context->get_global(), jdi::DEF_TYPENAME);
  }
  
  cout << "Initializing EDL Parser...\n";
  
  parser_init();
  
  cout << "Grabbing locals...\n";
  
  shared_locals_load(requested_extensions);
  
  cout << "Determining build target...\n";
  
  extensions::determine_target();
  
  cout << " Done.\n";
  
  return &ide_passback_error;
}
Esempio n. 26
0
File: main.c Progetto: Flyswat/wmmp
int main ( int argc, char *argv[] ) {

	parser_t * parser = NULL;
	uint key = 0, Nc = 0, Nv = 0, Ns = 0, epw, e;
	double wcr_start,
		wcr_step,
		wcr_end,
		wcr = 0.0;
	vec wcr_vec;

	mat 	U = NULL;


	if ( argc == 1 )
	{
		fprintf( stderr, "Usage: %s config.cfg\n", argv[0] );
		exit( EXIT_FAILURE );
	}

	parser = parser_init( argc, argv, argv[1], NULL );

	key = parser_get_int( parser, "KEY" );
	wcr_vec = parser_get_vec( parser, "WCR" );
	Nv  = parser_get_int( parser, "Nv" );
	Nc  = parser_get_int( parser, "Nc" );
	Ns  = parser_get_int( parser, "Ns" );
	epw  = parser_get_int( parser, "EPW" );
	parser_delete( parser );


	if (vec_length(wcr_vec) != 3)
	{
		fprintf( stderr, "Invalid config for WCR values\n" );
		exit( EXIT_FAILURE );
	}
	wcr_start = wcr_vec[0];
	wcr_step = wcr_vec[1];
	wcr_end = wcr_vec[2];

	U = make_carriers( Nc, Nv, key );

	for (wcr = wcr_start; wcr <= wcr_end; wcr += wcr_step)
	{
		for (e=0; e<epw;e++)
		{
			mat	U_est = NULL,
				Y = NULL,
				Y_attack = NULL;

			// gen watermarks with U
			Y = make_Y(Nv, Ns, Nc, U, wcr);

			// Estimated carriers from PCA
			U_est = estimate_carriers(Y, Nv, Nc);

			// Attack Y
			Y_attack = attack(Y,U_est);

			print_dist(Y,Y_attack,wcr);

			mat_delete( Y );
			mat_delete( Y_attack );
			mat_delete( U_est );
		}
	}

	mat_delete( U );

	exit( EXIT_SUCCESS );
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
  Timer t;
  parser_init();
  parse_commandline(argc,argv);
  DecisionForestDisc forest;

  int nthreads=MapReduceRunner::num_threads(param_set.nthreads.value);
  param_trnfile.nthreads.set_value(nthreads);
  param_tstfile.nthreads.set_value(nthreads);
  param_dt.nthreads.set_value(nthreads);
  assert(param_trnfile.nthreads.value==nthreads);
  assert(param_tstfile.nthreads.value==nthreads);
  assert(param_dt.nthreads.value==nthreads);
  if (param_set.verbose.value>=2) {
    cerr << " using up to " << nthreads << " threads" << endl;
  }
  param_rgf.verbose.set_value(param_set.verbose.value);

  bool pre_load= (param_rgf.eval_frequency.value>0)
    && (param_rgf.eval_frequency.value < param_rgf.ntrees.value)
    && param_tstfile.fn_x.value.size()>0;
    
  
  if (param_trnfile.fn_x.value.size()>0) {
    DataSetDisc trn;
    cerr << "loading training data ... " <<endl;
    param_trnfile.print_parameters(cerr);
    t=Timer("loading time");
    t.start();
    trn.append(param_trnfile);
    t.stop();
    t.print();

    if (pre_load) {
      tst_out.read_tstfile();
    }
    cerr <<endl<<endl;
    cout << "training decision forest ... " <<endl;
    param_dt.print_parameters(cerr);
    param_rgf.print_parameters(cerr);

    cerr <<endl<<endl;
    t=Timer("training time");
    t.start();
    forest.train(trn, 0, param_dt,param_rgf,tst_out.tst);
    t.stop();
    t.print();
  }
  
  
  if (param_modelfile.load_filename.value.size()>0) {
    cerr << endl <<endl;
    cerr << "loading forest model from <" << param_modelfile.load_filename.value
	 << ">" <<endl;
    ifstream is(param_modelfile.load_filename.value);
    if (!is.good()) {
      cerr << "cannot open model file for reading " <<endl;
    }
    else {
      forest.read(is);
    }
    is.close();
  }

  
  if (tst_out.tst.size()==0) {
    tst_out.read_tstfile();
  }  
  tst_out.print_outputs(forest,0,nthreads);

  
  if (param_modelfile.disc_model_file.value.size()>0) {
    cerr << "loading data discretization model from <" << param_modelfile.disc_model_file.value
	 << ">" <<endl;
    ifstream is(param_modelfile.disc_model_file.value);
    if (!is.good()) {
      cerr << "cannot open <" << param_modelfile.disc_model_file.value <<">" <<endl;
    }
    DataDiscretizationInt disc;
    disc.read(is);
    is.close();
    cerr << "reverting data discretization in decision forest" <<endl;
    forest.revert_discretization(disc);
  }
  
  
  if (param_modelfile.save_filename.value.size()>0) {
    cerr << endl <<endl;
    cerr << "saving forest model to <" << param_modelfile.save_filename.value
	 << ">" <<endl;
    ofstream os(param_modelfile.save_filename.value);
    if (!os.good()) {
      cerr << "cannot open model file for writing " <<endl;
    }
    else {
      os.precision(10);
      forest.write(os);
    }
    os.close();
  }


}
Esempio n. 28
0
/* Initializes the playback engine */
int stream_init(void)
{
    void *mem;
    size_t memsize;

    stream_mgr.status = STREAM_STOPPED;
    stream_mgr_init_state();

    /* Initialize our window to the outside world first */
    rb->mutex_init(&stream_mgr.str_mtx);
    rb->mutex_init(&stream_mgr.actl_mtx);

    stream_mgr.q = &stream_mgr_queue;
    rb->queue_init(stream_mgr.q, false);

    /* sets audiosize and returns buffer pointer */
    mem = rb->plugin_get_audio_buffer(&memsize);

    /* Initialize non-allocator blocks first */
#ifndef HAVE_LCD_COLOR
    long greysize;

    /* Greylib init handles all necessary cache alignment */
    if (!grey_init(mem, memsize, GREY_BUFFERED|GREY_ON_COP,
                   LCD_WIDTH, LCD_HEIGHT, &greysize))
    {
        rb->splash(HZ, "greylib init failed!");
        return STREAM_ERROR;
    }

    mem += greysize;
    memsize -= greysize;

    grey_clear_display();
#endif /* !HAVE_LCD_COLOR */

    stream_mgr.thread = rb->create_thread(stream_mgr_thread,
        stream_mgr_thread_stack, sizeof(stream_mgr_thread_stack),
        0, "mpgstream_mgr" IF_PRIO(, PRIORITY_SYSTEM) IF_COP(, CPU));

    rb->queue_enable_queue_send(stream_mgr.q, &stream_mgr_queue_send,
                                stream_mgr.thread);

    if (stream_mgr.thread == 0)
    {
        rb->splash(HZ, "Could not create stream manager thread!");
        return STREAM_ERROR;
    }

    /* Wait for thread to initialize */
    stream_mgr_send_msg(STREAM_NULL, 0);

    /* Initialise our malloc buffer */
    if (!mpeg_alloc_init(mem, memsize))
    {
        rb->splash(HZ, "Out of memory in stream_init");
    }
    /* These inits use the allocator */
    else if (!pcm_output_init())
    {
        rb->splash(HZ, "Could not initialize PCM!");
    }
    else if (!audio_thread_init())
    {
        rb->splash(HZ, "Cannot create audio thread!");
    }
    else if (!video_thread_init())
    {
        rb->splash(HZ, "Cannot create video thread!");
    }
    /* Disk buffer takes max allotment of what's left so it must be last */
    else if (!disk_buf_init())
    {
        rb->splash(HZ, "Cannot create buffering thread!");
    }
    else if (!parser_init())
    {
        rb->splash(HZ, "Parser init failed!");
    }
    else
    {    
        return STREAM_OK;
    }

    return STREAM_ERROR;
}
Esempio n. 29
0
int alg_info_parse_str (struct alg_info *alg_info
		    , const char *alg_str
		    , const char **err_p
		    , void (*parser_init)(struct parser_context *p_ctx)
		    , void (*alg_info_add)(struct alg_info *alg_info
					  , int ealg_id, int ek_bits
					  , int aalg_id, int ak_bits
					  , int modp_id
					  , bool permitmann)
		    , const struct oakley_group_desc *(*lookup_group)(u_int16_t group)
		    , bool permitmann)
{
	struct parser_context ctx;
	int ret;
	const char *ptr;
	static char err_buf[256];
	*err_buf=0;

	(*parser_init)(&ctx);

	if (err_p) *err_p=NULL;

	/* use default if nul esp string */
	if (!*alg_str) 
	{
	    (*alg_info_add)(alg_info, 0, 0, 0, 0, 0, 0);
	}

	for(ret=0,ptr=alg_str;ret<ST_EOF;) 
	{
	    ctx.ch=*ptr++;
	    ret= parser_machine(&ctx);
	    switch(ret) 
	    {
	    case ST_END:
	    case ST_EOF:
		DBG(DBG_CRYPT, DBG_log("alg_info_parse_str() " "ealg_buf=%s aalg_buf=%s" "eklen=%d  aklen=%d",ctx.ealg_buf, ctx.aalg_buf,ctx.eklen, ctx.aklen));

		if (parser_alg_info_add(&ctx, alg_info, alg_info_add, lookup_group, permitmann)<0) 
		{
		    snprintf(err_buf, sizeof(err_buf), "%s, enc_alg=\"%s\", auth_alg=\"%s\", " "modp=\"%s\"",ctx.err,ctx.ealg_buf,ctx.aalg_buf,ctx.modp_buf);
		    goto err;
		}
		/* zero out for next run (ST_END) */
		parser_init(&ctx);
		break;

	    case ST_ERR:
		snprintf(err_buf, sizeof(err_buf), "%s, " "just after \"%.*s\"" " (old_state=%s)", ctx.err, (int)(ptr-alg_str-1), alg_str , parser_state_name_esp(ctx.old_state) );	
		goto err;
	    default:
		if (!ctx.ch) break;
	    }
	}
	return 0;
 err:
	if (err_p) 
	{
	    *err_p=err_buf;
	}
	return -1;
}
Esempio n. 30
0
int main(int argc, char **argv) {

  struct precision pr;        /* for precision parameters */
  struct background ba;       /* for cosmological background */
  struct thermo th;           /* for thermodynamics */
  struct perturbs pt;         /* for source functions */
  struct bessels bs;          /* for bessel functions */
  struct transfers tr;        /* for transfer functions */
  struct primordial pm;       /* for primordial spectra */
  struct spectra sp;          /* for output spectra */
  struct lensing le;          /* for lensed spectra */
  struct output op;           /* for output files */
  struct spectra_nl nl;       /* for calculation of non-linear spectra */

  ErrorMsg errmsg;

  int i,l_max,l;

  struct file_content fc;

  double parameter_initial,parameter_logstep;
  double * parameter;
  int param_num;

  double *** cl;
  double ** noise;
  double chi2,chi2_bis;
  double percentage,max_percentage;
  int max_l;
  int ref_run;
  
  l_max=2500;

  parser_init(&fc,4,errmsg);

  strcpy(fc.name[0],"output");
  strcpy(fc.value[0],"tCl,pCl");

  strcpy(fc.name[1],"l_max_scalars");
  sprintf(fc.value[1],"%d",l_max);
 
/*   strcpy(fc.name[2],"perturbations_verbose"); */
/*   sprintf(fc.value[2],"%d",2); */

/*******************************************************/

  strcpy(fc.name[2],"lensing");
  strcpy(fc.value[2],"no");

  strcpy(fc.name[3],"transfer_cut_threshold_cl");

  parameter_initial=1.e-7;
  parameter_logstep=1.3;

  param_num=30;
  ref_run=0;

/*******************************************************/

  class_alloc(cl,param_num*sizeof(double**),errmsg);
  class_alloc(parameter,param_num*sizeof(double),errmsg);
  for (i=0; i<param_num; i++) {
    class_alloc(cl[i],(l_max+1)*sizeof(double*),errmsg);
    class_calloc(noise,(l_max+1),sizeof(double*),errmsg);
    for (l=2; l <= l_max; l++) {
      class_alloc(cl[i][l],3*sizeof(double),errmsg);
      class_calloc(noise[l],3,sizeof(double),errmsg);
    }
  }

  for (i=0; i<param_num; i++) {

    parameter[i] = parameter_initial * exp((double)i*log(parameter_logstep));

/*       parameter[i] = parameter_initial -i; */

/*     if (i==0) { */
/*       sprintf(fc.value[2],"%d",tc_osc); */
/*       strcpy(fc.name[3],"transfer_cut_threshold_osc"); */
/*       sprintf(fc.value[3],"%g",0.013); */
/*     } */
/*     else  { */
/*       sprintf(fc.value[2],"%d",tc_cl); */
/*       strcpy(fc.name[3],"transfer_cut_threshold_cl"); */
/*       sprintf(fc.value[3],"%g",8.e-7); */
/*     } */

/*     sprintf(fc.value[2],"%g",parameter[i]); */
      sprintf(fc.value[3],"%g",parameter[i]);
/*     sprintf(fc.value[3],"%d",(int)parameter[i]); */
 /*    sprintf(fc.value[2],"%d",1); */

    fprintf(stderr,"#run %d/%d with %s\n",i+1,param_num,fc.value[3]);

    if (input_init(&fc,&pr,&ba,&th,&pt,&bs,&tr,&pm,&sp,&le,&op,&nl,errmsg) == _FAILURE_) {
      printf("\n\nError running input_init_from_arguments \n=>%s\n",errmsg); 
      return _FAILURE_;
    }

    if (i==0) {
      
      if (bessel_init(&pr,&bs) == _FAILURE_) {
	printf("\n\nError in bessel_init \n =>%s\n",bs.error_message);
	return _FAILURE_;
      }
    }


 /*    class(&pr,&ba,&th,&pt,&bs,&tr,&pm,&sp,&le,&op,l_max,cl[i],errmsg); */
    class_assuming_bessels_computed(&pr,&ba,&th,&pt,&bs,&tr,&pm,&sp,&le,&op,l_max,cl[i],errmsg);
    

/*     for (l=2; l <= 2500; l++) */
/*       printf("%d %e %e %e\n",l, */
    /* 	     (l*(l+1)/2./_PI_)*cl[i][l][0],  */ /* here cl is the dimensionless C_l */ 
    /* 	     (l*(l+1)/2./_PI_)*cl[i][l][1],  */ /* multiply by pow((th.Tcmb*1.e6),2) for muK */ 
/* 	     (l*(l+1)/2./_PI_)*cl[i][l][2]); */
      
/*     printf("\n"); */
    
  }

  if (bessel_free(&bs) == _FAILURE_)  {
    printf("\n\nError in bessel_free \n=>%s\n",bs.error_message);
    return _FAILURE_;
  }

/*   for (i=0; i<param_num-1; i++) { */

/*     chi2=0; */
/*     max_percentage = 0.; */
/*     max_l = 0; */
/*     for (l=2; l <= 2500; l++) { */
/*       chi2 += pow(((cl[i][l][0]-cl[param_num-1][l][0])/cl[param_num-1][l][0]),2); */
/*       percentage = fabs(cl[i][l][0]/cl[param_num-1][l][0]-1.)*100.; */
/*       if (percentage > max_percentage) { */
/* 	max_percentage = percentage; */
/* 	max_l = l; */
/*       } */
/*     } */

/*     chi2_simple(cl[i],cl[param_num-1],2500,&chi2_bis); */

/*     fprintf(stderr,"parameter=%e chi2=%e (%e) l=%d percentage=%g\n", */
/* 	    parameter[i],chi2,chi2_bis,max_l,max_percentage); */
/*   } */

  noise_planck(&ba,&th,&sp,noise,l_max);

/*   for (l=2;l<=l_max;l++) { */
/*     printf("%d  %e  %e  %e  %e  %e  %e\n",l, */
/* 	   (l*(l+1)/2./_PI_)*cl[0][l][0]*pow(th.Tcmb*1.e6,2), */
/* 	   (l*(l+1)/2./_PI_)*cl[0][l][1]*pow(th.Tcmb*1.e6,2), */
/* 	   (l*(l+1)/2./_PI_)*cl[0][l][2]*pow(th.Tcmb*1.e6,2), */
/* 	   (l*(l+1)/2./_PI_)*noise[l][0]*pow(th.Tcmb*1.e6,2), */
/* 	   (l*(l+1)/2./_PI_)*noise[l][1]*pow(th.Tcmb*1.e6,2), */
/* 	   (l*(l+1)/2./_PI_)*noise[l][2]*pow(th.Tcmb*1.e6,2)); */
/*   } */

  for (i=0; i<param_num; i++) {
   
    chi2_planck(&sp,cl[i],cl[ref_run],noise,l_max,&chi2);

    if (chi2>0.1) {
      fprintf(stderr,"parameter=%e BAD: chi2=%2g \n",
	      parameter[i],chi2);
    }
    else {
      fprintf(stderr,"parameter=%e OK : chi2=%e \n",
	      parameter[i],chi2);
    }
  }

  return _SUCCESS_;

}