How to override class files (asm.ClassWriter.getCommonSuperClass)? - bytecode

What I am trying to do?
I am trying to add try/catch block in start and end of a particular method.
Why am I overriding asm.ClassWriter.getCommonSuperClass(String class1,String class2)?
I am using flag COMPUTE_FRAMES, and because of that, asm.ClassWriter.getCommonSuperClass() this class is being called and it is trying to load some classes again using class.ForName(), and saying classNotFoundException. I read somewhere to override this method and make sure it gets these two classes loaded. I got hold of Instrumentation object and got all loaded classes, but there are still some classes which are not loaded and this method throws NullPointer Exception..
Any suggesstions how to override it?
EDITED THE QUESTION BASED ON BELOW RESPONSE
What I understand here is :
1. There is no need to use COMPUTE_FRAMES instead of COMPUTE_MAXS, if I am trying to add a try/catch block for method content.
2. If I want to just add try/catch block for method content,(assume jdk8 only) then i just need to write try/catch block ASM part and rest should fall in place.
For a method which is called from a thread:
public void execute()throws IOException{
//some code
}
Below code should add try/catch block and should not give any java verify error?:
private Label startFinally = new Label();
public void visitMaxs(int maxStack, int maxLocals) {
Label endFinally = new Label();
visitTryCatchBlock(startFinally, endFinally, endFinally, "java/lang/Exception");
visitLabel(endFinally);
visitFrame(F_NEW, 0, null, 1, new Object[]{"java/lang/Exception"});
visitVarInsn(ASTORE, 1);
visitVarInsn(ALOAD, 1);
visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception", "printStackTrace", "()V", false);
visitInsn(RETURN);
}
public void visitCode() {
mv.visitLabel(startFinally);
super.visitCode();
}

When you start having to deal with getCommonSuperClass you are entering the very issue that stack map frames were designed to solve. Instead of letting the verifier do such a common superclass search, the frames derived from information available to the compiler should tell which type to assume and verifying the correctness is cheaper than performing this search.
But, of course, if you use a framework like ASM and let it conveniently calculate all these frames from scratch without the information available to the compiler, you end up doing that expensive operation and even have to assist ASM in case the types are not available to a simple Class.forName call (or you want avoid the loading of the classes).
You should note two important things:
You don’t have to load these classes. This method intentionally provides two strings and expect a result string. If you have meta information available that allow you to determine the common super type based on the name, you can use it
When you use Instrumentation to search for the name among all loaded classes, you might miss the class because it might not have been loaded yet. Even worse, you could get the wrong class in a more complex scenario when classes with the same name have been loaded by different ClassLoaders
At this time you should think about whether adhering to the original intent of using the already known information to generate the right frame is an option. When you instrument a class of a version where stack map frames are mandatory, all frames beside the one required for your exception handler are already present. And for older class files without frames, you don’t need to compute them anyway.
When you chain a ClassReader with a ClassWriter it will not only replicate members and instructions but also the stack map frames, unless you specify COMPUTE_FRAMES which causes ASM to drop all visited frames and recalculate them from scratch. So the first thing to do is to change COMPUTE_FRAMES back to COMPUTE_MAXS and then insert visitFrame calls as needed.
For covering the entire method with one exception handler, we need exactly one frame, for the entry of the handler (assuming there are no branches inside the handler itself). We already know that the operand stack consist of a sole reference to the exception itself—that’s always the case for exception handlers. Since the guarded code spans the entire method, no additional local variables introduced inside the method are available, so only this (if the method is not static) and the parameters are available—unless the method’s code reuses them for other purposes (ordinary Java code usually doesn’t). But the good news is, you don’t have to deal with them unless you want to use them.
So let’s assume we want to cover the entire method with an exception handler which will catch the exception, print its stack trace and return (assuming void). Then, we don’t need any local variables and the entire code, applied after completely visiting the original code, looks like:
Label endFinally = new Label();
visitTryCatchBlock(startFinally, endFinally, endFinally, "java/lang/Exception");
visitLabel(endFinally);
visitFrame(F_NEW, 0, null, 1, new Object[]{"java/lang/Exception"});
visitVarInsn(ASTORE, 1);
visitVarInsn(ALOAD, 1);
visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception", "printStackTrace", "()V", false);
visitInsn(RETURN);
The logic is
visitFrame(F_NEW, // not derived from a previous frame
0, null, // no local variables
1, new Object[]{"java/lang/Exception"} // one exception on the stack
);
Of course, the type of the exception on the stack must match the type of the visitTryCatchBlock or be a super type of it. Note that the local variable we’re going to introduce after entering the handler is irrelevant. If you want to re-throw instead of returning, just replace
visitInsn(RETURN);
with
visitVarInsn(ALOAD, 1);
visitInsn(ATHROW);
and the logic regarding the stack map frame doesn’t change.

