ClassGen.java 12.4 KB
Newer Older
S
Skylot 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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.IAttribute;
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 已提交
16
import jadx.core.dex.nodes.DexNode;
S
Skylot 已提交
17 18 19 20 21 22
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 已提交
23 24 25 26 27 28

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

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

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

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

S
Skylot 已提交
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 66
	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())) {
67
			clsCode.add("package ").add(cls.getPackage()).add(';');
68
			clsCode.newLine();
S
Skylot 已提交
69 70
		}

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

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

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

		clsCode.add(clsBody);
		return clsCode;
	}

	public void addClassCode(CodeWriter code) throws CodegenException {
		if (cls.getAttributes().contains(AttributeFlag.DONT_GENERATE))
			return;

S
Skylot 已提交
96 97 98
		if (cls.getAttributes().contains(AttributeFlag.INCONSISTENT_CODE))
			code.startLine("// jadx: inconsistent code");

S
Skylot 已提交
99 100
		makeClassDeclaration(code);
		makeClassBody(code);
101
		code.newLine();
S
Skylot 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
	}

	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);
		clsCode.startLine(af.makeString());
		if (af.isInterface()) {
			if (af.isAnnotation())
				clsCode.add('@');
			clsCode.add("interface ");
		} else if (af.isEnum()) {
			clsCode.add("enum ");
		} else {
			clsCode.add("class ");
		}
		clsCode.add(cls.getShortName());

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

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

		if (cls.getInterfaces().size() > 0 && !af.isAnnotation()) {
			if (cls.getAccessFlags().isInterface())
137
				clsCode.add("extends ");
S
Skylot 已提交
138
			else
139
				clsCode.add("implements ");
S
Skylot 已提交
140

S
Skylot 已提交
141
			for (Iterator<ClassInfo> it = cls.getInterfaces().iterator(); it.hasNext(); ) {
S
Skylot 已提交
142 143 144 145 146
				ClassInfo interf = it.next();
				clsCode.add(useClass(interf));
				if (it.hasNext())
					clsCode.add(", ");
			}
147 148 149
			if (!cls.getInterfaces().isEmpty())
				clsCode.add(' ');
		}
150 151

		clsCode.attachAnnotation(cls);
152 153
	}

S
Skylot 已提交
154
	public boolean makeGenericMap(CodeWriter code, Map<ArgType, List<ArgType>> gmap) {
155
		if (gmap == null || gmap.isEmpty())
S
Skylot 已提交
156
			return false;
157 158 159 160 161 162 163 164 165 166 167 168

		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 已提交
169
				for (Iterator<ArgType> it = list.iterator(); it.hasNext(); ) {
170 171 172 173 174 175 176 177
					ArgType g = it.next();
					code.add(useClass(g));
					if (it.hasNext()) {
						code.add(" & ");
					}
				}
			}
			i++;
S
Skylot 已提交
178
		}
179
		code.add('>');
S
Skylot 已提交
180
		return true;
S
Skylot 已提交
181 182 183
	}

	public void makeClassBody(CodeWriter clsCode) throws CodegenException {
184
		clsCode.add('{');
185 186
		insertSourceFileInfo(clsCode, cls);

S
Skylot 已提交
187
		CodeWriter mthsCode = makeMethods(clsCode, cls.getMethods());
S
Skylot 已提交
188 189 190
		CodeWriter fieldsCode = makeFields(clsCode, cls, cls.getFields());
		clsCode.add(fieldsCode);
		if (fieldsCode.notEmpty() && mthsCode.notEmpty())
191
			clsCode.newLine();
S
Skylot 已提交
192 193 194 195

		// insert inner classes code
		if (cls.getInnerClasses().size() != 0) {
			clsCode.add(makeInnerClasses(cls, clsCode.getIndent()));
S
Skylot 已提交
196
			if (mthsCode.notEmpty())
197
				clsCode.newLine();
S
Skylot 已提交
198 199
		}
		clsCode.add(mthsCode);
200
		clsCode.startLine('}');
S
Skylot 已提交
201 202
	}

S
Skylot 已提交
203
	private CodeWriter makeInnerClasses(ClassNode cls, int indent) throws CodegenException {
S
Skylot 已提交
204 205 206 207 208 209 210 211 212 213 214 215
		CodeWriter innerClsCode = new CodeWriter(indent + 1);
		for (ClassNode inCls : cls.getInnerClasses()) {
			if (inCls.isAnonymous())
				continue;

			ClassGen inClGen = new ClassGen(inCls, parentGen == null ? this : parentGen, fallback);
			inClGen.addClassCode(innerClsCode);
			imports.addAll(inClGen.getImports());
		}
		return innerClsCode;
	}

