LLDB print a variable named class - c

I have a C programm in which a variable called class is used.
I'm trying to debug it with LLDB but I'm encountering the following problem:
(lldb) print class
error: warning: declaration does not declare anything
error: declaration of anonymous class must be a definition
error: 1 errors parsing expression
I believe this problem occurs because class is a reserved keyword in C++ and LLDB interprets the code passed to print as C++. Is there still a way to print the content of my variable?
(Please do not advise me to rename the variable, I would have come up with this myself, if it was possible)

The problem is that the lldb expression parser uses C++ references to implement the job of finding & extracting results from the expressions we run. So we currently have to compile the expressions as C++ expressions, and as you guessed, you can't use "class" in a C++ expression. At some point, we have to teach clang how to do "C with references" and then we'll be able to compile & execute real C expressions.
However, provided you have debug information for "class", you can print the value of the variable using the "frame variable" command, i.e.:
(lldb) frame variable class
The "frame variable" command does not use the expression parser, it goes directly to the debug information, extracts the type & location of the variable, and prints that directly. So it doesn't suffer this restriction. If "class" is a global variable, not a frame local, use target variable instead.
frame variable does support a limited set of "expression-like" features, you can say:
(lldb) frame variable class.member
or
(lldb) frame variable *class
but you can't use it to call functions or pass the variable to a function call.
If you need to do that you can run the command:
(lldb) frame variable -L class
which will print the location of the variable. Usually that's some address, in which case you can use
(TypeOfClass *) <Address From Frame Variable>
in your expression in place of "class". If the location turns out to be a register, then use "$" appropriately cast in your expression. If you are going to use the variable in a number of expressions, remember you can do:
(lldb) expr TypeOfClass *$class = (TypeOfClass *) <Address From Frame Variable>
and then just use $class in your subsequent expressions. If you got super-motivated, you could even write a Python command that automates these steps...

Related

lldb in xcode detects integer called I to be a complex number

