slimwasm 0.1.0

A WASM size profiler for wasm32-unknown-unknown and wasm32-wasip2 binaries
Documentation
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Size analysis and retained size computation using reachability/dominator-style analysis

use crate::parser::{ParsedWasm, WasmItemKind};
use petgraph::algo::dominators;
use petgraph::graph::{DiGraph, NodeIndex};
use petgraph::visit::EdgeRef;
use std::collections::{HashMap, HashSet, VecDeque};

/// Information about an item's size
#[derive(Debug, Clone, serde::Serialize)]
pub struct SizeInfo {
    /// Shallow/raw size of this item
    pub shallow_size: u64,
    /// Retained size (this item + everything it uniquely keeps alive)
    pub retained_size: u64,
}

/// Detailed information about an item for display
#[derive(Debug, Clone, serde::Serialize)]
pub struct ItemInfo {
    pub name: String,
    pub raw_name: String,
    pub kind: WasmItemKind,
    pub shallow_size: u64,
    pub retained_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub func_index: Option<u32>,
}

/// Result of WASM analysis
#[derive(Debug, serde::Serialize)]
pub struct WasmAnalysis {
    pub total_size: u64,
    pub items: Vec<ItemInfo>,
    pub section_sizes: HashMap<String, u64>,
    pub is_component: bool,
}

/// Retention path explaining why an item is in the binary
#[derive(Debug, Clone, serde::Serialize)]
pub struct RetentionPath {
    pub target: String,
    pub target_kind: WasmItemKind,
    pub path: Vec<RetentionStep>,
}

/// A step in a retention path
#[derive(Debug, Clone, serde::Serialize)]
pub struct RetentionStep {
    pub name: String,
    pub kind: WasmItemKind,
    pub relationship: String,
}

/// Analyzer for computing retained sizes
pub struct RetainedSizeAnalyzer {
    /// The call graph as a petgraph
    graph: DiGraph<u32, ()>,
    /// Map from function index to node index
    func_to_node: HashMap<u32, NodeIndex>,
    /// Map from node index to function index
    node_to_func: HashMap<NodeIndex, u32>,
    /// Function sizes
    func_sizes: HashMap<u32, u64>,
    /// Root functions (exports, start function)
    roots: HashSet<u32>,
    /// Parsed WASM data
    parsed: ParsedWasm,
}

impl RetainedSizeAnalyzer {
    /// Create a new analyzer from parsed WASM
    pub fn new(parsed: ParsedWasm) -> Self {
        let mut graph = DiGraph::new();
        let mut func_to_node = HashMap::new();
        let mut node_to_func = HashMap::new();
        let mut func_sizes = HashMap::new();

        // Create nodes for all functions
        for item in &parsed.items {
            if item.kind == WasmItemKind::Function {
                if let Some(func_idx) = item.func_index {
                    let node = graph.add_node(func_idx);
                    func_to_node.insert(func_idx, node);
                    node_to_func.insert(node, func_idx);
                    func_sizes.insert(func_idx, item.size);
                }
            }
        }

        // Add edges from call graph
        for (caller, callees) in &parsed.call_graph {
            if let Some(&caller_node) = func_to_node.get(caller) {
                for callee in callees {
                    if let Some(&callee_node) = func_to_node.get(callee) {
                        graph.add_edge(caller_node, callee_node, ());
                    }
                }
            }
        }

        // Identify root functions (exports)
        let mut roots = HashSet::new();
        for item in &parsed.items {
            if item.kind == WasmItemKind::Export && item.name.contains("func") {
                // Extract function index from export
                // Exports reference functions by index
                for func_item in &parsed.items {
                    if func_item.kind == WasmItemKind::Function {
                        if let Some(func_idx) = func_item.func_index {
                            // Heuristic: mark all non-imported functions as potentially reachable
                            if func_idx >= parsed.num_imported_funcs {
                                roots.insert(func_idx);
                            }
                        }
                    }
                }
            }
        }

        // If no exports found, consider all functions as roots (conservative)
        if roots.is_empty() {
            for item in &parsed.items {
                if item.kind == WasmItemKind::Function {
                    if let Some(func_idx) = item.func_index {
                        roots.insert(func_idx);
                    }
                }
            }
        }

        Self {
            graph,
            func_to_node,
            node_to_func,
            func_sizes,
            roots,
            parsed,
        }
    }

