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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use clap::{crate_authors, crate_version, Parser};
#[cfg(feature = "check-endpoints")]
use ic_wasm::check_endpoints::check_endpoints;
use ic_wasm::utils::make_validator_with_features;
use std::path::PathBuf;
#[derive(Parser)]
#[clap(
version = crate_version!(),
author = crate_authors!(),
)]
struct Opts {
/// Input Wasm file.
input: PathBuf,
/// Write the transformed Wasm file if provided.
#[clap(short, long)]
output: Option<PathBuf>,
#[clap(subcommand)]
subcommand: SubCommand,
}
#[derive(Parser)]
enum SubCommand {
/// Manage metadata in the Wasm module
Metadata {
/// Name of metadata. If not provided, list the current metadata sections.
name: Option<String>,
/// Content of metadata as a string
#[clap(short, long, requires("name"))]
data: Option<String>,
/// Content of metadata from a file
#[clap(short, long, requires("name"), conflicts_with("data"))]
file: Option<PathBuf>,
/// Visibility of metadata
#[clap(short, long, value_parser = ["public", "private"], default_value = "private")]
visibility: String,
/// Preserve the `name` section in the generated Wasm. This is needed to
/// display the names of functions, locals, etc. in backtraces or
/// debuggers.
#[clap(short, long)]
keep_name_section: bool,
},
/// Limit resource usage
Resource {
/// Remove `ic0.call_cycles_add[128]` system API calls
#[clap(short, long)]
remove_cycles_transfer: bool,
/// Filter `ic0.call_cycles_add[128]` system API calls
#[clap(short, long, conflicts_with_all = &["remove_cycles_transfer", "playground_backend_redirect"])]
filter_cycles_transfer: bool,
/// Allocate at most specified amount of memory pages for Wasm heap memory
#[clap(short('m'), long)]
limit_heap_memory_page: Option<u32>,
/// Allocate at most specified amount of memory pages for stable memory
#[clap(short, long)]
limit_stable_memory_page: Option<u32>,
/// Redirects controller system API calls to specified motoko backend canister ID
#[clap(short, long)]
playground_backend_redirect: Option<candid::Principal>,
},
/// List information about the Wasm canister
Info {
/// Format the output as JSON
#[clap(short, long)]
#[cfg(feature = "serde")]
json: bool,
},
/// Remove unused functions and debug info
Shrink {
/// Preserve the `name` section in the generated Wasm. This is needed to
/// display the names of functions, locals, etc. in backtraces or
/// debuggers.
#[clap(short, long)]
keep_name_section: bool,
},
/// Optimize the Wasm module using wasm-opt
#[cfg(feature = "wasm-opt")]
Optimize {
#[clap()]
level: ic_wasm::optimize::OptLevel,
#[clap(long("inline-functions-with-loops"))]
inline_functions_with_loops: bool,
#[clap(long("always-inline-max-function-size"))]
always_inline_max_function_size: Option<u32>,
/// Preserve the `name` section in the generated Wasm. This is needed to
/// display the names of functions, locals, etc. in backtraces or
/// debuggers.
#[clap(short, long)]
keep_name_section: bool,
},
/// Instrument canister method to emit execution trace to stable memory (experimental)
Instrument {
/// Trace only the specified list of functions. The function cannot be recursive
#[clap(short, long)]
trace_only: Option<Vec<String>>,
/// If the canister preallocates a stable memory region, specify the starting page. Required if you want to profile upgrades, or the canister uses stable memory
#[clap(short, long)]
start_page: Option<i32>,
/// The number of pages of the preallocated stable memory
#[clap(short, long, requires("start_page"))]
page_limit: Option<i32>,
/// Store profiling traces in heap memory instead of stable memory.
/// Use this for canisters that use stable memory for their own purposes
/// (e.g., Emscripten, Idris2, AssemblyScript-based canisters).
/// Traces are stored in WASM linear memory and will not persist across upgrades.
#[clap(long, conflicts_with_all = &["start_page", "page_limit"])]
heap_trace: bool,
/// Number of WASM pages (64KB each) to allocate for heap trace buffer.
/// Only used with --heap-trace. Default: 64 (4MB total)
#[clap(long, default_value = "64", requires = "heap_trace")]
heap_pages: i32,
/// Replace WASI imports with stub functions that return 0 (success)
#[clap(long)]
stub_wasi: bool,
},
/// Check canister endpoints against provided Candid interface
#[cfg(feature = "check-endpoints")]
CheckEndpoints {
/// Candid interface file.
#[clap(long)]
candid: Option<PathBuf>,
/// Optionally specify hidden endpoints, i.e., endpoints that are exposed by the canister but
/// not present in the Candid interface file.
#[arg(long)]
hidden: Option<PathBuf>,
},
}
fn main() -> anyhow::Result<()> {
let opts: Opts = Opts::parse();
let keep_name_section = match opts.subcommand {
SubCommand::Shrink { keep_name_section } => keep_name_section,
#[cfg(feature = "wasm-opt")]
SubCommand::Optimize {
keep_name_section, ..
} => keep_name_section,
SubCommand::Metadata {
keep_name_section, ..
} => keep_name_section,
_ => false,
};
let mut m = ic_wasm::utils::parse_wasm_file(opts.input, keep_name_section)?;
match &opts.subcommand {
#[cfg(feature = "serde")]
SubCommand::Info { json } => {
let wasm_info = ic_wasm::info::WasmInfo::from(&m);
if *json {
let json = serde_json::to_string_pretty(&wasm_info)
.expect("Failed to express the Wasm information as JSON.");
println!("{json}");
} else {
print!("{wasm_info}");
}
}
#[cfg(not(feature = "serde"))]
SubCommand::Info {} => {
let wasm_info = ic_wasm::info::WasmInfo::from(&m);
print!("{wasm_info}");
}
SubCommand::Shrink { .. } => ic_wasm::shrink::shrink(&mut m),
#[cfg(feature = "wasm-opt")]
SubCommand::Optimize {
level,
inline_functions_with_loops,
always_inline_max_function_size,
..
} => ic_wasm::optimize::optimize(
&mut m,
level,
*inline_functions_with_loops,
always_inline_max_function_size,
keep_name_section,
)?,
SubCommand::Instrument {
trace_only,
start_page,
page_limit,
heap_trace,
heap_pages,
stub_wasi,
} => {
use ic_wasm::instrumentation::{instrument, Config};
let config = Config {
trace_only_funcs: trace_only.clone().unwrap_or(vec![]),
start_address: start_page.map(|page| i64::from(page) * 65536),
page_limit: *page_limit,
heap_trace: *heap_trace,
heap_pages: *heap_pages,
stub_wasi: *stub_wasi,
};
instrument(&mut m, config).map_err(|e| anyhow::anyhow!("{e}"))?;
}
SubCommand::Resource {
remove_cycles_transfer,
filter_cycles_transfer,
limit_heap_memory_page,
limit_stable_memory_page,
playground_backend_redirect,
} => {
use ic_wasm::limit_resource::{limit_resource, Config};
let config = Config {
remove_cycles_add: *remove_cycles_transfer,
filter_cycles_add: *filter_cycles_transfer,
limit_heap_memory_page: *limit_heap_memory_page,
limit_stable_memory_page: *limit_stable_memory_page,
playground_canister_id: *playground_backend_redirect,
};
limit_resource(&mut m, &config)
}
SubCommand::Metadata {
name,
data,
file,
visibility,
keep_name_section: _,
} => {
use ic_wasm::metadata::*;
if let Some(name) = name {
let visibility = match visibility.as_str() {
"public" => Kind::Public,
"private" => Kind::Private,
_ => unreachable!(),
};
let data = match (data, file) {
(Some(data), None) => data.as_bytes().to_vec(),
(None, Some(path)) => std::fs::read(path)?,
(None, None) => {
let data = get_metadata(&m, name);
if let Some(data) = data {
println!("{}", String::from_utf8_lossy(&data));
} else {
println!("Cannot find metadata {name}");
}
return Ok(());
}
(_, _) => unreachable!(),
};
add_metadata(&mut m, visibility, name, data)
} else {
let names = list_metadata(&m);
for name in names.iter() {
println!("{name}");
}
return Ok(());
}
}
#[cfg(feature = "check-endpoints")]
SubCommand::CheckEndpoints { candid, hidden } => {
return check_endpoints(&m, candid.as_deref(), hidden.as_deref());
}
};
// validate new module
let module_bytes = m.emit_wasm();
let mut validator = make_validator_with_features();
if let Err(e) = validator.validate_all(&module_bytes) {
println!("WARNING: The output of ic-wasm failed to validate. Please report this via github issue or on https://forum.dfinity.org/");
eprintln!("{e}");
}
if let Some(output) = opts.output {
std::fs::write(output, module_bytes).expect("failed to write wasm module");
}
Ok(())
}