relay_event_schema/protocol/
debugmeta.rs

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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;

use enumset::EnumSet;
use relay_protocol::{
    Annotated, Array, Empty, Error, FromValue, IntoValue, Meta, Object, SkipSerialization, Value,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::processor::{ProcessValue, ProcessingResult, ProcessingState, Processor, ValueType};
use crate::protocol::Addr;

/// A type for strings that are generally paths, might contain system user names, but still cannot
/// be stripped liberally because it would break processing for certain platforms.
///
/// Those strings get special treatment in our PII processor to avoid stripping the basename.
#[derive(Debug, FromValue, IntoValue, Empty, Clone, PartialEq, Deserialize, Serialize)]
pub struct NativeImagePath(pub String);

impl NativeImagePath {
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl<T: Into<String>> From<T> for NativeImagePath {
    fn from(value: T) -> NativeImagePath {
        NativeImagePath(value.into())
    }
}

impl ProcessValue for NativeImagePath {
    #[inline]
    fn value_type(&self) -> EnumSet<ValueType> {
        // Explicit decision not to expose NativeImagePath as valuetype, as people should not be
        // able to address processing internals.
        //
        // Also decided against exposing a $filepath ("things that may contain filenames") because
        // ruletypes/regexes are better suited for this, and in the case of $frame.package (where
        // it depends on platform) it's really not that useful.
        EnumSet::only(ValueType::String)
    }

    #[inline]
    fn process_value<P>(
        &mut self,
        meta: &mut Meta,
        processor: &mut P,
        state: &ProcessingState<'_>,
    ) -> ProcessingResult
    where
        P: Processor,
    {
        processor.process_native_image_path(self, meta, state)
    }

    fn process_child_values<P>(
        &mut self,
        _processor: &mut P,
        _state: &ProcessingState<'_>,
    ) -> ProcessingResult
    where
        P: Processor,
    {
        Ok(())
    }
}

/// Holds information about the system SDK.
///
/// This is relevant for iOS and other platforms that have a system
/// SDK.  Not to be confused with the client SDK.
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct SystemSdkInfo {
    /// The internal name of the SDK.
    pub sdk_name: Annotated<String>,

    /// The major version of the SDK as integer or 0.
    pub version_major: Annotated<u64>,

    /// The minor version of the SDK as integer or 0.
    pub version_minor: Annotated<u64>,

    /// The patch version of the SDK as integer or 0.
    pub version_patchlevel: Annotated<u64>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties)]
    pub other: Object<Value>,
}

/// Legacy apple debug images (MachO).
///
/// This was also used for non-apple platforms with similar debug setups.
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct AppleDebugImage {
    /// Path and name of the debug image (required).
    #[metastructure(required = true)]
    pub name: Annotated<String>,

    /// CPU architecture target.
    pub arch: Annotated<String>,

    /// MachO CPU type identifier.
    pub cpu_type: Annotated<u64>,

    /// MachO CPU subtype identifier.
    pub cpu_subtype: Annotated<u64>,

    /// Starting memory address of the image (required).
    #[metastructure(required = true)]
    pub image_addr: Annotated<Addr>,

    /// Size of the image in bytes (required).
    #[metastructure(required = true)]
    pub image_size: Annotated<u64>,

    /// Loading address in virtual memory.
    pub image_vmaddr: Annotated<Addr>,

    /// The unique UUID of the image.
    #[metastructure(required = true)]
    pub uuid: Annotated<Uuid>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties)]
    pub other: Object<Value>,
}

