当前位置:网站首页>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



边栏推荐
- Brief analysis of ref nerf
- 19、 MySQL -- SQL statements and queries
- Phpexcel import export
- Sort out several network request methods of JS -- get rid of callback hell
- Mysql database ----- common commands of database (based on database)
- Goodbye 2021, how do programmers go to the top of the disdain chain?
- Compilation Principle -- syntax analysis
- In 2021, the global revenue of syphilis rapid detection kits was about US $608.1 million, and it is expected to reach US $712.9 million in 2028
- Nmap and masscan have their own advantages and disadvantages. The basic commands are often mixed to increase output
- Hcie security Day10: six experiments to understand VRRP and reliability
猜你喜欢

Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of rotary tablet presses in the global market in 2022
![C 10 new feature [caller parameter expression] solves my confusion seven years ago](/img/32/2d81237d4f1165f710a27a7c4eb1e1.jpg)
C 10 new feature [caller parameter expression] solves my confusion seven years ago

Gee calculated area

UI automation test: selenium+po mode +pytest+allure integration

2022 high voltage electrician examination and high voltage electrician reexamination examination

Such as the visual appeal of the live broadcast of NBA Finals, can you still see it like this?

@Transactional注解失效的场景

The global industrial design revenue in 2021 was about $44360 million, and it is expected to reach $62720 million in 2028. From 2022 to 2028, the CAGR was 5.5%

MySQL master-slave synchronization principle

浅议.NET遗留应用改造
随机推荐
Goodbye 2021, how do programmers go to the top of the disdain chain?
大神们,我想发两个广播流1 从mysql加载基础数据,广播出去2 从kafka加载基础数据的变更
TLS environment construction and plaintext analysis
Thread, thread stack, method stack, the difference of creating thread
Gee calculated area
University of Electronic Science and technology | playback of clustering experience effectively used in reinforcement learning
抓包整理外篇——————autoResponder、composer 、statistics [ 三]
Line segment tree blue book explanation + classic example acwing 1275 Maximum number
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
[Tang Laoshi] C -- encapsulation: member variables and access modifiers
Reinforcement learning - learning notes 1 | basic concepts
Rhcsa third day operation
[Yugong series] February 2022 Net architecture class 004 ABP vNext used in WPF project
Is flush account opening and registration safe and reliable? Is there any risk?
Phpexcel import export
Scientific research document management Zotero
jvm jni 及 pvm pybind11 大批量数据传输及优化
Hcie security Day10: six experiments to understand VRRP and reliability
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
Measurement fitting based on Halcon learning -- Practice [1]