Welcome!

Industrial IoT Authors: Elizabeth White, Stackify Blog, Yeshim Deniz, SmartBear Blog, Liz McMillan

Blog Feed Post

HOW TO: BCI method calls into java methods

In the earlier HOW TO, we stereotyped the performance statics related methods into a class. This will not be of use unless we can call the start and the end methods at the beginning and end of all the methods we want to profile. In this HOW TO, we will see how we can profile the entry and exit of methods to call a function. In our case we will extend the earlier example to call the start and end at the beginning and end of all methods in a class.

To do this, we need to do the following steps:

  • Create a custom MethodVisitor that BCI’s method enter and exit
  • Override the visitMethod function in the ClassVisitor and return the custom method visitor.
  • Use this ClassVisitor to modify the bytes as described in HOW To BCI.

Create a custom MethodVisitor

To BCI entry and exit of methods, we can derive a MethodVisitor from AdviceAdapter and override the onMethodEnter and onMethodExit functions. So we write a MethodVisitor as below:

    public class PerfMethod extends AdviceAdapter
    {
        private String name; 
        private String _clsName;

        public PerfMethod(MethodVisitor mv, int acc, String name, String desc, String cls) 
        { 
            super(2, mv, acc, name, desc); 
            this.name = name; 
            this._clsName = cls;
            _latestVar = -1;
        } 

        protected void onMethodEnter() 
        {
            We need to add code here
        }

        protected void onMethodExit(int opcode)
        {
            We need to add code here
        }

        public void visitMaxs(int stack, int locals) 
        { 
            super.visitMaxs(stack, locals); 
        }
    }

In the above we have the skeleton of how the MethodVisitor will look like. Let’s see how we can call the method in the functions onEnter and onExit. We need to know what are the instructions that have to be executed to call the start and end methods. We can do this using the ASMifier class provided. This takes as an input a class and dumps out the set of instructions that if called will create the class. We will create a class SampleASMify as below:

public class SampleASMify
{
    public SampleASMify()
    {
    }

    public void profile()
    {
        start("val");
        int i = 0;
        end();
    }

    public void start(String nm)
    {
    }

    public void end()
    {
    }
}

In the above class if you notice, we have two dummy functions start and end with signatures as we will have in the PerfTemplate. We call this in the function profile at the start and end of the method. We now can run ASMifier as below:

java -cp 
    asm-util-4.0_RC2.jar:asm-commons-4.0_RC2.jar:
    asm-tree-4.0_RC2.jar:asm-4.0_RC2.jar:
    asm-analysis-4.0_RC2.jar:asm-xml-4.0_RC2.jar:. 
org.objectweb.asm.util.ASMifier SampleASMify.class

This will generate an output for all functions as below. We will ignore all the functions except the profile, because this is what is important to us. The profile function output is shown below.

{
mv = cw.visitMethod(ACC_PUBLIC, "profile", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitLdcInsn("val");
mv.visitMethodInsn(INVOKEVIRTUAL, "SampleASMify", "start", "(Ljava/lang/String;)V");
mv.visitInsn(ICONST_0);
mv.visitVarInsn(ISTORE, 1);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, "SampleASMify", "end", "()V");
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
}

I have marked the instructions that are the calls to start and end. This indicates what are the instructions that have to be called to call start or end function for the signature we have in PerfTemplate. So, now we can write the onEnter method with the instructions required to call start as shown above. So, onEnter in the class PerfMethod becomes:

        protected void onMethodEnter() 
        { 
            super.visitVarInsn(ALOAD, 0);
            super.visitLdcInsn(name);
            super.visitMethodInsn(INVOKESPECIAL, _clsName, "start", "(Ljava/lang/String;)V");
        }

I have replaced the constants that we had in the previous output with the parameters I need to pass to the method. We can the onExit method with the “end” call instructions from above as this:

        protected void onMethodExit(int opcode)
        {
            if (!name.equals("toString"))
            {
                super.visitVarInsn(ALOAD, 0);
                super.visitMethodInsn(INVOKESPECIAL, _clsName, "end", "()V");
            }
        }

Here again we have replace the parameters appropriately. In here we are preventing the performance to be added to the toString method. This type of check can be used to conditionally profile only the required methods. Now we have a complete MethodVisitor that will BCI to call the start and end method for performance.

Override the visitMethod function in the ClassVisitor

Now we have to override our visitMethod in the ClassVisitor to return the above visitor. We can do this as below:

        public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions)
        {
            MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
            if (name.equals("") || (name.equals("main")))
            {
                return mv; //don't modify the constructor
            }
            PerfMethod p = new PerfMethod(mv, access, name, desc, _name);
            return p;
        }

In the above I have prevented the constructor from being profiled. Please note, profiling a constructor in this way will be a problem, since the first line has to be the super call. This helps create an easy profiler as an AOP that can be turned on or off when required and need not be coded into the real production code.

Now we are all set to try the code. The code for this can be downloaded and tried from here.


Read the original blog entry...

More Stories By Raji Sankar

Raji Sankar is a techie at heart trying his hand at entrepreneur-ship. He is Co-Founder and Director of BrioTribes Technologies India Pvt Ltd. based out of Bangalore. He likes to try out anything that is new, interesting and cutting edge. His latest passion is cloud and creating an application platform for the cloud. Check out SMART the documentation for the open-source cloud application platform here and the demo for the platform here

IoT & Smart Cities Stories
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...