コード例 #1
0
ファイル: clanmate.c プロジェクト: DevilDaga/warfacebot
void clanmate_list_free ( void )
{
	list_free ( session.clan.clanmates );
	session.clan.clanmates = NULL;
}
コード例 #2
0
ファイル: ls.c プロジェクト: klange/toaruos
static int display_dir(char * p) {
	/* Open the directory */
	DIR * dirp = opendir(p);
	if (dirp == NULL) {
		return 2;
	}

	if (print_dir) {
		printf("%s:\n", p);
	}

	/* Read the entries in the directory */
	list_t * ents_list = list_create();

	TRACE("reading entries");
	struct dirent * ent = readdir(dirp);
	while (ent != NULL) {
		if (show_hidden || (ent->d_name[0] != '.')) {
			struct tfile * f = malloc(sizeof(struct tfile));

			f->name = strdup(ent->d_name);

			char tmp[strlen(p)+strlen(ent->d_name)+2];
			sprintf(tmp, "%s/%s", p, ent->d_name);
			lstat(tmp, &f->statbuf);
			if (S_ISLNK(f->statbuf.st_mode)) {
				stat(tmp, &f->statbufl);
				f->link = malloc(4096);
				readlink(tmp, f->link, 4096);
			}

			list_insert(ents_list, (void *)f);
		}
		ent = readdir(dirp);
	}
	closedir(dirp);

	TRACE("copying");

	/* Now, copy those entries into an array (for sorting) */

	if (!ents_list->length) return 0;

	struct tfile ** file_arr = malloc(sizeof(struct tfile *) * ents_list->length);
	int index = 0;
	foreach(node, ents_list) {
		file_arr[index++] = (struct tfile *)node->value;
	}

	list_free(ents_list);

	TRACE("sorting");
	qsort(file_arr, index, sizeof(struct tfile *), filecmp_notypesort);

	TRACE("displaying");
	display_tfiles(file_arr, index);

	free(file_arr);

	return 0;
}
コード例 #3
0
ファイル: ar_share.c プロジェクト: BackupTheBerlios/gift-ares
/*
 * Add share. If share->hash is NULL the hash will be calculated before the
 * function returns (very inefficient to do all the time). If the file does
 * not fall into one of Ares' realms or it is an incomplete download it will
 * not be shared and FALSE will be returned.
 */
as_bool ar_share_add (const ARShare *share)
{
	ASShare *s;
	ASHash *hash = NULL;
	ASMeta *meta;
	ASRealm realm;
	as_bool ret;

	/* Don't share this file since Ares wouldn't either. */
	if ((realm = as_meta_realm_from_filename (share->path)) == REALM_UNKNOWN)
	{
		return FALSE;
	}

	/* Don't share incomplete files */
	if (strncmp (as_get_filename (share->path),
	             AS_DOWNLOAD_INCOMPLETE_PREFIX,
		         strlen (AS_DOWNLOAD_INCOMPLETE_PREFIX)) == 0)
	{
		return FALSE;
	}


	/* Create internal share object */
	if (share->hash)
	{
		assert (AR_HASH_SIZE == AS_HASH_SIZE);

		if (!(hash = as_hash_create ((as_uint8 *)share->hash, AS_HASH_SIZE)))
		{
			AS_ERR ("Insufficient memory.");
			return FALSE;
		}
	}

	if (!(meta = ar_import_meta ((ARMetaTag *)share->meta)))
	{
		AS_ERR ("Failed to import meta data.");
		as_hash_free (hash);
		return FALSE;
	}

	/* takes ownership of hash and meta objects */
	if (!(s = as_share_create (share->path, hash, meta, share->size, realm)))
	{
		AS_ERR_1 ("Failed to create share object for '%s'", share->path);
		as_hash_free (hash);
		as_meta_free (meta);
		return FALSE;
	}

	/* Add share. */
	if (queueing)
	{
		/* If we are queueing there is no need to interrupt event system. */
		queued_shares = list_prepend (queued_shares, s);
		ret = TRUE;	
	}
	else
	{	
		/* Not queueing, add share directly. */
		List *link;

		if (!ar_events_pause ())
			return FALSE;
		
		link = list_prepend (NULL, s);
		ret = as_shareman_add_and_submit (AS->shareman, link);
		link = list_free (link);

		ar_events_resume ();
	}

	return ret;
}
コード例 #4
0
ファイル: pipeline_query.c プロジェクト: URXtech/pipelinedb
/*
 * get_next_id
 *
 * Gets the smallest possible id to assign to the next continuous view.
 * We keep this minimal so that we can minimize the size of bitmaps used
 * to tag stream buffer events with.
 */
static Oid
get_next_id(Relation rel)
{
	HeapScanDesc scandesc;
	HeapTuple tup;
	List *ids_list = NIL;
	int num_ids;

	Assert(MAX_CQS % 32 == 0);

	scandesc = heap_beginscan_catalog(rel, 0, NULL);

	while ((tup = heap_getnext(scandesc, ForwardScanDirection)) != NULL)
	{
		Form_pipeline_query row = (Form_pipeline_query) GETSTRUCT(tup);
		ids_list = lappend_oid(ids_list, row->id);
	}

	heap_endscan(scandesc);

	num_ids = list_length(ids_list);

	if (num_ids)
	{
		Oid ids[num_ids];
		int counts_per_combiner[continuous_query_num_combiners];
		int i = 0;
		Oid max;
		ListCell *lc;
		int j;
		int target_combiner;
		List *potential_ids;

		MemSet(counts_per_combiner, 0, sizeof(counts_per_combiner));

		foreach(lc, ids_list)
		{
			ids[i] = lfirst_oid(lc);
			counts_per_combiner[ids[i] % continuous_query_num_combiners] += 1;
			i++;
		}

		qsort(ids, num_ids, sizeof(Oid), &compare_oid);

		if (num_ids == MAX_CQS - 1) /* -1 because 0 is an invalid id */
			ereport(ERROR,
					(errcode(ERRCODE_TOO_MANY_CONTINUOUS_VIEWS),
					errmsg("maximum number of continuous views exceeded"),
					errhint("Please drop a existing continuous view before trying to create a new one.")));

		max = ids[num_ids - 1];
		Assert(max >= num_ids);

		/*
		 * FIXME(usmanm): We do some randomization of ID generation here to make sure that CQs that
		 * are created and dropped in quick succession don't read an event that was not for them.
		 */

		/*
		 * Collect any unused ids in [1, max].
		 */
		list_free(ids_list);
		ids_list = NIL;

		for (i = 1, j = 0; j < num_ids; i++)
		{
			if (ids[j] > i)
				ids_list = lappend_oid(ids_list, (Oid) i);
			else
				j++;
		}

		/*
		 * Add all IDs between max and the next multiple of 32.
		 */
		j = Min((max / 32 + 1) * 32, MAX_CQS);
		for (i = max + 1; i < j; i++)
			ids_list = lappend_oid(ids_list, (Oid) i);

		/*
		 * Less than 16 options? Throw in some more.
		 */
		if (list_length(ids_list) < 16 && j < MAX_CQS)
			for (i = j; i < j + 32; i++)
				ids_list = lappend_oid(ids_list, (Oid) i);

		/*
		 * Figure out the target combiner (one with least IDs allocated) and try to allocate
		 * an ID that belongs to it.
		 */
		target_combiner = 0;
		for (i = 0; i < continuous_query_num_combiners; i++)
			if (counts_per_combiner[i] < counts_per_combiner[target_combiner])
				target_combiner = i;

		potential_ids = NIL;
		foreach(lc, ids_list)
		{
			Oid id = lfirst_oid(lc);
			if (id % continuous_query_num_combiners == target_combiner)
				potential_ids = lappend_oid(potential_ids, id);
		}
コード例 #5
0
ファイル: main.cpp プロジェクト: RickyXwang/transf-badapple
int run_assembly()
{
#ifdef _WIN32
	struct _timeb time_start, time_end;
	_ftime(&time_start);
#endif
	exit_code = EXIT_NORMAL;
	
	/*extern int generic_map[256];
	ZeroMemory(generic_map, 256);*/
	program_counter = 0x0000;
	stats_codesize = stats_datasize = stats_mintime = stats_maxtime = 0;
	last_label = NULL;
	error_occurred = false;
	listing_offset = 0;
	listing_for_line_done = false;
	line_start = NULL;
	old_line_num = 0;
	in_macro = 0;
	line_num = 0;
#ifdef USE_BUILTIN_FCREATE
	cur_buf = 0;
#endif
#ifdef USE_REUSABLES
	curr_reusable = 0;
	total_reusables = 0;
#endif
	
	expr_list = NULL;
	expr_list_tail = NULL;
	output_list = NULL;
	output_list_tail = NULL;

	assert(curr_input_file != NULL);

	//read in the input file
	if (!(mode & MODE_COMMANDLINE))
		input_contents = (char *) get_file_contents (curr_input_file);

	if (!input_contents) {
		puts ("Couldn't open input file");
		return EXIT_FATAL_ERROR;
	}
	
	out_ptr = output_contents;

	//along with the listing buffer, if required
	if ((mode & MODE_LIST)) {
		listing_buf = eb_init (LISTING_BUF_SIZE);
		listing_offset = 0;
		listing_on = true;
	}
	
	//find the path of the input file
	if (is_abs_path(curr_input_file)) {
		int i;

		strcpy(temp_path, curr_input_file);
	
		for (i = strlen(temp_path) - 1; 
			temp_path[i] != '\\' && temp_path[i] != '/' && i > 0; i--);
		if (i >= 0)
			temp_path[i] = '\0';
		else
			strcpy(temp_path, ".");
	} else {
#ifdef WIN32
		_getcwd(temp_path, sizeof (temp_path));
#else
		getcwd(temp_path, sizeof (temp_path));
#endif
	}

	//add the the input file's path to the include directories
	include_dirs = list_prepend (include_dirs, strdup (temp_path));

	printf ("Pass one... \n");

	int first_pass_session = StartSPASMErrorSession();
	run_first_pass ((char *) input_contents);
	ReplayFatalSPASMErrorSession(first_pass_session);
	EndSPASMErrorSession(first_pass_session);

	//free include dirs when done
	if ((mode & MODE_COMMANDLINE) == 0)
	{
		release_file_contents(input_contents);
		input_contents = NULL;
	}
	
	list_free (include_dirs, true, NULL);
	include_dirs = NULL;

	//...and if there's output, run the second pass and write it to the output file
	if (mode & MODE_NORMAL || mode & MODE_LIST)
	{
		printf ("Pass two... \n");
		int second_pass_session = StartSPASMErrorSession();
		run_second_pass ();
		ReplaySPASMErrorSession(second_pass_session);
		EndSPASMErrorSession(second_pass_session);

		//run the output through the appropriate program export and write it to a file
		if (mode & MODE_NORMAL && output_filename != NULL)
		{
			write_file (output_contents, out_ptr - output_contents, output_filename);
		}

		//write the listing file if necessary
		if ((mode & MODE_LIST)) {
			FILE *file;
			char *name;

			//get file name
			name = change_extension (output_filename, "lst");
			file = fopen (name, "wb");
			if (!file) {
				printf ("Couldn't open listing file '%s'", name);
				free (name);
				return EXIT_FATAL_ERROR;
			}
			free (name);
			
			if (fwrite (listing_buf->start, 1, listing_offset, file) != listing_offset) {
				puts ("Error writing to listing file");
				fclose (file);
				return EXIT_FATAL_ERROR;
			}

			fclose (file);
			eb_free(listing_buf);
			listing_buf = NULL;
		}
		
		//free the output buffer and all the names of input files
		list_free(input_files, true, NULL);
		input_files = NULL;
	}

	//if there's info to be dumped, do that
	if (mode & MODE_CODE_COUNTER) {
		fprintf (stdout, "Size: %u\nMin. execution time: %u\nMax. execution time: %u\n",
		         stats_codesize, stats_mintime, stats_maxtime);
	}
	
	if (mode & MODE_SYMTABLE) {
		char* fileName = change_extension(output_filename, "lab");
		write_labels (fileName);
		free(fileName);
	}

	if (mode & MODE_STATS) {
		fprintf(stdout, "Number of labels: %u\nNumber of defines: %u\nCode size: %u\nData size: %u\nTotal size: %u\n",
		         get_num_labels (), get_num_defines (), stats_codesize, stats_datasize, stats_codesize + stats_datasize);
	}
	
#ifdef _WIN32
	_ftime(&time_end);
	int s_diff = (int) (time_end.time - time_start.time);
	int ms_diff = time_end.millitm - time_start.millitm;
	if (ms_diff < 0) {
		ms_diff += 1000;
		s_diff -= 1;
	} else if (ms_diff > 1000) {
		ms_diff -= 1000;
		s_diff += 1;
	}
	printf("Assembly time: %0.3f seconds\n", (float) s_diff + ((float) ms_diff / 1000.0f));
#endif
	return exit_code;
}
コード例 #6
0
ファイル: Z80Assembler.cpp プロジェクト: saibotshamtul/spasm
STDMETHODIMP CZ80Assembler::ClearDefines()
{
	list_free(default_defines, true, NULL);
	default_defines = NULL;
	return S_OK;
}
コード例 #7
0
ファイル: plancat.c プロジェクト: CraigBryan/PostgresqlFun
/*
 * get_relation_info -
 *	  Retrieves catalog information for a given relation.
 *
 * Given the Oid of the relation, return the following info into fields
 * of the RelOptInfo struct:
 *
 *	min_attr	lowest valid AttrNumber
 *	max_attr	highest valid AttrNumber
 *	indexlist	list of IndexOptInfos for relation's indexes
 *	pages		number of pages
 *	tuples		number of tuples
 *
 * Also, initialize the attr_needed[] and attr_widths[] arrays.  In most
 * cases these are left as zeroes, but sometimes we need to compute attr
 * widths here, and we may as well cache the results for costsize.c.
 */
void
get_relation_info(Oid relationObjectId, RelOptInfo *rel)
{
	Index		varno = rel->relid;
	Relation	relation;
	bool		hasindex;
	List	   *indexinfos = NIL;

	/*
	 * Normally, we can assume the rewriter already acquired at least
	 * AccessShareLock on each relation used in the query.	However this will
	 * not be the case for relations added to the query because they are
	 * inheritance children of some relation mentioned explicitly. For them,
	 * this is the first access during the parse/rewrite/plan pipeline, and so
	 * we need to obtain and keep a suitable lock.
	 *
	 * XXX really, a suitable lock is RowShareLock if the relation is an
	 * UPDATE/DELETE target, and AccessShareLock otherwise.  However we cannot
	 * easily tell here which to get, so for the moment just get
	 * AccessShareLock always.	The executor will get the right lock when it
	 * runs, which means there is a very small chance of deadlock trying to
	 * upgrade our lock.
	 */
	if (rel->reloptkind == RELOPT_BASEREL)
		relation = heap_open(relationObjectId, NoLock);
	else
		relation = heap_open(relationObjectId, AccessShareLock);

	rel->min_attr = FirstLowInvalidHeapAttributeNumber + 1;
	rel->max_attr = RelationGetNumberOfAttributes(relation);

	Assert(rel->max_attr >= rel->min_attr);
	rel->attr_needed = (Relids *)
		palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
	rel->attr_widths = (int32 *)
		palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));

	/*
	 * Estimate relation size.
	 */
	estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
					  &rel->pages, &rel->tuples);

	/*
	 * Make list of indexes.  Ignore indexes on system catalogs if told to.
	 */
	if (IsIgnoringSystemIndexes() && IsSystemClass(relation->rd_rel))
		hasindex = false;
	else
		hasindex = relation->rd_rel->relhasindex;

	if (hasindex)
	{
		List	   *indexoidlist;
		ListCell   *l;

		indexoidlist = RelationGetIndexList(relation);

		foreach(l, indexoidlist)
		{
			Oid			indexoid = lfirst_oid(l);
			Relation	indexRelation;
			Form_pg_index index;
			IndexOptInfo *info;
			int			ncolumns;
			int			i;
			int16		amorderstrategy;

			/*
			 * Extract info from the relation descriptor for the index.
			 *
			 * Note that we take no lock on the index; we assume our lock on
			 * the parent table will protect the index's schema information.
			 * When and if the executor actually uses the index, it will take
			 * a lock as needed to protect the access to the index contents.
			 */
			indexRelation = index_open(indexoid);
			index = indexRelation->rd_index;

			info = makeNode(IndexOptInfo);

			info->indexoid = index->indexrelid;
			info->rel = rel;
			info->ncolumns = ncolumns = index->indnatts;

			/*
			 * Need to make classlist and ordering arrays large enough to put
			 * a terminating 0 at the end of each one.
			 */
			info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
			info->classlist = (Oid *) palloc0(sizeof(Oid) * (ncolumns + 1));
			info->ordering = (Oid *) palloc0(sizeof(Oid) * (ncolumns + 1));

			for (i = 0; i < ncolumns; i++)
			{
				info->classlist[i] = indexRelation->rd_indclass->values[i];
				info->indexkeys[i] = index->indkey.values[i];
			}

			info->relam = indexRelation->rd_rel->relam;
			info->amcostestimate = indexRelation->rd_am->amcostestimate;
			info->amoptionalkey = indexRelation->rd_am->amoptionalkey;

			/*
			 * Fetch the ordering operators associated with the index, if any.
			 */
			amorderstrategy = indexRelation->rd_am->amorderstrategy;
			if (amorderstrategy != 0)
			{
				int			oprindex = amorderstrategy - 1;

				for (i = 0; i < ncolumns; i++)
				{
					info->ordering[i] = indexRelation->rd_operator[oprindex];
					oprindex += indexRelation->rd_am->amstrategies;
				}
			}

			/*
			 * Fetch the index expressions and predicate, if any.  We must
			 * modify the copies we obtain from the relcache to have the
			 * correct varno for the parent relation, so that they match up
			 * correctly against qual clauses.
			 */
			info->indexprs = RelationGetIndexExpressions(indexRelation);
			info->indpred = RelationGetIndexPredicate(indexRelation);
			if (info->indexprs && varno != 1)
				ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
			if (info->indpred && varno != 1)
				ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
			info->predOK = false;		/* set later in indxpath.c */
			info->unique = index->indisunique;

			/*
			 * Estimate the index size.  If it's not a partial index, we lock
			 * the number-of-tuples estimate to equal the parent table; if it
			 * is partial then we have to use the same methods as we would for
			 * a table, except we can be sure that the index is not larger
			 * than the table.
			 */
			if (info->indpred == NIL)
			{
				info->pages = RelationGetNumberOfBlocks(indexRelation);
				info->tuples = rel->tuples;
			}
			else
			{
				estimate_rel_size(indexRelation, NULL,
								  &info->pages, &info->tuples);
				if (info->tuples > rel->tuples)
					info->tuples = rel->tuples;
			}

			index_close(indexRelation);

			indexinfos = lcons(info, indexinfos);
		}

		list_free(indexoidlist);
	}
