Exemplo n.º 1
0
/*
 * Allocate segment table.  On error, destroy the table and set errno.
 *
 * Returns 0 on success
 */
static int
alloc_segs(HTAB *hashp, int nsegs)
{
	int i;
	SEGMENT store;

	int save_errno;

	if ((hashp->dir =
	    (SEGMENT *)calloc(hashp->DSIZE, sizeof(SEGMENT *))) == NULL) {
		save_errno = errno;
		(void)hdestroy(hashp);
		errno = save_errno;
		return (-1);
	}
	hashp->nsegs = nsegs;
	if (nsegs == 0)
		return (0);
	/* Allocate segments */
	if ((store = (SEGMENT)calloc(nsegs << hashp->SSHIFT,
	    sizeof(SEGMENT))) == NULL) {
		save_errno = errno;
		(void)hdestroy(hashp);
		errno = save_errno;
		return (-1);
	}
	for (i = 0; i < nsegs; i++)
		hashp->dir[i] = &store[i << hashp->SSHIFT];
	return (0);
}
Exemplo n.º 2
0
int
main(int argc, char *argv[])
{
    FILE *fp;
    char *mode, *file;
    char *w;
    char buf[MAXLEN];
    struct wordcnt wordcnt[2048];
    int wcount = 0;
    int i;

    if (argc < 3) {
        printf("Usage: %s [123] inputfile\n", argv[0]);
        return 1;
    }

    mode = argv[1];
    file = argv[2];

    if ((fp = fopen(file, "r")) == NULL) {
        printf("file open error: file=%s\n", file);
        return 1;
    }

    hcreate(4096);

    while (getword(fp, buf, MAXLEN) != NULL) {
        ENTRY item, *ip;
        struct wordcnt *wc = &wordcnt[wcount];

        item.key = buf;
        item.data = &wc->cnt;
        if ((ip = hsearch(item, FIND)) == NULL) {
            int len = strnlen(buf, MAXLEN);
            char *key = (char *) malloc(sizeof (char) * len);

            strncpy(key, buf, MAXLEN);
            item.key = key;
            wc->word = key;
            wc->cnt = 1;

            hsearch(item, ENTER);
            wcount++;
        } else {
            *((int *) ip->data) += 1;
        }
    }

    qsort(wordcnt, wcount, sizeof (struct wordcnt), wccmp);
    for (i = 0; i < wcount; i++) {
        struct wordcnt *wc = &wordcnt[i];
        printf("% 4d: %s\n", wc->cnt, wc->word);
    }

    hdestroy();

    fclose(fp);

    return 0;
}
Exemplo n.º 3
0
int
main(void)
{
    ENTRY e, *ep;
    int i;

   hcreate(30);

   for (i = 0; i < 24; i++) {
        e.key = data[i];
        /* data is just an integer, instead of a
           pointer to something */
        e.data = (void *) i;
        ep = hsearch(e, ENTER);
        /* there should be no failures */
        if (ep == NULL) {
            fprintf(stderr, "entry failed\n");
            exit(EXIT_FAILURE);
        }
    }

   for (i = 22; i < 26; i++) {
        /* print two entries from the table, and
           show that two are not in the table */
        e.key = data[i];
        ep = hsearch(e, FIND);
        printf("%9.9s -> %9.9s:%d\n", e.key,
               ep ? ep->key : "NULL", ep ? (int)(ep->data) : 0);
    }
    hdestroy();
    exit(EXIT_SUCCESS);
}
static bool checkPermissions(EntityManager *entityManager) {
  int16_t res;
  char userName[EXP_MAX_USER_NAME];
  const char *resourceName=NULL, *permission=NULL;
  AclPermissionsS *permissionsVec=NULL;
  htab *whoUses=NULL;
  const char *haveStr[] = {"doesn't have", "has"};

  snprintf(userName, sizeof(userName), USER_NAME_FMT, 1);
  resourceName = resourcesList[0];
  Acl_NewPermissionsList("", &permissionsVec);
  Acl_GetAllPermissions(entityManager, resourceName, permissionsVec);
  printf("The permissions for resource '%s' are:\n", resourceName);
  Acl_PrintPermissionsList(stdout, "", permissionsVec);
  Acl_FreePermissionsList(permissionsVec);
  resourceName = resourcesList[1];
  Acl_NewPermissionsList("", &permissionsVec);
  Acl_GetUserPermissions(entityManager, resourceName, userName, &permissionsVec);
  printf("User '%s' has for resource '%s' ", userName, resourceName);
  Acl_PrintPermissionsList(stdout, "", permissionsVec);
  Acl_FreePermissionsList(permissionsVec);
  permission = permissionsList[0];
  res = Acl_CheckEntityPermission(entityManager, resourceName, userName, permission);
  printf("User '%s' %s permission '%s' for resource '%s'\n", userName, haveStr[res], permission, resourceName);
  permission = permissionsList[1];
  res = Acl_CheckEntityPermission(entityManager, resourceName, userName, permission);
  printf("User '%s' %s permission '%s' for resource '%s'\n", userName, haveStr[res], permission, resourceName);
  whoUses = hcreate(H_TAB_SIZE);
  Acl_WhoUseAPermission(entityManager, allPermission, whoUses);
  printf("Users that have permission '%s':\n", allPermission);
  Utils_PrintHashKeys("", "  -", whoUses);
  hdestroy(whoUses);
  return true;
}
Exemplo n.º 5
0
Arquivo: asn.c Projeto: bzruk/mtr
void asn_close(void) {
    if (hash) {
        IIDEBUG_MSG((LOG_INFO, "hdestroy()"));
        hdestroy();
        hash = enable_ipinfo = 0;
    }
}
Exemplo n.º 6
0
/*
 * The hash table is to keep track of leaves which have already been displayed
 * to the user.
 */
