Esempio n. 1
0
/**
 * based on find_member() from vsd_utils.c:
 * http://vsdump.sourcearchive.com/documentation/0.0.44/vsd__utils_8c-source.html
 */
static GsfInput *
find_member (GsfInfile *arch,
             gchar const *name)
{
	gchar const *slash;

	slash = strchr (name, '/');

	if (slash) {
		gchar *dirname;
		GsfInput *member;

		dirname = g_strndup (name, slash - name);

		/**
		 * Ignore if the directory is the current one that is ".".
		 * Go to next direcotry if exists
		 */

		if (strcmp (dirname, ".") == 0) {
			member = find_member (arch, slash + 1);
		} else if ((member = gsf_infile_child_by_name (arch, dirname)) != NULL) {
			GsfInfile *dir;

			dir = GSF_INFILE (member);
			member = find_member (dir, slash + 1);
			g_object_unref (dir);
		}

		g_free (dirname);
		return member;
	} else {
		return gsf_infile_child_by_name (arch, name);
	}
}
Esempio n. 2
0
int main(int argc, char** argv)
{
  SIMIX_global_init(&argc, argv);

  simgrid::mc::Variable* var;
  simgrid::mc::Type* type;

  simgrid::mc::Process process(getpid(), -1);
  process.init();

  test_global_variable(process, process.binary_info.get(),
    "some_local_variable", &some_local_variable, sizeof(int));

  var = test_global_variable(process, process.binary_info.get(),
    "test_some_array", &test_some_array, sizeof(test_some_array));
  auto i = process.binary_info->types.find(var->type_id);
  xbt_assert(i != process.binary_info->types.end(), "Missing type");
  type = &i->second;
  xbt_assert(type->element_count == 6*5*4,
    "element_count mismatch in test_some_array : %i / %i",
    type->element_count, 6*5*4);

  var = test_global_variable(process, process.binary_info.get(),
    "test_some_struct", &test_some_struct, sizeof(test_some_struct));
  i = process.binary_info->types.find(var->type_id);
  xbt_assert(i != process.binary_info->types.end(), "Missing type");
  type = &i->second;

  assert(type);
  assert(find_member(*type, "first")->offset() == 0);
  assert(find_member(*type, "second")->offset()
      == ((const char*)&test_some_struct.second) - (const char*)&test_some_struct);

  unw_context_t context;
  unw_cursor_t cursor;
  unw_getcontext(&context);
  unw_init_local(&cursor, &context);

  test_local_variable(process.binary_info.get(), "main", "argc", &argc, &cursor);

  {
    int lexical_block_variable = 50;
    test_local_variable(process.binary_info.get(), "main",
      "lexical_block_variable", &lexical_block_variable, &cursor);
  }

  s_foo my_foo;
  test_type_by_name(process, my_foo);

  _exit(0);
}
Esempio n. 3
0
MEMBER *read_value
(     MPL *mpl,
      PARAMETER *par,         /* not changed */
      TUPLE *tuple            /* destroyed */
)
{     MEMBER *memb;
      insist(par != NULL);
      insist(is_symbol(mpl));
      /* there must be no member with the same n-tuple */
      if (find_member(mpl, par->array, tuple) != NULL)
         error(mpl, "%s%s already defined",
            par->name, format_tuple(mpl, '[', tuple));
      /* create new parameter member with given n-tuple */
      memb = add_member(mpl, par->array, tuple);
      /* read value and assigns it to the new parameter member */
      switch (par->type)
      {  case A_NUMERIC:
         case A_INTEGER:
         case A_BINARY:
            if (!is_number(mpl))
               error(mpl, "%s requires numeric data", par->name);
            memb->value.num = read_number(mpl);
            break;
         case A_SYMBOLIC:
            memb->value.sym = read_symbol(mpl);
            break;
         default:
            insist(par != par);
      }
      return memb;
}
Esempio n. 4
0
File: gsf.c Progetto: arcean/libgsf
static int
gsf_dump (int argc, char **argv, gboolean hex)
{
	char const *filename;
	GsfInfile *infile;
	int i;
	int res = 0;

	if (argc < 2)
		return 1;

	filename = argv[0];
	infile = open_archive (filename);
	if (!infile)
		return 1;

	for (i = 1; i < argc; i++) {
		char const *name = argv[i];
		GsfInput *member = find_member (infile, name);
		if (!member) {
			char *display_name = g_filename_display_name (name);
			g_print ("%s: archive has no member %s\n",
				 g_get_prgname (), display_name);
			g_free (display_name);
			res = 1;
			break;
		}

		if (hex) {
			char *display_name = g_filename_display_name (name);
			g_print ("%s:\n", display_name);
			g_free (display_name);
		}
		gsf_input_dump (member, hex);
		g_object_unref (member);
	}

	g_object_unref (infile);
	return res;
}
Esempio n. 5
0
File: gsf.c Progetto: arcean/libgsf
static GsfInput *
find_member (GsfInfile *arch, char const *name)
{
	char const *slash = strchr (name, '/');

	if (slash) {
		char *dirname = g_strndup (name, slash - name);
		GsfInput *member;
		GsfInfile *dir;

		member = gsf_infile_child_by_name (arch, dirname);
		g_free (dirname);
		if (!member)
			return NULL;
		dir = GSF_INFILE (member);
		member = find_member (dir, slash + 1);
		g_object_unref (dir);
		return member;
	} else {
		return gsf_infile_child_by_name (arch, name);
	}
}
Esempio n. 6
0
int erl_rpc_struct_scan(erl_rpc_ctx_t* ctx, char* fmt, ...)
{
	int* int_ptr;
	char** char_ptr;
	str* str_ptr;
	double* double_ptr;
	char* member_name;
	str s; /* helper str */

	int reads = 0;
	int modifiers = 0;
	int index;
	int autoconv = 0;

	int arity;

	va_list ap;

	/* save index */
	index = ctx->request_index;

	if(ei_decode_tuple_header(ctx->request->buff,&ctx->request_index, &arity))
	{
		erl_rpc_fault(ctx,400,"Bad tuple");
		return -1;
	}

	va_start(ap,fmt);

	while(*fmt)
	{
		member_name = va_arg(ap, char*);

		if (find_member(ctx,arity,member_name))
		{
			goto error;
		}

		switch(*fmt)
		{
		case 'b': /* Bool */
		case 't': /* Date and time */
		case 'd': /* Integer */
			int_ptr = va_arg(ap, int*);

			if (get_int(int_ptr,ctx,reads,autoconv))
			{
				goto error;
			}

			break;
		case 'f': /* double */
			double_ptr = va_arg(ap, double*);

			if (get_double(double_ptr,ctx,reads,autoconv))
			{
				goto error;
			}

			break;
		case 'S': /* str structure */

			str_ptr = va_arg(ap, str*);

			if (get_str(str_ptr,ctx,reads,autoconv))
			{
				goto error;
			}

			break;
		case 's':/* zero terminated string */

			char_ptr = va_arg(ap,char**);

			if (get_str(&s,ctx,reads,autoconv))
			{
				goto error;
			}

			*char_ptr = s.s;

			break;

		 default:
			 LM_ERR("Invalid parameter type in formatting string: %c\n", *fmt);
			 erl_rpc_fault(ctx, 500, "Server Internal Error (Invalid Formatting String)");
			 goto error;
		}

		reads++;
		fmt++;
	}

	/* restore index */
	ctx->request_index = index;

    va_end(ap);
    return reads-modifiers;

error:
    va_end(ap);
    return -(reads-modifiers);
}
Esempio n. 7
0
void set_data(MPL *mpl)
{     SET *set;
      TUPLE *tuple;
      MEMBER *memb;
      SLICE *slice;
      int tr = 0;
      insist(is_literal(mpl, "set"));
      get_token(mpl /* set */);
      /* symbolic name of set must follows the keyword 'set' */
      if (!is_symbol(mpl))
         error(mpl, "set name missing where expected");
      /* select the set to saturate it with data */
      set = select_set(mpl, mpl->image);
      get_token(mpl /* <symbolic name> */);
      /* read optional subscript list, which identifies member of the
         set to be read */
      tuple = create_tuple(mpl);
      if (mpl->token == T_LBRACKET)
      {  /* subscript list is specified */
         if (set->dim == 0)
            error(mpl, "%s cannot be subscripted", set->name);
         get_token(mpl /* [ */);
         /* read symbols and construct subscript list */
         for (;;)
         {  if (!is_symbol(mpl))
               error(mpl, "number or symbol missing where expected");
            tuple = expand_tuple(mpl, tuple, read_symbol(mpl));
            if (mpl->token == T_COMMA)
               get_token(mpl /* , */);
            else if (mpl->token == T_RBRACKET)
               break;
            else
               error(mpl, "syntax error in subscript list");
         }
         if (set->dim != tuple_dimen(mpl, tuple))
            error(mpl, "%s must have %d subscript%s rather than %d",
               set->name, set->dim, set->dim == 1 ? "" : "s",
               tuple_dimen(mpl, tuple));
         get_token(mpl /* ] */);
      }
      else
      {  /* subscript list is not specified */
         if (set->dim != 0)
            error(mpl, "%s must be subscripted", set->name);
      }
      /* there must be no member with the same subscript list */
      if (find_member(mpl, set->array, tuple) != NULL)
         error(mpl, "%s%s already defined",
            set->name, format_tuple(mpl, '[', tuple));
      /* add new member to the set and assign it empty elemental set */
      memb = add_member(mpl, set->array, tuple);
      memb->value.set = create_elemset(mpl, set->dimen);
      /* create an initial fake slice of all asterisks */
      slice = fake_slice(mpl, set->dimen);
      /* read zero or more data assignments */
      for (;;)
      {  /* skip optional comma */
         if (mpl->token == T_COMMA) get_token(mpl /* , */);
         /* process assignment element */
         if (mpl->token == T_ASSIGN)
         {  /* assignment ligature is non-significant element */
            get_token(mpl /* := */);
         }
         else if (mpl->token == T_LEFT)
         {  /* left parenthesis begins either new slice or "transpose"
               indicator */
            int is_tr;
            get_token(mpl /* ( */);
            is_tr = is_literal(mpl, "tr");
            unget_token(mpl /* ( */);
            if (is_tr) goto left;
            /* delete the current slice and read new one */
            delete_slice(mpl, slice);
            slice = read_slice(mpl, set->name, set->dimen);
            /* each new slice resets the "transpose" indicator */
            tr = 0;
            /* if the new slice is 0-ary, formally there is one 0-tuple
               (in the simple format) that follows it */
            if (slice_arity(mpl, slice) == 0)
               simple_format(mpl, set, memb, slice);
         }
         else if (is_symbol(mpl))
         {  /* number or symbol begins data in the simple format */
            simple_format(mpl, set, memb, slice);
         }
         else if (mpl->token == T_COLON)
         {  /* colon begins data in the matrix format */
            if (slice_arity(mpl, slice) != 2)
err1:          error(mpl, "slice currently used must specify 2 asterisk"
                  "s, not %d", slice_arity(mpl, slice));
            get_token(mpl /* : */);
            /* read elemental set data in the matrix format */
            matrix_format(mpl, set, memb, slice, tr);
         }
         else if (mpl->token == T_LEFT)
left:    {  /* left parenthesis begins the "transpose" indicator, which
               is followed by data in the matrix format */
            get_token(mpl /* ( */);
            if (!is_literal(mpl, "tr"))
err2:          error(mpl, "transpose indicator (tr) incomplete");
            if (slice_arity(mpl, slice) != 2) goto err1;
            get_token(mpl /* tr */);
            if (mpl->token != T_RIGHT) goto err2;
            get_token(mpl /* ) */);
            /* in this case the colon is optional */
            if (mpl->token == T_COLON) get_token(mpl /* : */);
            /* set the "transpose" indicator */
            tr = 1;
            /* read elemental set data in the matrix format */
            matrix_format(mpl, set, memb, slice, tr);
         }
         else if (mpl->token == T_SEMICOLON)
         {  /* semicolon terminates the data block */
            get_token(mpl /* ; */);
            break;
         }
         else
            error(mpl, "syntax error in set data block");
      }
      /* delete the current slice */
      delete_slice(mpl, slice);
      return;
}
Esempio n. 8
0
void Server::add_user_to_channel(const uint32_t session_id, const uint16_t channel_id, const uint8_t permissions, const uint16_t warn_level, const char *voucher, const uint16_t rating) {
	Channel *chan = NULL;
	uint32_t game_id = 0;
	chan = find_channel(channel_id);
	if (chan) {
		if (session[session_id]->add_channel(channel_id)) {
			unsigned char add_msg[1000], join_msg[1000];
			char user_join_msg[1000];
			snprintf(user_join_msg, sizeof(user_join_msg), "%s joined the channel.", session[session_id]->get_name());
			const int len = strlen(user_join_msg)+1;
			for (int x = 0; x < chan->n_members; ++x) {
				chan->members[x].ptr->msg(user_join_msg, len, 0, channel_id);
			}
			
			
			join_msg[0] = SERVER_MESSAGE_CHANNEL_JOIN;
			channel_info c;
			c.channel_id = channel_id;
			c.channel_flags = chan->flags;
			strncpy(c.channel_name, chan->name, sizeof(c.channel_name));
			memcpy(&join_msg[1], &c, sizeof(c));
			session[session_id]->send_raw(join_msg, 1 + sizeof(c));
			
			add_msg[0] = SERVER_MESSAGE_CHANNEL_ADD_USER;
			user_info add_info;
			add_info.channel_id = channel_id;
			add_info.rating = rating;
			add_info.permissions = permissions;
			add_info.warn_level = warn_level;
			add_info.user_id = session[session_id]->get_user_id();
			memset(add_info.username, 0, sizeof(add_info.username));
			memset(add_info.voucher_name, 0, sizeof(add_info.voucher_name));
			strncpy(add_info.username, session[session_id]->get_name(), sizeof(add_info.username));
			strncpy(add_info.voucher_name, voucher, sizeof(add_info.voucher_name));
			
			memcpy(&add_msg[1], &add_info, sizeof(add_info));
			for (int x = 0; x < chan->n_members; ++x) {
				chan->members[x].ptr->send_raw(add_msg, 1 + sizeof(add_info));
			}
		
			
			Member *ptr = (Member*)malloc(sizeof(Member)*(chan->n_members+1));
			memcpy(ptr, chan->members, sizeof(Member)*chan->n_members);
			free(chan->members);
			chan->members = ptr;
			chan->members[chan->n_members].id = session[session_id]->get_user_id();
			chan->members[chan->n_members].ptr = session[session_id];
			chan->members[chan->n_members].permission = permissions;
			strncpy(chan->members[chan->n_members].voucher, voucher, sizeof(add_info.voucher_name));
			chan->members[chan->n_members].warn_level = warn_level;
			chan->members[chan->n_members].rating = rating;
			chan->n_members++;
			for (int x = 0; x < chan->n_members; ++x) {
				add_info.rating = chan->members[x].rating;
				add_info.permissions = chan->members[x].permission;
				add_info.warn_level = chan->members[x].warn_level;
				add_info.user_id = chan->members[x].id;
				memset(add_info.username, 0, sizeof(add_info.username));
				memset(add_info.voucher_name, 0, sizeof(add_info.voucher_name));
				strncpy(add_info.username, chan->members[x].ptr->get_name(), sizeof(add_info.username));
				strncpy(add_info.voucher_name, chan->members[x].voucher, sizeof(add_info.username));
				
				
				memcpy(&add_msg[1], &add_info, sizeof(add_info));
				session[session_id]->send_raw(add_msg, 1+sizeof(add_info));
			}
			for (int x = 0; x < chan->n_games; ++x) {
				game_state new_state;
				new_state.league_id = channel_id;
				new_state.game_id = game_id;
				memset(new_state.game_name, 0, sizeof(new_state.game_name));
				memset(new_state.host_name, 0, sizeof(new_state.host_name));

				new_state.n_users = chan->game[game_id].n_signed;
				new_state.n_max = (chan->game_id == GAME_DOTA) ? 10 : 6;
				new_state.start_time = chan->game[game_id].start_time;
				strcpy(new_state.game_name, chan->game[game_id].game_name);
				
				
				Member *m = find_member(chan->game[game_id].hoster_id, channel_id);
				
				if (m && m->ptr) strcpy(new_state.host_name, m->ptr->get_name());
				else strcpy(new_state.host_name, "Unknown"); // this results from the game being disbanded and updated.
				
				unsigned char msg[1000];
				msg[0] = SERVER_MESSAGE_CHANNEL_UPDATE_GAMEINFO;
				memcpy(&msg[1], &new_state, sizeof(new_state));
				session[session_id]->send_raw(msg, 1+sizeof(new_state));
			}
			for (int x = 0; x < chan->n_games; ++x) {
				game_state new_state;
				new_state.league_id = channel_id;
				new_state.game_id = x;
				memset(new_state.game_name, 0, sizeof(new_state.game_name));
				memset(new_state.host_name, 0, sizeof(new_state.host_name));
				new_state.n_users = chan->game[x].n_signed;
				new_state.start_time = chan->game[x].start_time;
				strcpy(new_state.game_name, chan->game[x].game_name);
				
				
				Member *m = find_member(chan->game[x].hoster_id, channel_id);
				
				if (m && m->ptr) strcpy(new_state.host_name, m->ptr->get_name());
				else strcpy(new_state.host_name, "Unknown"); // this results from the game being disbanded and updated.
				
				unsigned char msg[1000];
				msg[0] = SERVER_MESSAGE_CHANNEL_UPDATE_GAMEINFO;
				memcpy(&msg[1], &new_state, sizeof(new_state));
				session[session_id]->send_raw(msg, 1+sizeof(new_state));
			}
			mysqlpp::Query get_ratings = sql_connection.query();
			try {
				unsigned char msg[(1+sizeof(rank_state))*10];
				rank_state rank;
				get_ratings << "SELECT * FROM league_members WHERE league_id = " << channel_id << " ORDER BY rating DESC LIMIT 10";
				mysqlpp::StoreQueryResult result = get_ratings.store();
				const int size = result.num_rows();
				for (int x = 0; x < result.num_rows(); ++x) {
					mysqlpp::Query get_user = sql_connection.query();
					get_user << "SELECT * FROM users WHERE id = " << result[x]["user_id"];
					mysqlpp::StoreQueryResult user = get_user.store();
					rank.position = x;
					rank.rating = result[x]["rating"];
					rank.channel = channel_id;
					memset(rank.name, 0, sizeof(rank.name));
					if (user.num_rows()) snprintf(rank.name, sizeof(rank.name), std::string(user[0]["username"]).c_str());
					else strcpy(rank.name,"Unknown");
					msg[(1+sizeof(rank_state))*x] = SERVER_MESSAGE_CHANNEL_UPDATE_LEADERBOARDS;
					memcpy(&msg[1+((1+sizeof(rank_state))*x)], &rank, sizeof(rank));
				}
				//for (int x = 0; x < chan->n_members; ++x) {
					session[session_id]->send_raw(msg, (1+sizeof(rank))*size);
				//}
			} catch (mysqlpp::BadQuery error) {
				char buffer[2048];
				snprintf(buffer,sizeof(buffer),"SQL reported bad query: %s. Attempting reconnect...",sql_connection.error());
				puts(buffer);
			}
		}
	} 
}
Esempio n. 9
0
int main(int argc, char** argv)
{
    // Print an error if the user invokes Far with an incorrect number of
    // arguments. There should be at least "Far key archive"
    if (argc < 3) {
        ERROR("Usage: Far key archive [name]*");
        return 1;
    }

    char* key = argv[1];
    char* archive_name = argv[2];

    int num_files = argc - 3;
    char** filenames = argv + 3;

    // Ignore trailing / in NAME arguments
    for (int i = 0; i < num_files; i++) strip_trailing_slash(filenames[i]);

    if (!strcmp(key, "r")) {
        member_list* members = make_list_recursive(filenames, num_files);
        archive_t* archive = open_archive(archive_name, true);
        member_list* processed_members =
          process_members(archive, members, replace_current_member);
        // Now that previously existing files have been deleted, add the
        // files to the end of the archive
        member_node* cur_member = members;
        while (cur_member) {
            add_member(archive, cur_member->filename);
            cur_member = cur_member->next;
        }
        delete_list(processed_members);
        close_archive(archive, true);

        delete_list(members);
        return 0;
    } else if (!strcmp(key, "x")) {
        member_list* members = make_list(filenames, num_files);
        archive_t* archive = open_archive(archive_name, false);
        member_list* processed_members =
          process_members(archive, members, extract_current_member);
        // Error handling for unprocessed NAME arguments
        for (int i = 0; i < num_files; i++) {
            char* name = filenames[i];
            if (!find_member(name, processed_members)) {
                ERROR_CREATE(name);
            }
        }
        delete_list(processed_members);
        close_archive(archive, false);

        delete_list(members);
        return 0;
    } else if (!strcmp(key, "d")) {
        member_list* members = make_list(filenames, num_files);
        archive_t* archive = open_archive(archive_name, false);
        member_list* processed_members =
          process_members(archive, members, delete_current_member);
        // Error handling for unprocessed NAME arguments
        for (int i = 0; i < num_files; i++) {
            char* name = filenames[i];
            if (!find_member(name, processed_members) &&
                !find_child(name, processed_members)) {
                ERROR_FIND(name);
            }
        }
        delete_list(processed_members);
        close_archive(archive, true);

        delete_list(members);
        return 0;
    } else if (!strcmp(key, "t")) {
        archive_t* archive = open_archive(archive_name, false);
        member_list* processed_members =
          process_members(archive, NULL, print_current_member);
        delete_list(processed_members);
        close_archive(archive, false);
        return 0;
    } else {
        ERROR("Key options: 'r', 'x', 'd', 't'");
        return 1;
    }
}
Esempio n. 10
0
static int mkgrplist(char *buf, gid_t **list, int len)
{
     int l,at=0;
     int blks;

     blks = blk_size(len);
     D(("cf. blks=%d and len=%d", blks,len));

     while ((l = find_member(buf,&at))) {
	  int edge;

	  if (len >= blks) {
	       gid_t *tmp;

	       D(("allocating new block"));
	       tmp = (gid_t *) realloc((*list)
				       , sizeof(gid_t) * (blks += GROUP_BLK));
	       if (tmp != NULL) {
		    (*list) = tmp;
	       } else {
		    _log_err("out of memory for group list");
		    free(*list);
		    (*list) = NULL;
		    return -1;
	       }
	  }

	  /* '\0' terminate the entry */

	  edge = (buf[at+l]) ? 1:0;
	  buf[at+l] = '\0';
	  D(("found group: %s",buf+at));

	  /* this is where we convert a group name to a gid_t */
#ifdef WANT_PWDB
	  {
	      int retval;
	      const struct pwdb *pw=NULL;

	      retval = pwdb_locate("group", PWDB_DEFAULT, buf+at
				   , PWDB_ID_UNKNOWN, &pw);
	      if (retval != PWDB_SUCCESS) {
		  _log_err("bad group: %s; %s", buf+at, pwdb_strerror(retval));
	      } else {
		  const struct pwdb_entry *pwe=NULL;

		  D(("group %s exists", buf+at));
		  retval = pwdb_get_entry(pw, "gid", &pwe);
		  if (retval == PWDB_SUCCESS) {
		      D(("gid = %d [%p]",* (const gid_t *) pwe->value,list));
		      (*list)[len++] = * (const gid_t *) pwe->value;
		      pwdb_entry_delete(&pwe);                  /* tidy up */
		  } else {
		      _log_err("%s group entry is bad; %s"
			       , pwdb_strerror(retval));
		  }
		  pw = NULL;          /* break link - cached for later use */
	      }
	  }
#else
	  {
	      const struct group *grp;

	      grp = getgrnam(buf+at);
	      if (grp == NULL) {
		  _log_err("bad group: %s", buf+at);
	      } else {
		  D(("group %s exists", buf+at));
		  (*list)[len++] = grp->gr_gid;
	      }
	  }
#endif

	  /* next entry along */

	  at += l + edge;
     }
     D(("returning with [%p/len=%d]->%p",list,len,*list));
     return len;
}
Esempio n. 11
0
/*
 * Begin a macro.
 *
 * Once we figure out the type of the thing that we're supposed to dump (struct,
 * union, or enum), we select the proper type-specific ops-vector for dumping.
 */
