priyank
priyank

Reputation: 887

converting bytecode structures to and from XML using ASM

I have been using ASM to do several stuff like parsing java classes using ClassVisitor method provided by ASM. As I know it provides other packages too , I want to understand XML package functionality to convert bytecode structures to and from XML. Can you please provide me the java example how we can achieve that?

Thanks a lot .

~yash

Upvotes: 1

Views: 996

Answers (1)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

There are some JavaDoc at the package level of asm-xml package. Basically it provides a bi-directional bridge between ASM's visitor events and XML SAX events. That allows to convert stream of those events to and from XML, as well as hook up XML processing tools, such as XSLT into that. You can find a few examples of XSLTs in the examples/xml folder in the ASM distribution package or in SVN.

For example, you can add the equivalent of following Java code for each label in the bytecode that has source line number information:

System.err.println( "<class>.<method><desc> Line:<source line number>");

Using this XSL transformation:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" encoding="ASCII" />

<xsl:template match="//method/code/Label">
  <xsl:variable name="n"><xsl:value-of select="@name"/></xsl:variable>
  <xsl:variable name="c"><xsl:value-of select="../LineNumber[@start=$n]/@line"/></xsl:variable>

  <label><xsl:apply-templates select="@*"/></label>

  <xsl:if test="string-length($c)>0">
    <xsl:comment>
      <xsl:text> Line: </xsl:text><xsl:value-of select="$c"/><xsl:text> </xsl:text>
    </xsl:comment>

    <GETSTATIC desc="Ljava/io/PrintStream;" name="err" owner="java/lang/System"/>
    <LDC desc="Ljava/lang/String;">
      <xsl:attribute name="cst">
        <xsl:value-of select="concat( /class/@name, '.' ,../../@name, ../../@desc, ' Line:', $c)"/>
      </xsl:attribute>
    </LDC>
    <INVOKEVIRTUAL desc="(Ljava/lang/String;)V" name="println" owner="java/io/PrintStream"/>
  </xsl:if>    

</xsl:template>

<!-- copy everything -->
<xsl:template match="@*|*|text()|processing-instruction()">
  <xsl:copy><xsl:apply-templates select="@*|*|text()|processing-instruction()"/></xsl:copy>
</xsl:template>

</xsl:stylesheet>

You should be able to run it using the following command:

java -jar asm-all.jar code code -in <input jar> -out <output jar> -xslt <xsl>

Also look at the JavaDoc and source code of org.objectweb.asm.xml.Processor class.

Upvotes: 2

Related Questions