Exemplo n.º 1
0
/** Read the file with the tips-of-the-day. */
static void read_tips_of_day(config& tips_of_day)
{
	loadscreen::global_loadscreen->disable_increments = true;
	
	tips_of_day.clear();

#ifdef FREE_VERSION
	std::string filename = get_cache_dir() + "/tips_free";
#else
	std::string filename = get_cache_dir() + "/tips";
#endif
	std::string checkFilename = filename + ".cache.dat";
	if (!file_exists(checkFilename))
	{
		try {
#ifdef FREE_VERSION
			scoped_istream stream = preprocess_file(get_wml_location("hardwired/tips_free.cfg"));
#else
			scoped_istream stream = preprocess_file(get_wml_location("hardwired/tips.cfg"));
#endif
			read(tips_of_day, *stream);
		} catch(config::error&) {
	//		ERR_CONFIG << "Could not read data/hardwired/tips.cfg\n";
		}
	
		tips_of_day.saveCache(filename);
	}
	else
	{
		tips_of_day.loadCache(filename);
	}
	
	
	//we shuffle the tips after each initial loading. We only shuffle if
	//the upload_log preference has been set. If it hasn't been set, it's the
	//user's first time playing since this feature has been added, so we'll
	//leave the tips in their default order, which will always contain a tip
	//regarding the upload log first, so the user sees it.
	config::child_itors tips = tips_of_day.child_range("tip");
	if (tips.first != tips.second && preferences::has_upload_log()) {
		std::random_shuffle(tips.first, tips.second);
	}
	
	//Make sure that the upload log preference is set, if it's not already, so
	//that we know next time we've already seen the message about uploads.
	if(!preferences::has_upload_log()) 
	{
		//preferences::set_upload_log(preferences::upload_log());
		preferences::set_upload_log(false);
	}
	loadscreen::global_loadscreen->disable_increments = false;

}
Exemplo n.º 2
0
FILE* run_preprocessor(FILE* input, char* filename)
{
	assert(input);
	
	preprocessor_state preproc;

	preproc.input = input;

	preproc.output = tmpfile();
	if (!preproc.output) {
		perror("Failed to open file for preprocessor output");
		exit(0);
	}

	cvec_str(&preproc.macros, 0, 15);
	cvec_str(&preproc.values, 0, 15);
	cvec_void(&preproc.params, 0, 15, sizeof(macro_params), free_macro_params, NULL);
	cvec_token_lex(&preproc.if_stack, 0, 10, free_token_lex, NULL);
	
	preproc.lexer = (lexer_state){ filename, 1, 0, 0 }; //TODO
	preprocess_file(&preproc);

	cvec_free_str(&preproc.macros);
	cvec_free_str(&preproc.values);
	cvec_free_void(&preproc.params);
	cvec_free_token_lex(&preproc.if_stack);
	fclose(input);

	rewind(preproc.output);
	return preproc.output;
}
Exemplo n.º 3
0
bool schema_validator::read_config_file(const std::string &filename){
	config cfg;
	try {
		preproc_map preproc(
				game_config::config_cache::instance().get_preproc_map());
		filesystem::scoped_istream stream = preprocess_file(filename, &preproc);
		read(cfg, *stream);
	} catch(config::error& e) {
		ERR_VL << "Failed to read file "<< filename << ":\n" << e.what() << "\n";
		return false;
	}
	for(const config &g : cfg.child_range("wml_schema")) {
		for(const config &schema : g.child_range("tag")) {
			if (schema["name"].str() == "root"){
				//@NOTE Don't know, maybe merging of roots needed.
				root_ = class_tag (schema);
			}
		}
		for(const config &type : g.child_range("type")) {
			try{
				types_[type["name"].str()] = boost::regex( type["value"].str());
			}
			catch (std::exception){
			// Need to check all type values in schema-generator
			}
		}
	}

	config_read_ = true;
	return true;
}
Exemplo n.º 4
0
bool load_font_config()
{
    //read font config separately, so we do not have to re-read the whole
    //config when changing languages
    config cfg;
    try {
        const std::string& cfg_path = filesystem::get_wml_location("hardwired/fonts.cfg");
        if(cfg_path.empty()) {
            ERR_FT << "could not resolve path to fonts.cfg, file not found\n";
            return false;
        }

        filesystem::scoped_istream stream = preprocess_file(cfg_path);
        read(cfg, *stream);
    } catch(config::error &e) {
        ERR_FT << "could not read fonts.cfg:\n"
               << e.message << '\n';
        return false;
    }

    const config &fonts_config = cfg.child("fonts");
    if (!fonts_config)
        return false;

    std::set<std::string> known_fonts;
    for (const config &font : fonts_config.child_range("font")) {
        known_fonts.insert(font["name"]);
        if (font.has_attribute("bold_name")) {
            known_fonts.insert(font["bold_name"]);
        }
        if (font.has_attribute("italic_name")) {
            known_fonts.insert(font["italic_name"]);
        }
    }

    family_order_sans = fonts_config["family_order"];
    family_order_mono = fonts_config["family_order_monospace"];

    if(family_order_mono.empty()) {
        ERR_FT << "No monospace font family order defined, falling back to sans serif order\n";
        family_order_mono = family_order_sans;
    }

    std::vector<font::subset_descriptor> fontlist;

    for(auto font : utils::split(fonts_config["order"])) {
        add_font_to_fontlist(fonts_config, fontlist, font);
        known_fonts.erase(font);
    }

    for(auto kfont : known_fonts) {
        add_font_to_fontlist(fonts_config, fontlist, kfont);
    }

    if(fontlist.empty())
        return false;

    sdl_ttf::set_font_list(fontlist);
    return true;
}
Exemplo n.º 5
0
bool load_language_list()
{
	config cfg;
	try {
		if (game_config::use_bin) {
			wml_config_from_file(game_config::path + "/xwml/" + "language.bin", cfg);
		} else {
			scoped_istream stream = preprocess_file(get_wml_location("hardwired/language.cfg"));
			read(cfg, *stream);

			wml_config_to_file(game_config::path + "/xwml/" + "language.bin", cfg);
		}
	} catch(config::error &) {
		return false;
	}

	known_languages.clear();
	known_languages.push_back(
		language_def("", t_string(N_("System default language"), "wesnoth"), "ltr", "", "A"));

	foreach (const config &lang, cfg.child_range("locale"))
	{
		known_languages.push_back(
			language_def(lang["locale"], lang["name"], lang["dir"],
			             lang["alternates"], lang["sort_name"]));
	}

	return true;
}
bool schema_validator::read_config_file(const std::string &filename){
	config cfg;
	try {
		preproc_map preproc(
				game_config::config_cache::instance().get_preproc_map());
		scoped_istream stream = preprocess_file(filename, &preproc);
		read(cfg, *stream);
	} catch(config::error&) {
		return false;
	}
	BOOST_FOREACH(const config &g, cfg.child_range("wml_schema")) {
		BOOST_FOREACH(const config &schema, g.child_range("tag")) {
			if (schema["name"].str() == "root"){
				//@NOTE Don't know, maybe merging of roots needed.
				root_ = class_tag (schema);
			}
		}
		BOOST_FOREACH(const config &type, g.child_range("type")) {
			try{
				types_[type["name"].str()] = boost::regex( type["value"].str());
			}
			catch (std::exception){
			// Need to check all type values in schema-generator
			}
		}
	}

	config_read_ = true;
	return true;
}
Exemplo n.º 7
0
void handle_include(preprocessor_state* preproc)
{
	int line = preproc->lexer.cur_line;
	token_lex tok_lex = read_token(preproc->input, &preproc->lexer, NULL);
	if (tok_lex.line != line)
		preprocessor_error(NULL, &preproc->lexer, "include directive arguments should all be on the same line\n");
	
	if (tok_lex.tok.type != LESS && tok_lex.tok.type != STR_LITERAL) {
		preprocessor_error(&tok_lex, &preproc->lexer, "expected < or \" for include,");
	}
	
	lexer_state save_lexer;
	long fpos;
	//I don't support <> for now
	if (tok_lex.tok.type == LESS) {
		//just clear the line
		while (1) {
			save_lexer = preproc->lexer;
			if ((fpos = ftell(preproc->input)) == -1) {
				perror("ftell error in handle_include");
				exit(0);
			}
			tok_lex = read_token(preproc->input, &preproc->lexer, NULL);
			if (tok_lex.line != line) {
				if (tok_lex.tok.type == ID || tok_lex.tok.type == STR_LITERAL)
					free(tok_lex.tok.v.id);
				preproc->lexer = save_lexer;
				if (fseek(preproc->input, fpos, SEEK_SET)) {
					perror("fseek failure in handle_include");
					exit(0);
				}
				return;
			}
			if (tok_lex.tok.type == ID || tok_lex.tok.type == STR_LITERAL)
				free(tok_lex.tok.v.id);
		}
	}

	FILE* file = fopen(tok_lex.tok.v.id, "r");
	if (!file) {
		preprocessor_error(NULL, &preproc->lexer, "error opening file %s\n", tok_lex.tok.v.id);
	}

	save_lexer = preproc->lexer;
	FILE* save_input = preproc->input;
	preproc->lexer = (lexer_state){ tok_lex.tok.v.id, 1, 0, 0 };
	preproc->input = file;
	
	preprocess_file(preproc);

	preproc->lexer = save_lexer;
	preproc->input = save_input;

	fprintf(preproc->output, "# %u \"%s\"\n", save_lexer.cur_line, save_lexer.cur_file);

	free(tok_lex.tok.v.id);
	fclose(file);
}
Exemplo n.º 8
0
Arquivo: pp.c Projeto: 0xroot/radare2
// TODO: Import enviroment variables?
// TODO: return error if failed
void cparsepp_file_fd (FILE *infile, FILE *outfile) {
	CparseSYM *defs = initsymset ();
	CparseSYM *undefs = initsymset ();
	CparsePP *pp = initppproc (defs, undefs);
	preprocess_file (pp, infile, outfile);
	freeppproc (pp);
	freesymset (defs);
	freesymset (undefs);
}
Exemplo n.º 9
0
void load_settings()
{
	LOG_GUI_G << "Setting: init gui.\n";

	// Init.
	twindow::update_screen_size();

	// Read file.
	config cfg;
	try
	{
		schema_validation::schema_validator validator(
				filesystem::get_wml_location("gui/schema.cfg"));
		preproc_map preproc(
				game_config::config_cache::instance().get_preproc_map());
		filesystem::scoped_istream stream = preprocess_file(
				filesystem::get_wml_location("gui/_main.cfg"), &preproc);

		read(cfg, *stream, &validator);
	}
	catch(config::error& e)
	{
		ERR_GUI_P << e.what() << '\n';
		ERR_GUI_P << "Setting: could not read file 'data/gui/_main.cfg'."
				  << std::endl;
	}
	catch(const abstract_validator::error& e)
	{
		ERR_GUI_P << "Setting: could not read file 'data/gui/schema.cfg'."
				  << std::endl;
		ERR_GUI_P << e.message;
	}
	// Parse guis
	for(const auto & g : cfg.child_range("gui"))
	{
		std::pair<std::string, tgui_definition> child;
		child.first = child.second.read(g);
		guis.insert(child);
	}

	default_gui = guis.find("default");
	VALIDATE(default_gui != guis.end(), _("No default gui defined."));

	std::string current_theme = preferences::gui_theme();
	current_gui = current_theme.empty() ? default_gui : guis.find(current_theme);
	if(current_gui == guis.end()) {
		ERR_GUI_P << "Missing [gui] definition for '" << current_theme << "'\n";
		current_gui = default_gui;
	}
	current_gui->second.activate();
}
const config cutter::load_config(const std::string &filename)
{
	const std::string conf_string = find_configuration(filename);

	config res;

	try {
		scoped_istream stream = preprocess_file(conf_string);
		read(res, *stream);
	} catch(config::error& err) {
		throw exploder_failure("Unable to load the configuration for the file " + filename + ": "+ err.message);
	}

	return res;
}
Exemplo n.º 11
0
bool set_language(const language_def& locale)
{
	strings_.clear();

	std::string locale_lc;
	locale_lc.resize(locale.localename.size());
	std::transform(locale.localename.begin(),locale.localename.end(),locale_lc.begin(),tolower);

	config cfg;

	current_language = locale;
	wesnoth_setlocale(LC_MESSAGES, locale.localename, &locale.alternates);
	wesnoth_setlocale(LC_COLLATE, locale.localename, &locale.alternates);

	// fill string_table (should be moved somwhere else some day)
	try {
		scoped_istream stream = preprocess_file(get_wml_location("hardwired/english.cfg"));
		read(cfg, *stream);
	} catch(config::error& e) {
		std::cerr << "Could not read english.cfg\n";
		throw e;
	}

	config* langp = cfg.child("language");
	if (langp == NULL) {
		std::cerr << "No [language] block found in english.cfg\n";
		return false;
	}

	for(string_map::const_iterator j = langp->values.begin(); j != langp->values.end(); ++j) {
		strings_[j->first] = j->second;
	}
	// end of string_table fill

	// Reset translations for the name of current languages
//	for (language_list::iterator itor = known_languages.begin();
//			itor != known_languages.end(); ++itor) {
//
//		itor->language.reset_translation();
//	}

	return true;
}
Exemplo n.º 12
0
/**
 * Loads a WML file into a config
 * - Arg 1: WML file path
 * - Arg 2: (optional) Array of preprocessor defines, or false to skip preprocessing (true is also valid)
 * - Arg 3: (optional) Path to a schema file for validation (omit for no validation)
 * - Ret: config
 */
