ClassGen.java 13.3 KB
Newer Older
S
Skylot 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package jadx.core.codegen;

import jadx.core.Consts;
import jadx.core.dex.attributes.AttrNode;
import jadx.core.dex.attributes.AttributeFlag;
import jadx.core.dex.attributes.AttributeType;
import jadx.core.dex.attributes.EnumClassAttr;
import jadx.core.dex.attributes.EnumClassAttr.EnumField;
import jadx.core.dex.attributes.SourceFileAttr;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.nodes.ClassNode;
S
Skylot 已提交
15
import jadx.core.dex.nodes.DexNode;
S
Skylot 已提交
16 17 18 19 20 21
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.parser.FieldValueAttr;
import jadx.core.utils.ErrorsCounter;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.CodegenException;
S
Skylot 已提交
22 23 24 25 26 27

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
28 29
import java.util.Map;
import java.util.Map.Entry;
S
Skylot 已提交
30 31
import java.util.Set;

32 33 34
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

S
Skylot 已提交
35 36 37
import com.android.dx.rop.code.AccessFlags;

public class ClassGen {
38 39
	private static final Logger LOG = LoggerFactory.getLogger(ClassGen.class);

S
Skylot 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	private final ClassNode cls;
	private final ClassGen parentGen;
	private final AnnotationGen annotationGen;
	private final boolean fallback;

	private final Set<ClassInfo> imports = new HashSet<ClassInfo>();

	public ClassGen(ClassNode cls, ClassGen parentClsGen, boolean fallback) {
		this.cls = cls;
		this.parentGen = parentClsGen;
		this.fallback = fallback;

		this.annotationGen = new AnnotationGen(cls, this);
	}

	public ClassNode getClassNode() {
		return cls;
	}

	public CodeWriter makeClass() throws CodegenException {
		CodeWriter clsBody = new CodeWriter();
		addClassCode(clsBody);

		CodeWriter clsCode = new CodeWriter();

		if (!"".equals(cls.getPackage())) {
66
			clsCode.add("package ").add(cls.getPackage()).add(';');
67
			clsCode.newLine();
S
Skylot 已提交
68 69
		}

S
Skylot 已提交
70 71 72 73
		int importsCount = imports.size();
		if (importsCount != 0) {
			List<String> sortImports = new ArrayList<String>(importsCount);
			for (ClassInfo ic : imports) {
S
Skylot 已提交
74
				sortImports.add(ic.getFullName());
S
Skylot 已提交
75
			}
S
Skylot 已提交
76 77 78
			Collections.sort(sortImports);

			for (String imp : sortImports) {
79
				clsCode.startLine("import ").add(imp).add(';');
S
Skylot 已提交
80
			}
81
			clsCode.newLine();
S
Skylot 已提交
82 83 84 85 86 87 88 89 90 91

			sortImports.clear();
			imports.clear();
		}

		clsCode.add(clsBody);
		return clsCode;
	}

	public void addClassCode(CodeWriter code) throws CodegenException {
S
Skylot 已提交
92
		if (cls.getAttributes().contains(AttributeFlag.DONT_GENERATE)) {
S
Skylot 已提交
93
			return;
S
Skylot 已提交
94 95
		}
		if (cls.getAttributes().contains(AttributeFlag.INCONSISTENT_CODE)) {
S
Skylot 已提交
96
			code.startLine("// jadx: inconsistent code");
S
Skylot 已提交
97
		}
S
Skylot 已提交
98 99
		makeClassDeclaration(code);
		makeClassBody(code);
100
		code.newLine();
S
Skylot 已提交
101 102 103 104 105 106 107 108 109 110 111
	}