コード例 #8
0
ファイル: main.c プロジェクト: huangxw/gx
static void *mainloop(void *thread_arg)
{
    struct REQUEST *conns = NULL;
    int curr_conn = 0;
    struct REQUEST      *req, *prev, *tmp;
    struct timeval      tv;
    int                 max;
    socklen_t           length;
    fd_set              rd, wr;

    for (; !termsig;) {
        if (got_sighup) {
            got_sighup = 0;
        }

        FD_ZERO(&rd);
        FD_ZERO(&wr);
        max = 0;

        /* add listening socket */
        if (curr_conn < max_conn) {
            FD_SET(slisten, &rd);
            max = slisten;
        }

        /* add connection sockets */
        for (req = conns; req != NULL; req = req->next) {
            switch (req->state) {
                case STATE_KEEPALIVE:
                case STATE_READ_HEADER:
                    FD_SET(req->fd, &rd);

                    if (req->fd > max) {
                        max = req->fd;
                    }

                    break;
                case STATE_WRITE_HEADER:
                case STATE_WRITE_BODY:
                case STATE_WRITE_FILE:
                case STATE_WRITE_RANGES:
                    FD_SET(req->fd, &wr);

                    if (req->fd > max) {
                        max = req->fd;
                    }

                    break;
            }
        }

        /* go! */
        tv.tv_sec  = keepalive_time;
        tv.tv_usec = 0;

        if (-1 == select(max + 1, &rd, &wr, NULL, (curr_conn > 0) ? &tv : NULL)) {
            perror("select");
            continue;
        }

        now = time(NULL);

        /* new connection ? */
        if (FD_ISSET(slisten, &rd)) {
            req = malloc(sizeof(struct REQUEST));

            if (NULL != req) {
                memset(req, 0, sizeof(struct REQUEST));

                if (-1 == (req->fd = accept(slisten, NULL, NULL))) {
                    if (EAGAIN != errno) {
                        free(req);
                    }
                } else {
                    close_on_exec(req->fd);
                    fcntl(req->fd, F_SETFL, O_NONBLOCK);
                    req->bfd = -1;
                    req->state = STATE_READ_HEADER;
                    req->ping = now;
                    req->next = conns;
                    conns = req;
                    curr_conn++;

                    /* Make sure the request has not been cancelled!
                     * Otherwise just ignore it. */
                    if (req) {
                        length = sizeof(req->peer);

                        if (-1 == getpeername(req->fd, (struct sockaddr *) & (req->peer), &length)) {
                            req->state = STATE_CLOSE;
                        }

                        getnameinfo((struct sockaddr *)&req->peer, length,
                                    req->peerhost, MAX_HOST,
                                    req->peerserv, MAX_MISC,
                                    NI_NUMERICHOST | NI_NUMERICSERV);
                        printf("%s:\tfd: %03d; connect from %s\n", get_time(), req->fd , req->peerhost);
                    }
                }
            }
        }

        /* check active connections */
        for (req = conns, prev = NULL; req != NULL;) {
            /* handle I/O */
            switch (req->state) {
                case STATE_KEEPALIVE:
                case STATE_READ_HEADER:

                    if (FD_ISSET(req->fd, &rd)) {
                        req->state = STATE_READ_HEADER;
                        read_request(req, 0);
                        req->ping = now;
                    }

                    break;
                case STATE_WRITE_HEADER:
                case STATE_WRITE_BODY:
                case STATE_WRITE_FILE:
                case STATE_WRITE_RANGES:

                    if (FD_ISSET(req->fd, &wr)) {
                        write_request(req);
                        req->ping = now;
                    }

                    break;
            }

            /* check timeouts */
            if (req->state == STATE_KEEPALIVE) {
                if (now > req->ping + keepalive_time || curr_conn > max_conn * 9 / 10) {
                    req->state = STATE_CLOSE;
                }
            } else if (req->state > 0) {
                if (now > req->ping + timeout) {
                    if (req->state == STATE_READ_HEADER) {
                        mkerror(req, 408, 0);
                    } else {
                        req->state = STATE_CLOSE;
                    }
                }
            }

            /* header parsing */
header_parsing:

            if (req->state == STATE_PARSE_HEADER) {
                parse_request(req);

                if (req->state == STATE_WRITE_HEADER) {
                    write_request(req);
                }
            }

            /* handle finished requests */
            if (req->state == STATE_FINISHED && !req->keep_alive) {
                req->state = STATE_CLOSE;
            }

            if (req->state == STATE_FINISHED) {
                req->auth[0]       = 0;
                req->if_modified   = NULL;
                req->if_unmodified = NULL;
                req->if_range      = NULL;
                req->range_hdr     = NULL;
                req->ranges        = 0;

                if (req->r_start) {
                    free(req->r_start);
                    req->r_start = NULL;
                }

                if (req->r_end) {
                    free(req->r_end);
                    req->r_end   = NULL;
                }

                if (req->r_head) {
                    free(req->r_head);
                    req->r_head  = NULL;
                }

                if (req->r_hlen) {
                    free(req->r_hlen);
                    req->r_hlen  = NULL;
                }

                list_free(&req->header);
                memset(req->mtime,   0, sizeof(req->mtime));

                if (req->bfd != -1) {
                    close(req->bfd);
                    req->bfd  = -1;
                }

                req->body      = NULL;
                req->written   = 0;
                req->head_only = 0;
                req->rh        = 0;
                req->rb        = 0;

                if (req->dir) {
                    free_dir(req->dir);
                    req->dir = NULL;
                }

                req->hostname[0] = 0;
                req->path[0]     = 0;
                req->query[0]    = 0;

                if (req->hdata == req->lreq) {
                    /* ok, wait for the next one ... */
                    req->state = STATE_KEEPALIVE;
                    req->hdata = 0;
                    req->lreq  = 0;
                } else {
                    /* there is a pipelined request in the queue ... */
                    req->state = STATE_READ_HEADER;
                    memmove(req->hreq, req->hreq + req->lreq,
                            req->hdata - req->lreq);
                    req->hdata -= req->lreq;
                    req->lreq  =  0;
                    read_request(req, 1);
                    goto header_parsing;
                }
            }

            /* connections to close */
            if (req->state == STATE_CLOSE) {
                close(req->fd);

                if (req->bfd != -1) {
                    close(req->bfd);
                }

                if (req->dir) {
                    free_dir(req->dir);
                }

                curr_conn--;
                printf("%s:\tfd: %03d; current connections: %d\n", get_time(), req->fd, curr_conn);
                /* unlink from list */
                tmp = req;

                if (prev == NULL) {
                    conns = req->next;
                    req = conns;
                } else {
                    prev->next = req->next;
                    req = req->next;
                }

                /* free memory  */
                if (tmp->r_start) {
                    free(tmp->r_start);
                }

                if (tmp->r_end) {
                    free(tmp->r_end);
                }

                if (tmp->r_head) {
                    free(tmp->r_head);
                }

                if (tmp->r_hlen) {
                    free(tmp->r_hlen);
                }

                list_free(&tmp->header);
                free(tmp);
            } else {
                prev = req;
                req = req->next;
            }
        }
    }

    return NULL;
}
コード例 #9
0
ファイル: hcache.c プロジェクト: Karlan88/xray
void
hcache_init()
{
    HCACHEDATA  cachedata, *c;
    FILE	*f;
    char	*version;
    int		header_count = 0;
    char*	hcachename;

    hcachehash = hashinit (sizeof (HCACHEDATA), "hcache");

    if (! (hcachename = cache_name()))
	return;

    if (! (f = fopen (hcachename, "rb" )))
	return;
    
    version = read_netstring(f);
    if (!version || strcmp(version, CACHE_FILE_VERSION)) {
	fclose(f);
	return;
    }

    while (1)
    {
	char* record_type;
	char *time_str;
	char *age_str;
	char *includes_count_str;
	char *hdrscan_count_str;
	int i, count;
	LIST *l;

	record_type = read_netstring(f);
	if (!record_type) {
	    fprintf(stderr, "invalid %s\n", hcachename);
	    goto bail;
	}
	if (!strcmp(record_type, CACHE_RECORD_END)) {
	    break;
	}
	if (strcmp(record_type, CACHE_RECORD_HEADER)) {
	    fprintf(stderr, "invalid %s with record separator <%s>\n",
		    hcachename, record_type ? record_type : "<null>");
	    goto bail;
	}
	
	c = &cachedata;
	    
	c->boundname = read_netstring(f);
	time_str = read_netstring(f);
	age_str = read_netstring(f);
	includes_count_str = read_netstring(f);
	
	if (!c->boundname || !time_str || !age_str
	    || !includes_count_str)
	{
	    fprintf(stderr, "invalid %s\n", hcachename);
	    goto bail;
	}

	c->time = atoi(time_str);
	c->age = atoi(age_str) + 1;

	count = atoi(includes_count_str);
	for (l = 0, i = 0; i < count; i++) {
	    char* s = read_netstring(f);
	    if (!s) {
		fprintf(stderr, "invalid %s\n", hcachename);
		goto bail;
	    }
	    l = list_new(l, s);
	}
	c->includes = l;

	hdrscan_count_str = read_netstring(f);
	if (!includes_count_str) {
	    list_free(c->includes);
	    fprintf(stderr, "invalid %s\n", hcachename);
	    goto bail;
	}

	count = atoi(hdrscan_count_str);
	for (l = 0, i = 0; i < count; i++) {
	    char* s = read_netstring(f);
	    if (!s) {
		fprintf(stderr, "invalid %s\n", hcachename);
		goto bail;
	    }
	    l = list_new(l, s);
	}
	c->hdrscan = l;

	if (!hashenter(hcachehash, (HASHDATA **)&c)) {
	    fprintf(stderr, "can't insert header cache item, bailing on %s\n",
		    hcachename);
	    goto bail;
	}

	c->next = hcachelist;
	hcachelist = c;

	header_count++;
    }

    if (DEBUG_HEADER) {
	printf("hcache read from file %s\n", hcachename);
    }
    
 bail:
    fclose(f);
}
コード例 #10
0
ファイル: core.c プロジェクト: jreed47/FINS-Framework
void core_main(uint8_t *envi_name, uint8_t *stack_name, uint32_t seed) {
	PRINT_IMPORTANT("Core Initiation: Starting ************");

#ifdef BUILD_FOR_ANDROID
	library_dummies();
#endif

	register_to_signal(SIGRTMIN);
	if (seed == DEFAULT_SEED_NUM) {
		srand((unsigned int) time(NULL));
	} else {
		srand(seed);
	}

	sem_init(&global_control_serial_sem, 0, 1); //TODO remove after gen_control_serial_num() converted to RNG

	signal(SIGINT, core_termination_handler); //register termination handler

	int status;
	int i, j, k;
	metadata_element *list_elem;
	int list_num;
	metadata_element *elem;
	metadata_element *ip_elem;
	uint32_t ip_num;

	//######################################################################
	overall = (struct fins_overall *) secure_malloc(sizeof(struct fins_overall));
	sem_init(&overall->sem, 0, 1);

	//######################################################################
	overall->envi = (struct envi_record *) secure_malloc(sizeof(struct envi_record));

	PRINT_IMPORTANT("########################## loading environment: '%s'", (char *) envi_name);
	metadata *meta_envi = (metadata *) secure_malloc(sizeof(metadata));
	metadata_create(meta_envi);

	status = config_read_file(meta_envi, (char *) envi_name);
	if (status == META_FALSE) {
		PRINT_ERROR("file='%s', %s:%d - %s\n", envi_name, config_error_file(meta_envi), config_error_line(meta_envi), config_error_text(meta_envi));
		metadata_destroy(meta_envi);
		PRINT_ERROR("todo error");
		exit(-1);
	}

	//############# if_list
	PRINT_IMPORTANT("############# Configuring List of Interfaces");
	overall->envi->if_list = list_create(MAX_INTERFACES);

	list_elem = config_lookup(meta_envi, "environment.interfaces");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	int32_t if_index;
	uint8_t *name;
	uint64_t mac;
	uint32_t mode;
	uint32_t mtu;
	uint32_t flags;

	struct if_record *ifr;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(elem, "name", (const char **) &name);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int64(elem, "mac", (long long *) &mac);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "mode", (int *) &mode);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "mtu", (int *) &mtu);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "flags", (int *) &flags);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		//#############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr == NULL) {
			ifr = (struct if_record *) secure_malloc(sizeof(struct if_record));
			ifr->index = if_index;
			strcpy((char *) ifr->name, (char *) name);
			ifr->mac = mac;

			ifr->mode = (uint8_t) mode;
			ifr->mtu = mtu;
			ifr->flags = flags;

			ifr->addr_list = list_create(MAX_FAMILIES);

			if (list_has_space(overall->envi->if_list)) {
				PRINT_IMPORTANT("Adding interface: ifr=%p, index=%u, name='%s', mac=0x%012llx", ifr, ifr->index, ifr->name, ifr->mac);
				list_append(overall->envi->if_list, ifr);
			} else {
				//TODO error
				PRINT_ERROR("todo error");
				exit(-1);
			}

			if (flags & IFF_LOOPBACK) {
				overall->envi->if_loopback = ifr;
			}
		} else {
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}
	PRINT_IMPORTANT("if_list: list=%p, max=%u, len=%u", overall->envi->if_list, overall->envi->if_list->max, overall->envi->if_list->len);

	//############# if_loopback
	PRINT_IMPORTANT("############# Configuring Loopback Interface");
	if (overall->envi->if_loopback != NULL) {
		PRINT_IMPORTANT("loopback: name='%s', addr_list->len=%u", overall->envi->if_loopback->name, overall->envi->if_loopback->addr_list->len);
	} else {
		PRINT_WARN("todo error");
	}

	//############# if_main
	PRINT_IMPORTANT("############# Configuring Main Interface");
	uint32_t if_main;

	status = config_lookup_int(meta_envi, "environment.main_interface", (int *) &if_main);
	if (status == META_FALSE) {
		PRINT_ERROR("todo error");
		exit(-1);
	}

	overall->envi->if_main = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_main);
	if (overall->envi->if_main != NULL) {
		PRINT_IMPORTANT("main interface: name='%s', addr_list->len=%u", overall->envi->if_main->name, overall->envi->if_main->addr_list->len);
		if (!ifr_running_test(overall->envi->if_main)) {
			PRINT_WARN("!!!!Selected main interface is NOT running: name='%s', flagx->len=0x%x", overall->envi->if_main->name, overall->envi->if_main->flags);
		}
	} else {
		PRINT_WARN("todo error");
	}

	//############# addr_list
	PRINT_IMPORTANT("############# Configuring List of Host Addresses");
	//overall->envi->addr_list = list_create(MAX_INTERFACES * MAX_FAMILIES); //TODO use?

	list_elem = config_lookup(meta_envi, "environment.addresses");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	uint32_t family; //atm only AF_INET, but eventually also AF_INET6
	uint32_t ip[4]; //SIOCGIFADDR //ip
	uint32_t mask[4]; //SIOCGIFNETMASK //mask
	uint32_t gw[4]; //? //(ip & mask) | 1;
	uint32_t bdc[4]; //SIOCGIFBRDADDR //(ip & mask) | ~mask
	uint32_t dst[4]; //SIOCGIFDSTADDR //dst

	struct addr_record *addr;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "if_index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "family", (int *) &family);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		ip_elem = config_setting_get_member(elem, "ip");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			ip[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "mask");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "gw");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "bdc");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			bdc[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "dst");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		//############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr != NULL) {
			if (ifr_running_test(ifr)) {
				if (family == AF_INET) {
					addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v4);
				} else {
					addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v6);
				}

				if (addr == NULL) {
					addr = (struct addr_record *) secure_malloc(sizeof(struct addr_record));
					addr->if_index = if_index;
					addr->family = AF_INET;

					if (family == AF_INET) {
						addr4_set_ip(&addr->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3]));
						addr4_set_ip(&addr->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3]));
						addr4_set_ip(&addr->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3]));
						addr4_set_ip(&addr->bdc, IP4_ADR_P2H(bdc[0], bdc[1], bdc[2], bdc[3]));
						addr4_set_ip(&addr->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3]));
					} else if (family == AF_INET6) {
						//TODO
						//addr_set_addr6(&addr->ip, ip);
						PRINT_WARN("todo");
					} else {
						//TODO error?
						PRINT_ERROR("todo error");
						exit(-1);
					}

					if (list_has_space(ifr->addr_list)) {
						PRINT_IMPORTANT(
								"Adding address: if_index=%d, family=%u, ip='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', bdc='%u.%u.%u.%u', dst='%u.%u.%u.%u'",
								if_index, family, ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], bdc[0], bdc[1], bdc[2], bdc[3], dst[0], dst[1], dst[2], dst[3]);
						list_append(ifr->addr_list, addr);
					} else {
						//TODO error
						PRINT_ERROR("todo error");
						exit(-1);
					}
				} else {
					//TODO error
					PRINT_ERROR("todo: previous address found, replace or add new?");
				}
			} else {
				if (family == AF_INET) {
					PRINT_WARN(
							"Ignoring address, no active interface: if_index=%d, family=%u, ip='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', bdc='%u.%u.%u.%u', dst='%u.%u.%u.%u'",
							if_index, family, ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], bdc[0], bdc[1], bdc[2], bdc[3], dst[0], dst[1], dst[2], dst[3]);
				} else if (family == AF_INET6) {
					//TODO
					PRINT_WARN("todo");
				} else {
					//TODO error?
					PRINT_ERROR("todo error");
					exit(-1);
				}
			}
		} else {
			//TODO error
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}

	//############# route_list
	PRINT_IMPORTANT("############# Configuring List of Routes");
	overall->envi->route_list = list_create(MAX_ROUTES);

	list_elem = config_lookup(meta_envi, "environment.routes");
	if (list_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	list_num = config_setting_length(list_elem);

	uint32_t metric; //SIOCGIFMETRIC
	uint32_t timeout;
	//struct timeval route_stamp;

	struct route_record *route;

	for (i = 0; i < list_num; i++) {
		elem = config_setting_get_elem(list_elem, i);
		if (elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "if_index", (int *) &if_index);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "family", (int *) &family);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		ip_elem = config_setting_get_member(elem, "dst");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "mask");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		ip_elem = config_setting_get_member(elem, "gw");
		if (ip_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		ip_num = config_setting_length(ip_elem);

		for (j = 0; j < ip_num; j++) {
			gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j);
		}

		status = config_setting_lookup_int(elem, "metric", (int *) &metric);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(elem, "timeout", (int *) &timeout);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		//############
		ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index);
		if (ifr != NULL) {
			if (ifr_running_test(ifr)) {
				route = (struct route_record *) secure_malloc(sizeof(struct route_record));
				route->if_index = if_index;
				route->family = family;

				if (family == AF_INET) {
					addr4_set_ip(&route->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3]));
					addr4_set_ip(&route->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3]));
					addr4_set_ip(&route->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3]));
					//addr4_set_addr(&route->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3]));
				} else if (family == AF_INET6) {
					//TODO
					//addr_set_addr6(&route->ip, ip);
				} else {
					//TODO error?
				}

				route->metric = metric;
				route->timeout = timeout;

				if (list_has_space(overall->envi->route_list)) {
					PRINT_IMPORTANT( "Adding route: if_index=%d, family=%u, dst='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', metric=%u, timeout=%u",
							route->if_index, route->family, dst[0], dst[1], dst[2], dst[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], metric, timeout);
					list_append(overall->envi->route_list, route);
				} else {
					//TODO error
					PRINT_ERROR("todo error");
					exit(-1);
				}
			} else {
				if (family == AF_INET) {
					PRINT_WARN(
							"Ignoring route, no active interface: if_index=%d, family=%u, dst='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', metric=%u, timeout=%u",
							if_index, family, dst[0], dst[1], dst[2], dst[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], metric, timeout);
				} else if (family == AF_INET6) {
					//TODO
					PRINT_WARN("todo");
				} else {
					//TODO error?
					PRINT_ERROR("todo error");
				}
			}
		}
	}
	PRINT_IMPORTANT("route_list: list=%p, max=%u, len=%u", overall->envi->route_list, overall->envi->route_list->max, overall->envi->route_list->len);
	metadata_destroy(meta_envi);

	//######################################################################
	PRINT_IMPORTANT("########################## loading stack: '%s'", (char *) stack_name);
	metadata *meta_stack = (metadata *) secure_malloc(sizeof(metadata));
	metadata_create(meta_stack);

	status = config_read_file(meta_stack, (char *) stack_name);
	if (status == META_FALSE) {
		PRINT_ERROR("file='%s', %s:%d - %s\n", stack_name, config_error_file(meta_stack), config_error_line(meta_stack), config_error_text(meta_stack));
		metadata_destroy(meta_stack);
		PRINT_ERROR("todo error");
		exit(-1);
	}

	//############# module_list
	PRINT_IMPORTANT("############# Configuring List of Modules");
	overall->lib_list = list_create(MAX_MODULES);
	memset(overall->modules, 0, MAX_MODULES * sizeof(struct fins_module *));
	overall->admin_list = list_create(MAX_MODULES);
	struct linked_list *mt_list = list_create(MAX_MODULES);

	uint8_t base_path[100];
	memset((char *) base_path, 0, 100);