int main(int argc, char **argv)
{
	int			i;

	/* Initialize space for blacklist hash table */
	if(hcreate(10000)==0) {
		fputs("Cannot create hash table.\n",stderr);
		return(EX_UNAVAILABLE);
	}

	i=0;
	do {
		if(read_pkglist(i++))
			break;
		if(display_menu())
			break;
		if(remove_packages())
			break;
		free_menu();
	} while(keep_going());
	hdestroy();

	fputs("\nProgram Terminated Successfully\n",stderr);
	return(0);
}
Exemplo n.º 7
0
int init_rtvars(char *filename, int number)
{
   int i,rtvar_value;
   ENTRY item;
   char *str_ptr;

   /* Initialize data areas */
   rtvarname_ptr = (char *)malloc(number*20);
   if (rtvarname_ptr == NULL) return (0);
   memset(rtvarname_ptr, 0, (number*20));

   info_ptr = (struct info *)malloc(sizeof(struct info)*number);

   /* Open rtvar info file */
   rtvarfile = fopen(filename,"r");
   if (rtvarfile == NULL)
   {  fprintf(stderr,"init_rtvars: cannot open %s\n",filename);
      return(0);			/* return failure */
   }

   /* create table */
   i = 0;
   str_ptr = rtvarname_ptr;
   hdestroy();			/* first destroy any previous table */
   (void) hcreate(number);
   while (fscanf(rtvarfile,"%s%d%d", str_ptr, &rtvar_value,
           &info_ptr->index) != EOF && i++ < number) {
              /* put info in structure, and structure in item */
         item.key = str_ptr;
         item.data = (void *)info_ptr;
         str_ptr += strlen(str_ptr) + 1;
         info_ptr++;
   	 /* put item into table */
         (void) hsearch(item, ENTER);
   }
   fclose(rtvarfile);
   if (i < number){
	 max_rtvars = i;
   }
   else {
	hdestroy();
	return(-1);
   }
   rtvarinfo_exist = 1;
   return(i);
}
Exemplo n.º 8
0
Arquivo: asn.c Projeto: russor/mtr
void asn_close(
    struct mtr_ctl *ctl)
{
    if ((ctl->ipinfo_no >= 0) && iihash) {
        DEB_syslog(LOG_INFO, "hdestroy()");
        hdestroy();
        iihash = 0;
    }
}
Exemplo n.º 9
0
Arquivo: asn.c Projeto: RichiH/mtr
void asn_close(void) {
    if (iihash) {
#ifdef IIDEBUG
        syslog(LOG_INFO, "hdestroy()");
#endif
        hdestroy();
        iihash = 0;
    }
}
Exemplo n.º 10
0
int ktup_comparison_hasch ( char *i_seq1, char *i_seq2, const int ktup)
{
  /*Ktup comparison adapted from Rob Edgar, NAR, vol32, No1, 381, 2004*/
  /*1: hasch sequence 1
    2: Count the number of seq2 ktup found in seq1
  */

  char c;
  int key;

  static HaschT*H1;
  static char *pseq;
  Hasch_entry *e;
  char *s;
  int l, ls;
  int p, a, max_dist=-1;
  double score=0;



  if (!strm (i_seq1, pseq))
    {
      if (H1)
	{
	  hdestroy (H1, declare_ktup_hasch_data, free_ktup_hasch_data);
	  string2key (NULL, NULL);
	}
      H1=hasch_sequence ( i_seq1, ktup);
      vfree (pseq);pseq=(char*)vcalloc ( strlen (i_seq1)+1, sizeof (char));
      sprintf ( pseq, "%s", i_seq1);
    }

  ls=l=strlen (i_seq2);
  s=i_seq2;
  p=0;
  while (ls>ktup)
    {
      c=s[ktup];s[ktup]='\0';
      key=string2key (s, NULL);
      e=hsearch (H1,key,FIND, declare_ktup_hasch_data, free_ktup_hasch_data);

      if ( e==NULL);
      else if ( max_dist==-1)score++;
      else
	{
	  for ( a=1; a<=(e->data)->list[1]; a++)
	    if (FABS((p-(e->data)->list[a]))<=max_dist)
	      {score++; break;}
	}
      s[ktup]=c;s++;p++;ls--;
    }
  score/=(l-ktup);
  score=(log(0.1+score)-log(0.1))/(log(1.1)-log(0.1));

  if ( score>100) score=100;
  return (int)(score*100);
}
STATIC void freeData(htab *t) {
  if (t == NULL) return;
  while (hcount(t)) {
    Utils_Free(hkey(t));
    Utils_Free(hstuff(t));
    hdel(t);
  }
  hdestroy(t);
}
Exemplo n.º 12
0
static utree_t * find_outgroup_mrca(utree_t ** node_list,
                                    utree_t * root,
                                    char * outgroup_list,
                                    int tip_count)
{
  int i;
  utree_t * outgroup;

  char * taxon;
  size_t taxon_len;

  ENTRY * found = NULL;

  /* create a hashtable of tip labels */
  hcreate(2 * tip_count);
  for (i = 0; i < tip_count; ++i)
  {
    ENTRY entry;
    entry.key  = node_list[i]->label;
    entry.data = node_list[i];
    hsearch(entry,ENTER);
  }

  while (*outgroup_list)
  {
    taxon_len = strcspn(outgroup_list, ",");
    if (!taxon_len)
      fatal("Erroneous outgroup format (double comma)/taxon missing");

    taxon = strndup(outgroup_list, taxon_len);

    /* find the taxon in the hash table */
    ENTRY query;
    query.key = taxon;
    found = NULL;
    found = hsearch(query,FIND);
    
    if (!found)
      fatal("Taxon %s in --outgroup does not appear in the tree", taxon);

    ((utree_t *)(found->data))->mark = 1;
    printf("\t%s\n", taxon);

    free(taxon);
    outgroup_list += taxon_len;
    if (*outgroup_list == ',') 
      outgroup_list += 1;
  }

  printf("Label: %s\n", ((utree_t *)(found->data))->label);
  outgroup = outgroup_node(((utree_t *)(found->data))->back);

  hdestroy();
  
  return outgroup;
}
Exemplo n.º 13
0
/* A new Lou ([email protected]) routine.
 *
 * The database is screwed.  
 *
 * This closes the file, flushing buffers as appropriate.
 */
