Exemple #1
0
void 
add_srcdirs(int argc, char **argv)
{
	int             i;
	char            tmppath[MAXPATHLEN];
	int             overflow;

	for (i = 1; i < argc; i++) {
		overflow = 0;
		if (argv[i][0] == '/' || topdir[0] == '\0') {
			if (strlcpy(tmppath, argv[i], sizeof(tmppath)) >=
			    sizeof(tmppath))
				overflow = 1;
		} else {
			if (strlcpy(tmppath, topdir, sizeof(tmppath)) >=
			    sizeof(tmppath) ||
			    strlcat(tmppath, "/", sizeof(tmppath)) >=
			    sizeof(tmppath) ||
			    strlcat(tmppath, argv[i], sizeof(tmppath)) >=
			    sizeof(tmppath))
				overflow = 1;
		}
		if (overflow) {
			goterror = 1;
			fprintf(stderr, "%s:%d: `%.40s...' is too long, skipping it.\n",
			    curfilename, linenum, argv[i]);
			continue;
		}
		if (is_dir(tmppath))
			add_string(&srcdirs, tmppath);
		else {
			fprintf(stderr, "%s:%d: `%s' is not a directory, skipping it.\n",
			    curfilename, linenum, tmppath);
			goterror = 1;
		}
	}
}
Exemple #2
0
static void build_bufed_list(EditState *s)
{
    QEmacsState *qs = s->qe_state;
    EditBuffer *b;
    BufedState *hs;
    int i;

    hs = s->mode_data;

    free_strings(&hs->items);
    for(b = qs->first_buffer; b != NULL; b = b->next) {
        if (!(b->flags & BF_SYSTEM))
            add_string(&hs->items, b->name);
    }
    
    /* build buffer */
    b = s->b;
    eb_delete(b, 0, b->total_size);
    for(i=0;i<hs->items.nb_items;i++) {
        eb_printf(b, " %s", hs->items.items[i]->str);
        if (i != hs->items.nb_items - 1)
            eb_printf(b, "\n");
    }
}
Exemple #3
0
/*
 * Put a simple element (basic class) onto a dialog template in memory.
 * return a pointer to where the next item should be added.
 *
 * parameters:
 *  lStyle = additional style flags
 *  x,y = x & y positions IN DIALOG UNITS
 *  w,h = width and height IN DIALOG UNITS
 *  Id	= ID used in messages
 *  clss  = class ID, e.g 0x80 for a button, 0x82 for a static
 *  caption = usually text or resource name
 *
 *  TODO: use the length information noted here to enable the dialog creation
 *  routines to work out more exactly how much memory they need to alloc.
 */
    static LPWORD
add_dialog_element(
    LPWORD p,
    DWORD lStyle,
    WORD x,
    WORD y,
    WORD w,
    WORD h,
    WORD Id,
    BYTE clss,
    const char *caption)
{

    lStyle = lStyle | WS_VISIBLE | WS_CHILD;

    add_word(x);
    add_word(y);
    add_word(w);
    add_word(h);
    add_word(Id);
    add_long(lStyle);
    add_byte(clss);
    if (((lStyle & SS_ICON) != 0) && (clss == 0x82))
    {
	/* Use resource ID */
	add_byte(0xff);
	add_byte(*caption);
    }
    else
	add_string(caption);

    add_byte(0);    //# of extra bytes following


    return p;
}
Exemple #4
0
/*************************************************************************
 * Entry point for pmp_bf
 *************************************************************************/
