Why gdb command "info locals" also print undeclared variable? - gcc

int a = 10;
if(a >= 5)
printf("Hello World");
int b;
b = 3;
For example I command "info locals" before execute line 4 "int b;" but gdb print information of variables a and b. Why gdb work like this and how can I print only declared variables?

It depends on the way the compiler decided to compile your code.
In your case, I believe that since variable b will always be used in your code, then the compiler might "declared" both a and b together to optimize execution time.
If you really want to understand what happened, disassemble the program and see the assembly that actually runs when you execute this code.
I assume you will discover that the instruction that allocates the space on the stack frame for the variable b allocated the space for both variables (a & b) at the same time.

gdb shows b variable because it has been declared by your compiler
Assuming this code is inside a function, once execution flow enters the function it allocates local variables in the stack, this is where a and b values reside. That's because the compiler reads your code and makes all declarations at the beginning, even if they haven't been declared on top of your function.
Take a look at How the local variable stored in stack

Related

Does CLion possible evaluate a function when debugging Rust code?

A snip of Rust code:
pub fn main() {
let a = "hello";
let b = a.len();
let c =b;
println!("len:{}",c)
}
When debugging in CLion, Is it possible to evaluate a function? For example, debug the code step by step, now the code is running to the last line println!... and the current step stops here, by adding the expression a.len() to the watch a variable window, the IDE can't evaluate the a.len(). It says: error: no field named len
This is the same reason you can't make conditional breakpoints for Rust code:
Can't create a conditional breakpoint in VSCode-LLDB with Rust
I hope, I'm not too late to answer this, but with both lldb and gdb, Rust debugging capability is currently rather constrained.
Expressions that are straightforward work; anything complex is likely to produce issues.
My observations from rust-lldb trying this, are that only a small portion of Rust is understood by the expression parser.
There is no support for macros.
Non-used functions are not included in the final binary.
For instance, since that method is not included in the binary, you are unable to execute capacity() on the HashMap in the debugger.
Methods must be named as follows:
struct value.method(&struct value)
There is no technique that I've discovered to call monomorphized functions on generic structs (like HashMap).
For example, "hello" is a const char [5] including the trailing NUL byte. String constants "..." in lldb expressions are produced as C-style string constants.
Therefore, they are not valid functions

Match the left side variable of an assignment to the return value of the right side function call

For the following statement inside function func(), I'm trying to figure out the variable name (which is 'dictionary' in the example) that points to the malloc'ed memory region.
Void func() {
uint64_t * dictionary = (uint64_t *) malloc ( sizeof(uint64_t) * 128 );
}
The instrumented malloc() can record the start address and size of the allocation. However, no knowledge of variable 'dictionary' that will be assigned to, any features from the compilers side can help to solve this problem, without modifying the compiler to instrument such assignment statements?
One way I've been thinking is to use the feature that variable 'dictionary' and function 'malloc' is on one source code line or next to each other, the dwarf provides line information.
One thing you can do with Clang and LLVM is emit the code with debug information and then look for malloc calls. These will be assigned to LLVM values, which can be traced (when not compiled with optimizations, that is) to the original C/C++ source code via the debug information metadata.

Compile time barriers - compiler code reordering - gcc and pthreads