static int
fth_section_init(char *fullname)
{
	ctf_id_t ltid = 0, tid;
	char *curtype, *lpart, *part, *npart;
	int lkind = 0, kind;

	curtype = xstrdup(fullname);
	lpart = NULL;
	part = strtok(fullname, ".");

	/*
	 * First figure out what sort of type we're looking at.  Life would be
	 * simple if we were only going to get type names, but it's not - we
	 * could also get `type.member'.  In that case, we need to figure out
	 * (and dump) the type of `member' instead.
	 */
	for (;;) {
		if (lpart == NULL) {
			/* First part - the struct name */
			if ((tid = find_type(part)) == CTF_ERR ||
			    (tid = ctf_type_resolve(ctf, tid)) == CTF_ERR ||
			    (kind = ctf_type_kind(ctf, tid)) == CTF_ERR) {
				free(curtype);
				return (parse_warn("Couldn't find %s: %s",
				    part, ctf_errmsg(ctf_errno(ctf))));
			}
		} else {
			/* Second (or more) part - the member name */
			if (lkind != CTF_K_STRUCT && lkind != CTF_K_UNION) {
				free(curtype);
				return (parse_warn("%s isn't a struct/union",
				    lpart));
			}

			if ((tid = find_member(ltid, part)) <= 0) {
				free(curtype);
				return (parse_warn("%s isn't a member of %s",
				    part, lpart));
			}

			if ((kind = ctf_type_kind(ctf, tid)) == CTF_ERR) {
				free(curtype);
				return (parse_warn("Can't get kind for %s",
				    part));
			}
		}

		/*
		 * Stop if there aren't any more parts.  We use `npart' here
		 * because we don't want to clobber part - we need it later.
		 */
		if ((npart = strtok(NULL, ".")) == NULL)
			break;

		lpart = part;
		ltid = tid;
		lkind = kind;

		part = npart;
	}

	/*
	 * Pick the right ops vector for dumping.
	 */
	switch (kind) {
	case CTF_K_STRUCT:
	case CTF_K_UNION:
		fth_type_ops = &fth_struct_ops;
		break;

	case CTF_K_ENUM:
		fth_type_ops = &fth_enum_ops;
		break;

	default:
		fth_type_ops = &fth_null_ops;
		free(curtype);
		return (parse_warn("%s isn't a struct, union, or enum", part));
	}

	fth_curtype = curtype;

	return (fth_type_ops->fto_header(tid));
}
Esempio n. 12
0
/*
 * Count chacacters and strip comments.  The stripped input is
 * sent to standard output.  The count is sent to to standard error
 * unless -i is given in which case the IOCCC size rule count is
 * sent to standard out.
 *
 * Not withstanding -i, if silence is true, then do not print anything
 * to standard output.
 */
