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

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

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

14 15 16 17 18 19
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;

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

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

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

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

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

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

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

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

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

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

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

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

		dex.addClassNode(this);
157 158
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	public String getPackage() {
532
		return clsInfo.getAliasPkg();
533 534
	}

535
	public String getSmali() {
536
		if (smali == null) {
537 538 539 540 541 542 543 544
			StringWriter stringWriter = new StringWriter(4096);
			getSmali(this, stringWriter);
			stringWriter.append(System.lineSeparator());
			for (ClassNode innerClass : innerClasses) {
				getSmali(innerClass, stringWriter);
				stringWriter.append(System.lineSeparator());
			}
			smali = stringWriter.toString();
545
		}
546 547 548
		return smali;
	}

549 550 551 552 553 554
	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);
	}

555 556 557 558 559 560 561 562
	public ProcessState getState() {
		return state;
	}

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

S
Skylot 已提交
563
	public List<ClassNode> getDependencies() {
564 565 566
		return dependencies;
	}

S
Skylot 已提交
567 568 569 570
	public void setDependencies(List<ClassNode> dependencies) {
		this.dependencies = dependencies;
	}

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
	@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 已提交
588 589
	@Override
	public String toString() {
S
Skylot 已提交
590
		return clsInfo.getFullName();
S
Skylot 已提交
591
	}
592

S
Skylot 已提交
593
}