static void
__remove_database(DB *dbp)
{
	HTAB *hashp = (HTAB *)dbp->internal;

	assert(0);

	if (!hashp)
		return;
	hdestroy(hashp);
	dbp->internal = NULL; 
}
Exemplo n.º 14
0
static void free_memory (void)
{
	hdestroy ();

	if (summary)
		free (summary);

	if (output_fields)
		free (output_fields);

	if (strat_id == strat_re)
		regfree (&regexp);
}
Exemplo n.º 15
0
static int
hash_close(DB *dbp)
{
	HTAB *hashp;
	int retval;

	if (!dbp)
		return (ERROR);

	hashp = (HTAB *)dbp->internal;
	retval = hdestroy(hashp);
	free(dbp);
	return (retval);
}
Exemplo n.º 16
0
Arquivo: io.c Projeto: seeslab/rgraph
int
AssignNodesToModulesFromFile(FILE *inF,
                             Partition *part,
                             char **labels) {
    char label[MAX_LABEL_LENGTH];
    char sep[2];
    int j = 0, nfields = 0, nnode = part->N;
    hcreate(part->N);
    int i;
    ENTRY e, *ep;

    for (i=0; i<nnode; i++) {
        e.key = labels[i];
        e.data = (void *) i;
        ep = hsearch(e, ENTER);
    }

    while (!feof(inF)) {
        nfields=fscanf(inF,"%[^\t\n]%[\t\n]",&label,&sep);
        if (nfields) {
            e.key = label;
            ep = hsearch(e, FIND);
            i = (int) ep->data;
            nnode--;

            if (!part->modules[j]->size) {
                part->nempty --;
                part->nodes[i]->module = j;
                part->modules[j]->size = 1;
                part->modules[j]->strength = part->nodes[i]->strength;
                part->modules[j]->first = part->nodes[i];
                part->modules[j]->last = part->nodes[i];
            }
            else {
                part->nodes[i]->module = j;
                part->modules[j]->size++;
                part->modules[j]->strength += part->nodes[i]->strength;
                part->modules[j]->last->next = part->nodes[i];
                part->nodes[i]->prev = part->modules[j]->last;
                part->modules[j]->last = part->nodes[i];
            }
            if(sep[0]=='\n')
                j++;
        }
    }

    CompressPartition(part);
    hdestroy();
    return nnode;
}
int main (int argc, char * argv[])
{
	int		i;
	ENTRY	entree;
	ENTRY *	trouve;

	if (argc < 2) {
		fprintf(stderr, "Syntaxe : %s [mois | jour]\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	/* 12 mois + 7 jours */
	if (hcreate(19) == 0) { 
		perror("hcreate");
		exit(EXIT_FAILURE);
	}
	ajoute_entree("janvier",   "january");
	ajoute_entree("fevrier",   "february");
	ajoute_entree("mars",      "march");
	ajoute_entree("avril",     "april");
	ajoute_entree("mai",       "may");
	ajoute_entree("juin",      "june");
	ajoute_entree("juillet",   "july");
	ajoute_entree("aout",      "august");
	ajoute_entree("septembre", "september");
	ajoute_entree("octobre",   "october");
	ajoute_entree("novembre",  "november");
	ajoute_entree("decembre",  "december");
	ajoute_entree("lundi",     "monday");
	ajoute_entree("mardi",     "tuesday");
	ajoute_entree("mercredi",  "wednesday");
	ajoute_entree("jeudi",     "thursday");
	ajoute_entree("vendredi",  "friday");
	ajoute_entree("samedi",    "satursday");
	ajoute_entree("dimanche",  "sunday");

	for (i = 1; i < argc; i ++) {
		entree.key = argv[i];
		fprintf(stdout, "%s -> ", argv[i]);
		trouve = hsearch(entree, FIND);
		if (trouve == NULL)
			fprintf(stdout, "pas dans la liste \n");
		else
			fprintf(stdout, "%s\n", (char *)trouve->data);
	}
	hdestroy();

	return EXIT_SUCCESS;
}
Exemplo n.º 18
0
Arquivo: hash.c Projeto: bsdcpp/mylib
int main(int argc, char* argv[])
{
    int i = 0;
    ENTRY e, *ep, *ep2;
    FILE *fp;
    char buf[MAXBUF];
    char num[15];

    hcreate(1);

    fp = Fopen("/home/jervis/csapp/tinyweb/data/kj20100602.txt", "r");

    memset(buf, 0, MAXBUF);
    while (Fgets(buf, 50, fp))
    {
        i++;
        if (i >100)
            break;
        memset(num, 0, sizeof(num));
        strncpy(num, buf, 3);
        e.key = num;
        printf("[%s][%d]\n", e.key, strlen(e.key));
        e.data = (void *)i;
        if ((ep = hsearch(e, FIND)) != NULL) {
            printf("第%d个[%s]与%d个[%s]重复\n", i, e.key, (int)(ep->data), ep->key);
        } else {
            printf("------------------------\n");
            printf("[%s][%d]\n\n", e.key, strlen(e.key));
            if ((ep2 = hsearch(e, ENTER)) != NULL) {
                /* printf("插入%s=>%d\n", ep2->key, (int)(ep2->data)); */
            } else {
                perror("table full");
                exit(EXIT_FAILURE);
            }
        }
    }
    printf("===================\n");
    e.key = "677";
    printf("[%s][%d]\n", e.key, strlen(e.key));
    if ((ep = hsearch(e, FIND)) != NULL) {
        printf("find %d => %s\n", (int)(ep->data), ep->key);
    }
    hdestroy();
    Fclose(fp);
    return 0;
}
Exemplo n.º 19
0
int main(int argc, char* argv[]){
    hcreate(100);
    ++argv, --argc;  /* skip over program name */

    if ( argc > 0 )
        yyin = fopen( argv[0], "r" );
    else
        yyin = stdin;
    do {
        yyparse();
    } while (!feof(yyin));

    printf("%s", outputFile);

    hdestroy();

    return EXIT_SUCCESS;
}
Exemplo n.º 20
0
int main(int argc, char *argv[]) {
    char        *word, *pEnd;
    int         word_count, i, nread;
    uint32_t    cmd_addr, flag;
    char        *gap = " \n";
    char        buff[BUFFSIZE];
    ENTRY       definition, *wp;
    pthread_t   receive_t;

    if (setupIO(argc, argv)) {
         return EXIT_FAILURE;
    }

    // if not given, use default filename
    if (namelen == 0) {
        strcpy(filename, "prufh");
        namelen = 5;
    }
    strcat(filename, ".defs");

    // open list of forth word addresses
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        fprintf(stderr, "Unable to open definitions file, %s\n", filename);
        return EXIT_FAILURE;
    }

    // get number of definitions from begining of file
    fgets (buff, BUFFSIZE, file );
    word_count = atoi(buff);

    // create hash for definition table
    hcreate(word_count);

    // fill hash with name-address pairs
    for (i=0; i<word_count;) {
        fgets(buff, BUFFSIZE, file);

        word = strtok(buff, gap);
        if (word != NULL) {
            definition.key = strdup(word);
            definition.data = (void*)strtol(strtok(NULL, gap), NULL, 0);

            wp = hsearch(definition, ENTER);

            if (wp == NULL) {
                fprintf(stderr, "Dictionary entry failed on \"%s\"\n", word);
                return EXIT_FAILURE;
            } else {
                if (!quiet_mode) 
                    printf("Saved %9.9s  as   %p\n", wp->key, wp->data); 
            }	    
            i++;
        }
    }
    fclose(file);

    if (pruInit(pru_num) == EXIT_SUCCESS) { 

        // start seperate thread to handle forth output
        if (pthread_create(&receive_t, NULL, receive, (void*) &outpipe)) {
        }

        // main loop, relay input to pru
        for(;;) {
            nread = read(0, buff, BUFFSIZE);  // wait here for input on stdin
            if (nread > 1) {
                word = strtok(buff, gap);

                // exit program on "bye" command
                if (strncmp(word, "bye", 3) == 0) break;

                // find address of word corresponding to input
                definition.key = word;
                wp = hsearch(definition, FIND);

                if (wp == NULL) {
                    // if input not defined, see if it is a number
                    cmd_addr = strtoul(word, &pEnd, 0);
                    if (pEnd == word) {
                        fprintf(stderr, "Unknown word, \"%s\"\n", word);
                        continue;
                    } else {
                        // if a number was input, signal forth to push it
                        flag = LIT_FLAG;
                        if (!quiet_mode) 
                            printf("Pushing %d\n", cmd_addr);
                    }
                } else {
                    // signal that a command address is being sent
                    flag = CMD_FLAG;
                    // retrieve the address
                    cmd_addr = (uint16_t)(intptr_t)(wp->data);
                    if (!quiet_mode) 
                        printf("Executing %9.9s %x\n", word, cmd_addr);
                }

                // send message to pruss
                if (exec(cmd_addr, flag)) {
                    fprintf(stderr, "Unable to issue command, \"%s\"\n", word);
                }
            }
        }
    }
    hdestroy();

    pthread_cancel(receive_t);
    pthread_join(receive_t, NULL);

    /* shutdown pru */
    prussdrv_pru_disable(pru_num);
    prussdrv_exit();

    if (outpipe != 1) {
        close(outpipe);
    }
    if (inpipe != 0) {
        close(inpipe);
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 21
0
/**
 * initializeScanRules
 *
 * this reads in the rules definition file for identifying the playload.
 * It compiles the regular
 * expressions and loads in the dynamic libraries as defined for later use
 *
 * @param scriptFile a file pointer to the rule definition file
 *
 */
gboolean
ycInitializeScanRules (
    FILE * scriptFile,
    GError ** err)
{
/*
// for every rule that is "imagined" can be returned on a single call to
   pcre_exec, you need to multiply that number by 6 for the correct number of
   "vector" entries (and because of pcre limitation should be a multiple of 3)
*/
#define NUM_SUBSTRING_VECTS 60
    const char         *errorString;
    int                 errorPos;

    char                eString[ESTRING_SIZE];
    pcre               *ruleScanner;
    pcre               *pluginScanner;
    pcre               *commentScanner;
    pcre               *pluginArgScanner;
    pcre               *signatureScanner;
    const char          commentScannerExp[] = "^\\s*#[^\\n]*\\n";
    const char          pluginScannerExp[] =
      "^[[:space:]]*label[[:space:]]+([[:digit:]]+)"
      "[[:space:]]+plugin[[:space:]]*([^[:space:]\\n].*)\\n";
    const char          ruleScannerExp[] =
      "^[[:space:]]*label[[:space:]]+([[:digit:]]+)"
      "[[:space:]]+regex[[:space:]]*([^\\n].*)\\n";
    const char          signatureScannerExp[] =
      "^[[:space:]]*label[[:space:]]+([[:digit:]]+)"
      "[[:space:]]+signature[[:space:]]*([^\\n].*)\\n";
    const char          pluginArgScannerExp[] = "[[:word:]]";
    int                 rc;
    int                 substringVects[NUM_SUBSTRING_VECTS];
    char                lineBuffer[LINE_BUF_SIZE];
    int                 readLength;
    char               *captString;
    unsigned int        bufferOffset = 0;
    int                 currentStartPos = 0;
    int                 loop;
    char                *ltdl_lib_path = NULL;

    /* first mark all plugin entries as empty, just in case */
    for (loop = 0; loop < MAX_PAYLOAD_RULES; loop++) {
        ruleTable[loop].ruleType = EMPTY;
    }

    /* initialize the hash table */
    ycPortHashInitialize();


    /* initialize the dynamic loader library */
    rc = lt_dlinit();
    if (0 != rc) {
        *err = g_error_new (YAF_ERROR_DOMAIN, YAF_ERROR_IMPL,
                     "error initializing the dynamic loader library: \"%s\"",
                     lt_dlerror ());
        return FALSE;
    }
    /* if LTDL_LIBRARY_PATH is set - add this one first */
    ltdl_lib_path = getenv("LTDL_LIBRARY_PATH");
    if (ltdl_lib_path) {
        lt_dladdsearchdir(ltdl_lib_path);
    }

#ifdef YAF_APPLABEL_PATH
    /* add the applabel path based on libdir at build time */
    lt_dladdsearchdir(YAF_APPLABEL_PATH);
#else
    /* add /usr/local/lib/yaf to path since libtool can never find it */

    lt_dladdsearchdir(YAF_SEARCH_PATH);
    lt_dladdsearchdir(ALT_SEARCH_PATH);
    lt_dladdsearchdir(ALT_SEARCH_PATH64);
#endif
    /* create the hash table for library modules to library handle names */
    if (!hcreate ((MAX_PAYLOAD_RULES * 20) / 100)) {
        *err = g_error_new (YAF_ERROR_DOMAIN, YAF_ERROR_IMPL,
                     "couldn't create load module hash table (%d)", errno);
        return FALSE;
    }


    /*
     * take all of the rules needed to parse the rule file and compile
     * them into a form that // the regular expression engine can deal with */
    ruleScanner = pcre_compile(ruleScannerExp, PCRE_MULTILINE, &errorString,
                               &errorPos, NULL);
    if (NULL == ruleScanner) {
        ycDisplayScannerRuleError(eString, ESTRING_SIZE,
                                  "couldn't build the rule scanner",
                                  errorString, ruleScannerExp, errorPos);
        *err = g_error_new(YAF_ERROR_DOMAIN,YAF_ERROR_INTERNAL, "%s", eString);
        return FALSE;
    }

    pluginScanner = pcre_compile(pluginScannerExp, PCRE_MULTILINE,
                                 &errorString, &errorPos, NULL);
    if (NULL == pluginScanner) {
        ycDisplayScannerRuleError(eString, ESTRING_SIZE,
                                  "couldn't build the plugin scanner",
                                  errorString, pluginScannerExp, errorPos);
        *err = g_error_new(YAF_ERROR_DOMAIN,YAF_ERROR_INTERNAL, "%s", eString);
        return FALSE;
    }

    commentScanner = pcre_compile(commentScannerExp, PCRE_MULTILINE,
                                  &errorString, &errorPos, NULL);
    if (NULL == commentScanner) {
        ycDisplayScannerRuleError (eString, ESTRING_SIZE,
                                   "couldn't build the comment scanner",
                                   errorString, commentScannerExp, errorPos);
        *err = g_error_new(YAF_ERROR_DOMAIN,YAF_ERROR_INTERNAL, "%s", eString);
        return FALSE;
    }

    pluginArgScanner = pcre_compile(pluginArgScannerExp, PCRE_MULTILINE,
                                    &errorString, &errorPos, NULL);
    if (NULL == pluginArgScanner) {
        ycDisplayScannerRuleError(eString, ESTRING_SIZE,
                                  "couldn't build the plugin argument scanner",
                                  errorString, pluginArgScannerExp, errorPos);
        *err = g_error_new(YAF_ERROR_DOMAIN,YAF_ERROR_INTERNAL, "%s", eString);
        return FALSE;
    }

    signatureScanner = pcre_compile(signatureScannerExp, PCRE_MULTILINE,
                                    &errorString, &errorPos, NULL);
    if (NULL == signatureScanner) {
        ycDisplayScannerRuleError (eString, ESTRING_SIZE,
                       "couldn't build the signature scanner",
                       errorString, signatureScannerExp, errorPos);
        *err = g_error_new(YAF_ERROR_DOMAIN,YAF_ERROR_INTERNAL, "%s", eString);
        return FALSE;
    }

    /*
     * this is the loop that does the lion's share of the rule file
     * processing first read a hunk of the rule file, (this may include
     * multiple lines of stuff) this gets a little bit ugly, there are a
     * number of issues that have to handled; first, because there may be
     * multiple lines (which is in fact likely) it has to be able to work
     * its way through the buffer, a single pass of the buffer through the
     * pcre engine simply won't cut it; at the end, it is possible // to have
     * part of line, when this happens, it needs to copy the leftover part
     * of the read into the front of the buffer, and then read again to fill in
     * the rest of line.  (this detail limits a single line to
     * LINE_BUF_SIZE size) */
    do {
        readLength =
          fread (lineBuffer + bufferOffset, 1, LINE_BUF_SIZE - 1 -bufferOffset,
                 scriptFile);
        if (0 == readLength) {
            if (ferror (scriptFile)) {
                *err = g_error_new(YAF_ERROR_DOMAIN, YAF_ERROR_IO,
                                   "couldn't read the rule file: %s",
                                   strerror (errno));
                return FALSE;
            }
            break;
        }

        /* fread only returns how much it read from the file - need to add
           extra we put in the buffer from last read, if any */

        readLength += bufferOffset;

        /*
         * substringVects is used by the pcre library to indicate where the
         * matched substrings are in the input string, but [1] points to
         * the very end of the total match, we use this to iterate through
         * the readBuffer, always reset it after a read */
        substringVects[0] = 0;
        substringVects[1] = 0;

        /* parse as much of the input buffer as possible */
        while (substringVects[1] < readLength) {

#if YFDEBUG_APPLABEL
            g_debug("readLength %d startPosition %d\n", readLength,
                    substringVects[1]);
            for (loop=0; loop < 10; loop++) {
                if (loop+substringVects[1] > readLength) {
                    break;
                }
                char curChar = *(lineBuffer + substringVects[1] + loop);
                if (iscntrl(curChar)) {
                    g_debug(".");
                    continue;
                }
                if (isprint(curChar)) {
                    g_debug("%c", curChar);
                } else {
                    g_debug(".");
                }
            }
            g_debug("\n");
#endif
            /* get rid of CR's and LF's at the begging, use the simple manual
             * method, they gum up the regex works */
            if ('\n' == *(lineBuffer + substringVects[1])
                || '\r' == *(lineBuffer + substringVects[1])) {
                substringVects[1]++;
                continue;
            }

            /* first check for comments, and eliminate them */
            currentStartPos = substringVects[1];
            /* need to store the current offset, if we fail to match, we
               get -1 in [1] */
            rc = pcre_exec (commentScanner, NULL, lineBuffer, readLength,
                            substringVects[1], PCRE_ANCHORED, substringVects,
                            NUM_SUBSTRING_VECTS);
            if (rc > 0) {
#if YFDEBUG_APPLABEL
                g_debug("comment match pos %d to pos %d\n",
                    substringVects[0], substringVects[1]);
                pcre_get_substring(lineBuffer, substringVects, rc, 0,
                    (const char**)&captString);
                g_debug("comment line is \"%s\"\n", captString);
                pcre_free(captString);
#endif
                continue;
            }
            substringVects[1] = currentStartPos;

            /* scan the line to see if it is a regex statement, and get the
             * arguments if it is */
            rc = pcre_exec (ruleScanner, NULL, lineBuffer, readLength,
                            substringVects[1], PCRE_ANCHORED, substringVects,
                            NUM_SUBSTRING_VECTS);
            if (rc > 0) {
                pcre               *newRule;
                pcre_extra         *newExtra;

                /* get the first matched field from the regex rule expression
                 * (the label value) */
                pcre_get_substring (lineBuffer, substringVects, rc, 1,
                                    (const char **) &captString);
                ruleTable[numPayloadRules].payloadLabelValue =
                  strtoul (captString, NULL, 10);
#if YFDEBUG_APPLABEL
                g_debug("regex: rule # %u, label value %lu ",
                        numPayloadRules, strtoul(captString, NULL, 10));
#endif
                pcre_free (captString);

                /* get the second matched field from the regex rule expression
                 * (should be the regex) */

                pcre_get_substring(lineBuffer, substringVects, rc, 2,
                                   (const char **) &captString);
#if YF_DEBUG_APPLABEL
                g_debug(" regex \"%s\"\n", captString);
#endif
                newRule = pcre_compile(captString, 0, &errorString, &errorPos,
                                       NULL);
                if (NULL == newRule) {
                    ycDisplayScannerRuleError(eString, ESTRING_SIZE,
                                     "error in regex application labeler rule",
                                              errorString, captString,
                                              errorPos);

                } else {
                    newExtra = pcre_study (newRule, 0, &errorString);
                    ruleTable[numPayloadRules].ruleArgs.regexFields.
                      scannerExpression = newRule;
                    ruleTable[numPayloadRules].ruleArgs.regexFields.
                      scannerExtra = newExtra;
                    ruleTable[numPayloadRules].ruleType = REGEX;
                    ycPortHashInsert(ruleTable[numPayloadRules].payloadLabelValue, numPayloadRules);
                    numPayloadRules++;
                }
                pcre_free (captString);

                if (MAX_PAYLOAD_RULES == numPayloadRules) {
                    *err = g_error_new (YAF_ERROR_DOMAIN, YAF_ERROR_LIMIT,
                                        "maximum number of application labeler"
                                        " rules has been reached");
                    return FALSE;
                }

                continue;
            }
            substringVects[1] = currentStartPos;
            /* scan the line to see if it is a plugin statement, and handle the
             * arguments if it is */
            rc = pcre_exec (pluginScanner, NULL, lineBuffer, readLength,
                            substringVects[1], PCRE_ANCHORED, substringVects,
                            NUM_SUBSTRING_VECTS);
            if (rc > 0) {
                int                 numArgs;
                char             **argStrings;

                /* get the first matched field from the regex rule expression
                 * (the lable value) */
                pcre_get_substring (lineBuffer, substringVects, rc, 1,
                                    (const char **) &captString);
                ruleTable[numPayloadRules].payloadLabelValue =
                  strtoul (captString, NULL, 10);
#if YFDEBUG_APPLABEL
                g_debug("plugin: rule # %u, label value %lu ",
                        numPayloadRules, strtoul(captString, NULL, 10));
#endif
                pcre_free (captString);

                /*
                 * get the second matched field, which should be the plugin
                 * name and all of its arguments, now we need to chunk that
                 * into an array of strings, ala argc, argv
                 */
                pcre_get_substring(lineBuffer, substringVects, rc, 2,
                                   (const char **) &captString);
                ycChunkString(captString, &numArgs, &argStrings);

                if (numArgs < 2) {
                    g_critical("error: not enough arguments to load and call "
                               "a plugin, at least a library name and function"
                               " name are needed\n");
                    pcre_free(captString);
                    pcre_get_substring(lineBuffer, substringVects, rc, 0,
                                       (const char **) &captString);
                    g_critical("input line: \"%s\"\n", captString);
                } else {
                    ENTRY               newItem;
                    ENTRY              *foundItem;
                    lt_dlhandle         modHandle;
                    lt_ptr              funcPtr;

                    ruleTable[numPayloadRules].ruleType = PLUGIN;
                    ruleTable[numPayloadRules].ruleArgs.pluginArgs.numArgs =
                      numArgs;
                    ruleTable[numPayloadRules].ruleArgs.pluginArgs.pluginArgs =
                      argStrings;
                    newItem.key = strdup(argStrings[0]);
                    if (NULL == newItem.key) {
                        g_error("out of memory error\n");
                        for (loop = 0; loop < numArgs; loop++) {
                            free ((char *) (argStrings[loop]));
                        }
                        free(argStrings);
                        return FALSE;
                    }
                    newItem.data = NULL;
                    foundItem = hsearch(newItem, FIND);
                    if (NULL == foundItem) {

                        modHandle = lt_dlopenext(newItem.key);
                        if (NULL == modHandle) {
                            g_critical("Couldn't open library \"%s\": %s",
                                       argStrings[0], lt_dlerror());
                            g_critical("Search path set to %s",
                                       lt_dlgetsearchpath());
                            g_critical("Set LTDL_LIBRARY_PATH to correct"
                                       " location.");
                            for (loop = 0; loop < numArgs; loop++) {
                                free((char *) (argStrings[loop]));
                            }
                            free(argStrings);
                            pcre_free(captString);
                            continue;
                        } else {
#if YFDEBUG_APPLABEL
                            const lt_dlinfo *info = lt_dlgetinfo(modHandle);
                            g_debug("Loading %s plugin from %s", info->name, info->filename);
#endif
                        }
                        newItem.data = (void *)modHandle;
                        hsearch(newItem, ENTER);
                    } else {
                        modHandle = (lt_dlhandle)foundItem->data;
                    }

                    funcPtr = lt_dlsym(modHandle, argStrings[1]);
                    if (NULL == funcPtr) {
                        g_critical("couldn't find function \"%s\" in library"
                                   " \"%s\"\n", argStrings[1], argStrings[0]);
                        for (loop = 0; loop < numArgs; loop++) {
                            free ((char *) (argStrings[loop]));
                        }
                        free (argStrings);
                        pcre_free (captString);
                        continue;
                    }
                    ruleTable[numPayloadRules].ruleArgs.pluginArgs.func =
                        (ycScannerPlugin_fn) funcPtr;

                    ycPortHashInsert(ruleTable[numPayloadRules].payloadLabelValue, numPayloadRules);
                    numPayloadRules++;
                }

                pcre_free(captString);

                if (MAX_PAYLOAD_RULES == numPayloadRules) {
                    g_warning ("maximum number of rules has been reached\n");
                    return TRUE;
                }
                continue;
            }


        substringVects[1] = currentStartPos;

        /* scan the line to see if it is a signature, and get the
         * arguments if it is */
        rc = pcre_exec(signatureScanner, NULL, lineBuffer, readLength,
                       substringVects[1], PCRE_ANCHORED, substringVects,
                       NUM_SUBSTRING_VECTS);
        if (rc > 0) {
            pcre               *newRule;
            pcre_extra         *newExtra;

            /* get the first matched field from the regex rule expression
             * (the label value) */
            pcre_get_substring(lineBuffer, substringVects, rc, 1,
                               (const char **) &captString);

            sigTable[numSigRules].payloadLabelValue = strtoul(captString, NULL,
                                                              10);
#if YFDEBUG_APPLABEL
            g_debug("signature: rule # %u, label value %lu ",
                    numSigRules, strtoul(captString, NULL, 10));
#endif
            pcre_free (captString);

            /* get the second matched field from the regex rule expression
             * (should be the regex) */
            pcre_get_substring(lineBuffer, substringVects, rc, 2,
                               (const char **) &captString);
#if YFDEBUG_APPLABEL
            g_debug(" signature \"%s\"\n", captString);
#endif
            newRule = pcre_compile(captString, 0, &errorString, &errorPos,
                                   NULL);
            if (NULL == newRule) {
                ycDisplayScannerRuleError (eString, ESTRING_SIZE,
                                           "error in signature application "
                                           "labeler rule", errorString,
                                           captString, errorPos);

            } else {
                newExtra = pcre_study (newRule, 0, &errorString);
                sigTable[numSigRules].ruleArgs.regexFields.
                    scannerExpression = newRule;
                sigTable[numSigRules].ruleArgs.regexFields.
                    scannerExtra = newExtra;
                sigTable[numSigRules].ruleType = SIGNATURE;
                numSigRules++;
            }

            pcre_free(captString);

            if (MAX_PAYLOAD_RULES == numSigRules) {
                *err = g_error_new(YAF_ERROR_DOMAIN, YAF_ERROR_LIMIT,
                                   "maximum number of signature rules has "
                                   "been reached");
                return FALSE;
            }

            continue;
        }

        substringVects[1] = currentStartPos;


        /*   pcre_free (captString);*/

#if YFDEBUG_APPLABEL
        g_debug("plugin args: ");
        for (loop = 0; loop < numArgs; loop++) {
            g_debug("\"%s\" ", (*argStrings)[loop]);
        }
        g_debug("\n");
#endif

        /*
         * check to see if we have partial text left over at the end of
         * the read buffer, if we copy it to the front of the read
         * buffer, and on the next read, read a little less to
         * compensate for the left over amount */
        if ((PCRE_ERROR_NOMATCH == rc) && (substringVects[1] < readLength)
            && !feof (scriptFile)) {
            memmove (lineBuffer, lineBuffer + substringVects[1],
                     readLength - substringVects[1]);
            bufferOffset = readLength - substringVects[1];
            break;
        } else if (PCRE_ERROR_NOMATCH == rc && feof (scriptFile)) {
            /* this is an error, we have crap left over at the end of the
             * file that we can't parse! */
            g_critical("unparsed text at the end of the application labeler"
                       " rule file!\n");
            break;
        }
        }

    } while (!ferror (scriptFile) && !feof (scriptFile));

    /*
     * get rid of the module handle lookup hash; this creates a mem leak of
     * the module handles, they can't be freed any longer (although this is a
     * crappy hash, and iterating the hash is not possible....) */
    hdestroy();

    g_debug("Application Labeler accepted %d rules.", numPayloadRules);
    g_debug("Application Labeler accepted %d signatures.", numSigRules);
    pcre_free(ruleScanner);
    pcre_free(pluginScanner);
    pcre_free(commentScanner);
    pcre_free(pluginArgScanner);
    pcre_free(signatureScanner);

    /* debug */
    return TRUE;
}
Exemplo n.º 22
0
Arquivo: main.c Projeto: runt18/bap
int
main(int argc, char **argv)
{
	int ch;
	int rc = 0;
	struct rule *r;
	fn_list *pre_input = NULL;
  
#ifdef YYDEBUG
	extern int yydebug;

	yydebug = 0;
#endif
	hcreate(MAXRULE);

	while ((ch = getopt(argc, argv, "cdi:kntqS:")) != -1) {
		switch (ch) {
		case 'c':
			cflag++;
			break;

		case 'd':
#ifdef YYDEBUG
			yydebug = 1;
#else
			fprintf(stderr, "Rebuild with -DYYDEBUG to use -d.\n");
#endif
			break;

		case 'k':
			c2flag++;
			break;

		case 'n':
			canon = 0;
			break;

		case 'i': {
			fn_list *ifile = calloc(sizeof(fn_list), 1);
			ifile->filename = optarg;
			ifile->next = pre_input;
			pre_input = ifile;
			break;
		}
      
		case 't':
			tflag++;
			break;

		case 'p':
			permissive = 0;
			break;

		case 'q':
			qflag++;
			break;

		case 'S': 
			top_rule_name = optarg;
			break;
      
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc > 1)
		usage();

	predefine(pre_input);    
  
	/* Parse the grammar, perhaps spouting errors. */
	parse_from((argc > 0)? argv[0] : NULL);

	/* If we're not quiet, then output the grammar again. */
	if (!qflag) {
		if (canon)
			canonify(rules);
		for (r = rules; r; r = r->next) {
			if (r->predefined) {
				/* do not output */
			}
			else if (r->rule) {
				printf("%s = ", r->name);
				printobj(r->rule, tflag);
				if (cflag)
					printf(" ; line %d", r->line);
				printf("\n");
			} else {
				printf("; %s UNDEFINED\n", r->name);
			}
			if (r->next == rules)
				break;
		}
		for (r = rules; r; r = r->next) {
			if (r->used == 0 
				&& r->predefined == 0 
				&& r->rule 
				&& strcmp(r->name, top_rule_name))
				printf("; %s defined but not used\n", r->name);
			if (r->next == rules)
				break;
		}
	}
  
	rc = summary();
	hdestroy();
	exit(rc);
}
Exemplo n.º 23
0
/*
 *  stress_hsearch()
 *	stress hsearch
 */
int stress_hsearch(
	uint64_t *const counter,
	const uint32_t instance,
	const uint64_t max_ops,
	const char *name)
{
	size_t i, max = (size_t)opt_hsearch_size;
	int ret = EXIT_FAILURE;
	char **keys;

	(void)instance;

	if (!set_hsearch_size) {
		if (opt_flags & OPT_FLAGS_MAXIMIZE)
			opt_hsearch_size = MAX_HSEARCH_SIZE;
		if (opt_flags & OPT_FLAGS_MINIMIZE)
			opt_hsearch_size = MIN_HSEARCH_SIZE;
	}

	max = (size_t)opt_hsearch_size;

	/* Make hash table with 25% slack */
	if (!hcreate(max + (max / 4))) {
		pr_failed_err(name, "hcreate");
		return EXIT_FAILURE;
	}

	if ((keys = calloc(max, sizeof(char *))) == NULL) {
		pr_err(stderr, "%s: cannot allocate keys\n", name);
		goto free_hash;
	}

	/* Populate hash, make it 100% full for worst performance */
	for (i = 0; i < max; i++) {
		char buffer[32];
		ENTRY e;

		snprintf(buffer, sizeof(buffer), "%zu", i);
		keys[i] = strdup(buffer);
		if (!keys[i]) {
			pr_err(stderr, "%s: cannot allocate key\n", name);
			goto free_all;
		}

		e.key = keys[i];
		e.data = (void *)i;

		if (hsearch(e, ENTER) == NULL) {
			pr_err(stderr, "%s: cannot allocate new hash item\n", name);
			goto free_all;
		}
	}

	do {
		for (i = 0; opt_do_run && i < max; i++) {
			ENTRY e, *ep;

			e.key = keys[i];
			e.data = NULL;	/* Keep Coverity quiet */
			ep = hsearch(e, FIND);
			if (opt_flags & OPT_FLAGS_VERIFY) {
				if (ep == NULL) {
					pr_fail(stderr, "%s: cannot find key %s\n", name, keys[i]);
				} else {
					if (i != (size_t)ep->data) {
						pr_fail(stderr, "%s: hash returned incorrect data %zd\n", name, i);
					}
				}
			}
		}
		(*counter)++;
	} while (opt_do_run && (!max_ops || *counter < max_ops));

	ret = EXIT_SUCCESS;

free_all:
	for (i = 0; i < max; i++)
		free(keys[i]);
	free(keys);
free_hash:
	hdestroy();

	return ret;
}
Exemplo n.º 24
0
extern DB *
__hash_open(const char *file, int flags, int mode, const HASHINFO *info, int dflags)
{
	HTAB *hashp=NULL;
	struct stat statbuf;
	DB *dbp;
	int bpages, hdrsize, new_table, nsegs, save_errno;

	if ((flags & O_ACCMODE) == O_WRONLY) {
		errno = EINVAL;
		return NULL;
	}

	/* zero the statbuffer so that
	 * we can check it for a non-zero
	 * date to see if stat succeeded
	 */
	memset(&statbuf, 0, sizeof(struct stat));

	if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB)))) {
		errno = ENOMEM;
		return NULL;
	}
	hashp->fp = NO_FILE;
	if(file)
		hashp->filename = strdup(file);

	/*
	 * Even if user wants write only, we need to be able to read
	 * the actual file, so we need to open it read/write. But, the
	 * field in the hashp structure needs to be accurate so that
	 * we can check accesses.
	 */
	hashp->flags = flags;

	new_table = 0;
	if (!file || (flags & O_TRUNC) 	|| (stat(file, &statbuf)  && (errno == ENOENT))) 
	{
		if (errno == ENOENT)
			errno = 0; /* Just in case someone looks at errno */
		new_table = 1;
	}
	else if(statbuf.st_mtime && statbuf.st_size == 0)
	{
		/* check for a zero length file and delete it
	 	 * if it exists
	 	 */
		new_table = 1;
	}
	hashp->file_size = statbuf.st_size;

	if (file) {				 
#if defined(_WIN32) || defined(_WINDOWS) || defined (macintosh)  || defined(XP_OS2)
		if ((hashp->fp = DBFILE_OPEN(file, flags | O_BINARY, mode)) == -1)
			RETURN_ERROR(errno, error1);
#else
		if ((hashp->fp = open(file, flags, mode)) == -1)
			RETURN_ERROR(errno, error1);
		(void)fcntl(hashp->fp, F_SETFD, 1);
#endif
	}
	if (new_table) {
		if (!init_hash(hashp, file, (HASHINFO *)info))
			RETURN_ERROR(errno, error1);
	} else {
		/* Table already exists */
		if (info && info->hash)
			hashp->hash = info->hash;
		else
			hashp->hash = __default_hash;

		hdrsize = read(hashp->fp, (char *)&hashp->hdr, sizeof(HASHHDR));
		if (hdrsize == -1)
			RETURN_ERROR(errno, error1);
		if (hdrsize != sizeof(HASHHDR))
			RETURN_ERROR(EFTYPE, error1);
#if BYTE_ORDER == LITTLE_ENDIAN
		swap_header(hashp);
#endif
		/* Verify file type, versions and hash function */
		if (hashp->MAGIC != HASHMAGIC)
			RETURN_ERROR(EFTYPE, error1);
#define	OLDHASHVERSION	1
		if (hashp->VERSION != HASHVERSION &&
		    hashp->VERSION != OLDHASHVERSION)
			RETURN_ERROR(EFTYPE, error1);
		if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
			RETURN_ERROR(EFTYPE, error1);
		if (hashp->NKEYS < 0) /* Old bad database. */
			RETURN_ERROR(EFTYPE, error1);

		/*
		 * Figure out how many segments we need.  Max_Bucket is the
		 * maximum bucket number, so the number of buckets is
		 * max_bucket + 1.
		 */
		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
			 hashp->SGSIZE;
		hashp->nsegs = 0;
		if (alloc_segs(hashp, nsegs))
			/* If alloc_segs fails, errno will have been set.  */
			RETURN_ERROR(errno, error1);
		/* Read in bitmaps */
		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
		    (hashp->BSIZE << BYTE_SHIFT) - 1) >>
		    (hashp->BSHIFT + BYTE_SHIFT);

		hashp->nmaps = bpages;
		(void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32 *));
	}

	/* Initialize Buffer Manager */
	if (info && info->cachesize)
		__buf_init(hashp, (int32) info->cachesize);
	else
		__buf_init(hashp, DEF_BUFSIZE);

	hashp->new_file = new_table;
