Skip to content

Commit 790f0d5

Browse files
committed
malloc: fix getting malloc size
After the rebase to new CBMC, constant propagation does not work in some cases. This is a problem for our malloc handling as we require to see: malloc_size = sizeof(...) This commit fixes the problem by recursively searching for the malloc size expression to handle cases like: size = sizeof(...) malloc_size = size Also adds a regression test for this case.
1 parent 41669a8 commit 790f0d5

File tree

3 files changed

+50
-8
lines changed

3 files changed

+50
-8
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
void *my_malloc(unsigned int size) {
2+
return malloc(size);
3+
}
4+
5+
int main() {
6+
void *a = my_malloc(sizeof(int));
7+
free(a);
8+
free(a);
9+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
CORE
2+
main.c
3+
--pointer-check --inline
4+
^EXIT=10$
5+
^SIGNAL=0$
6+
^VERIFICATION FAILED$
7+
\[free.precondition.6\] free argument must be NULL or valid pointer: FAILURE

src/ssa/malloc_ssa.cpp

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,38 @@ static bool replace_malloc_rec(
289289
}
290290
}
291291

292+
/// Finds the latest assignment to lhs before location_number and:
293+
/// - if the assignment rhs is a symbol, continues recursively
294+
/// - otherwise returns the rhs
295+
exprt get_malloc_size(
296+
const exprt &lhs,
297+
unsigned location_number,
298+
const goto_functiont &goto_function)
299+
{
300+
exprt result=nil_exprt();
301+
unsigned result_loc_num=0;
302+
forall_goto_program_instructions(it, goto_function.body)
303+
{
304+
if(!it->is_assign())
305+
continue;
306+
307+
if(lhs==it->assign_lhs())
308+
{
309+
result=it->assign_rhs();
310+
if(result.id()==ID_typecast)
311+
result=to_typecast_expr(result).op();
312+
result_loc_num=it->location_number;
313+
}
314+
315+
if(it->location_number==location_number)
316+
break;
317+
}
318+
if(result.id()==ID_symbol)
319+
return get_malloc_size(result, result_loc_num, goto_function);
320+
321+
return result;
322+
}
323+
292324
bool replace_malloc(
293325
goto_modelt &goto_model,
294326
const std::string &suffix,
@@ -336,14 +368,8 @@ bool replace_malloc(
336368
function_copy.copy_from(f_it.second);
337369
constant_propagator_ait const_propagator(function_copy);
338370
const_propagator(f_it.first, function_copy, ns);
339-
forall_goto_program_instructions(copy_i_it, function_copy.body)
340-
{
341-
if(copy_i_it->location_number==i_it->location_number)
342-
{
343-
assert(copy_i_it->is_assign());
344-
malloc_size=copy_i_it->get_assign().rhs();
345-
}
346-
}
371+
malloc_size=get_malloc_size(
372+
i_it->assign_lhs(), i_it->location_number, function_copy);
347373
}
348374
}
349375
if(replace_malloc_rec(code_assign.rhs(),

0 commit comments

Comments
 (0)