nsis 0.3.0

Parse and inspect NSIS installer 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Integration tests for the NSIS parser using self-built test fixtures.
//!
//! All test fixtures are built from `.nsi` scripts in `tests/build_fixtures/`
//! using `makensis` and cover specific compression/encoding/feature combinations.

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::arithmetic_side_effects,
    clippy::indexing_slicing
)]

use nsis::{Error, NsisInstaller};

fn fixture_bytes(name: &str) -> &'static [u8] {
    let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
    let data = std::fs::read(&path).unwrap_or_else(|e| panic!("cannot read {path}: {e}"));
    Vec::leak(data)
}

fn parse_fixture(name: &str) -> NsisInstaller<'static> {
    NsisInstaller::from_bytes(fixture_bytes(name))
        .unwrap_or_else(|e| panic!("failed to parse {name}: {e}"))
}

fn validate_all_structures(inst: &NsisInstaller<'_>) {
    for (i, section) in inst.sections().enumerate() {
        section.unwrap_or_else(|e| panic!("section {i} failed: {e}"));
    }
    for (i, entry) in inst.entries().enumerate() {
        entry.unwrap_or_else(|e| panic!("entry {i} failed: {e}"));
    }
    for (i, page) in inst.pages().enumerate() {
        page.unwrap_or_else(|e| panic!("page {i} failed: {e}"));
    }
}

#[test]
fn deflate_nonsolid() {
    let inst = parse_fixture("deflate_nonsolid.exe");
    assert_eq!(
        inst.compression(),
        nsis::decompress::CompressionMethod::Deflate
    );
    assert_eq!(
        inst.compression_mode(),
        nsis::decompress::CompressionMode::NonSolid
    );
    assert!(inst.section_count() > 0);
    assert!(inst.entry_count() > 0);
    validate_all_structures(&inst);
}

#[test]
fn deflate_solid() {
    let inst = parse_fixture("deflate_solid.exe");
    assert_eq!(
        inst.compression(),
        nsis::decompress::CompressionMethod::Deflate
    );
    assert_eq!(
        inst.compression_mode(),
        nsis::decompress::CompressionMode::Solid
    );
    assert!(inst.section_count() > 0);
    validate_all_structures(&inst);
}

#[test]
fn lzma_nonsolid() {
    let inst = parse_fixture("lzma_nonsolid.exe");
    assert_eq!(
        inst.compression(),
        nsis::decompress::CompressionMethod::Lzma
    );
    assert_eq!(
        inst.compression_mode(),
        nsis::decompress::CompressionMode::NonSolid
    );
    assert!(inst.section_count() > 0);
    validate_all_structures(&inst);
}

#[test]
fn lzma_solid() {
    let inst = parse_fixture("lzma_solid.exe");
    assert_eq!(
        inst.compression(),
        nsis::decompress::CompressionMethod::Lzma
    );
    assert_eq!(
        inst.compression_mode(),
        nsis::decompress::CompressionMode::Solid
    );
    assert!(inst.section_count() > 0);
    validate_all_structures(&inst);
}

#[test]
fn full_featured_sections() {
    let inst = parse_fixture("full_featured.exe");
    assert_eq!(
        inst.compression(),
        nsis::decompress::CompressionMethod::Lzma
    );
    assert_eq!(
        inst.compression_mode(),
        nsis::decompress::CompressionMode::Solid
    );
    assert_eq!(inst.section_count(), 2);
    let sections: Vec<_> = inst.sections().collect();
    let s0 = sections[0].as_ref().unwrap();
    let s1 = sections[1].as_ref().unwrap();
    let name0 = s0
        .inline_name()
        .or_else(|| inst.read_string(s0.name_ptr()).ok().map(|n| n.to_string()))
        .unwrap_or_default();
    let name1 = s1
        .inline_name()
        .or_else(|| inst.read_string(s1.name_ptr()).ok().map(|n| n.to_string()))
        .unwrap_or_default();
    assert_eq!(name0, "Core Files");
    assert_eq!(name1, "Optional Docs");
}

#[test]
fn full_featured_callbacks() {
    let inst = parse_fixture("full_featured.exe");
    assert!(inst.on_init().is_some(), "should have .onInit");
}

