当前位置:网站首页>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 :
invokestatic
invokespecial
invokeinterface
invokevirtual
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
CHATransformer
CallKind
: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
边栏推荐
- QT6 QML book/qt quick 3d/ Basics
- Baohong industry | good habits that Internet finance needs to develop
- How to choose cache read / write strategies in different business scenarios?
- Thread, thread stack, method stack, the difference of creating thread
- Cannot load driver class: com. mysql. cj. jdbc. Driver
- leetcode-540. A single element in an ordered array
- LabVIEW training
- 抓包整理外篇——————autoResponder、composer 、statistics [ 三]
- What is the maximum number of concurrent TCP connections for a server? 65535?
- Experience summary of database storage selection
猜你喜欢
Such as the visual appeal of the live broadcast of NBA Finals, can you still see it like this?
How to handle wechat circle of friends marketing activities and share production and release skills
LabVIEW training
UI automation test: selenium+po mode +pytest+allure integration
It is discussed that the success of Vit lies not in attention. Shiftvit uses the precision of swing transformer to outperform the speed of RESNET
Leetcode daily question 540 A single element in an ordered array Valentine's Day special article looking for a single dog in a pile of lovers ~ the clown is myself
leetcode-540. A single element in an ordered array
Mysql database ----- common commands of database (based on database)
运维各常用命令总结
设计电商秒杀系统
随机推荐
@Transactional注解失效的场景
Kernel symbol table
浅析 Ref-NeRF
运维各常用命令总结
leetcode-540. A single element in an ordered array
19、 MySQL -- SQL statements and queries
[secretly kill little buddy pytorch20 days -day02- example of image data modeling process]
From the behind the scenes arena of the ice and snow event, see how digital builders can ensure large-scale events
Instructions for common methods of regular expressions
MySQL——规范数据库设计
Summary of common operation and maintenance commands
Service discovery and load balancing mechanism -service
Link aggregation based on team mechanism
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
Gauss elimination solves linear equations (floating-point Gauss elimination template)
Xai+ network security? Brandon University and others' latest "interpretable artificial intelligence in network security applications" overview, 33 page PDF describes its current situation, challenges,
Strange way of expressing integers (expanding Chinese remainder theorem)
Memory analyzer (MAT)
LabVIEW training
C 10 new feature [caller parameter expression] solves my confusion seven years ago