int main(int argc, char *argv[]) {

  char* bg_filename = NULL;
  char* motif_name = "motif"; // Use this motif name in the output.
  STRING_LIST_T* selected_motifs = NULL;
  double fg_rate = 1.0;
  double bg_rate = 1.0;
  double purine_pyrimidine = 1.0; // r
  double transition_transversion = 0.5; // R
  double pseudocount = 0.1;
  GAP_SUPPORT_T gap_support = SKIP_GAPS;
  MODEL_TYPE_T model_type = F81_MODEL;
  BOOLEAN_T use_halpern_bruno = FALSE;
  char* ustar_label = NULL;	// TLB; create uniform star tree
  int i;

  program_name = "pmp_bf";

  /**********************************************
   * COMMAND LINE PROCESSING
   **********************************************/

  // Define command line options. (FIXME: Repeated code)
  // FIXME: Note that if you add or remove options you
  // must change n_options.
  int n_options = 12;
  cmdoption const pmp_options[] = {
    {"hb", NO_VALUE},
    {"ustar", REQUIRED_VALUE},
    {"model", REQUIRED_VALUE},
    {"pur-pyr", REQUIRED_VALUE},
    {"transition-transversion", REQUIRED_VALUE},
    {"bg", REQUIRED_VALUE},
    {"fg", REQUIRED_VALUE},
    {"motif", REQUIRED_VALUE},
    {"motif-name", REQUIRED_VALUE},
    {"bgfile", REQUIRED_VALUE},
    {"pseudocount", REQUIRED_VALUE},
    {"verbosity", REQUIRED_VALUE}
  };

  int option_index = 0;

  // Define the usage message.
  char      usage[1000] = "";
  strcat(usage, "USAGE: pmp [options] <tree file> <MEME file>\n");
  strcat(usage, "\n");
  strcat(usage, "   Options:\n");

  // Evolutionary model parameters.
  strcat(usage, "     --hb\n");
  strcat(usage, "     --model single|average|jc|k2|f81|f84|hky|tn");
  strcat(usage, " (default=f81)\n");
  strcat(usage, "     --pur-pyr <float> (default=1.0)\n");
  strcat(usage, "     --transition-transversion <float> (default=0.5)\n");
  strcat(usage, "     --bg <float> (default=1.0)\n");
  strcat(usage, "     --fg <float> (default=1.0)\n");

  // Motif parameters.
  strcat(usage, "     --motif <id> (default=all)\n");
  strcat(usage, "     --motif-name <string> (default from motif file)\n");

  // Miscellaneous parameters
  strcat(usage, "     --bgfile <background> (default from motif file)\n");
  strcat(usage, "     --pseudocount <float> (default=0.1)\n");
  strcat(usage, "     --ustar <label>\n");	// TLB; create uniform star tree
  strcat(usage, "     --verbosity [1|2|3|4] (default 2)\n");
  strcat(usage, "\n    Prints the FP and FN rate at each of 10000 score values.\n");
  strcat(usage, "\n    Output format: [<motif_id> score <score> FPR <fpr> TPR <tpr>]+\n");

  // Parse the command line.
  if (simple_setopt(argc, argv, n_options, pmp_options) != NO_ERROR) {
    die("Error processing command line options: option name too long.\n");
  }

  while (TRUE) { 
    int c = 0;
    char* option_name = NULL;
    char* option_value = NULL;
    const char * message = NULL;

    // Read the next option, and break if we're done.
    c = simple_getopt(&option_name, &option_value, &option_index);
    if (c == 0) {
      break;
    } else if (c < 0) {
      (void) simple_getopterror(&message);
      die("Error processing command line options (%s)\n", message);
    }
    
    if (strcmp(option_name, "model") == 0) {
      if (strcmp(option_value, "jc") == 0) {
        model_type = JC_MODEL;
      } else if (strcmp(option_value, "k2") == 0) {
        model_type = K2_MODEL;
      } else if (strcmp(option_value, "f81") == 0) {
        model_type = F81_MODEL;
      } else if (strcmp(option_value, "f84") == 0) {
        model_type = F84_MODEL;
      } else if (strcmp(option_value, "hky") == 0) {
        model_type = HKY_MODEL;
      } else if (strcmp(option_value, "tn") == 0) {
        model_type = TAMURA_NEI_MODEL;
      } else if (strcmp(option_value, "single") == 0) {
        model_type = SINGLE_MODEL;
      } else if (strcmp(option_value, "average") == 0) {
        model_type = AVERAGE_MODEL;
      } else {
        die("Unknown model: %s\n", option_value);
      }
    } else if (strcmp(option_name, "hb") == 0){
        use_halpern_bruno = TRUE;
    } else if (strcmp(option_name, "ustar") == 0){	// TLB; create uniform star tree
        ustar_label = option_value;
    } else if (strcmp(option_name, "pur-pyr") == 0){
        purine_pyrimidine = atof(option_value);
    } else if (strcmp(option_name, "transition-transversion") == 0){
        transition_transversion = atof(option_value);
    } else if (strcmp(option_name, "bg") == 0){
      bg_rate = atof(option_value);
    } else if (strcmp(option_name, "fg") == 0){
      fg_rate = atof(option_value);
    } else if (strcmp(option_name, "motif") == 0){
        if (selected_motifs == NULL) {
          selected_motifs = new_string_list();
        }
       add_string(option_value, selected_motifs);
    } else if (strcmp(option_name, "motif-name") == 0){
        motif_name = option_value;
    } else if (strcmp(option_name, "bgfile") == 0){
      bg_filename = option_value;
    } else if (strcmp(option_name, "pseudocount") == 0){
        pseudocount = atof(option_value);
    } else if (strcmp(option_name, "verbosity") == 0){
        verbosity = atoi(option_value);
    }
  }

  // Must have tree and motif file names
  if (argc != option_index + 2) {
    fprintf(stderr, "%s", usage);
    exit(EXIT_FAILURE);
  } 

  /**********************************************
   * Read the phylogenetic tree.
   **********************************************/
  char* tree_filename = NULL;
  TREE_T* tree = NULL;
  tree_filename = argv[option_index];
  option_index++;
  tree = read_tree_from_file(tree_filename);

  // get the species names
  STRING_LIST_T* alignment_species = make_leaf_list(tree);
  char *root_label = get_label(tree);	// in case target in center
  if (strlen(root_label)>0) add_string(root_label, alignment_species);
  //write_string_list(" ", alignment_species, stderr);

  // TLB; Convert the tree to a uniform star tree with
  // the target sequence at its center.
  if (ustar_label != NULL) {
    tree = convert_to_uniform_star_tree(tree, ustar_label);
    if (tree == NULL) 
      die("Tree or alignment missing target %s\n", ustar_label);
    if (verbosity >= NORMAL_VERBOSE) {
      fprintf(stderr, 
	"Target %s placed at center of uniform (d=%.3f) star tree:\n", 
          ustar_label, get_total_length(tree) / get_num_children(tree) 
      );
      write_tree(tree, stderr);
    }
  }

  /**********************************************
   * Read the motifs.
   **********************************************/
  char* meme_filename = argv[option_index];
  option_index++;
  int num_motifs = 0; 

  MREAD_T *mread;
  ALPH_T alph;
  ARRAYLST_T *motifs;
  ARRAY_T *bg_freqs;

  mread = mread_create(meme_filename, OPEN_MFILE);
  mread_set_bg_source(mread, bg_filename);
  mread_set_pseudocount(mread, pseudocount);
  // read motifs
  motifs = mread_load(mread, NULL);
  alph = mread_get_alphabet(mread);
  bg_freqs = mread_get_background(mread);
  // check
  if (arraylst_size(motifs) == 0) die("No motifs in %s.", meme_filename);

  

  // TLB; need to resize bg_freqs array to ALPH_SIZE items
  // or copy array breaks in HB mode.  This throws away
  // the freqs for the ambiguous characters;
  int asize = alph_size(alph, ALPH_SIZE);
  resize_array(bg_freqs, asize);

  /**************************************************************
  * Compute probability distributions for each of the selected motifs.
  **************************************************************/
  int motif_index;
  for (motif_index = 0; motif_index < arraylst_size(motifs); motif_index++) {

    MOTIF_T* motif = (MOTIF_T*)arraylst_get(motif_index, motifs);
    char* motif_id = get_motif_id(motif);
    char* bare_motif_id = motif_id;

    // We may have specified on the command line that
    // only certain motifs were to be used.
    if (selected_motifs != NULL) {
      if (*bare_motif_id == '+' || *bare_motif_id == '-') {
        // The selected  motif id won't included a strand indicator.
        bare_motif_id++;
      }
      if (have_string(bare_motif_id, selected_motifs) == FALSE) {
        continue;
      }
    }

    if (verbosity >= NORMAL_VERBOSE) {
      fprintf(
        stderr, 
        "Using motif %s of width %d.\n",
        motif_id, get_motif_length(motif)
      );
    }

    // Build an array of evolutionary models for each position in the motif.
    EVOMODEL_T** models = make_motif_models(
      motif, 
      bg_freqs,
      model_type,
      fg_rate, 
      bg_rate, 
      purine_pyrimidine, 
      transition_transversion, 
      use_halpern_bruno
    );

    // Get the frequencies under the background model (row 0) 
    // and position-dependent scores (rows 1..w)
    // for each possible alignment column.
    MATRIX_T* pssm_matrix = build_alignment_pssm_matrix(
      alph,
      alignment_species,
      get_motif_length(motif) + 1, 
      models, 
      tree, 
      gap_support
    );
    ARRAY_T* alignment_col_freqs = allocate_array(get_num_cols(pssm_matrix)); 
    copy_array(get_matrix_row(0, pssm_matrix), alignment_col_freqs);
    remove_matrix_row(0, pssm_matrix);		// throw away first row
    //print_col_frequencies(alph, alignment_col_freqs);

    //
    // Get the position-dependent null model alignment column frequencies
    //
    int w = get_motif_length(motif);
    int ncols = get_num_cols(pssm_matrix); 
    MATRIX_T* pos_dep_bkg = allocate_matrix(w, ncols);
    for (i=0; i<w; i++) {
      // get the evo model corresponding to this column of the motif
      // and store it as the first evolutionary model.
      myfree(models[0]);
      // Use motif PSFM for equilibrium freqs. for model.
      ARRAY_T* site_specific_freqs = allocate_array(asize);
      int j = 0;
      for(j = 0; j < asize; j++) {
	double value = get_matrix_cell(i, j, get_motif_freqs(motif));
	set_array_item(j, value, site_specific_freqs);
      }
      if (use_halpern_bruno == FALSE) {
	models[0] = make_model(
	  model_type,
	  fg_rate,
	  transition_transversion,
	  purine_pyrimidine,
	  site_specific_freqs,
          NULL
	);
      } else {
        models[0] = make_model(
	  model_type,
	  fg_rate,
	  transition_transversion,
	  purine_pyrimidine,
	  bg_freqs,
	  site_specific_freqs
	);
      }
      // get the alignment column frequencies using this model
      MATRIX_T* tmp_pssm_matrix = build_alignment_pssm_matrix(
        alph,
	alignment_species,
	2,				// only interested in freqs under bkg
	models, 
	tree, 
	gap_support
      );
      // assemble the position-dependent background alignment column freqs.
      set_matrix_row(i, get_matrix_row(0, tmp_pssm_matrix), pos_dep_bkg);
      // chuck the pssm (not his real name)
      free_matrix(tmp_pssm_matrix);
    }

    //
    // Compute and print the score distribution under the background model
    // and under the (position-dependent) motif model.
    //
    int range = 10000;	// 10^4 gives same result as 10^5, but 10^3 differs

    // under background model
    PSSM_T* pssm = build_matrix_pssm(alph, pssm_matrix, alignment_col_freqs, range);

    // under position-dependent background (motif) model
    PSSM_T* pssm_pos_dep = build_matrix_pssm(alph, pssm_matrix, alignment_col_freqs, range);
    get_pv_lookup_pos_dep(
      pssm_pos_dep, 
      pos_dep_bkg, 
      NULL // no priors used
    );

    // print FP and FN distributions
    int num_items = get_pssm_pv_length(pssm_pos_dep);
    for (i=0; i<num_items; i++) {
      double pvf = get_pssm_pv(i, pssm);
      double pvt = get_pssm_pv(i, pssm_pos_dep);
      double fpr = pvf;
      double fnr = 1 - pvt;
      if (fpr >= 0.99999 || fnr == 0) continue;
      printf("%s score %d FPR %.3g FNR %.3g\n", motif_id, i, fpr, fnr);
    }

    // free stuff
    free_pssm(pssm);
    free_pssm(pssm_pos_dep);
    if (models != NULL) {
      int model_index;
      int num_models = get_motif_length(motif) + 1;
      for (model_index = 0; model_index < num_models; model_index++) {
        free_model(models[model_index]);
      }
      myfree(models);
    }

  } // motif

  arraylst_destroy(destroy_motif, motifs);

  /**********************************************
   * Clean up.
   **********************************************/
  // TLB may have encountered a memory corruption bug here
  // CEG has not been able to reproduce it. valgrind says all is well.
  free_array(bg_freqs);
  free_tree(TRUE, tree);
  free_string_list(selected_motifs);

  return(0);
} // main
Exemple #5
0
void
fillin_program_objs(prog_t *p, char *path)
{
	char *obj, *cp;
	int fd, rc;
	FILE *f;
	char *objvar="OBJS";
	strlst_t *s;
	char line[MAXLINELEN];

	/* discover the objs from the srcdir Makefile */

	if ((fd = mkstemp(tempfname)) == -1) {
		perror(tempfname);
		exit(1);
	}
	if ((f = fdopen(fd, "w")) == NULL) {
		warn("%s", tempfname);
		goterror = 1;
		return;
	}
	if (p->objvar)
		objvar = p->objvar;

	/*
	* XXX include outhdrname (e.g. to contain Make variables)
	*/
	if (outhdrname[0] != '\0')
		fprintf(f, ".include \"%s\"\n", outhdrname);
	fprintf(f, ".include \"%s\"\n", path);
	fprintf(f, ".POSIX:\n");
	if (buildopts) {
		fprintf(f, "BUILDOPTS+=");
		output_strlst(f, buildopts);
	}
	fprintf(f, ".if defined(PROG)\n");
	fprintf(f, "%s?=${PROG}.o\n", objvar);
	fprintf(f, ".endif\n");
	fprintf(f, "loop:\n\t@echo 'OBJS= '${%s}\n", objvar);

	fprintf(f, "crunchgen_objs:\n"
	    "\t@cd %s && %s -f %s $(BUILDOPTS) $(%s_OPTS)",
	    p->srcdir, path_make, tempfname, p->ident);
	for (s = p->buildopts; s != NULL; s = s->next)
		fprintf(f, " %s", s->str);
	fprintf(f, " loop\n");

	fclose(f);

	snprintf(line, MAXLINELEN, "cd %s && %s -f %s -B crunchgen_objs",
	     p->srcdir, path_make, tempfname);
	if ((f = popen(line, "r")) == NULL) {
		warn("submake pipe");
		goterror = 1;
		return;
	}

	while(fgets(line, MAXLINELEN, f)) {
		if (strncmp(line, "OBJS= ", 6)) {
			warnx("make error: %s", line);
			goterror = 1;
			continue;
		}

		cp = line + 6;
		while (isspace((unsigned char)*cp))
			cp++;

		while(*cp) {
			obj = cp;
			while (*cp && !isspace((unsigned char)*cp))
				cp++;
			if (*cp)
				*cp++ = '\0';
			add_string(&p->objs, obj);
			while (isspace((unsigned char)*cp))
				cp++;
		}
	}

	if ((rc=pclose(f)) != 0) {
		warnx("make error: make returned %d", rc);
		goterror = 1;
	}

	unlink(tempfname);
}
void VG_(split_up_argv)( Int argc, HChar** argv )
{
          Int  i;
          Bool augment = True;
   static Bool already_called = False;

   XArrayStrings tmp_xarray = {0,0,NULL};

   /* This function should be called once, at startup, and then never
      again. */
   vg_assert(!already_called);
   already_called = True;

   /* Collect up the args-for-V. */
   i = 1; /* skip the exe (stage2) name. */
   for (; i < argc; i++) {
      vg_assert(argv[i]);
      if (0 == VG_(strcmp)(argv[i], "--")) {
         i++;
         break;
      }
      if (0 == VG_(strcmp)(argv[i], "--command-line-only=yes"))
         augment = False;
      if (argv[i][0] != '-')
	break;
      add_string( &tmp_xarray, argv[i] );
   }

   /* Should now be looking at the exe name. */
   if (i < argc) {
      vg_assert(argv[i]);
      VG_(args_the_exename) = argv[i];
      i++;
   }

   /* The rest are args for the client. */
   for (; i < argc; i++) {
      vg_assert(argv[i]);
      add_string( &VG_(args_for_client), argv[i] );
   }

   VG_(args_for_valgrind).size = 0;
   VG_(args_for_valgrind).used = 0;
   VG_(args_for_valgrind).strs = NULL;

   /* Get extra args from ~/.valgrindrc, $VALGRIND_OPTS and
      ./.valgrindrc into VG_(args_for_valgrind). */
   if (augment) {
      // read_dot_valgrindrc() allocates the return value with
      // VG_(malloc)().  We do not free f1_clo and f2_clo as they get
      // put into VG_(args_for_valgrind) and so must persist.
      HChar* home    = VG_(getenv)("HOME");
      HChar* f1_clo  = home ? read_dot_valgrindrc( home ) : NULL;
      HChar* env_clo = VG_(strdup)( VG_(getenv)(VALGRIND_OPTS) );
      HChar* f2_clo  = NULL;

      // Don't read ./.valgrindrc if "." is the same as "$HOME", else its
      // contents will be applied twice. (bug #142488)
      if (home) {
         HChar cwd[VKI_PATH_MAX+1];
         Bool  cwd_ok = VG_(getcwd)(cwd, VKI_PATH_MAX);
         f2_clo = ( (cwd_ok && VG_STREQ(home, cwd))
                       ? NULL : read_dot_valgrindrc(".") );
      }

      if (f1_clo)  add_args_from_string( f1_clo );
      if (env_clo) add_args_from_string( env_clo );
      if (f2_clo)  add_args_from_string( f2_clo );
   }

   /* .. and record how many extras we got. */
   VG_(args_for_valgrind_noexecpass) = VG_(args_for_valgrind).used;

   /* Finally, copy tmp_xarray onto the end. */
   for (i = 0; i < tmp_xarray.used; i++)
      add_string( &VG_(args_for_valgrind), tmp_xarray.strs[i] );

   if (tmp_xarray.strs)
      VG_(free)(tmp_xarray.strs);
}
Exemple #7
0
/* library list options get put in object list,
 * so order w.r.t. libraries is preserved. */
