Skip to content

Commit ef45775

Browse files
committed
Add a method to get the malloc(ed) size estimate
Returning 1 if variable was not malloc(ed). The estimation is described in the documentation.
1 parent 4e97536 commit ef45775

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/memory-analyzer/gdb_api.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Author: Malte Mues <[email protected]>
2424
#include <goto-programs/goto_model.h>
2525

2626
#include <util/prefix.h>
27+
#include <util/string2int.h>
2728
#include <util/string_utils.h>
2829

2930
#include <sys/wait.h>
@@ -56,6 +57,39 @@ gdb_apit::~gdb_apit()
5657
wait(NULL);
5758
}
5859

60+
size_t gdb_apit::query_malloc_size(const std::string &pointer_expr)
61+
{
62+
write_to_gdb("-var-create tmp * malloc_usable_size(" + pointer_expr + ")");
63+
64+
if(!was_command_accepted())
65+
{
66+
return 1;
67+
}
68+
69+
write_to_gdb("-var-evaluate-expression tmp");
70+
gdb_output_recordt record = get_most_recent_record("^done", true);
71+
72+
write_to_gdb("-var-delete tmp");
73+
check_command_accepted();
74+
75+
const auto it = record.find("value");
76+
CHECK_RETURN(it != record.end());
77+
78+
const std::string value = it->second;
79+
80+
INVARIANT(
81+
value.back() != '"' ||
82+
(value.length() >= 2 && value[value.length() - 2] == '\\'),
83+
"quotes should have been stripped off from value");
84+
INVARIANT(value.back() != '\n', "value should not end in a newline");
85+
86+
const auto result = string2optional_size_t(value);
87+
if(result.has_value())
88+
return *result;
89+
else
90+
return 1;
91+
}
92+
5993
void gdb_apit::create_gdb_process()
6094
{
6195
PRECONDITION(gdb_state == gdb_statet::NOT_CREATED);

src/memory-analyzer/gdb_api.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,17 @@ class gdb_apit
8383
const optionalt<std::string> string;
8484
};
8585

86+
/// Get the allocated size estimate for a pointer by evaluating
87+
/// `malloc_usable_size'. The function returns the number of usable bytes in
88+
/// the block pointed to by the pointer to a block of memory allocated by
89+
/// `malloc' or a related function. The value may be greater than the
90+
/// requested size of the allocation because of alignment and minimum size
91+
/// constraints.
92+
/// \param pointer_expr: expression with a pointer name
93+
/// \return 1 if the pointer was not allocated with malloc otherwise return
94+
/// the result of calling `malloc_usable_size'
95+
size_t query_malloc_size(const std::string &pointer_expr);
96+
8697
/// Create a new gdb process for analysing the binary indicated by the member
8798
/// variable `binary`
8899
void create_gdb_process();

0 commit comments

Comments
 (0)