Breaking into the debugger on iPhone - iphone

For assert macros in my iPhone project, I'm looking for a way to programmatically break into the debugger. On Windows (MSVC++), I can use __debugbreak() for this purpose. Invoking this function will stop my program, launch the debugger, and display a callstack of the line that called __debugbreak().
Is there anything similar to __debugbreak() for the iPhone? I've tried Debugger(), but that gives me a linker error.
Thanks,
Claus

edit
Turns out this also works:
#define Debugger() { raise( SIGINT ) ; }
I think it's the same principle.
I use this:
#define Debugger() { kill( getpid(), SIGINT ) ; }
I think it works
in the simulator and on the device.. no assembly required!

A helpful person on Apple's developer forum gave me the tip to use asm("trap") when running on the device and asm("int3") when running on the simulator. This makes the program break into the debugger if you started your programm in debug mode (Option-Command-Y).
(__builtin_trap() also breaks into the debugger, but you can't continue afterwards. assert(false) terminates the program with a message, but doesn't break into the debugger.)

First Add -DDEBUG to OTHER_CFLAGS on your debug target; this will define the DEBUG symbol when building a debug build.
Then add a simple assert macro to your prefix header:
#ifdef DEBUG
#define MyAssert(val) _MyAssert(val)
#else
#define MyAssert(val) do { } while(0)
#endif
Next create a _MyAssert function in a module somewhere:
#ifdef DEBUG
void _MyAssert(int expression)
{
if (expression == 0) {
NSLog(#"Assertion failed!"); // Place breakpoint here
}
}
#endif
Finally create a breakpoint on the NSLog line.

I just set a breakpoint at the place I want to stop. Xcode remembers breakpoints persistently, so any time I run the app with gdb, it'll stop at that point.
If you want to break on assertion failures, a good place to set a breakpoint is on the function objc_exception_throw, in the Objective-C runtime, which is what actually throws an exception. Use the Run > Show > Breakpoints window and double-click the "Double-click for symbol" row, then type the name.

Is there something wrong with the simple assert() macro? Something like
assert(pointerToTest != nil);
will halt your process at that point if the condition is not true. If running under the debugger, you'll be presented with a stack trace of calls that led to the failed assertion. If you want to trigger it every time you hit a certain code path, you could do
assert(false);
I find these assertions extremely useful for verifying that all IBOutlets are non-nil when a window or view is brought up from a NIB.

If you run your program in debug, your app should launch the debugger when it reaches an invalid assertion.
For it to stop, as Jens Alfke tried to say, you need to enable "Stop on Objective-C Exceptions" (under the Run menu).
For more info about debugging vs. releasing and asserts, read http://myok12.wordpress.com/2010/10/10/to-use-or-not-to-use-assertions/

While an ancient thread, found this while researching same topic for Xcode 7. What solved this for me was a feature called "Create Exception Breakpoint..."
Debug > Breakpoints > Create Exception Breakpoint...
This puts a special breakpoint in the Breakpoint Navigator (under View > Navigators > Show Breakpoint Navigator).
This breaks on the actual throw of the exception:
[ exception raise ]
without terminating your code execution. You can just continue if that is how your code is structured.
Double-clicking the break point marker next to "All Exception" lets you adjust where and how the exception break point stops:

Check out conditional breakpoints:
http://www.cocoabuilder.com/archive/message/xcode/2008/10/22/25358

Related

provideDebugConfigurations not getting called

I am using the vscode-mock-debug git as the basis for my work.
Activation event is OnDebug, although same result
I implement provideDebugConfigurations in my DebugConfigurationProvider and its not getting called.
provideDebugConfigurations(folder: WorkspaceFolder | undefined, token?: CancellationToken): DebugConfiguration[] {
return [...my data in here];
}
the resolveDebugConfiguration (the original from mock-debug) is called, I can set a breakpoint. However the provideDebugConfigurations is never getting reached. build 1.36 of vsce. am I missing something obvious ?
this is the answer from the vscode team: https://github.com/microsoft/vscode/issues/78362
I have investigated this and it is expected behavior.
Namely, provideDebugConfigurations is only called then the debug configurations are needed to generate a launch.jsonfile. If you click on the configure command the provideDebugConfigurations will get nicely called.
However if you do not have a launch.json and you simply press Debug Start, vscode will try to start debugging without using debug configurations, but using one on the fly provided by the resolveDebugConfiguration call.
More about this can be found in our docs https://code.visualstudio.com/api/extension-guides/debugger-extension
Thus closing this as designed.

Debugger.Break(); does not break

I'm using Debug.Break() to track down bugs in my code. I want to insert a "Halt" in the Visual Studio IDE so that I can inspect values.
Now I'm in a situation where the IDE just goes over Debug.Break() without stopping:
_lrNavMeshPath = nParentForLineRenderer.gameObject.AddComponent<LineRenderer>();
if (_lrNavMeshPath == null)
{
System.Diagnostics.Debugger.Break();
}
What might be the reason why the IDE just goes over this line without stopping?
I have set a breakpoint at this line, so I see that this line is called.
Thank you.

Ignore certain exceptions when using Xcode's All Exceptions breakpoint

I have an All Exceptions breakpoint configured in Xcode:
Sometimes Xcode will stop on a line like:
[managedObjectContext save:&error];
with the following backtrace:
but the program continues on as if nothing happened if you click Continue.
How can I ignore these "normal" exceptions, but still have the debugger stop on exceptions in my own code?
(I understand that this happens because Core Data internally throws and catches exceptions, and that Xcode is simply honoring my request to pause the program whenever an exception is thrown. However, I want to ignore these so I can get back to debugging my own code!)
Moderators: this is similar to "Xcode 4 exception breakpoint filtering", but I think that question takes too long to get around to the point and doesn't have any useful answers. Can they be linked?
For Core Data exceptions, what I typically do is remove the "All Exceptions" breakpoint from Xcode and instead:
Add a Symbolic Breakpoint on objc_exception_throw
Set a Condition on the Breakpoint to (BOOL)(! (BOOL)[[(NSException *)$x0 className] hasPrefix:#"_NSCoreData"])
The configured breakpoint should look something like this:
This will ignore any private Core Data exceptions (as determined by the class name being prefixed by _NSCoreData) that are used for control flow. Note that the appropriate register is going to be dependent on the target device / simulator that you are running in. Take a look at this table for reference.
Note that this technique can be adapted easily to other conditionals. The tricky part was in crafting the BOOL and NSException casts to get lldb happy with the condition.
I wrote an lldb script that lets you selectively ignore Objective-C exceptions with a much simpler syntax, and it handles both OS X, iOS Simulator, and both 32bit and 64bit ARM.
Installation
Put this script in ~/Library/lldb/ignore_specified_objc_exceptions.py or somewhere useful.
import lldb
import re
import shlex
# This script allows Xcode to selectively ignore Obj-C exceptions
# based on any selector on the NSException instance
def getRegister(target):
if target.triple.startswith('x86_64'):
return "rdi"
elif target.triple.startswith('i386'):
return "eax"
elif target.triple.startswith('arm64'):
return "x0"
else:
return "r0"
def callMethodOnException(frame, register, method):
return frame.EvaluateExpression("(NSString *)[(NSException *)${0} {1}]".format(register, method)).GetObjectDescription()
def filterException(debugger, user_input, result, unused):
target = debugger.GetSelectedTarget()
frame = target.GetProcess().GetSelectedThread().GetFrameAtIndex(0)
if frame.symbol.name != 'objc_exception_throw':
# We can't handle anything except objc_exception_throw
return None
filters = shlex.split(user_input)
register = getRegister(target)
for filter in filters:
method, regexp_str = filter.split(":", 1)
value = callMethodOnException(frame, register, method)
if value is None:
output = "Unable to grab exception from register {0} with method {1}; skipping...".format(register, method)
result.PutCString(output)
result.flush()
continue
regexp = re.compile(regexp_str)
if regexp.match(value):
output = "Skipping exception because exception's {0} ({1}) matches {2}".format(method, value, regexp_str)
result.PutCString(output)
result.flush()
# If we tell the debugger to continue before this script finishes,
# Xcode gets into a weird state where it won't refuse to quit LLDB,
# so we set async so the script terminates and hands control back to Xcode
debugger.SetAsync(True)
debugger.HandleCommand("continue")
return None
return None
def __lldb_init_module(debugger, unused):
debugger.HandleCommand('command script add --function ignore_specified_objc_exceptions.filterException ignore_specified_objc_exceptions')
Add the following to ~/.lldbinit:
command script import ~/Library/lldb/ignore_specified_objc_exceptions.py
replacing ~/Library/lldb/ignore_specified_objc_exceptions.py with the correct path if you saved it somewhere else.
Usage
In Xcode, add a breakpoint to catch all Objective-C exceptions
Edit the breakpoint and add a Debugger Command with the following command:
ignore_specified_objc_exceptions name:NSAccessibilityException className:NSSomeException
This will ignore exceptions where NSException -name matches NSAccessibilityException OR -className matches NSSomeException
It should look something like this:
In your case, you would use ignore_specified_objc_exceptions className:_NSCoreData
See http://chen.do/blog/2013/09/30/selectively-ignoring-objective-c-exceptions-in-xcode/ for the script and more details.
Here is an alternative quick answer for when you have a block of code e.g. a 3rd part library that throws multiple exceptions that you want to ignore:
Set two breakpoints, one before and one after the exception throwing block of code you want to ignore.
Run the program, until it stops at an exception, and type 'breakpoint list' into the debugger console, and find the number of the 'all exceptions' break point, it should look like this:
2: names = {'objc_exception_throw', '__cxa_throw'}, locations = 2
Options: disabled
2.1: where = libobjc.A.dylibobjc_exception_throw, address = 0x00007fff8f8da6b3, unresolved, hit count = 0
2.2: where = libc++abi.dylib__cxa_throw, address = 0x00007fff8d19fab7, unresolved, hit count = 0
This means it is breakpoint 2. Now in xcode, edit the first breakpoint (before the exception throwing code) and change the action to 'debugger command' and type in 'breakpoint disable 2' (and set 'automatically continue...' checkbox ).
Do the same for the break point after the offending line and have the command 'breakpoint enable 2'.
The all breakpoints exception will now turn on and off so it's only active when you need it.

Is there any way to clear NSLog Output?

I have been googling from last couple of hours for finding that is there any way to clear NSLog output using code or not?
Like we have clrscr() in c. So if we are trying to print something which we want to focus most and there is lots of log printin there we can put that code there and get keep our desire log on top for easy searching. This can be done by putting breakpoint on my NSLog line and than click on clear console. but question is is there a way to achive this programatically?
I found few question on stack overflow but I din't satisfied with answer like this is saying that I can disable log for release mode etc.
Or I can use DLog, ALog or ULog as requirement but my question is different..
Any one can help me in this?
Thanks in advance :)
You can use a conditional breakpoint to simulate it. Define a function like this in your code:
int clear_console()
{
NSLog(#"\n\n\n\n\n\n\n\n");
}
Then, when you want to clear the console just add a breakpoint before the NSLog with this condition:
Condition: 1 > 0
Action: Debugger Command expr (int) clear_console()
Options: Automatically continue after evaluating Check it to skip the pause.
Tested with Xcode 4.3.2 and lldb.
Previous answer:
AFAIK, no, there isn't.
Just in case you're not doing it yet, you can create custom macros to format the output to highlight what you want.
Define macros like this:
#define CLEAR(...) NSLog(#"\n\n\n\n\n\n") /* enough \n to "clear" the console */
#define WTF(...) CLEAR();NSLog(#"!!!!!!!!!!!!!!");NSLog(__VA_ARGS__)
#define TRACE(__message__) NSLog(#">>>>>>>>>>>>>>> %# <<<<<<<<<<<<<<<<<<<", __message__)
Then:
WTF(#"This should't be here object: %#", theObject);
...
TRACE(#"Start Encoding");
...
It's not what you want but it pretty much solves the problem. You'll end up with your own set of macros with custom prefixes easily scannable in the console output.

Suppressing NSLog statements for release? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Do I need to disable NSLog before release Application?
I wonder if someone could help me setup a number of NSLog statements so they print to console when executing in "Debug Mode" but don't print in "Release Mode". I understand I need to add something like DEBUG = 1 to the debug config in Xcode but I can't find where. Also how do I utilise this in my code?
NSLog(#"Print Always");
if(DEBUG) NSLog(#"Print only in debug");
Is there a simple way of doing this?
EDIT_001:
I tried following this but the keys now seem to be only listed under "All Settings", and are presenting as nice names. The one I should be using is GCC_PREPROCESSOR_DEFINITIONS, so I needed to find "Preprocessor Macros", select edit and add DEBUG=1
When you come to use this its simply a case of adding (see below) or some marco to remove the messy #ifdef / #endif tags.
NSLog(#"You always see me?");
#ifdef DEBUG
NSLog(#"Only in DEBUG");
#endif
This is a popular solution:
http://iphoneincubator.com/blog/debugging/the-evolution-of-a-replacement-for-nslog
See comments about using either -DDEBUG=1 or DEBUG=1.
The best solution is not to use NSLog in the first place but instead rely on the debugger.
You can set breakpoints that execute debugger commands to print out anything and you can set the breakpoints to execute the debugger commands but not to stop execution. In practice this works just like NSLog.
By using the debugger to do the logging, you don't have to worry about removing the log statements.
Please have a look at the answers of How to print out the method name and line number and conditionally disable NSLog?. There are some nice macros in there that can be very useful.
I use this:
-(void)debugWinLog
{
NSUserDefaults * defaultsDebug = [NSUserDefaults standardUserDefaults];
theDebugWin = [defaultsDebug boolForKey:#"logger"];
}
Which is called in the awakeFromNib.
It checks the apps plist file for a 1 or 0 for the BOOL entry "logger"
The normal state if off, but when debugging you can then turn it on or off at will in terminal. with the normal defaults write.
The NSlog statments look like:
if ( theDebugWin) {NSLog (#"%#", windowState );}