	public void makeClassDeclaration(CodeWriter clsCode) {
		AccessInfo af = cls.getAccessFlags();
		if (af.isInterface()) {
			af = af.remove(AccessFlags.ACC_ABSTRACT);
		} else if (af.isEnum()) {
			af = af.remove(AccessFlags.ACC_FINAL).remove(AccessFlags.ACC_ABSTRACT);
		}

		annotationGen.addForClass(clsCode);
S
Skylot 已提交
112
		insertSourceFileInfo(clsCode, cls);
S
Skylot 已提交
113 114
		clsCode.startLine(af.makeString());
		if (af.isInterface()) {
S
Skylot 已提交
115
			if (af.isAnnotation()) {
S
Skylot 已提交
116
				clsCode.add('@');
S
Skylot 已提交
117
			}
S
Skylot 已提交
118 119 120 121 122 123 124 125
			clsCode.add("interface ");
		} else if (af.isEnum()) {
			clsCode.add("enum ");
		} else {
			clsCode.add("class ");
		}
		clsCode.add(cls.getShortName());

126 127 128 129
		makeGenericMap(clsCode, cls.getGenericMap());
		clsCode.add(' ');

		ClassInfo sup = cls.getSuperClass();
S
Skylot 已提交
130 131 132
		if (sup != null
				&& !sup.getFullName().equals(Consts.CLASS_OBJECT)
				&& !sup.getFullName().equals(Consts.CLASS_ENUM)) {
133
			clsCode.add("extends ").add(useClass(sup)).add(' ');
S
Skylot 已提交
134 135 136
		}

		if (cls.getInterfaces().size() > 0 && !af.isAnnotation()) {
S
Skylot 已提交
137
			if (cls.getAccessFlags().isInterface()) {
138
				clsCode.add("extends ");
S
Skylot 已提交
139
			} else {
140
				clsCode.add("implements ");
S
Skylot 已提交
141
			}
S
Skylot 已提交
142
			for (Iterator<ClassInfo> it = cls.getInterfaces().iterator(); it.hasNext(); ) {
S
Skylot 已提交
143 144
				ClassInfo interf = it.next();
				clsCode.add(useClass(interf));
S
Skylot 已提交
145
				if (it.hasNext()) {
S
Skylot 已提交
146
					clsCode.add(", ");
S
Skylot 已提交
147
				}
S
Skylot 已提交
148
			}
S
Skylot 已提交
149
			if (!cls.getInterfaces().isEmpty()) {
150
				clsCode.add(' ');
S
Skylot 已提交
151
			}
152
		}
153

154
		clsCode.attachDefinition(cls);
155 156
	}

S
Skylot 已提交
157
	public boolean makeGenericMap(CodeWriter code, Map<ArgType, List<ArgType>> gmap) {
S
Skylot 已提交
158
		if (gmap == null || gmap.isEmpty()) {
S
Skylot 已提交
159
			return false;
S
Skylot 已提交
160
		}
161 162 163 164 165 166 167 168 169 170 171
		code.add('<');
		int i = 0;
		for (Entry<ArgType, List<ArgType>> e : gmap.entrySet()) {
			ArgType type = e.getKey();
			List<ArgType> list = e.getValue();
			if (i != 0) {
				code.add(", ");
			}
			code.add(useClass(type));
			if (list != null && !list.isEmpty()) {
				code.add(" extends ");
S
Skylot 已提交
172
				for (Iterator<ArgType> it = list.iterator(); it.hasNext(); ) {
173 174 175 176 177 178 179 180
					ArgType g = it.next();
					code.add(useClass(g));
					if (it.hasNext()) {
						code.add(" & ");
					}
				}
			}
			i++;
S
Skylot 已提交
181
		}
182
		code.add('>');
S
Skylot 已提交
183
		return true;
S
Skylot 已提交
184 185 186
	}