#ifdef BUILD_FOR_ANDROID
	strcpy((char *) base_path, FINS_TMP_ROOT);
	//strcpy((char *) base_path, ".");
#else
	strcpy((char *) base_path, ".");
#endif

	metadata_element *mods_elem = config_lookup(meta_stack, "stack.modules");
	if (mods_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	int mods_num = config_setting_length(mods_elem);

	metadata_element *mod_elem;
	uint32_t mod_id;
	uint8_t *mod_lib;
	uint8_t *mod_name;
	metadata_element *flows_elem;
	uint32_t mod_flows[MAX_MOD_FLOWS];
	uint32_t mod_flows_num;
	metadata_element *mod_params;
	metadata_element *mod_admin;

	struct fins_library *library;
	struct fins_module *module;
	struct fins_module_table *mt;

	for (i = 0; i < mods_num; i++) {
		mod_elem = config_setting_get_elem(mods_elem, i);
		if (mod_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(mod_elem, "id", (int *) &mod_id);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(mod_elem, "lib", (const char **) &mod_lib);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_string(mod_elem, "name", (const char **) &mod_name);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		flows_elem = config_setting_get_member(mod_elem, "flows");
		if (flows_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		mod_flows_num = config_setting_length(flows_elem);

		for (j = 0; j < mod_flows_num; j++) {
			mod_flows[j] = (uint32_t) config_setting_get_int_elem(flows_elem, j);
		}

		mod_params = config_setting_get_member(mod_elem, "params");
		if (mod_params == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		mod_admin = config_setting_get_member(mod_elem, "admin");
		PRINT_DEBUG("admin=%u", mod_admin != NULL);

		//############
		library = (struct fins_library *) list_find1(overall->lib_list, library_name_test, mod_lib);
		if (library == NULL) {
#ifdef BUILD_FOR_ANDROID
			library = library_fake_load(mod_lib, base_path);
#else
			library = library_load(mod_lib, base_path);
			//library = library_fake_load(mod_lib, base_path);
#endif
			if (library == NULL) {
				PRINT_ERROR("Failed in loading library: lib='%s', base_path='%s'", mod_lib, base_path);
				exit(-1);
			}

			if (list_has_space(overall->lib_list)) {
				PRINT_IMPORTANT("Adding library: library=%p, name='%s'", library, library->name);
				list_append(overall->lib_list, library);
			} else {
				PRINT_ERROR("Failed in init sequence, too many libraries: lib_list->len=%u", overall->lib_list->len);
				exit(-1);
			}
		}

		module = library->create(i, mod_id, mod_name);
		if (module == NULL) {
			//TODO error
			PRINT_ERROR("Failed to create module: library=%p, index=%u, id=%u, name='%s'", library, i, mod_id, mod_name);
			exit(-1);
		}
		library->num_mods++;

		//TODO move flow to update? or links here?
		status = module->ops->init(module, mod_params, overall->envi); //TODO merge init into create?
		if (status != 0) {
			overall->modules[i] = module;

			if (module->flows_max < mod_flows_num) {
				PRINT_ERROR("Loading module parameters failed, too many flows for this library: specified=%u, max=%u", mod_flows_num, module->flows_max);
				exit(-1);
			}

			mt = (struct fins_module_table *) secure_malloc(sizeof(struct fins_module_table));
			mt->flows_num = mod_flows_num;

			for (j = 0; j < mt->flows_num; j++) {
				mt->flows[j].link_id = mod_flows[j];
			}
			list_append(mt_list, mt);

			if (mod_admin != NULL) {
				PRINT_IMPORTANT("Adding admin module: module=%p, lib='%s', name='%s', id=%d, index=%u",
						module, module->lib, module->name, module->id, module->index);
				list_append(overall->admin_list, module);
			} else {
				PRINT_IMPORTANT("Adding module: module=%p, lib='%s', name='%s', id=%d, index=%u", module, module->lib, module->name, module->id, module->index);
			}
		} else {
			PRINT_ERROR("Initialization of module failed: module=%p, lib='%s', name='%s', flows_num=%u, flows=%p, params=%p, envi=%p",
					module, module->lib, module->name, mod_flows_num, mod_flows, mod_params, overall->envi);
			exit(-1);
		}

		//free(mod_lib); //don't free, string from libconfig points to metadata memory
		//free(mod_name);
	}

	//############# admin_list //TODO change to admin_list?
	list_for_each1(overall->admin_list, assign_overall, overall);

	//############# linking_list
	PRINT_IMPORTANT("############# Configuring Linking Table");
	overall->link_list = list_create(MAX_TABLE_LINKS);

	metadata_element *links_elem = config_lookup(meta_stack, "stack.links");
	if (links_elem == NULL) {
		PRINT_ERROR("todo error");
		exit(-1);
	}
	int links_num = config_setting_length(links_elem);

	metadata_element *link_elem;
	uint32_t link_id;
	uint32_t link_src;
	metadata_element *dsts_elem;
	uint32_t link_dsts[MAX_MODULES];
	int link_dsts_num;

	struct link_record *link;

	for (i = 0; i < links_num; i++) {
		link_elem = config_setting_get_elem(links_elem, i);
		if (link_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(link_elem, "id", (int *) &link_id);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		status = config_setting_lookup_int(link_elem, "src", (int *) &link_src);
		if (status == META_FALSE) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		dsts_elem = config_setting_get_member(link_elem, "dsts");
		if (dsts_elem == NULL) {
			PRINT_ERROR("todo error");
			exit(-1);
		}
		link_dsts_num = config_setting_length(dsts_elem);

		for (j = 0; j < link_dsts_num; j++) {
			link_dsts[j] = (uint32_t) config_setting_get_int_elem(dsts_elem, j);
		}

		//############
		link = (struct link_record *) secure_malloc(sizeof(struct link_record));
		link->id = link_id;

		//module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_src);
		link->src_index = -1;
		for (j = 0; j < MAX_MODULES; j++) {
			if (overall->modules[j] != NULL && overall->modules[j]->id == link_src) {
				link->src_index = overall->modules[j]->index;
			}
		}
		if (link->src_index == -1) {
			PRINT_ERROR("todo error");
			exit(-1);
		}

		link->dsts_num = link_dsts_num;
		for (j = 0; j < link_dsts_num; j++) {
			//module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_dsts[j]);
			link->dsts_index[j] = -1;
			for (k = 0; k < MAX_MODULES; k++) {
				if (overall->modules[k] != NULL && overall->modules[k]->id == link_dsts[j]) {
					link->dsts_index[j] = overall->modules[k]->index;
				}
			}
			if (link->dsts_index[j] == (uint32_t) -1) {
				PRINT_ERROR("todo error");
				exit(-1);
			}
		}

		if (list_has_space(overall->link_list)) {
			uint8_t buf[1000];
			uint8_t *pt = buf;
			int ret;
			int i;
			for (i = 0; i < link->dsts_num; i++) {
				ret = sprintf((char *) pt, "%u, ", link->dsts_index[i]);
				pt += ret;
			}
			*pt = '\0';

			PRINT_IMPORTANT("Adding link: link=%p, id=%u, src_index=%u, dsts_num=%u, ['%s']", link, link->id, link->src_index, link->dsts_num, buf);
			list_append(overall->link_list, link);
		} else {
			//TODO error
			PRINT_ERROR("todo error");
			exit(-1);
		}
	}
	metadata_destroy(meta_stack);

	//######################################################################
	PRINT_IMPORTANT("############# Updating modules with correct flows & links");
	//send out subset of linking table to each module as update
	//TODO table subset update

	metadata *meta_update;
	struct finsFrame *ff_update;

	for (i = 0; i < MAX_MODULES; i++) {
		if (overall->modules[i] != NULL) {
			mt = (struct fins_module_table *) list_remove_front(mt_list);
			mt->link_list = list_filter1(overall->link_list, link_src_test, &overall->modules[i]->index, link_clone); //was link_involved_test, decide which better?
			PRINT_IMPORTANT("Module link table subset: name='%s' index=%d, link_list=%p, len=%d",
					overall->modules[i]->name, i, mt->link_list, mt->link_list->len);

			for (j = 0; j < mt->flows_num; j++) {
				mt->flows[j].link = (struct link_record *) list_find1(mt->link_list, link_id_test, &mt->flows[j].link_id);
			}

//#ifdef DEBUG
			uint8_t buf[1000];
			uint8_t *pt = buf;
			int ret;
			for (j = 0; j < mt->flows_num; j++) {
				ret = sprintf((char *) pt, "%u (%p), ", mt->flows[j].link_id, mt->flows[j].link);
				pt += ret;
			}
			*pt = '\0';
			PRINT_IMPORTANT("Module flows: num=%u, ['%s']", mt->flows_num, buf);

			list_for_each(mt->link_list, link_print);
//#endif

			meta_update = (metadata *) secure_malloc(sizeof(metadata));
			metadata_create(meta_update);

			ff_update = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame));
			ff_update->dataOrCtrl = FF_CONTROL;
			ff_update->destinationID = i;
			ff_update->metaData = meta_update;

			ff_update->ctrlFrame.sender_id = 0;
			ff_update->ctrlFrame.serial_num = gen_control_serial_num();
			ff_update->ctrlFrame.opcode = CTRL_SET_PARAM;
			ff_update->ctrlFrame.param_id = MOD_SET_PARAM_DUAL;

			ff_update->ctrlFrame.data_len = sizeof(struct fins_module_table);
			ff_update->ctrlFrame.data = (uint8_t *) mt;

			module_to_switch(overall->modules[0], ff_update);
			//module_set_param_dual(overall->modules[i], ff_update);
		}
	}
	list_free(mt_list, free);

	//############ say by this point envi var completely init'd
	//assumed always connect/init to switch first

	pthread_attr_init(&overall->attr);
	pthread_attr_setdetachstate(&overall->attr, PTHREAD_CREATE_JOINABLE);

	PRINT_IMPORTANT("############# Calling run() for modules");

	for (i = 0; i < MAX_MODULES; i++) {
		if (overall->modules[i] != NULL) {
			overall->modules[i]->ops->run(overall->modules[i], &overall->attr);
		}
	}

	PRINT_IMPORTANT("Core Initiation: Finished ************");
}
コード例 #11
0
bt_status_t btsock_sco_cleanup(void) {
  list_free(sco_sockets);
  sco_sockets = NULL;
  pthread_mutex_destroy(&lock);
  return BT_STATUS_SUCCESS;
}
コード例 #12
0
ファイル: variable.c プロジェクト: cpascal/af-cpp
static void delete_var_( void * xvar, void * data )
{
    VARIABLE * v = (VARIABLE *)xvar;
    object_free( v->symbol );
    list_free( v-> value );
}
コード例 #13
0
ファイル: tracegdb.c プロジェクト: zorgnax/libcarp
/* Parses gdb's stdout fd after requesting a backtrace. The result is stored
in a linked list of FuncInfo structures.  */
static List *
parse_stack_trace (int gdb) {
    int i;
    int parentheses_are_off = 0;
    char c;
    char buf[4096];
    List *stack = NULL;
    FuncInfo *f;
    List *libs = NULL;
    SharedLib *lib;
    
    enum {
        NONE,
        ADDR,
        FUNC,
        ARGS,
        FILE,
        LINE,
        LIB,
        QUOTE,
        FROMADDR,
        TOADDR,
        SYMS,
        SONAME
    } state = NONE, prev_state = NONE;
    
    while (read(gdb, &c, 1)) {
        switch (state) {
        case NONE:
            if (c == '#') {
                f = calloc(sizeof (FuncInfo), 1);
                while (read(gdb, &c, 1))
                    if (!isdigit(c))
                        break;
                while (read(gdb, &c, 1))
                    if (!isspace(c)) {
                        buf[0] = c;
                        i = 1;
                        state = isdigit(c) ? ADDR : FUNC;
                        break;
                    }
            }
            else if (!stack && c == '0') {
                lib = calloc(sizeof (SharedLib), 1);
                state = FROMADDR;
                buf[0] = c;
                i = 1;
            }
            else if (stack && c == '(') {
                read(gdb, buf, 3);
                if (!strncmp(buf, "gdb", 3))
                    goto done;
            }
            else if (!stack && c == 'N') {
                read(gdb, buf, 7);
                if (!strncmp(buf, "o stack", 7))
                    goto done;
            }
            break;
        case FROMADDR:
            if (!isspace(c)) {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                sscanf(buf, "%p", &lib->from);
                read(gdb, buf, 1);
                state = TOADDR;
            }
            break;
        case TOADDR:
            if (!isspace(c)) {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                sscanf(buf, "%p", &lib->to);
                read(gdb, buf, 1);
                state = SYMS;
            }
            break;
        case SYMS:
            if (!isspace(c)) {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                if (eq(buf, "Yes"))
                    lib->readsyms = 1;
                read(gdb, buf, 3);
                if (strncmp(buf, "(*)", 3))
                    lib->dbinfo = 1;
                while (read(gdb, &c, 1))
                    if (!isspace(c)) {
                        buf[0] = c;
                        i = 1;
                        break;
                    }
                state = SONAME;
            }
            break;
        case SONAME:
            if (c != '\n') {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                lib->name = strdup(buf);
                libs = list_push(libs, lib);
                state = NONE;
            }
            break;
        case ADDR:
            if (!isspace(c)) {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                sscanf(buf, "%p", &f->addr);
                f->lib = get_lib_name(libs, f->addr);
                read(gdb, buf, 3);
                state = FUNC;
            }
            break;
        case FUNC:
            if (!isspace(c)) {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                f->func = strdup(buf);
                state = ARGS;
            }
            break;
        case ARGS:
            buf[i++] = c;
            if (c == '(')
                parentheses_are_off++;
            else if (c == ')') {
                parentheses_are_off--;
                if (parentheses_are_off)
                    continue;
                buf[i] = 0;
                i = 0;
                f->args = strdup(buf);
                read(gdb, &c, 1);
                if (c == '\n') {
                    stack = list_push(stack, f);
                    state = NONE;
                    break;
                }
                read(gdb, buf, 3);
                if (!strncmp(buf, "at ", 3)) {
                    state = FILE;
                }
                else if (!strncmp(buf, "fro", 3)) {
                    state = LIB;
                    read(gdb, buf, 2);
                }
                else {
                    free(f);
                    state = NONE;
                }
            }
            else if (c == '"') {
                prev_state = ARGS;
                state = QUOTE;
            }
            break;
        case QUOTE:
            buf[i++] = c;
            if (c == '\\') {
                read(gdb, &c, 1);
                buf[i++] = c;
            }
            else if (c == '"')
                state = prev_state;
            break;
        case LIB:
            if (!isspace(c)) {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                if (!f->lib)
                    f->lib = strdup(buf);
                stack = list_push(stack, f);
                state = NONE;
            }
            break;
        case FILE:
            if (c != ':') {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                f->file = strdup(buf);
                state = LINE;
            }
            break;
        case LINE:
            if (isdigit(c)) {
                buf[i++] = c;
            }
            else {
                buf[i] = 0;
                i = 0;
                f->line = atoi(buf);
                stack = list_push(stack, f);
                state = NONE;
            }
            break;
        }
    }
    
    done:
    list_free(libs, shared_lib_free);
    return stack;
}
コード例 #14
0
ファイル: variable.c プロジェクト: PengJi/gpdb-comments
/*
 * assign_datestyle: GUC assign_hook for datestyle
 */
const char *
assign_datestyle(const char *value, bool doit, GucSource source)
{
	int			newDateStyle = DateStyle;
	int			newDateOrder = DateOrder;
	bool		have_style = false;
	bool		have_order = false;
	bool		ok = true;
	char	   *rawstring;
	char	   *result;
	List	   *elemlist;
	ListCell   *l;

	/* Need a modifiable copy of string */
	rawstring = pstrdup(value);

	/* Parse string into list of identifiers */
	if (!SplitIdentifierString(rawstring, ',', &elemlist))
	{
		/* syntax error in list */
		pfree(rawstring);
		list_free(elemlist);
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("invalid list syntax for parameter \"datestyle\"")));
		return NULL;
	}

	foreach(l, elemlist)
	{
		char	   *tok = (char *) lfirst(l);

		/* Ugh. Somebody ought to write a table driven version -- mjl */

		if (pg_strcasecmp(tok, "ISO") == 0)
		{
			if (have_style && newDateStyle != USE_ISO_DATES)
				ok = false;		/* conflicting styles */
			newDateStyle = USE_ISO_DATES;
			have_style = true;
		}
		else if (pg_strcasecmp(tok, "SQL") == 0)
		{
			if (have_style && newDateStyle != USE_SQL_DATES)
				ok = false;		/* conflicting styles */
			newDateStyle = USE_SQL_DATES;
			have_style = true;
		}
		else if (pg_strncasecmp(tok, "POSTGRES", 8) == 0)
		{
			if (have_style && newDateStyle != USE_POSTGRES_DATES)
				ok = false;		/* conflicting styles */
			newDateStyle = USE_POSTGRES_DATES;
			have_style = true;
		}
		else if (pg_strcasecmp(tok, "GERMAN") == 0)
		{
			if (have_style && newDateStyle != USE_GERMAN_DATES)
				ok = false;		/* conflicting styles */
			newDateStyle = USE_GERMAN_DATES;
			have_style = true;
			/* GERMAN also sets DMY, unless explicitly overridden */
			if (!have_order)
				newDateOrder = DATEORDER_DMY;
		}
		else if (pg_strcasecmp(tok, "YMD") == 0)
		{
			if (have_order && newDateOrder != DATEORDER_YMD)
				ok = false;		/* conflicting orders */
			newDateOrder = DATEORDER_YMD;
			have_order = true;
		}
		else if (pg_strcasecmp(tok, "DMY") == 0 ||
				 pg_strncasecmp(tok, "EURO", 4) == 0)
		{
			if (have_order && newDateOrder != DATEORDER_DMY)
				ok = false;		/* conflicting orders */
			newDateOrder = DATEORDER_DMY;
			have_order = true;
		}
		else if (pg_strcasecmp(tok, "MDY") == 0 ||
				 pg_strcasecmp(tok, "US") == 0 ||
				 pg_strncasecmp(tok, "NONEURO", 7) == 0)
		{
			if (have_order && newDateOrder != DATEORDER_MDY)
				ok = false;		/* conflicting orders */
			newDateOrder = DATEORDER_MDY;
			have_order = true;
		}
		else if (pg_strcasecmp(tok, "DEFAULT") == 0)
		{
			/*
			 * Easiest way to get the current DEFAULT state is to fetch the
			 * DEFAULT string from guc.c and recursively parse it.
			 *
			 * We can't simply "return assign_datestyle(...)" because we need
			 * to handle constructs like "DEFAULT, ISO".
			 */
			int			saveDateStyle = DateStyle;
			int			saveDateOrder = DateOrder;
			const char *subval;

			subval = assign_datestyle(GetConfigOptionResetString("datestyle"),
									  true, source);
			if (!have_style)
				newDateStyle = DateStyle;
			if (!have_order)
				newDateOrder = DateOrder;
			DateStyle = saveDateStyle;
			DateOrder = saveDateOrder;
			if (!subval)
			{
				ok = false;
				break;
			}
			/* Here we know that our own return value is always malloc'd */
			/* when doit is true */
			free((char *) subval);
		}
		else
		{
			ereport(GUC_complaint_elevel(source),
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("unrecognized \"datestyle\" key word: \"%s\"",
							tok)));
			ok = false;
			break;
		}
	}
