当前位置:网站首页>Day 9 HomeWrok-ClassHierarchyAnalysis
Day 9 HomeWrok-ClassHierarchyAnalysis
2022-07-03 21:03:00 【CyanM0un】
Preface
utilize CHA Complete the construction of the call graph
Handle Java Four calls in :
invokestaticinvokespecialinvokeinterfaceinvokevirtual
Some preparation
- Directory settings
This time we are going to conduct interprocess analysis , So the role of some details appears .
I used to like to set the working directory directly to the code directory to be tested , such as :
Options.v().set_process_dir(Arrays.asList("target/classes/com/DeadCodeDetection/TestDC"));
There really won't be any problems before , And it doesn't include our analysis code directly , It's more convenient . But it's different for this time , If we still set it like this :
Options.v().set_process_dir(Arrays.asList("target/classes/com/CHA/TestCHA"));
For the code we want to analyze
package com.CHA.TestCHA;
public class TestCode{
}
class A {
static void main() {
A.foo();
}
static void foo() {
A a = new A();
a.bar();
}
void bar() {
C c = new C();
c.bar();
}
}
class B extends A {
void bar() {
}
}
class C extends A {
void bar() {
if (Math.random() > 0.5) {
A.foo();
}
}
void m() {
}
}
Generated Jimple as follows ( Not the full class name ):
But the function signature of the internal call is :

Contains the full name of the class , So from the generated Jimple As a result , There will be no corresponding method in the analysis ,debug This is true :

This is initialization , The method signature obtained because of the setting of the working directory , Go back and use Unit When analyzing :
Will not enter if 了 , So just pay a little attention , I'll just arrange the catalogue like this :

init It can be written like this in Chinese :
Options.v().set_process_dir(Arrays.asList("target/classes/"));
// Directory not analyzed
List<String> excluded = new LinkedList<>();
excluded.add("com.*");
Options.v().set_exclude(excluded);
Options.v().set_no_bodies_for_excluded(true);

- analysis phase
You need to turn on the global mode ( It may be because of interprocess analysis ?)
PackManager.v().getPack("wjtp").add(new Transform("wjtp.cg_CHA", new CHATransformer()));
PackManager.v().getPack("wjtp").apply();
- Specify the required classes
CHATransformerCallKind:java Enumeration classes in , In fact, it is used to judge which callCallEdge: Represents the calling edgeCallGraphBuilder,JimpleCallGraph:Builder Take advantage of the various operations provided by the latter , Implement algorithm analysis
process analysis
Yes JimpleCallGraph initialization , Put the method and all of it units Relationships are preserved , It is convenient to find when establishing the calling edge later . Then the idea is the method of the class to be analyzed , If it's not empty , Just save it in a Map in :

Then it can be transferred to our CallGraphBuilder It is analyzed in , Review the algorithm in class :
Then we are ready WL,RM, According to the simple , Methodical entry From the main Start , therefore JimpleCallGraph Provides an operation :
The rest is almost the same process , Write according to the algorithm , Just make up for what you lack , It's no longer so troublesome to write , But I still hope to think about it before writing code ,BuildCallGraph as follows :

cg Some operations of are as follows :
private Set<SootMethod> reachableMethods = new HashSet<>();
private Map<SootMethod, Set<CallEdge>> caller2callee = new HashMap<>();//caller ---> callees
public Collection<Unit> getCallSiteIn(SootMethod method) {
// All in one method callsites
List<Unit> callSites = new LinkedList<>();
if (method.hasActiveBody()) {
Body body = method.getActiveBody();
for (Unit unit : body.getUnits()) {
Stmt stmt = (Stmt) unit;
if (stmt.containsInvokeExpr()) {
callSites.add(stmt);
}
}
}
return callSites;
}
public boolean addEdge(Unit callsite, SootMethod callee, CallKind callKind){
CallEdge callEdge = new CallEdge(callKind, callsite, callee);
SootMethod caller = unit2Owner.get(callsite);
Set<CallEdge> callees = caller2callee.computeIfAbsent(caller, k -> new HashSet<>());
callees.add(callEdge);
return ret;
}
public boolean contains(SootMethod method) {
return reachableMethods.contains(method);
}
public void addRM(SootMethod method) {
reachableMethods.add(method);
}
about Resolve Come on , The same thing

