ClassNode.java 10.4 KB
Newer Older
S
Skylot 已提交
1 2 3 4 5
package jadx.core.dex.nodes;

import jadx.core.Consts;
import jadx.core.codegen.CodeWriter;
import jadx.core.dex.attributes.AttributeType;
6
import jadx.core.dex.attributes.LineAttrNode;
S
Skylot 已提交
7 8 9 10 11 12 13 14
import jadx.core.dex.attributes.SourceFileAttr;
import jadx.core.dex.attributes.annotations.Annotation;
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 已提交
15
import jadx.core.dex.instructions.args.LiteralArg;
16
import jadx.core.dex.instructions.args.PrimitiveType;
S
Skylot 已提交
17 18 19 20 21
import jadx.core.dex.nodes.parser.AnnotationsParser;
import jadx.core.dex.nodes.parser.FieldValueAttr;
import jadx.core.dex.nodes.parser.StaticValuesParser;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.DecodeException;
S
Skylot 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.android.dx.io.ClassData;
import com.android.dx.io.ClassData.Field;
import com.android.dx.io.ClassData.Method;
import com.android.dx.io.ClassDef;

37
public class ClassNode extends LineAttrNode implements ILoadable {
S
Skylot 已提交
38
	private static final Logger LOG = LoggerFactory.getLogger(ClassNode.class);
S
Skylot 已提交
39 40 41

	private final DexNode dex;
	private final ClassInfo clsInfo;
42 43 44
	private ClassInfo superClass;
	private List<ClassInfo> interfaces;
	private Map<ArgType, List<ArgType>> genericMap;
S
Skylot 已提交
45 46 47 48 49 50 51 52 53

	private final List<MethodNode> methods = new ArrayList<MethodNode>();
	private final List<FieldNode> fields = new ArrayList<FieldNode>();

	private final AccessInfo accessFlags;
	private List<ClassNode> innerClasses = Collections.emptyList();

	private final Map<Object, FieldNode> constFields = new HashMap<Object, FieldNode>();

S
Skylot 已提交
54 55
	private CodeWriter code; // generated code

S
Skylot 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68
	public ClassNode(DexNode dex, ClassDef cls) throws DecodeException {
		this.dex = dex;
		this.clsInfo = ClassInfo.fromDex(dex, cls.getTypeIndex());
		try {
			this.superClass = cls.getSupertypeIndex() == DexNode.NO_INDEX
					? null
					: ClassInfo.fromDex(dex, cls.getSupertypeIndex());

			this.interfaces = new ArrayList<ClassInfo>(cls.getInterfaces().length);
			for (short interfaceIdx : cls.getInterfaces()) {
				this.interfaces.add(ClassInfo.fromDex(dex, interfaceIdx));
			}

S
Skylot 已提交
69
			if (cls.getClassDataOffset() != 0) {
S
Skylot 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
				ClassData clsData = dex.readClassData(cls);

				for (Method mth : clsData.getDirectMethods())
					methods.add(new MethodNode(this, mth));

				for (Method mth : clsData.getVirtualMethods())
					methods.add(new MethodNode(this, mth));

				for (Field f : clsData.getStaticFields())
					fields.add(new FieldNode(this, f));

				loadStaticValues(cls, fields);

				for (Field f : clsData.getInstanceFields())
					fields.add(new FieldNode(this, f));
			}

			loadAnnotations(cls);

89 90
			parseClassSignature();
			setFieldsTypesFromSignature();
S
Skylot 已提交
91

92
			int sfIdx = cls.getSourceFileIndex();
93
			if (sfIdx != DexNode.NO_INDEX) {
94
				String fileName = dex.getString(sfIdx);
95
				if (!this.getFullName().contains(fileName.replace(".java", ""))) {
96
					this.getAttributes().add(new SourceFileAttr(fileName));
S
Skylot 已提交
97
					LOG.debug("Class '{}' compiled from '{}'", this, fileName);
98 99 100
				}
			}

101
			int accFlagsValue;
102
			Annotation a = getAttributes().getAnnotation(Consts.DALVIK_INNER_CLASS);
103 104 105 106
			if (a != null)
				accFlagsValue = (Integer) a.getValues().get("accessFlags");
			else
				accFlagsValue = cls.getAccessFlags();
S
Skylot 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

			this.accessFlags = new AccessInfo(accFlagsValue, AFType.CLASS);

		} catch (Exception e) {
			throw new DecodeException("Error decode class: " + getFullName(), e);
		}
	}