I have a C code, within which an int I gets declared and initialized. When I'm debugging within xcode, if I try to print the value of I, xcode tries to find a complex number:
(lldb) p I
error: <lldb wrapper prefix>:43:31: expected unqualified-id
using $__lldb_local_vars::I;
^
<user expression 3>:1760:11: expanded from here
#define I _Complex_I
^
<user expression 3>:7162:20: expanded from here
#define _Complex_I ( __extension__ 1.0iF )
When I try the same thing (stopping at the same exact line in the code) in the command line, without using xcode, it works fine:
(lldb) p I
(int) $0 = 56
I'm loading the following libraries:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
which shouldn't even include complex numbers, no? I definitely don't have a macro that defines I to be the complex variable. The one I run in xcode, I compile with the default xcode tools. The one I run in the command line, I use gcc. Is this the difference, somehow? Is xcode including more libraries than I ask it to? Why is this happening and how can I prevent it?
Edit: I should also add that the variable explorer in xcode shows the value of I correctly, as an integer.
$__lldb_local_vars is an artificial namespace that lldb injects into the wrapper it sets up for your expression before compilation so that clang can find the frame's local variables and their types. The problem comes as others have noted because we also run the preprocessor when compiling your expression, and your variable name collides with a preprocessor symbol in the expression context.
Normally, debug information does not record macros at all, so you aren't seeing the complex.h version of I from your own use of it in your code. Rather, you are seeing the I macro because something has caused the Darwin module to be imported into lldb's expression context.
That can happen in two ways, either because you explicitly asked for it by running:
(lldb) expr #import Darwin
or because you built this program with -fmodules and your code imported the Darwin module by inserting a statement like the above.
Doing this by hand is a common trick explicitly to make #defines from the module visible to the expression parser. Since it is the visibility of the macro that is causing problems, then you will have to stop doing that if you want this expression to succeed.
OTOH, if lldb is doing this because the debug information recorded that some part of you code imported this module, you can turn off the behavior by putting:
settings set target.auto-import-clang-modules 0
in your ~/.lldbinit and restarting your debug session.
BTW, the p command (or the expression command that p is an alias for) evaluates the text you provide it as a regular expression using the language and in the context of the current frame, with as much access to symbols, defines and the like as lldb can provide. Most users also want to be able to access class information that might not be directly visible in the current frame, so it tends to cast as wide a net as possible looking for symbols and types in order to enable this.
It is a very powerful feature, but as you are seeing sometimes the desire to provide this wide access for expressions can cause conflicting definitions. And anyway, it is way more powerful than needed just to view a local variable.
lldb has another command: frame var (convenient alias v) that prints local variable values by directly accessing the memory pointed to by the debug information and presenting it using the type from the debug info. It supports a limited subset of C-like syntax for subelement reference; you can use * to dereference, . or -> and if the variable is an array [0] etc...
So unless you really do need to run an expression (for instance to access a computed property or call another function), v will be faster and because its implementation is simpler and more direct, it will have less chance of subtle failures than p.
If you also want to access the object definition of some ObjC or Swift local variable, the command vo or frame var -O will fetch the description of the local variable it finds using the v method.
I definitely don't have a macro that defines I to be the complex variable.
It looks like lldb is getting confused somehow, not an issue with your code, but without a MRE it is hard to say.
The one I run in xcode, I compile with the default xcode tools. The one I run in the command line, I use gcc. Is this the difference, somehow?
xcode uses "Apple clang" (an old, custom version) with libc++ by default, as far as I know. gcc is quite different and it may not even use libc++.
Having said that, since xcode shows the variable as an integer but lldb does not, it looks like something else is going on.
Is xcode including more libraries than I ask it to?
I don't think so given the program works and Xcode shows the value as an integer.
Why is this happening and how can I prevent it?
Hard to say since it is a closed source tool. Try to make an MRE. It usually helps debugging the issue and finding workarounds.
By definition a complex number is not defined as simply int
Additionally, as mentioned, complex I is defined in <complex.h>:
To construct complex numbers you need a way to indicate the imaginary
part of a number. There is no standard notation for an imaginary
floating point constant. Instead, complex.h defines two macros that
can be used to create complex numbers.
Macro: const float complex _Complex_I
This macro is a representation of the complex number ā€œ0+1iā€. Multiplying a real floating-point value by _Complex_I gives a complex number whose value is purely imaginary. You can use this to construct complex constants:
3.0 + 4.0i = 3.0 + 4.0 * _Complex_I
Note that _Complex_I * _Complex_I has the value -1, but the type of that value is complex.
_Complex_I is a bit of a mouthful. complex.h also defines a shorter name for the same constant.
Macro: const float complex I
This macro has exactly the same value as _Complex_I. Most of the time it is preferable. However, it causes problems if you want to use the identifier I for something else. You can safely write
#include <complex.h>
#undef I
Reference here for GNU implementation
Include this header file (or similar from your environment), and no need to define it yourself

Disable LLDB restoring state whenever a function called within debugger is crashed

