Java Code Examples for ghidra.util.Msg#error()

The following examples show how to use ghidra.util.Msg#error() . 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: LanguageTranslatorFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void getExplicitTranslators(List<LanguageTranslator> translators) {
	for (Class<?> translatorClass : ClassSearcher.getClasses(LanguageTranslator.class)) {
		int modifiers = translatorClass.getModifiers();
		if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers) ||
			Modifier.isAbstract(modifiers)) {
			continue; // ignore utility implementations
		}
		try {
			translators.add((LanguageTranslator) translatorClass.newInstance());
		}
		catch (Exception e) {
			Msg.error(this,
				"Failed to instatiate language translator: " + translatorClass.getName(), e);
			++badFileCount;
		}
	}
}
 
Example 2
Source File: PreviewTable.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/*********************************************************************************************
 * PRIVATE METHODS
 ********************************************************************************************/

private void buildPreviewString(int instrSize, String valueStr, String maskStr, int posptr,
		int row) {

	// Extract the number of bytes from the full string created above, both for the value 
	// and the mask;
	String instrValTmp = valueStr.substring(posptr, posptr + (instrSize * 8));
	String instrMaskTmp = maskStr.substring(posptr, posptr + (instrSize * 8));

	// Add the strings to the table, making sure to format the string such that
	// masked bits are displayed correctly.
	String prevStr = "";
	try {
		prevStr = InstructionSearchUtils.formatSearchString(instrValTmp, instrMaskTmp);
	}
	catch (InvalidInputException e) {
		Msg.error(this, "Error formatting string for preview: " + instrValTmp);
		// Note, don't return here - continue to add the string (empty at this point) to the
		// preview at the given row.
	}

	addPreviewString(prevStr, row);
}
 
Example 3
Source File: TableUpdateJob.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * The basic run() method that executes the state machine.
 */
public void run() {
	gotoNextState(); // initialize the currentState.

	while (currentState != DONE) {
		try {
			processState(currentState);
		}
		catch (CancelledException ex) {
			// handled in gotoNextState
		}
		catch (Exception e) {
			if (!isFired) {
				Msg.error(this, "Unexpected Exception: " + e.getMessage(), e);
				break;
			}
		}

		gotoNextState();
	}
}
 
Example 4
Source File: FidDB.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Return libraries by name
 *   Restrict by version if -version- is non-null
 *   Restrict by variant if -variant- is non-null
 * @param family is the family name of the library (must not be null)
 * @param version is the optional version string
 * @param variant is the optional variant string
 * @return matching list of libraries
 */
public List<LibraryRecord> findLibrariesByName(String family, String version, String variant) {
	try {
		List<LibraryRecord> list = librariesTable.getLibrariesByName(family, version, variant);
		return list;
	}
	catch (IOException e) {
		Msg.error(this, "Serious problem search for FID Libraries by name", e);
	}
	return null;
}
 
Example 5
Source File: DexExceptionHandlersAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createCatchSymbol(Program program, String catchName, Address catchAddress) {
	Namespace catchNameSpace = DexUtil.getOrCreateNameSpace(program, "CatchHandlers");
	try {
		program.getSymbolTable().createLabel(catchAddress, catchName, catchNameSpace,
			SourceType.ANALYSIS);
	}
	catch (Exception e) {
		Msg.error(this, "Error creating label", e);
	}
}
 
Example 6
Source File: CliStreamBlob.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the blob at the given address with the new blob.
 * 
 * @param updatedBlob The updated blob.
 * @param addr The address of the blob to update.
 * @param program The program that will get the update.
 */