#ifdef macintosh
	hashp->save_file = file && !(hashp->flags & O_RDONLY);
#else
	hashp->save_file = file && (hashp->flags & O_RDWR);
#endif
	hashp->cbucket = -1;
	if (!(dbp = (DB *)malloc(sizeof(DB)))) {
		RETURN_ERROR(ENOMEM, error1);
	}
	dbp->internal = hashp;
	dbp->close = hash_close;
	dbp->del = hash_delete;
	dbp->fd = hash_fd;
	dbp->get = hash_get;
	dbp->put = hash_put;
	dbp->seq = hash_seq;
	dbp->sync = hash_sync;
	dbp->type = DB_HASH;

#ifdef HASH_STATISTICS
	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
#endif
	return (dbp);

error1:
	hdestroy(hashp);
	errno = save_errno;
	return (NULL);
}
Exemplo n.º 25
0
int main ( int argc , char **argv )
{
  FILE *wikipedia_ngram = NULL;
  FILE entities = NULL;
  
  char *line = NULL;
  char *file_name = NULL;
  char *word = NULL;
  
  size_t len = 0;
  ssize_t read;
  //Defining the hash variables
  ENTRY e, *ep;
  unsigned long int lines_ngram = 0; //number of lines in the n-gram file
  unsigned long iterator = 0;
  
  wikipedia_ngram = fopen ( argv [ 1 ] , "r" );
  if ( wikipedia_ngram == NULL )
  {
    fprintf ( stderr , "Wikipedia n-gram file open error\n" );
    return ( EXIT_FAILURE );
  }
  
  entities = fopen ( argv [ 2 ] , "r" );
  if ( entities == NULL )
  {
    fprintf ( stderr , "Entities file open error\n" );
    return ( EXIT_FAILURE );
  }
  
  file_name = ( char * ) malloc ( 5000 * sizeof ( char ) );
  if ( file_name == NULL )
  {
    fprintf ( stderr , "malloc() memory allocation failure in file_name\n" );
    return ( EXIT_FAILURE );
  }
  
  word = ( char * ) malloc ( 1000 * sizeof ( char ) );
  if ( word == NULL )
  {
    fprintf ( stderr , "malloc() memory allocation failure in word\n" );
    return ( EXIT_FAILURE );
  }
    
  while ( ( read = getline ( &line , &len , wikipedia_ngram ) ) != -1 )
  {
    lines_ngram ++;
  }
  rewind ( wikipedia_ngram );
  //got the number of lines above
  //create the hash table now.
  
  hcreate ( lines_ngram );
  
  for ( iterator = 0; iterator < lines_ngram; iterator++ )
  {
    fscanf ( wikipedia_ngram , "%s %s\n" , file_name , word );
    e.key = word;
    e.data = (char *) file_name;
    ep = hsearch ( e , ENTER );
    /* there should be no failures */
    if (ep == NULL)
    {
      fprintf(stderr, "Entry failed\n");
      exit ( EXIT_FAILURE );
    }
    memset ( file_name , 0 , 5000 );
    memset ( word , 0 , 1000 );
  }
  
  //find the entities in the hash table.
  while ( !feof ( entities ) )
  {
    fscanf ( entities , "%s\n" , word );
    e.key = word;
    ep = hsearch(e, FIND);
    printf ("%s\n" , ( char ) ( ep->data ) );
  }
  
  if ( line )
  {
    free ( line );
  }
  fclose ( wikipedia_ngram );
  fclose ( entities );
  free ( file_name );
  free ( word );
  hdestroy();
  return ( EXIT_SUCCESS );
}
Exemplo n.º 26
0
/** Destroys the global hash table.
 */