	public void makeClassBody(CodeWriter clsCode) throws CodegenException {
187
		clsCode.add('{');
S
Skylot 已提交
188
		CodeWriter mthsCode = makeMethods(clsCode, cls.getMethods());
S
Skylot 已提交
189 190
		CodeWriter fieldsCode = makeFields(clsCode, cls, cls.getFields());
		clsCode.add(fieldsCode);
S
Skylot 已提交
191
		if (fieldsCode.notEmpty() && mthsCode.notEmpty()) {
192
			clsCode.newLine();
S
Skylot 已提交
193
		}
S
Skylot 已提交
194 195 196
		// insert inner classes code
		if (cls.getInnerClasses().size() != 0) {
			clsCode.add(makeInnerClasses(cls, clsCode.getIndent()));
S
Skylot 已提交
197
			if (mthsCode.notEmpty()) {
198
				clsCode.newLine();
S
Skylot 已提交
199
			}
S
Skylot 已提交
200 201
		}
		clsCode.add(mthsCode);
202
		clsCode.startLine('}');
S
Skylot 已提交
203 204
	}

S
Skylot 已提交
205
	private CodeWriter makeInnerClasses(ClassNode cls, int indent) throws CodegenException {
S
Skylot 已提交
206 207
		CodeWriter innerClsCode = new CodeWriter(indent + 1);
		for (ClassNode inCls : cls.getInnerClasses()) {
S
Skylot 已提交
208 209 210 211 212
			if (!inCls.isAnonymous()) {
				ClassGen inClGen = new ClassGen(inCls, parentGen == null ? this : parentGen, fallback);
				inClGen.addClassCode(innerClsCode);
				imports.addAll(inClGen.getImports());
			}
S
Skylot 已提交
213 214 215 216
		}
		return innerClsCode;
	}

217
	private CodeWriter makeMethods(CodeWriter clsCode, List<MethodNode> mthList) {
S
Skylot 已提交
218
		CodeWriter code = new CodeWriter(clsCode.getIndent() + 1);
S
Skylot 已提交
219
		for (Iterator<MethodNode> it = mthList.iterator(); it.hasNext(); ) {
S
Skylot 已提交
220
			MethodNode mth = it.next();
221
			if (mth.getAttributes().contains(AttributeFlag.DONT_GENERATE)) {
S
Skylot 已提交
222
				continue;
223
			}
S
Skylot 已提交
224 225 226 227 228 229 230
			try {
				if (mth.getAccessFlags().isAbstract() || mth.getAccessFlags().isNative()) {
					MethodGen mthGen = new MethodGen(this, mth);
					mthGen.addDefinition(code);
					if (cls.getAccessFlags().isAnnotation()) {
						Object def = annotationGen.getAnnotationDefaultValue(mth.getName());
						if (def != null) {
231 232
							code.add(" default ");
							annotationGen.encodeValue(code, def);
S
Skylot 已提交
233 234
						}
					}
235
					code.add(';');
S
Skylot 已提交
236 237
				} else {
					MethodGen mthGen = new MethodGen(this, mth);
238 239 240 241
					boolean badCode = mth.getAttributes().contains(AttributeFlag.INCONSISTENT_CODE);
					if (badCode) {
						code.startLine("/* JADX WARNING: inconsistent code. */");
						code.startLine("/* Code decompiled incorrectly, please refer to instructions dump. */");
242 243
						LOG.error(ErrorsCounter.formatErrorMsg(mth, " Inconsistent code"));
					}
S
Skylot 已提交
244 245 246
					if (mthGen.addDefinition(code)) {
						code.add(' ');
					}
S
Skylot 已提交
247
					code.add('{');
248
					code.incIndent();
249
					insertSourceFileInfo(code, mth);
250 251
					mthGen.addInstructions(code);
					code.decIndent();
252
					code.startLine('}');
S
Skylot 已提交
253 254 255
				}
			} catch (Throwable e) {
				String msg = ErrorsCounter.methodError(mth, "Method generation error", e);
S
Skylot 已提交
256
				code.startLine("/* " + msg + CodeWriter.NL + Utils.getStackTrace(e) + " */");
S
Skylot 已提交
257
			}
258
			if (it.hasNext()) {
259
				code.newLine();
260
			}
S
Skylot 已提交
261 262 263 264 265 266 267
		}
		return code;
	}

	private CodeWriter makeFields(CodeWriter clsCode, ClassNode cls, List<FieldNode> fields) throws CodegenException {
		CodeWriter code = new CodeWriter(clsCode.getIndent() + 1);

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
		addEnumFields(cls, code);

		for (FieldNode f : fields) {
			if (f.getAttributes().contains(AttributeFlag.DONT_GENERATE)) {
				continue;
			}
			annotationGen.addForField(code, f);
			code.startLine(f.getAccessFlags().makeString());
			code.add(TypeGen.translate(this, f.getType()));
			code.add(' ');
			code.add(f.getName());
			FieldValueAttr fv = (FieldValueAttr) f.getAttributes().get(AttributeType.FIELD_VALUE);
			if (fv != null) {
				code.add(" = ");
				if (fv.getValue() == null) {
					code.add(TypeGen.literalToString(0, f.getType()));
				} else {
285
					annotationGen.encodeValue(code, fv.getValue());
286 287 288
				}
			}
			code.add(';');
289
			code.attachDefinition(f);
290 291 292 293 294
		}
		return code;
	}