public boolean updateBlob(CliBlob updatedBlob, Address addr, Program program) {

	// Get and validate the containing structure at the given address
	Data containingData = program.getListing().getDefinedDataContaining(addr);
	if (containingData == null || !containingData.isStructure()) {
		Msg.error(this, "Containing data of " + updatedBlob.getName() + " at address " + addr +
			" is not a structure.");
		return false;
	}
	Structure containingStructure = (Structure) containingData.getDataType();

	// Make sure there is an old blob at the given address
	int structureOffset = (int) addr.subtract(containingData.getAddress());
	DataTypeComponent oldBlobDataComponent = containingStructure.getComponentAt(structureOffset);
	if (oldBlobDataComponent == null) {
		Msg.error(this, "Existing blob at address " + addr + " was not found.");
		return false;
	}
	
	// Make sure the old blob has the same size as the new blob
	DataType oldBlobDataType = oldBlobDataComponent.getDataType();
	DataType newBlobDataType = updatedBlob.toDataType();
	if (oldBlobDataType.getLength() != newBlobDataType.getLength()) {
		Msg.error(this, "Cannot replace existing blob at address " + addr + " with " +
			updatedBlob.getName() + " because they have different sizes.");
		return false;
	}

	// Update the blob
	containingStructure.replaceAtOffset(structureOffset, newBlobDataType, updatedBlob.getSize(),
		updatedBlob.getName(), updatedBlob.getContentsComment());

	return true;
}
 
Example 7
Source File: PackDataTypeAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void packDataType(DataType dataType) throws InvalidInputException {
	if (!(dataType instanceof Structure)) {
		Msg.error(this,
			"Can't pack data type " + dataType.getName() + ". It's not a structure.");
		return;
	}
	((Structure) dataType).pack(1);
}
 
Example 8
Source File: FidDB.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all the function records that have the provided specific hash.
 * @param hash the hash value
 * @return a list of function records that match the hash value
 */
public List<FunctionRecord> findFunctionsBySpecificHash(long specificHash) {
	try {
		List<FunctionRecord> list =
			functionsTable.getFunctionRecordsBySpecificHash(specificHash);
		return list;
	}
	catch (IOException e) {
		Msg.error(this, "Serious problem searching for FID Functions by specific hash", e);
	}
	return null;
}
 
Example 9
Source File: OldLanguageFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Return old language if an old language specification file exists for the specified language and version.
 * @param languageID
 * @param majorVersion language major version, or -1 for latest version
 * @return old language or null if specification not found.
 */
public Language getOldLanguage(LanguageID languageID, int majorVersion) {
	OldLanguage oldLang = languageMap.get(new LanguageTag(languageID, majorVersion));
	if (oldLang != null) {
		try {
			oldLang.validate();
			return oldLang;
		}
		catch (Exception e) {
			Msg.error(log, e.getMessage());
		}
	}
	return null;
}
 
Example 10
Source File: NRO0Header.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
private void readHeader(BinaryReader reader)
{
    try 
    {
        reader.readNextInt(); // Reserved
        this.mod0Offset = reader.readNextInt();
        reader.readNextLong(); // Padding
        this.magic = reader.readNextAsciiString(4);
        
        if (!this.magic.equals("NRO0"))
            throw new InvalidMagicException("NRO0");
        
        this.version = reader.readNextInt();
        this.size = reader.readNextInt();
        this.flags = reader.readNextInt();
        this.textHeader = new NRO0SectionHeader(reader);
        this.rodataHeader = new NRO0SectionHeader(reader);
        this.dataHeader = new NRO0SectionHeader(reader);
        this.bssSize = reader.readNextInt();
        reader.readNextInt(); // Reserved
        this.buildId = reader.readNextByteArray(0x20);
        reader.readNextInt(); // Reserved
        this.apiInfo = new NRO0SectionHeader(reader);
        this.dynstr = new NRO0SectionHeader(reader);
        this.dynsym = new NRO0SectionHeader(reader);
    } 
    catch (IOException e) 
    {
        Msg.error(this, "Failed to read NRO0 header");
    }
}
 