#[test]
fn full_featured_registry() {
    let inst = parse_fixture("full_featured.exe");
    let writes: Vec<_> = inst
        .registry_ops()
        .filter_map(|op| match op.ok()? {
            nsis::RegistryOp::Write(w) => Some(w),
            _ => None,
        })
        .collect();
    assert!(writes.len() >= 3, "should have registry writes");
    let has_version = writes.iter().any(|w| {
        w.value_name()
            .map(|n| n.to_string() == "Version")
            .unwrap_or(false)
    });
    assert!(has_version, "should write Version registry value");
}

#[test]
fn full_featured_shortcuts() {
    let inst = parse_fixture("full_featured.exe");
    let shortcuts: Vec<_> = inst.shortcuts().collect();
    assert_eq!(shortcuts.len(), 2, "should have 2 shortcuts");
}

#[test]
fn full_featured_uninstaller() {
    let inst = parse_fixture("full_featured.exe");
    let uninstallers: Vec<_> = inst.uninstallers().collect();
    assert_eq!(uninstallers.len(), 1, "should have 1 uninstaller");
    let u = uninstallers[0].as_ref().unwrap();
    let path = u.path().unwrap().to_string();
    assert!(
        path.contains("uninstall"),
        "path should contain 'uninstall', got '{path}'"
    );
}

#[test]
fn uninstaller_registry_delete_uses_correct_param_layout() {
    let inst = parse_fixture("full_featured.exe");
    let uninstaller = inst.uninstallers().next().unwrap().unwrap();
    let data = uninstaller.decompress().unwrap();
    let uninst = NsisInstaller::from_bytes(&data).unwrap();

    let deletes: Vec<_> = uninst
        .registry_ops()
        .filter_map(|op| match op.ok()? {
            nsis::RegistryOp::Delete(delete) => Some((
                delete.root_name(),
                delete.key().ok()?.to_string(),
                delete.value_name().ok()?.to_string(),
            )),
            _ => None,
        })
        .collect();

    assert!(
        deletes.iter().any(|(root, key, value)| {
            *root == "HKLM" && key == "Software\\FullFeaturedTest" && value.is_empty()
        }),
        "DeleteRegKey should read root from param1 and key from param2"
    );
}

#[test]
fn file_extraction_nonsolid() {
    let inst = parse_fixture("deflate_nonsolid.exe");
    let mut count = 0;
    for file in inst.files() {
        let file = file.unwrap();
        assert!(!file.data().is_empty(), "non-solid file should have data");
        let content = file.decompress().unwrap();
        assert!(
            !content.is_empty(),
            "decompressed content should not be empty"
        );
        count += 1;
    }
    assert!(count > 0, "should find files");
}

#[test]
fn decompression_budget_rejects_oversized_file() {
    // With a tiny budget, every embedded file that decompresses to more than
    // the budget must surface `OutputTooLarge` rather than truncated `Ok`.
    // `deflate_nonsolid` has a genuinely compressed entry (`config.ini`).
    let inst = NsisInstaller::builder(fixture_bytes("deflate_nonsolid.exe"))
        .max_decompressed_size(8)
        .parse()
        .expect("header parsing is independent of the file budget");

    // Compressed entries that expand past the budget must error; uncompressed
    // (stored) entries are copied verbatim and cannot be a bomb, so they're
    // exempt from the budget.
    let mut saw_over_budget = false;
    for file in inst.files() {
        let file = file.unwrap();
        let compressed = file.is_compressed();
        match file.decompress() {
            Ok(_) => {}
            Err(Error::OutputTooLarge { limit }) => {
                assert!(compressed, "only compressed streams are budget-capped");
                assert_eq!(limit, 8);
                saw_over_budget = true;
            }
            Err(e) => panic!("unexpected error: {e}"),
        }
    }
    assert!(
        saw_over_budget,
        "expected at least one compressed file to exceed the 8-byte budget"
    );
}