extern void
add_object (int flag, string arg)
{
    /* cxx_prelinker_object_list contains real objects, -objectlist flags. */
	switch (flag) {
	case O_l:
		/* xpg fort77 has weird rule about putting all libs after objects */
		if (xpg_flag && invoked_lang == L_f77) {
			add_string(lib_objects, concat_strings("-l",arg));
		} else {
			add_string(objects, concat_strings("-l",arg));
			add_string(ld_args_objs, concat_strings("-l",arg));
		}
		if (invoked_lang == L_CC) {
		    add_string(cxx_prelinker_objects,concat_strings("-l",arg));
		}
		break;
 	case O_none: add_string(objects, get_option_name(flag));
 	             add_string(ld_args_objs, get_option_name(flag));
                                                break;
        case O_objectlist:
                add_multi_strings(objects, concat_strings("-objectlist ",arg));
                add_multi_strings(ld_args_objs, concat_strings("-objectlist ",arg));
                if (invoked_lang == L_CC) {
                    add_string(cxx_prelinker_objects,
                                concat_strings("-YO=",arg));
                }
                break;
        case O_object:
                if (dashdash_flag && arg[0] == '-') {
                  add_string(objects,"--");
                  add_string(ld_args_objs,"--");
                  dashdash_flag = 1;
                }
                add_string(objects, arg);
                add_string(ld_args_objs, arg);
                if (invoked_lang == L_CC) {
                    add_string(cxx_prelinker_objects, arg);
                }

                break;

	default:
		internal_error("add_object called with not-an-object");
	}
}
Exemple #8
0
/* append object files to the ar_objects list. */
extern void
add_ar_objects (string arg)
{
    add_string(ar_objects, arg);
}
void update_game(Game* G)
{
    float delta_time = (float)get_delta_time(G->timer);
    int ii;

    _control_camera(G, delta_time);
    set_view_matrix(G->graphics, mat4_inverse(transform_get_matrix(G->camera)));

    /* Dynamic Lights */
    if(G->dynamic_lights) {
        G->sun_light.position = mat3_mul_vector(vec3_create(5,5,0), mat3_rotation_y((float)get_running_time(G->timer)*0.5f));
        G->light_transform += delta_time;
        for(ii=0;ii<NUM_LIGHTS;++ii) {
            if(ii % 2)
                G->lights[ii].position.z = sinf((G->light_transform + ii * 1.0f)/2.0f) * 10.0f;
            else
                G->lights[ii].position.x = sinf((G->light_transform + ii * 1.0f)/2.0f) * 10.0f;
        }
    }

    add_light(G->graphics, G->sun_light);
    for(ii=0;ii<NUM_LIGHTS;++ii) {
        add_light(G->graphics, G->lights[ii]);
    }
    render_scene(G->scene, G->graphics);

    G->tap_timer += delta_time;

    /* Calculate FPS */
    G->fps_time += delta_time;
    G->fps_count++;

    if(G->fps_time >= 1.0f) {
        G->fps = G->fps_count/G->fps_time;
        system_log("FPS: %f\n", G->fps);
        G->fps_time -= 1.0f;
        G->fps_count = 0;
    }
    {
        int width, height;
        float scale = 50.0f;
        float x = -G->width/2.0f;
        float y = G->height/2.0f-scale;
        char buffer[256] = {0};
        // FPS
        sprintf(buffer, "FPS: %.2f", G->fps);
        add_string(G->ui, x, y, scale, buffer);
        y -= scale;
        // Renderer
        switch(renderer_type(G->graphics)) {
        case kForward: add_string(G->ui, x, y, scale, "Forward renderer"); break;
        case kLightPrePass: add_string(G->ui, x, y, scale, "Deferred Lighting"); break;
        case kDeferred: add_string(G->ui, x, y, scale, "Deferred Shading"); break;
        default: assert(!"Invalid renderer"); break;
        }
        y -= scale;
        // Resolution
        graphics_size(G->graphics, &width, &height);
        sprintf(buffer, "%dx%d", width, height);
        add_string(G->ui, x, y, scale, buffer);
    }
}
Exemple #10
0
static int
arg_match_short (struct getargs *args, size_t num_args,
		 char *argv, int argc, const char **rargv, int *optind)
{
    int j, k;

    for(j = 1; j > 0 && j < (int)strlen(rargv[*optind]); j++) {
	for(k = 0; k < (int)num_args; k++) {
	    char *optarg;

	    if(args[k].short_name == 0)
		continue;
	    if(argv[j] == args[k].short_name) {
		if(args[k].type == arg_flag) {
		    *(int*)args[k].value = 1;
		    break;
		}
		if(args[k].type == arg_negative_flag) {
		    *(int*)args[k].value = 0;
		    break;
		} 
		if(args[k].type == arg_counter) {
		    ++*(int *)args[k].value;
		    break;
		}
		if(args[k].type == arg_collect) {
		    struct getarg_collect_info *c = args[k].value;

		    if((*c->func)(TRUE, argc, rargv, optind, &j, c->data))
			return ARG_ERR_BAD_ARG;
		    break;
		}

		if(argv[j + 1])
		    optarg = &argv[j + 1];
		else {
		    ++*optind;
		    optarg = (char *) rargv[*optind];
		}
		if(optarg == NULL) {
		    --*optind;
		    return ARG_ERR_NO_ARG;
		}
		if(args[k].type == arg_integer) {
		    int tmp;
		    if(sscanf(optarg, "%d", &tmp) != 1)
			return ARG_ERR_BAD_ARG;
		    *(int*)args[k].value = tmp;
		    return 0;
		} else if(args[k].type == arg_string) {
		    *(char**)args[k].value = optarg;
		    return 0;
		} else if(args[k].type == arg_strings) {
		    add_string((getarg_strings*)args[k].value, optarg);
		    return 0;
		} else if(args[k].type == arg_double) {
		    double tmp;
		    if(sscanf(optarg, "%lf", &tmp) != 1)
			return ARG_ERR_BAD_ARG;
		    *(double*)args[k].value = tmp;
		    return 0;
		}
		return ARG_ERR_BAD_ARG;
	    }
	}
	if (k == (int)num_args)
	    return ARG_ERR_NO_MATCH;
    }
    return 0;
}
Exemple #11
0
static int
arg_match_long(struct getargs *args, size_t num_args,
	       char *argv, int argc, const char **rargv, int *optind)
{
    unsigned int i;
    const char *optarg = NULL;
    int negate = 0;
    int partial_match = 0;
    struct getargs *partial = NULL;
    struct getargs *current = NULL;
    int argv_len;
    char *p;

    argv_len = (int)strlen(argv);
    p = strchr (argv, '=');
    if (p != NULL)
	argv_len = (int)(p - argv);

    for (i = 0; i < num_args; ++i) {
	if(args[i].long_name) {
	    int len = (int)strlen(args[i].long_name);
	    char *p = argv;
	    int p_len = argv_len;
	    negate = 0;

	    for (;;) {
		if (strncmp (args[i].long_name, p, p_len) == 0) {
		    if(p_len == len)
			current = &args[i];
		    else {
			++partial_match;
			partial = &args[i];
		    }
		    optarg  = p + p_len;
		} else if (ISFLAG(args[i]) && strncmp (p, "no-", 3) == 0) {
		    negate = !negate;
		    p += 3;
		    p_len -= 3;
		    continue;
		}
		break;
	    }
	    if (current)
		break;
	}
    }
    if (current == NULL) {
	if (partial_match == 1)
	    current = partial;
	else
	    return ARG_ERR_NO_MATCH;
    }
    
    if(*optarg == '\0'
       && !ISFLAG(*current)
       && current->type != arg_collect
       && current->type != arg_counter)
	return ARG_ERR_NO_MATCH;
    switch(current->type){
    case arg_integer:
    {
	int tmp;
	if(sscanf(optarg + 1, "%d", &tmp) != 1)
	    return ARG_ERR_BAD_ARG;
	*(int*)current->value = tmp;
	return 0;
    }
    case arg_string:
    {
	*(char**)current->value = (char*)optarg + 1;
	return 0;
    }
    case arg_strings:
    {
	add_string((getarg_strings*)current->value, (char*)optarg + 1);
	return 0;
    }
    case arg_flag:
    case arg_negative_flag:
    {
	int *flag = current->value;
	if(*optarg == '\0' ||
	   strcmp(optarg + 1, "yes") == 0 || 
	   strcmp(optarg + 1, "true") == 0){
	    *flag = !negate;
	    return 0;
	} else if (*optarg && strcmp(optarg + 1, "maybe") == 0) {
	    *flag = rand() & 1;
	} else {
	    *flag = negate;
	    return 0;
	}
	return ARG_ERR_BAD_ARG;
    }
    case arg_counter :
    {
	int val;

	if (*optarg == '\0')
	    val = 1;
	else {
	    char *endstr;

	    val = strtol (optarg, &endstr, 0);
	    if (endstr == optarg)
		return ARG_ERR_BAD_ARG;
	}
	*(int *)current->value += val;
	return 0;
    }
    case arg_double:
    {
	double tmp;
	if(sscanf(optarg + 1, "%lf", &tmp) != 1)
	    return ARG_ERR_BAD_ARG;
	*(double*)current->value = tmp;
	return 0;
    }
    case arg_collect:{
	struct getarg_collect_info *c = current->value;
	int o = (int)(argv - rargv[*optind]);
	return (*c->func)(FALSE, argc, rargv, optind, &o, c->data);
    }

    default:
	abort ();
	return ARG_ERR_BAD_ARG;
    }
}
Exemple #12
0
int
agetarg(struct agetargs *args,
	int argc, char **argv, int *optind, int style)
{
    int i, j;
    struct agetargs *arg;
    int ret = 0;
    int swcount = *optind;
    int num_args = 0;
    char *usedargs;

    for(i = 0 ; args[i].type != aarg_end; i++)
	num_args++;
    
    usedargs = calloc (num_args, sizeof(char));
    if (usedargs == NULL)
	return ENOMEM;

    srand (time(NULL));
    (*optind)++;
    for(i = *optind; i < argc; i++) {
	if(argv[i][0] != '-'
	   && swcount != -1
	   && (args[swcount].mandatoryp == aarg_mandatory
	       || args[swcount].mandatoryp == aarg_optional_swless)) {
	    /* the mandatory junk up there is to prevent agetarg() from
	       automatically matching options even when not specified with
	       their flagged name
	    */
	    if (!(style & AARG_SWITCHLESS))
		break;
	    j = 0;
	    ret = parse_option(&args[swcount], style, argv[i],
			       argc - i, &argv[i], &j, 0);
	    if (ret) {
		*optind = i;
		free (usedargs);
		return ret;
	    }
	    usedargs[swcount] = 1;
	    i += j;
	    swcount++;
	} else if(argv[i][1] == '-' || 
		  ((style & AARG_TRANSLONG) && argv[i][1] != 0)) {
	    int k;

	    if(argv[i][2] == 0 && !(style & AARG_TRANSLONG)){
		i++;
		break;
	    }
	    swcount = -1;
	    ret = arg_match_long (args, argc - i, &argv[i], style, &j, &k);
	    if(ret) {
		*optind = i;
		free (usedargs);
		return ret;
	    }
	    usedargs[k] = 1;
	    i += j;
	}else if (style & AARG_SHORTARG && argv[i][0] == '-') {
	    for(j = 1; argv[i][j]; j++) {
		int arg_num = -1;
		for(arg = args; arg->type; arg++) {
		    char *optarg;
		    arg_num++;
		    if(arg->short_name == 0)
			continue;
		    if(argv[i][j] == arg->short_name){
			if(arg->type == aarg_flag){
			    *(int*)arg->value = 1;
			    usedargs[arg_num] = 1;
			    break;
			}
			if(arg->type == aarg_negative_flag){
			    *(int*)arg->value = 0;
			    usedargs[arg_num] = 1;
			    break;
			}
			if(argv[i][j + 1])
			    optarg = &argv[i][j + 1];
			else{
			    i++;
			    optarg = argv[i];
			}
			if(optarg == NULL) {
			    *optind = i - 1;
			    free (usedargs);
			    return AARG_ERR_NO_ARG;
			}
			if(arg->type == aarg_integer){
			    int tmp;
			    if(sscanf(optarg, "%d", &tmp) != 1) {
				*optind = i;
				free (usedargs);
				return AARG_ERR_BAD_ARG;
			    }
			    *(int*)arg->value = tmp;
			    usedargs[arg_num] = 1;
			    goto out;
			}else if(arg->type == aarg_string){
			    *(char**)arg->value = optarg;
			    usedargs[arg_num] = 1;
			    goto out;
			}else if(arg->type == aarg_strings){
			    add_string((agetarg_strings*)arg->value, optarg);
			    usedargs[arg_num] = 1;
			    goto out;
			}
			*optind = i;
			free (usedargs);
			return AARG_ERR_BAD_ARG;
		    }
			
		}
		if (!arg->type) {
		    *optind = i;
		    free (usedargs);
		    return AARG_ERR_NO_MATCH;
		}
	    }
	out:;
	}
    }
    *optind = i;

    for(i = 0 ; args[i].type != aarg_end; i++) {
	if (args[i].mandatoryp == aarg_mandatory && usedargs[i] == 0) {
	    *optind = i;
	    free (usedargs);
	    return AARG_ERR_NO_ARG;
	}
    }

    free (usedargs);
    return 0;
}
Exemple #13
0
/**
 *  We've found a '<' character.  We ignore this if it is a comment or a
 *  directive.  If it is something else, then whatever it is we are looking
 *  at is bogus.  Returning NULL stops processing.
 *
 * @param[in]     xml_name  the name of an xml bracket (usually)
 * @param[in,out] res_val   the option data derived from the XML element
 *
 * @returns the place to resume scanning input
 */