Example 11
Source File: LibraryLookupTable.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private static ResourceFile getSystemResourceDir(int size) {
	try {
		return ghidra.framework.Application.getModuleDataSubDirectory(
			"symbols/" + getMemorySizePath(size));
	}
	catch (Exception e) {
		Msg.error(LibraryLookupTable.class,
			"couldn't find symbols/win directory in module data directory", e);
	}
	return null;
}
 
Example 12
Source File: DWARFDataTypeImporter.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Copy an anon Datatype (or a chain of pointers to a anon DataType) into a new CategoryPath
 * with a new name that is appropriate for a structure member field.
 * <p>
 * Use this method when a struct has a field with an anon datatype.  The new copied
 * datatype will be called "anonorigname_for_structurefieldname"
 * <p>
 *
 * @param dt - DataType to copy
 * @param destCategory {@link CategoryPath} to copy to
 * @param membername the name of the structure member that uses this anon datatype.
 * @return new DataType that is a copy of the old type, but in a new location and name.
 */
private DataType copyAnonTypeForMember(DataType dt, CategoryPath destCategory,
		String membername) {
	List<Pointer> ptrChainTypes = new ArrayList<>();
	DataType actualDT = dt;
	while (actualDT instanceof Pointer) {
		ptrChainTypes.add((Pointer) actualDT);
		actualDT = ((Pointer) actualDT).getDataType();
	}

	if (actualDT.getCategoryPath().equals(destCategory)) {
		return dt;
	}

	DataType copy = actualDT.copy(dataTypeManager);
	try {
		copy.setNameAndCategory(destCategory, copy.getName() + "_for_" + membername);
	}
	catch (InvalidNameException | DuplicateNameException e) {
		Msg.error(this, "Failed to copy anon type " + dt);
		return dt;
	}

	DataType result = copy;
	for (int i = ptrChainTypes.size() - 1; i >= 0; i--) {
		Pointer origPtr = ptrChainTypes.get(i);
		result = new PointerDataType(result,
			origPtr.isDynamicallySized() ? -1 : origPtr.getLength(), dataTypeManager);
	}

	return result;
}
 
Example 13
Source File: FVSlider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the slider position for the given file pointer position. This is calculated by
 * computing the position of the file pointer as a percentage of the total file size, and 
 * applying the same to the slider (relative to its maximum value).
 * 
 * @param filePos
 * @return
 */
private int getSliderPosition(long filePos) {
	try {
		float fileRatio = (float) filePos / reader.getFileSize();
		return (int) (getMaximum() * fileRatio);
	}
	catch (IOException e) {
		Msg.error(this, "Error getting file size", e);
	}

	return 0;
}
 
Example 14
Source File: ParameterInfo.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public Parameter createParameterDefinition(Function destFunction, int ordinal) {
	try {
		Parameter var =
			new MyParameter(getName(), getOrdinal(), getDataType(),
				getVariableStorage().getSerializationString(), destFunction.getProgram(),
				getSource());
		var.setComment(getComment());
		return var;
	}
	catch (InvalidInputException e) {
		Msg.error(this, "Unable to apply parameter '" + getName() + "' to function " +
			destFunction.getName() + ": " + e.getMessage());
		return null;
	}
}
 