macro_rules! impl_traits {
    ($type:ident, $inner:path, $expectation:literal) => {
        impl Empty for $type {
            #[inline]
            fn is_empty(&self) -> bool {
                self.is_nil()
            }
        }

        impl FromValue for $type {
            fn from_value(value: Annotated<Value>) -> Annotated<Self> {
                match value {
                    Annotated(Some(Value::String(value)), mut meta) => match value.parse() {
                        Ok(value) => Annotated(Some(value), meta),
                        Err(err) => {
                            meta.add_error(Error::invalid(err));
                            meta.set_original_value(Some(value));
                            Annotated(None, meta)
                        }
                    },
                    Annotated(Some(value), mut meta) => {
                        meta.add_error(Error::expected($expectation));
                        meta.set_original_value(Some(value));
                        Annotated(None, meta)
                    }
                    Annotated(None, meta) => Annotated(None, meta),
                }
            }
        }

        impl IntoValue for $type {
            fn into_value(self) -> Value {
                Value::String(self.to_string())
            }

            fn serialize_payload<S>(
                &self,
                s: S,
                _behavior: SkipSerialization,
            ) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serde::Serialize::serialize(self, s)
            }
        }

        impl ProcessValue for $type {}

        impl fmt::Display for $type {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt(f)
            }
        }

        impl FromStr for $type {
            type Err = <$inner as FromStr>::Err;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                FromStr::from_str(s).map($type)
            }
        }

        impl Deref for $type {
            type Target = $inner;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl DerefMut for $type {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.0
            }
        }
    };
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DebugId(pub debugid::DebugId);

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CodeId(pub debugid::CodeId);

impl_traits!(CodeId, debugid::CodeId, "a code identifier");
impl_traits!(DebugId, debugid::DebugId, "a debug identifier");

impl<T> From<T> for DebugId
where
    debugid::DebugId: From<T>,
{
    fn from(t: T) -> Self {
        DebugId(t.into())
    }
}

impl<T> From<T> for CodeId
where
    debugid::CodeId: From<T>,
{
    fn from(t: T) -> Self {
        CodeId(t.into())
    }
}