コード例 #15
0
ファイル: file_io.c プロジェクト: EleanorRobson/oracc
void
file_free_names ()
{
  list_free (file_name_list, list_xfree);
  file_name_list = NULL;
}
コード例 #16
0
ファイル: hcache.c プロジェクト: Karlan88/xray
LIST *
hcache (TARGET *t, int rec, regexp *re[], LIST *hdrscan)
{
    HCACHEDATA  cachedata, *c = &cachedata;
    LIST 	*l = 0;

    ++queries;

    c->boundname = t->boundname;

    if (hashcheck (hcachehash, (HASHDATA **) &c))
    {
	if (c->time == t->time)
	{
	    LIST *l1 = hdrscan, *l2 = c->hdrscan;
	    while (l1 && l2) {
		if (l1->string != l2->string) {
		    l1 = NULL;
		} else {
		    l1 = list_next(l1);
		    l2 = list_next(l2);
		}
	    }
	    if (l1 || l2) {
		if (DEBUG_HEADER)
		    printf("HDRSCAN out of date in cache for %s\n",
			   t->boundname);

		printf("HDRSCAN out of date for %s\n", t->boundname);
		printf(" real  : ");
		list_print(hdrscan);
		printf("\n cached: ");
		list_print(c->hdrscan);
		printf("\n");

		list_free(c->includes);
		list_free(c->hdrscan);
		c->includes = 0;
		c->hdrscan = 0;
	    } else {
		if (DEBUG_HEADER)
		    printf ("using header cache for %s\n", t->boundname);
		c->age = 0;
		++hits;
		l = list_copy (0, c->includes);
		return l;
	    }
	} else {
	    if (DEBUG_HEADER)
	        printf ("header cache out of date for %s\n", t->boundname);
	    list_free (c->includes);
	    list_free(c->hdrscan);
	    c->includes = 0;
	    c->hdrscan = 0;
	}
    } else {
	if (hashenter (hcachehash, (HASHDATA **)&c)) {
	    c->boundname = newstr (c->boundname);
	    c->next = hcachelist;
	    hcachelist = c;
	}
    }

    /* 'c' points at the cache entry.  Its out of date. */

    l = headers1 (0, t->boundname, rec, re);

    c->time = t->time;
    c->age = 0;
    c->includes = list_copy (0, l);
    c->hdrscan = list_copy(0, hdrscan);

    return l;
}
コード例 #17
0
ファイル: Z80Assembler.cpp プロジェクト: saibotshamtul/spasm
STDMETHODIMP CZ80Assembler::ClearIncludeDirectories()
{
	list_free(include_dirs, true, NULL);
	include_dirs = NULL;
	return S_OK;
}
コード例 #18
0
ファイル: main.c プロジェクト: KnightOS/scas
int main(int argc, char **argv) {
	init_scas_runtime();
	parse_arguments(argc, argv);
	init_log(scas_runtime.verbosity);
	validate_scas_runtime();
	instruction_set_t *instruction_set = find_inst();
	scas_log(L_INFO, "Loaded instruction set: %s", instruction_set->arch);
	list_t *include_path = split_include_path();
	list_t *errors = create_list();
	list_t *warnings = create_list();

	list_t *objects = create_list();
	int i;
	for (i = 0; i < scas_runtime.input_files->length; ++i) {
		scas_log(L_INFO, "Assembling input file: '%s'", scas_runtime.input_files->items[i]);
		indent_log();
		FILE *f;
		if (strcasecmp(scas_runtime.input_files->items[i], "-") == 0) {
			f = stdin;
		} else {
			f = fopen(scas_runtime.input_files->items[i], "r");
		}
		if (!f) {
			scas_abort("Unable to open '%s' for assembly.", scas_runtime.input_files->items[i]);
		}
		char magic[7];
		bool is_object = false;
		if (fread(magic, sizeof(char), 7, f) == 7) {
			if (strncmp("SCASOBJ", magic, 7) == 0) {
				is_object = true;
			}
		}
		fseek(f, 0L, SEEK_SET);

		object_t *o;
		if (is_object) {
			scas_log(L_INFO, "Loading object file '%s'", scas_runtime.input_files->items[i]);
			o = freadobj(f, scas_runtime.input_files->items[i]);
		} else {
			assembler_settings_t settings = {
				.include_path = include_path,
				.set = instruction_set,
				.errors = errors,
				.warnings = warnings,
				.macros = scas_runtime.macros,
			};
			o = assemble(f, scas_runtime.input_files->items[i], &settings);
			fclose(f);
			scas_log(L_INFO, "Assembler returned %d errors, %d warnings for '%s'",
					errors->length, warnings->length, scas_runtime.input_files->items[i]);
		}
		list_add(objects, o);
		deindent_log();
	}

	scas_log(L_DEBUG, "Opening output file for writing: %s", scas_runtime.output_file);
	FILE *out;
	if (strcasecmp(scas_runtime.output_file, "-") == 0) {
		out = stdout;
	} else {
		out = fopen(scas_runtime.output_file, "w+");
	}
	if (!out) {
		scas_abort("Unable to open '%s' for output.", scas_runtime.output_file);
	}

	if ((scas_runtime.jobs & LINK) == LINK) {
		scas_log(L_INFO, "Passing objects to linker");
		linker_settings_t settings = {
			.automatic_relocation = scas_runtime.options.auto_relocation,
			.merge_only = (scas_runtime.jobs & MERGE) == MERGE,
			.errors = errors,
			.warnings = warnings,
			.write_output = scas_runtime.options.output_format
		};
		if (settings.merge_only) {
			object_t *merged = merge_objects(objects);
			fwriteobj(out, merged);
		} else {
			link_objects(out, objects, &settings);
		}
		scas_log(L_INFO, "Linker returned %d errors, %d warnings", errors->length, warnings->length);
	} else {
		scas_log(L_INFO, "Skipping linking - writing to object file");
		object_t *merged = merge_objects(objects);
		fwriteobj(out, merged);
		fflush(out);
		fclose(out);
	}
	if (errors->length != 0) {
		int i;
		for (i = 0; i < errors->length; ++i) {
			error_t *error = errors->items[i];
			fprintf(stderr, "%s:%d:%d: error #%d: %s\n", error->file_name,
					(int)error->line_number, (int)error->column, error->code,
					error->message);
			fprintf(stderr, "%s\n", error->line);
			if (error->column != 0) {
				int j;
				for (j = error->column; j > 0; --j) {
					fprintf(stderr, ".");
				}
				fprintf(stderr, "^\n");
			} else {
				fprintf(stderr, "\n");
			}
		}
		remove(scas_runtime.output_file);
	}
	if (warnings->length != 0) {
		int i;
		for (i = 0; i < errors->length; ++i) {
			warning_t *warning = warnings->items[i];
			fprintf(stderr, "%s:%d:%d: warning #%d: %s\n", warning->file_name,
					(int)warning->line_number, (int)warning->column, warning->code,
					get_warning_string(warning));
			fprintf(stderr, "%s\n", warning->line);
			if (warning->column != 0) {
				int j;
				for (j = warning->column; j > 0; --j) {
					fprintf(stderr, ".");
				}
				fprintf(stderr, "^\n");
			}
		}
	}

	int ret = errors->length;
	scas_log(L_DEBUG, "Exiting with status code %d, cleaning up", ret);
	list_free(scas_runtime.input_files);
	free_flat_list(include_path);
	list_free(objects);
	list_free(errors);
	list_free(warnings);
	instruction_set_free(instruction_set);
	return ret;
}
コード例 #19
0
ファイル: symbol.c プロジェクト: gregory144/clarity
void symbol_table_free(symbol_table_t* symbol_table) {
  printf("Freeing table: %p -> %p\n", symbol_table, symbol_table->symbols);
  list_visit(symbol_table->symbols, (void(*)(void*))symbol_free);
  list_free(symbol_table->symbols);
  free(symbol_table);
}
コード例 #20
0
ファイル: tablespace.c プロジェクト: avontd2868/postgres
/* check_hook: validate new temp_tablespaces */
bool
check_temp_tablespaces(char **newval, void **extra, GucSource source)
{
	char	   *rawname;
	List	   *namelist;

	/* Need a modifiable copy of string */
	rawname = pstrdup(*newval);

	/* Parse string into list of identifiers */
	if (!SplitIdentifierString(rawname, ',', &namelist))
	{
		/* syntax error in name list */
		GUC_check_errdetail("List syntax is invalid.");
		pfree(rawname);
		list_free(namelist);
		return false;
	}

	/*
	 * If we aren't inside a transaction, we cannot do database access so
	 * cannot verify the individual names.	Must accept the list on faith.
	 * Fortunately, there's then also no need to pass the data to fd.c.
	 */
	if (IsTransactionState())
	{
		temp_tablespaces_extra *myextra;
		Oid		   *tblSpcs;
		int			numSpcs;
		ListCell   *l;

		/* temporary workspace until we are done verifying the list */
		tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
		numSpcs = 0;
		foreach(l, namelist)
		{
			char	   *curname = (char *) lfirst(l);
			Oid			curoid;
			AclResult	aclresult;

			/* Allow an empty string (signifying database default) */
			if (curname[0] == '\0')
			{
				tblSpcs[numSpcs++] = InvalidOid;
				continue;
			}

			/*
			 * In an interactive SET command, we ereport for bad info.  When
			 * source == PGC_S_TEST, we are checking the argument of an ALTER
			 * DATABASE SET or ALTER USER SET command.  pg_dumpall dumps all
			 * roles before tablespaces, so if we're restoring a pg_dumpall
			 * script the tablespace might not yet exist, but will be created
			 * later.  Because of that, issue a NOTICE if source == PGC_S_TEST,
			 * but accept the value anyway.  Otherwise, silently ignore any
			 * bad list elements.
			 */
			curoid = get_tablespace_oid(curname, source <= PGC_S_TEST);
			if (curoid == InvalidOid)
			{
				if (source == PGC_S_TEST)
					ereport(NOTICE,
							(errcode(ERRCODE_UNDEFINED_OBJECT),
							 errmsg("tablespace \"%s\" does not exist",
									curname)));
				continue;
			}

			/*
			 * Allow explicit specification of database's default tablespace
			 * in temp_tablespaces without triggering permissions checks.
			 */
			if (curoid == MyDatabaseTableSpace)
			{
				tblSpcs[numSpcs++] = InvalidOid;
				continue;
			}

			/* Check permissions, similarly complaining only if interactive */
			aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
											   ACL_CREATE);
			if (aclresult != ACLCHECK_OK)
			{
				if (source >= PGC_S_INTERACTIVE)
					aclcheck_error(aclresult, ACL_KIND_TABLESPACE, curname);
				continue;
			}

			tblSpcs[numSpcs++] = curoid;
		}

		/* Now prepare an "extra" struct for assign_temp_tablespaces */
		myextra = malloc(offsetof(temp_tablespaces_extra, tblSpcs) +
						 numSpcs * sizeof(Oid));
		if (!myextra)
			return false;
		myextra->numSpcs = numSpcs;
		memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
		*extra = (void *) myextra;

		pfree(tblSpcs);
	}
