ghidra.program.model.lang.CompilerSpec Java Examples

The following examples show how to use ghidra.program.model.lang.CompilerSpec. 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: ApplyFunctionSignatureCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private String getCallingConvention(Function function, CompilerSpec compilerSpec) {
		PrototypeModel preferredModel = null;
		if (signature.getGenericCallingConvention() != GenericCallingConvention.unknown) {
			preferredModel = compilerSpec.matchConvention(signature.getGenericCallingConvention());
		}

		PrototypeModel convention = function.getCallingConvention();
		if (convention == null || !preserveCallingConvention) {
			convention = preferredModel;
// NOTE: This has been disable since it can cause imported signature information to be 
// ignored and overwritten by subsequent analysis
//			if (convention == null && compilerSpec.getCallingConventions().length > 1) {
//				// use default source for signature if convention is really unknown so that we
//				// know dynamic storage assignment is unreliable
//				source = SourceType.DEFAULT;
//			}
		}

		// Calling convention is permitted to change
		String conventionName = function.getCallingConventionName();
		if (!preserveCallingConvention && convention != null) {
			conventionName = convention.getName();
		}
		return conventionName;
	}
 
Example #2
Source File: ApplyFunctionSignatureCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private int getIndexOfFirstParameter(String conventionName, ParameterDefinition[] args) {

		if (args.length == 0) {
			return 0;
		}

		if (!CompilerSpec.CALLING_CONVENTION_thiscall.equals(conventionName)) {
			return 0;
		}

		if (!Function.THIS_PARAM_NAME.equals(args[0].getName())) {
			return 0;
		}

		// Ignore this parameter since it should be established as an auto-parameter
		return 1; // 'this call' and the first param's name is 'this'
	}
 
Example #3
Source File: ApplyFunctionSignatureCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private List<Parameter> createParameters(CompilerSpec compilerSpec, String conventionName,
		ParameterDefinition[] args) throws InvalidInputException {

	int firstParamIndex = getIndexOfFirstParameter(conventionName, args);

	List<Parameter> params = new ArrayList<>();
	boolean settleCTypes = compilerSpec.doesCDataTypeConversions();
	DataTypeManager dtm = program.getDataTypeManager();
	for (int i = firstParamIndex; i < args.length; i++) {
		String name = args[i].getName();
		if (Function.RETURN_PTR_PARAM_NAME.equals(name)) {
			continue; // discard what should be an auto-param
		}

		DataType type = args[i].getDataType().clone(dtm);
		if (settleCTypes) {
			type = settleCDataType(type, dtm);
		}
		Parameter param =
			new ParameterImpl(name, type, VariableStorage.UNASSIGNED_STORAGE, program);
		param.setComment(args[i].getComment());
		params.add(param);
	}
	return params;
}
 
Example #4
Source File: DecompileResults.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public DecompileResults(Function f, Language language, CompilerSpec compilerSpec,
		PcodeDataTypeManager d, String e, InputStream raw,
		DecompileProcess.DisposeState processState,
		boolean showNamespace) {
	function = f;
	this.language = language;
	this.compilerSpec = compilerSpec;
	dtmanage = d;
	errMsg = e;
	hfunc = null;
	hparamid = null;
	docroot = null;
	this.showNamespace = showNamespace;
	//dumpResults(raw);
	parseRawString(raw);
}
 
Example #5
Source File: DecompilerParameterIdCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void checkModelNameConsistency(Function func) {
	int paramCount = func.getParameterCount();

	String modelName = func.getCallingConventionName();

	if (func.getStackPurgeSize() == 0 && paramCount > 0 &&
		modelName.equals(CompilerSpec.CALLING_CONVENTION_stdcall)) {
		try {
			func.setCallingConvention(CompilerSpec.CALLING_CONVENTION_cdecl);
		}
		catch (InvalidInputException e) {
			setStatusMsg("Invalid Calling Convention " + CompilerSpec.CALLING_CONVENTION_cdecl +
				" : " + e);
		}
	}
}
 
Example #6
Source File: GameCubeLoader.java    From Ghidra-GameCube-Loader with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Program> loadProgram(ByteProvider provider, String programName,
		DomainFolder programFolder, LoadSpec loadSpec, List<Option> options, MessageLog log,
		Object consumer, TaskMonitor monitor)
		throws IOException, CancelledException {
	LanguageCompilerSpecPair pair = loadSpec.getLanguageCompilerSpec();
	Language importerLanguage = getLanguageService().getLanguage(pair.languageID);
	CompilerSpec importerCompilerSpec = importerLanguage.getCompilerSpecByID(pair.compilerSpecID);
	
	Address baseAddress = importerLanguage.getAddressFactory().getDefaultAddressSpace().getAddress(0);
	Program program = createProgram(provider, programName, baseAddress, getName(),
			importerLanguage, importerCompilerSpec, consumer);
	
	boolean success = false;
	try {
		success = this.loadInto(provider, loadSpec, options, log, program, monitor);
	}
	finally {
		if (!success) {
			program.release(consumer);
			program = null;
		}
	}
	
	List<Program> results = new ArrayList<Program>();
	if (program != null) {
		results.add(program);
	}
	
	return results;
}
 
