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