DebugBreak equivalent in Java? - java

I'm looking for a way to break into the debugger from Java code, without setting a breakpoint in the IDE.
In Win32 there was DebugBreak(), in C# there's DebugBreak() Equivalent in C#, but I can't find anything in Java.
What I'm trying to do: say I have a wait with a 30s timeout, but in normal conditions that wait should always be <1s. I'd like to use ByteMan or something similar to wait with 1s timeout first, and break into the debugger if that wait timed out.

Not a direct answer to your question but in most IDE's you can set conditional breakpoints.
This would require you to set a timestamp variable in your code before the timeout and test its value in your breakpoint, after the timeout. You would trigger your breakpoint conditional if the delta is greater than your threshold.

The poster of this question has done exactly what I was looking for: Secure Debugging for Production JVMs
It reproduces the best feature of DebugBreak, that is you can attach the IDE to your program only after the "breakpoint" is hit.

I created this class
import com.sun.jna.Library;
public interface Kernel32 extends Library {
public void OutputDebugStringA(String Text);
public void DebugBreak();
}
then used it like this:
Kernel32 lib = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
lib.OutputDebugStringA("just before DebugBreak\n");
lib.DebugBreak();
and that's it. It calls native function
void WINAPI DebugBreak(void);
inside Kernel32.dll
You also need the jar file jna-4.4.0.jar

