1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use super::{
	externalize_mem, inject_runtime_type, optimize, pack_instance, shrink_unknown_stack, std::fmt,
	ununderscore_funcs, OptimizerError, PackingError, TargetRuntime,
};
use parity_wasm::elements;

#[derive(Debug)]
pub enum Error {
	Encoding(elements::Error),
	Packing(PackingError),
	Optimizer,
}

impl From<OptimizerError> for Error {
	fn from(_err: OptimizerError) -> Self {
		Error::Optimizer
	}
}

impl From<PackingError> for Error {
	fn from(err: PackingError) -> Self {
		Error::Packing(err)
	}
}

#[derive(Debug, Clone, Copy)]
pub enum SourceTarget {
	Emscripten,
	Unknown,
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
		use self::Error::*;
		match self {
			Encoding(err) => write!(f, "Encoding error ({})", err),
			Optimizer => write!(f, "Optimization error due to missing export section. Pointed wrong file?"),
			Packing(e) => write!(f, "Packing failed due to module structure error: {}. Sure used correct libraries for building contracts?", e),
		}
	}
}

fn has_ctor(module: &elements::Module, target_runtime: &TargetRuntime) -> bool {
	if let Some(section) = module.export_section() {
		section.entries().iter().any(|e| target_runtime.symbols().create == e.field())
	} else {
		false
	}
}

#[allow(clippy::too_many_arguments)]
pub fn build(
	mut module: elements::Module,
	source_target: SourceTarget,
	runtime_type_version: Option<([u8; 4], u32)>,
	public_api_entries: &[&str],
	enforce_stack_adjustment: bool,
	stack_size: u32,
	skip_optimization: bool,
	target_runtime: &TargetRuntime,
) -> Result<(elements::Module, Option<elements::Module>), Error> {
	if let SourceTarget::Emscripten = source_target {
		module = ununderscore_funcs(module);
	}

	if let SourceTarget::Unknown = source_target {
		// 49152 is 48kb!
		if enforce_stack_adjustment {
			assert!(stack_size <= 1024 * 1024);
			let (new_module, new_stack_top) =
				shrink_unknown_stack(module, 1024 * 1024 - stack_size);
			module = new_module;
			let mut stack_top_page = new_stack_top / 65536;
			if new_stack_top % 65536 > 0 {
				stack_top_page += 1
			};
			module = externalize_mem(module, Some(stack_top_page), 16);
		} else {
			module = externalize_mem(module, None, 16);
		}
	}

	if let Some(runtime_type_version) = runtime_type_version {
		let (runtime_type, runtime_version) = runtime_type_version;
		module = inject_runtime_type(module, runtime_type, runtime_version);
	}

	let mut ctor_module = module.clone();

	let mut public_api_entries = public_api_entries.to_vec();
	public_api_entries.push(target_runtime.symbols().call);
	if !skip_optimization {
		optimize(&mut module, public_api_entries)?;
	}

	if !has_ctor(&ctor_module, target_runtime) {
		return Ok((module, None))
	}

	if !skip_optimization {
		let preserved_exports = match target_runtime {
			TargetRuntime::PWasm(_) => vec![target_runtime.symbols().create],
			TargetRuntime::Substrate(_) => {
				vec![target_runtime.symbols().call, target_runtime.symbols().create]
			},
		};
		optimize(&mut ctor_module, preserved_exports)?;
	}

	if let TargetRuntime::PWasm(_) = target_runtime {
		ctor_module = pack_instance(
			parity_wasm::serialize(module.clone()).map_err(Error::Encoding)?,
			ctor_module.clone(),
			target_runtime,
		)?;
	}

	Ok((module, Some(ctor_module)))
}