	private void addEnumFields(ClassNode cls, CodeWriter code) throws CodegenException {
S
Skylot 已提交
295 296
		EnumClassAttr enumFields = (EnumClassAttr) cls.getAttributes().get(AttributeType.ENUM_CLASS);
		if (enumFields != null) {
S
Skylot 已提交
297 298
			InsnGen igen = null;
			for (Iterator<EnumField> it = enumFields.getFields().iterator(); it.hasNext(); ) {
S
Skylot 已提交
299 300 301 302
				EnumField f = it.next();
				code.startLine(f.getName());
				if (f.getArgs().size() != 0) {
					code.add('(');
S
Skylot 已提交
303
					for (Iterator<InsnArg> aIt = f.getArgs().iterator(); aIt.hasNext(); ) {
S
Skylot 已提交
304
						InsnArg arg = aIt.next();
S
Skylot 已提交
305 306 307 308 309
						if (igen == null) {
							// don't init mth gen if this is simple enum
							MethodGen mthGen = new MethodGen(this, enumFields.getStaticMethod());
							igen = new InsnGen(mthGen, enumFields.getStaticMethod(), false);
						}
310
						igen.addArg(code, arg);
S
Skylot 已提交
311
						if (aIt.hasNext()) {
S
Skylot 已提交
312
							code.add(", ");
S
Skylot 已提交
313
						}
S
Skylot 已提交
314 315 316 317 318 319
					}
					code.add(')');
				}
				if (f.getCls() != null) {
					new ClassGen(f.getCls(), this, fallback).makeClassBody(code);
				}
S
Skylot 已提交
320
				if (it.hasNext()) {
S
Skylot 已提交
321
					code.add(',');
S
Skylot 已提交
322
				}
S
Skylot 已提交
323
			}
S
Skylot 已提交
324
			if (enumFields.getFields().isEmpty()) {
S
Skylot 已提交
325
				code.startLine();
S
Skylot 已提交
326
			}
S
Skylot 已提交
327
			code.add(';');
328
			code.newLine();
S
Skylot 已提交
329 330 331 332
		}
	}

