Prevent debuggers to see variable value - java

Is there a way that I can configure properties of my JPA(I am using hibernate as implementation) entity such that no one can see its value while debugging?
The property is transient and I don't want anyone to see it while debugging due to security reasons. The jar/war of my application will be used by third party.

Assuming you're running your program on an Oracle JVM, and allowing people to attach to that JVM via a debugger -- no, you can't hide certain fields.
The interface that the debuggers will use to talk to the Java process is JDI 1, and it gives pretty much all of the information that the JVM has about your code. Specifically:
If a person has an ObjectReference to the object that contains your sensitive data, they can get its ReferenceType.
They can call ReferenceType::allFields to list all of the fields, including transient ones, in the class:
All declared and inherited fields are included, regardless of whether they are hidden or multiply inherited.
Back on the ObjectReference, they can call ObjectReference::getValue(Field) to get the field's value. Note that the documentation doesn't say anything about an IllegalAccessException, or anything like that.
Even if you could lock down certain fields, it wouldn't do you much good; the debugger would be able to see the value when it's in a local variable (either when you read the field, or when you're about to write to it). What you really want is to lock down certain values, not fields. And that's also not in the JDI.
1 Actually JDWP under the hood, but JDI is built on top of that and easier to discuss here.

Related

When should classes be initialised - at load time or at first use?

One can load a class dynamically using this method of java.lang.Class:
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
According to the JavaDoc, the second parameter is used to control the timing of class initialization (execution of static initialization code). If true, the class is initialized after loading and during the execution of this method; if false, initialization is delayed until the first time the class is used.
Now, I understand all that, but the docs don't say how to decide which strategy to use. Is it better to always do initialization immediately? Is it better to always delay it to first use? Does it depend on the circumstances?
Yes, it depends on circumstances, but usually it is preferred to just let classes be loaded and initialized on first use.
Cases when you might want to early initialize them (e.g. by calling forName() for them):
Static initialization blocks might perform checks for external resources (e.g. files, database connection), and if those fail, you don't even want to continue the execution of your program.
Similar to the previous: loading external, native libraries. If those fail (or not suitable for the current platform), you might want to detect that early and not continue with your app.
Static initializaiton blocks might perform lengthy operations and you don't want to have delays/lags later on when they are really needed, you can initialize them early or on different, background threads.
If you have static configuration files where class names are specified as text, you might want to initialize/load them early to detect configuration errors/typos. Such examples are logger config files, web.xml, spring context etc.
Many classes in the standard Java library cache certain data like the HTTPUrlConnection caches the HTTP user agent returned by System.getProperty("http.agent"). When it is first used, its value will be cached and if you change it (with like System.setProperty()), the new value will not be used. You can force such caching if you initialize the proper classes early, protecting them to be modified by the code later on.
Cases when you should not initialize early:
Classes which might only need in rare cases, or they might not even be needed at all throughout the run of your application. For example a GUI application might only show the About dialog when the user selects the Help/About menu. Obviously no need to load the relevant classes early (e.g. AboutDialog) because this is a rare case and in most runs the user will not do this / need this.

Accessing "AllocatedFrom" compartment from Rhapsody java api

I need to customise a generic Internal block diagram to show customer specific variants. A simple tag based discrimination mechanism is used to suppress non relevant flows and allocated operations.
I have written a Java plug-in to iterate over the IBD’s encapsulated IRPGraphElements, examining their associated type and acting appropriately.
Manipulation of the flows is working fine, but I am having a lot of problems with the allocated operations – in summary I have 2 problems…
I cannot get a handle to the “AllocatedFrom” compartment
And therefore I cannot get to the IRPCollection containing the references to the actual operations.
Problem 1.
I have examined both the Rhapsody Java api documentation (!!!) and Java objects at runtime trying to discover the appropriate method(s) to invoke.
As it is a purely presentational issue (I do not want to suppress underlying allocations between model elements) I guess it is some kind of graphical property & I had thought it would be ObjectModelGe oriented.
I have looked at the properties mentioned in the Diagram package of the SysML profile.
Within General::Graphics I can see the AdditionalCompartments property mentions (amongst other things) AllocatedFrom
However within ObjectModelGe::Object I see that the Compartments property only mentions Operation – do I need to add AllocatedFrom to this property?
Problem 2.
Even if I get access to the compartment I am not sure what methods will be available to access the collection – there appears no interface defined for compartments. Looking in the .sbs file I can see that it is of type IRPYRawContainer but I cannot find any documentation on this.

Show passed parameter values when walking the stack

I am attempting to write Java code that will walk the stack and print not only the method names/line numbers, but also the values that were passed in as parameters to those methods. I was able to get at StackTraceElement objects (http://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html) for each frame as returned by Thread.getStackTrace() (http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace%28%29), but this class doesn't expose the detail that I need.
Is there another approach to getting access to the stack frames / activation records that would give me the details on what was passed to each method?
You may be able to do this if you implement the JPDA (debugger API) but I doubt that you want to do that. (The performance implications could be significant, apart from anything else.)
As far as I'm aware, without that level of invasiveness, you won't be able to get at parameter values (or any other local variable values within a particular stack frame) via reflection.
Sorry for the answer to be negative, but without either that or something like AOP which you've already said you can't use, you're out of luck.

how can I get the History of an object or trace an Object

I have a requirement, where support in my application a lot of processing is happening, at some point of time an exception occrured, due to an object. Now I would like to know the whole history of that object. I mean whatever happened with that object over the period of time since the application has started.
Is this peeping into this history of Object possible thru anyway using JMX or anything else ?
Thanks
In one word: No
With a few more words:
The JVM does not keep any history on any object past its current state, except for very little information related to garbage collection and perhaps some method call metrics needed for the HotSpot optimizer. Doing otherwise would imply a huge processing and memory overhead. There is also the question of granularity; do you log field changes only? Every method call? Every CPU instruction during a method call? The JVM simply takes the easy way out and does none of the above.
You have to isolate the class and/or specific instance of that object and log any operation that you need on your own. You will probably have to do that manually - I have yet to find a bytecode instrumentation library that would allow me to insert logging code at runtime...
Alternatively, you might be able to use an instrumenting profiler, but be prepared for a huge performance drop when doing that.
That's not possible with standard Java (or any other programming language I'm aware of). You should add sufficient logging to your application, which will allow you to get some idea of what's happened. Also, learn to use your IDE's debugger if you don't already know how.
I generally agree with #thkala and #artbristol (+1 for both).
But you have a requirement and have no choice: you need a solution.
I'd recommend you to try to wrap your objects with dynamic proxies that perform auditing, i.e. write all changes that happen to object.
You can probably use AspectJ for this. The aspect will note what method was called and what are the parameters that were sent. You can also use other, lower level tools, e.g. Javasist or CgLib.
Answer is No.JVM doesn't mainatain the history of object's state.Maximum what you can do you can keep track of states of your object that could be some where in-memory and when you get exception you can serialize that in-memory object and then i think you can do analysis.

cool debugging of object

I just had an idea that I wonder whether is possible in java. Let's say when doing debugging using eclipse or netbeans, you could record an object and save it. Then when going through the second round of debugging, save the object again. Now you could compare the first object recorded with the second object for all properties and find out any differences. Is this possible?
You can do this in plain Java code (assuming your objects are Serializable), but I don't think any debuggers have this feature built-in.
It would simply be a case of serialising the first object during the debugging run (which if you had a static method to do so, you could generally call from the debugger) and saving it somewhere. Then, during the second run, call another method to reconstitute the object from it's serialised form - and then compare the objects (either with their equals() methods, or some more bespoke comparison method).
In practice though I find that whenever I want to do this I just scribble down the relevant properties on a piece of paper and compare them manually. Rarely am I looking at thousands and thousands of properties that might change between a run; if you think about the symptoms you're seeing and the behaviour of your object, you can normally have a very good idea of what might be changing before you even fire up the debugger, and then use the latter to confirm your hypothesis and backtrack to see where the value "went wrong".
Give your object a useful toString() method and then use unit tests to compare the result with what you expect.
But I agree: The wire protocol for remote debugging can serialize any object, so it should be possible to write a program that does this automatically.
OTOH, objects which aren't meant to be serialized can be dangerous. If you accidentally use this on a classloader, you'll get all objects and classes and everything back as one big lump. So you need a way to stop the serialization to make sure it can't run havoc in a deep object tree.
On top of that, I'd like a feature to save the current state of the app and be able to go back in time.
I don't think any debugger can save object to compare them later. What you can do though is to create a watch variable on the variable, but wrap it with the ToStringBuilder() of the apache commons and dump it in the console, like so:
System.out.println(ToStringBuilder.reflectionToString(object));
Each time the breakpoint is reached, the content of the object will be shown in the console. You can even see the private data.
Therefore, you do not need to modify the toString() method of the object directly (this is useful for library object for example). You can then compare the output of your two passes.

Categories