for easier situation inside IDE use also this example with breakpoint in body, poor mans conditional... (sorry for c# format)
if (lineNumber==6502)
{
System.out.println("BREAK"); //breakpoint here
}

Currently (as of 2021) you cannot accomplish this in Java in a way as convenient as DebugBreak is in C#.
The best you can do in Java is throw a custom runtime exception (say, class DebugBreakException extends RuntimeException) and pray that you have also remembered to add an "exception breakpoint" which breaks whenever this exception is thrown, even if the exception is handled.
Immediately after your code throws this exception, it catches it and dumps a message saying that this particular exception occurred.
If this message ever appears in the log, and yet your debugger did not break, then you know you forgot to add the necessary "exception breakpoint." (In other words, you have to pray that if this message ever gets logged, it will be noticed by someone.)
You can also be extra smart about it and add some code which checks how many milliseconds have elapsed from the moment the exception was thrown until it was caught; if more than, say, 10 milliseconds elapsed, then most probably there was a break into the debugger, so the logging of the message can be skipped. If the exception was caught within fewer than 10 milliseconds, then the debugger probably did not break, so you can proceed with logging the message.
It goes without saying that besides simply logging a message you can try to take as many additional measures as you can, like produce a beep, turn on a lamp, send an email to yourself, bang a gong, fry a motherboard, whatever it takes.

Related

How to deal with: Call to 'Thread.sleep()' in a loop, probably busy-waiting

Guys how to deal with such code and warning?
private void listenOnLogForResult() {
String logs = "";
int timeCounter = 1;
while (logs.isEmpty()) {
try {
timeCounter++;
Thread.sleep(2000); // Wait 2 seconds
} catch (InterruptedException e) {
log.error(e.getLocalizedMessage(), e);
}
if (timeCounter < 30) {
logs = checkLogs()
} else {
logs = "Time out";
}
}
}
I need to pause current thread for 2 seconds to wait file to be filled, but my Intelij Rise an issue here.
And also I am getting error from sonar:
SonarLint: Either re-interrupt this method or rethrow the "InterruptedException".
I've tried already with many ExecutorService, but it is always run in seperate thread, and I need to pause current one.
Please help..
The busy-waiting warning
This is a warning coming from intellij that is dubious, in the sense that what you're doing is often just straight up required. In other words, it is detecting a pattern that is overused, but whose usage cannot be reduced to 0. So, likely the right solution is to just tell intellij to shut up about it here.
The problem it is looking at is not that Thread.sleep. That is not the problem. However, intellij's detector of this pattern needs it to find this case, but it is not what it is complaining about, which might be a little hard to wrap your head around.
What IntelliJ is worried about, is that you're wasting cycles continually rechecking log.isEmpty() for no reason. It has a problem with the while aspect of this code, not the sleep. It would prefer to see code where you invoke some sort of logs.poll() method which will just wait until it is actively woken up by the act of new logs appearing.
If this is all running within a single java process, then you can indeed rewrite this entire system (which includes rewrites to whatever log is here, and a complete re-imagining of the checkLogs() method: Instead of going out and checking, whatever is making logs needs to wake up this code instead.
If it's not, it is likely that you need to tell intellij to shut it: What you are doing is unavoidable without a complete systems redesign.
The re-interrupt warning
You have some deplorable exception handling here.
Your exception handling in general
Do not write catch blocks that log something and keep moving. This is really bad error handling: The system's variables and fields are now in an unknown state (you just caught and logged some stuff: Surely that means you have no idea what conditions have occurred to cause this line of execution to happen!), and yet code will move right along. It is extremely likely that 'catch exceptions and just keep going' style code results in more exceptions down the line: Generally, code that operates on unknown state is going to crash and burn sooner rather than later.
Then, if that crash-and-burn is dealt with in the same fashion (catch it, log it, keep going), then you get another crash-and-burn. You end up with code that will, upon hitting a problem, print 186 exceptions to the log and they are all utterly irrelevant except the first one. That's bad yuyu.
You're also making it completely impossible for calling code to recover. The point of exceptions is that they need to bubble upwards endlessly: Either the exception is caught by code that actually knows how to deal with the problem (and logging it is not dealing with it!), which you are making impossible, or, the code exception should bubble up all the way to the entry-point handler which is the right place to log the error and abort the entry-point handler.
An entry-point handler is a generic module or application runner; out of the box, the code baked into java.exe itself that ends up invoking your psv main() method is the most obvious 'entry point runner', but there's more: Web frameworks will eventually invoke some code of yours that is supposed to handle a web request: That code of yours is analogous to psv main(): It is the entry-point, and the code in the web framework that invokes it, is the entry-point runner.
Entry-point runners have a good reason to catch (Throwable t), and to spend their catch block primarily logging it, though they should generally log a lot more than just the exception (a web handler should for example log the request details, such as which HTTP params were sent and which path request it was, maybe the headers, etc). Any other code should never do this, though.
If you have no idea what to do and don't want to think about what that exception might mean, the correct 'whatever, just compile already javac' code strategy is to add the exception type to your throws line. If that is not feasible, the right code in the catch block is:
} catch (ExceptionIDoNotWantToThinkAboutRightNow e) {
throw new RuntimeException("Uncaught", e);
}
This will ensure that code will not just merrily continue onwards, operating on unknown state, and will ensure you get complete details in logs, and ensures that calling code can catch and deal with it if it can, and ensures that any custom logging info such as the HTTP request details get a chance to make it to the logs. Win-win-win-win.
This case in particular: What does InterruptedEx mean?
When some code running in that java process invokes yourThread.interrupt(), that is how InterruptedException can happen, and it cannot possibly happen in any other way. If the user hits CTRL+C, or goes into task manager and clicks 'end process', or if your android phone decides it is time for your app to get out as the memory is needed for something else - none of those cases can possibly result in InterruptedExceptions. Your threads just get killed midstep by java (if you want to act on shutdowns, use Runtime.getRuntime().addShutdownHook). The only way is for some code to call .interrupt(), and nothing in the core libs is going to do that. Thus, InterruptedException means whatever you think 'call .interrupt() on this thread' means. It is up to you.
The most common definition is effectively 'I ask you to stop': Just shut down the thread nicely. Generally it is bad to try to shut down threads nicely if you want to exit the entire VM (just invoke System.shutdown - you already need to deal with users hitting CTRL+C, why write shutdown code twice in different ways?) - but sometimes you just want one thread to stop. So, usually the best code to put in a catch (InterruptedException e) block is just return; and nothing else. Don't log anything: The 'interrupt' is intentional: You wrote it. Most likely that is nowhere in your code base and the InterruptedException is moot: It won't ever happen.
In your specific code, what happens if your code decides to stop the logger thread is that the logger thread will log something to the error logs, and will then shortcut its 2 second wait period to immediately check the logs, and then just keeps going. That sounds completely useless.
But, it means whatever you want it to. If you want an ability for e.g. the user to hit a 'force check the logs right now' button, then you can define that interrupting the logging thread just shortcuts the 2 seconds (but then just have an empty catch block with a comment explaining that this is how you designed it, obviously don't log it). If you ALSO want a button to 'stop the logging thread', have an AtomicBoolean that tracks 'running' state: When the 'stop log-refreshes' button is hit, set the AB to 'false' and then interrupt the thread: Then the code you pasted needs to check the AB and return; to close the thread if it is false.
fun sleep(timeMillis: Long) {
val currentTimeMillis = System.currentTimeMillis()
while (true) {
if (System.currentTimeMillis() - currentTimeMillis >= timeMillis) {
break
}
}
}
and use this in your method(It's code by koltin,you should trans to java)

How to create a breakpoint programmatically on Android

In C# I can write:
if(Debugger.IsAttached)
Debugger.Break();
This has no effect when the program is not being debugged. When a debugger is attached, it behaves like a breakpoint that can never be turned off. How can I achieve similar effect on Android?
Or maybe I should not focus on breakpoints at all. What I really want is to have no consequence in regular use (a generic error message will be shown to the user), but have the source of error become obvious the moment a dev will start looking at it. I've tried assert, but it's a sub-project that's compiled to release flavor most of the time and I can't rely on someone remembering to switch it to debug.
I think that Debug.isDebuggerConnected() is what you are looking for. This will return true only if the app is started with debugger attached and false otherwise, no matter of build type or flavor. Unfortunately, I don't think that you can stop the execution programatically, but with the above instruction you should be able to display an error message or throw an exception. Personally, I'm thinking to something like this:
if (Debug.isDebuggerConnected()) {
// throw an exception for the developer with a detailed message
} else {
// show the general error message to the user with a dialog/toast
}
I was also hoping that this could be done, but I've not found any reasonable way to programmatically cause the debugger to breakpoint. What I've done to get around this problem is to create a breakpoint class with a method call "br". When I'm debugging, I'll set a breakpoint in the "br" method. After that, whenever my code calls the "br" method, the debugger stops. I then step out of that method and then inspect the state of the program where the "br" method was called. Hope that helps!
If i clear understand you - try this snippet of code:
if (BuildConfig.DEBUG) {
// Your, developers behavior
}
else {
// release behavior
}

Debug-Execution Adventure

I debugged my java code. It didn't give any errors.But when i executed it (it isn't giving errors either, but) the code didn't successfully terminate. This is very funny. But is that even possible?
sure, when the slowdown introduced by debugger does mask some race condition, but this normally only applies to multi-threading or networking code.
Yes it is possible that code works when debugging and doesn't work when running. Two possible reasons I can think of right now are
Concurrency in case of multithreading: if your debugger stops on a breakpoint, timing between multiple threads can change which can influence the behaviour
When debugging, you can trigger certain parts of the code multiple times (more than when it has been executed without debugging), like for example via the toString method or via doing inspects or having some watch expression configured
Yes, your code can be syntactically correct (and thus might run without any errors) but may be semantically incorrect.
Assume the following:
public int add( int operand1, int operand2)
{
return operant1 - operand2;
}
This would run without errors but still be incorrect due to logic/implementation error.
So, it IS possible to get wrong results by otherwise smoothly running code.

When is it OK to catch a RuntimeException

On a recent project I recommended catching a RuntimeException within a test harness code and logging it. The code processes a series of inputs from a database, and I do not want the test to stop due to failure of any one input (Null values, Illegal arguments, etc.). Needless to say, my suggestion triggered a passionate discussion.
Is catching any kind of RuntimeException acceptable? If yes, what are other scenarios where it is OK to catch RuntimeExceptions?
You catch RuntimeException for the same reason that you catch any exception: You plan to do something with it. Perhaps you can correct whatever caused the exception. Perhaps you simply want to re-throw with a different exception type.
Catching and ignoring any exception, however, is extremely bad practice.
Unless you can correct a RuntimeException, you don't want to catch it...
...only true from a developers point of view....
you have to catch all exceptions before they reach up to the UI and make your user sad. This means on the "highest level" you want to catch anything that happend further down. Then you can let the user know there was a problem and at the same time take measures to inform the developers, like sending out alarm mails or whatever...
It is basically considered a data/programming error that could not be forseen, thus you want to improve future releases of the software while at the same time take the user by the hand and move on in a controlled manner...
RuntimeException is intended to be used for programmer errors. As such it should never be caught. There are a few cases where it should be:
you are calling code that comes from a 3rd party where you do not have control over when they throw exception. I would argue that you should do this on a case by case basis and wrap the usage of the 3rd party code within your own classes so you can pass back non-runtime exceptions.
your program cannot crash and leave a stack trace for the user to see. In this case it should go around main and around any threads and event handling code. The program should probably exit when such exception occurs as well.
In your specific case I would have to question why you are having RuntimeExceptions occur in the tests - you should be fixing them instead of working around them.
So you should guarantee that your code only throws RuntimeExceptions when you want to have the program exit. You should only catch RuntimeExceptions when you want to log it and exit. That is what is in line with the intent of RuntimeExceptions.
You can look at this discussion for some other reasons that people give... I personally haven't found a compelling reason in the answers though.
In my code 99% of my exceptions are derived from runtime_exception.
The reasons I catch exceptions are:
Catch Log and Fix problem.
Catch Log and Generate a more specific exception and throw
Catch Log and rethrow.
Catch Log and Kill operation (discard exception)
User/request initiated action fails.
An HTTP request handler for example. I would rather the requested operation die rather than bring the Service down. (Though preferably the handler has enough sense to return a 500 error code.)
Test case passed/failed with an exception.
All exceptions not in the main thread.
Allowing exceptions to escape a thread is usually badly documented but usually causes program termination (without stack unwinding).
Years ago, we wrote a control system framework and the Agent objects caught runtime exceptions, logged them if they could and continued.
Yes we caught Runtime exceptions including OutOfMemory in our framework code( and forced a GC, and it's surprising how well that kept even quite leaky code running.)
We had code that was doing very mathematical things involving the real world; and from time to time a Not-A-Number would get in due to tiny rounding errors and it coped okay with that too.
So in framework / "must not exit" code I think it can be justifiable. And when it works it's pretty cool.
The code was pretty solid, but it ran hardware, and hardware tends to give screwy answers sometimes.
It was designed to run without human intervention for months at a time.
It worked extremely well in our tests.
As part of the error recovery code, it could resort to rebooting the entire building using the UPS's ability to turn off in N minutes and turn on in M minutes.
Sometimes hardware faults need to power cycled :)
If I remember, the last resort after an unsuccessful power cycle was it sending an email to it's owners, saying
"I tried to fix myself and I can't; the problem is in subsystem XYZ", and included a link to raise a support call back to us.
Sadly the project got canned before it could become self aware :)>
Personally, I've always been told that you want to catch all RuntimeExceptions; however, you also want to do something about the exception, such as running a failsafe or possibly just informing the user that an error occurred.
The last Java project that I worked on had a similar approach, at the very least, we would log the exception so that if a user called complaining about a bug, we could find out exactly what happened and see where the error occurred.
Edit 1: As kdgregory said, catching and ignoring are two different things, generally, people are opposed to the latter :-)
We all know that checked exceptions and RuntimeExceptions are the two categories of exceptions. It is always suggested that we handle (either try-catch or throw) the checked exceptions because they are the programming conditions where unfortunately programmer can not to do anything on its own;
Like FileNotFoundException it is not the programmer who puts files on user's drive if program is actually trying to read the file 1.txt which is supposed to be there on f:\ of user with the statements:
File f11 = new File("f:\\1.txt");
FileInputStream fos = new FileInputStream(f11);
If the file is found it's all ok, but what happens in the other case if the file is not found is that, program crashes down with 0 error from the user. In this scenario programmer did not do anything wrong. This could be a checked exception which must be caught for the program to continue running.
Let me also explain the second scenario with which the concept of RuntimeException will be clear. Consider following code:
int a = {1,2,3,4,5};
System.out.println(a[9]);
This is poor coding which generates the ArrayIndexOutOfBoundsException. Which is an example of RuntimeException. So programmer should not actually handle the exception, let it crash the program, and later fix the logic.
You catch RuntimeException when you want to process it. Maybe you want to rethrow it as a different exception or log it to a file or database, or you want to turn on some exception flag in the return type, etc.
You catch RuntimeExceptions (in any language: unexpected exceptions/“all” exceptions) when your program is doing multiple subtasks and it makes sense to complete every one you can rather than stopping on the first unexpected situation. A test suite is a fine situation to do this — you want to know which of all the tests failed, not just the first test. The key characteristic is that each test is independent of all the others — it doesn't matter whether a previous test doesn't run because the order is not significant anyway.
Another common situation is a server; you don’t want to shut down just because one request was malformed in a way you didn't expect. (Unless it’s really, really important to minimize the chances of inconsistent state.)
In any of these situations, the appropriate thing to do is log/report the exception and continue with the remaining tasks.
One could vaguely generalize to any exception: it is “appropriate to catch” an exception if and only if there is something sensible to do after catching it: how your program should continue.
If a client can reasonably be expected to recover from an exception, make it a checked exception.
If a client cannot do anything to recover from the exception, make it an unchecked exception.
Here's the bottom line guideline.
From Java Docs. Please read this Unchecked Exceptions — The Controversy