/// A generic (new-style) native platform debug information file.
///
/// The `type` key must be one of:
///
/// - `macho`
/// - `elf`: ELF images are used on Linux platforms. Their structure is identical to other native images.
/// - `pe`
///
/// Examples:
///
/// ```json
/// {
///   "type": "elf",
///   "code_id": "68220ae2c65d65c1b6aaa12fa6765a6ec2f5f434",
///   "code_file": "/lib/x86_64-linux-gnu/libgcc_s.so.1",
///   "debug_id": "e20a2268-5dc6-c165-b6aa-a12fa6765a6e",
///   "image_addr": "0x7f5140527000",
///   "image_size": 90112,
///   "image_vmaddr": "0x40000",
///   "arch": "x86_64"
/// }
/// ```
///
/// ```json
/// {
///   "type": "pe",
///   "code_id": "57898e12145000",
///   "code_file": "C:\\Windows\\System32\\dbghelp.dll",
///   "debug_id": "9c2a902b-6fdf-40ad-8308-588a41d572a0-1",
///   "debug_file": "dbghelp.pdb",
///   "image_addr": "0x70850000",
///   "image_size": "1331200",
///   "image_vmaddr": "0x40000",
///   "arch": "x86"
/// }
/// ```
///
/// ```json
/// {
///   "type": "macho",
///   "debug_id": "84a04d24-0e60-3810-a8c0-90a65e2df61a",
///   "debug_file": "libDiagnosticMessagesClient.dylib",
///   "code_file": "/usr/lib/libDiagnosticMessagesClient.dylib",
///   "image_addr": "0x7fffe668e000",
///   "image_size": 8192,
///   "image_vmaddr": "0x40000",
///   "arch": "x86_64",
/// }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct NativeDebugImage {
    /// Optional identifier of the code file.
    ///
    /// - `elf`: If the program was compiled with a relatively recent compiler, this should be the hex representation of the `NT_GNU_BUILD_ID` program header (type `PT_NOTE`), or the value of the `.note.gnu.build-id` note section (type `SHT_NOTE`). Otherwise, leave this value empty.
    ///
    ///   Certain symbol servers use the code identifier to locate debug information for ELF images, in which case this field should be included if possible.
    ///
    /// - `pe`: Identifier of the executable or DLL. It contains the values of the `time_date_stamp` from the COFF header and `size_of_image` from the optional header formatted together into a hex string using `%08x%X` (note that the second value is not padded):
    ///
    ///   ```text
    ///   time_date_stamp: 0x5ab38077
    ///   size_of_image:           0x9000
    ///   code_id:           5ab380779000
    ///   ```
    ///
    ///   The code identifier should be provided to allow server-side stack walking of binary crash reports, such as Minidumps.
    ///
    ///
    /// - `macho`: Identifier of the dynamic library or executable. It is the value of the `LC_UUID` load command in the Mach header, formatted as UUID. Can be empty for Mach images, as it is equivalent to the debug identifier.
    pub code_id: Annotated<CodeId>,

    /// Path and name of the image file (required).
    ///
    /// The absolute path to the dynamic library or executable. This helps to locate the file if it is missing on Sentry.
    ///
    /// - `pe`: The code file should be provided to allow server-side stack walking of binary crash reports, such as Minidumps.
    #[metastructure(required = true, legacy_alias = "name")]
    #[metastructure(pii = "maybe")]
    pub code_file: Annotated<NativeImagePath>,

    /// Unique debug identifier of the image.
    ///
    /// - `elf`: Debug identifier of the dynamic library or executable. If a code identifier is available, the debug identifier is the little-endian UUID representation of the first 16-bytes of that
    ///   identifier. Spaces are inserted for readability, note the byte order of the first fields:
    ///
    ///   ```text
    ///   code id:  f1c3bcc0 2798 65fe 3058 404b2831d9e6 4135386c
    ///   debug id: c0bcc3f1-9827-fe65-3058-404b2831d9e6
    ///   ```
    ///
    ///   If no code id is available, the debug id should be computed by XORing the first 4096 bytes of the `.text` section in 16-byte chunks, and representing it as a little-endian UUID (again swapping the byte order).
    ///
    /// - `pe`: `signature` and `age` of the PDB file. Both values can be read from the CodeView PDB70 debug information header in the PE. The value should be represented as little-endian UUID, with the age appended at the end. Note that the byte order of the UUID fields must be swapped (spaces inserted for readability):
    ///
    ///   ```text
    ///   signature: f1c3bcc0 2798 65fe 3058 404b2831d9e6
    ///   age:                                            1
    ///   debug_id:  c0bcc3f1-9827-fe65-3058-404b2831d9e6-1
    ///   ```
    ///
    /// - `macho`: Identifier of the dynamic library or executable. It is the value of the `LC_UUID` load command in the Mach header, formatted as UUID.
    #[metastructure(required = true, legacy_alias = "id")]
    pub debug_id: Annotated<DebugId>,

    /// Path and name of the debug companion file.
    ///
    /// - `elf`: Name or absolute path to the file containing stripped debug information for this image. This value might be _required_ to retrieve debug files from certain symbol servers.
    ///
    /// - `pe`: Name of the PDB file containing debug information for this image. This value is often required to retrieve debug files from specific symbol servers.
    ///
    /// - `macho`: Name or absolute path to the dSYM file containing debug information for this image. This value might be required to retrieve debug files from certain symbol servers.
    #[metastructure(pii = "maybe")]
    pub debug_file: Annotated<NativeImagePath>,

    /// The optional checksum of the debug companion file.
    ///
    /// - `pe_dotnet`: This is the hash algorithm and hex-formatted checksum of the associated PDB file.
    ///   This should have the format `$algorithm:$hash`, for example `SHA256:aabbccddeeff...`.
    ///
    ///   See: <https://github.com/dotnet/runtime/blob/main/docs/design/specs/PE-COFF.md#pdb-checksum-debug-directory-entry-type-19>
    pub debug_checksum: Annotated<String>,

    /// CPU architecture target.
    ///
    /// Architecture of the module. If missing, this will be backfilled by Sentry.
    pub arch: Annotated<String>,

    /// Starting memory address of the image (required).
    ///
    /// Memory address, at which the image is mounted in the virtual address space of the process. Should be a string in hex representation prefixed with `"0x"`.
    pub image_addr: Annotated<Addr>,

    /// Size of the image in bytes (required).
    ///
    /// The size of the image in virtual memory. If missing, Sentry will assume that the image spans up to the next image, which might lead to invalid stack traces.
    pub image_size: Annotated<u64>,

    /// Loading address in virtual memory.
    ///
    /// Preferred load address of the image in virtual memory, as declared in the headers of the
    /// image. When loading an image, the operating system may still choose to place it at a
    /// different address.
    ///
    /// Symbols and addresses in the native image are always relative to the start of the image and do not consider the preferred load address. It is merely a hint to the loader.
    ///
    /// - `elf`/`macho`: If this value is non-zero, all symbols and addresses declared in the native image start at this address, rather than 0. By contrast, Sentry deals with addresses relative to the start of the image. For example, with `image_vmaddr: 0x40000`, a symbol located at `0x401000` has a relative address of `0x1000`.
    ///
    ///   Relative addresses used in Apple Crash Reports and `addr2line` are usually in the preferred address space, and not relative address space.
    pub image_vmaddr: Annotated<Addr>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties)]
    pub other: Object<Value>,
}