コード例 #21
0
/*
 * get_relation_info -
 *	  Retrieves catalog information for a given relation.
 *
 * Given the Oid of the relation, return the following info into fields
 * of the RelOptInfo struct:
 *
 *	min_attr	lowest valid AttrNumber
 *	max_attr	highest valid AttrNumber
 *	indexlist	list of IndexOptInfos for relation's indexes
 *	pages		number of pages
 *	tuples		number of tuples
 *
 * Also, initialize the attr_needed[] and attr_widths[] arrays.  In most
 * cases these are left as zeroes, but sometimes we need to compute attr
 * widths here, and we may as well cache the results for costsize.c.
 *
 * If inhparent is true, all we need to do is set up the attr arrays:
 * the RelOptInfo actually represents the appendrel formed by an inheritance
 * tree, and so the parent rel's physical size and index information isn't
 * important for it.
 */
void
get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
				  RelOptInfo *rel)
{
	Index		varno = rel->relid;
	Relation	relation;
	bool		hasindex;
	List	   *indexinfos = NIL;

	/*
	 * We need not lock the relation since it was already locked, either by
	 * the rewriter or when expand_inherited_rtentry() added it to the query's
	 * rangetable.
	 */
	relation = heap_open(relationObjectId, NoLock);

	/* Temporary and unlogged relations are inaccessible during recovery. */
	if (!RelationNeedsWAL(relation) && RecoveryInProgress())
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("cannot access temporary or unlogged relations during recovery")));

	rel->min_attr = FirstLowInvalidHeapAttributeNumber + 1;
	rel->max_attr = RelationGetNumberOfAttributes(relation);
	rel->reltablespace = RelationGetForm(relation)->reltablespace;

	Assert(rel->max_attr >= rel->min_attr);
	rel->attr_needed = (Relids *)
		palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
	rel->attr_widths = (int32 *)
		palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));

	/*
	 * Estimate relation size --- unless it's an inheritance parent, in which
	 * case the size will be computed later in set_append_rel_pathlist, and we
	 * must leave it zero for now to avoid bollixing the total_table_pages
	 * calculation.
	 */
	if (!inhparent)
		estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
						  &rel->pages, &rel->tuples, &rel->allvisfrac);

	/*
	 * Make list of indexes.  Ignore indexes on system catalogs if told to.
	 * Don't bother with indexes for an inheritance parent, either.
	 */
	if (inhparent ||
		(IgnoreSystemIndexes && IsSystemClass(relation->rd_rel)))
		hasindex = false;
	else
		hasindex = relation->rd_rel->relhasindex;

	if (hasindex)
	{
		List	   *indexoidlist;
		ListCell   *l;
		LOCKMODE	lmode;

		indexoidlist = RelationGetIndexList(relation);

		/*
		 * For each index, we get the same type of lock that the executor will
		 * need, and do not release it.  This saves a couple of trips to the
		 * shared lock manager while not creating any real loss of
		 * concurrency, because no schema changes could be happening on the
		 * index while we hold lock on the parent rel, and neither lock type
		 * blocks any other kind of index operation.
		 */
		if (rel->relid == root->parse->resultRelation)
			lmode = RowExclusiveLock;
		else
			lmode = AccessShareLock;

		foreach(l, indexoidlist)
		{
			Oid			indexoid = lfirst_oid(l);
			Relation	indexRelation;
			Form_pg_index index;
			IndexOptInfo *info;
			int			ncolumns;
			int			i;

			/*
			 * Extract info from the relation descriptor for the index.
			 */
			indexRelation = index_open(indexoid, lmode);
			index = indexRelation->rd_index;

			/*
			 * Ignore invalid indexes, since they can't safely be used for
			 * queries.  Note that this is OK because the data structure we
			 * are constructing is only used by the planner --- the executor
			 * still needs to insert into "invalid" indexes!
			 */
			if (!index->indisvalid)
			{
				index_close(indexRelation, NoLock);
				continue;
			}

			/*
			 * If the index is valid, but cannot yet be used, ignore it; but
			 * mark the plan we are generating as transient. See
			 * src/backend/access/heap/README.HOT for discussion.
			 */
			if (index->indcheckxmin &&
				!TransactionIdPrecedes(HeapTupleHeaderGetXmin(indexRelation->rd_indextuple->t_data),
									   TransactionXmin))
			{
				root->glob->transientPlan = true;
				index_close(indexRelation, NoLock);
				continue;
			}

			info = makeNode(IndexOptInfo);

			info->indexoid = index->indexrelid;
			info->reltablespace =
				RelationGetForm(indexRelation)->reltablespace;
			info->rel = rel;
			info->ncolumns = ncolumns = index->indnatts;
			info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
			info->indexcollations = (Oid *) palloc(sizeof(Oid) * ncolumns);
			info->opfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
			info->opcintype = (Oid *) palloc(sizeof(Oid) * ncolumns);

			for (i = 0; i < ncolumns; i++)
			{
				info->indexkeys[i] = index->indkey.values[i];
				info->indexcollations[i] = indexRelation->rd_indcollation[i];
				info->opfamily[i] = indexRelation->rd_opfamily[i];
				info->opcintype[i] = indexRelation->rd_opcintype[i];
			}

			info->relam = indexRelation->rd_rel->relam;
			info->amcostestimate = indexRelation->rd_am->amcostestimate;
			info->canreturn = index_can_return(indexRelation);
			info->amcanorderbyop = indexRelation->rd_am->amcanorderbyop;
			info->amoptionalkey = indexRelation->rd_am->amoptionalkey;
			info->amsearcharray = indexRelation->rd_am->amsearcharray;
			info->amsearchnulls = indexRelation->rd_am->amsearchnulls;
			info->amhasgettuple = OidIsValid(indexRelation->rd_am->amgettuple);
			info->amhasgetbitmap = OidIsValid(indexRelation->rd_am->amgetbitmap);

			/*
			 * Fetch the ordering information for the index, if any.
			 */
			if (info->relam == BTREE_AM_OID)
			{
				/*
				 * If it's a btree index, we can use its opfamily OIDs
				 * directly as the sort ordering opfamily OIDs.
				 */
				Assert(indexRelation->rd_am->amcanorder);

				info->sortopfamily = info->opfamily;
				info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
				info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);

				for (i = 0; i < ncolumns; i++)
				{
					int16		opt = indexRelation->rd_indoption[i];

					info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
					info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
				}
			}
			else if (indexRelation->rd_am->amcanorder)
			{
				/*
				 * Otherwise, identify the corresponding btree opfamilies by
				 * trying to map this index's "<" operators into btree.  Since
				 * "<" uniquely defines the behavior of a sort order, this is
				 * a sufficient test.
				 *
				 * XXX This method is rather slow and also requires the
				 * undesirable assumption that the other index AM numbers its
				 * strategies the same as btree.  It'd be better to have a way
				 * to explicitly declare the corresponding btree opfamily for
				 * each opfamily of the other index type.  But given the lack
				 * of current or foreseeable amcanorder index types, it's not
				 * worth expending more effort on now.
				 */
				info->sortopfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
				info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
				info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);

				for (i = 0; i < ncolumns; i++)
				{
					int16		opt = indexRelation->rd_indoption[i];
					Oid			ltopr;
					Oid			btopfamily;
					Oid			btopcintype;
					int16		btstrategy;

					info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
					info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;

					ltopr = get_opfamily_member(info->opfamily[i],
												info->opcintype[i],
												info->opcintype[i],
												BTLessStrategyNumber);
					if (OidIsValid(ltopr) &&
						get_ordering_op_properties(ltopr,
												   &btopfamily,
												   &btopcintype,
												   &btstrategy) &&
						btopcintype == info->opcintype[i] &&
						btstrategy == BTLessStrategyNumber)
					{
						/* Successful mapping */
						info->sortopfamily[i] = btopfamily;
					}
					else
					{
						/* Fail ... quietly treat index as unordered */
						info->sortopfamily = NULL;
						info->reverse_sort = NULL;
						info->nulls_first = NULL;
						break;
					}
				}
			}
			else
			{
				info->sortopfamily = NULL;
				info->reverse_sort = NULL;
				info->nulls_first = NULL;
			}

			/*
			 * Fetch the index expressions and predicate, if any.  We must
			 * modify the copies we obtain from the relcache to have the
			 * correct varno for the parent relation, so that they match up
			 * correctly against qual clauses.
			 */
			info->indexprs = RelationGetIndexExpressions(indexRelation);
			info->indpred = RelationGetIndexPredicate(indexRelation);
			if (info->indexprs && varno != 1)
				ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
			if (info->indpred && varno != 1)
				ChangeVarNodes((Node *) info->indpred, 1, varno, 0);

			/* Build targetlist using the completed indexprs data */
			info->indextlist = build_index_tlist(root, info, relation);

			info->predOK = false;		/* set later in indxpath.c */
			info->unique = index->indisunique;
			info->immediate = index->indimmediate;
			info->hypothetical = false;

			/*
			 * Estimate the index size.  If it's not a partial index, we lock
			 * the number-of-tuples estimate to equal the parent table; if it
			 * is partial then we have to use the same methods as we would for
			 * a table, except we can be sure that the index is not larger
			 * than the table.
			 */
			if (info->indpred == NIL)
			{
				info->pages = RelationGetNumberOfBlocks(indexRelation);
				info->tuples = rel->tuples;
			}
			else
			{
				double		allvisfrac; /* dummy */

				estimate_rel_size(indexRelation, NULL,
								  &info->pages, &info->tuples, &allvisfrac);
				if (info->tuples > rel->tuples)
					info->tuples = rel->tuples;
			}

			index_close(indexRelation, NoLock);

			indexinfos = lcons(info, indexinfos);
		}

		list_free(indexoidlist);
	}