216
	private CodeWriter makeMethods(CodeWriter clsCode, List<MethodNode> mthList) {
S
Skylot 已提交
217
		CodeWriter code = new CodeWriter(clsCode.getIndent() + 1);
S
Skylot 已提交
218
		for (Iterator<MethodNode> it = mthList.iterator(); it.hasNext(); ) {
S
Skylot 已提交
219
			MethodNode mth = it.next();
S
Skylot 已提交
220 221 222
			if (mth.getAttributes().contains(AttributeFlag.DONT_GENERATE))
				continue;

S
Skylot 已提交
223 224 225 226 227 228 229 230 231 232 233
			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) {
							String v = annotationGen.encValueToString(def);
							code.add(" default ").add(v);
						}
					}
234
					code.add(';');
S
Skylot 已提交
235 236 237 238 239
				} else {
					if (mth.isNoCode())
						continue;

					MethodGen mthGen = new MethodGen(this, mth);
240 241 242 243 244
					if (mth.getAttributes().contains(AttributeFlag.INCONSISTENT_CODE)) {
						code.startLine("/* JADX WARNING: inconsistent code */");
						LOG.error(ErrorsCounter.formatErrorMsg(mth, " Inconsistent code"));
						mthGen.makeMethodDump(code);
					}
S
Skylot 已提交
245
					mthGen.addDefinition(code);
S
Skylot 已提交
246
					code.add('{');
247
					insertSourceFileInfo(code, mth);
S
Skylot 已提交
248
					code.add(mthGen.makeInstructions(code.getIndent()));
249
					code.startLine('}');
S
Skylot 已提交
250 251 252 253 254 255 256
				}
			} catch (Throwable e) {
				String msg = ErrorsCounter.methodError(mth, "Method generation error", e);
				code.startLine("/* " + msg + CodeWriter.NL + Utils.getStackTrace(e) + "*/");
			}

			if (it.hasNext())
257
				code.newLine();
S
Skylot 已提交
258 259 260 261 262 263 264 265 266
		}
		return code;
	}

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

		EnumClassAttr enumFields = (EnumClassAttr) cls.getAttributes().get(AttributeType.ENUM_CLASS);
		if (enumFields != null) {
S
Skylot 已提交
267 268
			InsnGen igen = null;
			for (Iterator<EnumField> it = enumFields.getFields().iterator(); it.hasNext(); ) {
S
Skylot 已提交
269 270 271 272
				EnumField f = it.next();
				code.startLine(f.getName());
				if (f.getArgs().size() != 0) {
					code.add('(');
S
Skylot 已提交
273
					for (Iterator<InsnArg> aIt = f.getArgs().iterator(); aIt.hasNext(); ) {
S
Skylot 已提交
274
						InsnArg arg = aIt.next();
S
Skylot 已提交
275 276 277 278 279
						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);
						}
S
Skylot 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
						code.add(igen.arg(arg));
						if (aIt.hasNext())
							code.add(", ");
					}
					code.add(')');
				}
				if (f.getCls() != null) {
					new ClassGen(f.getCls(), this, fallback).makeClassBody(code);
				}
				if (it.hasNext())
					code.add(',');
			}
			if (enumFields.getFields().isEmpty())
				code.startLine();

			code.add(';');
296
			code.newLine();
S
Skylot 已提交
297 298 299
		}

		for (FieldNode f : fields) {
300 301 302
			if(f.getAttributes().contains(AttributeFlag.DONT_GENERATE)) {
				continue;
			}
S
Skylot 已提交
303 304 305
			annotationGen.addForField(code, f);
			code.startLine(f.getAccessFlags().makeString());
			code.add(TypeGen.translate(this, f.getType()));
306
			code.add(' ');
S
Skylot 已提交
307 308 309 310 311 312 313 314 315 316
			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 {
					code.add(annotationGen.encValueToString(fv.getValue()));
				}
			}
317
			code.add(';');
318
			code.attachAnnotation(f);
