ladybird/Userland/Libraries/LibWeb/HTML/Scripting/ModuleMap.cpp
Andreas Kling e28ac74e0b LibWeb: Queue a task to proceed after module map entry finishes fetching
We were doing this synchronously, which was unsafe in that caused us to
re-enter the module map entry setting code while iterating over the
map's entries.

The fix is simply to do what the spec says and queue up a task. This way
the processing gets deferred to a later time.

To avoid stepping into this problem again, I've also added a reentrancy
check in ModuleMap.

This fixes a sporadic crash in HTML::ModuleMap::add() caught by ASAN.
In particular, this was happening regularly on https://shopify.com/
2023-12-16 20:47:16 +01:00

71 lines
1.9 KiB
C++

/*
* Copyright (c) 2022-2023, networkException <networkexception@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/HTML/Scripting/ModuleMap.h>
namespace Web::HTML {
JS_DEFINE_ALLOCATOR(ModuleMap);
void ModuleMap::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
for (auto& it : m_values)
visitor.visit(it.value.module_script);
for (auto const& it : m_callbacks)
for (auto const& callback : it.value)
visitor.visit(callback);
}
bool ModuleMap::is_fetching(AK::URL const& url, DeprecatedString const& type) const
{
return is(url, type, EntryType::Fetching);
}
bool ModuleMap::is_failed(AK::URL const& url, DeprecatedString const& type) const
{
return is(url, type, EntryType::Failed);
}
bool ModuleMap::is(AK::URL const& url, DeprecatedString const& type, EntryType entry_type) const
{
auto value = m_values.get({ url, type });
if (!value.has_value())
return false;
return value->type == entry_type;
}
Optional<ModuleMap::Entry> ModuleMap::get(AK::URL const& url, DeprecatedString const& type) const
{
return m_values.get({ url, type });
}
AK::HashSetResult ModuleMap::set(AK::URL const& url, DeprecatedString const& type, Entry entry)
{
// NOTE: Re-entering this function while firing wait_for_change callbacks is not allowed.
VERIFY(!m_firing_callbacks);
auto value = m_values.set({ url, type }, entry);
auto callbacks = m_callbacks.get({ url, type });
if (callbacks.has_value()) {
m_firing_callbacks = true;
for (auto const& callback : *callbacks)
callback->function()(entry);
m_firing_callbacks = false;
}
return value;
}
void ModuleMap::wait_for_change(JS::Heap& heap, AK::URL const& url, DeprecatedString const& type, Function<void(Entry)> callback)
{
m_callbacks.ensure({ url, type }).append(JS::create_heap_function(heap, move(callback)));
}
}