コード例 #22
0
ファイル: cache.c プロジェクト: houstar/masala
void cache_free( void ) {
	list_clear( _main->cache->list );
	list_free( _main->cache->list );
	hash_free( _main->cache->hash );
	myfree( _main->cache, "cache_free" );
}
コード例 #23
0
ファイル: main.cpp プロジェクト: RickyXwang/transf-badapple
int main (int argc, char **argv)
{
	int curr_arg = 1;
	bool case_sensitive = false;
	bool is_storage_initialized = false;

	use_colors = true;
	extern WORD user_attributes;
	user_attributes = save_console_attributes ();
	atexit (restore_console_attributes_at_exit);

	//if there aren't enough args, show info
	if (argc < 2) {
		puts ("SPASM Z80 Assembler by Spencer Putt and Don Straney");
#ifdef _M_X64
		puts ("64-bit Version");
#endif
		puts ("\n\nspasm [options] <input file> <output file>\n");
		puts ("Options:\n-T = Generate code listing\n-C = Code counter mode\n-L = Symbol table mode\n-S = Stats mode\n-O = Don't write to output file");
		puts ("-I [directory] = Add include directory\n-A = Labels are cAse-sensitive\n-D<name>[=value] = Create a define 'name' [with 'value']");
		puts ("-N = Don't use colors for messages");
		puts ("-V <Expression> = Pipe expression directly into assembly");

#if defined(_DEBUG) && defined(WIN32)
		if (IsDebuggerPresent())
		{
			system("PAUSE");
		}
#endif
		return EXIT_NORMAL;
	}

	//init stuff
	mode = MODE_NORMAL;
	in_macro = 0;
	
	//otherwise, get any options
	curr_input_file = strdup("Commandline");
	const char * const starting_input_file = curr_input_file;

	while (curr_arg < argc) {
		if (argv[curr_arg][0] == '-'
#ifdef _WINDOWS
			|| argv[curr_arg][0] == '/'
#endif
			)
		{
			switch (argv[curr_arg][1])
			{
			//args for different modes
			case 'O':
				mode = mode & (~MODE_NORMAL);
				break;
			case 'T':
				mode |= MODE_LIST;
				break;
			case 'C':
				mode |= MODE_CODE_COUNTER;
				break;
			case 'L':
				mode |= MODE_SYMTABLE;
				break;
			case 'S':
				mode |= MODE_STATS;
				break;
			//handle no-colors flag
			case 'N':
				use_colors = false;
				break;
			//handle include files too
			case 'I':
			{
				char *dir, *p;
				//make sure there's another argument after it for the include path
				if (strlen(argv[curr_arg]) > 2) {
					dir = strdup (&argv[curr_arg][2]);
				} else {
					if (curr_arg >= argc - 1) {
						printf ("%s used without include path\n", argv[curr_arg]);
						break;
					}
					
					dir = strdup (argv[++curr_arg]);
				}
				
				for (p = strtok (dir, ";,"); p; p = strtok (NULL, ";,")) {
					include_dirs = list_append (include_dirs, strdup(p));
				}
				free(dir);
				break;
			}
			//and the case-sensitive flag
			case 'A':
				case_sensitive = true;
				break;
			//handle adding defines
			case 'D':
			{
				char name[256];
				char *ptr;
				define_t *define;

				if (!is_storage_initialized)
				{
					init_storage();
					is_storage_initialized = true;
				}

				if (strlen (argv[curr_arg]) > 2) {
					ptr = &argv[curr_arg][2];
				} else {
					if (curr_arg >= argc - 1) {
						printf ("%s used without define name", argv[curr_arg]);
						break;
					}
					
					ptr = argv[++curr_arg];
				}

				read_expr (&ptr, name, "=");

				define = add_define (strdup (name), NULL);
				if (*skip_whitespace (++ptr) != '\0')
					define->contents = strdup (ptr);
				else
					set_define (define, "1", 1, false);
				break;
			}
			case 'V':
			{
				char *line;
				
				//check for something after -V
				if (strlen(argv[curr_arg]) > 2) {
					line = &argv[curr_arg][2];
				} else {
					//if not lets fail
					if (curr_arg >= argc - 1) {
						printf ("%s used without a line to assemble\n", argv[curr_arg]);
						return EXIT_FATAL_ERROR;
					}
					line = argv[++curr_arg];
				}
				
				mode |= MODE_COMMANDLINE;
				curr_input_file = strdup("-v");
				input_contents = (char *) malloc (strlen(line) + 1 + 2);
				output_filename = change_extension (curr_input_file, "bin");
					
				strcpy(input_contents, line);
				strcat(input_contents, "\n");
				break;
			}
			default:
				{
#ifndef _TEST
#ifdef _WINDOWS
					FreeConsole();
					return _AtlModule.WinMain(SW_HIDE);
#endif
#else
					printf ("Unrecognized option %s\n", argv[curr_arg]);
#endif
				}
				
			}

		} else {
			//if it's not a flag, then it must be a filename
			if (curr_input_file && (curr_input_file != starting_input_file) && !output_filename)
				output_filename = strdup(argv[curr_arg]);
			else if ((!curr_input_file) || (curr_input_file == starting_input_file))
				curr_input_file = strdup(argv[curr_arg]);

		}
		curr_arg++;
	}

	// Update case sensitivity settings
	set_case_sensitive (case_sensitive);
	
	//check on filenames
	if (!(mode & MODE_COMMANDLINE) && !curr_input_file) {
		puts ("No input file specified");
		return EXIT_FATAL_ERROR;
	}

	if (!output_filename) {
		if (mode & MODE_SYMTABLE)
			output_filename = change_extension (curr_input_file, "lab");
		else
			output_filename = change_extension (curr_input_file, "bin");
	}

	if (!is_storage_initialized)
	{
		init_storage();
		is_storage_initialized = true;
	}
	output_contents = (unsigned char *) malloc(output_buf_size);
	ClearSPASMErrorSessions();

	int error = run_assembly();

	free(output_filename);
	output_filename = NULL;
	if (curr_input_file) {
		free(curr_input_file);
		curr_input_file = NULL;
	}
	if (include_dirs) {
		list_free(include_dirs, true, NULL);
	}

	free(output_contents);
	output_contents = NULL;
	ClearSPASMErrorSessions();
	free_storage();

#ifdef _WINDOWS
	_CrtDumpMemoryLeaks();
	if (IsDebuggerPresent())
	{
		system("PAUSE");
	}
#endif

	return error;
}
コード例 #24
0
ファイル: pdb_types.c プロジェクト: MJL85/Doom3Metamod
/*
 *	Free a list node.
 */
