ClassNode.java 14.0 KB
Newer Older
S
Skylot 已提交
1 2
package jadx.core.dex.nodes;

3 4 5 6 7 8
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

9 10 11 12
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

13 14 15 16 17 18
import com.android.dex.ClassData;
import com.android.dex.ClassData.Field;
import com.android.dex.ClassData.Method;
import com.android.dex.ClassDef;
import com.android.dex.Dex;

19
import jadx.api.ICodeCache;
S
Skylot 已提交
20
import jadx.api.ICodeInfo;
S
Skylot 已提交
21
import jadx.core.Consts;
S
Skylot 已提交
22
import jadx.core.ProcessClass;
23
import jadx.core.dex.attributes.AFlag;
S
Skylot 已提交
24
import jadx.core.dex.attributes.annotations.Annotation;
S
Skylot 已提交
25 26
import jadx.core.dex.attributes.nodes.LineAttrNode;
import jadx.core.dex.attributes.nodes.SourceFileAttr;
S
Skylot 已提交
27 28 29 30 31 32
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.AccessInfo.AFType;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.args.ArgType;
1
13.beta2 已提交
33
import jadx.core.dex.instructions.args.LiteralArg;
S
Skylot 已提交
34
import jadx.core.dex.nodes.parser.AnnotationsParser;
35
import jadx.core.dex.nodes.parser.FieldInitAttr;
S
Skylot 已提交
36
import jadx.core.dex.nodes.parser.SignatureParser;
S
Skylot 已提交
37
import jadx.core.dex.nodes.parser.StaticValuesParser;
38
import jadx.core.utils.SmaliUtils;
S
Skylot 已提交
39
import jadx.core.utils.exceptions.DecodeException;
S
Skylot 已提交
40
import jadx.core.utils.exceptions.JadxRuntimeException;
S
Skylot 已提交
41

S
Skylot 已提交
42
import static jadx.core.dex.nodes.ProcessState.LOADED;
43
import static jadx.core.dex.nodes.ProcessState.NOT_LOADED;
44

45
public class ClassNode extends LineAttrNode implements ILoadable, ICodeNode {
S
Skylot 已提交
46
	private static final Logger LOG = LoggerFactory.getLogger(ClassNode.class);
S
Skylot 已提交
47 48