void destroy_hash_table()
{
	hdestroy();
}
Exemplo n.º 27
0
/*
 * Just a wrapper to destory the hashtable.  At some point in the future we
 * might want to do something more....  For instance, verify that the cfg
 * database and the kernel configuration match (?)  Just an idea.
 */
static void
destroy_hashtable()
{
	hdestroy();
}
Exemplo n.º 28
0
void lecture(int recursive_load, TxDonneesFenetre *onglet_leto)
{
  int i;
  type_groupe *groupe;
  type_liaison * liaison;
  FILE *f1;
  int nbre_liaison_provisoire;
  int reverse, selected_plane;
  char *pt;

  static char ligne[TAILLE_CHAINE];

#ifndef AVEUGLE
  int j;
  remove_hash_table(onglet_leto->hashtab);
  init_hash_table(onglet_leto->hashtab);
#else
  hdestroy(); /* on detruit la table precedente si elle existait */
  hcreate(10000); /* table de hachage pour les no de groupes symboliques */
#endif
  nbre_groupes_lus = 0; /* on initialise le nombre de groupes lus */

  /* on place le flag_symb a 1 si le fichier est un .symb
   * (en esperant que l'utilisateur ne met pas de variable dans un .script !) */
  if ((pt = strstr(sc->nomfich1, SYMBOLIQUE_EXTENSION)) != NULL) sc->flag_symb = 1;
  else sc->flag_symb = 0;

  f1 = fopen(sc->nomfich1, "r");

  if (f1 == NULL)
  {
    printf("Cannot open file %s\n", sc->nomfich1);
    printf("We suppose it is a new script file \n");
    return;
  }

  liaison = sc->deb_liaison = sc->fin_liaison = NULL;
  groupe = sc->deb_groupe = sc->fin_groupe = NULL;

  sc->nbre_neurone = 0;
  sc->nbre_liaison = 0;
  sc->last_groupe_number = 0;
  sc->first_comment_group = (type_noeud_comment *) read_line_with_comment(f1, NULL, ligne);

  sscanf(ligne, "nombre de groupes = %d\n", &sc->nbre_groupe);
  printf("Nombre de groupe = %d\n",sc->nbre_groupe);
  if (sc->first_comment_group != NULL && strstr(sc->first_comment_group->chaine, "!ignore_include") != NULL)
  {

    if (recursive_load != 0)
    {
      recursive_load = 0;
    }
  }

  sc->infos_xyz=MANY_ALLOCATIONS(1000,char*);
  for(i=0;i<1000;i++)
  {
    sc->infos_xyz[i]=NULL;
  }


  for (i = 0; i < sc->nbre_groupe; i++)
  {
    if (i != 0) sc->fin_groupe = groupe = creer_groupeb(sc->fin_groupe);
    else groupe = sc->deb_groupe = sc->fin_groupe = creer_groupeb(NULL);

    sc->nbre_neurone += read_one_group_leto(f1, groupe, NULL, onglet_leto->hashtab,&(sc->infos_xyz[i]));

    /* gestion de la lecture d'un sous reseau */
    if (groupe->type == No_Sub_Network && recursive_load == 1)
    {
      /* le nbre de groupes a ete modifie dans read_macro */
      i = i + read_macro(groupe->no_name, groupe->nom, groupe->posx, groupe->posy, 1, 1, &selected_plane, onglet_leto->hashtab);
      if (groupe->reverse > 0) reverse = 1;
      else reverse = -1;
      groupe->reverse = reverse * selected_plane; /* plan >100 pour tout bouger ensemble */
      PRINT_WARNING("Les densites perso sont incompatible avec les macro-scripts pour le moment !\n");
    }

    groupe->deja_active = 0; /* c'est un groupe en direct de ce script, non un groupe insere */
  }

  sc->nbre_groupes_lus = nbre_groupes_lus = sc->nbre_groupe;

  sc->first_comment_link = (type_noeud_comment *) read_line_with_comment(f1, NULL, ligne);

  sscanf(ligne, "nombre de liaisons = %d\n", &nbre_liaison_provisoire);
  liaison = sc->fin_liaison;

  for (i = 0; i < nbre_liaison_provisoire; i++)
  {
    if (sc->deb_liaison == NULL)
    {
      liaison = sc->deb_liaison = sc->fin_liaison = (type_liaison *) creer_liaison(NULL);
    }
    else liaison = (type_liaison *) creer_liaison(liaison);

    if (onglet_leto == NULL) read_one_link(f1, liaison, NULL, NULL);
    else read_one_link(f1, liaison, NULL, onglet_leto->hashtab);

    liaison->deja_active = 0; /* liaison propre au script */
  }

  sc->nbre_liaison = sc->nbre_liaison + nbre_liaison_provisoire; /* tenir compte des scripts inclus */
  sc->fin_liaison = liaison;
  fclose(f1);

  initialise_liaisons();

#ifndef AVEUGLE
  j = script_load_file_xml(sc->draw);
  if (j == 1)
  {
    fprintf(stderr, "pb chargement fichier .draw (fichier introuvbale ou non defini) \n");
  }
  else if (j == -1)
  {
    fprintf(stderr, "pb chargement fichier draw: no liaisons found\n");
  }

  if (sc->premiere_lecture == 0 && onglet_leto->window != NULL) regenerer_test(onglet_leto);
  script_backup(sc);
#endif
  sc->premiere_lecture = 0;

}
Exemplo n.º 29
0
/* ARGSUSED */
DB *
__hash_open(const char *file, int flags, int mode,
    const HASHINFO *info,	/* Special directives for create */
    int dflags)
{
	HTAB *hashp;
	struct stat statbuf;
	DB *dbp;
	int bpages, hdrsize, new_table, nsegs, save_errno;

	if ((flags & O_ACCMODE) == O_WRONLY) {
		errno = EINVAL;
		return (NULL);
	}

	if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
		return (NULL);
	hashp->fp = -1;

	/*
	 * Even if user wants write only, we need to be able to read
	 * the actual file, so we need to open it read/write. But, the
	 * field in the hashp structure needs to be accurate so that
	 * we can check accesses.
	 */
	hashp->flags = flags;

	if (file) {
		if ((hashp->fp = _open(file, flags | O_CLOEXEC, mode)) == -1)
			RETURN_ERROR(errno, error0);
		new_table = _fstat(hashp->fp, &statbuf) == 0 &&
		    statbuf.st_size == 0 && (flags & O_ACCMODE) != O_RDONLY;
	} else
		new_table = 1;

	if (new_table) {
		if (!(hashp = init_hash(hashp, file, info)))
			RETURN_ERROR(errno, error1);
	} else {
		/* Table already exists */
		if (info && info->hash)
			hashp->hash = info->hash;
		else
			hashp->hash = __default_hash;

		hdrsize = _read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
#if BYTE_ORDER == LITTLE_ENDIAN
		swap_header(hashp);
#endif
		if (hdrsize == -1)
			RETURN_ERROR(errno, error1);
		if (hdrsize != sizeof(HASHHDR))
			RETURN_ERROR(EFTYPE, error1);
		/* Verify file type, versions and hash function */
		if (hashp->MAGIC != HASHMAGIC)
			RETURN_ERROR(EFTYPE, error1);
#define	OLDHASHVERSION	1
		if (hashp->VERSION != HASHVERSION &&
		    hashp->VERSION != OLDHASHVERSION)
			RETURN_ERROR(EFTYPE, error1);
		if ((int32_t)hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
			RETURN_ERROR(EFTYPE, error1);
		/*
		 * Figure out how many segments we need.  Max_Bucket is the
		 * maximum bucket number, so the number of buckets is
		 * max_bucket + 1.
		 */
		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
			 hashp->SGSIZE;
		if (alloc_segs(hashp, nsegs))
			/*
			 * If alloc_segs fails, table will have been destroyed
			 * and errno will have been set.
			 */
			return (NULL);
		/* Read in bitmaps */
		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
		    (hashp->BSIZE << BYTE_SHIFT) - 1) >>
		    (hashp->BSHIFT + BYTE_SHIFT);

		hashp->nmaps = bpages;
		(void)memset(&hashp->mapp[0], 0, bpages * sizeof(u_int32_t *));
	}

	/* Initialize Buffer Manager */
	if (info && info->cachesize)
		__buf_init(hashp, info->cachesize);
	else
		__buf_init(hashp, DEF_BUFSIZE);

	hashp->new_file = new_table;
	hashp->save_file = file && (hashp->flags & O_RDWR);
	hashp->cbucket = -1;
	if (!(dbp = (DB *)malloc(sizeof(DB)))) {
		save_errno = errno;
		hdestroy(hashp);
		errno = save_errno;
		return (NULL);
	}
	dbp->internal = hashp;
	dbp->close = hash_close;
	dbp->del = hash_delete;
	dbp->fd = hash_fd;
	dbp->get = hash_get;
	dbp->put = hash_put;
	dbp->seq = hash_seq;
	dbp->sync = hash_sync;
	dbp->type = DB_HASH;

#ifdef DEBUG
	(void)fprintf(stderr,
"%s\n%s%p\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
	    "init_htab:",
	    "TABLE POINTER   ", hashp,
	    "BUCKET SIZE     ", hashp->BSIZE,
	    "BUCKET SHIFT    ", hashp->BSHIFT,
	    "DIRECTORY SIZE  ", hashp->DSIZE,
	    "SEGMENT SIZE    ", hashp->SGSIZE,
	    "SEGMENT SHIFT   ", hashp->SSHIFT,
	    "FILL FACTOR     ", hashp->FFACTOR,
	    "MAX BUCKET      ", hashp->MAX_BUCKET,
	    "OVFL POINT	     ", hashp->OVFL_POINT,
	    "LAST FREED      ", hashp->LAST_FREED,
	    "HIGH MASK       ", hashp->HIGH_MASK,
	    "LOW  MASK       ", hashp->LOW_MASK,
	    "NSEGS           ", hashp->nsegs,
	    "NKEYS           ", hashp->NKEYS);
#endif
#ifdef HASH_STATISTICS
	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
#endif
	return (dbp);

error1:
	if (hashp != NULL)
		(void)_close(hashp->fp);

error0:
	free(hashp);
	errno = save_errno;
	return (NULL);
}
Exemplo n.º 30
0
LLVMValueRef gen_funcdef(struct node *ast)
{
	LLVMValueRef global, func, retval;
	LLVMTypeRef func_type, *param_types;
	LLVMBasicBlockRef body_block, ret_block;
	int param_count, i;

	if (hcreate(SYMTAB_SIZE) == 0)
		generror(">s");

	param_count = count_chain(ast->two);
	param_types = calloc(sizeof(LLVMTypeRef), param_count);

	if (param_count > 0 && param_types == NULL)
		generror("out of memory");

	for (i = 0; i < param_count; i++)
		param_types[i] = TYPE_INT;

	func_type = LLVMFunctionType(TYPE_INT, param_types, param_count, 0);
	func = LLVMAddFunction(module, ".gfunc", func_type);
	LLVMSetLinkage(func, LLVMPrivateLinkage);
	/* TODO: How to specify stack alignment? Should be 16 bytes */
	LLVMAddFunctionAttr(func, LLVMStackAlignment);

	global = find_or_add_global(ast->one->val);
	LLVMSetInitializer(global, LLVMBuildPtrToInt(builder, func, TYPE_INT, ""));

	body_block = LLVMAppendBasicBlock(func, "");
	ret_block = LLVMAppendBasicBlock(func, "");
	LLVMPositionBuilderAtEnd(builder, body_block);

	retval = LLVMBuildAlloca(builder, TYPE_INT, "");
	LLVMBuildStore(builder, CONST(0), retval);

	symtab_enter(ast->one->val, global);
	symtab_enter(".return", ret_block);
	symtab_enter(".retval", retval);

	label_count = 0;
	predeclare_labels(ast->three);

	if (ast->two)
		codegen(ast->two);

	codegen(ast->three);

	LLVMBuildBr(builder, ret_block);
	/* TODO: Untangle out-of-order blocks */
	LLVMPositionBuilderAtEnd(builder, ret_block);
	LLVMBuildRet(builder, LLVMBuildLoad(builder, retval, ""));

	LLVMMoveBasicBlockAfter(ret_block, LLVMGetLastBasicBlock(func));

	/* TODO: Handle failed verification and print internal compiler error */
	LLVMVerifyFunction(func, LLVMPrintMessageAction);

	hdestroy();

	return NULL;
}