2

I am trying to use ASM to count the individual bytecode instructions executed within a single function to build a histogram. I see there is a tool ByCounter that can do a similar task--but I do not have access to the source code.

My understanding is the Java asm bytecode library can instrument classes, fields, methods, but examples for instrumenting an individual bytecode instruction are not to be found (though from ByCounter--it is found to be possible).

If a tool like the JVMTI is better suited, then that is also useful information!

Thanks for your help!

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Mike
  • 81
  • 7
  • 4
    What are you planning to use this information for? If you're trying to profile or optimize the program, the bytecode isn't what the JIT will actually end up running -- it'll rewrite the whole thing to some completely differently arranged native code at runtime. – Louis Wasserman Feb 13 '17 at 23:55
  • Couldn't you just access a method's [`instructions`](http://asm.ow2.org/asm50/javadoc/user/org/objectweb/asm/tree/MethodNode.html#instructions) and check the [`size`](http://asm.ow2.org/asm50/javadoc/user/org/objectweb/asm/tree/InsnList.html#size--)? – Vince Feb 14 '17 at 00:17
  • @LouisWasserman I want to see how many instructions are executed in a method along different code paths. I agree it is an imperfect method, but it's a start to get some baseline metrics. – Mike Feb 15 '17 at 04:32
  • @VinceEmigh That's a nice idea for a static analysis, but that won't work for dynamic analysis correct? – Mike Feb 15 '17 at 04:33

1 Answers1

0

This is the kind of silly thing I made Jawa for. Example:

from collections import Counter
from jawa.cf import ClassFile
import pandas


with open('tests/data/HelloWorldDebug.class', 'rb') as fin:
    cf = ClassFile(fin)

    method = cf.methods.find_one(name='<init>')

    ins = Counter(i.mnemonic for i in method.code.disassemble())

    df = pandas.DataFrame.from_dict(ins, orient='index')
    fig = df.plot(kind='bar').get_figure()
    fig.savefig('example.png')

histogram

TkTech
  • 4,729
  • 1
  • 24
  • 32
  • This seems to produce a histogram of the instructions *contained* in a method, not the instructions that are actually *executed*… – Holger Feb 14 '17 at 18:10
  • You're completely right, that's a key word I missed. The undocumented `Context()` class can be used to run the method in a trivial JVM, but will obviously give very different results than a real JVM. – TkTech Feb 14 '17 at 21:38
  • @TkTech Nice little histogram there, thanks for sharing. I'll want a histogram, but instead for bytecode counts at runtime within a method as previously mentioned. – Mike Feb 15 '17 at 04:35