1 /* Copyright (c) 2004-2014,2016. The SimGrid Team.
2 * All rights reserved. */
14 #include <type_traits>
16 #include <xbt/config.h>
17 #include <xbt/config.hpp>
19 #include "xbt/sysdep.h"
22 #include "xbt/dynar.h"
27 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
29 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = NULL;
34 missing_key_error::~missing_key_error() noexcept {}
40 const char* true_values[] = {
41 "yes", "on", "true", "1"
43 const char* false_values[] = {
44 "no", "off", "false", "0"
47 static bool parseBool(const char* value)
49 for (const char* true_value : true_values)
50 if (std::strcmp(true_value, value) == 0)
52 for (const char* false_value : false_values)
53 if (std::strcmp(false_value, value) == 0)
55 throw std::range_error("not a boolean");
58 static double parseDouble(const char* value)
62 double res = std::strtod(value, &end);
64 throw std::range_error("out of range");
66 xbt_die("Unexpected errno");
67 if (end == value || *end != '\0')
68 throw std::range_error("invalid double");
73 static long int parseLong(const char* value)
77 long int res = std::strtol(value, &end, 0);
79 if (res == LONG_MIN && errno == ERANGE)
80 throw std::range_error("underflow");
81 else if (res == LONG_MAX && errno == ERANGE)
82 throw std::range_error("overflow");
83 xbt_die("Unexpected errno");
85 if (end == value || *end != '\0')
86 throw std::range_error("invalid integer");
91 // ***** ConfigType *****
93 /// A trait which define possible options types:
94 template<class T> struct ConfigType;
96 template<> struct ConfigType<int> {
97 static constexpr const char* type_name = "int";
98 static inline double parse(const char* value)
100 return parseLong(value);
103 template<> struct ConfigType<double> {
104 static constexpr const char* type_name = "double";
105 static inline double parse(const char* value)
107 return parseDouble(value);
110 template<> struct ConfigType<std::string> {
111 static constexpr const char* type_name = "string";
112 static inline std::string parse(const char* value)
114 return std::string(value);
117 template<> struct ConfigType<bool> {
118 static constexpr const char* type_name = "boolean";
119 static inline bool parse(const char* value)
121 return parseBool(value);
125 // **** Forward declarations ****
127 class ConfigurationElement ;
128 template<class T> class TypedConfigurationElement;
130 // **** ConfigurationElement ****
132 class ConfigurationElement {
136 bool isdefault = true;
141 xbt_cfg_cb_t old_callback = nullptr;
143 ConfigurationElement(const char* key, const char* desc)
144 : key(key ? key : ""), desc(desc ? desc : "") {}
145 ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
146 : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
148 virtual ~ConfigurationElement();
150 virtual std::string getStringValue() = 0;
151 virtual void setStringValue(const char* value) = 0;
152 virtual const char* getTypeName() = 0;
155 T const& getValue() const
157 return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
160 void setValue(T value)
162 dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
165 void setDefaultValue(T value)
167 dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
169 bool isDefault() const { return isdefault; }
171 std::string const& getDescription() const { return desc; }
174 ConfigurationElement::~ConfigurationElement() {}
176 // **** TypedConfigurationElement<T> ****
178 // TODO, could we use boost::any with some Type* reference?
180 class TypedConfigurationElement : public ConfigurationElement {
183 std::function<void(T&)> callback;
186 TypedConfigurationElement(const char* key, const char* desc, T value = T())
187 : ConfigurationElement(key, desc), content(std::move(value))
189 TypedConfigurationElement(const char* key, const char* desc, T value,
191 : ConfigurationElement(key, desc, cb), content(std::move(value))
193 TypedConfigurationElement(const char* key, const char* desc, T value,
194 std::function<void(T&)> callback)
195 : ConfigurationElement(key, desc), content(std::move(value)),
196 callback(std::move(callback))
198 ~TypedConfigurationElement() override;
200 std::string getStringValue() override;
201 const char* getTypeName() override;
202 void setStringValue(const char* value) override;
207 this->old_callback(key.c_str());
209 this->callback(this->content);
212 T const& getValue() const { return content; }
214 void setValue(T value)
216 this->content = std::move(value);
220 void setDefaultValue(T value)
222 if (this->isdefault) {
223 this->content = std::move(value);
226 XBT_DEBUG("Do not override configuration variable '%s' with value '%s'"
227 " because it was already set.", key.c_str(), to_string(value).c_str());
233 std::string TypedConfigurationElement<T>::getStringValue() // override
235 return to_string(content);
239 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
241 this->content = ConfigType<T>::parse(value);
242 this->isdefault = false;
247 const char* TypedConfigurationElement<T>::getTypeName() // override
249 return ConfigType<T>::type_name;
253 TypedConfigurationElement<T>::~TypedConfigurationElement()
256 } // end of anonymous namespace
262 // name -> ConfigElement:
264 // alias -> xbt_dict_elm_t from options:
272 Config(Config const&) = delete;
273 Config& operator=(Config const&) = delete;
275 ConfigurationElement& operator[](const char* name);
277 TypedConfigurationElement<T>& getTyped(const char* name);
278 void alias(const char* realname, const char* aliasname);
280 template<class T, class... A>
281 simgrid::config::TypedConfigurationElement<T>*
282 registerOption(const char* name, A&&... a)
284 xbt_assert(xbt_dict_get_or_null(this->options, name) == nullptr,
285 "Refusing to register the config element '%s' twice.", name);
286 TypedConfigurationElement<T>* variable =
287 new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
288 XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)",
290 variable->getDescription().c_str(),
291 variable->getTypeName(), variable, this);
292 xbt_dict_set(this->options, name, variable, NULL);
298 void dump(const char *name, const char *indent);
303 xbt_dictelm_t getDictElement(const char* name);
306 /* Internal stuff used in cache to free a variable */
307 static void xbt_cfgelm_free(void *data)
310 delete (simgrid::config::ConfigurationElement*) data;
314 options(xbt_dict_new_homogeneous(xbt_cfgelm_free)),
315 aliases(xbt_dict_new_homogeneous(NULL))
320 XBT_DEBUG("Frees cfg set %p", this);
321 xbt_dict_free(&this->options);
322 xbt_dict_free(&this->aliases);
326 xbt_dictelm_t Config::getDictElement(const char* name)
328 // We are interested in the options dictelm:
329 xbt_dictelm_t res = xbt_dict_get_elm_or_null(options, name);
332 // The aliases dict stores pointers to the options dictelm:
333 res = (xbt_dictelm_t) xbt_dict_get_or_null(aliases, name);
335 XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->key);
340 ConfigurationElement& Config::operator[](const char* name)
342 xbt_dictelm_t elm = getDictElement(name);
344 throw simgrid::config::missing_key_error(std::string("Bad config key, ") + name);
345 return *(ConfigurationElement*)elm->content;
348 void Config::alias(const char* realname, const char* aliasname)
350 xbt_assert(this->getDictElement(aliasname) == nullptr, "Alias '%s' already.", aliasname);
351 xbt_dictelm_t element = this->getDictElement(realname);
352 xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
353 xbt_dict_set(this->aliases, aliasname, element, NULL);
356 /** @brief Dump a config set for debuging purpose
358 * @param name The name to give to this config set
359 * @param indent what to write at the beginning of each line (right number of spaces)
361 void Config::dump(const char *name, const char *indent)
363 xbt_dict_t dict = this->options;
364 xbt_dict_cursor_t cursor = NULL;
365 simgrid::config::ConfigurationElement* variable = NULL;
369 printf("%s>> Dumping of the config set '%s':\n", indent, name);
371 xbt_dict_foreach(dict, cursor, key, variable)
372 printf("%s %s: ()%s) %s", indent, key,
373 variable->getTypeName(),
374 variable->getStringValue().c_str());
377 printf("%s<< End of the config set '%s'\n", indent, name);
380 xbt_dict_cursor_free(&cursor);
383 /** @brief Displays the declared aliases and their description */
384 void Config::showAliases()
386 xbt_dict_cursor_t dict_cursor;
387 unsigned int dynar_cursor;
388 xbt_dictelm_t dictel;
390 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
392 xbt_dict_foreach(this->aliases, dict_cursor, name, dictel)
393 xbt_dynar_push(names, &name);
394 xbt_dynar_sort_strings(names);
396 xbt_dynar_foreach(names, dynar_cursor, name)
397 printf(" %s: %s\n", name, (*this)[name].getDescription().c_str());
400 /** @brief Displays the declared options and their description */
403 xbt_dict_cursor_t dict_cursor;
404 unsigned int dynar_cursor;
405 simgrid::config::ConfigurationElement* variable;
407 xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
409 xbt_dict_foreach(this->options, dict_cursor, name, variable)
410 xbt_dynar_push(names, &name);
411 xbt_dynar_sort_strings(names);
413 xbt_dynar_foreach(names, dynar_cursor, name) {
414 variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(this->options, name);
415 printf(" %s: %s\n", name, variable->getDescription().c_str());
416 printf(" Type: %s; ", variable->getTypeName());
417 printf("Current value: %s\n", variable->getStringValue().c_str());
419 xbt_dynar_free(&names);
422 // ***** getConfig *****
425 XBT_PUBLIC(T const&) getConfig(const char* name)
427 return (*simgrid_config)[name].getValue<T>();
430 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
431 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
432 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
433 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
437 void alias(const char* realname, const char* aliasname)
439 simgrid_config->alias(realname, aliasname);
442 // ***** declareFlag *****
445 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
446 T value, std::function<void(const T&)> callback)
448 if (simgrid_config == NULL)
449 simgrid_config = xbt_cfg_new();
450 simgrid_config->registerOption<T>(
451 name, description, std::move(value), std::move(callback));
454 template XBT_PUBLIC(void) declareFlag(const char* name,
455 const char* description, int value, std::function<void(int const &)> callback);
456 template XBT_PUBLIC(void) declareFlag(const char* name,
457 const char* description, double value, std::function<void(double const &)> callback);
458 template XBT_PUBLIC(void) declareFlag(const char* name,
459 const char* description, bool value, std::function<void(bool const &)> callback);
460 template XBT_PUBLIC(void) declareFlag(const char* name,
461 const char* description, std::string value, std::function<void(std::string const &)> callback);
466 // ***** C bindings *****
468 xbt_cfg_t xbt_cfg_new(void) { return new simgrid::config::Config(); }
469 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
471 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
473 cfg->dump(name, indent);
476 /*----[ Registering stuff ]-----------------------------------------------*/
478 void xbt_cfg_register_double(const char *name, double default_value,
479 xbt_cfg_cb_t cb_set, const char *desc)
481 if (simgrid_config == NULL)
482 simgrid_config = xbt_cfg_new();
483 simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
486 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
488 if (simgrid_config == NULL)
489 simgrid_config = xbt_cfg_new();
490 simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
493 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
495 if (simgrid_config == NULL)
496 simgrid_config = xbt_cfg_new();
497 simgrid_config->registerOption<std::string>(name, desc,
498 default_value ? default_value : "", cb_set);
501 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
503 if (simgrid_config == NULL)
504 simgrid_config = xbt_cfg_new();
505 simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
508 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
510 if (simgrid_config == NULL)
511 simgrid_config = xbt_cfg_new();
512 simgrid_config->alias(realname, aliasname);
515 void xbt_cfg_aliases(void) { simgrid_config->showAliases(); }
516 void xbt_cfg_help(void) { simgrid_config->help(); }
518 /*----[ Setting ]---------------------------------------------------------*/
520 /** @brief Add values parsed from a string into a config set
522 * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
523 * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
524 * already registered variable, and [value] conforms to the data type under which this variable was registered.
526 * @todo This is a crude manual parser, it should be a proper lexer.
528 void xbt_cfg_set_parse(const char *options)
530 if (!options || !strlen(options)) { /* nothing to do */
533 char *optionlist_cpy = xbt_strdup(options);
535 XBT_DEBUG("List to parse and set:'%s'", options);
536 char *option = optionlist_cpy;
537 while (1) { /* breaks in the code */
541 int len = strlen(name);
542 XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
545 while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
546 XBT_DEBUG("Take %c.", *option);
549 if (option - name == len) {
550 XBT_DEBUG("Boundary=EOL");
551 option = NULL; /* don't do next iteration */
553 XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
554 /* Pass the following blank chars */
556 while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
557 /* fprintf(stderr,"Ignore a blank char.\n"); */
560 if (option - name == len - 1)
561 option = NULL; /* don't do next iteration */
563 XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
565 if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
570 char *val = strchr(name, ':');
571 xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
572 /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
575 if (strncmp(name, "contexts/", strlen("contexts/")) && strncmp(name, "path", strlen("path")))
576 XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
579 (*simgrid_config)[name].setStringValue(val);
581 catch (simgrid::config::missing_key_error& e) {
589 free(optionlist_cpy);
593 free(optionlist_cpy);
594 THROWF(not_found_error, 0, "Could not set variables %s", options);
597 free(optionlist_cpy);
598 THROWF(unknown_error, 0, "Could not set variables %s", options);
602 // Horrible mess to translate C++ exceptions to C exceptions:
603 // Exit from the catch blog (and do the correct exceptio cleaning)
604 // before attempting to THROWF.
605 #define TRANSLATE_EXCEPTIONS(...) \
606 catch(simgrid::config::missing_key_error& e) { goto on_exception; } \
607 catch(...) { goto on_missing_key; } \
608 on_missing_key: THROWF(not_found_error, 0, __VA_ARGS__); \
609 on_exception: THROWF(not_found_error, 0, __VA_ARGS__);
611 /** @brief Set the value of a variable, using the string representation of that value
613 * @param key name of the variable to modify
614 * @param value string representation of the value to set
617 void xbt_cfg_set_as_string(const char *key, const char *value)
620 (*simgrid_config)[key].setStringValue(value);
623 TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
626 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
628 * This is useful to change the default value of a variable while allowing
629 * users to override it with command line arguments
631 void xbt_cfg_setdefault_int(const char *key, int value)
634 (*simgrid_config)[key].setDefaultValue<int>(value);
637 TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i",
641 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
643 * This is useful to change the default value of a variable while allowing
644 * users to override it with command line arguments
646 void xbt_cfg_setdefault_double(const char *key, double value)
649 (*simgrid_config)[key].setDefaultValue<double>(value);
652 TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f",
656 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
658 * This is useful to change the default value of a variable while allowing
659 * users to override it with command line arguments
661 void xbt_cfg_setdefault_string(const char *key, const char *value)
664 (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
667 TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s",
671 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
673 * This is useful to change the default value of a variable while allowing
674 * users to override it with command line arguments
676 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
679 (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
682 TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s",
686 /** @brief Set an integer value to \a name within \a cfg
688 * @param name the name of the variable
689 * @param val the value of the variable
691 void xbt_cfg_set_int(const char *key, int value)
694 (*simgrid_config)[key].setValue<int>(value);
697 TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i",
701 /** @brief Set or add a double value to \a name within \a cfg
703 * @param name the name of the variable
704 * @param val the double to set
706 void xbt_cfg_set_double(const char *key, double value)
709 (*simgrid_config)[key].setValue<double>(value);
712 TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f",
716 /** @brief Set or add a string value to \a name within \a cfg
718 * @param cfg the config set
719 * @param name the name of the variable
720 * @param val the value to be added
723 void xbt_cfg_set_string(const char *key, const char *value)
726 (*simgrid_config)[key].setValue<std::string>(value ? value : "");
729 TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s",
733 /** @brief Set or add a boolean value to \a name within \a cfg
735 * @param name the name of the variable
736 * @param val the value of the variable
738 void xbt_cfg_set_boolean(const char *key, const char *value)
741 (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
744 TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s",
749 /* Say if the value is the default value */
750 int xbt_cfg_is_default_value(const char *key)
753 return (*simgrid_config)[key].isDefault() ? 1 : 0;
755 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
758 /*----[ Getting ]---------------------------------------------------------*/
759 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
761 * @param name the name of the variable
763 * Returns the first value from the config set under the given name.
765 int xbt_cfg_get_int(const char *key)
768 return (*simgrid_config)[key].getValue<int>();
770 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
773 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
775 * @param cfg the config set
776 * @param name the name of the variable
778 * Returns the first value from the config set under the given name.
780 double xbt_cfg_get_double(const char *key)
783 return (*simgrid_config)[key].getValue<double>();
785 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
788 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
790 * @param cfg the config set
791 * @param name the name of the variable
793 * Returns the first value from the config set under the given name.
794 * If there is more than one value, it will issue a warning.
795 * Returns NULL if there is no value.
797 * \warning the returned value is the actual content of the config set
799 char *xbt_cfg_get_string(const char *key)
802 return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
804 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
807 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
809 * @param cfg the config set
810 * @param name the name of the variable
812 * Returns the first value from the config set under the given name.
813 * If there is more than one value, it will issue a warning.
815 int xbt_cfg_get_boolean(const char *key)
818 return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
820 TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
830 #include <xbt/config.hpp>
832 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
834 XBT_TEST_SUITE("config", "Configuration support");
836 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
838 static void make_set()
840 simgrid_config = NULL;
841 xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
842 xbt_cfg_register_int("speed", 0, NULL, "");
843 xbt_cfg_register_string("peername", "", NULL, "");
844 xbt_cfg_register_string("user", "", NULL, "");
845 } /* end_of_make_set */
847 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
849 auto temp = simgrid_config;
851 xbt_test_add("Alloc and free a config set");
852 xbt_cfg_set_parse("peername:veloce user:bidule");
853 xbt_cfg_free(&simgrid_config);
854 simgrid_config = temp;
857 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
859 auto temp = simgrid_config;
861 xbt_test_add("Get a single value");
863 /* get_single_value */
866 xbt_cfg_set_parse("peername:toto:42 speed:42");
867 ival = xbt_cfg_get_int("speed");
869 xbt_test_fail("Speed value = %d, I expected 42", ival);
872 xbt_test_add("Access to a non-existant entry");
877 xbt_cfg_set_parse("color:blue");
879 if (e.category != not_found_error)
880 xbt_test_exception(e);
884 xbt_cfg_free(&simgrid_config);
885 simgrid_config = temp;
888 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
890 auto temp = simgrid_config;
892 xbt_test_add("C++ declaration of flags");
894 simgrid::config::Flag<int> int_flag("int", "", 0);
895 simgrid::config::Flag<std::string> string_flag("string", "", "foo");
896 simgrid::config::Flag<double> double_flag("double", "", 0.32);
897 simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
898 simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
900 xbt_test_add("Parse values");
901 xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
902 xbt_test_assert(int_flag == 42, "Check int flag");
903 xbt_test_assert(string_flag == "bar", "Check string flag");
904 xbt_test_assert(double_flag == 8.0, "Check double flag");
905 xbt_test_assert(bool_flag1, "Check bool1 flag");
906 xbt_test_assert(!bool_flag2, "Check bool2 flag");
908 xbt_cfg_free(&simgrid_config);
909 simgrid_config = temp;
912 #endif /* SIMGRID_TEST */