    /// Compute retained size for a function
    pub fn retained_size(&self, func_idx: u32) -> u64 {
        let Some(&node) = self.func_to_node.get(&func_idx) else {
            return 0;
        };

        // BFS to find all reachable functions
        let mut reachable = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back(node);
        reachable.insert(node);

        while let Some(current) = queue.pop_front() {
            for edge in self.graph.edges(current) {
                let target = edge.target();
                if !reachable.contains(&target) {
                    reachable.insert(target);
                    queue.push_back(target);
                }
            }
        }

        // Sum sizes of all reachable functions
        let mut total = 0u64;
        for &reached_node in &reachable {
            if let Some(&func_idx) = self.node_to_func.get(&reached_node) {
                total += self.func_sizes.get(&func_idx).copied().unwrap_or(0);
            }
        }

        total
    }

    /// Compute dominators to find truly retained (uniquely kept alive) sizes
    pub fn compute_dominated_sizes(&self) -> HashMap<u32, u64> {
        let mut dominated_sizes = HashMap::new();

        // For each root, compute what it dominates
        for &root_func in &self.roots {
            if let Some(&root_node) = self.func_to_node.get(&root_func) {
                // Compute dominators from this root
                let doms = dominators::simple_fast(&self.graph, root_node);

                // Count nodes dominated by each function
                let mut dominator_counts: HashMap<NodeIndex, HashSet<NodeIndex>> = HashMap::new();

                for node in self.graph.node_indices() {
                    let mut current = node;
                    while let Some(idom) = doms.immediate_dominator(current) {
                        dominator_counts.entry(idom).or_default().insert(node);
                        current = idom;
                    }
                }

                // Sum sizes for dominated nodes
                for (dominator, dominated) in dominator_counts {
                    if let Some(&func_idx) = self.node_to_func.get(&dominator) {
                        let size: u64 = dominated
                            .iter()
                            .filter_map(|n| self.node_to_func.get(n))
                            .filter_map(|f| self.func_sizes.get(f))
                            .sum();
                        *dominated_sizes.entry(func_idx).or_insert(0) += size;
                    }
                }
            }
        }

        // Add self-size to dominated size
        for (&func_idx, &self_size) in &self.func_sizes {
            *dominated_sizes.entry(func_idx).or_insert(0) += self_size;
        }

        dominated_sizes
    }

    /// Find why an item is retained (the path from roots to this item)
    pub fn find_retention_paths(&self, name: &str, max_depth: usize) -> Vec<RetentionPath> {
        let mut paths = Vec::new();

        // Find functions matching the name
        let matching_funcs: Vec<_> = self
            .parsed
            .items
            .iter()
            .filter(|item| {
                item.kind == WasmItemKind::Function
                    && (item.name.contains(name) || item.raw_name.contains(name))
            })
            .collect();

        for func in matching_funcs {
            let Some(func_idx) = func.func_index else {
                continue;
            };
            let Some(&target_node) = self.func_to_node.get(&func_idx) else {
                continue;
            };

            // BFS backwards to find paths from roots
            let reverse_paths = self.find_paths_to_roots(target_node, max_depth);

            for path in reverse_paths {
                let steps: Vec<RetentionStep> = path
                    .iter()
                    .map(|&node| {
                        let func_idx = self.node_to_func.get(&node).copied().unwrap_or(0);
                        let name = self
                            .parsed
                            .func_names
                            .get(&func_idx)
                            .cloned()
                            .unwrap_or_else(|| format!("func[{}]", func_idx));
                        RetentionStep {
                            name: rustc_demangle::demangle(&name).to_string(),
                            kind: WasmItemKind::Function,
                            relationship: "calls".to_string(),
                        }
                    })
                    .collect();

                paths.push(RetentionPath {
                    target: func.name.clone(),
                    target_kind: func.kind,
                    path: steps,
                });
            }
        }

        paths
    }

    /// Find paths from a node back to any root
    fn find_paths_to_roots(&self, target: NodeIndex, max_depth: usize) -> Vec<Vec<NodeIndex>> {
        let mut all_paths = Vec::new();
        let mut queue: VecDeque<(NodeIndex, Vec<NodeIndex>)> = VecDeque::new();
        queue.push_back((target, vec![target]));

        while let Some((current, path)) = queue.pop_front() {
            if path.len() > max_depth {
                continue;
            }

            // Check if current is a root
            if let Some(&func_idx) = self.node_to_func.get(&current) {
                if self.roots.contains(&func_idx) && path.len() > 1 {
                    // Found a path from root to target
                    let mut reversed = path.clone();
                    reversed.reverse();
                    all_paths.push(reversed);
                    continue;
                }
            }

            // Find predecessors (nodes that call this one)
            for edge in self
                .graph
                .edges_directed(current, petgraph::Direction::Incoming)
            {
                let source = edge.source();
                if !path.contains(&source) {
                    let mut new_path = path.clone();
                    new_path.push(source);
                    queue.push_back((source, new_path));
                }
            }
        }

        all_paths
    }

