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
use crate::analysis::pointer_inference::State as PointerInferenceState;
use crate::{
    abstract_domain::{AbstractDomain, DomainInsertion, HasTop, TryToBitvec},
    analysis::string_abstraction::{context::Context, state::State},
    intermediate_representation::ExternSymbol,
};

impl<'a, T: AbstractDomain + DomainInsertion + HasTop + Eq + From<String>> Context<'a, T> {
    /// Handles the resulting string domain from strcat and strncat calls.
    /// The symbol call returns the pointer to the destination string in its return register.
    pub fn handle_strcat_and_strncat_calls(
        &self,
        state: &State<T>,
        extern_symbol: &ExternSymbol,
    ) -> State<T> {
        let mut new_state = state.clone();
        if let Some(pi_state) = state.get_pointer_inference_state() {
            if let Some(return_arg) = extern_symbol.parameters.first() {
                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 target_domain =
                            Context::<T>::merge_domains_from_multiple_pointer_targets(
                                state,
                                pi_state,
                                return_pointer.get_relative_values(),
                            );

                        Context::add_new_string_abstract_domain(
                            &mut new_state,
                            pi_state,
                            return_pointer.get_relative_values(),
                            target_domain.append_string_domain(&self.process_second_input_domain(
                                state,
                                extern_symbol,
                                pi_state,
                            )),
                        );

                        if let Ok(return_register) = extern_symbol.get_unique_return_register() {
                            new_state.add_new_variable_to_pointer_entry(
                                return_register.clone(),
                                return_pointer,
                            );
                        } else {
                            new_state.add_unassigned_return_pointer(return_pointer);
                        }
                    }
                }
            }
        }

        new_state
    }

    /// Processes the contents of the second input parameter.
    pub fn process_second_input_domain(
        &self,
        state: &State<T>,
        extern_symbol: &ExternSymbol,
        pi_state: &PointerInferenceState,
    ) -> T {
        let mut input_domain = T::create_top_value_domain();
        if let Some(input_arg) = extern_symbol.parameters.get(1) {
            if let Ok(input_value) =
                pi_state.eval_parameter_arg(input_arg, &self.project.runtime_memory_image)
            {
                // Check whether the second input string is in read only memory or on stack/heap.
                if !input_value.get_relative_values().is_empty() {
                    input_domain = Context::<T>::merge_domains_from_multiple_pointer_targets(
                        state,
                        pi_state,
                        input_value.get_relative_values(),
                    );
                }

                if let Some(value) = input_value.get_absolute_value() {
                    if let Ok(global_address) = value.try_to_bitvec() {
                        if let Ok(input_string) = self
                            .project
                            .runtime_memory_image
                            .read_string_until_null_terminator(&global_address)
                        {
                            if !input_domain.is_top() {
                                input_domain =
                                    input_domain.merge(&T::from(input_string.to_string()));
                            } else {
                                input_domain = T::from(input_string.to_string());
                            }
                        }
                    }
                }
            }
        }

        input_domain
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        abstract_domain::{CharacterInclusionDomain, CharacterSet, IntervalDomain},
        analysis::pointer_inference::PointerInference as PointerInferenceComputation,
        analysis::string_abstraction::{
            context::symbol_calls::tests::Setup,
            tests::mock_project_with_intraprocedural_control_flow,
        },
        intermediate_representation::*,
        variable,
    };

    #[test]
    fn test_handle_strcat_and_strncat_calls_with_known_second_input() {
        let strcat_symbol = ExternSymbol::mock_strcat_symbol_arm();
        let project = mock_project_with_intraprocedural_control_flow(
            vec![(strcat_symbol.clone(), vec![true])],
            "func",
        );
        let mut pi_results = PointerInferenceComputation::mock(&project);
        pi_results.compute(false);

        let setup: Setup<CharacterInclusionDomain> = Setup::new(&pi_results);

        let expected_domain = CharacterInclusionDomain::Value((
            CharacterSet::Value(
                vec!['s', 't', 'r', ' ', '1', '2', '3', '4']
                    .into_iter()
                    .collect(),
            ),
            CharacterSet::Top,
        ));

        let new_state = setup
            .context
            .handle_strcat_and_strncat_calls(&setup.state_before_call, &strcat_symbol);

        assert_eq!(
            expected_domain,
            *new_state
                .get_stack_offset_to_string_map()
                .get(&(-0x3c as i64))
                .unwrap()
        );
    }

    #[test]
    fn test_handle_strcat_and_strncat_calls_with_unknown_second_input() {
        let strcat_symbol = ExternSymbol::mock_strcat_symbol_arm();
        let project = mock_project_with_intraprocedural_control_flow(
            vec![(strcat_symbol.clone(), vec![false])],
            "func",
        );
        let mut pi_results = PointerInferenceComputation::mock(&project);
        pi_results.compute(false);

        let mut setup: Setup<CharacterInclusionDomain> = Setup::new(&pi_results);

        // Test Case 1: No string domain is tracked for the second input.
        let new_state = setup
            .context
            .handle_strcat_and_strncat_calls(&setup.state_before_call, &strcat_symbol);

        assert_eq!(
            CharacterInclusionDomain::Top,
            *new_state
                .get_stack_offset_to_string_map()
                .get(&(-0x3c as i64))
                .unwrap()
        );

        // Test Case 2: A string domain is tracked for the second input.
        let expected_domain = CharacterInclusionDomain::Value((
            CharacterSet::Value(vec!['a'].into_iter().collect()),
            CharacterSet::Top,
        ));

        setup
            .state_before_call
            .add_new_stack_offset_to_string_entry(
                0x28,
                CharacterInclusionDomain::from("a".to_string()),
            );

        let new_state = setup
            .context
            .handle_strcat_and_strncat_calls(&setup.state_before_call, &strcat_symbol);

        assert_eq!(
            expected_domain,
            *new_state
                .get_stack_offset_to_string_map()
                .get(&(-0x3c as i64))
                .unwrap()
        );
    }

    #[test]
    fn test_process_second_input_domain_global() {
        let strcat_symbol = ExternSymbol::mock_strcat_symbol_arm();
        let project = mock_project_with_intraprocedural_control_flow(
            vec![(strcat_symbol.clone(), vec![true])],
            "func",
        );
        let mut pi_results = PointerInferenceComputation::mock(&project);
        pi_results.compute(false);

        let setup: Setup<CharacterInclusionDomain> = Setup::new(&pi_results);

        assert_eq!(
            CharacterInclusionDomain::ci("str1 str2 str3 str4"),
            setup.context.process_second_input_domain(
                &setup.state_before_call,
                &strcat_symbol,
                &setup.pi_state_before_symbol_call
            )
        );
    }

    #[test]
    fn test_process_second_input_domain_local() {
        let strcat_symbol = ExternSymbol::mock_strcat_symbol_arm();
        let project = mock_project_with_intraprocedural_control_flow(
            vec![(strcat_symbol.clone(), vec![false])],
            "func",
        );
        let mut pi_results = PointerInferenceComputation::mock(&project);
        pi_results.compute(false);

        let mut setup: Setup<CharacterInclusionDomain> = Setup::new(&pi_results);

        setup
            .state_before_call
            .add_new_stack_offset_to_string_entry(40, CharacterInclusionDomain::ci("abc"));

        assert_eq!(
            CharacterInclusionDomain::ci("abc"),
            setup.context.process_second_input_domain(
                &setup.state_before_call,
                &strcat_symbol,
                &setup.pi_state_before_symbol_call
            )
        );
    }

    #[test]
    fn test_process_second_input_domain_local_and_global() {
        let r1_reg = variable!("r1:4");
        let strcat_symbol = ExternSymbol::mock_strcat_symbol_arm();
        let project = mock_project_with_intraprocedural_control_flow(
            vec![(strcat_symbol.clone(), vec![false])],
            "func",
        );
        let mut pi_results = PointerInferenceComputation::mock(&project);
        pi_results.compute(false);

        let mut setup: Setup<CharacterInclusionDomain> = Setup::new(&pi_results);

        let mut target_domain = setup.pi_state_before_symbol_call.get_register(&r1_reg);

        target_domain.set_absolute_value(Some(IntervalDomain::mock(0x7000, 0x7000)));

        setup
            .pi_state_before_symbol_call
            .set_register(&r1_reg, target_domain);

        setup
            .state_before_call
            .add_new_stack_offset_to_string_entry(40, CharacterInclusionDomain::ci("str"));

        let expected_domain = CharacterInclusionDomain::Value((
            CharacterSet::Value(vec!['s', 't', 'r'].into_iter().collect()),
            CharacterSet::Value(
                vec!['s', 't', 'r', '1', '2', '3', '4', ' ']
                    .into_iter()
                    .collect(),
            ),
        ));

        assert_eq!(
            expected_domain,
            setup.context.process_second_input_domain(
                &setup.state_before_call,
                &strcat_symbol,
                &setup.pi_state_before_symbol_call
            )
        );
    }
}