static char const *
scan_xml(char const * xml_name, tOptionValue * res_val)
{
    size_t          nm_len, v_len;
    char const *    scan;
    char const *    val_str;
    tOptionValue    valu;
    tOptionLoadMode save_mode = option_load_mode;

    if (! IS_VAR_FIRST_CHAR(*++xml_name))
        return unnamed_xml(xml_name);

    /*
     * "scan_xml_name()" may change "option_load_mode".
     */
    val_str = scan_xml_name(xml_name, &nm_len, &valu);
    if (val_str == NULL)
        goto bail_scan_xml;

    if (valu.valType == OPARG_TYPE_NONE)
        scan = val_str;
    else {
        if (option_load_mode != OPTION_LOAD_KEEP)
            val_str = SPN_WHITESPACE_CHARS(val_str);
        scan = find_end_xml(xml_name, nm_len, val_str, &v_len);
        if (scan == NULL)
            goto bail_scan_xml;
    }

    /*
     * "scan" now points to where the scan is to resume after returning.
     * It either points after "/>" at the end of the XML element header,
     * or it points after the "</name>" tail based on the name in the header.
     */

    switch (valu.valType) {
    case OPARG_TYPE_NONE:
        add_string(&(res_val->v.nestVal), xml_name, nm_len, NULL, 0);
        break;

    case OPARG_TYPE_STRING:
    {
        tOptionValue * new_val = add_string(
            &(res_val->v.nestVal), xml_name, nm_len, val_str, v_len);

        if (option_load_mode != OPTION_LOAD_KEEP)
            munge_str(new_val->v.strVal, option_load_mode);

        break;
    }

    case OPARG_TYPE_BOOLEAN:
        add_bool(&(res_val->v.nestVal), xml_name, nm_len, val_str, v_len);
        break;

    case OPARG_TYPE_NUMERIC:
        add_number(&(res_val->v.nestVal), xml_name, nm_len, val_str, v_len);
        break;

    case OPARG_TYPE_HIERARCHY:
    {
        char * pz = AGALOC(v_len+1, "h scan");
        memcpy(pz, val_str, v_len);
        pz[v_len] = NUL;
        add_nested(&(res_val->v.nestVal), xml_name, nm_len, pz, v_len);
        AGFREE(pz);
        break;
    }

    case OPARG_TYPE_ENUMERATION:
    case OPARG_TYPE_MEMBERSHIP:
    default:
        break;
    }

    option_load_mode = save_mode;
    return scan;

bail_scan_xml:
    option_load_mode = save_mode;
    return NULL;
}
Exemple #14
0
/**
 *  We have an entry that starts with a name.  Find the end of it, cook it
 *  (if called for) and create the name/value association.
 */