I'm debugging a C project using LLDB debugger.
I'm attaching the debugger to a program and then calling some functions within the debugger, which are expected to crash. I wanted to know where this function crashes.
The problem is - since the function is called from within the debugger, once the function has crashed the debugger resets the state back to the state before calling the function. I don't want this, any idea how to disable this?
This is the message I get from the lldb debugger
Thanks
You can get lldb to preserve the state of a thread when an expression crashes in two ways.
1) If you want to ALWAYS stop in the crashed state when expressions crash, set the setting target.process.unwind-on-error-in-expressions to false:
settings set target.process.unwind-on-error-in-expressions false
either in the command line or in your ~\.lldbinit file.
BTW, for this reason, if you are using the lldb SB API's for scripting or you're writing your own debugger GUI and you need to call a function for some purpose, it's a good idea to explicitly override this setting when calling functions. Use the SBExpressionOptions.SetUnwindOnErrors method for this. Otherwise, your users might end up staring at a crash in an expression they did not call...
2) You can do it on a per-expression basis using:
expr -u 0 -- <expression>
Note, if you do this often, you can make an alias for this. Something like:
command alias pu expr -u 0 --
Then just do:
pu <expression>
While stopped at an expression crash, you can examine the stack, local variables, call other expressions, etc just as you would at a normal stop in lldb. When you are done with this investigation and want to return the thread to the state it was in prior to calling the expression, use the command:
thread return -x
Calling expressions on a thread nests; you can call an expression, stop when it crashes, call another expression that crashes, stop when it crashes, etc... thread return -x will unwind the youngest expression crash.
On a related note, you can also set breakpoints in a function that you call in the expression parser, hit the breakpoint and then step through the rest of the expression evaluation. That is also not on by default, but is controlled by the -i flag to expr like:
expr -i 0 -- <expression>
When you are done examining the code you've called, you can either use thread return -x to wipe the expression evaluation from the thread stack, or you can continue and the expression will finish evaluating and the result will be printed.
This trick is quite handy for watching how functions behave with odd inputs, etc.

Reading variables while debugging with GDB (C)

I am beginner with GDB debbuging. I need read variables in GDB, I use the command info variable and get this information:
0x000007c4 variable1.0
0x000007c8 variable2.1
I set a breakpoint inside the variables function and these are defined how type long *. How can I read the value inside these correctly? I tried with show, display, print $variable1, p/x variable and so on commands.
Sorry for my grammar, i am not native speaker.
To view the contents of memory use gdb's x/FMT ADDRESS command e.g. x/d 0x000007c4 (to display an integer sized object from address 0x000007c4 and format it in decimal).
The info variables command in gdb will list all global and static variables and their program addresses. You don't describe the language or implementation you're using, but in C the variable name "variable1.0" is not valid. Therefore it must have been created by some link editor or the compiler in a post-process. Therefore the symbol may not exist in debug information and is only accessible by directly viewing the contents of memory, which is why the gdb p command doesn't work (there is no valid expression to show you that variable because it's not a variable, but just a symbol at an address).

When does macro substitution happen in C

