ClassNode.java 14.9 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 ClassDef cls;
50
	private final int clsDefOffset;
S
Skylot 已提交
51
	private final ClassInfo clsInfo;
52
	private AccessInfo accessFlags;
S
Skylot 已提交
53 54
	private ArgType superClass;
	private List<ArgType> interfaces;
55
	private List<GenericInfo> generics = Collections.emptyList();
S
Skylot 已提交
56

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

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

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

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

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

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

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

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

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

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

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

132 133 134 135 136 137 138 139 140 141 142 143 144 145
	/**
	 * 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);
	}

146
	// empty synthetic class
147
	public ClassNode(DexNode dex, String name, int accessFlags) {
148
		this.dex = dex;
149
		this.clsDefOffset = 0;
150 151 152 153 154
		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);
155
		this.parentClass = this;
156
		this.cls = null;
157 158

		dex.addClassNode(this);
159 160
	}

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

172
	private void loadStaticValues(ClassDef cls, List<FieldNode> staticFields, boolean isRefresh) throws DecodeException {
S
Skylot 已提交
173
		for (FieldNode f : staticFields) {
174 175 176
			AccessInfo flags = f.getAccessFlags();
			if (flags.isStatic() && flags.isFinal()) {
				LOG.debug("loadStaticValues(): Adding NULL initializer to static final field {}", f.getAlias());
177
				f.addAttr(FieldInitAttr.NULL_VALUE);
S
Skylot 已提交
178 179 180
			}
		}
		int offset = cls.getStaticValuesOffset();
181 182 183
		if (offset == 0) {
			return;
		}
184 185 186 187 188
		Dex.Section section = dex.openSection(offset);
		StaticValuesParser parser = new StaticValuesParser(dex, section);
		parser.processFields(staticFields);

		// process const fields
189
		root().getConstValues().processConstFields(this, staticFields, isRefresh);
S
Skylot 已提交
190 191
	}

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

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

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	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("$")
250
					&& fileName.endsWith('$' + name)) {
251 252
				return;
			}
S
Skylot 已提交
253 254
			ClassInfo parentCls = clsInfo.getTopParentClass();
			if (parentCls != null && fileName.equals(parentCls.getShortName())) {
S
Skylot 已提交
255 256
				return;
			}
257 258 259 260
		}
		this.addAttr(new SourceFileAttr(fileName));
	}

261 262 263 264 265 266 267
	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 已提交
268 269
	}

270 271 272 273 274 275 276 277 278 279 280 281 282
	public ICodeInfo decompile() {
		return decompile(true);
	}

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

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

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

297
	public synchronized ICodeInfo refresh() {
298
		reloadRecursive();
299 300 301
		return decompile(false);
	}

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
	private void reloadRecursive() {
		load();
		int sfIdx = cls.getSourceFileIndex();
		if (sfIdx != DexNode.NO_INDEX) {
			String fileName = dex.getString(sfIdx);
			addSourceFilenameAttr(fileName);
		}
		for (ClassNode innerCls : getInnerClasses()) {
			innerCls.reloadRecursive();
		}
		loadStaticInfo();
		loadAnnotations(cls);
	}

	private void loadStaticInfo() {
		try {
			if (cls != null) {
319
				loadStaticValues(cls, fields, true);
320 321 322 323 324 325 326
			}
		} catch (DecodeException e) {
			LOG.error("Got DecodeException in loadStaticValues() for class {}", getRawName());
			e.printStackTrace();
		}
	}

S
Skylot 已提交
327
	@Override
S
Skylot 已提交
328
	public void load() {
S
Skylot 已提交
329
		for (MethodNode mth : getMethods()) {
S
Skylot 已提交
330 331
			try {
				mth.load();
332
			} catch (Exception e) {
333
				mth.addError("Method load error", e);
S
Skylot 已提交
334
			}
S
Skylot 已提交
335 336 337 338
		}
		for (ClassNode innerCls : getInnerClasses()) {
			innerCls.load();
		}
S
Skylot 已提交
339
		setState(LOADED);
S
Skylot 已提交
340 341 342 343
	}

	@Override
	public void unload() {
344 345 346 347
		methods.forEach(MethodNode::unload);
		innerClasses.forEach(ClassNode::unload);
		fields.forEach(FieldNode::unloadAttributes);
		unloadAttributes();
348
		setState(NOT_LOADED);
S
Skylot 已提交
349 350
	}

S
Skylot 已提交
351
	private void buildCache() {
S
Skylot 已提交
352
		mthInfoMap = new HashMap<>(methods.size());
S
Skylot 已提交
353 354 355 356 357
		for (MethodNode mth : methods) {
			mthInfoMap.put(mth.getMethodInfo(), mth);
		}
	}

S
Skylot 已提交
358 359
	@Nullable
	public ArgType getSuperClass() {
S
Skylot 已提交
360 361 362
		return superClass;
	}

S
Skylot 已提交
363
	public List<ArgType> getInterfaces() {
S
Skylot 已提交
364 365 366
		return interfaces;
	}

367 368
	public List<GenericInfo> getGenerics() {
		return generics;
369 370
	}

S
Skylot 已提交
371 372 373 374 375 376 377 378
	public List<MethodNode> getMethods() {
		return methods;
	}

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

379 380 381 382
	public FieldNode getConstField(Object obj) {
		return getConstField(obj, true);
	}

383
	@Nullable
384
	public FieldNode getConstField(Object obj, boolean searchGlobal) {
385
		return root().getConstValues().getConstField(this, obj, searchGlobal);
386 387
	}

388
	@Nullable
1
13.beta2 已提交
389
	public FieldNode getConstFieldByLiteralArg(LiteralArg arg) {
390
		return root().getConstValues().getConstFieldByLiteralArg(this, arg);
1
13.beta2 已提交
391 392
	}

S
Skylot 已提交
393
	public FieldNode searchFieldById(int id) {
394 395 396 397
		return searchField(FieldInfo.fromDex(dex, id));
	}

	public FieldNode searchField(FieldInfo field) {
S
Skylot 已提交
398
		for (FieldNode f : fields) {
399
			if (f.getFieldInfo().equals(field)) {
S
Skylot 已提交
400
				return f;
S
Skylot 已提交
401
			}
S
Skylot 已提交
402 403 404 405
		}
		return null;
	}

406 407 408 409 410 411 412 413 414
	public FieldNode searchFieldByNameAndType(FieldInfo field) {
		for (FieldNode f : fields) {
			if (f.getFieldInfo().equalsNameAndType(field)) {
				return f;
			}
		}
		return null;
	}

S
Skylot 已提交
415
	public FieldNode searchFieldByName(String name) {
S
Skylot 已提交
416
		for (FieldNode f : fields) {
S
Skylot 已提交
417
			if (f.getName().equals(name)) {
S
Skylot 已提交
418
				return f;
S
Skylot 已提交
419
			}
S
Skylot 已提交
420 421 422 423
		}
		return null;
	}

S
Skylot 已提交
424
	public MethodNode searchMethod(MethodInfo mth) {
S
Skylot 已提交
425
		return mthInfoMap.get(mth);
S
Skylot 已提交
426 427
	}

428
	public MethodNode searchMethodByShortId(String shortId) {
S
Skylot 已提交
429
		for (MethodNode m : methods) {
S
Skylot 已提交
430
			if (m.getMethodInfo().getShortId().equals(shortId)) {
S
Skylot 已提交
431
				return m;
S
Skylot 已提交
432
			}
S
Skylot 已提交
433 434 435 436
		}
		return null;
	}

437 438
	/**
	 * Return first method by original short name
439 440
	 * Note: methods are not unique by name (class can have several methods with same name but different
	 * signature)
441 442 443 444 445 446 447 448 449 450 451
	 */
	@Nullable
	public MethodNode searchMethodByShortName(String name) {
		for (MethodNode m : methods) {
			if (m.getMethodInfo().getName().equals(name)) {
				return m;
			}
		}
		return null;
	}