#[test]
fn generous_budget_extracts_all_files() {
    // The same fixture parses and extracts cleanly with a generous budget,
    // confirming the budget is the only thing the tiny cap changed.
    let inst = NsisInstaller::builder(fixture_bytes("deflate_nonsolid.exe"))
        .max_decompressed_size(256 * 1024 * 1024)
        .parse()
        .unwrap();
    let mut count = 0;
    for file in inst.files() {
        let content = file.unwrap().decompress().unwrap();
        assert!(!content.is_empty());
        count += 1;
    }
    assert!(count > 0);
}

#[test]
fn file_extraction_reports_out_of_bounds_payload() {
    let path = format!(
        "{}/tests/fixtures/deflate_nonsolid.exe",
        env!("CARGO_MANIFEST_DIR")
    );
    let mut data = std::fs::read(&path).unwrap_or_else(|e| panic!("cannot read {path}: {e}"));
    let prefix_offset = {
        let inst = NsisInstaller::from_bytes(&data).unwrap();
        let file = inst.files().next().unwrap().unwrap();
        inst.data_block_offset() + file.data_block_offset() as usize
    };
    data[prefix_offset..prefix_offset + 4].copy_from_slice(&0x7FFF_FFFFu32.to_le_bytes());

    let inst = NsisInstaller::from_bytes(&data).unwrap();
    let first_file = inst.files().next().unwrap();
    assert!(
        first_file.is_err(),
        "out-of-bounds payload should not produce an empty file"
    );
}

#[test]
fn file_extraction_solid() {
    let inst = parse_fixture("lzma_solid.exe");
    let mut count = 0;
    for file in inst.files() {
        let file = file.unwrap();
        assert!(
            !file.data().is_empty(),
            "solid file should have data from cache"
        );
        let content = file.decompress().unwrap();
        assert!(
            !content.is_empty(),
            "decompressed content should not be empty"
        );
        count += 1;
    }
    assert!(count > 0, "should find files");
}

#[test]
fn section_entries_mapping() {
    let inst = parse_fixture("full_featured.exe");
    for section in inst.sections() {
        let section = section.unwrap();
        if section.code_size() > 0 {
            let entries: Vec<_> = inst.section_entries(&section).collect();
            assert_eq!(entries.len(), section.code_size() as usize);
            for entry in &entries {
                entry.as_ref().unwrap();
            }
            return;
        }
    }
    panic!("no section with code found");
}

#[test]
fn opcode_resolution() {
    let inst = parse_fixture("full_featured.exe");
    let mut resolved = 0;
    for entry in inst.entries() {
        let entry = entry.unwrap();
        if inst.resolve_opcode(entry.which()).is_some() {
            resolved += 1;
        }
    }
    assert!(resolved > 0, "no opcodes resolved");
}

#[test]
fn script_formatting_uses_opcode_aware_param_types() {
    let inst = parse_fixture("full_featured.exe");
    let lines: Vec<_> = inst
        .entries()
        .map(|entry| inst.format_entry(&entry.unwrap()))
        .collect();

    assert!(
        lines.iter().any(|line| {
            line.starts_with("EW_GETDLGITEM ")
                && line.contains("dialog=\"$HWNDPARENT\"")
                && line.contains("item_id=\"1037\"")
        }),
        "GetDlgItem should render dialog and item id as strings"
    );
    assert!(
        lines
            .iter()
            .any(|line| line.starts_with("EW_SETCTLCOLORS ") && line.contains("hwnd=\"$_0_\"")),
        "SetCtlColors hwnd should render as a string parameter"
    );
    assert!(
        lines
            .iter()
            .all(|line| !line.contains("$_65503_") && !line.contains("==>")),
        "formatting should not wrap negative output vars or duplicate jump separators"
    );
}

