Skip to content

Risk of a data race in mustache::set_loader() when called concurrently with mustache::load_text() #1246

Description

@jwolak

The documentation (docs/getting_started/a_simple_webpage.md) shows that Mustache templates may be loaded from a route handler while the application is running:

int main()
{
    crow::SimpleApp app;

    CROW_ROUTE(app, "/")([](){
        auto page = crow::mustache::load_text("fancypage.html");
        return page;
    });

    app.port(18080).multithreaded().run();
}

However, the documentation does not describe set_loader() or specify whether it may be called while the server is handling requests.

        namespace detail
        {
            inline std::function<std::string(std::string)>& get_loader_ref()
            {
                static std::function<std::string(std::string)> loader = default_loader;
                return loader;
            }
        } // namespace detail

set_loader() assigns a process-wide std::function:

        inline void set_loader(std::function<std::string(std::string)> loader)
        {
            detail::get_loader_ref() = std::move(loader);
        }

At the same time, load() and load_text() invoke the same global function:

        inline template_t load(const std::string& filename)
        {
            std::string filename_sanitized(filename);
            utility::sanitize_filename(filename_sanitized);
            return compile(detail::get_loader_ref()(filename_sanitized));
        }
        inline std::string load_text(const std::string& filename)
        {
            std::string filename_sanitized(filename);
            utility::sanitize_filename(filename_sanitized);
            return detail::get_loader_ref()(filename_sanitized);
        }

If set_loader() is called from one thread while another thread calls load() or load_text(), ThreadSanitizer reports a data race on the global std::function.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions