Exemple #1
0
int main() {
  int i, *ptr;
  void *root = NULL;
  const void *ret;
  foo_t *val, *val2;

  val = calloc(1, sizeof(foo_t));
  val->name = strdup("one");
  val->value = 1;
  printf("name: %s\n", val->name);
  ret = tsearch(val, &root, cmp);
  printf("retname: %s\n", (*(foo_t **)ret)->name);

  val2 = calloc(1, sizeof(foo_t));
  val2->name = strdup(val->name);
  val2->value = 3;
  printf("name: %s\n", val->name);
  ret = tsearch(val, &root, cmp);
  printf("val2 result: %d\n", (*(foo_t **)ret)->value);

  printf("Walking with twalk\n");
  twalk(root, walker);
  return 0;

}
Exemple #2
0
TEST_SEPARATE_PROCESS(twalk, example) {
  // The numbers to insert into the tree.
  for (size_t i = 0; i < NELEMENTS; ++i)
    numbers[i] = i;

  // Generate random order in which elements should be inserted.
  size_t insertion_order[NELEMENTS];
  for (size_t i = 0; i < NELEMENTS; ++i)
    insertion_order[i] = i;
  for (ssize_t i = NELEMENTS - 1; i > 0; --i) {
    size_t j = arc4random_uniform(i);
    int tmp = insertion_order[i];
    insertion_order[i] = insertion_order[j];
    insertion_order[j] = tmp;
  }

  // Insert all elements into the tree in random order.
  void *root = NULL;
  for (size_t i = 0; i < NELEMENTS; ++i) {
    // Entry should not exist yet.
    int *keyp = &numbers[insertion_order[i]];
    ASSERT_EQ(NULL, tfind(keyp, &root, compar_int));
    ASSERT_EQ(NULL, tdelete(keyp, &root, compar_int));
    // Insertion should create new node in tree.
    ASSERT_EQ(keyp, *(int **)tsearch(keyp, &root, compar_int));
  }
  for (size_t i = 0; i < NELEMENTS; ++i) {
    // Successive searches should always return this node, even when
    // provided a different instance of the same key.
    int *keyp = &numbers[insertion_order[i]];
    int key = *keyp;
    ASSERT_EQ(keyp, *(int **)tfind(&key, &root, compar_int));
    ASSERT_EQ(keyp, *(int **)tsearch(&key, &root, compar_int));
  }

  // Invoke twalk() and check the order in which it iterates.
  twalk(root, traverse);
  ASSERT_EQ(NELEMENTS, next_key);
  ASSERT_EQ(-1, current_level);

  // Remove all elements from the tree.
  for (size_t i = 0; i < NELEMENTS; ++i) {
    int *keyp = &numbers[insertion_order[i]];
    int key = *keyp;
    ASSERT_NE(NULL, tdelete(&key, &root, compar_int));
    ASSERT_EQ(NULL, tdelete(&key, &root, compar_int));
    ASSERT_EQ(NULL, tfind(keyp, &root, compar_int));
  }
  ASSERT_EQ(NULL, root);
}
// Builds the binary tree for a given directory (having a snapshot buffer)
void buildDirectoryBinTree(struct directory *_inDirPtr) {
	
	struct directory _inDir = *_inDirPtr;
	void *binTree = *(void **)&_inDir.binTree;			// Make dereference to the binaryTree;
	treeNode *treeNodes = _inDir.treeNodes;	
	
	int i= 0;
	for(i=0;i<_inDir.elements; i++) {	
			tsearch(treeNodes, &binTree, cmpNodes);// (int (*)(const void*,const void*))cmpTnode);
			treeNodes++;
	}
	
	tsearch(_inDir.treeNodes, &binTree, cmpNodes); //(int (*)(const void*,const void*))cmpTnode);

}
void load()
{
map = malloc(sizeof(datastore_t));
//datastore_destroy(map);
datastore_init(map);
fd1 = fopen("data/stored.txt","r");
char keys[30];
char values[30];
int rr;
if (fd1!=NULL)
  {
  while(fscanf(fd1, "%s %s %d",keys, values, &rr)==3)
  {
  pthread_mutex_lock(&map->mutex);
  char * token;
  datastore_entry_t *datap = malloc(sizeof(datastore_entry_t));
  char* keyr = strdup(keys);
  char* valuer = strdup(values);
  datap->key = keyr;
  datap->value = valuer;
  datap->rev = rr;
  tsearch((void *)datap, &map->root, compare);
  pthread_mutex_unlock(&map->mutex);
  }
  }
  if (fd1!=NULL)
	fclose(fd1);



}
Exemple #5
0
static void AddPropertyToTree( char * s_property, char * s_family, enum ft_format s_format, size_t s_array, enum ag_combined s_combined, enum ag_index s_index_type, size_t s_length, enum fc_change s_change, char * s_read, char * s_write, char * s_data, char * s_other, enum external_type et )
{
	struct property_node * n  ;
	struct {
		struct property_node * key ;
		char other[0] ;
	} * opaque ;
	
	NonNull( s_property )
	NonNull( s_family )
	NonNull( s_read )
	NonNull( s_write )
	NonNull( s_data )
	NonNull( s_other )

	n = create_property_node( s_property, s_family, s_format, s_array, s_combined, s_index_type, s_length, s_change, s_read, s_write, s_data, s_other, et ) ;
	opaque = tsearch( (void *) n, &property_tree, property_compare ) ;
	
	if ( opaque->key != n ) {
		// already exists
		LEVEL_DEBUG("Duplicate property entry: %s,%s,%s,%s,%s,%s",s_property,s_family,s_read,s_write,s_data,s_other);
		owfree( n ) ;
	} else {
		LEVEL_DEBUG("New property entry: %s,%s,%s,%s,%s,%s",s_property,s_family,s_read,s_write,s_data,s_other);
	}		
}
Exemple #6
0
int MatchAdd(TFingerprint *FP, const char *Path, int Flags)
{
TFingerprint *Item;
int result=FALSE;
char *ptr;
void *vptr;

	if (Flags & FLAG_MEMCACHED)
	{
		ptr=FP->Data;
		if (StrEnd(ptr)) ptr=FP->Path;
		if (StrEnd(ptr)) ptr=Path;
		if (MemcachedSet(FP->Hash, 0, ptr)) result=TRUE;
	}
	else
	{
		vptr=tsearch(FP, &Tree, MatchCompareFunc);
		Item=*(TFingerprint **) vptr;
		if (strcmp(Item->Path, FP->Path) !=0)
		{
			while (Item->Next !=NULL) Item=(TFingerprint *) Item->Next;
			Item->Next=(void *) FP;
		}
		result=TRUE;
	}

	return(result);
}
Exemple #7
0
int add_rule (char *rule_buf, int rule_len, rules_t *rules)
{
  if (tfind (rule_buf, &root, compare_string) != NULL) return (-3);

  char in[BLOCK_SIZE];
  char out[BLOCK_SIZE];

  memset (in,  0, BLOCK_SIZE);
  memset (out, 0, BLOCK_SIZE);

  int result = apply_rule (rule_buf, rule_len, in, 1, out);

  if (result == -1) return (-1);

  char *next_rule = mystrdup (rule_buf);

  tsearch (next_rule, &root, compare_string);

  incr_rules_buf (rules);

  rules->rules_buf[rules->rules_cnt] = next_rule;

  rules->rules_len[rules->rules_cnt] = rule_len;

  rules->rules_cnt++;

  return (0);
}
Exemple #8
0
int *cthash_insert(CTHASH *h, int *rec)
{
    int ***p;

    int **node = (int **) e_malloc(sizeof(int *), "cthash_insert.node");
    *node = rec;

    p = (int ***) tfind((const void *) node, &h->root, cthash_cmp);
    if (p == (int ***) NULL) {
        /* new record */
        /* insert it into tree */
        p = (int ***) tsearch((const void *) node, &h->root, cthash_cmp);
        if (p == (int ***) NULL) {
            exit(-1);
        }
        (***p) = 1;  /* init counter */
    } else {
        /* existing record */

        (***p)++;               /* bump count by 1 */
        free((void *) rec);    /* delete new version of record */
        free((void *) node);   /* and pointer to it */
    }
    return **p;
}
Exemple #9
0
Fichier : util.c Projet : ju5t/npd6
/*****************************************************************************
 * storeListEntry
 *
 * Inputs:
 *  in6_addr *Target - this is the newly seen target to check
 *
 * Outputs:
 *  lRoot has a new item added if the address was new.
 *
 * Return:
 *  Void
 */
