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
use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};

use crate::category::{
    Category, CategoryHandle, CategoryPairHandle, SerializableSubcategoryColumn, Subcategory,
};
use crate::fast_hash_map::FastHashMap;
use crate::frame::FrameFlags;
use crate::func_table::{FuncIndex, FuncTable};
use crate::global_lib_table::{GlobalLibIndex, GlobalLibTable};
use crate::native_symbols::{NativeSymbolIndex, NativeSymbols};
use crate::resource_table::ResourceTable;
use crate::serialization_helpers::SerializableSingleValueColumn;
use crate::thread_string_table::{ThreadInternalStringIndex, ThreadStringTable};

#[derive(Debug, Clone, Default)]
pub struct FrameTable {
    addresses: Vec<Option<u32>>,
    categories: Vec<CategoryHandle>,
    subcategories: Vec<Subcategory>,
    funcs: Vec<FuncIndex>,
    native_symbols: Vec<Option<NativeSymbolIndex>>,
    internal_frame_to_frame_index: FastHashMap<InternalFrame, usize>,
}

impl FrameTable {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn index_for_frame(
        &mut self,
        string_table: &mut ThreadStringTable,
        resource_table: &mut ResourceTable,
        func_table: &mut FuncTable,
        native_symbol_table: &mut NativeSymbols,
        global_libs: &GlobalLibTable,
        frame: InternalFrame,
    ) -> usize {
        let addresses = &mut self.addresses;
        let funcs = &mut self.funcs;
        let native_symbols = &mut self.native_symbols;
        let categories = &mut self.categories;
        let subcategories = &mut self.subcategories;
        *self
            .internal_frame_to_frame_index
            .entry(frame.clone())
            .or_insert_with(|| {
                let frame_index = addresses.len();
                let (address, location_string_index, native_symbol, resource) = match frame.location
                {
                    InternalFrameLocation::UnknownAddress(address) => {
                        let location_string = format!("0x{address:x}");
                        let s = string_table.index_for_string(&location_string);
                        (None, s, None, None)
                    }
                    InternalFrameLocation::AddressInLib(address, lib_index) => {
                        let res =
                            resource_table.resource_for_lib(lib_index, global_libs, string_table);
                        let lib = global_libs.get_lib(lib_index).unwrap();
                        let native_symbol_and_name =
                            lib.symbol_table.as_deref().and_then(|symbol_table| {
                                let symbol = symbol_table.lookup(address)?;
                                Some(
                                    native_symbol_table.symbol_index_and_string_index_for_symbol(
                                        lib_index,
                                        symbol,
                                        string_table,
                                    ),
                                )
                            });
                        let (native_symbol, s) = match native_symbol_and_name {
                            Some((native_symbol, name_string_index)) => {
                                (Some(native_symbol), name_string_index)
                            }
                            None => {
                                let location_string = format!("0x{address:x}");
                                (None, string_table.index_for_string(&location_string))
                            }
                        };
                        (Some(address), s, native_symbol, Some(res))
                    }
                    InternalFrameLocation::Label(string_index) => (None, string_index, None, None),
                };
                let func_index =
                    func_table.index_for_func(location_string_index, resource, frame.flags);
                let CategoryPairHandle(category, subcategory_index) = frame.category_pair;
                let subcategory = match subcategory_index {
                    Some(index) => Subcategory::Normal(index),
                    None => Subcategory::Other(category),
                };
                addresses.push(address);
                categories.push(category);
                subcategories.push(subcategory);
                funcs.push(func_index);
                native_symbols.push(native_symbol);
                frame_index
            })
    }

    pub fn as_serializable<'a>(&'a self, categories: &'a [Category]) -> impl Serialize + 'a {
        SerializableFrameTable {
            table: self,
            categories,
        }
    }
}

struct SerializableFrameTable<'a> {
    table: &'a FrameTable,
    categories: &'a [Category],
}

impl<'a> Serialize for SerializableFrameTable<'a> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let len = self.table.addresses.len();
        let mut map = serializer.serialize_map(None)?;
        map.serialize_entry("length", &len)?;
        map.serialize_entry(
            "address",
            &SerializableFrameTableAddressColumn(&self.table.addresses),
        )?;
        map.serialize_entry("inlineDepth", &SerializableSingleValueColumn(0u32, len))?;
        map.serialize_entry("category", &self.table.categories)?;
        map.serialize_entry(
            "subcategory",
            &SerializableSubcategoryColumn(&self.table.subcategories, self.categories),
        )?;
        map.serialize_entry("func", &self.table.funcs)?;
        map.serialize_entry("nativeSymbol", &self.table.native_symbols)?;
        map.serialize_entry("innerWindowID", &SerializableSingleValueColumn((), len))?;
        map.serialize_entry("implementation", &SerializableSingleValueColumn((), len))?;
        map.serialize_entry("line", &SerializableSingleValueColumn((), len))?;
        map.serialize_entry("column", &SerializableSingleValueColumn((), len))?;
        map.serialize_entry("optimizations", &SerializableSingleValueColumn((), len))?;
        map.end()
    }
}

struct SerializableFrameTableAddressColumn<'a>(&'a [Option<u32>]);

impl<'a> Serialize for SerializableFrameTableAddressColumn<'a> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
        for address in self.0 {
            match address {
                Some(address) => seq.serialize_element(&address)?,
                None => seq.serialize_element(&-1)?,
            }
        }
        seq.end()
    }
}

#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct InternalFrame {
    pub location: InternalFrameLocation,
    pub category_pair: CategoryPairHandle,
    pub flags: FrameFlags,
}

#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub enum InternalFrameLocation {
    UnknownAddress(u64),
    AddressInLib(u32, GlobalLibIndex),
    Label(ThreadInternalStringIndex),
}