AFAIK there are pthread functions that acts as memory barriers (e.g. here clarifications-on-full-memory-barriers-involved-by-pthread-mutexes). But what about compile-time barrier, i.e. is compiler (especially gcc) aware of this?
In other words - e.g. - is pthread_create() reason for gcc not to perform reordering?
For example in code:
a = 1;
pthread_create(...);
Is it certain that reordering will not take place?
What about invocations from different functions:
void fun(void) {
pthread_create(...);
...
}
a = 1;
fun();
Is fun() also compile time barrier (assuming pthread_create() is)?
What about functions in different translation units?
Please note that I am interested in general gcc and pthreads behavior scpecification, not necessarily x86-specific (various different embedded platforms in focus).
I am also not interested in other compilers/thread libraries behavior.
Because functions such as pthread_create() are external functions the compiler must ensure that any side effects that could be visible to an external function (such as a write to a global variable) must be done before calling the function. The compile couldn't reorder the write to a until after the function call in the first case) assuming a was global or otherwise potentially accessible externally).
This is behavior that is necessary for any C compiler, and really has little to do with threads.
However, if the variable a was a local variable, the compiler might be able to reorder it until after the function call (a might not even end up in memory at all for that matter), unless something like the address of a was taken and made available externally somehow (like passing it as the thread parameter).
For example:
int a;
void foo(void)
{
a = 1;
pthread_create(...); // the compiler can't reorder the write to `a` past
// the call to `pthread_create()`
// ...
}
void bar(void)
{
int b;
b = 1;
pthread_create(...); // `b` can be initialized after calling `pthread_create()`
// `b` might not ever even exist except as a something
// passed on the stack or in a register to `printf()`
printf( "%d\n", b);
}
I'm not sure if there's a document that outlines this in more detail - this is covered largely by C's 'as if' rule. In C99 that's in 5.1.2.3/3 "Program execution". C is specified by an abstract machine with sequence points where side effects must be complete, and programs must follow that abstract machine model except where the compiler can deduce that the side effects aren't needed.
In my foo() example above, the compiler would generally not be able to deduce that setting a = 1; isn't needed by pthread_create(), so the side effect of setting a to the value 1 must be completed before calling pthread_create(). Note that if there are compilers that perform global optimizations that can deduce that a isn't used elsewhere, they could delay or elide the assignment. However, in that case nothing else is using the side effect, so there would be no problem with that.

GDB: Create local variable?

I'm using Xcode's debugger. While stopped at a breakpoint, is there a command I can type in the GDB command prompt to create a local variable? If so, how? Please provide an example.
I know I can do it in the code and then recompile the program, but I'm looking for a faster way.
If you don't need to reference the variable in your code but just want to do some ad-hoc investigation, you can use Convenience Variables by using the set command with a variable name starting with $:
(gdb) set $foo = method_that_makes_something()
(gdb) set $bar = 15
(gdb) p $bar
$4 = 15
You'll notice when you print things it's prefixed with a numeric variable - you can use these to refer to that value later as well:
(gdb) p $4
$5 = 15
To reiterate: this doesn't actually affect the program's stack, and it can't, as that would break a lot of things. But it's useful if you just need a local playground, some loop variables, etc.
While you can't modify the stack, you can interact with the program's memory space - you can call functions (including malloc) and construct objects, but these will all live in static memory, not as local variables on the stack.
Since a local variable would require stack space and the (compiled) code is tied to the stack layout, no you can't.
Comparing this with scripting languages is not quite appropriate.
Values printed by the print command are saved in the GDB "value history". This allows you to refer to them in other expressions.
For example, suppose you have just printed a pointer to a structure and want to see the contents of the structure. It suffices to type
p *$

Setting a watch point in GDB

I am operating a huge code base and want to monitor a value of a particular variable (which is buried deep down inside one of the files)especially when it gets set to zero.
1) Variable does not belong to global scope .Is there a better option than to first set breakpoint into the function where it is defined and then set the watch point?
2) After trying the option in 1 I see that watch point gets deleted after a while saying its out of frame which used this .This way it adds to the tediousness of the procedure since I have to add it again and again?Any workarounds?
3) Is there a way to check ie watch if a particular variable is equal to 0( or any specific constant)?
want to monitor a value of a particular variable
Often this is not the best approach, especially in large codebases.
What you really likely want to do is understand the invariants, and assert that they are true on entry and exit to various parts of the code.
1) Variable does not belong to global scope .Is there a better option than to first set breakpoint into the function where it is defined and then set the watch point?
No. For automatic (stack) variables you have to be in the scope where the variable is "active".
What you can do is set a breakpoint on some line, and attach commands to that breakpoint that will set the watchpoint automatically, e.g.
(gdb) break foo.c:123
(gdb) commands 1
silent
watch some_local
continue
end
3) Is there a way to check ie watch if a particular variable is equal to 0
You can't do that with a watchpoint, but you can with a conditional breakpoint:
(gdb) break foo.c:234 if some_local == 0
I will assume that you are using Linux. You can try this:
The first step is to make the variable static, like:
static int myVar;
Then, after compiling your code using -ggdb, you must discover the address of the variable inside your binary, like so (I have used a real case as example):
readelf -s pdv | grep tmp | c++filt
In my situation, the output is:
47: 081c1474 4 OBJECT LOCAL DEFAULT 25 startProc(int)::tmp
The address in this case is 081c1474. Now you can set a watch point inside GDB:
watch *0x081c1474
Mind the "*0x" before the correct address.
I know this question is old, but I hope it helps anyway.

Resources