Soot学习笔记(1)-Adding profiling instructions to applications

本文介绍了如何使用Soot库在应用程序中添加分析指令,详细讲解了SootClass, SootMethod和Unit类的用法。通过加载类、创建方法和添加代码到JimpleBody,展示了构建和操作Java类的方法。" 106421673,8322198,使用DFS解决LeetCode 1219的C++实现,"['算法', 'LeetCode', 'C++编程', '深度优先搜索', '回溯']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相关网页地址:https://github.com/Sable/soot/wiki/Adding-profiling-instructions-to-applications

这篇博文讲 SootClass, SootMethod and Unit classes 这几个类的具体使用方法。

1.首先,我们先要可以创造一个类来把方法放进去,下面是创造一个类的必要步骤:
(1)加载java.lang.Object,和库类。又由于这个类需要其他的类支持,又要加载Scene.v().loadClassAndSupport(“java.lang.System”);
The Scene is the container for all of the SootClasses in a program, and provides various utility methods. There is a singleton Scene object, accessible by calling Scene.v().

(2)加载SootClass,创建类
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 SootClass object for java.lang.Object. Note the use of the utility method getSootClass on the Scene.

Scene.v().addClass(sClass);
This adds the newly-created HelloWorld class to the Scene. All classes should belong to the Scene once they are created.

(3)在创建的Class中创建方法Main!
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 takes an array of java.lang.String objects, and that it returns void.

The constructor for SootMethod takes a list, so we call the Java utility method Arrays.asList to create a list from the one-element array which we generate on the fly with new Type[] … . In the list, we put an array type, corresponding to a one-dimensional ArrayType of java.lang.String objects. The call to RefType fetches the type corresponding to the java.lang.String class.

Types Each SootClass represents a Java object. We can instantiate the class, giving an object with a given type. The two notions - type and class - are closely related, but distinct. To get the type for the java.lang.String class, by name, we call RefType.v(“java.lang.String”). Given a SootClass object sc, we could also call sc.getType() to get the corresponding type.

sClass.addMethod(method);

(4)向方法中加代码

A method is useless if it doesn’t contain any code. We proceed to add some code to the main method. In order to do so, we must pick an intermediate representation for the code.

Create JimpleBody

In Soot, we attach a Body to a SootMethod to associate some code with the method. Each Body knows which SootMethod it corresponds to, but a SootMethod only has one active Body at once (accessible via SootMethod.getActiveBody()). Different types of Body’s are provided by the various intermediate representations; Soot has JimpleBody,ShimpleBody, BafBody and GrimpBody.

More precisely, a Body has three important features: chains of Locals, Traps and Units. A Chain is a list-like structure that provides O(1) access to insert and delete elements. Locals are the local variables in the body; Traps say which units catch which exceptions; and Units 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 associated with our method, and make it the active body for our method.

(5)加变量

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 not bound to the Locals of the Body. The IdentityStmt does this; it assigns into arg the value of the first parameter, which has type array of strings.

// insert “tmpRef.println(“Hello world!”)”
{
SootMethod toCall = Scene.v().getMethod
(“

/* 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)
 */


//package ashes.examples.createclass;

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();
    }

}
资源下载链接为: https://pan.quark.cn/s/22ca96b7bd39 在 IT 领域,文档格式转换是常见需求,尤其在处理多种文件类型时。本文将聚焦于利用 Java 技术栈,尤其是 Apache POI 和 iTextPDF 库,实现 doc、xls(涵盖 Excel 2003 及 Excel 2007+)以及 txt、图片等格式文件向 PDF 的转换,并实现在线浏览功能。 先从 Apache POI 说起,它是一个强大的 Java 库,专注于处理 Microsoft Office 格式文件,比如 doc 和 xls。Apache POI 提供了 HSSF 和 XSSF 两个 API,其中 HSSF 用于读写老版本的 BIFF8 格式(Excel 97-2003),XSSF 则针对新的 XML 格式(Excel 2007+)。这两个 API 均具备读取和写入工作表、单元格、公式、样式等功能。读取 Excel 文件时,可通过创建 HSSFWorkbook 或 XSSFWorkbook 对象来打开相应格式的文件,进而遍历工作簿中的每个 Sheet,获取行和列数据。写入 Excel 文件时,创建新的 Workbook 对象,添加 Sheet、Row 和 Cell,即可构建新 Excel 文件。 再看 iTextPDF,它是一个用于生成和修改 PDF 文档的 Java 库,拥有丰富的 API。创建 PDF 文档时,借助 Document 对象,可定义页面尺寸、边距等属性来定制 PDF 外观。添加内容方面,可使用 Paragraph、List、Table 等元素将文本、列表和表格加入 PDF,图片可通过 Image 类加载插入。iTextPDF 支持多种字体和样式,可设置文本颜色、大小、样式等。此外,iTextPDF 的 TextRenderer 类能将 HTML、
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值