Java Code Examples for com.strobel.assembler.metadata.TypeReference#resolve()

The following examples show how to use com.strobel.assembler.metadata.TypeReference#resolve() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CovariantArrays.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private boolean allImplementationsDerivedFromSubclass(Hierarchy h, TypeReference superClass,
        TypeReference subClass) {
    TypeDefinition td = superClass.resolve();
    if(td == null || (!td.isInterface() && !Flags.testAny(td.getFlags(), Flags.ABSTRACT)) )
        return false;
    for(TypeHierarchy th : h.get(td).getSubClasses()) {
        if(subClass.getInternalName().equals(th.getInternalName()))
            continue;
        if(th.hasFlag(Flags.INTERFACE) || th.hasFlag(Flags.ABSTRACT))
            continue;
        TypeReference subType = td.getResolver().lookupType(th.getInternalName());
        if(subType == null || Types.isInstance(subType, subClass))
            continue;
        return false;
    }
    return true;
}
 
Example 2
Source File: LockProblems.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if (expr.getCode() != AstCode.InvokeVirtual)
        return;
    MethodReference mr = (MethodReference) expr.getOperand();
    String name = mr.getName();
    if (!Types.isObject(mr.getDeclaringType()) || (!name.equals("wait") && !name.startsWith("notify")))
        return;
    TypeReference type = ValuesFlow.reduceType(expr.getArguments().get(0));
    if (type == null || !type.getInternalName().startsWith("java/util/concurrent/"))
        return;
    TypeDefinition target = type.resolve();
    if (target == null || !target.isPublic())
        return;
    MethodDefinition replacement = findReplacement(name, target);
    if(replacement != null) {
        mc.report("IncorrectConcurrentMethod", 0, expr, TARGET.create(target), Roles.REPLACEMENT_METHOD.create(replacement));
    }
}
 
Example 3
Source File: InitializerRefersSubclass.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS, methodName="<clinit>")
public void visit(Expression expr, NodeChain nc, MethodContext mc, TypeDefinition td) {
    if(expr.getOperand() instanceof MemberReference) {
        MemberReference mr = (MemberReference) expr.getOperand();
        TypeReference tr = mr.getDeclaringType();
        TypeDefinition subType = tr == null ? null : tr.resolve();
        if (subType != null && (subType.isAnonymous() || subType.isLocalClass())) {
            subType = subType.getBaseType().resolve();
        }
        if (subType != null && !td.isEquivalentTo(subType) && Types.isInstance(subType, td) && nc
                .getLambdaMethod() == null) {
            mc.report("InitializerRefersSubclass", td.isNonPublic() || subType.isNonPublic() ? 5 : 0, expr,
                Roles.SUBCLASS.create(subType));
        }
    }
}
 
Example 4
Source File: SingleType.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
static EType of(TypeReference tr, What what) {
    if (tr == null || tr.isPrimitive() || (what == What.SUBTYPE && Types.isObject(tr)))
        return UNKNOWN;
    TypeDefinition td = tr.resolve();
    if (td == null)
        return UNKNOWN;
    if (td.isFinal() || td.isPrimitive()) {
        if (what == What.SUBTYPE)
            what = What.EXACT;
        if (what == What.NOT)
            what = What.NOT_SUBTYPE;
    }
    TypeReference newTr = td;
    while (tr.isArray()) {
        tr = tr.getElementType();
        newTr = newTr.makeArrayType();
    }
    boolean complete = Types.hasCompleteHierarchy(td);
    return new SingleType(newTr, what, complete);
}
 