S
Skylot 已提交
452
	public MethodNode searchMethodById(int id) {
453
		return searchMethodByShortId(MethodInfo.fromDex(dex, id).getShortId());
S
Skylot 已提交
454 455
	}

456 457 458 459
	public ClassNode getParentClass() {
		if (parentClass == null) {
			if (clsInfo.isInner()) {
				ClassNode parent = dex().resolveClass(clsInfo.getParentClass());
460
				parentClass = parent == null ? this : parent;
461 462 463 464 465 466 467
			} else {
				parentClass = this;
			}
		}
		return parentClass;
	}

468 469
	public ClassNode getTopParentClass() {
		ClassNode parent = getParentClass();
470
		return parent == this ? this : parent.getTopParentClass();
471 472
	}

473 474 475 476 477 478 479 480 481 482 483
	public boolean hasNotGeneratedParent() {
		if (contains(AFlag.DONT_GENERATE)) {
			return true;
		}
		ClassNode parent = getParentClass();
		if (parent == this) {
			return false;
		}
		return parent.hasNotGeneratedParent();
	}

S
Skylot 已提交
484 485 486 487 488
	public List<ClassNode> getInnerClasses() {
		return innerClasses;
	}

	public void addInnerClass(ClassNode cls) {
489 490 491
		if (innerClasses.isEmpty()) {
			innerClasses = new ArrayList<>(5);
		}
S
Skylot 已提交
492
		innerClasses.add(cls);
493
		cls.parentClass = this;
S
Skylot 已提交
494 495
	}