Related

GetFunctionPointerForDelegate and pin pointer

Hi this is in regard to some code given in C++ CLI i action which i have trouble understanding.The code is given below
delegate bool EnumWindowsDelegateProc(
IntPtr hwnd,IntPtr lParam);
ref class WindowEnumerator
{
private:
EnumWindowsDelegateProc^ _WindowFound;
public:
WindowEnumerator(EnumWindowsDelegateProc^ handler)
{
_WindowFound = handler;
}
void Init()
{
pin_ptr<EnumWindowsDelegateProc^> tmp = &_WindowFound;
EnumWindows((WNDENUMPROC)
Marshal::GetFunctionPointerForDelegate(
_WindowFound).ToPointer(), 0);
}
};
In the above code _WindowFound has been pinned so GC wont moove it.The Question is
Isn't tmp only valid inside Int() thus _WindowFound pinned only
during call to Int() ?
If thats the case Isn't there a chance the delegate location in
memory might change at the time EnumWindows calls it as a function
pointer?
A pin_ptr<> automatically unpins, RAII-style, when code execution leaves the block that it is declared it. So it will be pinned for the entire body of the Init() method in your code. So your 2 bullet does not apply.
It is notable that the code is in not infact correct. It works, but by accident. Marshal.GetFunctionPointerForDelegate() invokes the stub compiler to auto-generate the native code that's needed to allow the native code to invoke the delegate target. The lifetime of that stub is controlled by the lifetime of the delegate object. In other words, as soon as the delegate object gets garbage collected, the stub will be destroyed as well.
Pinning the delegate object does not in any way affect the stub. It is already unmovable, the GC never moves code. It works by accident because pinning an object requires creating an extra GC handle for the object (GCHandle::Alloc), enough to prevent premature collection.
It doesn't make an enormous difference in this kind of code, EnumWindows() is slow anyway. Not necessarily the case when you call other native code that requires a callback, avoiding pinning should always be a goal in general. All you have to do is let the jitter see a reference to the delegate object beyond the code where it can still be used, like this:
void Init() {
EnumWindows((WNDENUMPROC)
Marshal::GetFunctionPointerForDelegate(
_WindowFound).ToPointer(), 0);
GC::KeepAlive(_WindowFound);
}
Very efficient, GC::KeepAlive() doesn't generate any code, it just tells the jitter to extend the lifetime of the _WIndowFound reference so it can't be collected while EnumWindows() is executing. Even that is overkill in this specific case since somebody is going to have a reference to the WindowEnumerator object in order to retrieve _WindowFound, but better safe than sorry.

XNA phase management