The next step is Dispatch:
The rest is the supplement of other classes
CallKind:
public enum CallKind {
INTERFACE("invokeinterface"),
VIRTUAL("invokevirtual"),
SPECIAL("invokespecial"),
STATIC("invokestatic");
private String inst;
CallKind(String inst) {
this.inst = inst;
}
public static CallKind getCallKind(Unit unit) throws IllegalArgumentException {
// Return to a given Unit Call type of
InvokeExpr invoke = ((Stmt) unit).getInvokeExpr();
if (invoke instanceof InterfaceInvokeExpr) {
return INTERFACE;
}
if (invoke instanceof VirtualInvokeExpr) {
return VIRTUAL;
}
if (invoke instanceof SpecialInvokeExpr) {
return SPECIAL;
}
if (invoke instanceof StaticInvokeExpr) {
return STATIC;
}
throw new IllegalArgumentException(invoke.toString());
}
@Override
public String toString() {
return inst;
}
}
CallEdge:
public class CallEdge {
private CallKind callKind;
private Unit callSite;
private SootMethod callee;
public CallEdge(CallKind callKind, Unit callSite, SootMethod callee) {
this.callKind = callKind;
this.callSite = callSite;
this.callee = callee;
}
public CallKind getCallKind() {
return callKind;
}
public Unit getCallSite() {
return callSite;
}
public SootMethod getCallee() {
return callee;
}
@Override
public String toString() {
StringBuilder buff = new StringBuilder();
buff.append("@").append(callSite.getTag(LineNumberTag.IDENTIFIER))
.append(": ").append(callSite)
.append(" -> ").append(callee.getSignature());
return buff.toString();
}
}
And then we'll Transformer Add the following tests to :
public class CHATransformer extends SceneTransformer {
@Override
protected void internalTransform(String s, Map<String, String> map) {
CHACallGraphBuilder cgBuilder = CHACallGraphBuilder.v();
JimpleCallGraph cg = new JimpleCallGraph();
cgBuilder.buildCallGraph(cg);
for (SootClass clazz : Scene.v().getApplicationClasses()) {
for (SootMethod method : clazz.getMethods()) {
StringBuilder buff = new StringBuilder();
// basic information
buff.append(method.getSignature())
.append(": \n")
.append("\t ").append(cg.contains(method) ? "Reachable" : "Unreachable")
.append("\n");
// call edge
Set<CallEdge> edgeSet = cg.getCallOutOf(method);
for (CallEdge callEdge : edgeSet) {
buff.append("\t ").append(callEdge).append("\n");
}
buff.append("\n");
System.out.println(buff);
}
}
}
}


result



边栏推荐
- Capturing and sorting out external articles -- autoresponder, composer, statistics [III]
- Hcie security Day10: six experiments to understand VRRP and reliability
- @Scenario of transactional annotation invalidation
- Read the root directory of the folder, write txt and generate random samples
- How to set the system volume programmatically- How to programmatically set the system volume?
- 阻塞非阻塞和同步异步的区分 参考一些书籍
- 【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
- 强化學習-學習筆記1 | 基礎概念
- 电子科技大学|强化学习中有效利用的聚类经验回放
- 全网都在疯传的《老板管理手册》(转)
猜你喜欢

TLS environment construction and plaintext analysis

Shortest path problem of graph theory (acwing template)

APEC industry +: father of the king of the ox mill, industrial Internet "king of the ox mill anti-wear faction" Valentine's Day greetings | Asia Pacific Economic media | ChinaBrand

Hcie security Day11: preliminarily learn the concepts of firewall dual machine hot standby and vgmp

In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028

Viewing Chinese science and technology from the Winter Olympics (II): when snowmaking breakthrough is in progress

一台服务器最大并发 tcp 连接数多少?65535?

Baohong industry | good habits that Internet finance needs to develop

Haven't expressed the artifact yet? Valentine's Day is coming. Please send her a special gift~

全网都在疯传的《老板管理手册》(转)
随机推荐
2022 low voltage electrician examination and low voltage electrician simulation examination question bank
Basic knowledge of dictionaries and collections
UI automation test: selenium+po mode +pytest+allure integration
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向
[secretly kill little buddy pytorch20 days -day02- example of image data modeling process]
Go learning notes (4) basic types and statements (3)
Recommendation of books related to strong foundation program mathematics
18、 MySQL -- index
[postgresql]postgresql custom function returns an instance of table type
Basic number theory -- Chinese remainder theorem
Wireless network (preprocessing + concurrent search)
MySQL 8.0 data backup and recovery
强基计划 数学相关书籍 推荐
Experience summary of database storage selection
Line segment tree blue book explanation + classic example acwing 1275 Maximum number
The "boss management manual" that is wildly spread all over the network (turn)
From the behind the scenes arena of the ice and snow event, see how digital builders can ensure large-scale events
In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of rotary tablet presses in the global market in 2022