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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![forbid(unsafe_code)]

use anyhow::{format_err, Result};
use move_binary_format::file_format::{CodeOffset, CompiledModule};
use move_core_types::{
    account_address::AccountAddress,
    identifier::{IdentStr, Identifier},
};
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    fs::File,
    io::{BufRead, BufReader, Read, Write},
    path::Path,
};

pub type FunctionCoverage = BTreeMap<u64, u64>;

#[derive(Debug, Serialize, Deserialize)]
pub struct CoverageMap {
    pub exec_maps: BTreeMap<String, ExecCoverageMap>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ModuleCoverageMap {
    pub module_addr: AccountAddress,
    pub module_name: Identifier,
    pub function_maps: BTreeMap<Identifier, FunctionCoverage>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ExecCoverageMap {
    pub exec_id: String,
    pub module_maps: BTreeMap<(AccountAddress, Identifier), ModuleCoverageMap>,
}

#[derive(Debug)]
pub struct ExecCoverageMapWithModules {
    pub module_maps: BTreeMap<(String, AccountAddress, Identifier), ModuleCoverageMap>,
    pub compiled_modules: BTreeMap<String, CompiledModule>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TraceEntry {
    pub module_addr: AccountAddress,
    pub module_name: Identifier,
    pub func_name: Identifier,
    pub func_pc: CodeOffset,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TraceMap {
    pub exec_maps: BTreeMap<String, Vec<TraceEntry>>,
}

impl CoverageMap {
    /// Takes in a file containing a raw VM trace, and returns an updated coverage map.
    pub fn update_coverage_from_trace_file<P: AsRef<Path>>(mut self, filename: P) -> Self {
        let file = File::open(filename).unwrap();
        for line in BufReader::new(file).lines() {
            let line = line.unwrap();
            let mut splits = line.split(',');
            let exec_id = splits.next().unwrap();
            let context = splits.next().unwrap();
            let pc = splits.next().unwrap().parse::<u64>().unwrap();

            let mut context_segs: Vec<_> = context.split("::").collect();
            let is_script = context_segs.len() == 2;
            if !is_script {
                let func_name = Identifier::new(context_segs.pop().unwrap()).unwrap();
                let module_name = Identifier::new(context_segs.pop().unwrap()).unwrap();
                let module_addr =
                    AccountAddress::from_hex_literal(context_segs.pop().unwrap()).unwrap();
                self.insert(exec_id, module_addr, module_name, func_name, pc);
            } else {
                // Don't count scripts (for now)
                assert_eq!(context_segs.pop().unwrap(), "main",);
                assert_eq!(context_segs.pop().unwrap(), "Script",);
            }
        }
        self
    }

    /// Takes in a file containing a raw VM trace, and returns a coverage map.
    pub fn from_trace_file<P: AsRef<Path>>(filename: P) -> Self {
        let empty_module_map = CoverageMap {
            exec_maps: BTreeMap::new(),
        };
        empty_module_map.update_coverage_from_trace_file(filename)
    }

    /// Takes in a file containing a serialized coverage map and returns a coverage map.
    pub fn from_binary_file<P: AsRef<Path>>(filename: P) -> Self {
        let mut bytes = Vec::new();
        File::open(filename)
            .ok()
            .and_then(|mut file| file.read_to_end(&mut bytes).ok())
            .ok_or_else(|| format_err!("Error while reading in coverage map binary"))
            .unwrap();
        bcs::from_bytes(&bytes)
            .map_err(|_| format_err!("Error deserializing into coverage map"))
            .unwrap()
    }

    // add entries in a cascading manner
    pub fn insert(
        &mut self,
        exec_id: &str,
        module_addr: AccountAddress,
        module_name: Identifier,
        func_name: Identifier,
        pc: u64,
    ) {
        let exec_entry = self
            .exec_maps
            .entry(exec_id.to_owned())
            .or_insert_with(|| ExecCoverageMap::new(exec_id.to_owned()));
        exec_entry.insert(module_addr, module_name, func_name, pc);
    }

    pub fn to_unified_exec_map(&self) -> ExecCoverageMap {
        let mut unified_map = ExecCoverageMap::new(String::new());
        for (_, exec_map) in self.exec_maps.iter() {
            for ((module_addr, module_name), module_map) in exec_map.module_maps.iter() {
                for (func_name, func_map) in module_map.function_maps.iter() {
                    for (pc, count) in func_map.iter() {
                        unified_map.insert_multi(
                            *module_addr,
                            module_name.clone(),
                            func_name.clone(),
                            *pc,
                            *count,
                        );
                    }
                }
            }
        }
        unified_map
    }
}

impl ModuleCoverageMap {
    pub fn new(module_addr: AccountAddress, module_name: Identifier) -> Self {
        ModuleCoverageMap {
            module_addr,
            module_name,
            function_maps: BTreeMap::new(),
        }
    }

    pub fn insert_multi(&mut self, func_name: Identifier, pc: u64, count: u64) {
        let func_entry = self
            .function_maps
            .entry(func_name)
            .or_insert_with(FunctionCoverage::new);
        let pc_entry = func_entry.entry(pc).or_insert(0);
        *pc_entry += count;
    }

    pub fn insert(&mut self, func_name: Identifier, pc: u64) {
        self.insert_multi(func_name, pc, 1);
    }

    pub fn merge(&mut self, another: ModuleCoverageMap) {
        for (key, val) in another.function_maps {
            self.function_maps
                .entry(key)
                .or_insert_with(FunctionCoverage::new)
                .extend(val);
        }
    }

    pub fn get_function_coverage(&self, func_name: &IdentStr) -> Option<&FunctionCoverage> {
        self.function_maps.get(func_name)
    }
}

impl ExecCoverageMap {
    pub fn new(exec_id: String) -> Self {
        ExecCoverageMap {
            exec_id,
            module_maps: BTreeMap::new(),
        }
    }

    pub fn insert_multi(
        &mut self,
        module_addr: AccountAddress,
        module_name: Identifier,
        func_name: Identifier,
        pc: u64,
        count: u64,
    ) {
        let module_entry = self
            .module_maps
            .entry((module_addr, module_name.clone()))
            .or_insert_with(|| ModuleCoverageMap::new(module_addr, module_name));
        module_entry.insert_multi(func_name, pc, count);
    }

    pub fn insert(
        &mut self,
        module_addr: AccountAddress,
        module_name: Identifier,
        func_name: Identifier,
        pc: u64,
    ) {
        self.insert_multi(module_addr, module_name, func_name, pc, 1);
    }

    pub fn into_coverage_map_with_modules(
        self,
        modules: BTreeMap<AccountAddress, BTreeMap<Identifier, (String, CompiledModule)>>,
    ) -> ExecCoverageMapWithModules {
        let retained: BTreeMap<(String, AccountAddress, Identifier), ModuleCoverageMap> = self
            .module_maps
            .into_iter()
            .filter_map(|((module_addr, module_name), module_cov)| {
                modules.get(&module_addr).and_then(|func_map| {
                    func_map.get(&module_name).map(|(module_path, _)| {
                        ((module_path.clone(), module_addr, module_name), module_cov)
                    })
                })
            })
            .collect();

        let compiled_modules = modules
            .into_iter()
            .flat_map(|(_, module_map)| {
                module_map
                    .into_iter()
                    .map(|(_, (module_path, compiled_module))| (module_path, compiled_module))
            })
            .collect();

        ExecCoverageMapWithModules {
            module_maps: retained,
            compiled_modules,
        }
    }
}

impl ExecCoverageMapWithModules {
    pub fn empty() -> Self {
        Self {
            module_maps: BTreeMap::new(),
            compiled_modules: BTreeMap::new(),
        }
    }

    pub fn merge(&mut self, another: ExecCoverageMapWithModules) {
        for ((module_path, module_addr, module_name), val) in another.module_maps {
            self.module_maps
                .entry((module_path.clone(), module_addr, module_name.clone()))
                .or_insert_with(|| ModuleCoverageMap::new(module_addr, module_name))
                .merge(val);
        }

        for (module_path, compiled_module) in another.compiled_modules {
            self.compiled_modules
                .entry(module_path)
                .or_insert(compiled_module);
        }
    }
}

impl TraceMap {
    /// Takes in a file containing a raw VM trace, and returns an updated coverage map.
    pub fn update_from_trace_file<P: AsRef<Path>>(mut self, filename: P) -> Self {
        let file = File::open(filename).unwrap();
        for line in BufReader::new(file).lines() {
            let line = line.unwrap();
            let mut splits = line.split(',');
            let exec_id = splits.next().unwrap();
            let context = splits.next().unwrap();
            let pc = splits.next().unwrap().parse::<u64>().unwrap();

            let mut context_segs: Vec<_> = context.split("::").collect();
            let is_script = context_segs.len() == 2;
            if !is_script {
                let func_name = Identifier::new(context_segs.pop().unwrap()).unwrap();
                let module_name = Identifier::new(context_segs.pop().unwrap()).unwrap();
                let module_addr =
                    AccountAddress::from_hex_literal(context_segs.pop().unwrap()).unwrap();
                self.insert(exec_id, module_addr, module_name, func_name, pc);
            } else {
                // Don't count scripts (for now)
                assert_eq!(context_segs.pop().unwrap(), "main",);
                assert_eq!(context_segs.pop().unwrap(), "Script",);
            }
        }
        self
    }

    // Takes in a file containing a raw VM trace, and returns a parsed trace.
    pub fn from_trace_file<P: AsRef<Path>>(filename: P) -> Self {
        let trace_map = TraceMap {
            exec_maps: BTreeMap::new(),
        };
        trace_map.update_from_trace_file(filename)
    }

    // Takes in a file containing a serialized trace and deserialize it.
    pub fn from_binary_file<P: AsRef<Path>>(filename: P) -> Self {
        let mut bytes = Vec::new();
        File::open(filename)
            .ok()
            .and_then(|mut file| file.read_to_end(&mut bytes).ok())
            .ok_or_else(|| format_err!("Error while reading in coverage map binary"))
            .unwrap();
        bcs::from_bytes(&bytes)
            .map_err(|_| format_err!("Error deserializing into coverage map"))
            .unwrap()
    }

    // add entries in a cascading manner
    pub fn insert(
        &mut self,
        exec_id: &str,
        module_addr: AccountAddress,
        module_name: Identifier,
        func_name: Identifier,
        pc: u64,
    ) {
        let exec_entry = self
            .exec_maps
            .entry(exec_id.to_owned())
            .or_insert_with(Vec::new);
        exec_entry.push(TraceEntry {
            module_addr,
            module_name,
            func_name,
            func_pc: pc as CodeOffset,
        });
    }
}

pub fn output_map_to_file<M: Serialize, P: AsRef<Path>>(file_name: P, data: &M) -> Result<()> {
    let bytes = bcs::to_bytes(data)?;
    let mut file = File::create(file_name)?;
    file.write_all(&bytes)?;
    Ok(())
}