Validator.h 13 KB

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