static char const *
scan_name(char const * name, tOptionValue * res)
{
    tOptionValue * new_val;
    char const *   pzScan = name+1; /* we know first char is a name char */
    char const *   pzVal;
    size_t         nm_len = 1;
    size_t         d_len = 0;

    /*
     *  Scan over characters that name a value.  These names may not end
     *  with a colon, but they may contain colons.
     */
    pzScan = SPN_VALUE_NAME_CHARS(name + 1);
    if (pzScan[-1] == ':')
        pzScan--;
    nm_len = (size_t)(pzScan - name);

    pzScan = SPN_HORIZ_WHITE_CHARS(pzScan);

 re_switch:

    switch (*pzScan) {
    case '=':
    case ':':
        pzScan = SPN_HORIZ_WHITE_CHARS(pzScan + 1);
        if ((*pzScan == '=') || (*pzScan == ':'))
            goto default_char;
        goto re_switch;

    case NL:
    case ',':
        pzScan++;
        /* FALLTHROUGH */

    case NUL:
        add_string(&(res->v.nestVal), name, nm_len, NULL, (size_t)0);
        break;

    case '"':
    case '\'':
        pzVal = pzScan;
        pzScan = scan_q_str(pzScan);
        d_len = (size_t)(pzScan - pzVal);
        new_val = add_string(&(res->v.nestVal), name, nm_len, pzVal,
                         d_len);
        if ((new_val != NULL) && (option_load_mode == OPTION_LOAD_COOKED))
            ao_string_cook(new_val->v.strVal, NULL);
        break;

    default:
    default_char:
        /*
         *  We have found some strange text value.  It ends with a newline
         *  or a comma.
         */
        pzVal = pzScan;
        for (;;) {
            char ch = *(pzScan++);
            switch (ch) {
            case NUL:
                pzScan--;
                d_len = (size_t)(pzScan - pzVal);
                goto string_done;
                /* FALLTHROUGH */

            case NL:
                if (   (pzScan > pzVal + 2)
                    && (pzScan[-2] == '\\')
                    && (pzScan[ 0] != NUL))
                    continue;
                /* FALLTHROUGH */

            case ',':
                d_len = (size_t)(pzScan - pzVal) - 1;
            string_done:
                new_val = add_string(&(res->v.nestVal), name, nm_len,
                                     pzVal, d_len);
                if (new_val != NULL)
                    remove_continuation(new_val->v.strVal);
                goto leave_scan_name;
            }
        }
        break;
    } leave_scan_name:;

    return pzScan;
}
Exemple #15
0
int serialize_tree(struct kowhai_node_t** desc, void** data, char* target_buffer, size_t target_size, int level, void* get_name_param, kowhai_get_symbol_name_t get_name, int in_union, int* largest_data_field)
{
    int target_offset = 0;
    struct kowhai_node_t* node;
    int i, chars;
    char* node_end_str;

    while (1)
    {
        node = *desc;

        if (node->type == KOW_BRANCH_END)
            return target_offset;

        // indent to current level using tabs
        chars = add_indent(&target_buffer, &target_size, &target_offset, level);
        if (chars < 0)
            return chars;

        //
        // write node
        //

        switch (node->type)
        {
            case KOW_BRANCH_START:
            case KOW_BRANCH_U_START:
            {
                int node_is_union = node->type == KOW_BRANCH_U_START;
                int largest_child_data_field = 0;
                void* initial_data = *data;
                // write header
                chars = add_header(&target_buffer, &target_size, &target_offset, node, get_name_param, get_name);
                if (chars < 0)
                    return chars;
                if (node->count > 1)
                {
                    struct kowhai_node_t* initial_node = *desc;
                    // write array identifier
                    chars = add_string(&target_buffer, &target_size, &target_offset, ", \""ARRAY"\": [\n");
                    if (chars < 0)
                    return chars;
                    for (i = 0; i < node->count; i++)
                    {
                        // set descriptor to initial node at the branch array
                        *desc = initial_node;
                        (*desc) += 1;
                        // indent to current level using tab
                        chars = add_indent(&target_buffer, &target_size, &target_offset, level + 1);
                        if (chars < 0)
                            return chars;
                        // write branch children start
                        chars = add_string(&target_buffer, &target_size, &target_offset, "[\n");
                        if (chars < 0)
                            return chars;
                        // write branch children
                        chars = serialize_tree(desc, data, target_buffer, target_size, level + 1, get_name_param, get_name, node_is_union, &largest_child_data_field);
                        if (chars < 0)
                            return chars;
                        target_offset += chars;
                        target_buffer += chars;
                        target_size -= chars;
                        // increment data pointer if node is a union
                        if (node_is_union)
                        {
                            *data = (char*)initial_data + largest_child_data_field;
                            initial_data = *data;
                        }
                        // indent to current level using tab
                        chars = add_indent(&target_buffer, &target_size, &target_offset, level + 1);
                        if (chars < 0)
                            return chars;
                        // write branch children end
                        chars = add_string(&target_buffer, &target_size, &target_offset, "]");
                        if (chars < 0)
                            return chars;
                        if (i < node->count - 1)
                        {
                            chars = add_string(&target_buffer, &target_size, &target_offset, ",\n");
                            if (chars < 0)
                                return chars;
                        }
                        else
                        {
                            chars = add_string(&target_buffer, &target_size, &target_offset, "\n");
                            if (chars < 0)
                                return chars;
                        }
                    }
                }
                else
                {
                    // write children identifier
                    chars = add_string(&target_buffer, &target_size, &target_offset, ", \""CHILDREN"\": [\n");
                    if (chars < 0)
                        return chars;
                    // write branch children
                    (*desc) += 1;
                    chars = serialize_tree(desc, data, target_buffer, target_size, level + 1, get_name_param, get_name, node_is_union, &largest_child_data_field);
                    if (chars < 0)
                        return chars;
                    target_offset += chars;
                    target_buffer += chars;
                    target_size -= chars;
                    // increment data pointer if node is a union
                    if (node_is_union)
                        *data = (char*)initial_data + largest_child_data_field;
                }
                // indent to current level using tab
                chars = add_indent(&target_buffer, &target_size, &target_offset, level);
                if (chars < 0)
                    return chars;
                // write node end
                if (level == 0 || (*desc)[1].type == KOW_BRANCH_END)
                    node_end_str = "]}\n";
                else
                    node_end_str = "]},\n";
                chars = add_string(&target_buffer, &target_size, &target_offset, node_end_str);
                if (chars < 0)
                    return chars;
                break;
            }
            default:
            {
                int value_size = kowhai_get_node_type_size(node->type);
                // write header
                chars = add_header(&target_buffer, &target_size, &target_offset, node, get_name_param, get_name);
                if (chars < 0)
                    return chars;
                // write value identifier
                chars = add_string(&target_buffer, &target_size, &target_offset, ", \""VALUE"\": ");
                if (chars < 0)
                    return chars;
                // write value/s
                if (node->type == KOW_CHAR && node->count > 1 && str_printable((char *)*data, node->count))
                {
                    // special string case
                    chars = write_string(target_buffer, target_size, "\"%.*s\"", node->count, (char*)*data);
                    if (chars >= 0)
                    {
                        target_buffer += chars;
                        target_size -= chars;
                        target_offset += chars;
                    }
                    else
                        return chars;
                    // increment data pointer
                    if (!in_union)
                        *data = (char*)*data + value_size * node->count;
                    else if (value_size * node->count > *largest_data_field)
                        *largest_data_field = value_size * node->count;
                }
                else if (node->count > 1)
                {
                    // write start bracket
                    chars = add_string(&target_buffer, &target_size, &target_offset, "[");
                    if (chars < 0)
                        return chars;
                    for (i = 0; i < node->count; i++)
                    {
                        // write leaf node array item value
                        chars = add_value(&target_buffer, &target_size, &target_offset, node->type, (char*)*data + i * value_size);
                        if (chars < 0)
                            return chars;
                        // write comma if there is another array item
                        if (i < node->count - 1)
                        {
                            chars = add_string(&target_buffer, &target_size, &target_offset, ", ");
                            if (chars < 0)
                                return chars;
                        }
                    }
                    // increment data pointer
                    if (!in_union)
                        *data = (char*)*data + value_size * node->count;
                    else if (value_size * node->count > *largest_data_field)
                        *largest_data_field = value_size * node->count;
                    // write end bracket
                    chars = add_string(&target_buffer, &target_size, &target_offset, "]");
                    if (chars < 0)
                        return chars;
                }
                else
                {
                    // write leaf node value
                    chars = add_value(&target_buffer, &target_size, &target_offset, node->type, *data);
                    if (chars < 0)
                        return chars;
                    // increment data pointer
                    if (!in_union)
                        *data = (char*)*data + value_size;
                    else if (value_size > *largest_data_field)
                        *largest_data_field = value_size;
                }
                // write node end
                if (level == 0 || node[1].type == KOW_BRANCH_END)
                    node_end_str = " }\n";
                else
                    node_end_str = " },\n";
                chars = add_string(&target_buffer, &target_size, &target_offset, node_end_str);
                if (chars < 0)
                    return chars;
                break;
            }
        }

        if (level == 0)
            return target_offset;

        (*desc) += 1;
    }
}
Exemple #16
0
CAMLexport char * caml_format_exception(value exn)
{
  mlsize_t start, i;
  struct stringbuf buf;
  char intbuf[64];
  char * res;
  CAMLparam1(exn);
  CAMLlocal4(bucket, v, exnclass, field1);

  buf.ptr = buf.data;
  buf.end = buf.data + sizeof(buf.data) - 1;
  /* An exception class is a value with tag Object_tag, whose first
     field is a string naming the exception.
     Exceptions that take parameters (e.g. Invalid_argument) are blocks
     with tag 0, where the first field is the exception class.
     Exceptions without parameters (e.g. Not_found) are just the exception
     class. */
  if (Tag_val(exn) == 0) {
    /* Field 0 of exn is the exception class, which is immutable */
    exnclass = Field_imm(exn, 0);
    add_string(&buf, String_val(Field_imm(exnclass, 0)));
    /* Check for exceptions in the style of Match_failure and Assert_failure */
    if (Wosize_val(exn) == 2) {
      caml_read_field(exn, 1, &field1);
    } else {
      field1 = Val_unit;
    }
    if (Is_block(field1) &&
        Tag_val(field1) == 0 &&
        caml_is_special_exception(exnclass)) {
      bucket = field1;
      start = 0;
    } else {
      bucket = exn;
      start = 1;
    }
    add_char(&buf, '(');
    for (i = start; i < Wosize_val(bucket); i++) {
      if (i > start) add_string(&buf, ", ");
      caml_read_field(bucket, i, &v);
      if (Is_long(v)) {
        snprintf(intbuf, sizeof(intbuf),
                 "%" ARCH_INTNAT_PRINTF_FORMAT "d", Long_val(v));
        add_string(&buf, intbuf);
      } else if (Tag_val(v) == String_tag) {
        add_char(&buf, '"');
        add_string(&buf, String_val(v));
        add_char(&buf, '"');
      } else {
        add_char(&buf, '_');
      }
    }
    add_char(&buf, ')');
  } else {
    /* Exception without parameters */
    exnclass = exn;
    add_string(&buf, String_val(Field_imm(exnclass, 0)));
  }

  *buf.ptr = 0;              /* Terminate string */
  i = buf.ptr - buf.data + 1;
  res = malloc(i);
  if (res == NULL) CAMLreturnT (char*, NULL);
  memmove(res, buf.data, i);
  CAMLreturnT (char*, res);
}
Exemple #17
0
static void
add_cb (GtkButton              *button,
        GtkInspectorStrvEditor *editor)
{
  add_string (editor, "");
}
Exemple #18
0
void
add_c_string(char *s)
{
  add_string(s, strlen(s));
}
Exemple #19
0
int parse_logins(struct login_data* md)
{
	FILE *passwd;
	if((passwd = fopen("user.db", "r")) == NULL)
	{
		log_write("Could not read user database", LOG_ERR);
		return 1;
	}

	// Read password file
	int passwd_fs;
	fseek(passwd, 0, SEEK_END);
	passwd_fs = ftell(passwd);
	fseek(passwd, 0, SEEK_SET);

	if(passwd_fs <= 0)
	{
		log_write("Failed on determining size of passwd", LOG_ERR);
		fclose(passwd);

		return 1;
	}

	// Yep - Coverity is paranoid :)
	if(passwd_fs == INT_MAX)
	{
		log_write("user.db file is too big...", LOG_ERR);
		fclose(passwd);

		return 1;
	}

	char *passwd_content = calloc(1, passwd_fs+1);
	if(passwd_content == NULL)
	{
		log_write("Failed on allocating passwd memory", LOG_ERR);
		fclose(passwd);

		return 1;
	}

	if((fread(passwd_content, passwd_fs, 1, passwd)) != passwd_fs)
	{
		log_write("Failed on reading passwd", LOG_ERR);
		free(passwd_content);
		fclose(passwd);

		return 1;
	}


	pthread_mutex_lock(&md->search_lock);
	int i;
	for(i=0; i<passwd_fs; i+=120)
	{
		// Copy password to set null terminator
		unsigned char pw[21] = {0};
		memcpy(pw, &passwd_content[i+100], 20);

		if(add_string(md->search, (unsigned char *)&passwd_content[i], pw) != 0)
		{

			pthread_mutex_unlock(&md->search_lock);

			log_write("Error on writing passwd data into search tree", LOG_ERR);
			fclose(passwd);
			free(passwd_content);

			return 1;
		}
	}
	pthread_mutex_unlock(&md->search_lock);

	free(passwd_content);
	fclose(passwd);

	return 0;
}
Exemple #20
0
//------------------------------------------------------------------------------
    Elf_Word
    add_string( const std::string& str )
    {
        return add_string( str.c_str() );
    }