Example 5
Source File: Types.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
public static boolean isInstance(TypeReference type, String wantedType) {
    if (type == null || type.isPrimitive())
        return false;
    if (wantedType.equals("java/lang/Object"))
        return true;
    if (type.getInternalName().equals(wantedType))
        return true;
    if (type.isArray()) {
        if(!wantedType.startsWith("["))
            return false;
        return isInstance(type.getElementType(), wantedType.substring(1));
    }
    TypeDefinition td = type.resolve();
    if (td == null)
        return false;
    for (TypeReference iface : td.getExplicitInterfaces()) {
        if (isInstance(iface, wantedType))
            return true;
    }
    TypeReference bt = td.getBaseType();
    if (bt == null)
        return false;
    return isInstance(bt, wantedType);
}
 
Example 6
Source File: DecompilerLinkProvider.java    From Luyten with Apache License 2.0 6 votes vote down vote up
private TypeReference getMostOuterTypeRefBySlowLookuping(TypeReference typeRef) {
	String name = typeRef.getName();
	if (name == null)
		return typeRef;
	String packageName = typeRef.getPackageName();
	if (packageName == null)
		return typeRef;
	String[] nameParts = name.split("\\$");
	String newName = "";
	String sep = "";
	for (int i = 0; i < nameParts.length - 1; i++) {
		newName = newName + sep + nameParts[i];
		sep = "$";
		String newInternalName = packageName.replaceAll("\\.", "/") + "/" + newName;
		TypeReference newTypeRef = metadataSystem.lookupType(newInternalName);
		if (newTypeRef != null) {
			TypeDefinition newTypeDef = newTypeRef.resolve();
			if (newTypeDef != null) {
				return newTypeRef;
			}
		}
	}
	return typeRef;
}
 
Example 7
Source File: UncalledPrivateMethod.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitType(TypeDefinition td) {
    TypeReference tr = td.getDeclaringType();
    if(tr == null) return;
    TypeDefinition outer = tr.resolve();
    if(outer == null || !outer.isAnonymous()) return;
    for(MethodDefinition md : td.getDeclaredMethods()) {
        extractCalls(md, mr -> {
            mis.add(new MemberInfo(mr));
            return true;
        });
    }
}
 
Example 8
Source File: SingleType.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
public YesNoMaybe is(TypeReference other, boolean exact) {
    switch (what) {
    case EXACT:
        if (exact)
            return YesNoMaybe.of(tr.getInternalName().equals(other.getInternalName()));
        if (Types.isInstance(tr, other))
            return YesNoMaybe.YES;
        if (!complete)
            return YesNoMaybe.MAYBE;
        return YesNoMaybe.NO;
    case NOT:
        if (exact)
            return YesNoMaybe.of(!tr.getInternalName().equals(other.getInternalName()));
        return YesNoMaybe.MAYBE;
    case NOT_SUBTYPE:
        return Types.isInstance(other, tr) ? YesNoMaybe.NO : YesNoMaybe.MAYBE;
    case SUBTYPE: {
        if (exact)
            return Types.isInstance(other, tr) || !Types.hasCompleteHierarchy(other.resolve()) ? YesNoMaybe.MAYBE
                    : YesNoMaybe.NO;
        if (Types.isInstance(tr, other))
            return YesNoMaybe.YES;
        if (!complete || tr.resolve().isInterface())
            return YesNoMaybe.MAYBE;
        TypeDefinition superTd = other.resolve();
        if (superTd == null || superTd.isInterface() || Types.isInstance(other, tr) || !Types.hasCompleteHierarchy(
            superTd))
            return YesNoMaybe.MAYBE;
        return YesNoMaybe.NO;
    }
    default:
        throw new InternalError();
    }
}
 
Example 9
Source File: Types.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
public static synchronized TypeDefinition lookupJdkType(String internalName) {
    TypeReference tr = ms.lookupType(internalName);
    if (tr == null) {
        throw new InternalError("Unable to lookup type " + internalName);
    }
    TypeDefinition td = tr.resolve();
    if (td == null) {
        throw new InternalError("Unable to resolve type " + internalName);
    }
    return td;
}
 