    /// Get analysis results
    pub fn analyze(&self, compute_retained: bool) -> WasmAnalysis {
        let dominated_sizes = if compute_retained {
            self.compute_dominated_sizes()
        } else {
            HashMap::new()
        };

        let items: Vec<ItemInfo> = self
            .parsed
            .items
            .iter()
            .map(|item| {
                let retained_size = if compute_retained {
                    item.func_index
                        .and_then(|idx| dominated_sizes.get(&idx))
                        .copied()
                        .unwrap_or(item.size)
                } else {
                    item.size
                };

                ItemInfo {
                    name: item.name.clone(),
                    raw_name: item.raw_name.clone(),
                    kind: item.kind,
                    shallow_size: item.size,
                    retained_size,
                    func_index: item.func_index,
                }
            })
            .collect();

        WasmAnalysis {
            total_size: self.parsed.total_size,
            items,
            section_sizes: self.parsed.section_sizes.clone(),
            is_component: self.parsed.is_component,
        }
    }

    /// Get the parsed WASM data
    pub fn parsed(&self) -> &ParsedWasm {
        &self.parsed
    }
}

/// Compare two WASM analyses
#[derive(Debug, serde::Serialize)]
pub struct DiffResult {
    pub old_total: u64,
    pub new_total: u64,
    pub size_delta: i64,
    pub items: Vec<DiffItem>,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct DiffItem {
    pub name: String,
    pub kind: WasmItemKind,
    pub old_size: u64,
    pub new_size: u64,
    pub delta: i64,
    pub status: DiffStatus,
}

#[derive(Debug, Clone, Copy, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DiffStatus {
    Added,
    Removed,
    Changed,
    Unchanged,
}

impl std::fmt::Display for DiffStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DiffStatus::Added => write!(f, "added"),
            DiffStatus::Removed => write!(f, "removed"),
            DiffStatus::Changed => write!(f, "changed"),
            DiffStatus::Unchanged => write!(f, "unchanged"),
        }
    }
}

/// Compute diff between two analyses
pub fn compute_diff(old: &WasmAnalysis, new: &WasmAnalysis) -> DiffResult {
    let mut old_items: HashMap<(&str, WasmItemKind), u64> = HashMap::new();
    let mut new_items: HashMap<(&str, WasmItemKind), u64> = HashMap::new();

    for item in &old.items {
        old_items.insert((&item.name, item.kind), item.shallow_size);
    }
    for item in &new.items {
        new_items.insert((&item.name, item.kind), item.shallow_size);
    }

    let mut diff_items = Vec::new();

    // Items in old
    for item in &old.items {
        let old_size = item.shallow_size;
        let key = (&item.name as &str, item.kind);
        let new_size = new_items.get(&key).copied();

        let (new_size, status) = match new_size {
            Some(ns) if ns == old_size => (ns, DiffStatus::Unchanged),
            Some(ns) => (ns, DiffStatus::Changed),
            None => (0, DiffStatus::Removed),
        };

        let delta = new_size as i64 - old_size as i64;

        diff_items.push(DiffItem {
            name: item.name.clone(),
            kind: item.kind,
            old_size,
            new_size,
            delta,
            status,
        });
    }

    // Items only in new
    for item in &new.items {
        let key = (&item.name as &str, item.kind);
        if !old_items.contains_key(&key) {
            diff_items.push(DiffItem {
                name: item.name.clone(),
                kind: item.kind,
                old_size: 0,
                new_size: item.shallow_size,
                delta: item.shallow_size as i64,
                status: DiffStatus::Added,
            });
        }
    }

    // Sort by absolute delta (largest changes first)
    diff_items.sort_by_key(|b| std::cmp::Reverse(b.delta.abs()));

    DiffResult {
        old_total: old.total_size,
        new_total: new.total_size,
        size_delta: new.total_size as i64 - old.total_size as i64,
        items: diff_items,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_diff_status_display() {
        assert_eq!(format!("{}", DiffStatus::Added), "added");
        assert_eq!(format!("{}", DiffStatus::Removed), "removed");
        assert_eq!(format!("{}", DiffStatus::Changed), "changed");
    }
}