Exemple #21
0
extern void
add_library_dir (string path)
{
	add_string(library_dirs, path);
}
Exemple #22
0
void TMClist::AddGroup(RDSgroup& group)
{
  if (group.GetGroupStatus() != GS_COMPLETE) return;

  TMCtype type = (TMCtype)((group.GetByte(1,0) & 0x18) >> 3);
  int duration = group.GetByte(1,0) & 0x07;
  int CI = duration;
  int event = group.GetWord(2) & 0x7FF;
  int location = group.GetWord(3);
  int extent = (group.GetByte(2,1) & 0x38) >> 3;
  int direction = (group.GetByte(2,1) & 0x40) >> 6;
  int SGI = direction;
  int diversion = (group.GetByte(2,1) & 0x80) >> 7;
  int GSI = (group.GetByte(2,1) & 0x30) >> 4;
  int frequency = ((group.GetWord(2) & 0xFFF) << 16)+group.GetWord(3);
  ostringstream oss;
  int i;
  switch (type){
    case TMC_GROUP:  if ((CI >= 1) & (CI <= 6)) {
                       /* CI=0 is for encrypted TMCpro */
                       /* CI=7 is reserved for future use */
                       if (diversion) {
                         /* first group */
                         oss << "GF evt=" << event << " loc=" << location;
                         oss << " ext=" << extent << " CI=" << CI;
                         oss << " dir=" << direction;
                       } else {
                         /* subsequent groups */
                         oss << "GS CI=" << CI << " GSI=" << GSI;
                         oss << " F1=" << event << " F2=" << location; // Free Format
                       }
                     break;
    case TMC_SINGLE: oss << "S evt=" << event << " loc=" << location;
                     oss << " ext=" << extent << " dur=" << duration;
                     oss << " dir=" << direction << " div=" << diversion;
                     break;
    case TMC_SYSTEM: oss << "Y ";
                     switch (CI){
                       case 0:
                       case 1:
                       case 2:
                       case 3: oss << "CI=" << CI << " ";
                               for (i=1; i<=3; ++i){
                                 oss.setf(ios::hex,ios::basefield);
                                 oss.width(4);
                                 oss.fill('0');
                                 oss << group.GetWord(i) << " ";
                               }
                               break;
                       case 4: tmc_provider[0]=group.GetByte(2,1);
                               tmc_provider[1]=group.GetByte(2,0);
                               tmc_provider[2]=group.GetByte(3,1);
                               tmc_provider[3]=group.GetByte(3,0);
                               oss << "provider=" << tmc_provider;
                               break;
                       case 5: tmc_provider[4]=group.GetByte(2,1);
                               tmc_provider[5]=group.GetByte(2,0);
                               tmc_provider[6]=group.GetByte(3,1);
                               tmc_provider[7]=group.GetByte(3,0);
                               oss << "provider=" << tmc_provider;
                               break;
                       case 6:
                       case 7:;
                     }
                     break;
    case TMC_TUNING: oss << "T ";
                     switch (CI){
                       case 0:
                       case 1:
                       case 2:
                       case 3:
                       case 4:
                       case 5:
                       case 6:
                       case 7: oss << "CI=" << CI << " ";
                               for (i=1; i<=3; ++i){
                                 oss.setf(ios::hex,ios::basefield);
                                 oss.width(4);
                                 oss.fill('0');
                                 oss << group.GetWord(i) << " ";
                               }
                     }
                     break;
  }
  if (add_string(oss.str())) is_changed = true;
  if (check_timeouts()) is_changed = true;
}

const string& TMClist::AsString()
{
  ostringstream oss;
  list<TMCinfo>::iterator it;
  for (it=tmc_list.begin(); it != tmc_list.end(); ++it){
    oss << (*it).data << endl;
  }
  list_string = oss.str();
  return list_string;
}
Exemple #23
0
void decode_program(FILE *f)
  {
  int c;
  char next_sub=0;
  char *d;

  d=(char *)calloc(sizeof(char),16384);
  open_level=0;
  c=fgetc(f);
  while (c!=EOF)
     {
     if (c=='!')
        {
        char d[256];

        fgets(&d,256,f);
        decode_pgf1(d);
        }
     else if (isdigit(c) || c=='-')
        {
        int cislo;
        ungetc(c,f);
        get_cislo(f,&cislo);
        add_short(cislo);
        }
     else if (c=='*')
        {
        int cislo;
        get_cislo(f,&cislo);
        if (cislo!=517 && next_sub)
           {
           js_close_sub();
           next_sub=0;
           }
        if (cislo!=171 && !iff_mode) pop_and_fill(prog_pos,open_level);
        switch (cislo)
           {
           case 512:js_dialoge(f);break; //Sekce DIALOG
           case 513:js_first(f);break;   //Prikaz FIRST
           case 514:add_short(152);  //Prikaz WHEN_ITEM
                    copy_short(f);
                    add_short(140);
                    get_cislo(f,&cislo);
                    if (cislo>0)add_short(cislo);else add_short(cislo+32767-basic_num);
                    break;
           case 515:add_short(163); //prikaz WHEN_FLAG
                    copy_short(f);
                    add_short(140);
                    get_cislo(f,&cislo);
                    if (cislo>0)add_short(cislo);else add_short(cislo+32767-basic_num);
                    break;
           case 516:js_standard(f);break; //prikaz STANDARD
           case 517:js_sub(f);next_sub=1;break; //prikaz SUB
           case 520:js_sentence(f);break;   //Sekce SENTENCE
           case -1:js_close_block();break; //znak }//
           case -2: if (iff_mode) add_if_jump();else error("Neocekavany znak '{' (open_block)");
                    open_level++;
                    break; //znak {//
           case 999:save_pgf_name(f);break;
           case 169:if (iff_mode) add_if_jump(); //prikaz if
                    iff_mode=IF_NOT_JUMP;break;
           case 170:if (iff_mode!=IF_NOT_JUMP) error("NOT bez IF"); //modifikator not
                    iff_mode=IF_JUMP;break;
           case 171:if (iff_mode) error("Chybn� pou�it� p�kazu ELSE"); //prikaz else
                    add_else();break;
           case 173:set_alternative(f);break;
           default: add_short(cislo);break;
           }
        }
     else if (c=='$')
        {
        fgets(d,16384,f);
        add_string(d);
        }
     else if (c=='&')
        {
        int cislo;
        get_cislo(f,&cislo);
        add_var(cislo);
        }
     c=fgetc(f);
     }
  free(d);
  }
Exemple #24
0
/////////////////////////////////////
// Funkce get_token
/////////////////////////////////////
int get_token(FILE *f, string *str) {
    int c;
    int ret;
    int state = start;
    char hex[] = "00";
    bool must_be_next = false;
    if(del_string(str) == RET_ERR)
        return RET_ERR;

    while((c=fgetc(f)) != EOF) {
        switch(state) {
        case start:
            ////// identifikátor
            if(isalpha(c) || c == '_') {
                state = identificator;
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            ////// Proměnná
            else if(c == '$') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                state = variable;
                must_be_next = true;
            }
            ////// Řetězcový literál
            else if(c == '"') {
                state = string_literal;
            }
            ////// číslo
            else if(isdigit(c)) {
                state = int_num;
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            ////////////////////////
            ////// Rovno, nerovno
            ////// jedno nebo tři rovnítka
            else if(c == '=') {
                state = equal;
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            ////// nerovno
            else if(c == '!') {
                state = not_equal;
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            ////// konkatenace - další znaky netřeba
            else if(c == '.') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return concatenate;
            }
            //////////////////
            ////// Logické
            ////// menší || menší nebo rovno
            else if(c == '<') {
                state = less;
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            ////// větší || větší nebo rovno
            else if(c == '>') {
                state = greater;
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            //////////////////
            ////// Aritmetické
            ////// pouze znak plus - další znaky netřeba
            else if(c == '+') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return plus;
            }
            ////// pouze znak plus - další znaky netřeba
            else if(c == '*') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return multiply;
            }
            ////// pouze znak mínus - další znaky netřeba
            else if(c == '-') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return minus;
            }
            ////// znak děleno || začátek komentáře
            else if(c == '/') {
                if(first)
                    return SYNT_ERR;
                else {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    state = comment;
                }
            }
            //////////////////
            ////// Závorky
            ////// pouze znak ( - další znaky netřeba
            else if(c == '(') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return left_parent;
            }
            ////// pouze znak ) - další znaky netřeba
            else if(c == ')') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return right_parent;
            }
            ////// pouze znak { - další znaky netřeba
            else if(c == '{') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return left_braces;
            }
            ////// pouze znak } - další znaky netřeba
            else if(c == '}') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return right_braces;
            }
            ////// znak děleno || začátek komentáře
            else if(c == ',') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return comma;
            }
            ////// pouze středník - další znaky netřeba
            else if(c == ';') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return semicolon;
            }
            else if(isspace(c)==0) {
                return LEX_ERR;
            }
            else {
                if(first)
                    return SYNT_ERR;
            }
            break;

        //////////////////
        ////// Identifikátor
        case identificator:
            if(isalpha(c) || isdigit(c) || c == '_') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            else {
                ungetc(c,f);
                int id = 0;
                if((id = is_keyword(str->strg))!=RET_ERR) {
                    return id;
                }
                else if((id = is_type(str->strg))!=RET_ERR) {
                    return id;
                }
                else if((id = is_const(str->strg))!=RET_ERR) {
                    return id;
                }
                else {
                    return identificator;
                }
            }
            break;

        //////////////////
        ////// Proměnná
        case variable:
            if(must_be_next) {
                if(isalpha(c) || c == '_') {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    must_be_next = false;
                }
                else
                    return LEX_ERR;
            }
            else {
                if(isalpha(c) || isdigit(c) || c == '_') {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                }
                else {
                    ungetc(c,f);
                    return variable;
                }
            }
            break;

        //////////////////
        ////// Řetězcový literál
        case string_literal:
            if(c > 31) {
                if(c == '\\') {
                    c=fgetc(f);
                    if(c == '"') {
                        if((ret = add_string(str,'\"')) == RET_ERR) return RET_ERR;
                    }
                    else if(c == 'n') {
                        if((ret = add_string(str,'\n')) == RET_ERR) return RET_ERR;
                    }
                    else if(c == '$') {
                        if((ret = add_string(str,'$')) == RET_ERR) return RET_ERR;
                    }
                    else if(c == 't') {
                        if((ret = add_string(str,'\t')) == RET_ERR) return RET_ERR;
                    }
                    else if(c == '\\') {
                        if((ret = add_string(str,'\\')) == RET_ERR) return RET_ERR;
                    }
                    else if(c == 'x') {
                        hex[0]=fgetc(f);
                        if(hex[0] == EOF)
                            return LEX_ERR;
                        else if(hex[0] == '\"') {
                            if((ret = add_string(str,'\\')) == RET_ERR) return RET_ERR;
                            if((ret = add_string(str,'x')) == RET_ERR) return RET_ERR;
                            return string_literal;
                        }
                        else if(hex[0] > 31) {
                            if(((hex[0]>'f') || (hex[0]<'a')) && ((hex[0]>'F') || (hex[0]<'A')) && ((hex[0]>'9') || (hex[0]<'0'))) {
                                if((ret = add_string(str,'\\')) == RET_ERR) return RET_ERR;
                                if((ret = add_string(str,'x')) == RET_ERR) return RET_ERR;
                                ungetc(hex[0],f);
                            }
                            else {
                                hex[1]=fgetc(f);
                                if(hex[1] == EOF)
                                    return LEX_ERR;
                                else if(hex[1] == '\"') {
                                    if((ret = add_string(str,'\\')) == RET_ERR) return RET_ERR;
                                    if((ret = add_string(str,'x')) == RET_ERR) return RET_ERR;
                                    if((ret = add_string(str,hex[0])) == RET_ERR) return RET_ERR;
                                    return string_literal;
                                }
                                else if(hex[1] > 31) {
                                    if(((hex[1]>'f') || (hex[1]<'a')) && ((hex[1]>'F') || (hex[1]<'A')) && ((hex[1]>'9') || (hex[1]<'0'))) {
                                        if((ret = add_string(str,'\\')) == RET_ERR) return RET_ERR;
                                        if((ret = add_string(str,'x')) == RET_ERR) return RET_ERR;
                                        ungetc(hex[0],f);
                                        ungetc(hex[1],f);

                                    }
                                    else {
                                        char* end = NULL;
                                        int pomoc = strtol(hex,&end,16);
                                        if(pomoc!=0 && *end == '\0') {
                                            if((ret = add_string(str,pomoc)) == RET_ERR) return RET_ERR;
                                        }

                                    }
                                }
                                else {
                                    return LEX_ERR;
                                }
                            }
                        }
                        else {
                            return LEX_ERR;
                        }
                    }
                    else if(c>31) {
                        ungetc(c,f);
                        c='\\';
                        if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    }
                    else
                        return LEX_ERR;
                }
                else if(c == '"') {
                    return string_literal;
                }
                else if(c == '$') {
                    return LEX_ERR;
                }
                else {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                }
            }
            else
                return LEX_ERR;
            break;

        //////////////////
        ////// Číslo
        case int_num:
            if(isdigit(c)) {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
            }
            else if(c=='.') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                state = double_num;
                must_be_next = true;
            }
            else if(c=='e'||c=='E') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                must_be_next = true;
                state = double_num_exp;
                c=fgetc(f);
                if(c=='-' || c=='+') {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                }
                else
                    ungetc(c,f);
            }
            else {
                ungetc(c,f);
                return int_num;
            }
            break;
        ////// desetinné číslo
        case double_num:
            if(must_be_next) {
                if(isdigit(c)) {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    must_be_next = false;
                }
                else {
                    return LEX_ERR;
                }
            }
            else {
                if(isdigit(c)) {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    must_be_next = false;
                }
                else if(c=='e'||c=='E') {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    state = double_num_exp;
                    c=fgetc(f);
                    must_be_next = true;
                    if(c=='-' || c=='+') {
                        if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    }
                    else
                        ungetc(c,f);
                }
                else {
                    ungetc(c,f);
                    return double_num;
                }
            }
            break;
        ////// desetinné číslo
        case double_num_exp:
            if(must_be_next) {
                if(isdigit(c)) {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    must_be_next = false;
                }
                else {
                    return LEX_ERR;
                }
            }
            else {
                if(isdigit(c)) {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                }
                else {
                    ungetc(c,f);
                    return double_num;
                }
            }
            break;

        //////////////////
        ////// Rovno
        case equal:
            if(c == '=') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                c=fgetc(f);
                if(c == '=') {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    return equal;
                }
                else {
                    ungetc(c,f);
                    return LEX_ERR;
                }
            }
            else {
                ungetc(c,f);
                return assign;
            }
            break;

        //////////////////
        ////// Nerovno
        case not_equal:
            if(c == '=') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                c=fgetc(f);
                if(c == '=') {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    return not_equal;
                }
                else {
                    ungetc(c,f);
                    return LEX_ERR;
                }
            }
            else {
                ungetc(c,f);
                return LEX_ERR;
            }
            break;

        //////////////////
        ////// Větší či většíRovno
        case greater:

            if(c == '=') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return greater_equal;
            }
            else {
                ungetc(c,f);
                return greater;
            }
            break;

        //////////////////
        ////// Menší či menšíRovno
        case less:
            if(c == '=') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                return less_equal;
            }
            else if(c == '?') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                state=php_entry;
            }
            else {
                ungetc(c,f);
                return less;
            }
            break;

        case php_entry:
            if(c == 'p') {
                if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                c=fgetc(f);
                if(c == 'h') {
                    if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                    c=fgetc(f);
                    if(c == 'p') {
                        if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                        c=fgetc(f);
                        if(c==EOF) {
                            return php_entry_wrong;
                        }
                        else  if(isspace(c)) {
                            c=fgetc(f);
                            if(c==EOF) {
                                return php_entry_wrong;
                            }
                            ungetc(c,f);
                            if((ret = add_string(str,c)) == RET_ERR) return RET_ERR;
                            first = false;
                            return php_entry;
                        }

                        else {
                            first = false;
                            return php_entry;
                        }
                    }
                    else {
                        return LEX_ERR;
                    }
                }
                else {
                    return LEX_ERR;
                }
            }
            else {
                ungetc(c,f);
                return LEX_ERR;
            }
            break;
        //////////////////
        ////// Komentáře
        case comment:
            if(c == '/') {
                while((c=fgetc(f)) != EOF) {
                    if(c=='\n')
                        break;
                }
                del_string(str);
                state = start;
            }
            else if(c=='*') {
                while((c=fgetc(f)) != EOF) {
                    if(c=='*') {
                        if((c=fgetc(f)) == '/') {
                            state = start;
                            del_string(str);
                            break;
                        }
                        else
                            ungetc(c,f);
                    }
                }
                if(c==EOF && state==comment)
                    return LEX_ERR;

            }
            else {
                ungetc(c,f);
                return divide;
            }
            break;
        }
    }
    return EOF;
}
Exemple #25
0
void
add_special(int argc, char **argv)
{
	int i;
	prog_t *p = find_prog(argv[1]);

	if (p == NULL) {
		if (reading_cache)
			return;

		warnx("%s:%d: no prog %s previously declared, skipping special",
		    curfilename, linenum, argv[1]);
		goterror = 1;
		return;
	}

	if (!strcmp(argv[2], "ident")) {
		if (argc != 4)
			goto argcount;
		if ((p->ident = strdup(argv[3])) == NULL)
			out_of_memory();
	} else if (!strcmp(argv[2], "srcdir")) {
		if (argc != 4)
			goto argcount;
		if ((p->srcdir = strdup(argv[3])) == NULL)
			out_of_memory();
	} else if (!strcmp(argv[2], "objdir")) {
		if(argc != 4)
			goto argcount;
		if((p->objdir = strdup(argv[3])) == NULL)
			out_of_memory();
	} else if (!strcmp(argv[2], "objs")) {
		p->objs = NULL;
		for (i = 3; i < argc; i++)
			add_string(&p->objs, argv[i]);
	} else if (!strcmp(argv[2], "objpaths")) {
		p->objpaths = NULL;
		for (i = 3; i < argc; i++)
			add_string(&p->objpaths, argv[i]);
	} else if (!strcmp(argv[2], "keep")) {
		p->keeplist = NULL;
		for(i = 3; i < argc; i++)
			add_string(&p->keeplist, argv[i]);
	} else if (!strcmp(argv[2], "objvar")) {
		if(argc != 4)
			goto argcount;
		if ((p->objvar = strdup(argv[3])) == NULL)
			out_of_memory();
	} else if (!strcmp(argv[2], "buildopts")) {
		p->buildopts = NULL;
		for (i = 3; i < argc; i++)
			add_string(&p->buildopts, argv[i]);
	} else if (!strcmp(argv[2], "lib")) {
		for (i = 3; i < argc; i++)
			add_string(&p->libs, argv[i]);
	} else {
		warnx("%s:%d: bad parameter name `%s', skipping line",
		    curfilename, linenum, argv[2]);
		goterror = 1;
	}
	return;

 argcount:
	warnx("%s:%d: too %s arguments, expected \"special %s %s <string>\"",
	    curfilename, linenum, argc < 4? "few" : "many", argv[1], argv[2]);
	goterror = 1;
}
Exemple #26
0
/********************************************//**
 * Name:
 *  parse_line
 *
 * Params:
 *  *comp - A pointer to a compiler.
 *
 * Description:
 *  This function will parse the lines.
 *  it will is the standard libraries strtok() function
 *  to break the line in to tokens for further processing.
 *
 * Return:
 *  1 There was a problem parsing the line.
 *  0 The line was parsed successfully.
 *
 ***********************************************/
