/* * Copyright (c) 2021, Ali Mohammad Pur * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include #include #include #include #include #include namespace Wasm { struct Context { Vector types; Vector functions; Vector tables; Vector memories; Vector globals; Vector elements; Vector datas; Vector locals; Vector labels; Optional return_; AK::HashTable references; size_t imported_function_count { 0 }; }; struct ValidationError : public Error { ValidationError(DeprecatedString error) : Error(Error::from_string_view(error)) , error_string(move(error)) { } DeprecatedString error_string; }; class Validator { AK_MAKE_NONCOPYABLE(Validator); AK_MAKE_NONMOVABLE(Validator); public: Validator() = default; [[nodiscard]] Validator fork() const { return Validator { m_context }; } // Module ErrorOr validate(Module&); ErrorOr validate(ImportSection const&); ErrorOr validate(ExportSection const&); ErrorOr validate(StartSection const&); ErrorOr validate(DataSection const&); ErrorOr validate(ElementSection const&); ErrorOr validate(GlobalSection const&); ErrorOr validate(MemorySection const&); ErrorOr validate(TableSection const&); ErrorOr validate(CodeSection const&); ErrorOr validate(FunctionSection const&) { return {}; } ErrorOr validate(DataCountSection const&) { return {}; } ErrorOr validate(TypeSection const&) { return {}; } ErrorOr validate(CustomSection const&) { return {}; } ErrorOr validate(TypeIndex index) const { if (index.value() < m_context.types.size()) return {}; return Errors::invalid("TypeIndex"sv); } ErrorOr validate(FunctionIndex index) const { if (index.value() < m_context.functions.size()) return {}; return Errors::invalid("FunctionIndex"sv); } ErrorOr validate(MemoryIndex index) const { if (index.value() < m_context.memories.size()) return {}; return Errors::invalid("MemoryIndex"sv); } ErrorOr validate(ElementIndex index) const { if (index.value() < m_context.elements.size()) return {}; return Errors::invalid("ElementIndex"sv); } ErrorOr validate(DataIndex index) const { if (index.value() < m_context.datas.size()) return {}; return Errors::invalid("DataIndex"sv); } ErrorOr validate(GlobalIndex index) const { if (index.value() < m_context.globals.size()) return {}; return Errors::invalid("GlobalIndex"sv); } ErrorOr validate(LabelIndex index) const { if (index.value() < m_context.labels.size()) return {}; return Errors::invalid("LabelIndex"sv); } ErrorOr validate(LocalIndex index) const { if (index.value() < m_context.locals.size()) return {}; return Errors::invalid("LocalIndex"sv); } ErrorOr validate(TableIndex index) const { if (index.value() < m_context.tables.size()) return {}; return Errors::invalid("TableIndex"sv); } // Instructions struct StackEntry { StackEntry(ValueType type) : concrete_type(type) , is_known(true) { } explicit StackEntry() : concrete_type(ValueType::I32) , is_known(false) { } bool is_of_kind(ValueType::Kind kind) const { if (is_known) return concrete_type.kind() == kind; return true; } bool is_numeric() const { return !is_known || concrete_type.is_numeric(); } bool is_reference() const { return !is_known || concrete_type.is_reference(); } bool operator==(ValueType const& other) const { if (is_known) return concrete_type == other; return true; } bool operator==(StackEntry const& other) const { if (is_known && other.is_known) return other.concrete_type == concrete_type; return true; } ValueType concrete_type; bool is_known { true }; }; // This is a wrapper that can model "polymorphic" stacks, // by treating unknown stack entries as a potentially infinite number of entries class Stack : private Vector { template friend struct AK::Formatter; public: // The unknown entry will never be popped off, so we can safely use the original `is_empty`. using Vector::is_empty; using Vector::last; using Vector::at; StackEntry take_last() { if (last().is_known) return Vector::take_last(); return last(); } void append(StackEntry entry) { if (!entry.is_known) m_did_insert_unknown_entry = true; Vector::append(entry); } ErrorOr take(ValueType type, SourceLocation location = SourceLocation::current()) { if (is_empty()) return Errors::invalid("stack state"sv, type, ""sv, location); auto type_on_stack = take_last(); if (type_on_stack != type) return Errors::invalid("stack state"sv, type, type_on_stack, location); return {}; } template ErrorOr take(SourceLocation location = SourceLocation::current()) { ErrorOr result; if (((result = take(Wasm::ValueType(kinds), location)).is_error(), ...)) { return result; } return result; } size_t actual_size() const { return Vector::size(); } size_t size() const { return m_did_insert_unknown_entry ? static_cast(-1) : actual_size(); } Vector release_vector() { return exchange(static_cast&>(*this), Vector {}); } bool operator==(Stack const& other) const; private: bool m_did_insert_unknown_entry { false }; }; struct ExpressionTypeResult { Vector result_types; bool is_constant { false }; }; ErrorOr validate(Expression const&, Vector const&); ErrorOr validate(Instruction const& instruction, Stack& stack, bool& is_constant); template ErrorOr validate_instruction(Instruction const&, Stack& stack, bool& is_constant); // Types ErrorOr validate(Limits const&, size_t k); // n <= 2^k-1 && m? <= 2^k-1 ErrorOr validate(BlockType const&); ErrorOr validate(FunctionType const&) { return {}; } ErrorOr validate(TableType const&); ErrorOr validate(MemoryType const&); ErrorOr validate(GlobalType const&) { return {}; } private: explicit Validator(Context context) : m_context(move(context)) { } struct Errors { static ValidationError invalid(StringView name) { return DeprecatedString::formatted("Invalid {}", name); } template static ValidationError invalid(StringView name, Expected expected, Given given, SourceLocation location = SourceLocation::current()) { if constexpr (WASM_VALIDATOR_DEBUG) return DeprecatedString::formatted("Invalid {} in {}, expected {} but got {}", name, find_instruction_name(location), expected, given); else return DeprecatedString::formatted("Invalid {}, expected {} but got {}", name, expected, given); } template static ValidationError non_conforming_types(StringView name, Args... args) { return DeprecatedString::formatted("Non-conforming types for {}: {}", name, Vector { args... }); } static ValidationError duplicate_export_name(StringView name) { return DeprecatedString::formatted("Duplicate exported name '{}'", name); } template static ValidationError out_of_bounds(StringView name, V value, T min, U max) { return DeprecatedString::formatted("Value {} for {} is out of bounds ({},{})", value, name, min, max); } template static ValidationError invalid_stack_state(Stack const& stack, Tuple expected, SourceLocation location = SourceLocation::current()) { constexpr size_t count = expected.size(); StringBuilder builder; if constexpr (WASM_VALIDATOR_DEBUG) builder.appendff("Invalid stack state in {}: ", find_instruction_name(location)); else builder.appendff("Invalid stack state in : "); builder.append("Expected [ "sv); expected.apply_as_args([&](Ts const&... args) { (builder.appendff("{} ", args), ...); }); builder.append("], but found [ "sv); auto actual_size = stack.actual_size(); for (size_t i = 1; i <= min(count, actual_size); ++i) { auto& entry = stack.at(actual_size - i); if (entry.is_known) { builder.appendff("{} ", entry.concrete_type); } else { builder.appendff(""); break; } } builder.append(']'); return { builder.to_deprecated_string() }; } private: static DeprecatedString find_instruction_name(SourceLocation const&); }; enum class ChildScopeKind { Block, IfWithoutElse, IfWithElse, Else, }; struct BlockDetails { size_t initial_stack_size { 0 }; struct IfDetails { Stack initial_stack; }; Variant details; }; Context m_context; Vector m_parent_contexts; Vector m_entered_scopes; Vector m_block_details; Vector m_entered_blocks; }; } template<> struct AK::Formatter : public AK::Formatter { ErrorOr format(FormatBuilder& builder, Wasm::Validator::StackEntry const& value) { if (value.is_known) return Formatter::format(builder, Wasm::ValueType::kind_name(value.concrete_type.kind())); return Formatter::format(builder, ""sv); } }; template<> struct AK::Formatter : public AK::Formatter> { ErrorOr format(FormatBuilder& builder, Wasm::Validator::Stack const& value) { return Formatter>::format(builder, static_cast const&>(value)); } }; template<> struct AK::Formatter : public AK::Formatter { ErrorOr format(FormatBuilder& builder, Wasm::ValueType const& value) { return Formatter::format(builder, Wasm::ValueType::kind_name(value.kind())); } }; template<> struct AK::Formatter : public AK::Formatter { ErrorOr format(FormatBuilder& builder, Wasm::ValidationError const& error) { return Formatter::format(builder, error.error_string); } };