/
ObjectiveC1_MessageAnalyzer.java
325 lines (282 loc) · 9.93 KB
/
ObjectiveC1_MessageAnalyzer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.analysis;
import java.util.List;
import ghidra.app.services.*;
import ghidra.app.util.bin.format.macho.SectionNames;
import ghidra.app.util.bin.format.objectiveC.ObjectiveC1_Constants;
import ghidra.app.util.bin.format.objectiveC.ObjectiveC1_Utilities;
import ghidra.app.util.importer.MessageLog;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.symbol.*;
import ghidra.util.exception.*;
import ghidra.util.task.TaskMonitor;
public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
private static final String DESCRIPTION =
"An analyzer for extracting _objc_msgSend information.";
private static final String NAME = "Objective-C Message";
public ObjectiveC1_MessageAnalyzer() {
super(NAME, DESCRIPTION, AnalyzerType.FUNCTION_ANALYZER);
setDefaultEnablement(true);
setPriority(new AnalysisPriority(10000000));
}
/* ************************************************************************** */
/* ************************************************************************** */
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
throws CancelledException {
CurrentState state = new CurrentState(program);
monitor.initialize(set.getNumAddresses());
int progress = 0;
AddressIterator iterator = set.getAddresses(true);
while (iterator.hasNext()) {
if (monitor.isCancelled()) {
break;
}
monitor.setProgress(++progress);
Address address = iterator.next();
Function function = program.getListing().getFunctionAt(address);
try {
inspectFunction(program, function, state, monitor);
}
catch (Exception e) {
}
}
return true;
}
@Override
public boolean canAnalyze(Program program) {
return ObjectiveC1_Constants.isObjectiveC(program);
}
/* ************************************************************************** */
/* ************************************************************************** */
private void inspectFunction(Program program, Function function, CurrentState state,
TaskMonitor monitor) {
if (function == null) {
return;
}
InstructionIterator instructionIterator =
program.getListing().getInstructions(function.getBody(), true);
while (instructionIterator.hasNext()) {
if (monitor.isCancelled()) {
break;
}
Instruction instruction = instructionIterator.next();
if (isCallingObjcMsgSend(instruction)) {
String eolComment = instruction.getComment(CodeUnit.EOL_COMMENT);
if (eolComment != null) {//if a comment already exists, ignore...
continue;
}
markupInstruction(instruction, state, monitor);
}
}
}
private boolean isCallingObjcMsgSend(Instruction instruction) {
if (instruction.getNumOperands() != 1) {
return false;
}
Reference reference = instruction.getPrimaryReference(0);
if (reference == null) {
return false;
}
if (!reference.getReferenceType().isCall() && !reference.getReferenceType().isJump()) {
return false;
}
SymbolTable symbolTable = instruction.getProgram().getSymbolTable();
Symbol symbol = symbolTable.getPrimarySymbol(reference.getToAddress());
return isObjcNameMatch(symbol);
}
private boolean isObjcNameMatch(Symbol symbol) {
String name = symbol.getName();
return name.startsWith(ObjectiveC1_Constants.OBJC_MSG_SEND) ||
name.equals(ObjectiveC1_Constants.READ_UNIX2003) ||
name.startsWith("thunk" + ObjectiveC1_Constants.OBJC_MSG_SEND);
}
private class CurrentState {
Program program;
Namespace globalNamespace;
Namespace selectorNamespace;
Namespace idNamespace;
String currentClassName = null;
String currentMethodName = null;
//Function currentFunction = null;
CurrentState(Program program) {
this.program = program;
globalNamespace = program.getGlobalNamespace();
SymbolTable symbolTable = program.getSymbolTable();
selectorNamespace = findMatchingChildNamespace("@sel", globalNamespace, symbolTable);
idNamespace = findMatchingChildNamespace("@id", globalNamespace, symbolTable);
}
boolean isValid() {
return currentMethodName != null && currentClassName != null;
}
void reset() {
currentClassName = null;
currentMethodName = null;
}
@Override
public String toString() {
return "[" + currentClassName + " " + currentMethodName + "]";
}
private Namespace findMatchingChildNamespace(String namespaceName,
Namespace parentNamespace, SymbolTable symbolTable) {
SymbolIterator it = symbolTable.getSymbols(parentNamespace);
while (it.hasNext()) {
Symbol s = it.next();
if (s.getSymbolType() == SymbolType.NAMESPACE) {
if (namespaceName.equals(s.getName())) {
return (Namespace) s.getObject();
}
}
}
try {
return symbolTable.createNameSpace(parentNamespace, namespaceName,
SourceType.ANALYSIS);
}
catch (DuplicateNameException e) {
}
catch (InvalidInputException e) {
}
return null;
}
}
private void markupInstruction(Instruction instruction, CurrentState state,
TaskMonitor monitor) {
Address fromAddress = instruction.getMinAddress();
Function function = state.program.getListing().getFunctionContaining(fromAddress);
if (function == null) {
return;
}
state.reset();
InstructionIterator iter = state.program.getListing().getInstructions(fromAddress, false);
while (iter.hasNext()) {
if (monitor.isCancelled()) {
break;
}
Instruction instructionBefore = iter.next();
if (!function.getBody().contains(instructionBefore.getMinAddress())) {
break;//don't look outside of the function
}
if (!isValidInstruction(instructionBefore)) {
continue;
}
Reference[] opRefs = instructionBefore.getOperandReferences(1);
if (opRefs.length != 1) {
continue;
}
Address toAddress = opRefs[0].getToAddress();
MemoryBlock block = state.program.getMemory().getBlock(toAddress);
if (block == null) {
continue;
}
pullNameThrough(state, toAddress, null);
if (state.isValid()) {
instruction.setComment(CodeUnit.EOL_COMMENT, state.toString());
setReference(fromAddress, state);
break;
}
}
}
// Tries to lay down a reference to the function that is actually being called
private void setReference(Address fromAddress, CurrentState state) {
SymbolTable symbolTable = state.program.getSymbolTable();
Symbol classSymbol = symbolTable.getClassSymbol(state.currentClassName, (Namespace) null);
if (classSymbol == null) {
return;
}
Namespace namespace = (Namespace) classSymbol.getObject();
List<Symbol> functionSymbols = symbolTable.getSymbols(state.currentMethodName, namespace);
if (functionSymbols.size() >= 1) {
Address toAddress = functionSymbols.get(0).getAddress();
ReferenceManager referenceManager = state.program.getReferenceManager();
Reference reference = referenceManager.addMemoryReference(fromAddress, toAddress,
RefType.UNCONDITIONAL_CALL, SourceType.ANALYSIS, 0);
referenceManager.setPrimary(reference, true);
}
}
/**
* Objective-C class and method names are stored in the
* "__cstring" memory block. The strings are referenced
* by either the "class" block or the "message" block.
* The references are through n-levels of pointer indirection
* based on the specific target (x86 vs ppc vs arm).
* This method will pull the string through the pointer indirection
* and set the appropriate value in the current state.
*/
String pullNameThrough(CurrentState state, Address address, Namespace space) {
MemoryBlock block = state.program.getMemory().getBlock(address);
if (block == null) {
return null;
}
if (block.getName().equals(SectionNames.TEXT_CSTRING)) {
return ObjectiveC1_Utilities.createString(state.program, address);
}
Data data = state.program.getListing().getDataAt(address);
if (data == null) {
data = state.program.getListing().getDataContaining(address);
if (data == null) {
return null;
}
data = data.getComponentAt((int) address.subtract(data.getAddress()));
if (data == null) {
return null;
}
}
Reference[] references = data.getValueReferences();
if (references.length == 0) {
return null;
}
if (address.equals(references[0].getToAddress())) {
return null;//self reference
}
if (isClassBlock(block)) {
space = state.idNamespace;
}
else if (isMessageBlock(block)) {
space = state.selectorNamespace;
}
String name = pullNameThrough(state, references[0].getToAddress(), space);
if (isClassBlock(block)) {
if (state.currentClassName == null) {
state.currentClassName = name;
}
}
else if (isMessageBlock(block)) {
if (state.currentMethodName == null) {
state.currentMethodName = name;
}
}
return name;
}
private boolean isMessageBlock(MemoryBlock block) {
return block.getName().equals(ObjectiveC1_Constants.OBJC_SECTION_MESSAGE_REFS);
}
private boolean isClassBlock(MemoryBlock block) {
return block.getName().equals(ObjectiveC1_Constants.OBJC_SECTION_CLASS_REFS) ||
block.getName().equals(ObjectiveC1_Constants.OBJC_SECTION_CLASS);
}
private boolean isValidInstruction(Instruction instruction) {
if (instruction.getNumOperands() != 2) {
return false;
}
boolean isMOV = instruction.getMnemonicString().equals("MOV");//intel
boolean isLWZ = instruction.getMnemonicString().equals("lwz");//powerpc
boolean isLDR = instruction.getMnemonicString().equals("ldr");//arm
return isMOV || isLWZ || isLDR;
}
}