int parse_line(Compiler *comp) {

	//Create local copy of line so strtok() doesn't destroy the original.
	char *symbol = NULL;
	char *locLine = (char *) malloc(sizeof(char) * MAX_LINE_LEN);
	strcpy(locLine, comp->line);
	char *token = strtok(locLine, " \r\t\n");

	//Check if the line is empty, if it is stop the processing.
	if (token == NULL)
		return 0;

	//Check if the line is a comment, if it is stop the processing.
	if (strstr(token, ";") != NULL)
		return 0;

	//Check if optional label exists, if it does set symbol parameter, and get next token.
	if ((strstr(token, ":")) != NULL) {
		symbol = token;
		CUT_LAST_CHAR(symbol);
		token = strtok(NULL, " \r\t\n");
	}

	//Check if the line is .entry
	if (strstr(comp->line, ".entry") != NULL) {
		token = strtok(NULL, " \r\t\n");
		add_entry(comp, token);
		if (symbol != NULL)
			add_symbol(comp, symbol, DATA);
		return 0;
	}

	//Check if the line is .extern
	if (strstr(comp->line, ".extern") != NULL) {
		token = strtok(NULL, " \r\t\n");
		add_extern(comp, token);
		if (symbol != NULL)
			add_symbol(comp, symbol, DATA);
		return 0;
	}

	//Check if the line is .data
	if (strstr(comp->line, ".data") != NULL) {
		if (symbol != NULL)
			add_symbol(comp, symbol, DATA);
		token = strtok(NULL, " \r\t\n");
		add_data(comp, atoi(token));
		return 0;
	}

	//Check if the line is .string
	if (strstr(comp->line, ".string") != NULL) {
		if (symbol != NULL)
			add_symbol(comp, symbol, DATA);
		token = strtok(NULL, " \r\t\n");
		if (is_valid_string(token))
			add_string(comp, token);
		else
			add_error(comp, comp->fileName, comp->lineIdx, "Missing \"\n");
		return 0;
	}

	//if we got here the the line is code, if it has an optional symbol add it to symbol table.
	if (symbol != NULL)
		add_symbol(comp, symbol, CODE);

	//Add code to the compiler and check if the addition was successful.
	if (!add_code(comp, token, strtok(NULL, " \r\t\n"), strtok(NULL, ","))) {

		//Update the codeLen and dataLen fields
		comp->codeLen = comp->IC;
		comp->dataLen = comp->DC;
		free(locLine);
		return 0;
	}
	add_error(comp, comp->fileName, comp->lineIdx,
			"Incorrect line definition.");
	return 1;
}
bool string_base::fix_eol(const char * append,t_size start)
{
	const bool rv = truncate_eol(start);
	if (rv) add_string(append);
	return rv;
}
Exemple #28
0
void add_option(struct module *module, char const * option)
{
  add_string(&module->options, &module->num_options, option);
}
Exemple #29
0
errno_t
sysdb_svc_add(TALLOC_CTX *mem_ctx,
              struct sss_domain_info *domain,
              const char *primary_name,
              int port,
              const char **aliases,
              const char **protocols,
              struct ldb_dn **dn)
{
    errno_t ret;
    int lret;
    TALLOC_CTX *tmp_ctx;
    struct ldb_message *msg;
    unsigned long i;

    tmp_ctx = talloc_new(NULL);
    if (!tmp_ctx) return ENOMEM;

    msg = ldb_msg_new(tmp_ctx);
    if (!msg) {
        ret = ENOMEM;
        goto done;
    }

    /* svc dn */
    msg->dn = sysdb_svc_dn(domain->sysdb, msg, domain->name, primary_name);
    if (!msg->dn) {
        ret = ENOMEM;
        goto done;
    }

    /* Objectclass */
    ret = add_string(msg, LDB_FLAG_MOD_ADD,
                     SYSDB_OBJECTCLASS, SYSDB_SVC_CLASS);
    if (ret != EOK) goto done;

    /* Set the primary name */
    ret = add_string(msg, LDB_FLAG_MOD_ADD,
                     SYSDB_NAME, primary_name);
    if (ret != EOK) goto done;

    /* Set the port number */
    ret = add_ulong(msg, LDB_FLAG_MOD_ADD,
                    SYSDB_SVC_PORT, port);
    if (ret != EOK) goto done;

    /* If this service has any aliases, include them */
    if (aliases && aliases[0]) {
        /* Set the name aliases */
        lret = ldb_msg_add_empty(msg, SYSDB_NAME_ALIAS,
                                 LDB_FLAG_MOD_ADD, NULL);
        if (lret != LDB_SUCCESS) {
            ret = sysdb_error_to_errno(lret);
            goto done;
        }
        for (i=0; aliases[i]; i++) {
            lret = ldb_msg_add_string(msg, SYSDB_NAME_ALIAS, aliases[i]);
            if (lret != LDB_SUCCESS) {
                ret = sysdb_error_to_errno(lret);
                goto done;
            }
        }
    }

    /* Set the protocols */
    lret = ldb_msg_add_empty(msg, SYSDB_SVC_PROTO,
                             LDB_FLAG_MOD_ADD, NULL);
    if (lret != LDB_SUCCESS) {
        ret = sysdb_error_to_errno(lret);
        goto done;
    }
    for (i=0; protocols[i]; i++) {
        lret = ldb_msg_add_string(msg, SYSDB_SVC_PROTO, protocols[i]);
        if (lret != LDB_SUCCESS) {
            ret = sysdb_error_to_errno(lret);
            goto done;
        }
    }

    /* creation time */
    ret = add_ulong(msg, LDB_FLAG_MOD_ADD, SYSDB_CREATE_TIME,
                    (unsigned long)time(NULL));
    if (ret) goto done;

    lret = ldb_add(domain->sysdb->ldb, msg);
    ret = sysdb_error_to_errno(lret);

    if (ret == EOK && dn) {
        *dn = talloc_steal(mem_ctx, msg->dn);
    }

done:
    if (ret) {
        DEBUG(SSSDBG_TRACE_INTERNAL,
              "Error: %d (%s)\n", ret, strerror(ret));
    }
    talloc_free(tmp_ctx);
    return ret;
}
Exemple #30
0
/*************************************************************************
 * int main
 *************************************************************************/