496
	public boolean isEnum() {
S
Skylot 已提交
497 498 499
		return getAccessFlags().isEnum()
				&& getSuperClass() != null
				&& getSuperClass().getObject().equals(ArgType.ENUM.getObject());
500 501
	}

S
Skylot 已提交
502
	public boolean isAnonymous() {
503
		return contains(AFlag.ANONYMOUS_CLASS);
504 505
	}

506 507
	@Nullable
	public MethodNode getClassInitMth() {
508
		return searchMethodByShortId("<clinit>()V");
509 510 511
	}

	@Nullable
S
Skylot 已提交
512 513
	public MethodNode getDefaultConstructor() {
		for (MethodNode mth : methods) {
514
			if (mth.isDefaultConstructor()) {
S
Skylot 已提交
515
				return mth;
S
Skylot 已提交
516 517
			}
		}
S
Skylot 已提交
518
		return null;
S
Skylot 已提交
519 520
	}

521
	@Override
S
Skylot 已提交
522 523 524 525
	public AccessInfo getAccessFlags() {
		return accessFlags;
	}

526 527 528 529 530
	@Override
	public void setAccessFlags(AccessInfo accessFlags) {
		this.accessFlags = accessFlags;
	}

531
	@Override
S
Skylot 已提交
532 533 534 535
	public DexNode dex() {
		return dex;
	}

536 537 538 539 540
	@Override
	public RootNode root() {
		return dex.root();
	}

541 542 543 544 545
	@Override
	public String typeName() {
		return "class";
	}

S
Skylot 已提交
546 547 548 549 550 551 552
	public String getRawName() {
		return clsInfo.getRawName();
	}

	/**
	 * Internal class info (don't use in code generation and external api).
	 */
S
Skylot 已提交
553 554 555 556 557
	public ClassInfo getClassInfo() {
		return clsInfo;
	}

	public String getShortName() {
558
		return clsInfo.getAliasShortName();
S
Skylot 已提交
559 560 561
	}

	public String getFullName() {
562
		return clsInfo.getAliasFullName();
S
Skylot 已提交
563 564 565
	}

	public String getPackage() {
566
		return clsInfo.getAliasPkg();
567 568
	}

569
	public String getSmali() {
570 571 572
		if (smali == null) {
			smali = SmaliUtils.getSmaliCode(dex, clsDefOffset);
		}
573 574 575
		return smali;
	}

576 577 578 579 580 581 582 583
	public ProcessState getState() {
		return state;
	}

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

S
Skylot 已提交
584
	public List<ClassNode> getDependencies() {
585 586 587
		return dependencies;
	}

S
Skylot 已提交
588 589 590 591
	public void setDependencies(List<ClassNode> dependencies) {
		this.dependencies = dependencies;
	}

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
	@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 已提交
609 610
	@Override
	public String toString() {
S
Skylot 已提交
611
		return clsInfo.getFullName();
S
Skylot 已提交
612
	}
613

S
Skylot 已提交
614
}