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

3
import java.io.StringWriter;
4 5 6
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
7
import java.util.LinkedHashSet;
8 9
import java.util.List;
import java.util.Map;
10
import java.util.Set;
11

12 13 14 15
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

16 17 18 19 20 21
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;

22
import jadx.api.ICodeCache;
S
Skylot 已提交
23
import jadx.api.ICodeInfo;
S
Skylot 已提交
24
import jadx.core.Consts;
S
Skylot 已提交
25
import jadx.core.ProcessClass;
26
import jadx.core.dex.attributes.AFlag;
S
Skylot 已提交
27
import jadx.core.dex.attributes.annotations.Annotation;
S
Skylot 已提交
28 29
import jadx.core.dex.attributes.nodes.LineAttrNode;
import jadx.core.dex.attributes.nodes.SourceFileAttr;
S
Skylot 已提交
30 31 32 33 34 35
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 已提交
36
import jadx.core.dex.instructions.args.LiteralArg;
S
Skylot 已提交
37
import jadx.core.dex.nodes.parser.AnnotationsParser;
38
import jadx.core.dex.nodes.parser.FieldInitAttr;
S
Skylot 已提交
39
import jadx.core.dex.nodes.parser.SignatureParser;
S
Skylot 已提交
40
import jadx.core.dex.nodes.parser.StaticValuesParser;
41
import jadx.core.utils.SmaliUtils;
S
Skylot 已提交
42
import jadx.core.utils.exceptions.DecodeException;
S
Skylot 已提交
43
import jadx.core.utils.exceptions.JadxRuntimeException;
S
Skylot 已提交
44

S
Skylot 已提交
45
import static jadx.core.dex.nodes.ProcessState.LOADED;
46
import static jadx.core.dex.nodes.ProcessState.NOT_LOADED;
47

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

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

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

63 64
	private List<ClassNode> inlinedClasses = Collections.emptyList();

65 66
	// store smali
	private String smali;
67 68
	// store parent for inner classes or 'this' otherwise
	private ClassNode parentClass;
S
Skylot 已提交
69

S
Skylot 已提交
70
	private volatile ProcessState state = ProcessState.NOT_LOADED;
S
Skylot 已提交
71
	private List<ClassNode> dependencies = Collections.emptyList();
72

S
Skylot 已提交
73 74 75
	// cache maps
	private Map<MethodInfo, MethodNode> mthInfoMap = Collections.emptyMap();

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

S
Skylot 已提交
95 96
				methods = new ArrayList<>(mthsCount);
				fields = new ArrayList<>(fieldsCount);
S
Skylot 已提交
97

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

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

			loadAnnotations(cls);
118
			initAccessFlags(cls);
119 120
			parseClassSignature();
			setFieldsTypesFromSignature();
121
			methods.forEach(MethodNode::initMethodTypes);
S
Skylot 已提交
122

123
			int sfIdx = cls.getSourceFileIndex();
124
			if (sfIdx != DexNode.NO_INDEX) {
125
				String fileName = dex.getString(sfIdx);
126
				addSourceFilenameAttr(fileName);
127 128
			}

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

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

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

		dex.addClassNode(this);
161 162
	}

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

	private void loadStaticValues(ClassDef cls, List<FieldNode> staticFields) throws DecodeException {
		for (FieldNode f : staticFields) {
			if (f.getAccessFlags().isFinal()) {
177
				// incorrect initialization will be removed if assign found in constructor
178
				f.addAttr(FieldInitAttr.NULL_VALUE);
S
Skylot 已提交
179 180 181
			}
		}
		int offset = cls.getStaticValuesOffset();
182 183 184
		if (offset == 0) {
			return;
		}
185 186 187 188 189 190
		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 已提交
191 192
	}

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

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

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

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

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

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

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

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

S
Skylot 已提交
298
	@Override