I am making a tactical RPG game in XNA 4.0 and was wondering what the best way to go about "phases" is? What I mean by phases is creating a phase letting the player place his soldiers on the map, creating a phase for the player's turn, and another phase for the enemy's turn.
I was thinking I could create some sort of enum and set the code in the upgrade/draw methods to run accordingly, but I want to make sure this is the best way to go about it first.
Thanks!
Edit: To anaximander below:
I should have mentioned this before, but I already have something implemented in my application that is similar to what you mentioned. Mine is called ScreenManager and Screen but it works exactly in the same way. I think the problem is that I am treating screen, phase, state, etc, to be different things but in reality they are the same thing.
Basically what I really want is a way to manage different "phases" in a single screen. One of my screens called map will basically represent all of the possible maps in the game. This is where the fighting takes place etc. I want to know what is the best way to go about this:
Either creating an enum called FightStage that holds values like
PlacementPhase,PlayerPhase, etc, and then split the Draw and
Update method according to the enum
Or create an external class to manage this.
Sorry for the confusion!
An approach I often take with states or phases is to have a manager class. Essentially, you need a GamePhase object which has Initialise(), Update(), Draw() and Dispose() methods, and possibly Pause() and Resume() as well. Also often worth having is some sort of method to handle the handover. More on that later. Once you have this class, inherit from it to create a class for each phase; SoldierPlacementPhase, MovementPhase, AttackPhase, etc.
Then you have a GamePhaseManager class, which has Initialise(), Update(), Draw() and Dispose() methods, and probably a SetCurrentPhase() method of some kind. You'll also need an Add() method to add states to the manager - it'll need a way to store them. I recommend a Dictionary<> using either an int/enum or string as the key. Your SetCurrentPhase() method will take that key as a parameter.
Basically, what you do is to set up an instance of the GamePhaseManager in your game, and then create and initialise each phase object and add it to the manager. Then your game's update loop will call GamePhaseManager.Update(), which simply calls through to the current state's Update method, passing the parameters along.
Your phases will need some way of telling when it's time for them to end, and some way of handling that. I find that the easiest way is to set up your GamePhase objects, and then have a method like GamePhase.SetNextPhase(GamePhase next) which gives each phase a reference to the one that comes next. Then all they need is a boolean Exiting with a protected setter and a public getter, so that they can set Exiting = true in their Update() when their internal logic decides that phase is over, and then in the GamePhaseManager.Update() you can do this:
public void Update(TimeSpan elapsed)
{
if (CurrentPhase.Exiting)
{
CurrentPhase.HandOver();
CurrentPhase = CurrentPhase.NextPhase;
}
CurrentPhase.Update(elapsed);
}
You'll notice I change phase before the update. That's so that the exiting phase can finish its cycle; you get odd behaviour otherwise. The CurrentPhase.HandOver() method basically gets the current phase to pass on anything the next phase needs to know to carry on from the right point. This is probably done by having it call NextPhase.Resume() internally, passing it any info it needs as parameters. Remember to also set Exiting = false in here, or else it'll keep handing over after only one update loop.
The Draw() methods are handled in the same way - your game loop calls GamePhaseManager.Draw(), which just calls CurrentPhase.Draw(), passing the parameters through.
If you have anything that isn't dependent on phase - the map, for example - you can either have it stored in the GamePhaseManager and call its methods in GamePhaseManager's methods, you can have the phases pass it around and have them call its methods, or you can keep it up at the top level and call it's methods alongsideGamePhaseManager's. It depends how much access the phases need to it.
EDIT
Your edit shows that a fair portion of what's above is known to you, but I'm leaving it there to help anyone who comes across this question in future.
If already you have a manager to handle stages of the game, my immediate instinct would be to nest it. You saw that your game has stages, and built a class to handle them. You have a stage that has its own stages, so why not use the stage-handling code you already wrote? Inherit from your Screen object to have a SubdividedScreen class, or whatever you feel like calling it. This new class is mostly the same as the parent, but it also contains its own instance of the ScreenManager class. Replace the Screen object you're calling map with one of these SubdividedScreen objects, and fill its ScreenManager with Screen instances to represent the various stages (PlacementPhase, PlayerPhase, etc). You might need a few tweaks to the ScreenManager code to make sure the right info can get to the methods that need it, but it's much neater than having a messy Update() method subdivided by switch cases.

Disposing a HtmlControl