Can I put try / catch around an OS API that crashes?

I use a Windows OS library to manipulate image files. Sometimes it crashes deep inside it for no apparent reason—all the inputs are reasonable and its not a threading issue. The crash is memory A/V.
So, what are the down sides to something like this:
try {
pFoo = OsAPIThatCrashes();
} catch {
pFoo = NULL;
}
Will that even work? We don't use exceptions anywhere else in our code.
For one, while we all like to bash MS for the flaws in their software, IME in 99 out of 100 cases the problem wasn't a bug in the OS, the compiler, or the standard library, but in the code calling it. Whatever Win API you're using - it's tested a lot more thoroughly than most (if not all) code ever using it.
Further, try/catch catches C++ exceptions, not OS exceptions. (Earlier versions of VC did this wrong, but later ones have the right default.) So try/catch won't catch an AV. That said, VC provides ways to catch OS exceptions. I think it's called structured exception handling and centered around __try/__catch, but I'm not sure since I have never used it. However:
Once your application ran into an AV, all bets are off. An AV is just one way for undefined behavior to manifest itself and once you (or the API code, however unlikely that might be) invoked undefined behavior, there's nothing you can assume about the state of your application. You should not continue.
To sum it up: You should try to find out what you did wrong. A good way to do this is trying to boil the problem down to a small piece of example code that reproduces the problem. In 90% of all cases, this will reveal the error. If even a small piece of code reproduced the problem and you still don't know what the problem is, you have a nice repro case to come back with (or to throw at MS support). IME, in 9 of those 10% someone else points out your error, and only the remaining 1% will reveal a bug you didn't make yourself.
Chances are that this won't do any good -- it would only help if the OS API threw an exception that you could catch. If it was doing that, and you weren't catching the exception, you'd normally get an exit from the application, with an error message to the effect that it had exited by throwing an exception that wasn't caught. Unless you're seeing something on that general order, there's very little chance that wrapping the call in a try block will do any good.
Depending on the OS, you might be able to use a native exception handling mechanism to accomplish a bit more -- for example, under Windows, you can catch things like page faults using structured exception handling. Again, it's not entirely clear whether this will do any good though -- if an unhandled exception is the source of the problem, it may help, but if the code has a bug where (for example) value X==10 and value Y == 20 leads to an infinite loop, or something on that order, you're probably going to have to pin down when the code crashes, and assure that never arises.
The internal state of the library is probably bad at this point, so continuing to use it is risky. Best to fix it, crash, or use a different library. Sometimes life just sucks.
While the win32 API is a C library and doesn't use exceptions, MSVC can implement certain things as exceptions (such as division by zero) that aren't required to be done that way (by the C++ standard). So: it depends.
Your best bet is finding out what's causing the problem and fixing that.
You may like to explore Structured Exception Handling. The structured exception handling and termination handling mechanisms are integral parts of the Windows operating system. MSDN reference
try/catch is for C++ exceptions what you need to use is
__try {
} __except(EXCEPTION_EXECUTE_HANDLER) {
}
But all that will do is eat the exception, it won't fix the problem and could leave the library (or your app!) in an inconsistent state. If the exception is a floating point exception, then you have a good chance of ignoring it an moving on, but if it's an access violation, then you may be just delaying the crash.
If you can nail it down to a specific type of exception, you can catch and eat only that type
long WINAPI filter(EXCEPTION_POINTERS * pex)
{
EXCEPTION_RECORD * per = pex->ExceptionRecord;
DWORD dwCode = per->ExceptionCode;
if (EXCEPTION_DATATYPE_MISALIGNMENT == dwCode)
return EXCEPTION_CONTINUE_SEARCH; // let a handler above us deal with it.
else if (EXCEPTION_FLT_DIVIDE_BY_ZERO == dwCode)
return EXCEPTION_EXECUTE_HANDLER; // Eat this one
return EXCEPTION_CONTINUE_SEARCH; // let all the rest on through...
}
__try {
...
} __except(filter(GetExceptionInformation())) {
}

Categories