int
count(int flags)
{
	Word *w;
	int span;
	char *p, buf[256];
	int lcount, wcount, bcount;
	int is_comment, is_word, dquote;
	int count, keywords, saved, kw_saved;

	/* Start of buffer sentinel. */
	buf[0] = ' ';

	count = saved = 0;
	keywords = kw_saved = 0;
	lcount = wcount = bcount = 0;
	is_comment = is_word = dquote = 0;

	/*
	 * "no matter how well you may think you understand this code,
	 *  you don't, so don't mess with it." :-)
	 */
	for ( ; fgets(buf+1, sizeof (buf)-1, stdin) != NULL;) {
		/* Leading whitespace before comment block? */
		span = strspn(buf+1, "\t ");
		if (buf[1+span] == '/' && buf[2+span] == '*') {
			/* Strip leading whitespace before comment block. */
			is_comment = 1;
		}

		for (p = buf+1; *p != '\0'; p++) {
			/* Strip comment block? */
			if (is_comment) {
				/* End of comment? */
				if (*p == '*' && p[1] == '/') {
					is_comment = 0;

					/* Remove whitespace and newline
					 * trailing closing comment.
					 */
					p += 1 + strspn(p+2, " \t\r\n");
				}
				/* Skip octets in comment block. */
				continue;
			}

			/* Start of comment block to strip? */
			/* "You are not expected to understand this" */
			if (!(flags & FLAG_KEEP) && !dquote && *p == '/' && p[1] == '*') {
				/* Begin comment block. */
				is_comment = 1;
				p++;
				continue;
			}

			/* Toggle start/end of double-quote string. */
			if (*p == '"' && p[-1] != '\\' && p[-1] != '\'')
				dquote = !dquote;

			/* C reserved word? */
			if (!dquote && (w = find_member(cwords, p)) != NULL) {
				keywords++;
				if (flags & FLAG_RESERVED) {
					bcount += w->length;
					if (!is_word) {
						is_word = 1;
						wcount++;
					}

					if (!(flags & FLAG_SILENCE))
						fputs(w->word, stdout);

					/* Count reserved word as one. */
					kw_saved += w->length - 1;
					p += w->length - 1;
					count++;
					continue;
				}
			}

			/* Everything above here is stripped from the input. */
			if (!(flags & FLAG_SILENCE))
				fputc(*p, stdout);

			bcount++;
			if (*p == '\n')
				lcount++;

			/* Ignore all whitespace. */
			if (isspace(*p)) {
				is_word = 0;
				saved++;
				continue;
			} else if (!is_word) {
				is_word = 1;
				wcount++;
			}

			/* Ignore curly braces and semicolons when followed
			 * by any whitspace or EOF.
			 */
			if (strchr("{;}", *p) != NULL
			&& (isspace(p[1]) || p[1] == '\0')) {
				saved++;
				continue;
			}
			/* Count this octet. */
			count++;
		}
	}

	/* final count */
	if (flags & FLAG_IOCCC_SIZE) {
		/* output the official IOCCC size tool size to standard out */
		printf("%d\n", count);
	} else {
		fprintf(stderr, "%d %d %d %d %d %d %d\n",
			lcount, wcount, bcount, count, saved,
			keywords, kw_saved);
	}
	return count;
}
Esempio n. 13
0
/**
 * tracker_gsf_parse_xml_in_zip:
 * @zip_file_uri: URI of the ZIP archive
 * @xml_filename: Name of the XML file stored inside the ZIP archive
 * @context: Markup context to be used when parsing the XML
 *
 * This function reads and parses the contents of an XML file stored
 *  inside a ZIP compressed archive. Reading and parsing is done buffered, and
 *  maximum size of the uncompressed XML file is limited to be to 20MBytes.
 */