void storeListEntry(struct in6_addr *newEntry)
{
    struct in6_addr *ptr;

    // Take a permanenet copy of the target
    ptr = (struct in6_addr *)malloc(sizeof(struct in6_addr) );
    if (!ptr)
    {
        flog(LOG_ERR, "Malloc failed. Ignoring.");
	return;
    }
    memcpy(ptr, newEntry, sizeof(struct in6_addr) );

    if ( tfind( (void *)ptr, &lRoot, tCompare) == NULL )
    {
        // New entry
        flog(LOG_DEBUG2, "New list entry");
        if ( tsearch( (void *)ptr, &lRoot, tCompare) == NULL)
        {
            flog(LOG_ERR, "tsearch failed. Cannot record entry.");
            return;
        }
    }
    else
    {
        flog(LOG_ERR, "Dupe list entry. Ignoring.");
    }
}
/*
 * @return 0      if successful.
 * @return ENOMEM if out-of-memory.
 */
int
cps_add(
    pid_t pid)
{
    int    error;

    if (cps_contains(pid)) {
        error = 0;
    }
    else {
        pid_t *elt;

        elt = (pid_t*)malloc(sizeof(pid_t));

        if (elt == NULL) {
            error = ENOMEM;
        }
        else {
            *elt = pid;

            if (tsearch(elt, &root, compare) == NULL) {
                error = ENOMEM;
            }
            else {
                ++count;
                error = 0;
            }
        }
    }

    return error;
}
Exemple #11
0
int
_StatStuff(const struct afscp_venusfid *fid, const struct AFSFetchStatus *s)
{
    struct afscp_volume *v;
    struct afscp_statent key, *stored;
    void **cached;

    v = afscp_VolumeById(fid->cell, fid->fid.Volume);
    if (v == NULL) {
	return -1;
    }
    memmove(&key.me, fid, sizeof(*fid));

    cached = tsearch(&key, &v->statcache, statcompare);
    if (cached != NULL) {
	stored = malloc(sizeof(struct afscp_statent));
	if (stored != NULL) {
	    pthread_mutex_init(&(stored->mtx), NULL);
	    pthread_cond_init(&(stored->cv), NULL);
	    stored->nwaiters = 0;
	    stored->cleanup = 0;
	    memmove(&stored->me, fid, sizeof(*fid));
	    memmove(&stored->status, s, sizeof(*s));
	    *(struct afscp_statent **)cached = stored;
	} else {
	    tdelete(&key, &v->statcache, statcompare);
	}
    }
    return 0;
}
Exemple #12
0
/* add a new malloc entry to the table */
static
void ncmpii_add_mem_entry(void       *buf,
                          size_t      size,
                          const int   lineno,
                          const char *func,
                          const char *filename)
{
    /* use C tsearch utility */
    ncmpii_mem_entry *node = (ncmpii_mem_entry*) malloc(sizeof(ncmpii_mem_entry));
    node->self     = node;
    node->buf      = buf;
    node->size     = size;
    node->lineno   = lineno;
    node->func     = (char*)malloc(strlen(func)+1);
    node->filename = (char*)malloc(strlen(filename)+1);
    strcpy(node->func, func);
    node->func[strlen(func)] = '\0';
    strcpy(node->filename, filename);
    node->filename[strlen(filename)] = '\0';

    /* search and add a new item */
    void *ret = tsearch(node, &ncmpii_mem_root, ncmpii_cmp);
    if (ret == NULL) {
        printf("Error: tsearch()\n");
        return;
    }
    ncmpii_mem_alloc += (MPI_Offset)size;
    ncmpii_max_mem_alloc = MAX(ncmpii_max_mem_alloc, ncmpii_mem_alloc);
}
Exemple #13
0
static void
set_hash_element(struct hash_table *hash, struct hash_element *element)
{
	int p;

	p=element->hash%hash->size;

	if (hash->table[p] == NULL)
	{
		hash->table[p]=(struct hash_entry*)xmalloc(sizeof(*hash->table[p]));
		hash->table[p]->tree=NULL;
		hash->table[p]->count=0;
	}

	element->hash_table=hash;

	if (tsearch(element,&hash->table[p]->tree,hash_data_cmp) == NULL)
		xmemerror();

	hash->table[p]->count++;

	//DEBUG_PRINT("0x%x: hash %lu: Now in position %d\n",
	//     (unsigned int)element->data,(unsigned long)element->hash,p);

}
Exemple #14
0
static
int handle_file(const char *fpath, const struct stat *sb,
		int typeflag, struct FTW *ftwb)
{
	ix_attr_t attr;

	attr.filename = fpath + ftwb->base;

	if (ix_attr_get(&attr) == -1) {
		log_perror("ix_get_attr(%s)", fpath);
		errcnt++;
		return FTW_STOP;
	}

	if (!(attr.mask & IATTR_TAG))
		return FTW_CONTINUE;

	if (sb->st_nlink == 1 || tfind(&sb->st_ino, &inotable, inocmp) == NULL) {
		if (attr.xid == xid) {
			used_blocks += sb->st_blocks;
			used_inodes += 1;
		}

		if (tsearch(&sb->st_ino, &inotable, inocmp) == NULL) {
			log_perror("tsearch(%u)", sb->st_ino);
			errcnt++;
			return FTW_STOP;
		}
	}

	return FTW_CONTINUE;
}
Exemple #15
0
HTokenType h_allocate_token_type(const char* name) {
  Entry* new_entry = (&system_allocator)->alloc(&system_allocator, sizeof(*new_entry));
  if (!new_entry) {
    return TT_INVALID;
  }
  new_entry->name = name;
  new_entry->value = 0;
  Entry* probe = *(Entry**)tsearch(new_entry, &tt_registry, compare_entries);
  if (probe->value != 0) {
    // Token type already exists...
    // TODO: treat this as a bug?
    (&system_allocator)->free(&system_allocator, new_entry);
    return probe->value;
  } else {
    // new value
    probe->name = strdup(probe->name); // drop ownership of name
    probe->value = tt_next++;
    if ((probe->value - TT_START) >= tt_by_id_sz) {
      if (tt_by_id_sz == 0) {
	tt_by_id = malloc(sizeof(*tt_by_id) * ((tt_by_id_sz = (tt_next - TT_START) * 16)));
      } else {
	tt_by_id = realloc(tt_by_id, sizeof(*tt_by_id) * ((tt_by_id_sz *= 2)));
      }
      if (!tt_by_id) {
	return TT_INVALID;
      }
    }
    assert(probe->value - TT_START < tt_by_id_sz);
    tt_by_id[probe->value - TT_START] = probe;
    return probe->value;
  }
}
Exemple #16
0
xtreeStatus_t xtreeAdd(void *treehandle, char *key, void *userdata)
{
	xtree_t *tree = treehandle;
	treerec_t *rec, **erec;

	if (!tree) return XTREE_STATUS_NOTREE;

	rec = (treerec_t *)calloc(1, sizeof(treerec_t));
	rec->key = key;
	rec->userdata = userdata;
	rec->compare = tree->compare;

	erec = tsearch(rec, &tree->root, xtree_i_compare);
	if (erec == NULL) {
		free(rec);
		return XTREE_STATUS_MEM_EXHAUSTED;
	}
	if (*erec != rec) {
		/* Was already there */
		free(rec);
		return XTREE_STATUS_DUPLICATE_KEY;
	}

	return XTREE_STATUS_OK;
}
Exemple #17
0
static void memkey_add(void *p,size_t size){
    if(!p || disable_memdbg) return;
    LOCK(mutex_mem);
    int disable_save=disable_memdbg;
    disable_memdbg=1;//prevent recursive calling
    T_MEMKEY *key=calloc_default(1,sizeof(T_MEMKEY));
    key->p=p;
    key->size=size;
    key->nfunc=backtrace(key->func,DT);
    void **found=tfind(key, &MROOT, key_cmp);
    if(found){
	T_MEMKEY*key1=*found;
	warning("memkey_add: %p already exists with size %zd. new size %zd\n", 
		p, key1->size, size);
	key1->size=size;
    }else{
	if(!tsearch(key, &MROOT, key_cmp)){
	    warning("memkey_add: Error inserting to tree\n");
	}
	memcnt++;
	memalloc+=size;
    }
    disable_memdbg=disable_save;
    if(MEM_VERBOSE==1){
	info("%p malloced with %zu bytes: %s\n",p, size, found?"collision":"success");
    }else if(MEM_VERBOSE==2 && size>1024){
	info("Alloc:%.3f MB mem used\n", (memalloc-memfree)/1024./1024.);
    }
    UNLOCK(mutex_mem);
    if(found) print_backtrace();
}
Exemple #18
0
void remix_init() {
    int word_num;
    void *node;

    if (initialized) {
#ifdef DEBUG
        wprintf(L"Already initialized\n");
#endif
        return;
    }

#ifdef DEBUG
        wprintf(L"Initializing\n");
#endif

    for (word_num = 0; word_num < wordlist_size; word_num++) {
        node = tsearch((void *) wordlist[word_num], &wordlist_tree, (__compar_fn_t) wcscmp);
        assert(node != NULL);
    }
    
    initialized = 1;

#ifdef DEBUG
        wprintf(L"Initialized\n");
#endif

}
Exemple #19
0
static void
enter(struct ctmp *c)
{
	unsigned i;
	int j;
	struct ctab **pt;

	if ((pctab = (struct ctab *)malloc(sizeof (struct ctab))) == NULL) {
		fprintf(stderr, "acctcon: malloc fail!\n");
		exit(2);
	}

	pctab->ct_uid = c->ct_uid;
	CPYN(pctab->ct_name, c->ct_name);
	pctab->ct_con[0] = c->ct_con[0];
	pctab->ct_con[1] = c->ct_con[1];
	pctab->ct_sess = 1;

	if (*(pt = (struct ctab **)tsearch((void *)pctab, (void **)&root,  \
		node_compare)) == NULL) {
		fprintf(stderr, "Not enough space available to build tree\n");
		exit(1);
	}

	if (*pt != pctab) {
		(*pt)->ct_con[0] += c->ct_con[0];
		(*pt)->ct_con[1] += c->ct_con[1];
		(*pt)->ct_sess++;
		free(pctab);
	}

}
Exemple #20
0
static int add_to_file_list(FILE *list, const char *path, void **ftree,
			    psys_err_t *err)
{
	char *found;

	found = tfind(path, ftree, pathcmp_fn);
	if (!found) {
		int rc;

		if (strcmp(path, "/") != 0)
			add_to_file_list(list, dirname(nfstrsave(path)),
					 ftree, err);

		if (!strcmp(path, "/"))
			rc = fprintf(list, "/.\n"); 
		else
			rc = fprintf(list, "%s\n", path);

		if (rc < 0) {
			psys_err_set(err, PSYS_EINTERNAL,
				     "Cannot write to file list: %s",
				     strerror(errno));
			return -1;
		}

		if (!tsearch(path, ftree, pathcmp_fn)) {
			psys_err_set_nomem(err);
			return -1;
		}
	}
	return 0;
}
/*
..main()
Stack.cpp.Stack::getNumStacksCreated()
Stack.cpp.Stack::Link::initialize(char*, Stack::Link*)
#Stack.cpp.Stack()
#Stack.cpp.~Stack()
Stack.cpp.Stack::getName()
Stack.cpp.Stack::privateStuff()
#Stack.cpp.Stack::push(char*)
#Stack.cpp.Stack::peek()
Stack.cpp.Stack::pop()
*/
void initializeProgramPointsTree()
{
  while (fgets(input_line, 200, trace_prog_pts_input_fp))
    {
      char *newString;
      int lineLen = VG_(strlen)(input_line);

      // Skip blank lines (those consisting of solely the newline character)
      // Also skip comment lines (those beginning with COMMENT_CHAR)
      if(('\n' == input_line[0]) ||
         (COMMENT_CHAR == input_line[0])) {
        //        VG_(printf)("skipping blank line ...\n");
        continue;
      }

      // Strip '\n' off the end of the line
      // NOTE: Only do this if the end of the line is a newline character.
      // If the very last line of a file is not followed by a newline character,
      // then blindly stripping off the last character will truncate the actual
      // string, which is undesirable.
      if (input_line[lineLen - 1] == '\n') {
        input_line[lineLen - 1] = '\0';
      }

      newString = VG_(strdup)("fjalar_selec.c: initializePPT", input_line);

      // That is the Fjalar name of the function so grab it
      tsearch((void*)newString, (void**)&prog_pts_tree, compareStrings);
    }

  fclose(trace_prog_pts_input_fp);
  trace_prog_pts_input_fp = 0;
}
Exemple #22
0
void fun()
{
	int i, *ptr;
	void *val;
	//srand(time(NULL)); // 官方文档上的例子是采用随机数,但是由于每次执行都会产生不同的随机数,这样不便于观察,所以这里采用下面固定的数组。
	int array[12] = {2, 2, 1, 12, 9, 4, 8, 10, 3, 7, 5, 11};
	for (i = 0; i < 12; i++)
	{
		printf("~~~~~~~~~~~~ i = %d ~~~~~~~~~~~~~~\n", i);
		ptr = xmalloc(sizeof(int));
		//*ptr = rand() & 0xff; // 取随机数的低8位。
		*ptr = array[i];
		//ptr = array + i;
		printf("*ptr = %d\n", *ptr);

		val = tsearch((void *) ptr, &root, compare);

		int *pint = *(int **)val;
		printf("ptr = %p, *ptr = %d, val = %p, pint = %p, *pint = %d, root = %p\n", ptr, *ptr, val, pint, *pint, root);
		if (val == NULL)
		{
			printf("tsearch return NULL, will exit\n");
			exit(EXIT_FAILURE);
		}
		else if (pint != ptr)
		{
			printf("pint != ptr, will free(ptr)\n");
			free(ptr);
		}
	}
}
void search()
{
Panel search;
search.init(6,56,getmaxx()-5,getmaxy()-7,THIN,IN);;
search.show();
search.shape("SEARCH");


Panel move;

       move.init(220,120,525,455,OUT,THIN);
       move.show( );
       move.shape("SEARCH");




      settextstyle(1,0,1);

       tsearch();
int cnt=0;
while((!kbhit())&&(!(leftmousekeypressed())))
cnt++;
Panel scribble;

       scribble.init(6,56,getmaxx()-5,getmaxy()-7,THIN,IN);
       scribble.show();

}
Exemple #24
0
/**
 * Adds a PID.
 *
 * @param pid       [in] The PID to be added.
 * @retval 0        Success.
 * @retval ENOMEM   Out-of-memory.
 */