Example #7
Source File: SwitchLoader.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
@Override
protected List<Program> loadProgram(ByteProvider provider, String programName,
        DomainFolder programFolder, LoadSpec loadSpec, List<Option> options, MessageLog log,
        Object consumer, TaskMonitor monitor)
                throws IOException, CancelledException 
{
    LanguageCompilerSpecPair pair = loadSpec.getLanguageCompilerSpec();
    Language importerLanguage = getLanguageService().getLanguage(pair.languageID);
    CompilerSpec importerCompilerSpec = importerLanguage.getCompilerSpecByID(pair.compilerSpecID);

    Address baseAddr = importerLanguage.getAddressFactory().getDefaultAddressSpace().getAddress(0);
    Program prog = createProgram(provider, programName, baseAddr, getName(), importerLanguage, importerCompilerSpec, consumer);
    boolean success = false;

    try 
    {
        success = this.loadInto(provider, loadSpec, options, log, prog, monitor);
    }
    finally 
    {
        if (!success) 
        {
            prog.release(consumer);
            prog = null;
        }
    }

    List<Program> results = new ArrayList<Program>();
    if (prog != null) results.add(prog);
    return results;
}
 
Example #8
Source File: FunctionUtility.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether or not the two programs are considered to have the same processor
 * language and compiler specification.
 * @param program1 the first program
 * @param program2 the second program
 * @return true if the two programs have the same processor language and compiler spec.
 */
public static boolean isSameLanguage(Program program1, Program program2) {
	Language language1 = program1.getLanguage();
	Language language2 = program2.getLanguage();
	if (language1.getLanguageID() != language2.getLanguageID()) {
		return false;
	}
	CompilerSpec compilerSpec1 = program1.getCompilerSpec();
	CompilerSpec compilerSpec2 = program2.getCompilerSpec();
	if (compilerSpec1.getCompilerSpecID() != compilerSpec2.getCompilerSpecID()) {
		return false;
	}
	return true;
}
 
Example #9
Source File: ApplyFunctionSignatureCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Sets a function's signature in the program.
 * @param program The program containing the function.
 * @param func the function
 * @param signature the signature to apply
 * @param preserveCallingConvention if true, the functions calling convention will not be modified
 * @param forceName force the name of the signature onto the function
 *                  normally the name is only set on default function names (not user-defined).
 * @param source the source of this function signature
 */
private boolean setSignature(Function func, FunctionSignature signature,
		boolean preserveCallingConvention, boolean forceName, SourceType source)
		throws InvalidInputException {

	// take on the signatures name if this is not a user defined symbol
	String name = signature.getName();
	setName(func, name, source, forceName);

	CompilerSpec compilerSpec = program.getCompilerSpec();
	String conventionName = getCallingConvention(func, compilerSpec);

	ParameterDefinition[] args = signature.getArguments();
	List<Parameter> params = createParameters(compilerSpec, conventionName, args);

	SymbolTable symbolTable = program.getSymbolTable();
	try {

		adjustParameterNamesToAvoidConflicts(symbolTable, func, params);

		ReturnParameterImpl returnParam =
			new ReturnParameterImpl(signature.getReturnType(), program);

		func.updateFunction(conventionName, returnParam, params,
			FunctionUpdateType.DYNAMIC_STORAGE_FORMAL_PARAMS, false, source);
		func.setVarArgs(signature.hasVarArgs());
	}
	catch (DuplicateNameException e) {
		// should not happen unless caused by a concurrent operation
		throw new InvalidInputException(
			"Parameter name conflict, likely due to concurrent operation");
	}

	updateStackPurgeSize(func, program);

	return true;
}
 
Example #10
Source File: GnuDemanglerParser.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
DemangledObject doBuild(Demangled demangledObject) {

	DemangledFunction function = (DemangledFunction) demangledObject;
	function.setSignature(type);
	function.setCallingConvention(CompilerSpec.CALLING_CONVENTION_thiscall);

	DemangledThunk thunk = new DemangledThunk(mangledSource, demangledSource, function);
	if (prefix.contains(COVARIANT_RETURN_THUNK)) {
		thunk.setCovariantReturnThunk();
	}

	thunk.setSignaturePrefix(prefix);
	return thunk;
}
 
