ClassNode.java 14.7 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
				}
S
Skylot 已提交
105
				loadStaticValues(cls, fields);
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 173 174
			}
		}
	}

	private void loadStaticValues(ClassDef cls, List<FieldNode> staticFields) throws DecodeException {
		for (FieldNode f : staticFields) {
			if (f.getAccessFlags().isFinal()) {
175
				f.addAttr(FieldInitAttr.NULL_VALUE);
S
Skylot 已提交
176 177 178
			}
		}
		int offset = cls.getStaticValuesOffset();
179 180 181
		if (offset == 0) {
			return;
		}
182 183 184 185 186 187
		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 已提交
188 189
	}

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

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

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

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

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

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

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

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

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

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
	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) {
				loadStaticValues(cls, fields);
			}
		} catch (DecodeException e) {
			LOG.error("Got DecodeException in loadStaticValues() for class {}", getRawName());
			e.printStackTrace();
		}
	}

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

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

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

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

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

365 366
	public List<GenericInfo> getGenerics() {
		return generics;
367 368
	}

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

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

377 378 379 380
	public FieldNode getConstField(Object obj) {
		return getConstField(obj, true);
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	public String getPackage() {
564
		return clsInfo.getAliasPkg();
565 566
	}

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

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

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

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

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

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

S
Skylot 已提交
612
}