I was reading the book "Compilers: Principles, Techniques, and Tools (2nd Edition)" by Alfred V. Aho. There is an example in this book (example 1.7) which asks to analyze the scope of x in the following macro definition in C:
#define a (x+1)
From this example,
We cannot resolve x statically, that is, in terms of the program text.
In fact, in order to interpret x, we must use the usual dynamic-scope
rule. We examine all the function calls that are currently active, and
we take the most recently called function that has a declaration of x.
It is to this declaration that the use of x refers.
I've become confused reading this - as far as I know, macro substitution happens in the preprocessing stage, before compilation starts. But if I get it right, the book says it happens when the program is getting executed. Can anyone please clarify this?
The macro itself has no notion of scope, at least not in the same sense as the C language has. Wherever the symbol a appears in the source after the #define (and before a possible #undef) it is replaced by (x + 1).
But the text talks about the scope of x, the symbol in the macro substitution. That is interpreted by the usual C rules. If there is no symbol x in the scope where a was substituted, this is a compilation error.
The macro is not self-contained. It uses a symbol external to the macro, some kind of global variable if you will, but one whose meaning will change according to the place in the source text where the macro is invoked. I think what the quoted text wants to say is that we cannot know what macro a does unless we know where it is evoked.
I've become confused reading this - as far as I know, macro substitution happens in preprocessing stage, before compilation starts.
Yes, this is how a compiler works.
But if I get it right, the book says it happens when the program is getting executed. Can anyone please clarify this?
Speaking without referring to the book, there are other forms of program analysis besides translating source code to object code (a.k.a. compilation). A C compiler replaces macros before compiling, thus losing information about what was originally a macro, because that information is not significant to the rest of the translation process. The question of the scope of x within the macro never comes up, so the compiler may ignore the issue.
Debuggers often implement tighter integration with source code, though. One could conceive of a debugger that points at subexpressions while stepping through the program (I have seen this feature in an embedded toolchain), and furthermore points inside macros which generate expressions (this I have never seen, but it's conceivable). Or, some debuggers allow you to point at any identifier and see its value. Pointing at the macro definition would then require resolving the identifiers used in the macro, as Aho et al discuss there.
It's difficult to be sure without seeing more context from the book, but I think that passage is at least unclear, and probably incorrect. It's basically correct about how macro definitions work, but not about how the name x is resolved.
#define a (x+1)
C macros are expanded early in the compilation process, in translation phase 4 of 8, as specified in N1570 5.1.1.2. Variable names aren't resolved until phase 7).
So the name x will be meaningfully visible to the compiler, not at the point where the macro is defined, but at the point in the source code where the macro a is used. Two different uses of the a macro could refer to two different declarations of variables named x.
We cannot resolve x statically, that is, in terms of the program text.
We cannot resolve it at the point of the macro definition.
In fact, in order to interpret x, we must use the usual dynamic-scope
rule. We examine all the function calls that are currently active, and
we take the most recently called function that has a declaration of x.
It is to this declaration that the use of x refers.
This is not correct for C. When the compiler sees a reference to x, it must determine what declaration it refers to (or issue a diagnostic if there is no such declaration). That determination does not depend on currently active function calls, something that can only be determined at run time. C is statically scoped, meaning that the appropriate declaration of x can be determined entirely by examining the program text.
At compile time, the compiler will examine symbol table entries for the current block, then for the enclosing block, then for the current function (x might be the name of a parameter), then for file scope.
There are languages that uses dynamic scoping, where the declaration a name refers to depends on the current run-time call stack. C is not one of them.
Here's an example of dynamic scoping in Perl (note that this is considered poor style):
#!/usr/bin/perl
use strict;
use warnings;
no strict "vars";
sub inner {
print " name=\"$name\"\n";
}
sub outer1 {
local($name) = "outer1";
print "outer1 calling inner\n";
inner();
}
sub outer2 {
local($name) = "outer2";
print "outer2 calling inner\n";
inner();
}
outer1();
outer2();
The output is:
outer1 calling inner
name="outer1"
outer2 calling inner
name="outer2"
A similar program in C would be invalid, since the declaration of name would not be statically visible in the function inner.

C Macro to Override Variable Assignment with Function Call

Calling all C macro gurus...
Is there any way to write a C macro that will replace something like this:
my_var = 5;
with this:
setVar(&my_var, 5);
In other words, can I write a C macro that will override assignments for a specific variable (in the above example, my_var) and instead pass it to a function whose job it is to set that variable? If possible, I'd like to be able to hook into assignments of a specific variable.
EDIT: After thinking about this some more, I'm not sure it could be done. Even if you can come up with a macro to do it, setVar wouldn't necessarily know the type of the variable its setting, so what would be the type of its second argument?
EDIT: The reason I'd like to hook assignments of specific variables is for use in a primitive debugger for some specialized embedded C code. It would be nice to be able to have a "watch list", essentially like you have in an IDE. My first instinct was to try to hook variable assignments with a C macro so you could just drop the macro into your code and have that variable "watched", but then again I've never really written a debugger before so maybe I'm going about that all wrong.
Not with the standard preprocessor. It cannot change the parsing of the file, only replace proper names with a piece of code (and "=" isn't valid in a name).
If you're feeling adventurous, you can try to replace the executable "cpp" with a small script which pre-processes the source code. But that might wreck havoc with the debugging information (file name and, if you're replacing one line of code with several, with line number information, too). The script would call "sed"`:
sed -e 's/my_var\s*=\s*([^;]+);/MY_VAR(my_var, $1);/' file.c > file_tmp.c
But your best bet is probably to put this into a script and simply run it on all your sources. This will change the code and you'll see what is happening in your debugger.
#define setVar(_left_, _right_) *(_left_) = _right_

Resources