	private final DexNode dex;
49
	private final int clsDefOffset;
S
Skylot 已提交
50
	private final ClassInfo clsInfo;
51
	private AccessInfo accessFlags;
S
Skylot 已提交
52 53
	private ArgType superClass;
	private List<ArgType> interfaces;
54
	private List<GenericInfo> generics = Collections.emptyList();
S
Skylot 已提交
55

S
Skylot 已提交
56 57
	private final List<MethodNode> methods;
	private final List<FieldNode> fields;
58
	private List<ClassNode> innerClasses = Collections.emptyList();
S
Skylot 已提交
59

60 61
	// store smali
	private String smali;
62 63
	// store parent for inner classes or 'this' otherwise
	private ClassNode parentClass;
S
Skylot 已提交
64

S
Skylot 已提交
65
	private volatile ProcessState state = ProcessState.NOT_LOADED;
S
Skylot 已提交
66
	private List<ClassNode> dependencies = Collections.emptyList();
67

S
Skylot 已提交
68 69 70
	// cache maps
	private Map<MethodInfo, MethodNode> mthInfoMap = Collections.emptyMap();

71
	public ClassNode(DexNode dex, ClassDef cls) {
S
Skylot 已提交
72
		this.dex = dex;
73
		this.clsDefOffset = cls.getOffset();
S
Skylot 已提交
74 75
		this.clsInfo = ClassInfo.fromDex(dex, cls.getTypeIndex());
		try {
S
Skylot 已提交
76 77 78
			if (cls.getSupertypeIndex() == DexNode.NO_INDEX) {
				this.superClass = null;
			} else {
S
Skylot 已提交
79
				this.superClass = dex.getType(cls.getSupertypeIndex());
S
Skylot 已提交
80
			}
S
Skylot 已提交
81
			this.interfaces = new ArrayList<>(cls.getInterfaces().length);
S
Skylot 已提交
82
			for (short interfaceIdx : cls.getInterfaces()) {
D
Donlon 已提交
83
				this.interfaces.add(dex.getType(interfaceIdx));
S
Skylot 已提交
84
			}
S
Skylot 已提交
85
			if (cls.getClassDataOffset() != 0) {
S
Skylot 已提交
86
				ClassData clsData = dex.readClassData(cls);
S
Skylot 已提交
87 88
				int mthsCount = clsData.getDirectMethods().length + clsData.getVirtualMethods().length;
				int fieldsCount = clsData.getStaticFields().length + clsData.getInstanceFields().length;
S
Skylot 已提交
89

S
Skylot 已提交
90 91
				methods = new ArrayList<>(mthsCount);
				fields = new ArrayList<>(fieldsCount);
S
Skylot 已提交
92

S
Skylot 已提交
93
				for (Method mth : clsData.getDirectMethods()) {
94
					methods.add(new MethodNode(this, mth, false));
S
Skylot 已提交
95 96
				}
				for (Method mth : clsData.getVirtualMethods()) {
97
					methods.add(new MethodNode(this, mth, true));
S
Skylot 已提交
98
				}
S
Skylot 已提交
99

S
Skylot 已提交
100
				for (Field f : clsData.getStaticFields()) {
S
Skylot 已提交
101
					fields.add(new FieldNode(this, f));
S
Skylot 已提交
102
				}
S
Skylot 已提交
103
				loadStaticValues(cls, fields);
S
Skylot 已提交
104
				for (Field f : clsData.getInstanceFields()) {
S
Skylot 已提交
105
					fields.add(new FieldNode(this, f));
S
Skylot 已提交
106 107 108 109
				}
			} else {
				methods = Collections.emptyList();
				fields = Collections.emptyList();
S
Skylot 已提交
110 111 112
			}

			loadAnnotations(cls);
113
			initAccessFlags(cls);
114 115
			parseClassSignature();
			setFieldsTypesFromSignature();
116
			methods.forEach(MethodNode::initMethodTypes);
S
Skylot 已提交
117

118
			int sfIdx = cls.getSourceFileIndex();
119
			if (sfIdx != DexNode.NO_INDEX) {
120
				String fileName = dex.getString(sfIdx);
121
				addSourceFilenameAttr(fileName);
122 123
			}

S
Skylot 已提交
124
			buildCache();
S
Skylot 已提交
125
		} catch (Exception e) {
126
			throw new JadxRuntimeException("Error decode class: " + clsInfo, e);
S
Skylot 已提交
127 128 129
		}
	}

130 131 132 133 134 135 136 137 138 139 140 141 142 143
	/**
	 * Restore original access flags from Dalvik annotation if present
	 */
	private void initAccessFlags(ClassDef cls) {
		int accFlagsValue;
		Annotation a = getAnnotation(Consts.DALVIK_INNER_CLASS);
		if (a != null) {
			accFlagsValue = (Integer) a.getValues().get("accessFlags");
		} else {
			accFlagsValue = cls.getAccessFlags();
		}
		this.accessFlags = new AccessInfo(accFlagsValue, AFType.CLASS);
	}

144
	// empty synthetic class
145
	public ClassNode(DexNode dex, String name, int accessFlags) {
146
		this.dex = dex;
147
		this.clsDefOffset = 0;
148 149 150 151 152
		this.clsInfo = ClassInfo.fromName(dex.root(), name);
		this.interfaces = new ArrayList<>();
		this.methods = new ArrayList<>();
		this.fields = new ArrayList<>();
		this.accessFlags = new AccessInfo(accessFlags, AFType.CLASS);
153
		this.parentClass = this;
154 155

		dex.addClassNode(this);
156 157
	}

S
Skylot 已提交
158 159 160 161
	private void loadAnnotations(ClassDef cls) {
		int offset = cls.getAnnotationsOffset();
		if (offset != 0) {
			try {
S
Skylot 已提交
162
				new AnnotationsParser(this).parse(offset);
163
			} catch (Exception e) {
S
Skylot 已提交
164
				LOG.error("Error parsing annotations in {}", this, e);
S
Skylot 已提交
165 166 167 168 169 170 171
			}
		}
	}

