Validator.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/HashTable.h>
  8. #include <AK/SourceLocation.h>
  9. #include <AK/Tuple.h>
  10. #include <LibWasm/Forward.h>
  11. #include <LibWasm/Types.h>
  12. namespace Wasm {
  13. struct Context {
  14. Vector<FunctionType> types;
  15. Vector<FunctionType> functions;
  16. Vector<TableType> tables;
  17. Vector<MemoryType> memories;
  18. Vector<GlobalType> globals;
  19. Vector<ValueType> elements;
  20. Vector<bool> datas;
  21. Vector<ValueType> locals;
  22. Vector<ResultType> labels;
  23. Optional<ResultType> return_;
  24. AK::HashTable<FunctionIndex> references;
  25. size_t imported_function_count { 0 };
  26. };
  27. struct ValidationError : public Error {
  28. ValidationError(String error)
  29. : Error(Error::from_string_literal(error))
  30. , error_string(move(error))
  31. {
  32. }
  33. String error_string;
  34. };
  35. class Validator {
  36. AK_MAKE_NONCOPYABLE(Validator);
  37. AK_MAKE_NONMOVABLE(Validator);
  38. public:
  39. Validator() = default;
  40. [[nodiscard]] Validator fork() const
  41. {
  42. return Validator { m_context };
  43. }
  44. // Module
  45. ErrorOr<void, ValidationError> validate(Module&);
  46. ErrorOr<void, ValidationError> validate(ImportSection const&);
  47. ErrorOr<void, ValidationError> validate(ExportSection const&);
  48. ErrorOr<void, ValidationError> validate(StartSection const&);
  49. ErrorOr<void, ValidationError> validate(DataSection const&);
  50. ErrorOr<void, ValidationError> validate(ElementSection const&);
  51. ErrorOr<void, ValidationError> validate(GlobalSection const&);
  52. ErrorOr<void, ValidationError> validate(MemorySection const&);
  53. ErrorOr<void, ValidationError> validate(TableSection const&);
  54. ErrorOr<void, ValidationError> validate(CodeSection const&);
  55. ErrorOr<void, ValidationError> validate(FunctionSection const&) { return {}; }
  56. ErrorOr<void, ValidationError> validate(DataCountSection const&) { return {}; }
  57. ErrorOr<void, ValidationError> validate(TypeSection const&) { return {}; }
  58. ErrorOr<void, ValidationError> validate(CustomSection const&) { return {}; }
  59. ErrorOr<void, ValidationError> validate(TypeIndex index) const
  60. {
  61. if (index.value() < m_context.types.size())
  62. return {};
  63. return Errors::invalid("TypeIndex"sv);
  64. }
  65. ErrorOr<void, ValidationError> validate(FunctionIndex index) const
  66. {
  67. if (index.value() < m_context.functions.size())
  68. return {};
  69. return Errors::invalid("FunctionIndex"sv);
  70. }
  71. ErrorOr<void, ValidationError> validate(MemoryIndex index) const
  72. {
  73. if (index.value() < m_context.memories.size())
  74. return {};
  75. return Errors::invalid("MemoryIndex"sv);
  76. }
  77. ErrorOr<void, ValidationError> validate(ElementIndex index) const
  78. {
  79. if (index.value() < m_context.elements.size())
  80. return {};
  81. return Errors::invalid("ElementIndex"sv);
  82. }
  83. ErrorOr<void, ValidationError> validate(DataIndex index) const
  84. {
  85. if (index.value() < m_context.datas.size())
  86. return {};
  87. return Errors::invalid("DataIndex"sv);
  88. }
  89. ErrorOr<void, ValidationError> validate(GlobalIndex index) const
  90. {
  91. if (index.value() < m_context.globals.size())
  92. return {};
  93. return Errors::invalid("GlobalIndex"sv);
  94. }
  95. ErrorOr<void, ValidationError> validate(LabelIndex index) const
  96. {
  97. if (index.value() < m_context.labels.size())
  98. return {};
  99. return Errors::invalid("LabelIndex"sv);
  100. }
  101. ErrorOr<void, ValidationError> validate(LocalIndex index) const
  102. {
  103. if (index.value() < m_context.locals.size())
  104. return {};
  105. return Errors::invalid("LocalIndex"sv);
  106. }
  107. ErrorOr<void, ValidationError> validate(TableIndex index) const
  108. {
  109. if (index.value() < m_context.tables.size())
  110. return {};
  111. return Errors::invalid("TableIndex"sv);
  112. }
  113. // Instructions
  114. struct StackEntry {
  115. StackEntry(ValueType type)
  116. : concrete_type(type)
  117. , is_known(true)
  118. {
  119. }
  120. explicit StackEntry()
  121. : concrete_type(ValueType::I32)
  122. , is_known(false)
  123. {
  124. }
  125. bool is_of_kind(ValueType::Kind kind) const
  126. {
  127. if (is_known)
  128. return concrete_type.kind() == kind;
  129. return true;
  130. }
  131. bool is_numeric() const { return !is_known || concrete_type.is_numeric(); }
  132. bool is_reference() const { return !is_known || concrete_type.is_reference(); }
  133. bool operator==(ValueType const& other) const
  134. {
  135. if (is_known)
  136. return concrete_type == other;
  137. return true;
  138. }
  139. bool operator==(StackEntry const& other) const
  140. {
  141. if (is_known && other.is_known)
  142. return other.concrete_type == concrete_type;
  143. return true;
  144. }
  145. ValueType concrete_type;
  146. bool is_known { true };
  147. };
  148. // This is a wrapper that can model "polymorphic" stacks,
  149. // by treating unknown stack entries as a potentially infinite number of entries
  150. class Stack : private Vector<StackEntry> {
  151. template<typename, typename>
  152. friend struct AK::Formatter;
  153. public:
  154. // The unknown entry will never be popped off, so we can safely use the original `is_empty`.
  155. using Vector<StackEntry>::is_empty;
  156. using Vector<StackEntry>::last;
  157. using Vector<StackEntry>::at;
  158. StackEntry take_last()
  159. {
  160. if (last().is_known)
  161. return Vector<StackEntry>::take_last();
  162. return last();
  163. }
  164. void append(StackEntry entry)
  165. {
  166. if (!entry.is_known)
  167. m_did_insert_unknown_entry = true;
  168. Vector<StackEntry>::append(entry);
  169. }
  170. ErrorOr<void, ValidationError> take(ValueType type, SourceLocation location = SourceLocation::current())
  171. {
  172. if (is_empty())
  173. return Errors::invalid("stack state", type, "<nothing>", location);
  174. auto type_on_stack = take_last();
  175. if (type_on_stack != type)
  176. return Errors::invalid("stack state", type, type_on_stack, location);
  177. return {};
  178. }
  179. template<auto... kinds>
  180. ErrorOr<void, ValidationError> take(SourceLocation location = SourceLocation::current())
  181. {
  182. ErrorOr<void, ValidationError> result;
  183. if (((result = take(Wasm::ValueType(kinds), location)).is_error(), ...)) {
  184. return result;
  185. }
  186. return result;
  187. }
  188. size_t actual_size() const { return Vector<StackEntry>::size(); }
  189. size_t size() const { return m_did_insert_unknown_entry ? static_cast<size_t>(-1) : actual_size(); }
  190. Vector<StackEntry> release_vector() { return exchange(static_cast<Vector<StackEntry>&>(*this), Vector<StackEntry> {}); }
  191. bool operator==(Stack const& other) const;
  192. private:
  193. bool m_did_insert_unknown_entry { false };
  194. };
  195. struct ExpressionTypeResult {
  196. Vector<StackEntry> result_types;
  197. bool is_constant { false };
  198. };
  199. ErrorOr<ExpressionTypeResult, ValidationError> validate(Expression const&, Vector<ValueType> const&);
  200. ErrorOr<void, ValidationError> validate(Instruction const& instruction, Stack& stack, bool& is_constant);
  201. template<u32 opcode>
  202. ErrorOr<void, ValidationError> validate_instruction(Instruction const&, Stack& stack, bool& is_constant);
  203. // Types
  204. bool type_is_subtype_of(ValueType const& candidate_subtype, ValueType const& candidate_supertype);
  205. ErrorOr<void, ValidationError> validate(Limits const&, size_t k); // n <= 2^k-1 && m? <= 2^k-1
  206. ErrorOr<FunctionType, ValidationError> validate(BlockType const&);
  207. ErrorOr<void, ValidationError> validate(FunctionType const&) { return {}; }
  208. ErrorOr<void, ValidationError> validate(TableType const&);
  209. ErrorOr<void, ValidationError> validate(MemoryType const&);
  210. ErrorOr<void, ValidationError> validate(GlobalType const&) { return {}; }
  211. private:
  212. explicit Validator(Context context)
  213. : m_context(move(context))
  214. {
  215. }
  216. struct Errors {
  217. static ValidationError invalid(StringView name) { return String::formatted("Invalid {}", name); }
  218. template<typename Expected, typename Given>
  219. static ValidationError invalid(StringView name, Expected expected, Given given, SourceLocation location = SourceLocation::current())
  220. {
  221. if constexpr (WASM_VALIDATOR_DEBUG)
  222. return String::formatted("Invalid {} in {}, expected {} but got {}", name, find_instruction_name(location), expected, given);
  223. else
  224. return String::formatted("Invalid {}, expected {} but got {}", name, expected, given);
  225. }
  226. template<typename... Args>
  227. static ValidationError non_conforming_types(StringView name, Args... args)
  228. {
  229. return String::formatted("Non-conforming types for {}: {}", name, Vector { args... });
  230. }
  231. static ValidationError duplicate_export_name(StringView name) { return String::formatted("Duplicate exported name '{}'", name); }
  232. template<typename T, typename U, typename V>
  233. static ValidationError out_of_bounds(StringView name, V value, T min, U max) { return String::formatted("Value {} for {} is out of bounds ({},{})", value, name, min, max); }
  234. template<typename... Expected>
  235. static ValidationError invalid_stack_state(Stack const& stack, Tuple<Expected...> expected, SourceLocation location = SourceLocation::current())
  236. {
  237. constexpr size_t count = expected.size();
  238. StringBuilder builder;
  239. if constexpr (WASM_VALIDATOR_DEBUG)
  240. builder.appendff("Invalid stack state in {}: ", find_instruction_name(location));
  241. else
  242. builder.appendff("Invalid stack state in <unknown>: ");
  243. builder.append("Expected [ ");
  244. expected.apply_as_args([&]<typename... Ts>(Ts const&... args) {
  245. (builder.appendff("{} ", args), ...);
  246. });
  247. builder.append("], but found [ ");
  248. auto actual_size = stack.actual_size();
  249. for (size_t i = 1; i <= min(count, actual_size); ++i) {
  250. auto& entry = stack.at(actual_size - i);
  251. if (entry.is_known) {
  252. builder.appendff("{} ", entry.concrete_type);
  253. } else {
  254. builder.appendff("<polymorphic stack>");
  255. break;
  256. }
  257. }
  258. builder.append("]");
  259. return { builder.to_string() };
  260. }
  261. private:
  262. static String find_instruction_name(SourceLocation const&);
  263. };
  264. enum class ChildScopeKind {
  265. Block,
  266. IfWithoutElse,
  267. IfWithElse,
  268. Else,
  269. };
  270. struct BlockDetails {
  271. size_t initial_stack_size { 0 };
  272. struct IfDetails {
  273. Stack initial_stack;
  274. };
  275. Variant<IfDetails, Empty> details;
  276. };
  277. Context m_context;
  278. Vector<Context> m_parent_contexts;
  279. Vector<ChildScopeKind> m_entered_scopes;
  280. Vector<BlockDetails> m_block_details;
  281. Vector<FunctionType> m_entered_blocks;
  282. };
  283. }
  284. template<>
  285. struct AK::Formatter<Wasm::Validator::StackEntry> : public AK::Formatter<StringView> {
  286. ErrorOr<void> format(FormatBuilder& builder, Wasm::Validator::StackEntry const& value)
  287. {
  288. if (value.is_known)
  289. return Formatter<StringView>::format(builder, Wasm::ValueType::kind_name(value.concrete_type.kind()));
  290. return Formatter<StringView>::format(builder, "<unknown>"sv);
  291. }
  292. };
  293. template<>
  294. struct AK::Formatter<Wasm::Validator::Stack> : public AK::Formatter<Vector<Wasm::Validator::StackEntry>> {
  295. ErrorOr<void> format(FormatBuilder& builder, Wasm::Validator::Stack const& value)
  296. {
  297. return Formatter<Vector<Wasm::Validator::StackEntry>>::format(builder, static_cast<Vector<Wasm::Validator::StackEntry> const&>(value));
  298. }
  299. };
  300. template<>
  301. struct AK::Formatter<Wasm::ValueType> : public AK::Formatter<StringView> {
  302. ErrorOr<void> format(FormatBuilder& builder, Wasm::ValueType const& value)
  303. {
  304. return Formatter<StringView>::format(builder, Wasm::ValueType::kind_name(value.kind()));
  305. }
  306. };
  307. template<>
  308. struct AK::Formatter<Wasm::ValidationError> : public AK::Formatter<StringView> {
  309. ErrorOr<void> format(FormatBuilder& builder, Wasm::ValidationError const& error)
  310. {
  311. return Formatter<StringView>::format(builder, error.error_string);
  312. }
  313. };