S
Skylot 已提交
299
	public void load() {
S
Skylot 已提交
300
		for (MethodNode mth : getMethods()) {
S
Skylot 已提交
301 302
			try {
				mth.load();
303
			} catch (Exception e) {
304
				mth.addError("Method load error", e);
S
Skylot 已提交
305
			}
S
Skylot 已提交
306 307 308 309
		}
		for (ClassNode innerCls : getInnerClasses()) {
			innerCls.load();
		}
S
Skylot 已提交
310
		setState(LOADED);
S
Skylot 已提交
311 312 313 314
	}

	@Override
	public void unload() {
315 316 317 318
		methods.forEach(MethodNode::unload);
		innerClasses.forEach(ClassNode::unload);
		fields.forEach(FieldNode::unloadAttributes);
		unloadAttributes();
319
		setState(NOT_LOADED);
S
Skylot 已提交
320 321
	}

S
Skylot 已提交
322
	private void buildCache() {
S
Skylot 已提交
323
		mthInfoMap = new HashMap<>(methods.size());
S
Skylot 已提交
324 325 326 327 328
		for (MethodNode mth : methods) {
			mthInfoMap.put(mth.getMethodInfo(), mth);
		}
	}

S
Skylot 已提交
329 330
	@Nullable
	public ArgType getSuperClass() {
S
Skylot 已提交
331 332 333
		return superClass;
	}

S
Skylot 已提交
334
	public List<ArgType> getInterfaces() {
S
Skylot 已提交
335 336 337
		return interfaces;
	}

338 339
	public List<GenericInfo> getGenerics() {
		return generics;
340 341
	}

S
Skylot 已提交
342 343 344 345 346 347 348 349
	public List<MethodNode> getMethods() {
		return methods;
	}

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

350 351 352 353
	public FieldNode getConstField(Object obj) {
		return getConstField(obj, true);
	}

354
	@Nullable
355
	public FieldNode getConstField(Object obj, boolean searchGlobal) {
356
		return root().getConstValues().getConstField(this, obj, searchGlobal);
357 358
	}

359
	@Nullable
1
13.beta2 已提交
360
	public FieldNode getConstFieldByLiteralArg(LiteralArg arg) {
361
		return root().getConstValues().getConstFieldByLiteralArg(this, arg);
1
13.beta2 已提交
362 363
	}

S
Skylot 已提交
364
	public FieldNode searchFieldById(int id) {
365 366 367 368
		return searchField(FieldInfo.fromDex(dex, id));
	}

	public FieldNode searchField(FieldInfo field) {
S
Skylot 已提交
369
		for (FieldNode f : fields) {
370
			if (f.getFieldInfo().equals(field)) {
S
Skylot 已提交
371
				return f;
S
Skylot 已提交
372
			}
S
Skylot 已提交
373 374 375 376
		}
		return null;
	}

377 378 379 380 381 382 383 384 385
	public FieldNode searchFieldByNameAndType(FieldInfo field) {
		for (FieldNode f : fields) {
			if (f.getFieldInfo().equalsNameAndType(field)) {
				return f;
			}
		}
		return null;
	}

S
Skylot 已提交
386
	public FieldNode searchFieldByName(String name) {
S
Skylot 已提交
387
		for (FieldNode f : fields) {
S
Skylot 已提交
388
			if (f.getName().equals(name)) {
S
Skylot 已提交
389
				return f;
S
Skylot 已提交
390
			}
S
Skylot 已提交
391 392 393 394
		}
		return null;
	}

S
Skylot 已提交
395
	public MethodNode searchMethod(MethodInfo mth) {
S
Skylot 已提交
396
		return mthInfoMap.get(mth);
S
Skylot 已提交
397 398
	}

399
	public MethodNode searchMethodByShortId(String shortId) {
S
Skylot 已提交
400
		for (MethodNode m : methods) {
S
Skylot 已提交
401
			if (m.getMethodInfo().getShortId().equals(shortId)) {
S
Skylot 已提交
402
				return m;
S
Skylot 已提交
403
			}
S
Skylot 已提交
404 405 406 407
		}
		return null;
	}

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

S
Skylot 已提交
423
	public MethodNode searchMethodById(int id) {
424
		return searchMethodByShortId(MethodInfo.fromDex(dex, id).getShortId());
S
Skylot 已提交
425 426
	}