int
cps_add(
    pid_t pid)
{
    int    error;

    if (cps_contains(pid)) {
        error = 0;
    }
    else {
        pid_t *elt = malloc(sizeof(pid_t));

        if (elt == NULL) {
            error = ENOMEM;
        }
        else {
            *elt = pid;

            if (tsearch(elt, &root, compare) == NULL) {
                error = ENOMEM;
            }
            else {
                ++count;
                error = 0;
            }

            if (error)
                free(elt);
        } /* "elt" allocated */
    } /* "pid" doesn't exist */

    return error;
}
Exemple #25
0
void
enter(struct ptmp *p)
{
        double memk;
        struct utab **pt;
         
	if ((ub = (struct utab *)malloc(sizeof (struct utab))) == NULL) {
		fprintf(stderr, "acctprc: malloc fail!\n");
		exit(2);
	}

        ub->ut_uid = p->pt_uid;
        CPYN(ub->ut_name, p->pt_name);
        ub->ut_cpu[0] = MINT(p->pt_cpu[0]);
        ub->ut_cpu[1] = MINT(p->pt_cpu[1]);
        memk = KCORE(pb.pt_mem);  
        ub->ut_kcore[0] = memk * MINT(p->pt_cpu[0]);
        ub->ut_kcore[1] = memk * MINT(p->pt_cpu[1]);
        ub->ut_pc = 1;
         
        if (*(pt = (struct utab **)tsearch((void *)ub, (void **)&root,  \
                node_compare)) == NULL) {
                fprintf(stderr, "Not enough space available to build tree\n");
                exit(1);
	}

	if (*pt != ub) {
        	(*pt)->ut_cpu[0] += MINT(p->pt_cpu[0]);
        	(*pt)->ut_cpu[1] += MINT(p->pt_cpu[1]);
        	(*pt)->ut_kcore[0] += memk * MINT(p->pt_cpu[0]);
        	(*pt)->ut_kcore[1] += memk * MINT(p->pt_cpu[1]);
		(*pt)->ut_pc++;
		free(ub);
        }
}
Exemple #26
0
/*
 * ===  FUNCTION  ======================================================================
 *         Name:  process_queue
 *  Description:  Reads messages from queue and places them in a search tree
 *                using the tsearch() function.  When all messages have been read, traverses
 *                the tree, sending messages based upon the alphabetical order of the mtext
 *                field.
 * =====================================================================================
 */
