Skip to main content

gear_pwasm_utils/
rules.rs

1#[cfg(not(features = "std"))]
2use crate::std::collections::BTreeMap as Map;
3#[cfg(features = "std")]
4use crate::std::collections::HashMap as Map;
5
6use crate::std::{num::NonZeroU32, str::FromStr};
7use parity_wasm::elements::Instruction;
8
9pub struct UnknownInstruction;
10
11/// An interface that describes instruction costs.
12pub trait Rules {
13	/// Returns the cost for the passed `instruction`.
14	///
15	/// Returning `None` makes the gas instrumention end with an error. This is meant
16	/// as a way to have a partial rule set where any instruction that is not specifed
17	/// is considered as forbidden.
18	fn instruction_cost(&self, instruction: &Instruction) -> Option<u32>;
19
20	/// Returns the costs for growing the memory using the `memory.grow` instruction.
21	///
22	/// Please note that these costs are in addition to the costs specified by `instruction_cost`
23	/// for the `memory.grow` instruction. Specifying `None` leads to no additional charge.
24	/// Those are meant as dynamic costs which take the amount of pages that the memory is
25	/// grown by into consideration. This is not possible using `instruction_cost` because
26	/// those costs depend on the stack and must be injected as code into the function calling
27	/// `memory.grow`. Therefore returning `Some` comes with a performance cost.
28	fn memory_grow_cost(&self) -> Option<MemoryGrowCost>;
29}
30
31/// Dynamic costs for memory growth.
32#[derive(Debug, PartialEq, Eq, Copy, Clone)]
33pub enum MemoryGrowCost {
34	/// Charge the specified amount for each page that the memory is grown by.
35	Linear(NonZeroU32),
36}
37
38#[derive(Debug, PartialEq, Eq, Copy, Clone)]
39pub enum Metering {
40	Regular,
41	Forbidden,
42	Fixed(u32),
43}
44
45#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
46pub enum InstructionType {
47	Bit,
48	Add,
49	Mul,
50	Div,
51	Load,
52	Store,
53	Const,
54	FloatConst,
55	Local,
56	Global,
57	ControlFlow,
58	IntegerComparison,
59	FloatComparison,
60	Float,
61	Conversion,
62	FloatConversion,
63	Reinterpretation,
64	Unreachable,
65	Nop,
66	CurrentMemory,
67	GrowMemory,
68	SignExt,
69}
70
71impl FromStr for InstructionType {
72	type Err = UnknownInstruction;
73
74	fn from_str(s: &str) -> Result<Self, Self::Err> {
75		match s {
76			"bit" => Ok(InstructionType::Bit),
77			"add" => Ok(InstructionType::Add),
78			"mul" => Ok(InstructionType::Mul),
79			"div" => Ok(InstructionType::Div),
80			"load" => Ok(InstructionType::Load),
81			"store" => Ok(InstructionType::Store),
82			"const" => Ok(InstructionType::Const),
83			"local" => Ok(InstructionType::Local),
84			"global" => Ok(InstructionType::Global),
85			"flow" => Ok(InstructionType::ControlFlow),
86			"integer_comp" => Ok(InstructionType::IntegerComparison),
87			"float_comp" => Ok(InstructionType::FloatComparison),
88			"float" => Ok(InstructionType::Float),
89			"conversion" => Ok(InstructionType::Conversion),
90			"float_conversion" => Ok(InstructionType::FloatConversion),
91			"reinterpret" => Ok(InstructionType::Reinterpretation),
92			"unreachable" => Ok(InstructionType::Unreachable),
93			"nop" => Ok(InstructionType::Nop),
94			"current_mem" => Ok(InstructionType::CurrentMemory),
95			"grow_mem" => Ok(InstructionType::GrowMemory),
96			"sign_ext" => Ok(InstructionType::SignExt),
97
98			_ => Err(UnknownInstruction),
99		}
100	}
101}
102
103impl InstructionType {
104	pub fn op(instruction: &Instruction) -> Self {
105		use Instruction::*;
106
107		match *instruction {
108			Unreachable => InstructionType::Unreachable,
109			Nop => InstructionType::Nop,
110			Block(_) => InstructionType::ControlFlow,
111			Loop(_) => InstructionType::ControlFlow,
112			If(_) => InstructionType::ControlFlow,
113			Else => InstructionType::ControlFlow,
114			End => InstructionType::ControlFlow,
115			Br(_) => InstructionType::ControlFlow,
116			BrIf(_) => InstructionType::ControlFlow,
117			BrTable(_) => InstructionType::ControlFlow,
118			Return => InstructionType::ControlFlow,
119			Call(_) => InstructionType::ControlFlow,
120			CallIndirect(_, _) => InstructionType::ControlFlow,
121			Drop => InstructionType::ControlFlow,
122			Select => InstructionType::ControlFlow,
123
124			GetLocal(_) => InstructionType::Local,
125			SetLocal(_) => InstructionType::Local,
126			TeeLocal(_) => InstructionType::Local,
127			GetGlobal(_) => InstructionType::Global,
128			SetGlobal(_) => InstructionType::Global,
129
130			I32Load(_, _) => InstructionType::Load,
131			I64Load(_, _) => InstructionType::Load,
132			F32Load(_, _) => InstructionType::Load,
133			F64Load(_, _) => InstructionType::Load,
134			I32Load8S(_, _) => InstructionType::Load,
135			I32Load8U(_, _) => InstructionType::Load,
136			I32Load16S(_, _) => InstructionType::Load,
137			I32Load16U(_, _) => InstructionType::Load,
138			I64Load8S(_, _) => InstructionType::Load,
139			I64Load8U(_, _) => InstructionType::Load,
140			I64Load16S(_, _) => InstructionType::Load,
141			I64Load16U(_, _) => InstructionType::Load,
142			I64Load32S(_, _) => InstructionType::Load,
143			I64Load32U(_, _) => InstructionType::Load,
144
145			I32Store(_, _) => InstructionType::Store,
146			I64Store(_, _) => InstructionType::Store,
147			F32Store(_, _) => InstructionType::Store,
148			F64Store(_, _) => InstructionType::Store,
149			I32Store8(_, _) => InstructionType::Store,
150			I32Store16(_, _) => InstructionType::Store,
151			I64Store8(_, _) => InstructionType::Store,
152			I64Store16(_, _) => InstructionType::Store,
153			I64Store32(_, _) => InstructionType::Store,
154
155			CurrentMemory(_) => InstructionType::CurrentMemory,
156			GrowMemory(_) => InstructionType::GrowMemory,
157
158			I32Const(_) => InstructionType::Const,
159			I64Const(_) => InstructionType::Const,
160
161			F32Const(_) => InstructionType::FloatConst,
162			F64Const(_) => InstructionType::FloatConst,
163
164			I32Eqz => InstructionType::IntegerComparison,
165			I32Eq => InstructionType::IntegerComparison,
166			I32Ne => InstructionType::IntegerComparison,
167			I32LtS => InstructionType::IntegerComparison,
168			I32LtU => InstructionType::IntegerComparison,
169			I32GtS => InstructionType::IntegerComparison,
170			I32GtU => InstructionType::IntegerComparison,
171			I32LeS => InstructionType::IntegerComparison,
172			I32LeU => InstructionType::IntegerComparison,
173			I32GeS => InstructionType::IntegerComparison,
174			I32GeU => InstructionType::IntegerComparison,
175
176			I64Eqz => InstructionType::IntegerComparison,
177			I64Eq => InstructionType::IntegerComparison,
178			I64Ne => InstructionType::IntegerComparison,
179			I64LtS => InstructionType::IntegerComparison,
180			I64LtU => InstructionType::IntegerComparison,
181			I64GtS => InstructionType::IntegerComparison,
182			I64GtU => InstructionType::IntegerComparison,
183			I64LeS => InstructionType::IntegerComparison,
184			I64LeU => InstructionType::IntegerComparison,
185			I64GeS => InstructionType::IntegerComparison,
186			I64GeU => InstructionType::IntegerComparison,
187
188			F32Eq => InstructionType::FloatComparison,
189			F32Ne => InstructionType::FloatComparison,
190			F32Lt => InstructionType::FloatComparison,
191			F32Gt => InstructionType::FloatComparison,
192			F32Le => InstructionType::FloatComparison,
193			F32Ge => InstructionType::FloatComparison,
194
195			F64Eq => InstructionType::FloatComparison,
196			F64Ne => InstructionType::FloatComparison,
197			F64Lt => InstructionType::FloatComparison,
198			F64Gt => InstructionType::FloatComparison,
199			F64Le => InstructionType::FloatComparison,
200			F64Ge => InstructionType::FloatComparison,
201
202			I32Clz => InstructionType::Bit,
203			I32Ctz => InstructionType::Bit,
204			I32Popcnt => InstructionType::Bit,
205			I32Add => InstructionType::Add,
206			I32Sub => InstructionType::Add,
207			I32Mul => InstructionType::Mul,
208			I32DivS => InstructionType::Div,
209			I32DivU => InstructionType::Div,
210			I32RemS => InstructionType::Div,
211			I32RemU => InstructionType::Div,
212			I32And => InstructionType::Bit,
213			I32Or => InstructionType::Bit,
214			I32Xor => InstructionType::Bit,
215			I32Shl => InstructionType::Bit,
216			I32ShrS => InstructionType::Bit,
217			I32ShrU => InstructionType::Bit,
218			I32Rotl => InstructionType::Bit,
219			I32Rotr => InstructionType::Bit,
220
221			I64Clz => InstructionType::Bit,
222			I64Ctz => InstructionType::Bit,
223			I64Popcnt => InstructionType::Bit,
224			I64Add => InstructionType::Add,
225			I64Sub => InstructionType::Add,
226			I64Mul => InstructionType::Mul,
227			I64DivS => InstructionType::Div,
228			I64DivU => InstructionType::Div,
229			I64RemS => InstructionType::Div,
230			I64RemU => InstructionType::Div,
231			I64And => InstructionType::Bit,
232			I64Or => InstructionType::Bit,
233			I64Xor => InstructionType::Bit,
234			I64Shl => InstructionType::Bit,
235			I64ShrS => InstructionType::Bit,
236			I64ShrU => InstructionType::Bit,
237			I64Rotl => InstructionType::Bit,
238			I64Rotr => InstructionType::Bit,
239
240			F32Abs => InstructionType::Float,
241			F32Neg => InstructionType::Float,
242			F32Ceil => InstructionType::Float,
243			F32Floor => InstructionType::Float,
244			F32Trunc => InstructionType::Float,
245			F32Nearest => InstructionType::Float,
246			F32Sqrt => InstructionType::Float,
247			F32Add => InstructionType::Float,
248			F32Sub => InstructionType::Float,
249			F32Mul => InstructionType::Float,
250			F32Div => InstructionType::Float,
251			F32Min => InstructionType::Float,
252			F32Max => InstructionType::Float,
253			F32Copysign => InstructionType::Float,
254			F64Abs => InstructionType::Float,
255			F64Neg => InstructionType::Float,
256			F64Ceil => InstructionType::Float,
257			F64Floor => InstructionType::Float,
258			F64Trunc => InstructionType::Float,
259			F64Nearest => InstructionType::Float,
260			F64Sqrt => InstructionType::Float,
261			F64Add => InstructionType::Float,
262			F64Sub => InstructionType::Float,
263			F64Mul => InstructionType::Float,
264			F64Div => InstructionType::Float,
265			F64Min => InstructionType::Float,
266			F64Max => InstructionType::Float,
267			F64Copysign => InstructionType::Float,
268
269			I32WrapI64 => InstructionType::Conversion,
270			I64ExtendSI32 => InstructionType::Conversion,
271			I64ExtendUI32 => InstructionType::Conversion,
272
273			I32TruncSF32 => InstructionType::FloatConversion,
274			I32TruncUF32 => InstructionType::FloatConversion,
275			I32TruncSF64 => InstructionType::FloatConversion,
276			I32TruncUF64 => InstructionType::FloatConversion,
277			I64TruncSF32 => InstructionType::FloatConversion,
278			I64TruncUF32 => InstructionType::FloatConversion,
279			I64TruncSF64 => InstructionType::FloatConversion,
280			I64TruncUF64 => InstructionType::FloatConversion,
281			F32ConvertSI32 => InstructionType::FloatConversion,
282			F32ConvertUI32 => InstructionType::FloatConversion,
283			F32ConvertSI64 => InstructionType::FloatConversion,
284			F32ConvertUI64 => InstructionType::FloatConversion,
285			F32DemoteF64 => InstructionType::FloatConversion,
286			F64ConvertSI32 => InstructionType::FloatConversion,
287			F64ConvertUI32 => InstructionType::FloatConversion,
288			F64ConvertSI64 => InstructionType::FloatConversion,
289			F64ConvertUI64 => InstructionType::FloatConversion,
290			F64PromoteF32 => InstructionType::FloatConversion,
291
292			I32ReinterpretF32 => InstructionType::Reinterpretation,
293			I64ReinterpretF64 => InstructionType::Reinterpretation,
294			F32ReinterpretI32 => InstructionType::Reinterpretation,
295			F64ReinterpretI64 => InstructionType::Reinterpretation,
296
297			SignExt(_) => InstructionType::SignExt,
298		}
299	}
300}
301
302#[derive(Debug)]
303pub struct Set {
304	regular: u32,
305	entries: Map<InstructionType, Metering>,
306	grow: u32,
307}
308
309impl Default for Set {
310	fn default() -> Self {
311		Set { regular: 1, entries: Map::new(), grow: 0 }
312	}
313}
314
315impl Set {
316	pub fn new(regular: u32, entries: Map<InstructionType, Metering>) -> Self {
317		Set { regular, entries, grow: 0 }
318	}
319
320	pub fn grow_cost(&self) -> u32 {
321		self.grow
322	}
323
324	pub fn with_grow_cost(mut self, val: u32) -> Self {
325		self.grow = val;
326		self
327	}
328
329	pub fn with_forbidden_floats(mut self) -> Self {
330		self.entries.insert(InstructionType::Float, Metering::Forbidden);
331		self.entries.insert(InstructionType::FloatComparison, Metering::Forbidden);
332		self.entries.insert(InstructionType::FloatConst, Metering::Forbidden);
333		self.entries.insert(InstructionType::FloatConversion, Metering::Forbidden);
334		self
335	}
336}
337
338impl Rules for Set {
339	fn instruction_cost(&self, instruction: &Instruction) -> Option<u32> {
340		match self.entries.get(&InstructionType::op(instruction)) {
341			None | Some(Metering::Regular) => Some(self.regular),
342			Some(Metering::Fixed(val)) => Some(*val),
343			Some(Metering::Forbidden) => None,
344		}
345	}
346
347	fn memory_grow_cost(&self) -> Option<MemoryGrowCost> {
348		NonZeroU32::new(self.grow).map(MemoryGrowCost::Linear)
349	}
350}