427 428 429 430
	public ClassNode getParentClass() {
		if (parentClass == null) {
			if (clsInfo.isInner()) {
				ClassNode parent = dex().resolveClass(clsInfo.getParentClass());
431
				parentClass = parent == null ? this : parent;
432 433 434 435 436 437 438
			} else {
				parentClass = this;
			}
		}
		return parentClass;
	}

439 440
	public ClassNode getTopParentClass() {
		ClassNode parent = getParentClass();
441
		return parent == this ? this : parent.getTopParentClass();
442 443
	}

444 445 446 447 448 449 450 451 452 453 454
	public boolean hasNotGeneratedParent() {
		if (contains(AFlag.DONT_GENERATE)) {
			return true;
		}
		ClassNode parent = getParentClass();
		if (parent == this) {
			return false;
		}
		return parent.hasNotGeneratedParent();
	}

S
Skylot 已提交
455 456 457 458
	public List<ClassNode> getInnerClasses() {
		return innerClasses;
	}

459
	/**
460
	 * Get all inner and inlined classes recursively
461
	 *
462
	 * @param resultClassesSet all identified inner and inlined classes are added to this set
463
	 */
464 465 466 467 468 469 470 471 472 473
	public void getInnerAndInlinedClassesRecursive(Set<ClassNode> resultClassesSet) {
		for (ClassNode innerCls : innerClasses) {
			if (resultClassesSet.add(innerCls)) {
				innerCls.getInnerAndInlinedClassesRecursive(resultClassesSet);
			}
		}
		for (ClassNode inlinedCls : inlinedClasses) {
			if (resultClassesSet.add(inlinedCls)) {
				inlinedCls.getInnerAndInlinedClassesRecursive(resultClassesSet);
			}
474 475 476
		}
	}

S
Skylot 已提交
477
	public void addInnerClass(ClassNode cls) {
478 479 480
		if (innerClasses.isEmpty()) {
			innerClasses = new ArrayList<>(5);
		}
S
Skylot 已提交
481
		innerClasses.add(cls);
482
		cls.parentClass = this;
S
Skylot 已提交
483 484
	}

485 486 487 488 489 490 491
	public void addInlinedClass(ClassNode cls) {
		if (inlinedClasses.isEmpty()) {
			inlinedClasses = new ArrayList<>(5);
		}
		inlinedClasses.add(cls);
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

	public String getPackage() {
562
		return clsInfo.getAliasPkg();
563 564
	}

565
	public String getSmali() {
566
		if (smali == null) {
567 568 569
			StringWriter stringWriter = new StringWriter(4096);
			getSmali(this, stringWriter);
			stringWriter.append(System.lineSeparator());
570 571 572
			Set<ClassNode> allInlinedClasses = new LinkedHashSet<>();
			getInnerAndInlinedClassesRecursive(allInlinedClasses);
			for (ClassNode innerClass : allInlinedClasses) {
573 574 575 576
				getSmali(innerClass, stringWriter);
				stringWriter.append(System.lineSeparator());
			}
			smali = stringWriter.toString();
577
		}
578 579 580
		return smali;
	}

581 582 583 584 585 586
	protected static boolean getSmali(ClassNode classNode, StringWriter stringWriter) {
		stringWriter.append(String.format("###### Class %s (%s)", classNode.getFullName(), classNode.getRawName()));
		stringWriter.append(System.lineSeparator());
		return SmaliUtils.getSmaliCode(classNode.dex, classNode.clsDefOffset, stringWriter);
	}

587 588 589 590 591 592 593 594
	public ProcessState getState() {
		return state;
	}

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

S
Skylot 已提交
595
	public List<ClassNode> getDependencies() {
596 597 598
		return dependencies;
	}

S
Skylot 已提交
599 600 601 602
	public void setDependencies(List<ClassNode> dependencies) {
		this.dependencies = dependencies;
	}

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
	@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 已提交
620 621
	@Override
	public String toString() {
S
Skylot 已提交
622
		return clsInfo.getFullName();
S
Skylot 已提交
623
	}
624

S
Skylot 已提交
625
}