📜 ⬆️ ⬇️

Debugging a Java application that cannot be stopped. We catch exotics with the most accessible means - BTrace approach


Java applications - this means that in the modern Java world the opportunity to meet this percentage by 90% or even more (consider the most common environments, HotSpot based JVM version from 1.6)
which cannot be stopped - the application is working, and for one reason or another it cannot be restarted
Exotic - something such that it does not happen every day to catch a head (a certain sequence of calling methods, outlandish combinations of parameter values, ...)
available means - free of charge, efficient, effective, easy, simple, etc., etc. This article describes the wonderful tool BTrace kenai.com/projects/btrace

And of course nothing has been specifically added to the Java application code regarding debugging tools ...


')
This article is essentially a continuation of the post “Debugging a Java application when it does not wait at all - welcome to the InTrace approach” habrahabr.ru/post/219661 , which showed how to get into an already running application and build a fairly detailed execution trace. That there is a very useful skill, but in real life, sometimes, there are cases when an incomprehensible behavior jumps with a probability of 1 per 1,000, or even worse, and try to find it in tons of traces.
Therefore, for example, we take a simple program (file excitement / Coin.java) and we will collect “exotic” on the fly.

package excitement; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Random; public class Coin { public void head() { } public void tail() { } public static void main(String... args) throws Exception { System.out.println("  Enter  ..."); new BufferedReader(new InputStreamReader(System.in)).readLine(); Random rand = new Random(); for (int count = 0; count < 1000; ++count) { if (rand.nextInt(2) > 0) { new Coin().head(); } else { new Coin().tail(); } } System.out.println("  !"); } } 


Compile
 javac excitement/Coin.java 


And run
 javac excitement.Coin 


It's easier nowhere, right? )

For exotics, I’ll take the exciting question: “How many times in a row will an eagle and tails go out the most, and also how many times will they just fall out?” This is a rand.nextInt (2) test. What are the predictions? Bets are accepted ...

Get the answer will help very well-known and, among other things, just a great tool BTrace kenai.com/projects/btrace , repeatedly mentioned on Habré in comments, but unfortunately never described hitherto in posts.

To launch it is worth considering a couple of ways:
1) command line lovers - console utility downloaded from kenai.com/projects/btrace/downloads/directory/releases/release-1.2.4 (latest available version)
and run as
 btrace <PID> TracingScript.java 

Where
PID is the process identifier (obtained, for example, via jps)
TracingScript.java - a tracing script, with which a more intimate acquaintance will be a little further

2) window lovers are encouraged to use the VisualVM plugin in visualvm.java.net/download.html . Why go to Tools-> Plugins-> Available Plugins, click BTrace Workbench and press “Install”, carefully read the license (although who reads them), okay, so be it, without the slightest hesitation, we agree to this and subsequent windows for everything . And now, after successful installation, in the context menu of the process of interest, a new item “Trace Application ...” has appeared in VisualVM



BTrace does its job by relying on the algorithm described in a very Java-like script (you can also use D-scripts). Very similar - because it’s like Java itself, but still because BTrace does not change the execution of the program being traced (I mean, even so, it tries not to modify its behavior, only to receive information on the execution following the format “ read-only ”), you have to forget about a lot of java things (starting with the creation of new objects and ending with many more, see kenai.com/projects/btrace/pages/UserGuide BTrace Restrictions) and use the tools provided directly by BTrace.

And now the script (file TracingScript.java)

 import com.sun.btrace.annotations.*; import static com.sun.btrace.BTraceUtils.*; @BTrace //     public class TracingScript { @Property //    " "  MBean JMX (jconsole, VisualVM, ...) private static long tailCount; @Property(name="Total head count is") //    JMX private static long headCount; @Property private static long maxHeadSequence = 1; @Property private static long maxTailSequence = 1; @Property private static long sequence = 1; @Property private static long prevId = -1; @OnMethod(clazz = "excitement.Coin", //      excitement  Coin method = "head", // c  head location = @Location(Kind.RETURN)) //     public static void onHead() { ++headCount; sequence = prevId == 0 ? sequence + 1 : 1; if (sequence > maxHeadSequence) maxHeadSequence = sequence; prevId = 0; } @OnMethod(clazz = "excitement.Coin", method = "tail", location = @Location(Kind.RETURN)) public static void onTail() { ++tailCount; sequence = prevId == 1 ? sequence + 1 : 1; if (sequence > maxTailSequence) maxTailSequence = sequence; prevId = 1; } @OnExit //     public static void onexit(int code) { println(strcat("total heads:", str(headCount))); // -            println(strcat("total tails:", str(tailCount))); println(strcat("max tail sequence:", str(maxTailSequence))); println(strcat("max head sequence:", str(maxHeadSequence))); } } 


In the end, we run this script, click "Enter" in the program waiting for the coins to be thrown and get (from someone both, and I did this):

total heads:531
total tails:469
max tail sequence:9
max head sequence:8

In general, heads and tails fell out 8 and 9 times in a row (although I had 10-11 times in several launches). Those who wish are invited to independently verify how much the obtained coincides with the results of the formulas of the theory of probability (so as not to stop here in a complex topic regarding the methods of generating such simple random numbers).

Summing up:
BTrace is a pretty powerful tool that allows you to trace very, very wild features on the fly. This article only touches the tip of the iceberg of its chic features (if you wish, at least take it and write a book), the material is given with the aim of teaching the very basics and getting as interested as possible. For those hooked, look in more detail here kenai.com/projects/btrace/pages/UserGuide , first of all, pay attention to the number of annotations and a long list of very, very vital useful examples. But still, do not forget - everything happens at your own peril and risk, because the transformation of Java classes used by BTrac to achieve the goal (penetration) can always play a cruel joke.

And finally, about coins (physics and only) - often the coin is not perfectly balanced (usually the eagle is a bit heavier than tails), so it’s impossible to get a coin and get 50/50 in real life. Be alert, take the side of the coin directly with your mind.
Yes, luck will come with you)

Thank you for attention!

Source: https://habr.com/ru/post/227639/


All Articles