static int
process_queue(int msqid, size_t maxmsgsz, long msgtyp, int msgflg,
        int(*compar)(const void *, const void *),
        void (*action)(const void *nodep, const VISIT value, const int level))
{
    int ret;
    msg_t *msg = NULL, *msg_node = NULL;
    void *root = NULL, *node = NULL;
    int msgsnd_flag = 0;

    while(1) {
        /* Each node of the tree must be separately
         * allocated. */
        msg = xmalloc(sizeof(msg_t));
        ret = msgrcv(msqid, msg, maxmsgsz, msgtyp, msgflg);
        if(ret == -1) {
            perror("process_queue: msgrcv");
            _exit(EXIT_FAILURE);
        }
        /* If msg's count field == -1, there are
         * no more messages to process. */
        if(msg->count == -1) {
            free(msg);
            break;
        }
        node = tsearch(msg, &root, compar);
        /* If 'node' is NULL, tsearch failed to insert
         * the message into the tree. */
        if(node == NULL) {
            perror("tsearch");
            _exit(EXIT_FAILURE);
        } else {
            msg_node = *(msg_t **)node;
            /* Check whether the newly-inserted node
             * points to the same place as 'msg'.  If it
             * doesn't, increment the node's count field
             * and free msg. */
            if(msg_node != msg) {
                msg_node->count++;
                free(msg);
            }
        }
    }

    /* Place messages in queue in
     * alphabetical order */
    twalk(root, action);

    /* Free the memory associated
     * with the tree */
    tdestroy(root, &free);

    /* Send terminating message to parent */
    if(msgsnd_str(child_queue, 1, msgsnd_flag, msgtyp, "", -1) == -1) {
        perror("msgsnd_str");
        _exit(EXIT_FAILURE);
    }

    return ret;
}
Exemple #27
0
static struct dwarf_fde *
intern_fde (Dwarf_CFI *cache, const Dwarf_FDE *entry)
{
  /* Look up the new entry's CIE.  */
  struct dwarf_cie *cie = __libdw_find_cie (cache, entry->CIE_pointer);
  if (cie == NULL)
    return (void *) -1l;

  struct dwarf_fde *fde = malloc (sizeof (struct dwarf_fde));
  if (fde == NULL)
    {
      __libdw_seterrno (DWARF_E_NOMEM);
      return NULL;
    }

  fde->instructions = entry->start;
  fde->instructions_end = entry->end;
  if (unlikely (read_encoded_value (cache, cie->fde_encoding,
				    &fde->instructions, &fde->start))
      || unlikely (read_encoded_value (cache, cie->fde_encoding & 0x0f,
				       &fde->instructions, &fde->end)))
    {
      free (fde);
      __libdw_seterrno (DWARF_E_INVALID_DWARF);
      return NULL;
    }
  fde->end += fde->start;

  fde->cie = cie;

  if (cie->sized_augmentation_data)
    {
      /* The CIE augmentation says the FDE has a DW_FORM_block
	 before its actual instruction stream.  */
      Dwarf_Word len;
      get_uleb128 (len, fde->instructions, fde->instructions_end);
      if ((Dwarf_Word) (fde->instructions_end - fde->instructions) < len)
	{
	  free (fde);
	  __libdw_seterrno (DWARF_E_INVALID_DWARF);
	  return NULL;
	}
      fde->instructions += len;
    }
  else
    /* We had to understand all of the CIE augmentation string.
       We've recorded the number of data bytes in FDEs.  */
    fde->instructions += cie->fde_augmentation_data_size;

  /* Add the new entry to the search tree.  */
  if (tsearch (fde, &cache->fde_tree, &compare_fde) == NULL)
    {
      free (fde);
      __libdw_seterrno (DWARF_E_NOMEM);
      return NULL;
    }

  return fde;
}
Exemple #28
0
/*
 * Adds an entry to a child-map.
 *
 * @retval 0    Success
 * @retval 1    Usage error. \c log_start() called.
 * @retval 2    O/S failure. \c log_start() called.
 */
