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
use regex::Match;

use crate::analysis::pointer_inference::State as PointerInferenceState;
use crate::{
    abstract_domain::{
        AbstractDomain, DataDomain, DomainInsertion, HasTop, IntervalDomain, TryToBitvec,
    },
    analysis::string_abstraction::{context::Context, state::State},
    intermediate_representation::{Arg, Datatype, ExternSymbol},
    utils::arguments::{get_input_format_string, get_variable_parameters},
};

impl<'a, T: AbstractDomain + DomainInsertion + HasTop + Eq + From<String>> Context<'a, T> {
    /// Handles the detection of string parameters to sprintf and snprintf calls.
    /// Is able to identify a string constant parameter and to insert it into the format string.
    /// e.g. the format string is "cat %s" and the analysis detected that the input string
    /// is a constant in memory, for instance "bash.sh".
    /// Then the abstract string domain is constructed with the string "cat bash.sh".
    pub fn handle_sprintf_and_snprintf_calls(
        &self,
        state: &State<T>,
        extern_symbol: &ExternSymbol,
    ) -> State<T> {
        let mut new_state = state.clone();
        if let Some(return_arg) = extern_symbol.parameters.first() {
            if let Some(pi_state) = state.get_pointer_inference_state() {
                if let Ok(return_pointer) =
                    pi_state.eval_parameter_arg(return_arg, &self.project.runtime_memory_image)
                {
                    if !return_pointer.get_relative_values().is_empty() {
                        let format_string_index = self
                            .format_string_index_map
                            .get(&extern_symbol.name)
                            .unwrap();
                        self.parse_format_string_and_add_new_string_domain(
                            &mut new_state,
                            pi_state,
                            extern_symbol,
                            *format_string_index,
                            &return_pointer,
                        )
                    }

                    new_state.add_unassigned_return_pointer(return_pointer);
                }
            }
        }

        new_state
    }

    /// Gets the input format string, parses the input parameters and adds
    /// the generated domain to the string maps.
    pub fn parse_format_string_and_add_new_string_domain(
        &self,
        state: &mut State<T>,
        pi_state: &PointerInferenceState,
        extern_symbol: &ExternSymbol,
        format_string_index: usize,
        return_pointer: &DataDomain<IntervalDomain>,
    ) {
        if let Ok(input_format_string) = get_input_format_string(
            pi_state,
            extern_symbol,
            format_string_index,
            &self.project.runtime_memory_image,
        ) {
            let returned_abstract_domain = self.create_string_domain_for_sprintf_snprintf(
                pi_state,
                state,
                extern_symbol,
                input_format_string,
            );

            Context::<T>::add_new_string_abstract_domain(
                state,
                pi_state,
                return_pointer.get_relative_values(),
                returned_abstract_domain,
            );
        } else {
            Context::<T>::add_new_string_abstract_domain(
                state,
                pi_state,
                return_pointer.get_relative_values(),
                T::create_top_value_domain(),
            );
        }
    }

    /// Creates a string domain for a s(n)printf call by considering input constants
    /// and other domains.
    pub fn create_string_domain_for_sprintf_snprintf(
        &self,
        pi_state: &PointerInferenceState,
        state: &State<T>,
        extern_symbol: &ExternSymbol,
        input_format_string: String,
    ) -> T {
        if Context::<T>::no_specifiers(input_format_string.clone()) {
            return T::from(input_format_string);
        }
        match get_variable_parameters(
            self.project,
            pi_state,
            extern_symbol,
            &self.format_string_index_map,
        ) {
            Ok(var_args) => {
                if var_args.is_empty() {
                    return T::create_top_value_domain();
                }

                self.create_string_domain_using_constants_and_sub_domains(
                    input_format_string,
                    &var_args,
                    pi_state,
                    state,
                )
            }
            Err(_) => self.create_string_domain_using_data_type_approximations(input_format_string),
        }
    }

    /// Creates a domain from a format string where all specifiers are approximated according
    /// to their data type. This ensures that, if there is a long data type, that the domain is
    /// no returned as *Top*.
    pub fn create_string_domain_using_data_type_approximations(&self, format_string: String) -> T {
        let re = Context::<T>::re_format_specifier();
        let mut domains: Vec<T> = Vec::new();
        let mut last_specifier_end = 0;
        for (index, specifier) in re.find_iter(&format_string).enumerate() {
            Context::push_constant_subsequences_before_and_between_specifiers(
                &mut domains,
                &format_string,
                specifier,
                last_specifier_end,
                index,
            );

            Context::push_format_specifier_approximation(&mut domains, specifier);

            last_specifier_end = specifier.end();
        }

        Context::push_constant_suffix_if_available(
            &mut domains,
            &format_string,
            last_specifier_end,
        );

        Context::concat_domains(&mut domains)
    }

    /// Creates a string domain from found constants and sub domains.
    pub fn create_string_domain_using_constants_and_sub_domains(
        &self,
        format_string: String,
        var_args: &[Arg],
        pi_state: &PointerInferenceState,
        state: &State<T>,
    ) -> T {
        let re = Context::<T>::re_format_specifier();
        let mut domains: Vec<T> = Vec::new();
        let mut last_specifier_end = 0;
        for (index, (specifier, arg)) in re.find_iter(&format_string).zip(var_args).enumerate() {
            Context::push_constant_subsequences_before_and_between_specifiers(
                &mut domains,
                &format_string,
                specifier,
                last_specifier_end,
                index,
            );
            domains.push(self.fetch_constant_and_domain_for_format_specifier(
                arg,
                specifier.as_str().to_string(),
                pi_state,
                state,
            ));
            last_specifier_end = specifier.end();
        }

        Context::push_constant_suffix_if_available(
            &mut domains,
            &format_string,
            last_specifier_end,
        );

        Context::concat_domains(&mut domains)
    }

