ghidra 0.0.3

Typed Rust bindings for an embedded Ghidra JVM
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use std::{marker::PhantomData, path::Path};

use crate::{
    Address, AddressRange, AnalysisOptions, AnalysisReport, ControlFlowGraph, DataInfo,
    DecompileOptions, DecompileResult, Error, ExportInfo, FunctionControlFlowGraph,
    FunctionDescriptor, FunctionSummary, GhidraRuntime, ImportInfo, InstructionInfo, LaunchOptions,
    MemoryBlockInfo, ProgramCallGraph, ProgramLoadInfo, ProgramLoadOptions, ProgramMetadata,
    ProgramOpenOptions, ReferenceInfo, Result, SourceMapInfo, SymbolInfo,
    bridge::{self, JavaHandle},
};

/// Entry point for project and program operations.
#[derive(Clone)]
pub struct Ghidra {
    runtime: GhidraRuntime,
}

/// Open Ghidra project handle.
pub struct Project {
    runtime: GhidraRuntime,
    handle: Option<JavaHandle>,
}

/// Open Ghidra program handle tied to its owning project.
pub struct Program<'project> {
    runtime: GhidraRuntime,
    project: JavaHandle,
    handle: Option<JavaHandle>,
    _project: PhantomData<&'project Project>,
}

/// Result of opening or importing a program.
pub struct LoadedProgram<'project> {
    pub program: Program<'project>,
    pub info: ProgramLoadInfo,
}

/// Open Ghidra transaction.
///
/// Dropping an uncommitted transaction rolls it back.
pub struct ProgramTransaction<'program> {
    runtime: GhidraRuntime,
    handle: Option<JavaHandle>,
    _program: PhantomData<&'program ()>,
}

/// Reusable decompiler session for a program.
///
/// Reusing one session preserves the program type registry used by decompile
/// results and `program_metadata`.
pub struct Decompiler<'program> {
    runtime: GhidraRuntime,
    handle: Option<JavaHandle>,
    _program: PhantomData<&'program ()>,
}

impl Ghidra {
    /// Starts the embedded Ghidra runtime and attaches the bridge classes.
    pub fn start(options: LaunchOptions) -> Result<Self> {
        Ok(Self {
            runtime: bridge::start(options)?,
        })
    }

    /// Builds a Ghidra API facade from an already-started runtime.
    pub fn with_runtime(runtime: GhidraRuntime) -> Result<Self> {
        bridge::attach_bridge(&runtime)?;
        Ok(Self { runtime })
    }

    /// Returns the embedded runtime used by this facade.
    pub fn runtime(&self) -> &GhidraRuntime {
        &self.runtime
    }

    /// Opens an existing project or creates it at `project_location`.
    pub fn open_or_create_project(
        &self,
        project_location: impl AsRef<Path>,
        project_name: &str,
    ) -> Result<Project> {
        let handle =
            bridge::open_or_create_project(&self.runtime, project_location.as_ref(), project_name)?;
        Ok(Project {
            runtime: self.runtime.clone(),
            handle: Some(handle),
        })
    }
}

impl Project {
    /// Opens an existing root-level program matching the binary file name or imports the binary.
    pub fn open_or_import_program(&self, binary: impl AsRef<Path>) -> Result<Program<'_>> {
        Ok(self
            .open_or_import_program_with_options(ProgramLoadOptions::new(binary.as_ref())?)?
            .program)
    }

    /// Opens a program already present in this project.
    pub fn open_program(&self, options: ProgramOpenOptions) -> Result<Program<'_>> {
        let project = self.handle()?;
        let handle = bridge::open_program(&self.runtime, project, &options.path)?;
        Ok(Program {
            runtime: self.runtime.clone(),
            project,
            handle: Some(handle),
            _project: PhantomData,
        })
    }

    /// Opens or imports a program with explicit loader, path, and monitor options.
    pub fn open_or_import_program_with_options(
        &self,
        options: ProgramLoadOptions,
    ) -> Result<LoadedProgram<'_>> {
        let project = self.handle()?;
        let loaded = bridge::open_or_import_program(&self.runtime, project, &options)?;
        Ok(LoadedProgram {
            program: Program {
                runtime: self.runtime.clone(),
                project,
                handle: Some(loaded.handle),
                _project: PhantomData,
            },
            info: loaded.info,
        })
    }

    /// Closes this project handle.
    pub fn close(mut self) -> Result<()> {
        self.close_inner()
    }

    fn handle(&self) -> Result<JavaHandle> {
        self.handle
            .ok_or_else(|| Error::closed_handle("Ghidra project"))
    }

    fn close_inner(&mut self) -> Result<()> {
        if let Some(handle) = self.handle.take() {
            bridge::close_project(&self.runtime, handle)?;
        }
        Ok(())
    }
}