int cm_add_string(
    ChildMap* const     map,            /**< [in/out] Pointer to the child-map
                                         */
    const pid_t         pid,            /**< [in] Process ID of the child.
                                         *   Must not already exist in map. */
    const char* const   command)        /**< [in] Command-line of the child.
                                         *   Defensively copied. */
{
    int    status;

    if (NULL == map) {
        LOG_START0("Null map argument");
        status = 1;
    }
    else if (NULL == command) {
        LOG_START0("Null command argument");
        status = 1;
    }
    else {
        status = cm_contains(map, pid);

        if (0 == status) {
            Entry* const    entry = (Entry*)malloc(sizeof(Entry));

            if (NULL == entry) {
                LOG_SERROR0("Couldn't allocate new entry");
                status = 2;
            }
            else {
                entry->command = strdup(command);

                if (NULL == entry->command) {
                    LOG_SERROR0("Couldn't duplicate command-line");
                    status = 2;
                }
                else {
                    entry->pid = pid;

                    if (NULL == tsearch(entry, &map->root, compare)) {
                        LOG_SERROR0("Couldn't add entry to map");
                        status = 2;
                    }
                    else {
                        map->count++;
                        status = 0;
                    }

                    if (0 != status)
                        free(entry->command);
                }                       /* "entry->command" allocated */

                if (0 != status)
                    free(entry);
            }                           /* "entry" allocated */
        }                               /* "pid" not in map */
    }                                   /* valid arguments */

    return status;
}
void metafield_register(metafield_t * metafield)
{
    // Process the patterns
    // XXX

    // Insert the metafield in the tree if the keys does not yet exist
    tsearch(metafield, &metafields_root, (ELEMENT_COMPARE) metafield_compare);
}
Exemple #30
0
void near FiltOverride(void *v, char *words[], char *line)
{
  OVRLIST ol=malloc(sizeof(*ol));
  int idx;

  NW(line);

  if (!ol)
    NoMem();

/* 0        1       2         3          4 */
/* override message msg_reply sysop/1234 R */

  if (!*words[1])
  {
    printf("Error!  No menu name specified for override on line %d!\n", linenum);
    return;
  }

  if (!*words[3])
  {
    printf("Error!  No access control string specified for override on line %d!\n", linenum);
    return;
  }

  if ((idx=tsearch(words[2], silt_table, silt_table_size)) != -1)
    ol->or.opt=silt_table[idx].opt;
  else Unknown_Ctl(linenum, words[2]);

  if (*words[4])
    ol->or.name=*words[4];
  else ol->or.name=0;

  if (PFI(v)->marea)
  {
    HeapAdd(&PMI(v)->h, &ol->or.menuname, words[1]);
    HeapAdd(&PMI(v)->h, &ol->or.acs, words[3]);

    /* Add this to the linked list of override options */

    ol->next=PMI(v)->ol;
    PMI(v)->ol=ol;

    PMI(v)->ma.num_override++;
  }
  else
  {
    HeapAdd(&PFI(v)->h, &ol->or.menuname, words[1]);
    HeapAdd(&PFI(v)->h, &ol->or.acs, words[3]);

    /* Add this to the linked list of override options */

    ol->next=PFI(v)->ol;
    PFI(v)->ol=ol;

    PFI(v)->fa.num_override++;
  }
}