#[test]
fn script_analysis_builds_roots_blocks_and_edges() {
    let inst = parse_fixture("full_featured.exe");
    let analysis = inst.script_analysis().unwrap();

    assert_eq!(analysis.entry_count, inst.entry_count());
    assert!(!analysis.roots.is_empty(), "should discover script roots");
    assert!(
        analysis
            .roots
            .iter()
            .any(|root| matches!(root.kind, nsis::ScriptRootKind::Callback { .. })),
        "should include callback roots"
    );
    assert!(
        analysis
            .roots
            .iter()
            .any(|root| matches!(root.kind, nsis::ScriptRootKind::Section { index: 0 })),
        "should include section roots"
    );
    assert!(!analysis.blocks.is_empty(), "should build basic blocks");
    assert!(
        analysis
            .edges
            .iter()
            .any(|edge| matches!(edge.kind, nsis::EdgeKind::Return)),
        "should include return edges"
    );
    assert!(
        analysis
            .edges
            .iter()
            .any(|edge| matches!(edge.kind, nsis::EdgeKind::Branch { .. })),
        "should include branch edges"
    );
    assert_eq!(
        analysis.entry_to_block.len(),
        analysis.entry_count,
        "entry-to-block map should cover all entries"
    );
    let block = analysis
        .block_for_entry(49)
        .expect("entry 49 should be in a block");
    assert!(
        analysis
            .outgoing_edges(block.id)
            .any(|edge| matches!(edge.kind, nsis::EdgeKind::Branch { .. })),
        "entry 49's block should have a branch edge"
    );
    assert!(
        analysis
            .function_for_entry(81)
            .map(|function| function.name.as_str())
            == Some("section_0"),
        "section body should be assigned to section_0"
    );
    assert!(
        analysis
            .roots_for_entry(79)
            .any(|root| matches!(root.kind, nsis::ScriptRootKind::Callback { .. })),
        "entry 79 should have a callback root"
    );
}

#[test]
fn symbolic_formatting_uses_script_analysis_symbols() {
    let inst = parse_fixture("full_featured.exe");
    let analysis = inst.script_analysis().unwrap();

    let mut saw_symbolic_target = false;
    for (index, entry) in inst.entries().enumerate() {
        let entry = entry.unwrap();
        let line = inst.format_entry_with_analysis(&entry, &analysis);
        if line.contains("=>") && line.contains("(@") {
            saw_symbolic_target = true;
        }
        if index == 49 {
            assert!(
                line.contains("=>") && !line.contains("==>"),
                "symbolic formatting should preserve jump syntax"
            );
        }
    }

    assert!(
        saw_symbolic_target,
        "should render at least one symbolic target"
    );
}

#[test]
fn opcode_constants_are_exported_at_crate_root() {
    let exported = [
        nsis::EW_INVALID_OPCODE,
        nsis::EW_RET,
        nsis::EW_CALL,
        nsis::EW_FGETWS,
    ];
    assert_eq!(exported, [0, 1, 5, 70]);
}

#[test]
fn string_resolution() {
    let inst = parse_fixture("full_featured.exe");
    for section in inst.sections() {
        let section = section.unwrap();
        let _ = inst.read_string(section.name_ptr());
    }
}

#[test]
fn bzip2_nonsolid() {
    let inst = parse_fixture("bzip2_nonsolid.exe");
    assert_eq!(
        inst.compression(),
        nsis::decompress::CompressionMethod::Bzip2
    );
    assert_eq!(
        inst.compression_mode(),
        nsis::decompress::CompressionMode::NonSolid
    );
    assert!(inst.section_count() > 0);
    assert!(inst.entry_count() > 0);
    validate_all_structures(&inst);
}

#[test]
fn bzip2_solid() {
    let inst = parse_fixture("bzip2_solid.exe");
    assert_eq!(
        inst.compression(),
        nsis::decompress::CompressionMethod::Bzip2
    );
    assert_eq!(
        inst.compression_mode(),
        nsis::decompress::CompressionMode::Solid
    );
    assert!(inst.section_count() > 0);
    validate_all_structures(&inst);
}

#[test]
fn bzip2_file_extraction_nonsolid() {
    let inst = parse_fixture("bzip2_nonsolid.exe");
    let mut count = 0;
    for file in inst.files() {
        let file = file.unwrap();
        assert!(
            !file.data().is_empty(),
            "bzip2 non-solid file should have data"
        );
        let content = file.decompress().unwrap();
        assert!(!content.is_empty());
        count += 1;
    }
    assert!(count > 0, "should find files");
}

#[test]
fn bzip2_file_extraction_solid() {
    let inst = parse_fixture("bzip2_solid.exe");
    let mut count = 0;
    for file in inst.files() {
        let file = file.unwrap();
        assert!(!file.data().is_empty(), "bzip2 solid file should have data");
        let content = file.decompress().unwrap();
        assert!(!content.is_empty());
        count += 1;
    }
    assert!(count > 0, "should find files");
}