static int intf_load_wml(lua_State* L)
{
	std::string file = luaL_checkstring(L, 1);
	bool preprocess = true;
	preproc_map defines_map;
	if(lua_type(L, 2) == LUA_TBOOLEAN) {
		preprocess = luaW_toboolean(L, 2);
	} else if(lua_type(L, 2) == LUA_TTABLE || lua_type(L, 2) == LUA_TUSERDATA) {
		lua_len(L, 2);
		int n = lua_tonumber(L, -1);
		lua_pop(L, 1);
		for(int i = 0; i < n; i++) {
			lua_geti(L, 2, i);
			if(!lua_isstring(L, -1)) {
				return luaL_argerror(L, 2, "expected bool or array of strings");
			}
			std::string define = lua_tostring(L, -1);
			lua_pop(L, 1);
			if(!define.empty()) {
				defines_map.emplace(define, preproc_define(define));
			}
		}
	} else if(!lua_isnoneornil(L, 2)) {
		return luaL_argerror(L, 2, "expected bool or array of strings");
	}
	std::string schema_path = luaL_optstring(L, 3, "");
	std::shared_ptr<schema_validation::schema_validator> validator;
	if(!schema_path.empty()) {
		validator.reset(new schema_validation::schema_validator(filesystem::get_wml_location(schema_path)));
		validator->set_create_exceptions(false); // Don't crash if there's an error, just go ahead anyway
	}
	std::string wml_file = filesystem::get_wml_location(file);
	filesystem::scoped_istream stream;
	config result;
	if(preprocess) {
		stream = preprocess_file(wml_file, &defines_map);
	} else {
		stream.reset(new std::ifstream(wml_file));
	}
	read(result, *stream, validator.get());
	luaW_pushconfig(L, result);
	return 1;
}
/** Read the file with the tips-of-the-day. */
void read_tips_of_day(config& tips_of_day)
{
	tips_of_day.clear();
	LOG_CF << "Loading tips of day\n";
	try {
		scoped_istream stream = preprocess_file(get_wml_location("hardwired/tips.cfg"));
		read(tips_of_day, *stream);
	} catch(config::error&) {
		ERR_CF << "Could not read data/hardwired/tips.cfg\n";
	}

	//We shuffle the tips after each initial loading.
	config::const_child_itors itors = tips_of_day.child_range("tip");
	if (itors.first != itors.second ) {
		std::vector<config> tips(itors.first, itors.second);
		std::random_shuffle(tips.begin(), tips.end());
		tips_of_day.clear();
		foreach (const config &tip, tips) {
			tips_of_day.add_child("tip", tip);
		}
Exemplo n.º 14
0
/**
 * Function called by the directory iterator to (recursively) add all
 * of the files in the directory to the tree.  Called by the directory
 * scanner to initiate the scan.  Does NOT yet add any metadata.
 *
 * @param cls the `struct RecursionContext`
 * @param filename file or directory to scan
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
static int
scan_callback (void *cls,
	       const char *filename)
{
  struct RecursionContext *rc = cls;
  struct ScanTreeNode *chld;

  if (GNUNET_OK !=
      preprocess_file (filename,
		       &chld))
  {
    rc->stop = GNUNET_YES;
    return GNUNET_SYSERR;
  }
  if (NULL == chld)
    return GNUNET_OK;
  chld->parent = rc->parent;
  GNUNET_CONTAINER_DLL_insert (rc->parent->children_head,
			       rc->parent->children_tail,
			       chld);
  return GNUNET_OK;
}
Exemplo n.º 15
0
bool load_language_list()
{
	config cfg;
	try {
		scoped_istream stream = preprocess_file(get_wml_location("hardwired/language.cfg"));
		read(cfg, *stream);
	} catch(config::error &) {
		return false;
	}

	known_languages.clear();
	known_languages.push_back(
		language_def("", "System default language", "ltr", "", "A"));

	config::const_child_itors langs = cfg.child_range("locale");
	for(;langs.first != langs.second; ++langs.first) {
		known_languages.push_back(
			language_def((**langs.first)["locale"], (**langs.first)["name"], (**langs.first)["dir"],
				(**langs.first)["alternates"], (**langs.first)["sort_name"]));
	}

	return true;
}
Exemplo n.º 16
0
bool load_language_list()
{
	config cfg;
	try {
		scoped_istream stream = preprocess_file(get_wml_location("hardwired/language.cfg"));
		read(cfg, *stream);
	} catch(config::error &) {
		return false;
	}

	known_languages.clear();
	known_languages.push_back(
		language_def("", t_string(N_("System default language"), "wesnoth"), "ltr", "", "A"));

	BOOST_FOREACH(const config &lang, cfg.child_range("locale"))
	{
		known_languages.push_back(
			language_def(lang["locale"], lang["name"], lang["dir"],
			             lang["alternates"], lang["sort_name"]));
	}

	return true;
}
Exemplo n.º 17
0
bool set_language(const language_def& locale)
{
	strings_.clear();

	std::string locale_lc;
	locale_lc.resize(locale.localename.size());
	std::transform(locale.localename.begin(),locale.localename.end(),locale_lc.begin(),tolower);

	config cfg;

	current_language = locale;
	wesnoth_setlocale(LC_COLLATE, locale.localename, &locale.alternates);
	wesnoth_setlocale(LC_TIME, locale.localename, &locale.alternates);
	wesnoth_setlocale(LC_MESSAGES, locale.localename, &locale.alternates);

	// fill string_table (should be moved somwhere else some day)
	try {
		scoped_istream stream = preprocess_file(get_wml_location("hardwired/english.cfg"));
		read(cfg, *stream);
	} catch(config::error& e) {
		std::cerr << "Could not read english.cfg\n";
		throw e;
	}

	config &langp = cfg.child("language");
	if (!langp) {
		std::cerr << "No [language] block found in english.cfg\n";
		return false;
	}

	foreach (const config::attribute &j, langp.attribute_range()) {
		strings_[j.first] = j.second;
	}
	// end of string_table fill

	return true;
}
Exemplo n.º 18
0
/** Read the file with the tips-of-the-day. */
void read_tips_of_day(config& tips_of_day)
{
	tips_of_day.clear();
	LOG_CF << "Loading tips of day\n";
	try {
		scoped_istream stream = preprocess_file(get_wml_location("hardwired/tips.cfg"));
		read(tips_of_day, *stream);
	} catch(config::error&) {
		ERR_CF << "Could not read data/hardwired/tips.cfg\n";
	}

	//we shuffle the tips after each initial loading. We only shuffle if
	//the upload_log preference has been set. If it hasn't been set, it's the
	//user's first time playing since this feature has been added, so we'll
	//leave the tips in their default order, which will always contain a tip
	//regarding the upload log first, so the user sees it.
	config::const_child_itors itors = tips_of_day.child_range("tip");
	if (itors.first != itors.second && preferences::has_upload_log()) {
		std::vector<config> tips(itors.first, itors.second);
		std::random_shuffle(tips.begin(), tips.end());
		tips_of_day.clear();
		foreach (const config &tip, tips) {
			tips_of_day.add_child("tip", tip);
		}
Exemplo n.º 19
0
/**
 * Main function of the helper process to extract meta data.
 *
 * @param argc should be 3
 * @param argv [0] our binary name
 *             [1] name of the file or directory to process
 *             [2] "-" to disable extraction, NULL for defaults,
 *                 otherwise custom plugins to load from LE
 * @return 0 on success
 */
int
main (int argc,
      char *const *argv)
{
  const char *filename_expanded;
  const char *ex;
  struct ScanTreeNode *root;

#if WINDOWS
  /* We're using stdout to communicate binary data back to the parent; use
   * binary mode.
   */
  _setmode (1, _O_BINARY);
  /* Get utf-8-encoded arguments */
  if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
    return 5;
  output_stream = 1; /* stdout */
#else
  ignore_sigpipe ();
  /* move stdout to some other FD for IPC, bind
     stdout/stderr to /dev/null */
  output_stream = dup (1);
  make_dev_zero (1, O_WRONLY);
  make_dev_zero (2, O_WRONLY);
#endif

  /* parse command line */
  if ( (3 != argc) && (2 != argc) )
  {
    FPRINTF (stderr,
	     "%s",
	     "gnunet-helper-fs-publish needs exactly one or two arguments\n");
#if WINDOWS
    GNUNET_free ((void*) argv);
#endif
    return 1;
  }
  filename_expanded = argv[1];
  ex = argv[2];
  if ( (NULL == ex) ||
       (0 != strcmp (ex, "-")) )
  {
#if HAVE_LIBEXTRACTOR
    plugins = EXTRACTOR_plugin_add_defaults (EXTRACTOR_OPTION_DEFAULT_POLICY);
    if (NULL != ex)
      plugins = EXTRACTOR_plugin_add_config (plugins, ex,
					     EXTRACTOR_OPTION_DEFAULT_POLICY);
#endif
  }

  /* scan tree to find out how much work there is to be done */
  if (GNUNET_OK != preprocess_file (filename_expanded,
				    &root))
  {
    (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0);
#if HAVE_LIBEXTRACTOR
    EXTRACTOR_plugin_remove_all (plugins);
#endif
#if WINDOWS
    GNUNET_free ((void*) argv);
#endif
    return 2;
  }
  /* signal that we're done counting files, so that a percentage of
     progress can now be calculated */
  if (GNUNET_OK !=
      write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE, NULL, 0))
  {
#if HAVE_LIBEXTRACTOR
    EXTRACTOR_plugin_remove_all (plugins);
#endif
#if WINDOWS
    GNUNET_free ((void*) argv);
#endif
    return 3;
  }
  if (NULL != root)
  {
    if (GNUNET_OK !=
	extract_files (root))
    {
      (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0);
      free_tree (root);
#if HAVE_LIBEXTRACTOR
      EXTRACTOR_plugin_remove_all (plugins);
#endif
#if WINDOWS
      GNUNET_free ((void*) argv);
#endif
      return 4;
    }
    free_tree (root);
  }
  /* enable "clean" shutdown by telling parent that we are done */
  (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED, NULL, 0);
#if HAVE_LIBEXTRACTOR
  EXTRACTOR_plugin_remove_all (plugins);
#endif
#if WINDOWS
  GNUNET_free ((void*) argv);
#endif
  return 0;
}
/**
 * Main function of the helper process to extract meta data.
 *
 * @param argc should be 3
 * @param argv [0] our binary name
 *             [1] name of the file or directory to process
 *             [2] "-" to disable extraction, NULL for defaults,
 *                 otherwise custom plugins to load from LE
 * @return 0 on success
 */
int main(int argc,
	 char **argv)
{
  const char *filename_expanded;
  const char *ex;
  struct ScanTreeNode *root;

#if WINDOWS
  /* We're using stdout to communicate binary data back to the parent; use
   * binary mode.
   */
  _setmode (1, _O_BINARY);
#endif

  /* parse command line */
  if ( (3 != argc) && (2 != argc) )
  {
    FPRINTF (stderr, 
	     "%s",
	     "gnunet-helper-fs-publish needs exactly one or two arguments\n");
    return 1;
  }
  filename_expanded = argv[1];
  ex = argv[2];
  if ( (NULL == ex) ||
       (0 != strcmp (ex, "-")) )
  {
    plugins = EXTRACTOR_plugin_add_defaults (EXTRACTOR_OPTION_DEFAULT_POLICY);
    if (NULL != ex)
      plugins = EXTRACTOR_plugin_add_config (plugins, ex,
					     EXTRACTOR_OPTION_DEFAULT_POLICY);
  }

  /* scan tree to find out how much work there is to be done */
  if (GNUNET_OK != preprocess_file (filename_expanded, 
				    &root))
  {
    (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0);
    return 2;
  }
  /* signal that we're done counting files, so that a percentage of 
     progress can now be calculated */
  if (GNUNET_OK !=
      write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE, NULL, 0))
    return 3;  
  if (NULL != root)
  {
    if (GNUNET_OK !=
	extract_files (root))
    {
      (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0);
      free_tree (root);
      return 4;
    }
    free_tree (root);
  }
  /* enable "clean" shutdown by telling parent that we are done */
  (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED, NULL, 0);
  if (NULL != plugins)
    EXTRACTOR_plugin_remove_all (plugins);

  return 0;
}
Exemplo n.º 21
0
int include_file(char *name) {

    static int first_load = 0;
    int file_size, id;
    char *tmp_b, *n, *tmp_c;
    FILE *f;


    /* create the full output file name */
    if (use_incdir == YES)
        tmp_c = ext_incdir;
    else
        tmp_c = include_dir;

    if (create_full_name(tmp_c, name) == FAILED)
        return FAILED;

    f = fopen(full_name, "rb");
    id = 0;

    if (f == NULL && (tmp_c == NULL || tmp_c[0] == 0)) {
        sprintf(emsg, "Error opening file \"%s\".\n", name);
        if (first_load == 0)
            fprintf(stderr, "INCLUDE_FILE: %s", emsg);
        else
            print_error(emsg, ERROR_INC);
        return FAILED;
    }

    /* if not found in ext_incdir silently try the include directory */
    if (f == NULL && use_incdir == YES) {
        if (create_full_name(include_dir, name) == FAILED)
            return FAILED;

        f = fopen(full_name, "rb");
        id = 0;

        if (f == NULL && (include_dir == NULL || include_dir[0] == 0)) {
            sprintf(emsg, "Error opening file \"%s\".\n", name);
            if (first_load == 0)
                fprintf(stderr, "INCLUDE_FILE: %s", emsg);
            else
                print_error(emsg, ERROR_INC);
            return FAILED;
        }
    }

    /* if failed try to find the file in the current directory */
    if (f == NULL) {
        fprintf(stderr, "%s:%d: ", get_file_name(active_file_info_last->filename_id), active_file_info_last->line_current);
        fprintf(stderr, "INCLUDE_FILE: Could not open \"%s\", trying \"%s\"... ", full_name, name);
        f = fopen(name, "rb");
        id = 1;
    }

    if (f == NULL) {
        fprintf(stderr, "not found.\n");
        sprintf(emsg, "Error opening file \"%s\".\n", full_name);
        if (first_load == 0)
            fprintf(stderr, "INCLUDE_FILE: %s", emsg);
        else
            print_error(emsg, ERROR_INC);
        return FAILED;
    }

    if (id == 1) {
        fprintf(stderr, "found.\n");
        strcpy(full_name, name);
    }

    first_load = 1;

    if (extra_definitions == ON) {
        redefine("WLA_FILENAME", 0.0, name, DEFINITION_TYPE_STRING, strlen(name));
        redefine("wla_filename", 0.0, name, DEFINITION_TYPE_STRING, strlen(name));
    }

    fseek(f, 0, SEEK_END);
    file_size = ftell(f);
    fseek(f, 0, SEEK_SET);

    active_file_info_tmp = malloc(sizeof(struct active_file_info));
    if (active_file_info_tmp == NULL) {
        sprintf(emsg, "Out of memory while trying allocate error tracking data structure for file \"%s\".\n", full_name);
        print_error(emsg, ERROR_INC);
        return FAILED;
    }
    active_file_info_tmp->next = NULL;

    if (active_file_info_first == NULL) {
        active_file_info_first = active_file_info_tmp;
        active_file_info_last = active_file_info_tmp;
        active_file_info_tmp->prev = NULL;
    }
    else {
        active_file_info_tmp->prev = active_file_info_last;
        active_file_info_last->next = active_file_info_tmp;
        active_file_info_last = active_file_info_tmp;
    }

    active_file_info_tmp->line_current = 1;

    /* name */
    file_name_info_tmp = file_name_info_first;
    id = 0;
    while (file_name_info_tmp != NULL) {
        if (strcmp(file_name_info_tmp->name, full_name) == 0) {
            id = file_name_info_tmp->id;
            active_file_info_tmp->filename_id = id;
            break;
        }
        file_name_info_tmp = file_name_info_tmp->next;
    }

    if (id == 0) {
        file_name_info_tmp = malloc(sizeof(struct file_name_info));
        n = malloc(strlen(full_name)+1);
        if (file_name_info_tmp == NULL || n == NULL) {
            if (file_name_info_tmp != NULL)
                free(file_name_info_tmp);
            if (n != NULL)
                free(n);
            sprintf(emsg, "Out of memory while trying allocate info structure for file \"%s\".\n", full_name);
            print_error(emsg, ERROR_INC);
            return FAILED;
        }
        file_name_info_tmp->next = NULL;

        if (file_name_info_first == NULL) {
            file_name_info_first = file_name_info_tmp;
            file_name_info_last = file_name_info_tmp;
        }
        else {
            file_name_info_last->next = file_name_info_tmp;
            file_name_info_last = file_name_info_tmp;
        }

        strcpy(n, full_name);
        file_name_info_tmp->name = n;
        active_file_info_tmp->filename_id = file_name_id;
        file_name_info_tmp->id = file_name_id;
        file_name_id++;
    }

    /* reallocate buffer */
    if (include_in_tmp_size < file_size) {
        if (include_in_tmp != NULL)
            free(include_in_tmp);

        include_in_tmp = malloc(sizeof(char) * file_size);
        if (include_in_tmp == NULL) {
            sprintf(emsg, "Out of memory while trying to allocate room for \"%s\".\n", full_name);
            print_error(emsg, ERROR_INC);
            return FAILED;
        }

        include_in_tmp_size = file_size;
    }

    /* read the whole file into a buffer */
    fread(include_in_tmp, 1, file_size, f);
    fclose(f);

    if (size == 0) {
        buffer = malloc(sizeof(char) * (file_size + 4));
        if (buffer == NULL) {
            sprintf(emsg, "Out of memory while trying to allocate room for \"%s\".\n", full_name);
            print_error(emsg, ERROR_INC);
            return FAILED;
        }

        /* preprocess */
        preprocess_file(include_in_tmp, include_in_tmp + file_size, buffer, &size, full_name);

        buffer[size++] = 0xA;
        buffer[size++] = '.';
        buffer[size++] = 'E';
        buffer[size++] = ' ';

        open_files++;

        return SUCCEEDED;
    }

    tmp_b = malloc(sizeof(char) * (size + file_size + 4));
    if (tmp_b == NULL) {
        sprintf(emsg, "Out of memory while trying to expand the project to incorporate file \"%s\".\n", full_name);
        print_error(emsg, ERROR_INC);
        return FAILED;
    }

    /* reallocate tmp_a */
    if (tmp_a_size < file_size + 4) {
        if (tmp_a != NULL)
            free(tmp_a);

        tmp_a = malloc(sizeof(char) * (file_size + 4));
        if (tmp_a == NULL) {
            sprintf(emsg, "Out of memory while allocating new room for \"%s\".\n", full_name);
            print_error(emsg, ERROR_INC);
            return FAILED;
        }

        tmp_a_size = file_size + 4;
    }

    /* preprocess */
    inz = 0;
    preprocess_file(include_in_tmp, include_in_tmp + file_size, tmp_a, &inz, full_name);

    tmp_a[inz++] = 0xA;
    tmp_a[inz++] = '.';
    tmp_a[inz++] = 'E';
    tmp_a[inz++] = ' ';

    open_files++;

    memcpy(tmp_b, buffer, i);
    memcpy(tmp_b + i, tmp_a, inz);
    memcpy(tmp_b + i + inz, buffer + i, size - i);

    free(buffer);

    size += inz;
    buffer = tmp_b;

    return SUCCEEDED;
}
Exemplo n.º 22
0
int main(int argc, char * argv[])
{
	struct static_hash_table tbl;
	struct input_table intbl;
	struct input_data *pdata;
	long length;
	FILE *fp;
	char * szfile;
	char * szfileorg;
	char * szend;
	int ideal_size;
	parse_cmd_line(argc, argv);
	memset(&tbl, 0x00, sizeof(tbl));
	memset(&intbl, 0x00, sizeof(intbl));
	pdata = 0;

	fp = fopen(g_szInFile, "rb");
	if (!fp)
	{
		printf("could not open file for read: %s\r\n", g_szInFile);
		return 1;
	}

	length = _filelength(_fileno(fp));
	szfile = (char *) malloc(length*sizeof(char));
	if (!szfile)
	{
		printf("out of memory\r\n");
		return 1;
	}
	fread(szfile, length, 1, fp);
	szend = szfile+length;
	szfileorg = szfile;

	if (!preprocess_file(&szfile))
	{
		return 1;
	}

	while (szfile != szend)
	{
		pdata = add_input_data(&intbl);
		if (!pdata)
		{
			printf("out of memory\r\n");
			return 1;
		}
		if (!get_input_from_line(pdata, &szfile))
		{
			printf("bad input file\r\n");
			return 1;
		}
//		printf("%.*s, %.*s\r\n", pdata->keylen, pdata->key, pdata->datalen, pdata->data);
	}

	pdata = intbl.phead;
	ideal_size = 2*(intbl.size);
	create_runtime_hash(&tbl, ideal_size);
	while (pdata)
	{
		set_runtime_element(&tbl, pdata->key, pdata->keylen, pdata->data, pdata->datalen);
		pdata = pdata->next;
	}

	generate_static_table(&tbl, "soap_types");
	destroy_runtime_hash(&tbl);
	destroy_input_table(&intbl);
	free(szfileorg);
	fclose(fp);
#if 0
	create_runtime_hash(&tbl, 17);
	set_runtime_element(&tbl, "BSTR", "string");
	set_runtime_element(&tbl, "int", "int");
	set_runtime_element(&tbl, "long", "int");
	set_runtime_element(&tbl, "char", "byte");
	set_runtime_element(&tbl, "short", "short");
	set_runtime_element(&tbl, "__int8", "byte");
	set_runtime_element(&tbl, "__int16", "short");
	set_runtime_element(&tbl, "__int32", "int");
	set_runtime_element(&tbl, "__int64", "long");
	set_runtime_element(&tbl, "float", "float");
	set_runtime_element(&tbl, "double", "double");
	set_runtime_element(&tbl, "unsigned int", "unsignedInt");
	set_runtime_element(&tbl, "unsigned long", "unsignedInt");
	set_runtime_element(&tbl, "unsigned char", "unsignedByte");
	set_runtime_element(&tbl, "unsigned short", "unsignedShort");
	set_runtime_element(&tbl, "unsigned __int8", "unsignedByte");
	set_runtime_element(&tbl, "unsigned __int16", "unsignedShort");
	set_runtime_element(&tbl, "unsigned __int32", "unsignedInt");
//	printf("%d\n", all_hashes_unique(&tbl));
	generate_static_table(&tbl, "soap_types");
	destroy_runtime_hash(&tbl);
#endif
}
    void LoweringPhase::fortran_preprocess_api(DTO& dto)
    {
        ERROR_CONDITION(!IS_FORTRAN_LANGUAGE, "This is only for Fortran", 0);

        Nodecl::NodeclBase top_level = *std::static_pointer_cast<Nodecl::NodeclBase>(dto["nodecl"]);

        const char** old_preprocessor_options = CURRENT_CONFIGURATION->preprocessor_options;

        int num_orig_args = count_null_ended_array((void**)old_preprocessor_options);
        int num_args = num_orig_args;

        // -x c
        num_args += 2;

        // NULL ended
        num_args += 1;

        const char** preprocessor_options = new const char*[num_args];

        for (int i = 0;  i < num_orig_args; i++)
        {
            preprocessor_options[i] = old_preprocessor_options[i];
        }

        // We add -x c since we want /dev/null be preprocessed as an empty C file
        // FIXME - This is very gcc specific
        preprocessor_options[num_args - 3] = "-x";
        preprocessor_options[num_args - 2] = "c";
        preprocessor_options[num_args - 1] = NULL;

        CURRENT_CONFIGURATION->preprocessor_options = preprocessor_options;

        const char* output_filename = preprocess_file("/dev/null");

        delete[] preprocessor_options;

        // Restore old flags
        CURRENT_CONFIGURATION->preprocessor_options = old_preprocessor_options;

        TL::Source src;

        std::ifstream preproc_file(output_filename);

        if (preproc_file.is_open())
        {
            std::string str;

            while (preproc_file.good())
            {
                std::getline(preproc_file, str);
                src << str << "\n";
            }
            preproc_file.close();
        }
        else
        {
            fatal_error("Could not open Nanos++ include");
        }

        Source::source_language = SourceLanguage::C;

        Nodecl::NodeclBase new_tree = src.parse_global(top_level);
        // This is actually a top level tree!
        new_tree = Nodecl::TopLevel::make(new_tree);
        // FIXME - keep this?

        Source::source_language = SourceLanguage::Current;
    }
Exemplo n.º 24
0
bool
OSLCompilerImpl::compile (string_view filename,
                          const std::vector<std::string> &options,
                          string_view stdoslpath)
{
    if (! OIIO::Filesystem::exists (filename)) {
        error (ustring(), 0, "Input file \"%s\" not found", filename.c_str());
        return false;
    }

    std::vector<std::string> defines;
    std::vector<std::string> includepaths;
#if OIIO_VERSION >= 10604
    m_cwd = OIIO::Filesystem::current_path();
#else
    m_cwd = boost::filesystem::current_path().string();
#endif
    m_main_filename = filename;

    // Determine where the installed shader include directory is, and
    // look for ../shaders/stdosl.h and force it to include.
    if (stdoslpath.empty()) {
        // look in $OSLHOME/shaders
        const char *OSLHOME = getenv ("OSLHOME");
        if (OSLHOME && OSLHOME[0]) {
            std::string path = std::string(OSLHOME) + "/shaders";
            if (OIIO::Filesystem::exists (path)) {
                path = path + "/stdosl.h";
                if (OIIO::Filesystem::exists (path))
                    stdoslpath = ustring(path);
            }
        }
    }
    if (stdoslpath.empty() || ! OIIO::Filesystem::exists(stdoslpath))
        warning (ustring(filename), 0, "Unable to find \"stdosl.h\"");
    else {
        // Add the directory of stdosl.h to the include paths
        includepaths.push_back (OIIO::Filesystem::parent_path (stdoslpath));
    }

    read_compile_options (options, defines, includepaths);

    std::string preprocess_result;
    if (! preprocess_file (filename, stdoslpath,
                           defines, includepaths, preprocess_result)) {
        return false;
    } else if (m_preprocess_only) {
        std::cout << preprocess_result;
    } else {
        bool parseerr = osl_parse_buffer (preprocess_result);
        if (! parseerr) {
            if (shader())
                shader()->typecheck ();
            else
                error (ustring(), 0, "No shader function defined");
        }

        // Print the parse tree if there were no errors
        if (m_debug) {
            symtab().print ();
            if (shader())
                shader()->print (std::cout);
        }

        if (! error_encountered()) {
            shader()->codegen ();
            track_variable_dependencies ();
            track_variable_lifetimes ();
            check_for_illegal_writes ();
//            if (m_optimizelevel >= 1)
//                coalesce_temporaries ();
        }
 
        if (! error_encountered()) {
            if (m_output_filename.size() == 0)
                m_output_filename = default_output_filename ();

            std::ofstream oso_output (m_output_filename.c_str());
            if (! oso_output.good()) {
                error (ustring(), 0, "Could not open \"%s\"",
                       m_output_filename.c_str());
                return false;
            }
            ASSERT (m_osofile == NULL);
            m_osofile = &oso_output;

            write_oso_file (m_output_filename, OIIO::Strutil::join(options," "));
            ASSERT (m_osofile == NULL);
        }

        oslcompiler = NULL;
    }

    return ! error_encountered();
}
Exemplo n.º 25
0
void config_cache::read_configs(const std::string& file_path, config& cfg, preproc_map& defines_map)
{
	//read the file and then write to the cache
	filesystem::scoped_istream stream = preprocess_file(file_path, &defines_map);
	read(cfg, *stream);
}