void
tracker_gsf_parse_xml_in_zip (const gchar          *zip_file_uri,
                              const gchar          *xml_filename,
                              GMarkupParseContext  *context,
                              GError              **err)
{
	gchar *filename;
	GError *error = NULL;
	GsfInfile *infile = NULL;
	GsfInput *src = NULL;
	GsfInput *member = NULL;
	FILE *file;

	g_debug ("Parsing '%s' XML file contained inside zip archive...",
	         xml_filename);

	/* Get filename from the given URI */
	if ((filename = g_filename_from_uri (zip_file_uri,
	                                     NULL, &error)) == NULL) {
		g_warning ("Can't get filename from uri '%s': %s",
		           zip_file_uri, error ? error->message : "no error given");
	} else { /* Create a new Input GSF object for the given file */

		file = tracker_file_open (filename);
		if (!file) {
			g_warning ("Can't open file from uri '%s': %s",
			           zip_file_uri, g_strerror (errno));
		} else if ((src = gsf_input_stdio_new_FILE (filename, file, TRUE)) == NULL) {
			g_warning ("Failed creating a GSF Input object for '%s': %s",
			           zip_file_uri, error ? error->message : "no error given");
		}
		/* Input object is a Zip file */
		else if ((infile = gsf_infile_zip_new (src, &error)) == NULL) {
			g_warning ("'%s' Not a zip file: %s",
			           zip_file_uri, error ? error->message : "no error given");
		}
		/* Look for requested filename inside the ZIP file */
		else if ((member = find_member (infile, xml_filename)) == NULL) {
			g_warning ("No member '%s' in zip file '%s'",
			           xml_filename, zip_file_uri);
		}
		/* Load whole contents of the internal file in the xml buffer */
		else {
			guint8 buf[XML_BUFFER_SIZE];
			size_t remaining_size, chunk_size, accum;

			/* Get whole size of the contents to read */
			remaining_size = (size_t) gsf_input_size (GSF_INPUT (member));

			/* Note that gsf_input_read() needs to be able to read ALL specified
			 *  number of bytes, or it will fail */
			chunk_size = MIN (remaining_size, XML_BUFFER_SIZE);

			accum = 0;
			while (!error &&
			       accum  <= XML_MAX_BYTES_READ &&
			       chunk_size > 0 &&
			       gsf_input_read (GSF_INPUT (member), chunk_size, buf) != NULL) {

				/* update accumulated count */
				accum += chunk_size;

				/* Pass the read stream to the context parser... */
				g_markup_parse_context_parse (context, buf, chunk_size, &error);

				/* update bytes to be read */
				remaining_size -= chunk_size;
				chunk_size = MIN (remaining_size, XML_BUFFER_SIZE);
			}
		}

		if (file) {
			tracker_file_close (file, FALSE);
		}
	}

	g_free (filename);

	if (error)
		g_propagate_error (err, error);
	if (infile)
		g_object_unref (infile);
	if (src)
		g_object_unref (src);
	if (member)
		g_object_unref (member);
}