Validator.h 13 KB

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