Example 10
Source File: Types.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
public static List<TypeReference> getBaseTypes(TypeReference input) {
    List<TypeReference> result = new ArrayList<>();
    while (true) {
        result.add(input);
        TypeDefinition td = input.resolve();
        if (td == null)
            break;
        input = td.getBaseType();
        if (input == null)
            break;
    }
    Collections.reverse(result);
    return result;
}
 
Example 11
Source File: ClassFile.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static CompilationUnit decompileClassFile(TypeReference typeRef) {
  TypeDefinition typeDef = typeRef.resolve();
  DeobfuscationUtilities.processType(typeDef);
  DecompilationOptions options = new DecompilationOptions();
  DecompilerSettings settings = DecompilerSettings.javaDefaults();
  settings.setShowSyntheticMembers(true);
  options.setSettings(settings);
  options.setFullDecompilation(true);
  return Languages.java().decompileTypeToAst(typeDef, options);
}
 
Example 12
Source File: FileSaver.java    From Luyten with Apache License 2.0 5 votes vote down vote up
private void doSaveClassDecompiled(File inFile, File outFile) throws Exception {
	DecompilerSettings settings = cloneSettings();
	LuytenTypeLoader typeLoader = new LuytenTypeLoader();
	MetadataSystem metadataSystem = new MetadataSystem(typeLoader);
	TypeReference type = metadataSystem.lookupType(inFile.getCanonicalPath());

	DecompilationOptions decompilationOptions = new DecompilationOptions();
	decompilationOptions.setSettings(settings);
	decompilationOptions.setFullDecompilation(true);

	boolean isUnicodeEnabled = decompilationOptions.getSettings().isUnicodeOutputEnabled();
	TypeDefinition resolvedType = null;
	if (type == null || ((resolvedType = type.resolve()) == null)) {
		throw new Exception("Unable to resolve type.");
	}
	StringWriter stringwriter = new StringWriter();
	PlainTextOutput plainTextOutput = new PlainTextOutput(stringwriter);
	plainTextOutput.setUnicodeOutputEnabled(isUnicodeEnabled);
	settings.getLanguage().decompileType(resolvedType, plainTextOutput, decompilationOptions);
	String decompiledSource = stringwriter.toString();

	System.out.println("[SaveAll]: " + inFile.getName() + " -> " + outFile.getName());
	try (FileOutputStream fos = new FileOutputStream(outFile);
			OutputStreamWriter writer = isUnicodeEnabled ? new OutputStreamWriter(fos, "UTF-8")
					: new OutputStreamWriter(fos);
			BufferedWriter bw = new BufferedWriter(writer);) {
		bw.write(decompiledSource);
		bw.flush();
	}
}
 