Example #11
Source File: GnuDemangler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canDemangle(Program program) {

	String executableFormat = program.getExecutableFormat();
	if (isELF(executableFormat) || isMacho(executableFormat)) {
		return true;
	}

	CompilerSpec spec = program.getCompilerSpec();
	String specId = spec.getCompilerSpecID().getIdAsString();
	if (!specId.toLowerCase().contains("windows")) {
		return true;
	}
	return false;
}
 
Example #12
Source File: DecompilerParallelConventionAnalysisCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private SourceType updateCallingConvention(Function f, SourceType signatureSource,
		HighFunction highFunction, String modelName) throws InvalidInputException {
	// do the number of parameters disagree and decompiler says there is one more
	Namespace parentNamespace = f.getParentNamespace();
	if (f.getParameterCount() + 1 == highFunction.getFunctionPrototype().getNumParams()) {
		// does it have a namespace
		if (parentNamespace.getID() != Namespace.GLOBAL_NAMESPACE_ID &&
			// prevent accidental treatment of std namespace as class
			!parentNamespace.getName().equals(STD_NAMESPACE)) {
			//    does it have a this call convention that is the equivalent of the stdcall
			PrototypeModel callingConvention = program.getCompilerSpec().getCallingConvention(
				CompilerSpec.CALLING_CONVENTION_thiscall);
			if (callingConvention != null) {
				modelName = CompilerSpec.CALLING_CONVENTION_thiscall;
			}
		}
	}
	//   Then is __thiscall, create an object and new parameter if it doesn't have one yet.
	if (modelName.equals(CompilerSpec.CALLING_CONVENTION_stdcall) &&
		f.getStackPurgeSize() == 0 && f.getParameterCount() > 0) {
		// if has parameters, and there is no purge, it can't be a stdcall, change it to cdecl
		if (program.getLanguageID().getIdAsString().startsWith("x86:LE:32")) {
			modelName = CompilerSpec.CALLING_CONVENTION_cdecl;
			// it could be a this call...
		}
	}
	if (parentNamespace.getSymbol().getSymbolType() == SymbolType.NAMESPACE &&
		modelName.equals(CompilerSpec.CALLING_CONVENTION_thiscall)) {
		NamespaceUtils.convertNamespaceToClass(f.getParentNamespace());
	}
	f.setCallingConvention(modelName);
	if (signatureSource == SourceType.DEFAULT) {
		signatureSource = SourceType.ANALYSIS;
	}
	return signatureSource;
}
 
Example #13
Source File: DecompilerValidator.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private DecompileOptions getDecompilerOptions() {
	try {
		CompilerSpec spec = program.getCompilerSpec();
		PrototypeModel model = (PrototypeModel) spec.getPrototypeEvaluationModel(program);
		options.setProtoEvalModel(model.getName());
	}
	catch (Exception e) {
		Msg.warn(this, "problem setting prototype evaluation model: " + e.getMessage());
	}
	return options;
}
 
Example #14
Source File: HighFunction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @param function  function associated with the higher level function abstraction.
 * @param language  description of the processor language of the function
 * @param compilerSpec description of the compiler that produced the function
 * @param dtManager data type manager
 * @param showNamespace true signals to print function names with their namespace
 */
public HighFunction(Function function, Language language, CompilerSpec compilerSpec,
		PcodeDataTypeManager dtManager, boolean showNamespace) {
	super(function.getProgram().getAddressFactory(), dtManager);
	func = function;
	this.language = language;
	this.compilerSpec = compilerSpec;
	this.showNamespace = showNamespace;
	localSymbols = new LocalSymbolMap(this, "stack");
	globalSymbols = new GlobalSymbolMap(this);
	proto = new FunctionPrototype(localSymbols, function);
	jumpTables = null;
	protoOverrides = null;
}
 
Example #15
Source File: DataTypeManagerDB.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * This method is only invoked during an upgrade.
 * 
 * @param compilerSpec compiler spec
 * @param monitor      task monitor
 * @throws CancelledException if task cacn
 */
protected void doSourceArchiveUpdates(CompilerSpec compilerSpec, TaskMonitor monitor)
		throws CancelledException {
	SourceArchiveUpgradeMap upgradeMap = new SourceArchiveUpgradeMap();
	for (SourceArchive sourceArchive : getSourceArchives()) {
		SourceArchive mappedSourceArchive =
			upgradeMap.getMappedSourceArchive(sourceArchive, compilerSpec);
		if (mappedSourceArchive != null) {
			replaceSourceArchive(sourceArchive, mappedSourceArchive);
		}
	}
	BuiltInDataTypeManager builtInDTM = BuiltInDataTypeManager.getDataTypeManager();
	for (String name : SourceArchiveUpgradeMap.getTypedefReplacements()) {
		monitor.checkCanceled();
		DataType dataType = getDataType(CategoryPath.ROOT, name);
		if (dataType instanceof TypeDef) {
			DataType builtIn = builtInDTM.getDataType(CategoryPath.ROOT, name);
			if (builtIn != null) {
				try {
					replace(dataType, resolve(builtIn, null));
				}
				catch (DataTypeDependencyException e) {
					throw new AssertException("Got DataTypeDependencyException on built in", e);
				}
			}
		}
	}
}
 