    /// Creates a string domain by approximating a format specifier and pushes it to the domain vector.
    pub fn push_format_specifier_approximation(domains: &mut Vec<T>, specifier: Match) {
        domains.push(Context::<T>::approximate_string_domain_from_datatype(
            Context::<T>::trim_format_specifier(specifier.as_str().to_string()),
        ));
    }

    /// Creates string domains from constant subsequences that either appear
    /// at the beginning of the format string or between specifiers.
    pub fn push_constant_subsequences_before_and_between_specifiers(
        domains: &mut Vec<T>,
        format_string: &str,
        specifier: Match,
        last_specifier_end: usize,
        index: usize,
    ) {
        if index == 0 {
            if specifier.start() > 0 {
                domains.push(T::from(format_string[..specifier.start()].to_string()));
            }
        } else {
            let between_specifiers =
                format_string[last_specifier_end..specifier.start()].to_string();
            if !between_specifiers.is_empty() {
                domains.push(T::from(
                    format_string[last_specifier_end..specifier.start()].to_string(),
                ));
            }
        }
    }

    /// Pushes a potential constant suffix to the string domain vector.
    pub fn push_constant_suffix_if_available(
        domains: &mut Vec<T>,
        format_string: &str,
        last_specifier_end: usize,
    ) {
        if last_specifier_end != format_string.len() {
            domains.push(T::from(format_string[last_specifier_end..].to_string()));
        }
    }

    /// Takes a vector of string domains and concatenates them.
    pub fn concat_domains(domains: &mut Vec<T>) -> T {
        let mut init_domain = domains.first().unwrap().clone();
        domains.remove(0);
        for remaining_domain in domains.iter() {
            init_domain = init_domain.append_string_domain(remaining_domain);
        }

        init_domain
    }

    /// Checks whether the string has no format specifiers.
    pub fn no_specifiers(format_string: String) -> bool {
        !Context::<T>::re_format_specifier().is_match(&format_string)
    }

    /// Tries to fetch a constant or sub domain for the format specifier.
    /// If no data is available, it approximates the sub domain corresponding to
    /// the characters that can be contained in the data type.
    pub fn fetch_constant_and_domain_for_format_specifier(
        &self,
        arg: &Arg,
        specifier: String,
        pi_state: &PointerInferenceState,
        state: &State<T>,
    ) -> T {
        if let Ok(data) = pi_state.eval_parameter_arg(arg, &self.project.runtime_memory_image) {
            let constant_domain: Option<T> = self.fetch_constant_domain_if_available(&data, arg);
            if let Some(generated_domain) = Context::<T>::fetch_subdomains_if_available(
                &data,
                state,
                pi_state,
                arg,
                constant_domain.clone(),
            ) {
                return generated_domain;
            }

            if let Some(domain) = constant_domain {
                return domain;
            }
        }

        Context::<T>::approximate_string_domain_from_datatype(Context::<T>::trim_format_specifier(
            specifier,
        ))
    }

    /// Removes the '%' character and any size number from a format specifier.
    pub fn trim_format_specifier(specifier: String) -> String {
        specifier
            .as_str()
            .trim_start_matches(&['%', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'][..])
            .to_string()
    }

    /// Fetches subdomains if they are available for a pointer domain and merges a potential
    /// constant domain into the result.
    pub fn fetch_subdomains_if_available(
        data: &DataDomain<IntervalDomain>,
        state: &State<T>,
        pi_state: &PointerInferenceState,
        arg: &Arg,
        constant_domain: Option<T>,
    ) -> Option<T> {
        if !data.get_relative_values().is_empty() {
            if let Some(data_type) = arg.get_data_type() {
                if matches!(data_type, Datatype::Pointer) {
                    let mut generated_domain =
                        Context::<T>::merge_domains_from_multiple_pointer_targets(
                            state,
                            pi_state,
                            data.get_relative_values(),
                        );
                    if let Some(constant) = constant_domain {
                        generated_domain = generated_domain.merge(&constant);
                    }

                    return Some(generated_domain);
                }
            }
        }

        None
    }

    /// Takes a data domain and tries to get a constant value.
    pub fn fetch_constant_domain_if_available(
        &self,
        data: &DataDomain<IntervalDomain>,
        arg: &Arg,
    ) -> Option<T> {
        if let Some(value) = data.get_absolute_value() {
            if let Ok(value_vector) = value.try_to_bitvec() {
                if let Some(data_type) = arg.get_data_type() {
                    match data_type {
                        Datatype::Char => {
                            if let Some(char_domain) = self.get_constant_char_domain(value_vector) {
                                return Some(char_domain);
                            }
                        }
                        Datatype::Integer => {
                            if let Some(integer_domain) =
                                Context::<T>::get_constant_integer_domain(value_vector)
                            {
                                return Some(integer_domain);
                            }
                        }
                        Datatype::Pointer => {
                            if let Some(string_domain) =
                                self.get_constant_string_domain(value_vector)
                            {
                                return Some(string_domain);
                            }
                        }
                        _ => (),
                    }
                }
            }
        }

        None
    }
}

#[cfg(test)]
mod tests;