impl Drop for Project {
    fn drop(&mut self) {
        let _ = self.close_inner();
    }
}

impl Program<'_> {
    /// Returns the program name stored in the Ghidra project.
    pub fn name(&self) -> Result<String> {
        bridge::program_name(&self.runtime, self.handle()?)
    }

    /// Runs default analysis when the program has not already been analyzed.
    pub fn analyze(&self) -> Result<()> {
        self.analyze_with_options(AnalysisOptions::default())?;
        Ok(())
    }

    /// Runs analysis with explicit mode and monitor options.
    pub fn analyze_with_options(&self, options: AnalysisOptions) -> Result<AnalysisReport> {
        bridge::analyze_program(&self.runtime, self.project, self.handle()?, options)
    }

    /// Saves the program back into its Ghidra project.
    pub fn save(&self) -> Result<()> {
        bridge::save_program(&self.runtime, self.project, self.handle()?)
    }

    /// Lists non-external functions in program order.
    pub fn functions(&self) -> Result<Vec<FunctionDescriptor>> {
        let json = bridge::list_functions(&self.runtime, self.handle()?)?;
        parse_json(&json, "failed to parse Ghidra function descriptors")
    }

    /// Parses a Ghidra address string in this program.
    pub fn parse_address(&self, address: &str) -> Result<Address> {
        let json = bridge::parse_address(&self.runtime, self.handle()?, address)?;
        parse_json(&json, format!("failed to parse Ghidra address {address}"))
    }

    /// Returns the function whose entry point is exactly `address`.
    pub fn function_at(&self, address: &Address) -> Result<Option<FunctionDescriptor>> {
        let Some(json) = bridge::function_at(&self.runtime, self.handle()?, address.as_str())?
        else {
            return Ok(None);
        };
        parse_json(
            &json,
            format!("failed to parse Ghidra function descriptor at {address}"),
        )
    }

    /// Returns the function whose body contains `address`.
    pub fn function_containing(&self, address: &Address) -> Result<Option<FunctionDescriptor>> {
        let Some(json) =
            bridge::function_containing(&self.runtime, self.handle()?, address.as_str())?
        else {
            return Ok(None);
        };
        parse_json(
            &json,
            format!("failed to parse Ghidra function descriptor containing {address}"),
        )
    }

    /// Lists program symbols visible through Ghidra's symbol table.
    pub fn symbols(&self) -> Result<Vec<SymbolInfo>> {
        let json = bridge::symbols(&self.runtime, self.handle()?)?;
        parse_json(&json, "failed to parse Ghidra symbols")
    }

    /// Lists symbols located exactly at `address`.
    pub fn symbols_at(&self, address: &Address) -> Result<Vec<SymbolInfo>> {
        let json = bridge::symbols_at(&self.runtime, self.handle()?, address.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra symbols at {address}"),
        )
    }

    /// Finds symbols by name.
    pub fn find_symbols(&self, name: &str, case_sensitive: bool) -> Result<Vec<SymbolInfo>> {
        let json = bridge::find_symbols(&self.runtime, self.handle()?, name, case_sensitive)?;
        parse_json(
            &json,
            format!("failed to parse Ghidra symbols named {name}"),
        )
    }

    /// Lists references originating from `address`.
    pub fn references_from(&self, address: &Address) -> Result<Vec<ReferenceInfo>> {
        let json = bridge::references_from(&self.runtime, self.handle()?, address.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra references from {address}"),
        )
    }

    /// Lists references targeting `address`.
    pub fn references_to(&self, address: &Address) -> Result<Vec<ReferenceInfo>> {
        let json = bridge::references_to(&self.runtime, self.handle()?, address.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra references to {address}"),
        )
    }

    /// Lists memory blocks in the program.
    pub fn memory_blocks(&self) -> Result<Vec<MemoryBlockInfo>> {
        let json = bridge::memory_blocks(&self.runtime, self.handle()?)?;
        parse_json(&json, "failed to parse Ghidra memory blocks")
    }

    /// Builds a basic-block control-flow graph for one function.
    pub fn control_flow_graph(&self, function: &FunctionDescriptor) -> Result<ControlFlowGraph> {
        let json =
            bridge::control_flow_graph(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!(
                "failed to parse Ghidra control-flow graph for {} at {}",
                function.name, function.entry
            ),
        )
    }

    /// Builds basic-block control-flow graphs for functions in input order.
    pub fn control_flow_graphs(
        &self,
        functions: &[FunctionDescriptor],
    ) -> Result<Vec<FunctionControlFlowGraph>> {
        if functions.is_empty() {
            return Ok(Vec::new());
        }
        let addresses = functions
            .iter()
            .map(|function| function.entry.as_str())
            .collect::<Vec<_>>();
        let json = bridge::control_flow_graphs(&self.runtime, self.handle()?, &addresses)?;
        parse_json(&json, "failed to parse Ghidra control-flow graphs")
    }

    /// Returns the linked program call graph.
    pub fn call_graph(&self) -> Result<ProgramCallGraph> {
        let json = bridge::call_graph(&self.runtime, self.handle()?)?;
        parse_json(&json, "failed to parse Ghidra call graph")
    }

    /// Returns program-level symbols, functions, and recursive type metadata.
    pub fn metadata(&self) -> Result<ProgramMetadata> {
        let json = bridge::metadata(&self.runtime, self.handle()?)?;
        parse_json(&json, "failed to parse Ghidra program metadata")
    }

    /// Collects function-local listing, reference, import, export, and source-map data.
    pub fn function_summary(&self, function: &FunctionDescriptor) -> Result<FunctionSummary> {
        let json =
            bridge::function_summary(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!(
                "failed to parse Ghidra function summary for {} at {}",
                function.name, function.entry
            ),
        )
    }

    /// Collects function summaries for functions in input order.
    pub fn function_summaries(
        &self,
        functions: &[FunctionDescriptor],
    ) -> Result<Vec<FunctionSummary>> {
        if functions.is_empty() {
            return Ok(Vec::new());
        }
        let addresses = functions
            .iter()
            .map(|function| function.entry.as_str())
            .collect::<Vec<_>>();
        let json = bridge::function_summaries(&self.runtime, self.handle()?, &addresses)?;
        parse_json(&json, "failed to parse Ghidra function summaries")
    }

    /// Opens a reusable decompiler session for this program.
    pub fn open_decompiler(&self) -> Result<Decompiler<'_>> {
        let handle = bridge::open_decompiler(&self.runtime, self.handle()?)?;
        Ok(Decompiler {
            runtime: self.runtime.clone(),
            handle: Some(handle),
            _program: PhantomData,
        })
    }

    /// Decompiles a function with a timeout in seconds.
    pub fn decompile_function(
        &self,
        function: &FunctionDescriptor,
        timeout: u64,
    ) -> Result<DecompileResult> {
        let decompiler = self.open_decompiler()?;
        decompiler.decompile(function, timeout)
    }

    /// Decompiles a function with explicit decompiler options.
    pub fn decompile_function_with_options(
        &self,
        function: &FunctionDescriptor,
        options: DecompileOptions,
    ) -> Result<DecompileResult> {
        let decompiler = self.open_decompiler()?;
        decompiler.decompile_with_options(function, options)
    }

    /// Returns listing instructions in a function body.
    pub fn instructions_for_function(
        &self,
        function: &FunctionDescriptor,
    ) -> Result<Vec<InstructionInfo>> {
        let json = bridge::instructions_for_function(
            &self.runtime,
            self.handle()?,
            function.entry.as_str(),
        )?;
        parse_json(
            &json,
            format!("failed to parse Ghidra instructions for {}", function.name),
        )
    }

    /// Returns listing instructions in an address range.
    pub fn instructions_in_range(&self, range: &AddressRange) -> Result<Vec<InstructionInfo>> {
        let json = bridge::instructions_in_range(
            &self.runtime,
            self.handle()?,
            range.start.as_str(),
            range.end.as_str(),
        )?;
        parse_json(
            &json,
            format!(
                "failed to parse Ghidra instructions in range {}..{}",
                range.start, range.end
            ),
        )
    }

    /// Returns the instruction located exactly at `address`.
    pub fn instruction_at(&self, address: &Address) -> Result<Option<InstructionInfo>> {
        let Some(json) = bridge::instruction_at(&self.runtime, self.handle()?, address.as_str())?
        else {
            return Ok(None);
        };
        parse_json(
            &json,
            format!("failed to parse Ghidra instruction at {address}"),
        )
    }

    /// Returns the defined data located exactly at `address`.
    pub fn data_at(&self, address: &Address) -> Result<Option<DataInfo>> {
        let Some(json) = bridge::data_at(&self.runtime, self.handle()?, address.as_str())? else {
            return Ok(None);
        };
        parse_json(&json, format!("failed to parse Ghidra data at {address}"))
    }

    /// Returns the defined data item containing `address`.
    pub fn data_containing(&self, address: &Address) -> Result<Option<DataInfo>> {
        let Some(json) = bridge::data_containing(&self.runtime, self.handle()?, address.as_str())?
        else {
            return Ok(None);
        };
        parse_json(
            &json,
            format!("failed to parse Ghidra data containing {address}"),
        )
    }

    /// Returns Ghidra's basic block count for a function.
    pub fn basic_block_count(&self, function: &FunctionDescriptor) -> Result<u64> {
        bridge::basic_block_count(&self.runtime, self.handle()?, function.entry.as_str())
    }

    /// Returns the number of instructions in a function body.
    pub fn instruction_count(&self, function: &FunctionDescriptor) -> Result<u64> {
        bridge::instruction_count(&self.runtime, self.handle()?, function.entry.as_str())
    }

    /// Returns function entry addresses that call `function`.
    pub fn callers(&self, function: &FunctionDescriptor) -> Result<Vec<Address>> {
        let json = bridge::callers(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra callers for {}", function.name),
        )
    }

    /// Returns function entry addresses called by `function`.
    pub fn callees(&self, function: &FunctionDescriptor) -> Result<Vec<Address>> {
        let json = bridge::callees(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra callees for {}", function.name),
        )
    }

    /// Returns strings referenced from a function.
    pub fn strings(&self, function: &FunctionDescriptor) -> Result<Vec<String>> {
        let json = bridge::strings(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra strings for {}", function.name),
        )
    }

    /// Returns scalar constants referenced from a function.
    pub fn constants(&self, function: &FunctionDescriptor) -> Result<Vec<String>> {
        let json = bridge::constants(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra constants for {}", function.name),
        )
    }

    /// Returns data addresses referenced from a function.
    pub fn data_refs(&self, function: &FunctionDescriptor) -> Result<Vec<Address>> {
        let json = bridge::data_refs(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!(
                "failed to parse Ghidra data references for {}",
                function.name
            ),
        )
    }

    /// Returns external symbols referenced from a function.
    pub fn imports(&self, function: &FunctionDescriptor) -> Result<Vec<ImportInfo>> {
        let json = bridge::imports(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra imports for {}", function.name),
        )
    }

    /// Returns exported entry-point names for a function.
    pub fn exports(&self, function: &FunctionDescriptor) -> Result<Vec<ExportInfo>> {
        let json = bridge::exports(&self.runtime, self.handle()?, function.entry.as_str())?;
        parse_json(
            &json,
            format!("failed to parse Ghidra exports for {}", function.name),
        )
    }

    /// Returns best-effort source-file identity for a function.
    pub fn source_map(&self, function: &FunctionDescriptor) -> Result<Option<SourceMapInfo>> {
        let Some(json) =
            bridge::source_map(&self.runtime, self.handle()?, function.entry.as_str())?
        else {
            return Ok(None);
        };
        parse_json(
            &json,
            format!("failed to parse Ghidra source map for {}", function.name),
        )
    }

    /// Starts a program transaction.
    pub fn start_transaction(&self, description: &str) -> Result<ProgramTransaction<'_>> {
        let handle = bridge::start_transaction(&self.runtime, self.handle()?, description)?;
        Ok(ProgramTransaction {
            runtime: self.runtime.clone(),
            handle: Some(handle),
            _program: PhantomData,
        })
    }

    /// Returns the plate comment for a function.
    pub fn function_plate_comment(&self, function: &FunctionDescriptor) -> Result<Option<String>> {
        bridge::function_plate_comment(&self.runtime, self.handle()?, function.entry.as_str())
    }

    /// Closes this program handle.
    pub fn close(mut self) -> Result<()> {
        self.close_inner()
    }

    fn handle(&self) -> Result<JavaHandle> {
        self.handle
            .ok_or_else(|| Error::closed_handle("Ghidra program"))
    }

    fn close_inner(&mut self) -> Result<()> {
        if let Some(handle) = self.handle.take() {
            bridge::close_program(&self.runtime, self.project, handle)?;
        }
        Ok(())
    }
}