	private void loadStaticValues(ClassDef cls, List<FieldNode> staticFields) throws DecodeException {
		for (FieldNode f : staticFields) {
			if (f.getAccessFlags().isFinal()) {
172
				f.addAttr(FieldInitAttr.NULL_VALUE);
S
Skylot 已提交
173 174 175
			}
		}
		int offset = cls.getStaticValuesOffset();
176 177 178
		if (offset == 0) {
			return;
		}
179 180 181 182 183 184
		Dex.Section section = dex.openSection(offset);
		StaticValuesParser parser = new StaticValuesParser(dex, section);
		parser.processFields(staticFields);

		// process const fields
		root().getConstValues().processConstFields(this, staticFields);
S
Skylot 已提交
185 186
	}

187
	private void parseClassSignature() {
S
Skylot 已提交
188 189
		SignatureParser sp = SignatureParser.fromNode(this);
		if (sp == null) {
190
			return;
S
Skylot 已提交
191
		}
S
Skylot 已提交
192 193
		try {
			// parse class generic map
194
			generics = sp.consumeGenericMap();
S
Skylot 已提交
195
			// parse super class signature
S
Skylot 已提交
196
			superClass = sp.consumeType();
S
Skylot 已提交
197 198 199 200
			// parse interfaces signatures
			for (int i = 0; i < interfaces.size(); i++) {
				ArgType type = sp.consumeType();
				if (type != null) {
S
Skylot 已提交
201
					interfaces.set(i, type);
S
Skylot 已提交
202 203
				} else {
					break;
204 205
				}
			}
206
		} catch (Exception e) {
S
Skylot 已提交
207
			LOG.error("Class signature parse error: {}", this, e);
208 209 210 211 212
		}
	}

	private void setFieldsTypesFromSignature() {
		for (FieldNode field : fields) {
213 214 215
			try {
				SignatureParser sp = SignatureParser.fromNode(field);
				if (sp != null) {
S
Skylot 已提交
216 217 218 219
					ArgType gType = sp.consumeType();
					if (gType != null) {
						field.setType(gType);
					}
S
Skylot 已提交
220
				}
221 222
			} catch (Exception e) {
				LOG.error("Field signature parse error: {}.{}", this.getFullName(), field.getName(), e);
S
Skylot 已提交
223
			}
224 225 226
		}
	}

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	private void addSourceFilenameAttr(String fileName) {
		if (fileName == null) {
			return;
		}
		if (fileName.endsWith(".java")) {
			fileName = fileName.substring(0, fileName.length() - 5);
		}
		if (fileName.isEmpty()
				|| fileName.equals("SourceFile")
				|| fileName.equals("\"")) {
			return;
		}
		if (clsInfo != null) {
			String name = clsInfo.getShortName();
			if (fileName.equals(name)) {
				return;
			}
			if (fileName.contains("$")
245
					&& fileName.endsWith('$' + name)) {
246 247
				return;
			}
S
Skylot 已提交
248 249
			ClassInfo parentCls = clsInfo.getTopParentClass();
			if (parentCls != null && fileName.equals(parentCls.getShortName())) {
S
Skylot 已提交
250 251
				return;
			}
252 253 254 255
		}
		this.addAttr(new SourceFileAttr(fileName));
	}

256 257 258 259 260 261 262
	public void ensureProcessed() {
		ClassNode topClass = getTopParentClass();
		ProcessState topState = topClass.getState();
		if (!topState.isProcessed()) {
			throw new JadxRuntimeException("Expected class to be processed at this point,"
					+ " class: " + topClass + ", state: " + topState);
		}
S
Skylot 已提交
263 264
	}

265 266 267 268 269 270 271 272 273 274 275 276 277
	public ICodeInfo decompile() {
		return decompile(true);
	}

	public ICodeInfo getCode() {
		return decompile(true);
	}

	public ICodeInfo reloadCode() {
		return decompile(false);
	}

	private synchronized ICodeInfo decompile(boolean searchInCache) {
278 279 280
		ICodeCache codeCache = root().getCodeCache();
		ClassNode topParentClass = getTopParentClass();
		String clsRawName = topParentClass.getRawName();
281 282 283 284 285
		if (searchInCache) {
			ICodeInfo code = codeCache.get(clsRawName);
			if (code != null) {
				return code;
			}
S
Skylot 已提交
286
		}
287 288
		ICodeInfo codeInfo = ProcessClass.generateCode(topParentClass);
		codeCache.add(clsRawName, codeInfo);
S
Skylot 已提交
289 290 291
		return codeInfo;
	}

S
Skylot 已提交
292
	@Override
S
Skylot 已提交
293
	public void load() {
S
Skylot 已提交
294
		for (MethodNode mth : getMethods()) {
S
Skylot 已提交
295 296
			try {
				mth.load();
297
			} catch (Exception e) {
298
				mth.addError("Method load error", e);
S
Skylot 已提交
299
			}
S
Skylot 已提交
300 301 302 303
		}
		for (ClassNode innerCls : getInnerClasses()) {
			innerCls.load();
		}
S
Skylot 已提交
304
		setState(LOADED);
S
Skylot 已提交
305 306 307 308
	}