int pdb_free_list_node_cb(struct pdb_node_t* nptr) {
	struct linkList* lptr = nptr->data;
	list_free(lptr, 1, (void*)&pdb_free_node_cb);
	return 1;
}
コード例 #25
0
int main () {
    callbacks = list_create();

    talloc_set_callback_fn ( add, del );

    // 1. add child "root" to the parent "NULL"
    TALLOC_CTX * root = talloc_new ( NULL );
    
    if ( callbacks->length == 1 ) {
        callback * cb = callbacks->first->data;
        if ( cb->id != 1 || cb->parent != NULL || cb->child != root ) {
            talloc_free ( root );
            list_each ( callbacks, free_callback );
            list_free ( callbacks );
            return 1;
        }
    } else {
        talloc_free ( root );
        list_each ( callbacks, free_callback );
        list_free ( callbacks );
        return 2;
    }
    list_clear ( callbacks );

    // 1. add child "a" to the parent "root"
    char * a = talloc ( root, char );

    if ( callbacks->length == 1 ) {
        callback * cb = callbacks->first->data;
        if ( cb->id != 1 || cb->parent != root || cb->child != a ) {
            talloc_free ( root );
            list_each ( callbacks, free_callback );
            list_free ( callbacks );
            return 3;
        }
    } else {
        talloc_free ( root );
        list_each ( callbacks, free_callback );
        list_free ( callbacks );
        return 4;
    }
    list_clear ( callbacks );

    // 1. add child "b" to the parent "a"
    short * b = talloc ( a, short );
    // 2. add child "c" to the parent "a"
    int * c   = talloc ( a, int );
    // 3. add child "d" to the parent "c"
    long * d  = talloc ( c, long );

    if ( callbacks->length == 3 ) {
        callback * cb1 = callbacks->first->data;
        callback * cb2 = callbacks->first->next->data;
        callback * cb3 = callbacks->last->data;
        if (
            cb1->id != 1 || cb1->parent != a || cb1->child != b ||
            cb2->id != 1 || cb2->parent != a || cb2->child != c ||
            cb3->id != 1 || cb3->parent != c || cb3->child != d
        ) {
            talloc_free ( root );
            list_each ( callbacks, free_callback );
            list_free ( callbacks );
            return 5;
        }
    } else {
        talloc_free ( root );
        list_each ( callbacks, free_callback );
        list_free ( callbacks );
        return 6;
    }
    list_clear ( callbacks );

    // 1. del child "b" from the parent "a"
    // 2. add child "b" to   the parent "root"
    b = talloc_move ( root, &b );

    if ( callbacks->length == 2 ) {
        callback * cb1 = callbacks->first->data;
        callback * cb2 = callbacks->last->data;
        if (
            cb1->id != 2 || cb1->parent != a    || cb1->child != b ||
            cb2->id != 1 || cb2->parent != root || cb2->child != b
        ) {
            talloc_free ( root );
            list_each ( callbacks, free_callback );
            list_free ( callbacks );
            return 7;
        }
    } else {
        talloc_free ( root );
        list_each ( callbacks, free_callback );
        list_free ( callbacks );
        return 8;
    }
    list_clear ( callbacks );

    // 1. del child "a" from the parent "root"
    // 2. add child "a" to   the parent "b"
    a = talloc_move ( b, &a );
    // 3. del child "d" from the parent "c"
    // 4. add child "d" to   the parent "a"
    d = talloc_move ( a, &d );

    if ( callbacks->length == 4 ) {
        callback * cb1 = callbacks->first->data;
        callback * cb2 = callbacks->first->next->data;
        callback * cb3 = callbacks->first->next->next->data;
        callback * cb4 = callbacks->last->data;
        if (
            cb1->id != 2 || cb1->parent != root || cb1->child != a ||
            cb2->id != 1 || cb2->parent != b    || cb2->child != a ||
            cb3->id != 2 || cb3->parent != c    || cb3->child != d ||
            cb4->id != 1 || cb4->parent != a    || cb4->child != d
        ) {
            talloc_free ( root );
            list_each ( callbacks, free_callback );
            list_free ( callbacks );
            return 9;
        }
    } else {
        talloc_free ( root );
        list_each ( callbacks, free_callback );
        list_free ( callbacks );
        return 10;
    }
    list_clear ( callbacks );

    // del all 5 elements
    talloc_free ( root );
    
    if (callbacks->length != 5) {
        list_each ( callbacks, free_callback );
        list_free ( callbacks );
        return 11;
    }

    list_each ( callbacks, free_callback );
    list_free ( callbacks );

    return 0;
}
コード例 #26
0
int main()
{
    // Thist test does not check all the error conditions that may happen
    {
        // Int example
        int i = 0;
        Generic_List_Node_t *list;
        Generic_List_Node_t *head;

        list = list_create(&i, sizeof(i));
        head = list;

        if (list == NULL)
        {
            fprintf(stderr,"Error creating new element\n");
            exit (-1);
        }

        for (i; i<11; i++)
        {
            head = list_insert_after(head, &i, sizeof(i));
        }

        list_foreach(list, print_int_node);

        list_free(&list);

        if (list == NULL)
        {
            fprintf(stderr,"list is empty \n");
        }

        list_foreach(list, print_int_node);
    }

    {
        // my_type_t example
        int i=0;
        my_type_t itm;
        Generic_List_Node_t *list;
        Generic_List_Node_t *head;

        itm.a = 1;
        itm.b = 2.2;
        itm.c = 3;
        list = list_create(&itm, sizeof(itm));
        head = list;

        if (list == NULL)
        {
            fprintf(stderr,"Error creating new element\n");
            exit (-1);
        }

        for (i=1; i<11; i++)
        {
            itm.a++;
            itm.b++;
            itm.c++;
            head = list_insert_after(head, &itm, sizeof(itm));
        }

        list_foreach(list, print_my_type_t_node);

        list_free(&list);

        if (list == NULL)
        {
            fprintf(stderr,"list is empty \n");
        }

        list_foreach(list, print_my_type_t_node);
    }


    return 0;
}
コード例 #27
0
ファイル: ls.c プロジェクト: klange/toaruos
int main (int argc, char * argv[]) {

	/* Parse arguments */
	char * p = ".";

	if (argc > 1) {
		int c;
		while ((c = getopt(argc, argv, "ahl?")) != -1) {
			switch (c) {
				case 'a':
					show_hidden = 1;
					break;
				case 'h':
					human_readable = 1;
					break;
				case 'l':
					long_mode = 1;
					break;
				case '?':
					show_usage(argc, argv);
					return 0;
			}
		}

		if (optind < argc) {
			p = argv[optind];
		}
		if (optind + 1 < argc) {
			print_dir = 1;
		}
	}


	stdout_is_tty = isatty(STDOUT_FILENO);

	if (long_mode) {
		struct tm * timeinfo;
		struct timeval now;
		gettimeofday(&now, NULL); //time(NULL);
		timeinfo = localtime((time_t *)&now.tv_sec);
		this_year = timeinfo->tm_year;
	}

	if (stdout_is_tty) {
		TRACE("getting display size");
		struct winsize w;
		ioctl(1, TIOCGWINSZ, &w);
		term_width = w.ws_col;
		term_height = w.ws_row;
		term_width -= 1; /* And this just helps clean up our math */
	}

	int out = 0;

	if (argc == 1 || optind == argc) {
		TRACE("no file to look up");
		if (display_dir(p) == 2) {
			fprintf(stderr, "%s: %s: %s\n", argv[0], p, strerror(errno));
		}
	} else {
		list_t * files = list_create();
		while (p) {
			struct tfile * f = malloc(sizeof(struct tfile));

			f->name = p;
			int t = lstat(p, &f->statbuf);

			if (t < 0) {
				fprintf(stderr, "%s: %s: %s\n", argv[0], p, strerror(errno));
				free(f);
				out = 2;
			} else {
				if (S_ISLNK(f->statbuf.st_mode)) {
					stat(p, &f->statbufl);
					f->link = malloc(4096);
					readlink(p, f->link, 4096);
				}
				list_insert(files, f);
			}

			optind++;
			if (optind >= argc) p = NULL;
			else p = argv[optind];
		}

		if (!files->length) {
			/* No valid entries */
			return out;
		}

		struct tfile ** file_arr = malloc(sizeof(struct tfile *) * files->length);
		int index = 0;
		foreach(node, files) {
			file_arr[index++] = (struct tfile *)node->value;
		}

		list_free(files);

		qsort(file_arr, index, sizeof(struct tfile *), filecmp);

		int first_directory = index;

		for (int i = 0; i < index; ++i) {
			if (S_ISDIR(file_arr[i]->statbuf.st_mode)) {
				first_directory = i;
				break;
			}
		}

		if (first_directory) {
			display_tfiles(file_arr, first_directory);
		}

		for (int i = first_directory; i < index; ++i) {
			if (i != 0) {
				printf("\n");
			}
			if (display_dir(file_arr[i]->name) == 2) {
				fprintf(stderr, "%s: %s: %s\n", argv[0], file_arr[i]->name, strerror(errno));
			}
		}
	}

	return out;
}
コード例 #28
0
ファイル: room.c プロジェクト: anwerx2007/warfacebot
void room_list_free(void)
{
    list_free(session.rooms);
    session.rooms = NULL;
}
コード例 #29
0
ファイル: set.c プロジェクト: jpcoles/htrack
//============================================================================
//                                  set_free
//============================================================================
int set_free(set_t *set)
{
    return list_free(set);
}
コード例 #30
0
ファイル: compile.c プロジェクト: mba5157/opbb10
LIST * compile_eval( PARSE * parse, FRAME * frame )
{
    LIST * ll;
    LIST * lr;
    LIST * s;
    LIST * t;
    int status = 0;

    /* Short circuit lr eval for &&, ||, and 'in'. */

    ll = parse_evaluate( parse->left, frame );
    lr = 0;

    switch ( parse->num )
    {
        case EXPR_AND:
        case EXPR_IN : if ( ll ) goto eval; break;
        case EXPR_OR : if ( !ll ) goto eval; break;
        default: eval: lr = parse_evaluate( parse->right, frame );
    }

    /* Now eval. */
    switch ( parse->num )
    {
    case EXPR_NOT: if ( !ll      ) status = 1; break;
    case EXPR_AND: if ( ll && lr ) status = 1; break;
    case EXPR_OR : if ( ll || lr ) status = 1; break;

    case EXPR_IN:
        /* "a in b": make sure each of ll is equal to something in lr. */
        for ( t = ll; t; t = list_next( t ) )
        {
            for ( s = lr; s; s = list_next( s ) )
            if ( !strcmp( t->string, s->string ) )
                break;
            if ( !s ) break;
        }
        /* No more ll? Success. */
        if ( !t ) status = 1;
        break;

    case EXPR_EXISTS: if ( lcmp( ll, L0 ) != 0 ) status = 1; break;
    case EXPR_EQUALS: if ( lcmp( ll, lr ) == 0 ) status = 1; break;
    case EXPR_NOTEQ : if ( lcmp( ll, lr ) != 0 ) status = 1; break;
    case EXPR_LESS  : if ( lcmp( ll, lr ) < 0  ) status = 1; break;
    case EXPR_LESSEQ: if ( lcmp( ll, lr ) <= 0 ) status = 1; break;
    case EXPR_MORE  : if ( lcmp( ll, lr ) > 0  ) status = 1; break;
    case EXPR_MOREEQ: if ( lcmp( ll, lr ) >= 0 ) status = 1; break;
    }

    if ( DEBUG_IF )
    {
        debug_compile( 0, "if", frame );
        list_print( ll );
        printf( "(%d) ", status );
        list_print( lr );
        printf( "\n" );
    }

    /* Find something to return. */
    /* In odd circumstances (like "" = "") */
    /* we'll have to return a new string. */

    if ( !status ) t = 0;
    else if ( ll ) t = ll, ll = 0;
    else if ( lr ) t = lr, lr = 0;
    else t = list_new( L0, newstr( "1" ) );

    if ( ll ) list_free( ll );
    if ( lr ) list_free( lr );
    return t;
}