Example 15
Source File: FrameDescriptionEntry.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void createLsda(MemoryBlock ehblock, RegionDescriptor region)
		throws MemoryAccessException {

	DwarfDecodeContext lsdaDecodeContext =
		new DwarfDecodeContext(program, augmentationDataAddr, ehblock);

	DwarfEHDecoder lsdaDecoder = DwarfDecoderFactory.getDecoder(cie.getLSDAEncoding());
	Address lsdaAddr = lsdaDecoder.decodeAddress(lsdaDecodeContext);

	region.setLSDAAddress(lsdaAddr);

	String lsdaComment = "(FDE Augmentation Data) LSDA Data Pointer";
	createAndCommentData(program, augmentationDataAddr, lsdaDecoder.getDataType(program),
		lsdaComment, CodeUnit.EOL_COMMENT);

	if (augmentationDataAddr.equals(lsdaAddr)) {
		// decoded a reference that returned here -- a null reference
		return;
	}

	program.getReferenceManager().addMemoryReference(augmentationDataAddr, lsdaAddr,
		RefType.DATA, SourceType.ANALYSIS, 0);

	if (!program.getMemory().getAllInitializedAddressSet().contains(lsdaAddr)) {

		String errorMessage = "Can't create LSDA data @ " + lsdaAddr +
			". The address is not in the program's initialized memory!  CIE @ " +
			cie.getAddress() + " FDE @ " + baseAddress;

		// Log error.
		Msg.error(this, errorMessage);

		// Add error bookmark.
		BookmarkManager bookmarkManager = program.getBookmarkManager();
		bookmarkManager.setBookmark(augmentationDataAddr, BookmarkType.ERROR,
			"Exception Handling Data", errorMessage);

		return;
	}

	try {
		LSDATable table = new LSDATable(monitor, program);
		table.create(lsdaAddr, region);
	}
	catch (Exception e) {
		Msg.error(this, "Error creating LSDA @ " + lsdaAddr + "  " + e.getMessage(), e);
	}
}
 
Example 16
Source File: CountedDynamicDataType.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
protected DataTypeComponent[] getAllComponents(MemBuffer buf) {
	Memory memory = buf.getMemory();
	Address start = buf.getAddress();

	// Find count
	int n = (int) getCount(memory, start.add(counterOffset));

	DataTypeComponent[] comps = new DataTypeComponent[n + 1];
	DataTypeInstance dti = DataTypeInstance.getDataTypeInstance(header, buf);

	if (dti == null) {
		Msg.error(this, "ERROR: problem with data at " + buf.getAddress());
		return null;
	}
	int countSize = dti.getLength();
	comps[0] =
		new ReadOnlyDataTypeComponent(dti.getDataType(), this, countSize, 0, 0,
			header.getName() + "_" + buf.getAddress(), "");
	int offset = countSize;
	MemoryBufferImpl newBuf = new MemoryBufferImpl(memory, buf.getAddress());
	try {
		newBuf.advance(countSize);
		for (int i = 1; i <= n; i++) {
			dti = DataTypeInstance.getDataTypeInstance(baseStruct, buf);
			if (dti == null) {
				Msg.error(this, "ERROR: problem with data at " + buf.getAddress());
				return null;
			}
			int len = dti.getLength();
			comps[i] = new ReadOnlyDataTypeComponent(dti.getDataType(), this, len, i, offset,
				baseStruct.getName() + "_" + newBuf.getAddress(), "");
			offset += len;
			newBuf.advance(len);
		}
	}
	catch (AddressOverflowException e) {
		Msg.error(this, "ERROR: problem with data at " + buf.getAddress());
		return null;
	}
	return comps;
}
 
Example 17
Source File: AndroidProjectCreator.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void processListing(File outputDirectory, List<GFile> listing, TaskMonitor monitor)
		throws IOException, CancelledException {
	for (GFile child : listing) {

		String childName = child.getName();

		if (monitor.isCancelled()) {
			break;
		}
		monitor.setIndeterminate(true);

		if (child.isDirectory()) {
			if (childName.equals("META-INF")) {
				continue;
			}
			File subDir = new File(outputDirectory, childName);
			FileUtilities.checkedMkdir(subDir);
			processListing(subDir, child.getListing(), monitor);
			continue;
		}

		File cacheFile = FileSystemService.getInstance().getFile(child.getFSRL(), monitor);
		try {
			if (childName.endsWith(".xml") &&
				AndroidXmlFileSystem.isAndroidXmlFile(cacheFile, monitor)) {
				processXML(outputDirectory, child, monitor);
			}
			else if (childName.endsWith("classes.dex")) {
				processDex(outputDirectory, child, monitor);
			}
			else if (childName.endsWith("resources.arsc")) {
				//TODO convert resources file back into actual resources
				copyFile(cacheFile, outputDirectory, child.getName(), monitor);
			}
			else if (childName.endsWith(".class")) {
				processClass(outputDirectory, child, monitor);
			}
			else {
				copyFile(cacheFile, outputDirectory, childName, monitor);
			}
		}
		catch (Exception e) {
			log.appendMsg("Unable to export child file: " + child.getFSRL());
			log.appendMsg("\tISSUE WAS: " + e.getMessage());
			Msg.error(this, "Unable to export child file", e);
		}
	}
}
 