Example 13
Source File: ProcyonDecompiler.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
public String decompile(byte[] b, MethodNode mn) {
  try {
  //TODO decompile method only
    DecompilerSettings settings = new DecompilerSettings();
    try {
      for (Field f : settings.getClass().getDeclaredFields()) {
        if (f.getType() == boolean.class) {
          f.setAccessible(true);
          f.setBoolean(settings, JByteMod.ops.get("procyon" + f.getName()).getBoolean());
        }
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }
    settings.setShowSyntheticMembers(true);
    MetadataSystem metadataSystem = new MetadataSystem(new ITypeLoader() {
      private InputTypeLoader backLoader = new InputTypeLoader();

      @Override
      public boolean tryLoadType(String s, Buffer buffer) {
        if (s.equals(cn.name)) {
          buffer.putByteArray(b, 0, b.length);
          buffer.position(0);
          return true;
        } else {
          return backLoader.tryLoadType(s, buffer);
        }
      }
    });
    TypeReference type = metadataSystem.lookupType(cn.name);
    DecompilationOptions decompilationOptions = new DecompilationOptions();
    decompilationOptions.setSettings(DecompilerSettings.javaDefaults());
    decompilationOptions.setFullDecompilation(true);
    TypeDefinition resolvedType = null;
    if (type == null || ((resolvedType = type.resolve()) == null)) {
      new ErrorDisplay("Unable to resolve type.");
      return "error";
    }
    StringWriter stringwriter = new StringWriter();
    settings.getLanguage().decompileType(resolvedType, new PlainTextOutput(stringwriter), decompilationOptions);
    String decompiledSource = stringwriter.toString();
    return decompiledSource;
  } catch (Exception e) {
    e.printStackTrace();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    return sw.toString();
  }
}
 
Example 14
Source File: Model.java    From Luyten with Apache License 2.0 4 votes vote down vote up
void extractClassToTextPane(TypeReference type, String tabTitle, String path, String navigatonLink)
		throws Exception {
	if (tabTitle == null || tabTitle.trim().length() < 1 || path == null) {
		throw new FileEntryNotFoundException();
	}
	OpenFile sameTitledOpen = null;
	for (OpenFile nextOpen : hmap) {
		if (tabTitle.equals(nextOpen.name) && path.equals(nextOpen.path) && type.equals(nextOpen.getType())) {
			sameTitledOpen = nextOpen;
			break;
		}
	}
	if (sameTitledOpen != null && sameTitledOpen.isContentValid()) {
		sameTitledOpen.setInitialNavigationLink(navigatonLink);
		addOrSwitchToTab(sameTitledOpen);
		return;
	}

	// resolve TypeDefinition
	TypeDefinition resolvedType = null;
	if (type == null || ((resolvedType = type.resolve()) == null)) {
		throw new Exception("Unable to resolve type.");
	}

	// open tab, store type information, start decompilation
	if (sameTitledOpen != null) {
		sameTitledOpen.path = path;
		sameTitledOpen.invalidateContent();
		sameTitledOpen.setDecompilerReferences(metadataSystem, settings, decompilationOptions);
		sameTitledOpen.setType(resolvedType);
		sameTitledOpen.setInitialNavigationLink(navigatonLink);
		sameTitledOpen.resetScrollPosition();
		sameTitledOpen.decompile();
		addOrSwitchToTab(sameTitledOpen);
	} else {
		OpenFile open = new OpenFile(tabTitle, path, getTheme(), mainWindow);
		open.setDecompilerReferences(metadataSystem, settings, decompilationOptions);
		open.setType(resolvedType);
		open.setInitialNavigationLink(navigatonLink);
		open.decompile();
		hmap.add(open);
		addOrSwitchToTab(open);
	}
}
 
Example 15
Source File: DecompilerLinkProvider.java    From Luyten with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isLinkNavigable(String uniqueStr) {
	if (isSelectionMapsPopulated && definitionToSelectionMap.containsKey(uniqueStr))
		return true;
	if (uniqueStr == null)
		return false;
	String[] linkParts = uniqueStr.split("\\|");
	if (linkParts.length < 3)
		return false;
	String typeStr = linkParts[2];
	if (typeStr.trim().length() <= 0)
		return false;
	TypeReference typeRef = metadataSystem.lookupType(typeStr.replaceAll("\\.", "/"));
	if (typeRef == null)
		return false;
	TypeDefinition typeDef = typeRef.resolve();
	if (typeDef == null)
		return false;
	if (typeDef.isSynthetic())
		return false;

	if (isSelectionMapsPopulated) {
		// current type's navigable definitions checked already, now it's erroneous
		if (currentTypeQualifiedName == null || currentTypeQualifiedName.trim().length() <= 0)
			return false;
		if (typeStr.equals(currentTypeQualifiedName) || typeStr.startsWith(currentTypeQualifiedName + ".")
				|| typeStr.startsWith(currentTypeQualifiedName + "$"))
			return false;
	}

	// check linked field/method exists
	if (uniqueStr.startsWith("method")) {
		if (findMethodInType(typeDef, uniqueStr) == null) {
			return false;
		}
	} else if (uniqueStr.startsWith("field")) {
		if (findFieldInType(typeDef, uniqueStr) == null) {
			return false;
		}
	}
	return true;
}