#[test]
fn all_fixtures_produce_consistent_headers() {
    let fixtures = [
        "deflate_nonsolid.exe",
        "deflate_solid.exe",
        "lzma_nonsolid.exe",
        "lzma_solid.exe",
        "bzip2_nonsolid.exe",
        "bzip2_solid.exe",
        "full_featured.exe",
        "ansi_deflate.exe",
    ];
    for name in fixtures {
        let inst = parse_fixture(name);
        // All fixtures should have valid header data.
        assert!(
            inst.header_data().len() >= 68,
            "{name}: header too short ({})",
            inst.header_data().len()
        );
        // All should have at least one section.
        assert!(inst.section_count() > 0, "{name}: no sections");
        // All should have entries.
        assert!(inst.entry_count() > 0, "{name}: no entries");
        // All structures should parse without errors.
        validate_all_structures(&inst);
    }
}

#[test]
fn all_fixtures_extract_files() {
    let fixtures = [
        "deflate_nonsolid.exe",
        "deflate_solid.exe",
        "lzma_nonsolid.exe",
        "lzma_solid.exe",
        "bzip2_nonsolid.exe",
        "bzip2_solid.exe",
        "full_featured.exe",
    ];
    for name in fixtures {
        let inst = parse_fixture(name);
        let mut file_count = 0;
        for file in inst.files() {
            let file = file.unwrap();
            let content = file.decompress().unwrap();
            assert!(!content.is_empty(), "{name}: decompressed file is empty");
            file_count += 1;
        }
        assert!(file_count > 0, "{name}: no files extracted");
    }
}

#[test]
fn extracted_file_content_is_valid() {
    // Our fixtures contain payload.txt with known content.
    let inst = parse_fixture("deflate_nonsolid.exe");
    for file in inst.files() {
        let file = file.unwrap();
        let name = file.name().unwrap().to_string();
        if name.contains("payload.txt") {
            let content = file.decompress().unwrap();
            let text = String::from_utf8_lossy(&content);
            assert!(
                text.contains("test payload"),
                "payload.txt should contain 'test payload', got: {text}"
            );
            return;
        }
    }
    panic!("payload.txt not found in fixture");
}

#[test]
fn solid_and_nonsolid_produce_same_content() {
    // Compare extracted payload.txt between solid and non-solid deflate.
    let nonsolid = parse_fixture("deflate_nonsolid.exe");
    let solid = parse_fixture("deflate_solid.exe");

    let get_payload = |inst: &nsis::NsisInstaller<'_>| -> Vec<u8> {
        for file in inst.files() {
            let file = file.unwrap();
            let name = file.name().unwrap().to_string();
            if name.contains("payload.txt") {
                return file.decompress().unwrap();
            }
        }
        panic!("payload.txt not found");
    };

    let ns_content = get_payload(&nonsolid);
    let s_content = get_payload(&solid);
    assert_eq!(
        ns_content, s_content,
        "solid and non-solid should produce identical payload content"
    );
}

#[test]
fn all_compression_methods_produce_same_content() {
    // Compare payload.txt across all 6 compression variants.
    let fixtures = [
        "deflate_nonsolid.exe",
        "deflate_solid.exe",
        "lzma_nonsolid.exe",
        "lzma_solid.exe",
        "bzip2_nonsolid.exe",
        "bzip2_solid.exe",
    ];

    let mut reference: Option<Vec<u8>> = None;
    for name in fixtures {
        let inst = parse_fixture(name);
        for file in inst.files() {
            let file = file.unwrap();
            let fname = file.name().unwrap().to_string();
            if fname.contains("payload.txt") {
                let content = file.decompress().unwrap();
                if let Some(ref expected) = reference {
                    assert_eq!(
                        &content, expected,
                        "{name}: payload.txt differs from deflate_nonsolid"
                    );
                } else {
                    reference = Some(content);
                }
                break;
            }
        }
    }
    assert!(reference.is_some(), "no payload.txt found in any fixture");
}