Example 18
Source File: DWARFImportSummary.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Writes summary information to the {@link Msg} log.
 */
public void logSummaryResults() {
	if (totalElapsedMS > 0) {
		Msg.info(this, String.format("DWARF import - total elapsed: %dms", totalElapsedMS));
	}
	if (dataTypeElapsedMS > 0) {
		Msg.info(this,
			String.format("DWARF data type import - elapsed: %dms", dataTypeElapsedMS));
	}
	if (funcsElapsedMS > 0) {
		Msg.info(this,
			String.format("DWARF func & symbol import - elapsed: %dms", funcsElapsedMS));
	}
	if (dataTypesAdded > 0) {
		Msg.info(this, String.format("DWARF types imported: %d", dataTypesAdded));
	}
	if (funcsAdded > 0) {
		Msg.info(this, String.format("DWARF funcs added: %d", funcsAdded));
	}
	if (funcSignaturesAdded > 0) {
		Msg.info(this,
			String.format("DWARF function signatures added: %d", funcSignaturesAdded));
	}

	if (!typeRemappings.isEmpty()) {
		Msg.error(this,
			"DWARF data type remappings (DWARF data type definitions that changed meaning in different compile units):");
		Msg.error(this, "  Data type -> changed to -> Data Type");
		int x = 0;
		for (String s : typeRemappings) {
			Msg.error(this, "  " + s);
			if (x++ > 1000) {
				Msg.error(this, "...omitting " + (typeRemappings.size() - 1000) +
					" additional type remapping warnings.");
				break;
			}
		}
	}

	if (!relocationErrorVarDefs.isEmpty()) {
		Msg.error(this, "DWARF static variables with missing address info:");
		Msg.error(this, "  [Variable symbolic name  : variable data type]");
		for (String varDef : relocationErrorVarDefs) {
			Msg.error(this, "  " + varDef);
		}
	}

	if (varFitError > 0) {
		Msg.error(this,
			"DWARF variable definitions that failed because the data type was too large for the defined register location: " +
				varFitError);
	}

	if (varDynamicRegisterError > 0) {
		Msg.error(this,
			"DWARF variable definitions that failed because they depended on the dynamic value of a register: " +
				varDynamicRegisterError);
	}

	if (varDWARFExpressionValue > 0) {
		Msg.error(this,
			"DWARF variable definitions that failed because they are computed pseudo variables: " +
				varDWARFExpressionValue);
	}
	if (exprReadError > 0) {
		Msg.error(this, "DWARF expression failed to read: " + exprReadError);
	}
}
 