/// A debug image pointing to a source map.
///
/// Examples:
///
/// ```json
/// {
///   "type": "sourcemap",
///   "code_file": "https://example.com/static/js/main.min.js",
///   "debug_id": "395835f4-03e0-4436-80d3-136f0749a893"
/// }
/// ```
///
/// **Note:** Stack frames and the correlating entries in the debug image here
/// for `code_file`/`abs_path` are not PII stripped as they need to line up
/// perfectly for source map processing.
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct SourceMapDebugImage {
    /// Path and name of the image file as URL. (required).
    ///
    /// The absolute path to the minified JavaScript file.  This helps to correlate the file to the stack trace.
    #[metastructure(required = true)]
    pub code_file: Annotated<String>,

    /// Unique debug identifier of the source map.
    #[metastructure(required = true)]
    pub debug_id: Annotated<DebugId>,

    /// Path and name of the associated source map.
    #[metastructure(pii = "maybe")]
    pub debug_file: Annotated<String>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties)]
    pub other: Object<Value>,
}

/// A debug image consisting of source files for a JVM based language.
///
/// Examples:
///
/// ```json
/// {
///   "type": "jvm",
///   "debug_id": "395835f4-03e0-4436-80d3-136f0749a893"
/// }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct JvmDebugImage {
    /// Unique debug identifier of the bundle.
    #[metastructure(required = true)]
    pub debug_id: Annotated<DebugId>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties)]
    pub other: Object<Value>,
}

/// Proguard mapping file.
///
/// Proguard images refer to `mapping.txt` files generated when Proguard obfuscates function names. The Java SDK integrations assign this file a unique identifier, which has to be included in the list of images.
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct ProguardDebugImage {
    /// UUID computed from the file contents, assigned by the Java SDK.
    #[metastructure(required = true)]
    pub uuid: Annotated<Uuid>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties)]
    pub other: Object<Value>,
}

/// A debug information file (debug image).
#[derive(Clone, Debug, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
#[metastructure(process_func = "process_debug_image")]
pub enum DebugImage {
    /// Legacy apple debug images (MachO).
    Apple(Box<AppleDebugImage>),
    /// A generic (new-style) native platform debug information file.
    Symbolic(Box<NativeDebugImage>),
    /// MachO (macOS and iOS) debug image.
    MachO(Box<NativeDebugImage>),
    /// ELF (Linux) debug image.
    Elf(Box<NativeDebugImage>),
    /// PE (Windows) debug image.
    Pe(Box<NativeDebugImage>),
    /// .NET PE debug image with associated Portable PDB debug companion.
    #[metastructure(tag = "pe_dotnet")]
    PeDotnet(Box<NativeDebugImage>),
    /// A reference to a proguard debug file.
    Proguard(Box<ProguardDebugImage>),
    /// WASM debug image.
    Wasm(Box<NativeDebugImage>),
    /// Source map debug image.
    SourceMap(Box<SourceMapDebugImage>),
    /// JVM based debug image.
    Jvm(Box<JvmDebugImage>),
    /// A debug image that is unknown to this protocol specification.
    #[metastructure(fallback_variant)]
    Other(Object<Value>),
}

/// Debugging and processing meta information.
///
/// The debug meta interface carries debug information for processing errors and crash reports.
/// Sentry amends the information in this interface.
///
/// Example (look at field types to see more detail):
///
/// ```json
/// {
///   "debug_meta": {
///     "images": [],
///     "sdk_info": {
///       "sdk_name": "iOS",
///       "version_major": 10,
///       "version_minor": 3,
///       "version_patchlevel": 0
///     }
///   }
/// }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
#[metastructure(process_func = "process_debug_meta")]
pub struct DebugMeta {
    /// Information about the system SDK (e.g. iOS SDK).
    #[metastructure(field = "sdk_info")]
    #[metastructure(skip_serialization = "empty")]
    pub system_sdk: Annotated<SystemSdkInfo>,