int main(int argc, char *argv[])
{
  /* Data structures. */
  int       num_motifs;         /* The number of motifs in the model. */
  MOTIF_T   motifs[2 * MAX_MOTIFS]; /* The motifs. */
  STRING_LIST_T* motif_occurrences = NULL; /* Strings describing occurrences of
                                              motifs */
  BOOLEAN_T has_reverse_strand = FALSE;    /* MEME file contained both strands */
  ARRAY_T*  background;         /* Background probs for alphabet. */
  ORDER_T*  order_spacing;      /* Linear HMM order and spacing. */
  MATRIX_T* transp_freq = NULL; /* Matrix of inter-motif transitions freqs. */
  MATRIX_T* spacer_ave = NULL;  /* Matrix of average spacer lengths. */
  MHMM_T *  the_hmm = NULL;     /* The HMM being constructed. */

  /* Command line parameters. */
  char *    meme_filename;      /* Input file containg motifs. */
  char *    hmm_type_str;       /* HMM type. */
  HMM_T     hmm_type;
  STRING_LIST_T* requested_motifs; /* Indices of requested motifs. */
  int       request_n;          /* The user asked for the first n motifs. */
  double    e_threshold;        /* E-value threshold for motif inclusion. */
  double    complexity_threshold; // For eliminating low-complexity motifs.
  double    p_threshold;        /* p-value threshold for motif occurences. */
  char*     order_string;       /* Motif order and spacing. */
  int       spacer_states;      /* Number of states in each spacer. */
  BOOLEAN_T fim;                /* Represent spacers as free insertion
				   modules? */
  BOOLEAN_T keep_unused;        // Drop unused inter-motif transitions?
  double    trans_pseudo;       /* Transition pseudocount. */
  double    spacer_pseudo;      // Spacer (self-loop) pseudocount. */
  char*     description;        // Descriptive text to be stored in model.
  BOOLEAN_T print_header;       /* Print file header? */
  BOOLEAN_T print_params;       /* Print parameter summary? */
  BOOLEAN_T print_time;         /* Print timing data (dummy: always false). */

  /* Local variables. */
  int       i_motif;

  /**********************************************
   * COMMAND LINE PROCESSING
   **********************************************/
  // Define command line options.
  cmdoption const options[] = {
    {"type", OPTIONAL_VALUE},
    {"description", REQUIRED_VALUE},
    {"motif", REQUIRED_VALUE},
    {"nmotifs", REQUIRED_VALUE},
    {"ethresh", REQUIRED_VALUE},
    {"lowcomp", REQUIRED_VALUE},
    {"pthresh", REQUIRED_VALUE},
    {"order", REQUIRED_VALUE},
    {"nspacer", REQUIRED_VALUE},
    {"fim", NO_VALUE},
    {"keep-unused", NO_VALUE},
    {"transpseudo", REQUIRED_VALUE},
    {"spacerpseudo", REQUIRED_VALUE},
    {"verbosity", REQUIRED_VALUE},
    {"noheader", NO_VALUE},
    {"noparams", NO_VALUE},
    {"notime", NO_VALUE},
    {"quiet", NO_VALUE},
  };
  int option_count = 18;
  int option_index = 0;

  // Define the usage message.
  char      usage[1000] = "";
  strcat(usage, "USAGE: mhmm [options] <MEME file>\n");
  strcat(usage, "\n");
  strcat(usage, "   Options:\n");
  strcat(usage, "     --type [linear|complete|star] (default=linear)\n");
  strcat(usage, "     --description <string> (may be repeated)\n");
  strcat(usage, "     --motif <motif #> (may be repeated)\n");
  strcat(usage, "     --nmotifs <#>\n");
  strcat(usage, "     --ethresh <E-value>\n");
  strcat(usage, "     --lowcomp <value>\n");
  strcat(usage, "     --pthresh <p-value>\n");
  strcat(usage, "     --order <string>\n");
  strcat(usage, "     --nspacer <spacer length> (default=1)\n");
  strcat(usage, "     --fim\n");
  strcat(usage, "     --keep-unused\n");
  strcat(usage, "     --transpseudo <pseudocount>\n");
  strcat(usage, "     --spacerpseudo <pseudocount>\n");
  strcat(usage, "     --verbosity 1|2|3|4|5 (default=2)\n");
  strcat(usage, "     --noheader\n");
  strcat(usage, "     --noparams\n");
  strcat(usage, "     --notime\n");
  strcat(usage, "     --quiet\n");
  strcat(usage, "\n");

  /* Make sure various options are set to NULL or defaults. */
  meme_filename = NULL;
  hmm_type_str = NULL;
  hmm_type = INVALID_HMM;
  requested_motifs = new_string_list();
  request_n = 0;
  e_threshold = 0.0;
  complexity_threshold = 0.0;
  p_threshold = 0.0;
  order_string = NULL;
  spacer_states = DEFAULT_SPACER_STATES,
  fim = FALSE;
  keep_unused = FALSE;
  trans_pseudo = DEFAULT_TRANS_PSEUDO;
  spacer_pseudo = DEFAULT_SPACER_PSEUDO;
  description = NULL;
  print_header = TRUE;
  print_params = TRUE;
  print_time = FALSE;

	simple_setopt(argc, argv, option_count, options);

  // Parse the command line.
  while (1) { 
    int c = 0;
    char* option_name = NULL;
    char* option_value = NULL;
    const char * message = NULL;


    // Read the next option, and break if we're done.
    c = simple_getopt(&option_name, &option_value, &option_index);
    if (c == 0) {
      break;
    } else if (c < 0) {
    	simple_getopterror(&message);
      die("Error processing command line options (%s)\n", message);
    }

    if (strcmp(option_name, "type") == 0) {
			if (option_value != NULL) {
      	hmm_type_str = option_value;
			}
    } else if (strcmp(option_name, "description") == 0) {
      description = option_value;
    } else if (strcmp(option_name, "motif") == 0) {
      add_string(option_value, requested_motifs);
    } else if (strcmp(option_name, "nmotifs") == 0) {
      request_n = atoi(option_value);
    } else if (strcmp(option_name, "ethresh") == 0) {
      e_threshold = atof(option_value);
    } else if (strcmp(option_name, "lowcomp") == 0) {
      complexity_threshold = atof(option_value);
    } else if (strcmp(option_name, "pthresh") == 0) {
      p_threshold = atof(option_value);
    } else if (strcmp(option_name, "order") == 0) {
      order_string = option_value;
    } else if (strcmp(option_name, "nspacer") == 0) {
      spacer_states = atoi(option_value);
    } else if (strcmp(option_name, "fim") == 0) {
      fim = TRUE;
    } else if (strcmp(option_name, "keep-unused") == 0) {
      keep_unused = TRUE;
    } else if (strcmp(option_name, "transpseudo") == 0) {
      trans_pseudo = atof(option_value);
    } else if (strcmp(option_name, "spacerpseudo") == 0) {
      spacer_pseudo = atof(option_value);
    } else if (strcmp(option_name, "verbosity") == 0) {
      verbosity = (VERBOSE_T)atoi(option_value);
    } else if (strcmp(option_name, "noheader") == 0) {
      print_header = FALSE;
    } else if (strcmp(option_name, "noparams") == 0) {
      print_params = FALSE;
    } else if (strcmp(option_name, "notime") == 0) {
      print_time = FALSE;
    } else if (strcmp(option_name, "quiet") == 0) {
      print_header = print_params = print_time = FALSE;
      verbosity = QUIET_VERBOSE;
    }
  }

  // Read the single required argument.
  if (option_index + 1 != argc) {
    fprintf(stderr, "%s", usage);
    exit(1);
  }
  meme_filename = argv[option_index];

  // Set up motif requests. 
  if (request_n != 0) {
    if (get_num_strings(requested_motifs) != 0) {
      die("Can't combine the -motif and -nmotifs options.\n");
    } else {
      for (i_motif = 0; i_motif < request_n; i_motif++) {
        char motif_id[MAX_MOTIF_ID_LENGTH + 1];
        sprintf(motif_id, "%d", i_motif + 1);
        add_string(motif_id, requested_motifs);
      }
    }
  }

  /* Set the model type. */
  hmm_type = convert_enum_type_str(hmm_type_str, LINEAR_HMM, HMM_STRS, 
				   NUM_HMM_T);

  /* Gotta have positive spacer length. */
  if (spacer_states <= 0) {
    die("Negative spacer length (%d).\n", spacer_states);
  }

  /* Make sure motifs weren't selected redundantly. */
  // FIXME: Add tests for complexity threshold.
  if ((get_num_strings(requested_motifs) != 0) && (e_threshold != 0.0)) {
    die("Can't use -motif or -nmotifs with -ethresh.");
  }
  if ((get_num_strings(requested_motifs) != 0) && (order_string != NULL)) {
    die("Can't use -motif or -nmotifs with -order.");
  }
  if ((order_string != NULL) && (e_threshold != 0.0)) {
    die("Can't use -ethresh and -order.");
  }

  /* Prevent trying to build a complete or star model with ordering. */
  if (order_string != NULL) {
    if (hmm_type == COMPLETE_HMM) 
      die("Can't specify motif order with a completely connected model.");
    else if (hmm_type == STAR_HMM)
      die("Can't specify motif order with a star model.");
  } 

  // Parse the order string. 
  order_spacing = create_order(order_string);

  /**********************************************
   * READING THE MOTIFS
   **********************************************/

  BOOLEAN_T read_file = FALSE;
  double pseudocount = 0;

  read_meme_file(
		 meme_filename,
		 "motif-file", // Take bg freq. from motif file.
		 pseudocount,
     REQUIRE_PSPM,
		 &num_motifs,
		 motifs,
		 &motif_occurrences,
		 &has_reverse_strand,
		 &background
		 );

  process_raw_motifs_for_model(
       &num_motifs,
       motifs,
       motif_occurrences,
       requested_motifs,
       has_reverse_strand,
       keep_unused,
       p_threshold,
       e_threshold, 
       complexity_threshold, 
       &order_spacing,
       &transp_freq,
       &spacer_ave,
       trans_pseudo,
       spacer_pseudo
  );

  /**********************************************
   * BUILDING THE HMM
   **********************************************/

  /* Build the motif-based HMM. */
  if (hmm_type == LINEAR_HMM) {

    if (order_spacing != NULL) {
      reorder_motifs(order_spacing, &num_motifs, motifs);
    }
    else {
      die("No order specified for the motifs.\n"
          "For the linear model the motif file must contain motif occurence\n" 
          "data or the motif order must be specified using "
          "the --order option.");
    }

    build_linear_hmm(
      background,
		  order_spacing,
		  spacer_states,
		  motifs,
		  num_motifs, 
		  fim,
		  &the_hmm
    );

  } else if (hmm_type == COMPLETE_HMM) {

    build_complete_hmm(
      background,
		  spacer_states,
		  motifs,
		  num_motifs,
		  transp_freq,
		  spacer_ave,
		  fim,
		  &the_hmm
    );

  } else if (hmm_type == STAR_HMM) {

    build_star_hmm(
      background,
		  spacer_states,
		  motifs,
		  num_motifs,
		  fim,
		  &the_hmm
    );

  }

  // Add some global information.
  copy_string(&(the_hmm->motif_file), meme_filename);

  /**********************************************
   * WRITING THE HMM
   **********************************************/

  /* Print the header. */
  if (print_header)
    write_header(
     program, 
     "",
		 description,
		 meme_filename,
		 NULL,
		 NULL, 
		 stdout
    );

  /* Write the HMM. */
  write_mhmm(verbosity, the_hmm, stdout);

  /* Print the program parameters. */
  if (print_params) {
    printf("Program parameters for mhmm\n");
    printf("  MEME file: %s\n", meme_filename);
    printf("  Motifs:");
    write_string_list(" ", requested_motifs, stdout);
    printf("\n");
    printf("  Model topology: %s\n",
	   convert_enum_type(hmm_type, HMM_STRS, NUM_HMM_T));
    printf("  States per spacer: %d\n", spacer_states);
    printf("  Spacers are free-insertion modules: %s\n",
	   boolean_to_string(fim));
    printf("\n");
  }

  free_array(background);
  free_string_list(requested_motifs);
  free_order(order_spacing);
  free_matrix(transp_freq);
  free_matrix(spacer_ave);
  for (i_motif = 0; i_motif < num_motifs; i_motif++)
    free_motif(&(motifs[i_motif]));
  free_mhmm(the_hmm);
  return(0);
}