On the advice of Code Analysis in VS to call Dispose on an object (which I wasn't previuosly) I ended up with a method containing this:
using (var favicon = new HtmlLink
{
Href = "~/templates/default/images/cc_favicon.ico"
})
{
favicon.Attributes.Add("rel", "shortcut icon");
Header.Controls.Add(favicon);
}
This confused me slightly, if I dispose this object after adding it to the Controls collection is that such a good idea?
How does this still work? Is it because the Controls.Add method disposes the object after use as opposed to holding on to it?
I would say that this code shouldn't work but if you say it's working then the only things I can think of are:
Header.Controls.Add add a copy of the object so there is no problem disposing the original.
The Dispose method does not clean anything that is used later.
Hope this helps.
If a method on favicon is called that uses any of the unmanaged resources it will give exception.
From msdn:
You can instantiate the resource object and then pass the variable to
the using statement, but this is not a best practice. In this case,
the object remains in scope after control leaves the using block even
though it will probably no longer have access to its unmanaged
resources. In other words, it will no longer be fully initialized. If
you try to use the object outside the using block, you risk causing an
exception to be thrown. For this reason, it is generally better to
instantiate the object in the using statement and limit its scope to
the using block.
using statement msdn
I assume that you code analysis gave you CA2000: Dispose objects before losing scope before you changed the code. The problem is that you shouldn't dispose your object because you want to use it even after returning from the method (it has been added to a collection).
You can either suppress the message using the SuppressMessage attribute or you can rewrite you code to be really paranoid:
var favicon = new HtmlLink { Href = "~/templates/default/images/cc_favicon.ico" };
try {
favicon.Attributes.Add("rel", "shortcut icon");
}
catch {
favicon.Dispose();
throw;
}
Header.Controls.Add(favicon);
The normal flow of this code adds favicon to the collection that is then responsible for disposing it. However, the abnormal flow where favicon.Attributes.Add throws an exception will dispose favicon before propagating the exception.
In most case, because the garbage collector will do its job eventually, you don't need the paranoid version of the code.

Turn-Based-Strategy Game - Where to Store User State

I'm writing a turn-based strategy game. Each player in the game has a team of units which can be individually controlled. On a user's turn, the game currently follows a pretty constant sequence of events:
Select a unit -> Move the selected unit -> Issue a command -> Confirm
I could implement this by creating a game class that keeps track of which of these stages the player is in and providing methods to move from one stage to the next, like this:
interface TeamCommander {
public void select(Coordinate where);
public void move(Coordinate to);
public void sendCommand(String command);
public void execute();
}
However, that would allow the possibility of a method being called at the wrong time (for example, calling move() before calling select()), and I would like to avoid that. So I currently have it implemented statelessly, like this:
interface UnitSelector {
public UnitMover select(Coordinate where);
}
interface UnitMover {
public UnitCommander move(Coordinate to);
}
interface UnitCommander {
public CommandExecutor sendCommand(String command);
}
interface CommandExecutor {
public void execute();
}
However, I'm having difficulty presenting this information to the user. Since this is stateless, the game model does not store any information about what the user is currently doing, and thus the view can't query the model about it. I could store some state in the GUI, but that would be bad form. So, my question is: does anyone have an idea about how to resolve this?
First, there's something I'm not getting here: You have to be storing persistent state somewhere, even if it is only in the View / GUI. Without persistent state you cannot have a game. I'm guessing you're using either ASP or PHP; if so, use sessions to track state.
Secondly, build your state logic into that so it is known where in the input sequence you are for each player / each unit in that player's team. Don't try to get fancy with it. B requires A, C requires B and so on. While you're writing it, just give yourself a scaffold by throwing exceptions if the call order comes up incorrect (which you should be checking on every user input as I assume this is an event driven rather than loop-driven game), and debug it from there.
As an aside: I get suspicious when I see interfaces with a single method as in your second example above. An interface typically informs of there being a unique SET of functionalities which different classes each fulfill -- unless you are trying to construct multiple different classes which use slightly different sets of individual method signatures, don't do what you're doing there. It is all fine and good to say "code to an interface and not an implementation", but you need to first take the top down approach, saying, "How does my ultimate client code (in your root game logic class or method) need to call for such-and-such to occur?" and keep asking that question up the call stack (i.e. at each subsequent sub-call codepoint). If you try to build it from the bottom up, you will end up with the confusing and unnecessarily complicated code I see there. The only other exception to this which I see on a regular basis is the command pattern, and that is generally intended to look like
void execute();
or
void execute(Object data);
...But typically not a whole slew of slightly different method signatures (again possible, but unlikely). My gut feeling comes from my experience with such constructs in that they usually don't make sense and you end up completely refactoring code that uses them.

Where to perform Parameter Validation within nested methods

Where is the proper place to perform validation given the following scenario/code below:
In MethodA only: since this is the public method which is meant to be used by external assemblies?
In MethodA and B since both these can be accessed outside the class?
Or Methods A, B and C since method C may be used by another internal method (but it might not efficient since the programmer can see the code for MethodC already and therefore should be able to know the valid parameters to pass)?
Thanks for any input.
public class A
{
public void MethodA(param)
{
MethodB(param);
}
internal void MethodB(param)
{
MethodC(param);
}
private void MethodC(param)
{
}
}
Parameter validation should always be performed regardless of the caller's location (inside or outside of the assembly). Defensive programming, one can say.
MethodC; that way the parameter always gets checked, even if someone comes along later and adds a call to MethodC from within class A, or they make MethodC public. Any exception should be bubbled up to where it can be best dealt with.
There isn't a 'proper' place, except to adhere to DRY principles and avoid copying the validation code to several places. I'd normally suggest that you delay validation to the latest possible stage, as then if the parameter is never used you don't need to spend time validating it though. This also gives the validation some locality to the place it is used, and you never need to think 'oh, has this parameter been validated yet?' as the validation is right there.
Given that a more likely senario would involve each method having different parameters and also probably some
if (P1 == 1) { MethodA(P2) } else { MethodB(P2) }
type logic in hte longer term it makes more sense to validate each parameter at the point of entry, escpecially as you may want different error handling depending on where hte method was called.
If the validation logic for a given parameter start to get complex ( i.e. more than five lines of code) then consider a private method to validate that parameter.

Resources