	@Override
	public void unload() {
309 310 311 312
		methods.forEach(MethodNode::unload);
		innerClasses.forEach(ClassNode::unload);
		fields.forEach(FieldNode::unloadAttributes);
		unloadAttributes();
313
		setState(NOT_LOADED);
S
Skylot 已提交
314 315
	}

S
Skylot 已提交
316
	private void buildCache() {
S
Skylot 已提交
317
		mthInfoMap = new HashMap<>(methods.size());
S
Skylot 已提交
318 319 320 321 322
		for (MethodNode mth : methods) {
			mthInfoMap.put(mth.getMethodInfo(), mth);
		}
	}

S
Skylot 已提交
323 324
	@Nullable
	public ArgType getSuperClass() {
S
Skylot 已提交
325 326 327
		return superClass;
	}

S
Skylot 已提交
328
	public List<ArgType> getInterfaces() {
S
Skylot 已提交
329 330 331
		return interfaces;
	}

332 333
	public List<GenericInfo> getGenerics() {
		return generics;
334 335
	}

S
Skylot 已提交
336 337 338 339 340 341 342 343
	public List<MethodNode> getMethods() {
		return methods;
	}

	public List<FieldNode> getFields() {
		return fields;
	}

344 345 346 347
	public FieldNode getConstField(Object obj) {
		return getConstField(obj, true);
	}

348
	@Nullable
349
	public FieldNode getConstField(Object obj, boolean searchGlobal) {
350
		return root().getConstValues().getConstField(this, obj, searchGlobal);
351 352
	}

353
	@Nullable
1
13.beta2 已提交
354
	public FieldNode getConstFieldByLiteralArg(LiteralArg arg) {
355
		return root().getConstValues().getConstFieldByLiteralArg(this, arg);
1
13.beta2 已提交
356 357
	}

S
Skylot 已提交
358
	public FieldNode searchFieldById(int id) {
359 360 361 362
		return searchField(FieldInfo.fromDex(dex, id));
	}

	public FieldNode searchField(FieldInfo field) {
S
Skylot 已提交
363
		for (FieldNode f : fields) {
364
			if (f.getFieldInfo().equals(field)) {
S
Skylot 已提交
365
				return f;
S
Skylot 已提交
366
			}
S
Skylot 已提交
367 368 369 370
		}
		return null;
	}

371 372 373 374 375 376 377 378 379
	public FieldNode searchFieldByNameAndType(FieldInfo field) {
		for (FieldNode f : fields) {
			if (f.getFieldInfo().equalsNameAndType(field)) {
				return f;
			}
		}
		return null;
	}

S
Skylot 已提交
380
	public FieldNode searchFieldByName(String name) {
S
Skylot 已提交
381
		for (FieldNode f : fields) {
S
Skylot 已提交
382
			if (f.getName().equals(name)) {
S
Skylot 已提交
383
				return f;
S
Skylot 已提交
384
			}
S
Skylot 已提交
385 386 387 388
		}
		return null;
	}

S
Skylot 已提交
389
	public MethodNode searchMethod(MethodInfo mth) {
S
Skylot 已提交
390
		return mthInfoMap.get(mth);
S
Skylot 已提交
391 392
	}

393
	public MethodNode searchMethodByShortId(String shortId) {
S
Skylot 已提交
394
		for (MethodNode m : methods) {
S
Skylot 已提交
395
			if (m.getMethodInfo().getShortId().equals(shortId)) {
S
Skylot 已提交
396
				return m;
S
Skylot 已提交
397
			}
S
Skylot 已提交
398 399 400 401
		}
		return null;
	}

402 403
	/**
	 * Return first method by original short name
404 405
	 * Note: methods are not unique by name (class can have several methods with same name but different
	 * signature)
406 407 408 409 410 411 412 413 414 415 416
	 */
	@Nullable
	public MethodNode searchMethodByShortName(String name) {
		for (MethodNode m : methods) {
			if (m.getMethodInfo().getName().equals(name)) {
				return m;
			}
		}
		return null;
	}

S
Skylot 已提交
417
	public MethodNode searchMethodById(int id) {
418
		return searchMethodByShortId(MethodInfo.fromDex(dex, id).getShortId());
S
Skylot 已提交
419 420
	}

421 422 423 424
	public ClassNode getParentClass() {
		if (parentClass == null) {
			if (clsInfo.isInner()) {
				ClassNode parent = dex().resolveClass(clsInfo.getParentClass());
425
				parentClass = parent == null ? this : parent;
426 427 428 429 430 431 432
			} else {
				parentClass = this;
			}
		}
		return parentClass;
	}

433 434
	public ClassNode getTopParentClass() {
		ClassNode parent = getParentClass();
435
		return parent == this ? this : parent.getTopParentClass();
436 437
	}

438 439 440 441 442 443 444 445 446 447 448
	public boolean hasNotGeneratedParent() {
		if (contains(AFlag.DONT_GENERATE)) {
			return true;
		}
		ClassNode parent = getParentClass();
		if (parent == this) {
			return false;
		}
		return parent.hasNotGeneratedParent();
	}

S
Skylot 已提交
449 450 451 452 453
	public List<ClassNode> getInnerClasses() {
		return innerClasses;
	}