	public String useClass(ArgType clsType) {
333 334 335
		if (clsType.isGenericType()) {
			return clsType.getObject();
		}
S
Skylot 已提交
336
		return useClass(ClassInfo.fromType(clsType));
337
	}
338

339
	public String useClass(ClassInfo classInfo) {
S
Skylot 已提交
340
		String baseClass = useClassInternal(cls.getClassInfo(), classInfo);
S
Skylot 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		ArgType type = classInfo.getType();
		ArgType[] generics = type.getGenericTypes();
		if (generics == null) {
			return baseClass;
		}

		StringBuilder sb = new StringBuilder();
		sb.append(baseClass);
		sb.append('<');
		int len = generics.length;
		for (int i = 0; i < len; i++) {
			if (i != 0) {
				sb.append(", ");
			}
			ArgType gt = generics[i];
			ArgType wt = gt.getWildcardType();
			if (wt != null) {
				sb.append('?');
				int bounds = gt.getWildcardBounds();
				if (bounds != 0) {
					sb.append(bounds == -1 ? " super " : " extends ");
					sb.append(TypeGen.translate(this, wt));
S
Skylot 已提交
363
				}
S
Skylot 已提交
364 365
			} else {
				sb.append(TypeGen.translate(this, gt));
366 367
			}
		}
S
Skylot 已提交
368 369
		sb.append('>');
		return sb.toString();
S
Skylot 已提交
370 371
	}

S
Skylot 已提交
372
	private String useClassInternal(ClassInfo useCls, ClassInfo classInfo) {
373
		String fullName = classInfo.getFullName();
S
Skylot 已提交
374
		if (fallback) {
375
			return fullName;
S
Skylot 已提交
376
		}
S
Skylot 已提交
377 378 379 380 381
		String shortName = classInfo.getShortName();
		if (classInfo.getPackage().equals("java.lang") && classInfo.getParentClass() == null) {
			return shortName;
		} else {
			// don't add import if this class inner for current class
S
Skylot 已提交
382
			if (isClassInnerFor(classInfo, useCls)) {
S
Skylot 已提交
383
				return shortName;
S
Skylot 已提交
384
			}
385
			// don't add import if this class from same package
S
Skylot 已提交
386
			if (classInfo.getPackage().equals(useCls.getPackage()) && !classInfo.isInner()) {
387
				return shortName;
S
Skylot 已提交
388
			}
S
Skylot 已提交
389 390 391 392
			// don't add import if class not public (must be accessed using inheritance)
			ClassNode classNode = cls.dex().resolveClass(classInfo);
			if (classNode != null && !classNode.getAccessFlags().isPublic()) {
				return shortName;
S
Skylot 已提交
393 394
			}
			if (searchCollision(cls.dex(), useCls, shortName)) {
395
				return fullName;
S
Skylot 已提交
396
			}
S
Skylot 已提交
397 398 399
			if (classInfo.getPackage().equals(useCls.getPackage())) {
				fullName = classInfo.getNameWithoutPackage();
			}
400
			for (ClassInfo importCls : getImports()) {
S
Skylot 已提交
401 402
				if (!importCls.equals(classInfo)
						&& importCls.getShortName().equals(shortName)) {
403 404 405 406 407 408
					if (classInfo.isInner()) {
						String parent = useClassInternal(useCls, classInfo.getParentClass());
						return parent + "." + shortName;
					} else {
						return fullName;
					}
S
Skylot 已提交
409 410
				}
			}
411
			addImport(classInfo);
S
Skylot 已提交
412 413 414 415
			return shortName;
		}
	}

416 417 418 419 420 421 422 423
	private void addImport(ClassInfo classInfo) {
		if (parentGen != null) {
			parentGen.addImport(classInfo);
		} else {
			imports.add(classInfo);
		}
	}

424 425 426 427 428 429 430 431
	private Set<ClassInfo> getImports() {
		if (parentGen != null) {
			return parentGen.getImports();
		} else {
			return imports;
		}
	}

S
Skylot 已提交
432
	private static boolean isClassInnerFor(ClassInfo inner, ClassInfo parent) {
S
Skylot 已提交
433 434
		if (inner.isInner()) {
			ClassInfo p = inner.getParentClass();
S
Skylot 已提交
435
			return p.equals(parent) || isClassInnerFor(p, parent);
S
Skylot 已提交
436 437 438 439
		}
		return false;
	}

S
Skylot 已提交
440 441 442 443 444 445 446 447
	private static boolean searchCollision(DexNode dex, ClassInfo useCls, String shortName) {
		if (useCls == null) {
			return false;
		}
		if (useCls.getShortName().equals(shortName)) {
			return true;
		}
		ClassNode classNode = dex.resolveClass(useCls);
448 449 450 451 452
		if (classNode != null) {
			for (ClassNode inner : classNode.getInnerClasses()) {
				if (inner.getShortName().equals(shortName)) {
					return true;
				}
S
Skylot 已提交
453 454 455 456 457
			}
		}
		return searchCollision(dex, useCls.getParentClass(), shortName);
	}

458
	private void insertSourceFileInfo(CodeWriter code, AttrNode node) {
459
		SourceFileAttr sourceFileAttr = (SourceFileAttr) node.getAttributes().get(AttributeType.SOURCE_FILE);
460
		if (sourceFileAttr != null) {
461
			code.startLine("// compiled from: ").add(sourceFileAttr.getFileName());
462 463 464
		}
	}

S
Skylot 已提交
465
	public ClassGen getParentGen() {
466
		return parentGen == null ? this : parentGen;
S
Skylot 已提交
467 468 469 470 471 472 473 474 475 476
	}

	public AnnotationGen getAnnotationGen() {
		return annotationGen;
	}

	public boolean isFallbackMode() {
		return fallback;
	}
}