	private void loadAnnotations(ClassDef cls) {
		int offset = cls.getAnnotationsOffset();
		if (offset != 0) {
			try {
				new AnnotationsParser(this, offset);
			} catch (DecodeException e) {
				LOG.error("Error parsing annotations in " + this, e);
			}
		}
	}

	private void loadStaticValues(ClassDef cls, List<FieldNode> staticFields) throws DecodeException {
		for (FieldNode f : staticFields) {
			if (f.getAccessFlags().isFinal()) {
				FieldValueAttr nullValue = new FieldValueAttr(null);
				f.getAttributes().add(nullValue);
			}
		}

		int offset = cls.getStaticValuesOffset();
		if (offset != 0) {
			StaticValuesParser parser = new StaticValuesParser(dex, dex.openSection(offset));
			parser.processFields(staticFields);

			for (FieldNode f : staticFields) {
140 141
				AccessInfo accFlags = f.getAccessFlags();
				if (accFlags.isStatic() && accFlags.isFinal()) {
S
Skylot 已提交
142 143
					FieldValueAttr fv = (FieldValueAttr) f.getAttributes().get(AttributeType.FIELD_VALUE);
					if (fv != null && fv.getValue() != null) {
144
						if (accFlags.isPublic()) {
145
							dex.getConstFields().put(fv.getValue(), f);
146 147
						}
						constFields.put(fv.getValue(), f);
S
Skylot 已提交
148 149 150 151 152 153
					}
				}
			}
		}
	}

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
	@SuppressWarnings("unchecked")
	private void parseClassSignature() {
		Annotation a = this.getAttributes().getAnnotation(Consts.DALVIK_SIGNATURE);
		if (a == null)
			return;

		String sign = Utils.mergeSignature((List<String>) a.getDefaultValue());
		// parse generic map
		int end = Utils.getGenericEnd(sign);
		if (end != -1) {
			String gen = sign.substring(1, end);
			genericMap = ArgType.parseGenericMap(gen);
			sign = sign.substring(end + 1);
		}

		// parse super class signature and interfaces
		List<ArgType> list = ArgType.parseSignatureList(sign);
		if (list != null && !list.isEmpty()) {
			try {
				ArgType st = list.remove(0);
S
Skylot 已提交
174
				this.superClass = ClassInfo.fromType(st);
175 176
				int i = 0;
				for (ArgType it : list) {
S
Skylot 已提交
177
					ClassInfo interf = ClassInfo.fromType(it);
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
					interfaces.set(i, interf);
					i++;
				}
			} catch (Throwable e) {
				LOG.warn("Can't set signatures for class: {}, sign: {}", this, sign, e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void setFieldsTypesFromSignature() {
		for (FieldNode field : fields) {
			Annotation a = field.getAttributes().getAnnotation(Consts.DALVIK_SIGNATURE);
			if (a == null)
				continue;

			String sign = Utils.mergeSignature((List<String>) a.getDefaultValue());
			ArgType gType = ArgType.parseSignature(sign);
			if (gType != null)
				field.setType(gType);
		}
	}

S
Skylot 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
	@Override
	public void load() throws DecodeException {
		for (MethodNode mth : getMethods()) {
			mth.load();
		}
		for (ClassNode innerCls : getInnerClasses()) {
			innerCls.load();
		}
	}

	@Override
	public void unload() {
		for (MethodNode mth : getMethods()) {
			mth.unload();
		}
		for (ClassNode innerCls : getInnerClasses()) {
			innerCls.unload();
		}
	}

	public ClassInfo getSuperClass() {
		return superClass;
	}

	public List<ClassInfo> getInterfaces() {
		return interfaces;
	}

229 230 231 232
	public Map<ArgType, List<ArgType>> getGenericMap() {
		return genericMap;
	}

S
Skylot 已提交
233 234 235 236 237 238 239 240
	public List<MethodNode> getMethods() {
		return methods;
	}

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

241 242 243 244 245
	public FieldNode getConstField(Object obj) {
		return getConstField(obj, true);
	}

	public FieldNode getConstField(Object obj, boolean searchGlobal) {
246 247 248
		ClassNode cn = this;
		FieldNode field;
		do {
249
			field = cn.constFields.get(obj);
250 251
		}
		while (field == null
252 253
				&& (cn.clsInfo.getParentClass() != null)
				&& (cn = dex.resolveClass(cn.clsInfo.getParentClass())) != null);
254

255 256 257
		if (field == null && searchGlobal) {
			field = dex.getConstFields().get(obj);
		}
258 259 260
		return field;
	}

1
13.beta2 已提交
261
	public FieldNode getConstFieldByLiteralArg(LiteralArg arg) {
262 263 264 265
		PrimitiveType type = arg.getType().getPrimitiveType();
		if (type == null) {
			return null;
		}
1
13.beta2 已提交
266
		long literal = arg.getLiteral();
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
		switch (type) {
			case BOOLEAN:
				return getConstField(literal == 1, false);
			case CHAR:
				return getConstField((char) literal, Math.abs(literal) > 1);
			case BYTE:
				return getConstField((byte) literal, Math.abs(literal) > 1);
			case SHORT:
				return getConstField((short) literal, Math.abs(literal) > 1);
			case INT:
				return getConstField((int) literal, Math.abs(literal) > 1);
			case LONG:
				return getConstField(literal, Math.abs(literal) > 1);
			case FLOAT:
				return getConstField(Float.intBitsToFloat((int) literal), true);
			case DOUBLE:
				return getConstField(Double.longBitsToDouble(literal), true);
1
13.beta2 已提交
284 285 286 287
		}
		return null;
	}

S
Skylot 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
	public FieldNode searchFieldById(int id) {
		String name = FieldInfo.getNameById(dex, id);
		for (FieldNode f : fields) {
			if (f.getName().equals(name))
				return f;
		}
		return null;
	}

	public FieldNode searchField(FieldInfo field) {
		String name = field.getName();
		for (FieldNode f : fields) {
			if (f.getName().equals(name))
				return f;
		}
		return null;
	}

S
Skylot 已提交
306 307 308 309 310 311 312 313 314
	public MethodNode searchMethod(MethodInfo mth) {
		for (MethodNode m : methods) {
			if (m.getMethodInfo().equals(mth))
				return m;
		}
		return null;
	}

	public MethodNode searchMethodByName(String shortId) {
S
Skylot 已提交
315 316 317 318 319 320 321 322
		for (MethodNode m : methods) {
			if (m.getMethodInfo().getShortId().equals(shortId))
				return m;
		}
		return null;
	}

	public MethodNode searchMethodById(int id) {
S
Skylot 已提交
323
		return searchMethodByName(MethodInfo.fromDex(dex, id).getShortId());
S
Skylot 已提交
324 325 326 327 328 329 330 331 332 333 334 335
	}

	public List<ClassNode> getInnerClasses() {
		return innerClasses;
	}

	public void addInnerClass(ClassNode cls) {
		if (innerClasses.isEmpty())
			innerClasses = new ArrayList<ClassNode>(3);
		innerClasses.add(cls);
	}

336 337 338 339
	public boolean isEnum() {
		return getAccessFlags().isEnum() && getSuperClass().getFullName().equals(Consts.CLASS_ENUM);
	}

S
Skylot 已提交
340
	public boolean isAnonymous() {
S
Skylot 已提交
341 342 343
		return clsInfo.isInner()
				&& getShortName().startsWith(Consts.ANONYMOUS_CLASS_PREFIX)
				&& getDefaultConstructor() != null;
S
Skylot 已提交
344 345 346 347 348 349
	}

	public MethodNode getDefaultConstructor() {
		for (MethodNode mth : methods) {
			if (mth.getAccessFlags().isConstructor()
					&& mth.getMethodInfo().isConstructor()
S
Skylot 已提交
350 351
					&& (mth.getMethodInfo().getArgsCount() == 0
						|| (mth.getArguments(false) != null && mth.getArguments(false).isEmpty()))) {
S
Skylot 已提交
352
				return mth;
S
Skylot 已提交
353 354
			}
		}
S
Skylot 已提交
355
		return null;
S
Skylot 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
	}

	public AccessInfo getAccessFlags() {
		return accessFlags;
	}

	public DexNode dex() {
		return dex;
	}

	public ClassInfo getClassInfo() {
		return clsInfo;
	}

	public String getShortName() {
		return clsInfo.getShortName();
	}

	public String getFullName() {
		return clsInfo.getFullName();
	}

	public String getPackage() {
		return clsInfo.getPackage();
	}

382 383 384 385
	public String getRawName() {
		return clsInfo.getRawName();
	}

S
Skylot 已提交
386 387 388 389 390 391 392 393
	public void setCode(CodeWriter code) {
		this.code = code;
	}

	public CodeWriter getCode() {
		return code;
	}

S
Skylot 已提交
394 395 396 397 398
	@Override
	public String toString() {
		return getFullName();
	}
}