    /// List of debug information files (debug images).
    #[metastructure(skip_serialization = "empty")]
    pub images: Annotated<Array<DebugImage>>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties)]
    pub other: Object<Value>,
}

#[cfg(test)]
mod tests {
    use relay_protocol::Map;
    use similar_asserts::assert_eq;

    use super::*;

    #[test]
    fn test_debug_image_proguard_roundtrip() {
        let json = r#"{
  "uuid": "395835f4-03e0-4436-80d3-136f0749a893",
  "other": "value",
  "type": "proguard"
}"#;
        let image = Annotated::new(DebugImage::Proguard(Box::new(ProguardDebugImage {
            uuid: Annotated::new("395835f4-03e0-4436-80d3-136f0749a893".parse().unwrap()),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_jvm_based_roundtrip() {
        let json = r#"{
  "debug_id": "395835f4-03e0-4436-80d3-136f0749a893",
  "other": "value",
  "type": "jvm"
}"#;
        let image = Annotated::new(DebugImage::Jvm(Box::new(JvmDebugImage {
            debug_id: Annotated::new("395835f4-03e0-4436-80d3-136f0749a893".parse().unwrap()),
            other: {
                let mut map = Map::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_apple_roundtrip() {
        let json = r#"{
  "name": "CoreFoundation",
  "arch": "arm64",
  "cpu_type": 1233,
  "cpu_subtype": 3,
  "image_addr": "0x0",
  "image_size": 4096,
  "image_vmaddr": "0x8000",
  "uuid": "494f3aea-88fa-4296-9644-fa8ef5d139b6",
  "other": "value",
  "type": "apple"
}"#;

        let image = Annotated::new(DebugImage::Apple(Box::new(AppleDebugImage {
            name: Annotated::new("CoreFoundation".to_string()),
            arch: Annotated::new("arm64".to_string()),
            cpu_type: Annotated::new(1233),
            cpu_subtype: Annotated::new(3),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            image_vmaddr: Annotated::new(Addr(32768)),
            uuid: Annotated::new("494f3aea-88fa-4296-9644-fa8ef5d139b6".parse().unwrap()),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_apple_default_values() {
        let json = r#"{
  "name": "CoreFoundation",
  "image_addr": "0x0",
  "image_size": 4096,
  "uuid": "494f3aea-88fa-4296-9644-fa8ef5d139b6",
  "type": "apple"
}"#;

        let image = Annotated::new(DebugImage::Apple(Box::new(AppleDebugImage {
            name: Annotated::new("CoreFoundation".to_string()),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            uuid: Annotated::new("494f3aea-88fa-4296-9644-fa8ef5d139b6".parse().unwrap()),
            ..Default::default()
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_symbolic_roundtrip() {
        let json = r#"{
  "code_id": "59b0d8f3183000",
  "code_file": "C:\\Windows\\System32\\ntdll.dll",
  "debug_id": "971f98e5-ce60-41ff-b2d7-235bbeb34578-1",
  "debug_file": "wntdll.pdb",
  "arch": "arm64",
  "image_addr": "0x0",
  "image_size": 4096,
  "image_vmaddr": "0x8000",
  "other": "value",
  "type": "symbolic"
}"#;

        let image = Annotated::new(DebugImage::Symbolic(Box::new(NativeDebugImage {
            code_id: Annotated::new("59b0d8f3183000".parse().unwrap()),
            code_file: Annotated::new("C:\\Windows\\System32\\ntdll.dll".into()),
            debug_id: Annotated::new("971f98e5-ce60-41ff-b2d7-235bbeb34578-1".parse().unwrap()),
            debug_file: Annotated::new("wntdll.pdb".into()),
            debug_checksum: Annotated::empty(),
            arch: Annotated::new("arm64".to_string()),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            image_vmaddr: Annotated::new(Addr(32768)),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_symbolic_legacy() {
        let json = r#"{
  "name": "CoreFoundation",
  "arch": "arm64",
  "image_addr": "0x0",
  "image_size": 4096,
  "image_vmaddr": "0x8000",
  "id": "494f3aea-88fa-4296-9644-fa8ef5d139b6-1234",
  "other": "value",
  "type": "symbolic"
}"#;

        let image = Annotated::new(DebugImage::Symbolic(Box::new(NativeDebugImage {
            code_id: Annotated::empty(),
            code_file: Annotated::new("CoreFoundation".into()),
            debug_id: Annotated::new("494f3aea-88fa-4296-9644-fa8ef5d139b6-1234".parse().unwrap()),
            debug_file: Annotated::empty(),
            debug_checksum: Annotated::empty(),
            arch: Annotated::new("arm64".to_string()),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            image_vmaddr: Annotated::new(Addr(32768)),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
    }

    #[test]
    fn test_debug_image_symbolic_default_values() {
        let json = r#"{
  "code_file": "CoreFoundation",
  "debug_id": "494f3aea-88fa-4296-9644-fa8ef5d139b6-1234",
  "image_addr": "0x0",
  "image_size": 4096,
  "type": "symbolic"
}"#;

        let image = Annotated::new(DebugImage::Symbolic(Box::new(NativeDebugImage {
            code_file: Annotated::new("CoreFoundation".into()),
            debug_id: Annotated::new(
                "494f3aea-88fa-4296-9644-fa8ef5d139b6-1234"
                    .parse::<DebugId>()
                    .unwrap(),
            ),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            ..Default::default()
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_elf_roundtrip() {
        let json = r#"{
  "code_id": "f1c3bcc0279865fe3058404b2831d9e64135386c",
  "code_file": "crash",
  "debug_id": "c0bcc3f1-9827-fe65-3058-404b2831d9e6",
  "arch": "arm64",
  "image_addr": "0x0",
  "image_size": 4096,
  "image_vmaddr": "0x8000",
  "other": "value",
  "type": "elf"
}"#;

        let image = Annotated::new(DebugImage::Elf(Box::new(NativeDebugImage {
            code_id: Annotated::new("f1c3bcc0279865fe3058404b2831d9e64135386c".parse().unwrap()),
            code_file: Annotated::new("crash".into()),
            debug_id: Annotated::new("c0bcc3f1-9827-fe65-3058-404b2831d9e6".parse().unwrap()),
            debug_file: Annotated::empty(),
            debug_checksum: Annotated::empty(),
            arch: Annotated::new("arm64".to_string()),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            image_vmaddr: Annotated::new(Addr(32768)),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_pe_dotnet_roundtrip() {
        let json = r#"{
  "debug_id": "4e2ca887-825e-46f3-968f-25b41ae1b5f3-cc3f6d9e",
  "debug_file": "TimeZoneConverter.pdb",
  "debug_checksum": "SHA256:87a82c4e5e82f386968f25b41ae1b5f3cc3f6d9e79cfb4464f8240400fc47dcd79",
  "type": "pe_dotnet"
}"#;

        let image = Annotated::new(DebugImage::PeDotnet(Box::new(NativeDebugImage {
            debug_id: Annotated::new(
                "4e2ca887-825e-46f3-968f-25b41ae1b5f3-cc3f6d9e"
                    .parse()
                    .unwrap(),
            ),
            debug_file: Annotated::new("TimeZoneConverter.pdb".into()),
            debug_checksum: Annotated::new(
                "SHA256:87a82c4e5e82f386968f25b41ae1b5f3cc3f6d9e79cfb4464f8240400fc47dcd79".into(),
            ),
            ..Default::default()
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_macho_roundtrip() {
        let json = r#"{
  "code_id": "67E9247C-814E-392B-A027-DBDE6748FCBF",
  "code_file": "crash",
  "debug_id": "67e9247c-814e-392b-a027-dbde6748fcbf",
  "arch": "arm64",
  "image_addr": "0x0",
  "image_size": 4096,
  "image_vmaddr": "0x8000",
  "other": "value",
  "type": "macho"
}"#;

        let image = Annotated::new(DebugImage::MachO(Box::new(NativeDebugImage {
            code_id: Annotated::new("67E9247C-814E-392B-A027-DBDE6748FCBF".parse().unwrap()),
            code_file: Annotated::new("crash".into()),
            debug_id: Annotated::new("67e9247c-814e-392b-a027-dbde6748fcbf".parse().unwrap()),
            debug_file: Annotated::empty(),
            debug_checksum: Annotated::empty(),
            arch: Annotated::new("arm64".to_string()),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            image_vmaddr: Annotated::new(Addr(32768)),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
    }

    #[test]
    fn test_debug_image_pe_roundtrip() {
        let json = r#"{
  "code_id": "59b0d8f3183000",
  "code_file": "C:\\Windows\\System32\\ntdll.dll",
  "debug_id": "971f98e5-ce60-41ff-b2d7-235bbeb34578-1",
  "debug_file": "wntdll.pdb",
  "arch": "arm64",
  "image_addr": "0x0",
  "image_size": 4096,
  "image_vmaddr": "0x8000",
  "other": "value",
  "type": "pe"
}"#;

        let image = Annotated::new(DebugImage::Pe(Box::new(NativeDebugImage {
            code_id: Annotated::new("59b0d8f3183000".parse().unwrap()),
            code_file: Annotated::new("C:\\Windows\\System32\\ntdll.dll".into()),
            debug_id: Annotated::new("971f98e5-ce60-41ff-b2d7-235bbeb34578-1".parse().unwrap()),
            debug_file: Annotated::new("wntdll.pdb".into()),
            debug_checksum: Annotated::empty(),
            arch: Annotated::new("arm64".to_string()),
            image_addr: Annotated::new(Addr(0)),
            image_size: Annotated::new(4096),
            image_vmaddr: Annotated::new(Addr(32768)),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_source_map_image_roundtrip() {
        let json = r#"{
  "code_file": "https://mycdn.invalid/foo.js.min",
  "debug_id": "971f98e5-ce60-41ff-b2d7-235bbeb34578",
  "debug_file": "https://mycdn.invalid/foo.js.map",
  "other": "value",
  "type": "sourcemap"
}"#;

        let image = Annotated::new(DebugImage::SourceMap(Box::new(SourceMapDebugImage {
            code_file: Annotated::new("https://mycdn.invalid/foo.js.min".into()),
            debug_file: Annotated::new("https://mycdn.invalid/foo.js.map".into()),
            debug_id: Annotated::new("971f98e5-ce60-41ff-b2d7-235bbeb34578".parse().unwrap()),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        })));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_image_other_roundtrip() {
        let json = r#"{"other":"value","type":"mytype"}"#;
        let image = Annotated::new(DebugImage::Other({
            let mut map = Map::new();
            map.insert(
                "type".to_string(),
                Annotated::new(Value::String("mytype".to_string())),
            );
            map.insert(
                "other".to_string(),
                Annotated::new(Value::String("value".to_string())),
            );
            map
        }));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json().unwrap());
    }

    #[test]
    fn test_debug_image_untagged_roundtrip() {
        let json = r#"{"other":"value"}"#;
        let image = Annotated::new(DebugImage::Other({
            let mut map = Map::new();
            map.insert(
                "other".to_string(),
                Annotated::new(Value::String("value".to_string())),
            );
            map
        }));

        assert_eq!(image, Annotated::from_json(json).unwrap());
        assert_eq!(json, image.to_json().unwrap());
    }

    #[test]
    fn test_debug_meta_roundtrip() {
        // NOTE: images are tested separately
        let json = r#"{
  "sdk_info": {
    "sdk_name": "iOS",
    "version_major": 10,
    "version_minor": 3,
    "version_patchlevel": 0,
    "other": "value"
  },
  "other": "value"
}"#;
        let meta = Annotated::new(DebugMeta {
            system_sdk: Annotated::new(SystemSdkInfo {
                sdk_name: Annotated::new("iOS".to_string()),
                version_major: Annotated::new(10),
                version_minor: Annotated::new(3),
                version_patchlevel: Annotated::new(0),
                other: {
                    let mut map = Map::new();
                    map.insert(
                        "other".to_string(),
                        Annotated::new(Value::String("value".to_string())),
                    );
                    map
                },
            }),
            other: {
                let mut map = Map::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
            ..Default::default()
        });

        assert_eq!(meta, Annotated::from_json(json).unwrap());
        assert_eq!(json, meta.to_json_pretty().unwrap());
    }

    #[test]
    fn test_debug_meta_default_values() {
        let json = "{}";
        let meta = Annotated::new(DebugMeta::default());

        assert_eq!(meta, Annotated::from_json(json).unwrap());
        assert_eq!(json, meta.to_json_pretty().unwrap());
    }
}