Example #16
Source File: SourceArchiveUpgradeMap.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public SourceArchive getMappedSourceArchive(SourceArchive sourceArchive,
		CompilerSpec compiler) {
	if (compiler != null) {
		CompilerSpecID compilerSpecID = compiler.getCompilerSpecID();
		if (WINDOWS_CSPEC_ID.equals(compilerSpecID)) {
			SourceArchive replacementSourceArchive =
				windowsMap.get(sourceArchive.getSourceArchiveID());
			if (replacementSourceArchive != null) {
				return replacementSourceArchive;
			}
		}
	}
	return defaultMap.get(sourceArchive.getSourceArchiveID());
}
 
Example #17
Source File: ProgramAddressFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void initStackSpace(Language language, CompilerSpec compilerSpec) {
	this.stackSpace = compilerSpec.getStackSpace();
	try {
		addAddressSpace(stackSpace);
	}
	catch (DuplicateNameException e) {
		throw new IllegalStateException("Language must not define 'STACK' space: " +
			language.getLanguageID().getIdAsString());
	}
}
 
Example #18
Source File: ProgramAddressFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public ProgramAddressFactory(Language language, CompilerSpec compilerSpec) {
	super(language.getAddressFactory().getAllAddressSpaces(),
		language.getAddressFactory().getDefaultAddressSpace());
	this.originalFactory = language.getAddressFactory();
	initOtherSpace(language);
	initExternalSpace(language);
	initStackSpace(language, compilerSpec);
	initHashSpace(language);
	initJoinSpace(language);
}
 
Example #19
Source File: MDMangGhidra.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private DemangledFunction processFunction(MDFunctionInfo functionInfo,
		DemangledFunction function) {
	MDFunctionType functionType = (MDFunctionType) functionInfo.getMDType();
	String convention = functionType.getCallingConvention().toString();
	if ("__cdecl".equals(convention) && functionInfo.isMember() && !functionInfo.isStatic()) {
		// TODO: ultimately the presence of a 'this' parareter will not be keyed 
		// to the calling convention, but for now we need to force it
		convention = CompilerSpec.CALLING_CONVENTION_thiscall;
	}
	function.setCallingConvention(convention);
	MDDataType retType = functionType.getReturnType();
	if ((retType != null) && !retType.toString().isEmpty()) {
		function.setReturnType(processDataType(null, retType));
	}
	MDArgumentsList args = functionType.getArgumentsList();
	if (args != null) {
		for (int index = 0; index < args.getNumArgs(); index++) {
			function.addParameter(processDataType(null, args.getArg(index)));
		}
	}
	if (functionType.isTypeCast()) {
		function.setTypeCast();
	}
	// function.setVirtual(functionType.isVirtual());
	// function.setStatic(functionType.isStatic());
	// if (functionType.isPrivate()) {
	// function.setVisibilty("private");
	// }
	// else if (functionType.isProtected()) {
	// function.setVisibilty("protected");
	// }
	// else if (functionType.isPublic()) {
	// function.setVisibilty("public");
	// }

	// TODO: fix this kludge. Need to add appropriate suffixes to  DemangledFunction (look
	// at DemangledFunctionPointer?). Missing other possible suffixes from
	// functionType.getCVMod().
	// String suffix = "";
	MDCVMod thisPointerCVMod = functionType.getThisPointerCVMod();
	if (thisPointerCVMod != null) {
		if (thisPointerCVMod.isConst()) {
			function.setTrailingConst();
		}
		if (thisPointerCVMod.isVolatile()) {
			function.setTrailingVolatile();
		}
		if (thisPointerCVMod.isPointer64()) {
			function.setTrailingPointer64();
		}
		if (thisPointerCVMod.isRestricted()) {
			function.setTrailingRestrict();
		}
		if (thisPointerCVMod.isUnaligned()) {
			function.setTrailingUnaligned();
		}
	}
	MDThrowAttribute ta = functionType.getThrowAttribute();
	if (ta != null) {
		function.setThrowAttribute(ta.toString());
	}

	// TODO: fill in lots of function.____ items
	return function;
}
 
Example #20
Source File: HighFunction.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public CompilerSpec getCompilerSpec() {
	return compilerSpec;
}