	public void addInnerClass(ClassNode cls) {
454 455 456
		if (innerClasses.isEmpty()) {
			innerClasses = new ArrayList<>(5);
		}
S
Skylot 已提交
457
		innerClasses.add(cls);
458
		cls.parentClass = this;
S
Skylot 已提交
459 460
	}

461
	public boolean isEnum() {
S
Skylot 已提交
462 463 464
		return getAccessFlags().isEnum()
				&& getSuperClass() != null
				&& getSuperClass().getObject().equals(ArgType.ENUM.getObject());
465 466
	}

S
Skylot 已提交
467
	public boolean isAnonymous() {
468
		return contains(AFlag.ANONYMOUS_CLASS);
469 470
	}

471 472
	@Nullable
	public MethodNode getClassInitMth() {
473
		return searchMethodByShortId("<clinit>()V");
474 475 476
	}

	@Nullable
S
Skylot 已提交
477 478
	public MethodNode getDefaultConstructor() {
		for (MethodNode mth : methods) {
479
			if (mth.isDefaultConstructor()) {
S
Skylot 已提交
480
				return mth;
S
Skylot 已提交
481 482
			}
		}
S
Skylot 已提交
483
		return null;
S
Skylot 已提交
484 485
	}

486
	@Override
S
Skylot 已提交
487 488 489 490
	public AccessInfo getAccessFlags() {
		return accessFlags;
	}

491 492 493 494 495
	@Override
	public void setAccessFlags(AccessInfo accessFlags) {
		this.accessFlags = accessFlags;
	}

496
	@Override
S
Skylot 已提交
497 498 499 500
	public DexNode dex() {
		return dex;
	}

501 502 503 504 505
	@Override
	public RootNode root() {
		return dex.root();
	}

506 507 508 509 510
	@Override
	public String typeName() {
		return "class";
	}

S
Skylot 已提交
511 512 513 514 515 516 517
	public String getRawName() {
		return clsInfo.getRawName();
	}

	/**
	 * Internal class info (don't use in code generation and external api).
	 */
S
Skylot 已提交
518 519 520 521 522
	public ClassInfo getClassInfo() {
		return clsInfo;
	}

	public String getShortName() {
523
		return clsInfo.getAliasShortName();
S
Skylot 已提交
524 525 526
	}

	public String getFullName() {
527
		return clsInfo.getAliasFullName();
S
Skylot 已提交
528 529
	}

530 531 532 533
	public String getRealFullName() {
		return clsInfo.getType().getObject();
	}

S
Skylot 已提交
534
	public String getPackage() {
535
		return clsInfo.getAliasPkg();
536 537
	}

538
	public String getSmali() {
539 540 541
		if (smali == null) {
			smali = SmaliUtils.getSmaliCode(dex, clsDefOffset);
		}
542 543 544
		return smali;
	}

545 546 547 548 549 550 551 552
	public ProcessState getState() {
		return state;
	}

	public void setState(ProcessState state) {
		this.state = state;
	}

S
Skylot 已提交
553
	public List<ClassNode> getDependencies() {
554 555 556
		return dependencies;
	}

S
Skylot 已提交
557 558 559 560
	public void setDependencies(List<ClassNode> dependencies) {
		this.dependencies = dependencies;
	}

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
	@Override
	public int hashCode() {
		return clsInfo.hashCode();
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o instanceof ClassNode) {
			ClassNode other = (ClassNode) o;
			return clsInfo.equals(other.clsInfo);
		}
		return false;
	}

S
Skylot 已提交
578 579
	@Override
	public String toString() {
S
Skylot 已提交
580
		return clsInfo.getFullName();
S
Skylot 已提交
581
	}
582

S
Skylot 已提交
583
}