S
Skylot 已提交
319 320 321 322 323
		}
		return code;
	}

	public String useClass(ArgType clsType) {
324 325 326
		if (clsType.isGenericType()) {
			return clsType.getObject();
		}
S
Skylot 已提交
327
		return useClass(ClassInfo.fromType(clsType));
328
	}
329

330
	public String useClass(ClassInfo classInfo) {
S
Skylot 已提交
331
		String baseClass = useClassInternal(cls.getClassInfo(), classInfo);
332
		ArgType[] generics = classInfo.getType().getGenericTypes();
333 334 335
		if (generics != null) {
			StringBuilder sb = new StringBuilder();
			sb.append(baseClass);
336
			sb.append('<');
337 338 339 340 341 342 343
			int len = generics.length;
			for (int i = 0; i < len; i++) {
				if (i != 0) {
					sb.append(", ");
				}
				ArgType gt = generics[i];
				if (gt.isTypeKnown())
344
					sb.append(TypeGen.translate(this, gt));
345 346 347
				else
					sb.append('?');
			}
348
			sb.append('>');
349 350 351 352
			return sb.toString();
		} else {
			return baseClass;
		}
S
Skylot 已提交
353 354
	}

S
Skylot 已提交
355
	private String useClassInternal(ClassInfo useCls, ClassInfo classInfo) {
S
Skylot 已提交
356
		String clsStr = classInfo.getFullName();
S
Skylot 已提交
357
		if (fallback) {
S
Skylot 已提交
358
			return clsStr;
S
Skylot 已提交
359
		}
S
Skylot 已提交
360 361 362 363 364
		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 已提交
365
			if (isClassInnerFor(classInfo, useCls)) {
S
Skylot 已提交
366
				return shortName;
S
Skylot 已提交
367
			}
368
			// don't add import if this class from same package
S
Skylot 已提交
369
			if (classInfo.getPackage().equals(useCls.getPackage()) && !classInfo.isInner()) {
370
				return shortName;
S
Skylot 已提交
371 372 373 374 375 376 377
			}
			if (classInfo.getPackage().equals(useCls.getPackage())) {
				clsStr = classInfo.getNameWithoutPackage();
			}
			if (searchCollision(cls.dex(), useCls, shortName)) {
				return clsStr;
			}
S
Skylot 已提交
378 379
			for (ClassInfo cls : imports) {
				if (!cls.equals(classInfo)) {
S
Skylot 已提交
380
					if (cls.getShortName().equals(shortName)) {
S
Skylot 已提交
381
						return clsStr;
S
Skylot 已提交
382
					}
S
Skylot 已提交
383 384
				}
			}
385
			addImport(classInfo);
S
Skylot 已提交
386 387 388 389
			return shortName;
		}
	}

390 391 392 393 394 395 396 397
	private void addImport(ClassInfo classInfo) {
		if (parentGen != null) {
			parentGen.addImport(classInfo);
		} else {
			imports.add(classInfo);
		}
	}

S
Skylot 已提交
398
	private static boolean isClassInnerFor(ClassInfo inner, ClassInfo parent) {
S
Skylot 已提交
399 400
		if (inner.isInner()) {
			ClassInfo p = inner.getParentClass();
S
Skylot 已提交
401
			return p.equals(parent) || isClassInnerFor(p, parent);
S
Skylot 已提交
402 403 404 405
		}
		return false;
	}

S
Skylot 已提交
406 407 408 409 410 411 412 413
	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);
414 415 416 417 418
		if (classNode != null) {
			for (ClassNode inner : classNode.getInnerClasses()) {
				if (inner.getShortName().equals(shortName)) {
					return true;
				}
S
Skylot 已提交
419 420 421 422 423
			}
		}
		return searchCollision(dex, useCls.getParentClass(), shortName);
	}

424 425
	private void insertSourceFileInfo(CodeWriter code, AttrNode node) {
		IAttribute sourceFileAttr = node.getAttributes().get(AttributeType.SOURCE_FILE);
426
		if (sourceFileAttr != null) {
427
			code.startLine(1, "// compiled from: ");
428
			code.add(((SourceFileAttr) sourceFileAttr).getFileName());
429 430 431
		}
	}

S
Skylot 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
	public Set<ClassInfo> getImports() {
		return imports;
	}

	public ClassGen getParentGen() {
		return parentGen;
	}

	public AnnotationGen getAnnotationGen() {
		return annotationGen;
	}

	public boolean isFallbackMode() {
		return fallback;
	}
}