Creating a class from scratch with Soot
来源:互联网 发布:技术狗python网盘 编辑:程序博客网 时间:2024/04/29 05:14
Creating a class from scratch with Soot
Feng Qian (fqian@sable.mcgill.ca)
Patrick Lam (plam@sable.mcgill.ca)
February 4, 2005
Chris Goard (cgoard@sable.mcgill.ca)
This tutorial is based on the createclass example, written byRaja-Vallée-Rai and distributed with the Ashes tools.
Goals
By the end of this lesson, the student should be able to:- name the basic classes of Soot and describe their functionality
- create a simple program which uses Soot to create a classfile from scratch.
The createclass example creates the Java class file HelloWorld.class from scratch, using the Soot framework.
The student should refer to the Main.java file, whichputs all of the steps together in a working Java file. Even though a typical use of Soot would be to write a newTransformer, extendingSoot's functionality, we illustrate a standalone application here;the same classes and methods are used in either case.
Creating a class file using Soot
First, we need to create a class to put methods into.The following steps are necessary to create a class file.
Loading java.lang.Object and Library Classes
Load java.lang.Object, the root of the Java class hierarchy.
This step is not necessary when building code that extends theSoot framework; in that case, loading of classfiles is already donewhen user code is called.
Scene.v().loadClassAndSupport("java.lang.Object");
This line of code causes Soot to load the java.lang.Object classand create the correspondingSootClass object, as well as SootMethods and SootFields for its fields. Of course,java.lang.Object has references to other objects. The call to loadClassAndSupport will load the transitive closure of the specifiedclass, so that all types needed in order to loadjava.lang.Object are themselves loaded.
This process is known as resolution.
Since our HelloWorld program will be using classes in the standard library, we must also resolve these:
Scene.v().loadClassAndSupport("java.lang.System");
These lines reference Scene.v(). The Scene is thecontainer for all of theSootClasses in a program, and providesvarious utility methods. There is a singletonScene object,accessible by calling Scene.v().
Implementation note: Soot loads these classes from eitherclassfiles or.jimple input files. When the former is used,Soot will load all class names referred to in the constant pool ofeach class file. Loading from.jimple will make Soot load onlythe required types.
Creation of a new SootClass object
Create the `HelloWorld' SootClass, and set its super class as ``java.lang.Object''.
sClass = new SootClass("HelloWorld", Modifier.PUBLIC);
This code creates a SootClass object for a public class named HelloWorld.
sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object"));
This sets the superclass of the newly-created class to the SootClassobject forjava.lang.Object. Note the use of the utility methodgetSootClass on the Scene.
Scene.v().addClass(sClass);
This adds the newly-created HelloWorld class to the Scene. All classesshould belong to theScene once they are created.
Adding methods to SootClasses
Create a main() method for HelloWorld with an empty body.
Now that we have a SootClass, we need to add methods to it.
method = new SootMethod("main", Arrays.asList(new Type[] {ArrayType.v(RefType.v("java.lang.String"), 1)}), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC);
We create a new public static method, main, declare that it takesan array ofjava.lang.String objects, and that it returns void.
The constructor for SootMethod takes a list, so we call the Javautility methodArrays.asList to create a list from theone-element array which we generate on the fly withnew Type[] .... In the list, we put an array type,corresponding to a one-dimensional ArrayType ofjava.lang.Stringobjects. The call to RefType fetches the typecorresponding to thejava.lang.String class.
Types
Each SootClass represents a Java object. We caninstantiate the class, giving an object with a given type. The twonotions - type and class - are closely related, but distinct. Toget the type for thejava.lang.String class, by name, we callRefType.v("java.lang.String"). Given aSootClass objectsc, we could also call sc.getType() to get thecorresponding type.sClass.addMethod(method);
This code adds the method to its containing class.
Adding code to methods
A method is useless if it doesn't contain any code. We proceed to add somecode to themain method. In order to do so, we must pick an intermediaterepresentation for the code.
Create JimpleBody
In Soot, we attach a Body to a SootMethod to associate some code withthe method. Each Body knows which SootMethod it corresponds to, but a SootMethodonly has one active Body at once (accessible viaSootMethod.getActiveBody()).Different types of Body's are provided by the various intermediate representations;Soot hasJimpleBody, BafBody and GrimpBody.
More precisely, a Body has three important features: chains oflocals, traps and units. Achain is a list-like structure thatprovides O(1) access to insert and delete elements.Localsare the local variables in the body; traps say which units catchwhich exceptions; andunits are the statements themselves.
Note that ``unit'' is the term which denotes both statements (as in Jimple)and instructions (as in Baf).
Create a Jimple Body for 'main' class, adding locals and instructions to body.
JimpleBody body = Jimple.v().newBody(method); method.setActiveBody(body);
We call the Jimple singleton object to get a new JimpleBody associatedwith our method, and make it the active body for our method.
Adding a Local
arg = Jimple.v().newLocal("l0", ArrayType.v(RefType.v("java.lang.String"), 1)); body.getLocals().add(arg);
We create a few new Jimple Locals and add them to our Body.
Adding a Unit
units.add(Jimple.v().newIdentityStmt(arg, Jimple.v().newParameterRef(ArrayType.v (RefType.v("java.lang.String"), 1), 0)));
The SootMethod declares that it has parameters, but these are notbound to the locals of the Body. The IdentityStmt does this; it assignsintoarg the value of the first parameter, which has type ``array ofstrings''.
// insert "tmpRef.println("Hello world!")" { SootMethod toCall = Scene.v().getMethod ("<java.io.PrintStream: void println(java.lang.String)>"); units.add(Jimple.v().newInvokeStmt (Jimple.v().newVirtualInvokeExpr (tmpRef, toCall.makeRef(), StringConstant.v("Hello world!")))); }
We get the method with signature <java.io.PrintStream: void println(java.lang.String)>(it is namedprintln, belongs to PrintStream, returns void andtakes aString as its argument - this is enough to uniquelyidentify the method), and invoke it with theStringConstant ``Hello world!''.
Write to class file
In order to write the program out to a .class file, the method bodies must be converted from Jimple to Jasmin, and assembled into bytecode. Assembly into bytecode is performed by aJasminOutputStream.
We first construct the output stream that will take Jasmin source and output a.class file. We can either specify the filename manually, or we can let soot determine the correct filename. We do the latter, here.
String fileName = SourceLocator.v().getFileNameFor(sClass, Options.output_format_class); OutputStream streamOut = new JasminOutputStream( new FileOutputStream(fileName)); PrintWriter writerOut = new PrintWriter( new OutputStreamWriter(streamOut));
We now convert from Jimple to Jasmin, and print the resulting Jasmin class to the output stream.
JasminClass jasminClass = new soot.jimple.JasminClass(sClass); jasminClass.print(writerOut); writerOut.flush(); streamOut.close();
If we wished to output jimple source instead of a .class file, we would use the following code:
String fileName = SourceLocator.v().getFileNameFor(sClass, Options.output_format_jimple); OutputStream streamOut = new FileOutputStream(fileName); PrintWriter writerOut = new PrintWriter( new OutputStreamWriter(streamOut)); Printer.v().printTo(sClass, writerOut); writerOut.flush(); streamOut.close();
We have omitted the JaminOuputStream, and are calling the printTo method onPrinter.
The Jimple created for the HelloWorld class is:
public class HelloWorld extends java.lang.Object{ public static void main(java.lang.String[]) { java.lang.String[] r0; java.io.PrintStream r1; r0 := @parameter0: java.lang.String[]; r1 = <java.lang.System: java.io.PrintStream out>; virtualinvoke r1.<java.io.PrintStream: void println(java.lang.String)> ("Hello world!"); return; }}
Conclusion
We've seen how to use the basic objects and methods ofSoot, and how to create Jimple statements. This tutorial wasbrought to you by these classes:Scene, SootClass, SootMethod,Body, JimpleBody, Local, and Unit.
Appendix A: Complete code forcreateclass example
The code for this example is reproduced below. It can be downloadedat:
http://www.sable.mcgill.ca/soot/tutorial/createclass/Main.java.
/* Soot - a J*va Optimization Framework * Copyright (C) 1997-1999 Raja Vallee-Rai * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. *//* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */import soot.*;import soot.jimple.*;import soot.options.Options;import soot.util.*;import java.io.*;import java.util.*;/** Example of using Soot to create a classfile from scratch. * The 'createclass' example creates a HelloWorld class file using Soot. * It proceeds as follows: * * - Create a SootClass <code>HelloWorld</code> extending java.lang.Object. * * - Create a 'main' method and add it to the class. * * - Create an empty JimpleBody and add it to the 'main' method. * * - Add locals and statements to JimpleBody. * * - Write the result out to a class file. */public class Main{ public static void main(String[] args) throws FileNotFoundException, IOException { SootClass sClass; SootMethod method; // Resolve Dependencies Scene.v().loadClassAndSupport("java.lang.Object"); Scene.v().loadClassAndSupport("java.lang.System"); // Declare 'public class HelloWorld' sClass = new SootClass("HelloWorld", Modifier.PUBLIC); // 'extends Object' sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object")); Scene.v().addClass(sClass); // Create the method, public static void main(String[]) method = new SootMethod("main", Arrays.asList(new Type[] {ArrayType.v(RefType.v("java.lang.String"), 1)}), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); sClass.addMethod(method); // Create the method body { // create empty body JimpleBody body = Jimple.v().newBody(method); method.setActiveBody(body); Chain units = body.getUnits(); Local arg, tmpRef; // Add some locals, java.lang.String l0 arg = Jimple.v().newLocal("l0", ArrayType.v(RefType.v("java.lang.String"), 1)); body.getLocals().add(arg); // Add locals, java.io.printStream tmpRef tmpRef = Jimple.v().newLocal("tmpRef", RefType.v("java.io.PrintStream")); body.getLocals().add(tmpRef); // add "l0 = @parameter0" units.add(Jimple.v().newIdentityStmt(arg, Jimple.v().newParameterRef(ArrayType.v(RefType.v("java.lang.String"), 1), 0))); // add "tmpRef = java.lang.System.out" units.add(Jimple.v().newAssignStmt(tmpRef, Jimple.v().newStaticFieldRef( Scene.v().getField("<java.lang.System: java.io.PrintStream out>").makeRef()))); // insert "tmpRef.println("Hello world!")" { SootMethod toCall = Scene.v().getMethod("<java.io.PrintStream: void println(java.lang.String)>"); units.add(Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(tmpRef, toCall.makeRef(), StringConstant.v("Hello world!")))); } // insert "return" units.add(Jimple.v().newReturnVoidStmt()); } String fileName = SourceLocator.v().getFileNameFor(sClass, Options.output_format_class); OutputStream streamOut = new JasminOutputStream( new FileOutputStream(fileName)); PrintWriter writerOut = new PrintWriter( new OutputStreamWriter(streamOut)); JasminClass jasminClass = new soot.jimple.JasminClass(sClass); jasminClass.print(writerOut); writerOut.flush(); streamOut.close(); } }
History
- March 8, 2000: Initial version.
- September 1, 2000: Changed syntax to conform with the current release.
- May 31, 2003: Updated for Soot 2.0.
- February 4, 2005: Updated for Soot 2.2.
About this document ...
Creating a class from scratch with SootThis document was generated using theLaTeX2HTML translator Version 2008 (1.71)
Copyright © 1993, 1994, 1995, 1996,Nikos Drakos, Computer Based Learning Unit, University of Leeds.
Copyright © 1997, 1998, 1999,Ross Moore, Mathematics Department, Macquarie University, Sydney.
The command line arguments were:
latex2html createclass -split 0 -nonavigation -dir ./
The translation was initiated by Eric Bodden on 2012-01-22
Eric Bodden2012-01-22
- Creating a class from scratch with Soot
- Creating a class from scratch(从头开始创建一个类)
- Bullet cocos2d-x Creating a project from scratch
- Building a Visual Robot Model with URDF from Scratch
- Creating a XML Document from scratch without using a file in C#
- A Groovy DSL from scratch
- Building a PyCommand from scratch
- Install Kubernetes From a Scratch
- How to create a server from scratch
- start a android App from scratch
- Creating custom View - Creating a View Class
- Creating a Game with CocosBuilder
- Creating a Game with CocosBuilder
- Creating a Game with CocosBuilder
- Creating a video with OpenCV
- (FW: From MSDN)Creating a Child Process with Redirected Input and Output
- Creating a Shape from a Stroked Shape
- A Class for Creating a Trace Log
- ajax 脚本语言直接访问本页面中的WebMethod
- 如何读 Linux 内核
- 磁盘基本概念
- 第十二周项目一阅读程序(1)
- 第12周项目一 程序阅读题(4)
- Creating a class from scratch with Soot
- 正解局域网网关与使用以及将二层lan口做路由器、三层交换机的静态路由出口的实验
- 第十二周项目一阅读程序(2)②去掉x=5
- OpenCV-2.4.2丢失tbb_debug.dll的解决方法
- C++仿函数的概念
- 《Velocity用户手册》-第八章
- 第12周项目3求两个数的最大公约数(递归函数)
- js去掉字符串前后空格的五种方法
- 线程同步