impl Drop for Program<'_> {
    fn drop(&mut self) {
        let _ = self.close_inner();
    }
}

impl ProgramTransaction<'_> {
    /// Sets a function plate comment inside this transaction.
    pub fn set_function_plate_comment(
        &self,
        function: &FunctionDescriptor,
        comment: &str,
    ) -> Result<()> {
        bridge::set_function_plate_comment(
            &self.runtime,
            self.handle()?,
            function.entry.as_str(),
            comment,
        )
    }

    /// Commits this transaction.
    pub fn commit(mut self) -> Result<()> {
        self.end(true)
    }

    /// Rolls this transaction back.
    pub fn rollback(mut self) -> Result<()> {
        self.end(false)
    }

    fn handle(&self) -> Result<JavaHandle> {
        self.handle
            .ok_or_else(|| Error::closed_handle("Ghidra transaction"))
    }

    fn end(&mut self, commit: bool) -> Result<()> {
        if let Some(handle) = self.handle {
            bridge::end_transaction(&self.runtime, handle, commit)?;
            self.handle = None;
        }
        Ok(())
    }
}

impl Drop for ProgramTransaction<'_> {
    fn drop(&mut self) {
        let _ = self.end(false);
    }
}

impl Decompiler<'_> {
    /// Returns program metadata using the decompiler session type registry.
    pub fn program_metadata(&self) -> Result<ProgramMetadata> {
        let json = bridge::decompiler_metadata(&self.runtime, self.handle()?)?;
        parse_json(&json, "failed to parse Ghidra decompiler program metadata")
    }

    /// Decompiles a function with a timeout in seconds.
    pub fn decompile(
        &self,
        function: &FunctionDescriptor,
        timeout: u64,
    ) -> Result<DecompileResult> {
        let json = bridge::decompile_function(
            &self.runtime,
            self.handle()?,
            function.entry.as_str(),
            DecompileOptions::new(timeout),
        )?;
        parse_json(
            &json,
            format!(
                "failed to parse Ghidra decompile result for {} at {}",
                function.name, function.entry
            ),
        )
    }

    /// Decompiles a function with explicit decompiler options.
    pub fn decompile_with_options(
        &self,
        function: &FunctionDescriptor,
        options: DecompileOptions,
    ) -> Result<DecompileResult> {
        let json = bridge::decompile_function(
            &self.runtime,
            self.handle()?,
            function.entry.as_str(),
            options,
        )?;
        parse_json(
            &json,
            format!(
                "failed to parse Ghidra decompile result for {} at {}",
                function.name, function.entry
            ),
        )
    }

    /// Closes this decompiler session.
    pub fn close(mut self) -> Result<()> {
        self.close_inner()
    }

    fn handle(&self) -> Result<JavaHandle> {
        self.handle
            .ok_or_else(|| Error::closed_handle("Ghidra decompiler"))
    }

    fn close_inner(&mut self) -> Result<()> {
        if let Some(handle) = self.handle.take() {
            bridge::close_decompiler(&self.runtime, handle)?;
        }
        Ok(())
    }
}

impl Drop for Decompiler<'_> {
    fn drop(&mut self) {
        let _ = self.close_inner();
    }
}

fn parse_json<T, C>(json: &str, context: C) -> Result<T>
where
    T: serde::de::DeserializeOwned,
    C: JsonContext,
{
    serde_json::from_str(json).map_err(|source| context.error(source))
}

trait JsonContext {
    fn error(self, source: serde_json::Error) -> Error;
}

impl JsonContext for &'static str {
    fn error(self, source: serde_json::Error) -> Error {
        Error::json(self, source)
    }
}

impl JsonContext for String {
    fn error(self, source: serde_json::Error) -> Error {
        Error::json(self, source)
    }
}

impl<F> JsonContext for F
where
    F: FnOnce(serde_json::Error) -> Error,
{
    fn error(self, source: serde_json::Error) -> Error {
        self(source)
    }
}