Example 19
Source File: ISO9660Analyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Offset checkSignatures(Program program) {
	int magicLen = ISO9660Constants.MAGIC_BYTES.length;
	byte[] signatureArray = new byte[magicLen];

	try {
		Options options = program.getOptions("Program Information");
		String format = options.getString("Executable Format", null);
		if (!BinaryLoader.BINARY_NAME.equals(format)) {
			return Offset.NotFound;
		}

		MemoryBlock[] blocks = program.getMemory().getBlocks();
		if (blocks.length != 1) {
			return Offset.NotFound;
		}

		AddressSpace addressSpace = program.getAddressFactory().getDefaultAddressSpace();
		if (!(blocks[0].getStart().getAddressSpace().equals(addressSpace))) {
			return Offset.NotFound;
		}

		long blockSize = blocks[0].getSize();

		//block must start at zero
		if (blocks[0].getStart().getOffset() != 0L) {
			return Offset.NotFound;
		}

		//is the block initialized
		if (!blocks[0].isInitialized()) {
			return Offset.NotFound;
		}

		ByteProvider provider = new MemoryByteProvider(program.getMemory(), addressSpace);
		BinaryReader reader = new BinaryReader(provider, true);

		//Make sure that the current programs max offset is at least big enough to check
		//for the ISO's max address location of a signature
		if (blockSize < ISO9660Constants.MIN_ISO_LENGTH1) {
			return Offset.NotFound;
		}

		//Check first possible signature location
		reader.setPointerIndex(ISO9660Constants.SIGNATURE_OFFSET1_0x8001);
		signatureArray = reader.readNextByteArray(magicLen);
		if (Arrays.equals(signatureArray, ISO9660Constants.MAGIC_BYTES)) {
			//Where to start the reader during mark up
			return Offset.Offset1;
		}

		if (blockSize < ISO9660Constants.MIN_ISO_LENGTH2) {
			return Offset.NotFound;
		}

		//Check second possible signature location
		reader.setPointerIndex(ISO9660Constants.SIGNATURE_OFFSET2_0x8801);
		signatureArray = reader.readNextByteArray(magicLen);
		if (Arrays.equals(signatureArray, ISO9660Constants.MAGIC_BYTES)) {
			//Where to start the reader during mark up
			return Offset.Offset2;
		}

		if (blockSize < ISO9660Constants.MIN_ISO_LENGTH3) {
			return Offset.NotFound;
		}
		//Check third possible signature location
		reader.setPointerIndex(ISO9660Constants.SIGNATURE_OFFSET3_0x9001);
		signatureArray = reader.readNextByteArray(magicLen);
		if (Arrays.equals(signatureArray, ISO9660Constants.MAGIC_BYTES)) {
			//Where to start the reader during mark up
			return Offset.Offset3;
		}

	}
	catch (Exception e) {
		Msg.error(this, "Error when checking for ISO9660 file signatures", e);
	}

	//Signature is not found at any of the three possible address locations
	return Offset.NotFound;
}
 
Example 20
Source File: CodeBrowserClipboardProvider.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected Transferable copyCode(TaskMonitor monitor) {

		AddressSetView addressSet = getSelectedAddresses();
		try {
			TextLayoutGraphics g = new TextLayoutGraphics();

			Rectangle rect = new Rectangle(Integer.MAX_VALUE, Integer.MAX_VALUE);

			AddressRangeIterator rangeItr = addressSet.getAddressRanges();
			while (rangeItr.hasNext()) {
				AddressRange curRange = rangeItr.next();
				Address curAddress = curRange.getMinAddress();
				Address maxAddress = curRange.getMaxAddress();

				// getAddressAfter(curAddress) returns null in certain situations
				while (curAddress != null && curAddress.compareTo(maxAddress) <= 0) {
					if (monitor.isCancelled()) {
						break;
					}

					//Add the layout for the present address
					Layout layout = getListingModel().getLayout(curAddress, false);
					if (layout != null) {
						LayoutBackgroundColorManager layoutColorMap =
							new EmptyLayoutBackgroundColorManager(PAINT_CONTEXT.getBackground());
						layout.paint(null, g, PAINT_CONTEXT, rect, layoutColorMap, null);
						g.flush();
					}
					// may be null
					curAddress = getListingModel().getAddressAfter(curAddress);
				}
			}

			return createStringTransferable(g.getBuffer().toString());
		}
		catch (Exception e) {
			String msg = e.getMessage();
			if (msg == null) {
				msg = e.toString();
			}

			String message = "Copy failed: " + msg;
			Msg.error(this, message, e);
			tool.setStatusInfo(message, true);
		}

		return null;
	}