Ghidra is a software reverse engineering (SRE) framework
Support for analyzing DTB/DTBO and FTD binaries.
lazybinding-dev629924ed2982
diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtConstants.javanew file mode 100644index 0000000000..87873689b6--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtConstants.java@@ -0,0 +1,40 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++/**+ * Device Tree (DT) constants.+ *+ */+public final class DtConstants {++ /** Device Tree (DT) Magic Value */+ public static final int DT_TABLE_MAGIC = 0xd7b7ab1e;++ /** Device Tree (DT) Magic Value Bytes */+ public static final byte[] DT_TABLE_MAGIC_BYTES =+ new byte[] { (byte) 0xd7, (byte) 0xb7, (byte) 0xab, (byte) 0x1e };++ /** Device Tree (DT) Magic Value Size */+ public static final int DT_TABLE_MAGIC_SIZE = 4;++ /** Device Tree (DT) Page Size */+ public static final int DT_TABLE_DEFAULT_PAGE_SIZE = 2048;++ /** Device Tree (DT) Default Version */+ public static final int DT_TABLE_DEFAULT_VERSION = 0;++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtTableEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtTableEntry.javanew file mode 100644index 0000000000..0b13127996--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtTableEntry.java@@ -0,0 +1,108 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * Class to represent a Device Tree (DT) Table Entry.+ *+ * @see <a href="https://github.com/u-boot/u-boot/blob/master/include/dt_table.h#L40">master/include/dt_table.h</a>+ */+public class DtTableEntry implements StructConverter {++ private int dt_size;+ private int dt_offset;+ private int id;+ private int rev;+ private int[] custom;++ private FdtHeader _fdtHeader;++ public DtTableEntry(BinaryReader reader) throws IOException {+ if (!reader.isBigEndian()) {+ throw new IOException("DTB is always big endian.");+ }++ dt_size = reader.readNextInt();+ dt_offset = reader.readNextInt();+ id = reader.readNextInt();+ rev = reader.readNextInt();+ custom = reader.readNextIntArray(4);++ BinaryReader clonedReader = reader.clone(dt_offset);+ if (clonedReader.peekNextInt() == FdtConstants.FDT_MAGIC) {+ _fdtHeader = new FdtHeader(clonedReader);+ }+ }++ /**+ * Returns the Device Tree (DT) Table Size.+ * @return the Device Tree (DT) Table Size+ */+ public int getDtSize() {+ return dt_size;+ }++ /**+ * Returns the Device Tree (DT) Table Offset.+ * @return the Device Tree (DT) Table Offset+ */+ public int getDtOffset() {+ return dt_offset;+ }++ /**+ * Returns the Device Tree (DT) Table ID.+ * @return the Device Tree (DT) Table ID+ */+ public int getId() {+ return id;+ }++ /**+ * Returns the Device Tree (DT) Table Revision.+ * @return the Device Tree (DT) Table Revision+ */+ public int getRev() {+ return rev;+ }++ /**+ * Returns the Device Tree (DT) Table Custom Bytes.+ * @return the Device Tree (DT) Table Custom Bytes+ */+ public int[] getCustom() {+ return custom;+ }++ /**+ * Returns the FDT Header.+ * @return the FDT Header+ */+ public FdtHeader getFdtHeader() {+ return _fdtHeader;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(this);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtTableHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtTableHeader.javanew file mode 100644index 0000000000..c7fa086b6c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtTableHeader.java@@ -0,0 +1,146 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * Class to represent a Device Tree (DT) Table Header.+ *+ * @see <a href="https://source.android.com/devices/architecture/dto/partitions">devices/architecture/dto/partitions</a>+ *+ * @see <a href="https://github.com/u-boot/u-boot/blob/master/include/dt_table.h#L19">master/include/dt_table.h</a>+ */+public class DtTableHeader implements StructConverter {++ private int magic;+ private int total_size;+ private int header_size;+ private int dt_entry_size;+ private int dt_entry_count;+ private int dt_entries_offset;+ private int page_size;+ private int version;++ private List<DtTableEntry> _entries = new ArrayList<>();++ public DtTableHeader(BinaryReader reader) throws IOException {+ if (!reader.isBigEndian()) {+ throw new IOException("DTB is always big endian.");+ }++ magic = reader.readNextInt();+ if ( magic != DtConstants.DT_TABLE_MAGIC) {+ throw new IOException("Invalid DTB Header magic.");+ }++ total_size = reader.readNextInt();+ header_size = reader.readNextInt();+ dt_entry_size = reader.readNextInt();+ dt_entry_count = reader.readNextInt();+ dt_entries_offset = reader.readNextInt();+ page_size = reader.readNextInt();+ version = reader.readNextInt();++ reader.setPointerIndex(dt_entries_offset);+ for (int i = 0; i < dt_entry_count; ++i) {+ _entries.add(new DtTableEntry(reader));+ }+ }++ /**+ * Returns the Device Tree (DT) magic value.+ * @return the Device Tree (DT) magic value+ */+ public int getMagic() {+ return magic;+ }++ /**+ * Returns the Device Tree (DT) total size.+ * @return the Device Tree (DT) total size+ */+ public int getTotalSize() {+ return total_size;+ }++ /**+ * Returns the Device Tree (DT) header size.+ * @return the Device Tree (DT) header size+ */+ public int getHeaderSize() {+ return header_size;+ }++ /**+ * Returns the Device Tree (DT) entry size.+ * @return the Device Tree (DT) entry size+ */+ public int getDtEntrySize() {+ return dt_entry_size;+ }++ /**+ * Returns the Device Tree (DT) entry count.+ * @return the Device Tree (DT) entry count+ */+ public int getDtEntryCount() {+ return dt_entry_count;+ }++ /**+ * Returns the Device Tree (DT) entries offset.+ * @return the Device Tree (DT) entries offset+ */+ public int getDtEntriesOffset() {+ return dt_entries_offset;+ }++ /**+ * Returns the Device Tree (DT) page size.+ * @return the Device Tree (DT) page size+ */+ public int getPageSize() {+ return page_size;+ }++ /**+ * Returns the Device Tree (DT) version.+ * @return the Device Tree (DT) version+ */+ public int getVersion() {+ return version;+ }++ /**+ * Returns the Device Tree (DT) entries.+ * @return the Device Tree (DT) entries+ */+ public List<DtTableEntry> getEntries() {+ return _entries;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(this);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtbAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtbAnalyzer.javanew file mode 100644index 0000000000..53cd95e651--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtbAnalyzer.java@@ -0,0 +1,120 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.util.Arrays;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSetView;+import ghidra.program.model.data.DataType;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.RefType;+import ghidra.program.model.symbol.SourceType;+import ghidra.util.task.TaskMonitor;++public class DtbAnalyzer extends FileFormatAnalyzer {++ @Override+ public String getName() {+ return "Device Tree (DTB/DTBO) Analyzer";+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return true;+ }++ @Override+ public String getDescription() {+ return "Analyzes Device Tree (DTB/DTBO) files.";+ }++ @Override+ public boolean canAnalyze(Program program) {+ try {+ if (DtbUtil.isCorrectLoader(program)) {+ Address address = toAddr(program, 0);+ byte[] magicBytes = new byte[DtConstants.DT_TABLE_MAGIC_SIZE];+ program.getMemory().getBytes(address, magicBytes);+ return Arrays.equals(magicBytes, DtConstants.DT_TABLE_MAGIC_BYTES);+ }+ }+ catch (Exception e) {+ //ignore+ }+ return false;+ }++ @Override+ public boolean isPrototype() {+ return false;+ }++ @Override+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {++ if (!DtbUtil.isCorrectProcessor(program, log)) {+ return false;+ }++ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), program.getMinAddress());+ BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());++ DtTableHeader header = new DtTableHeader(reader);+ DataType headerDataType = header.toDataType();+ createData(program, program.getMinAddress(), headerDataType);+ createFragment(program, "DtTableHeader", program.getMinAddress(),+ program.getMinAddress().add(headerDataType.getLength()));++ Address entryStartAddress = toAddr(program, header.getDtEntriesOffset());++ monitor.initialize(header.getEntries().size());+ for (int i = 0; i < header.getEntries().size(); ++i) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ DtTableEntry entry = header.getEntries().get(i);+ Data entryData = createData(program, entryStartAddress, entry.toDataType());+ Address entryEndAddress = entryStartAddress.add(header.getDtEntrySize());+ createFragment(program, "DtTableEntry_" + i, entryStartAddress, entryEndAddress);+ entryStartAddress = entryEndAddress;++ Data offsetData = entryData.getComponent(1);//dt_offset field+ program.getReferenceManager()+ .addMemoryReference(offsetData.getMinAddress(),+ toAddr(program, entry.getDtOffset()), RefType.DATA, SourceType.ANALYSIS, 0);++ Address entryDataStartAddress = toAddr(program, entry.getDtOffset());+ Address entryDataEndAddress = entryDataStartAddress.add(entry.getDtSize());+ createFragment(program, "DtTableEntry_" + i, entryDataStartAddress,+ entryDataEndAddress);++ FdtHeader fdtHeader = entry.getFdtHeader();+ if (fdtHeader != null) {+ fdtHeader.markup(toAddr(program, entry.getDtOffset()), program, monitor, log);+ }+ }++ return true;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtbUtil.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtbUtil.javanew file mode 100644index 0000000000..3d9dc4bd30--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/DtbUtil.java@@ -0,0 +1,50 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import ghidra.app.util.importer.MessageLog;+import ghidra.app.util.opinion.BinaryLoader;+import ghidra.program.model.lang.Language;+import ghidra.program.model.lang.Processor;+import ghidra.program.model.listing.Program;++public final class DtbUtil {++ /**+ * Returns TRUE if the program is using the DATA Big-Endian language.+ * @param program the program to check language.+ * @param log the message log to report errors.+ * @return TRUE if the program is using the DATA Big-Endian language+ */+ public final static boolean isCorrectProcessor(Program program, MessageLog log) {+ Language language = program.getLanguage();+ if (language.getProcessor() == Processor.findOrPossiblyCreateProcessor("DATA") &&+ language.isBigEndian()) {+ return true;+ }+ log.appendMsg(program.getName() + " must use \"Data Big-Endian\" processor module.");+ return false;+ }++ /**+ * Returns TRUE if the program is loaded using Binary Loader.+ * @param program the program to check loader.+ * @return TRUE if the program is loaded using Binary Loader+ */+ public final static boolean isCorrectLoader(Program program) {+ return BinaryLoader.BINARY_NAME.equals(program.getExecutableFormat());+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtAnalyzer.javanew file mode 100644index 0000000000..869d204cbf--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtAnalyzer.java@@ -0,0 +1,100 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.util.Arrays;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSetView;+import ghidra.program.model.listing.Program;+import ghidra.util.task.TaskMonitor;++public class FdtAnalyzer extends FileFormatAnalyzer {++ @Override+ public String getName() {+ return "Flattened Device Tree (FDT/DTB/DTBO) Analyzer";+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return true;+ }++ @Override+ public String getDescription() {+ return "Analyzes Flattened Device Tree (FDT) files.";+ }++ @Override+ public boolean canAnalyze(Program program) {+ try {+ if (DtbUtil.isCorrectLoader(program)) {+ Address address = toAddr(program, 0);+ byte[] magicBytes = new byte[FdtConstants.FDT_MAGIC_SIZE];+ program.getMemory().getBytes(address, magicBytes);+ return Arrays.equals(magicBytes, FdtConstants.FDT_MAGIC_BYTES);+ }+ }+ catch (Exception e) {+ //ignore+ }+ return false;+ }++ @Override+ public boolean isPrototype() {+ return false;+ }++ @Override+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {++ if (!DtbUtil.isCorrectProcessor(program, log)) {+ return false;+ }++ try (ByteProvider provider =+ MemoryByteProvider.createProgramHeaderByteProvider(program, true)) {++ BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());++ Address address = program.getMinAddress();++ while (true) {+ monitor.checkCanceled();++ if (address.compareTo(program.getMaxAddress()) >= 0) {+ break;+ }++ reader.setPointerIndex(address.getOffset());++ FdtHeader fdtHeader = new FdtHeader(reader);+ fdtHeader.markup(address, program, monitor, log);++ // look for next FDT entry+ address = address.add(fdtHeader.getTotalSize());+ }+ }+ return true;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtConstants.javanew file mode 100644index 0000000000..4c7f85a116--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtConstants.java@@ -0,0 +1,71 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++/**+ * Flattened Device Tree (FDT) constants.+ *+ * @see <a href="https://android.googlesource.com/platform/system/libufdt/+/refs/heads/master/utils/">libufdt utils folder</a>+ */+public final class FdtConstants {++ /** FDT Magic Value */+ public static final int FDT_MAGIC = 0xd00dfeed;++ /** FDT Magic Value Bytes */+ public static final byte[] FDT_MAGIC_BYTES =+ new byte[] { (byte) 0xd0, (byte) 0x0d, (byte) 0xfe, (byte) 0xed };++ /** FDT Magic Size */+ public static final int FDT_MAGIC_SIZE = 4;++ /** FDT TAG Size */+ public static final int FDT_TAGSIZE = 4;++ /** FDT Begin Node Value */+ public static final int FDT_BEGIN_NODE = 0x1;+ /** FDT End Node Value */+ public static final int FDT_END_NODE = 0x2;+ /** FDT Property Value */+ public static final int FDT_PROP = 0x3;+ /** FDT Begin NOP Value */+ public static final int FDT_NOP = 0x4;+ /** FDT End Node Value */+ public static final int FDT_END = 0x9;++ /** Size of FDT Header Version 1 */+ public static final int FDT_V1_SIZE = (7 * 4);+ /** Size of FDT Header Version 2 */+ public static final int FDT_V2_SIZE = (FDT_V1_SIZE + 4);+ /** Size of FDTHeader Version 3 */+ public static final int FDT_V3_SIZE = (FDT_V2_SIZE + 4);+ /** Size of FDT Header Version 16 */+ public static final int FDT_V16_SIZE = FDT_V3_SIZE;+ /** Size of FDT Header Version 17 */+ public static final int FDT_V17_SIZE = (FDT_V16_SIZE + 4);++ /** FDT Header Version 1 */+ public static final int FDT_VERSION_1 = 1;+ /** FDT Header Version 2 */+ public static final int FDT_VERSION_2 = 2;+ /** FDT Header Version 3 */+ public static final int FDT_VERSION_3 = 3;+ /** FDT Header Version 16 */+ public static final int FDT_VERSION_16 = 16;+ /** FDT Header Version 17 */+ public static final int FDT_VERSION_17 = 17;++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtHeader.javanew file mode 100644index 0000000000..db292c9a0f--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtHeader.java@@ -0,0 +1,349 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.io.IOException;+import java.util.HashMap;+import java.util.Map;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.flatapi.FlatProgramAPI;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.RefType;+import ghidra.program.model.util.CodeUnitInsertionException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.exception.NotFoundException;+import ghidra.util.task.TaskMonitor;++/**+ * Class to represent a Flattened Device Tree (FDT) Header.+ *+ */+public class FdtHeader implements StructConverter {++ private static final int OFF_DT_STRUCT_INDEX = 2;+ private static final int OFF_DT_STRINGS_INDEX = 3;+ private static final int OFF_MEM_RSVMAP_INDEX = 4;++ private int magic;+ private int totalsize;+ private int off_dt_struct;+ private int off_dt_strings;+ private int off_mem_rsvmap;+ private int version;+ private int last_comp_version;+ /* version 2 fields below */+ private int boot_cpuid_phys;+ /* version 3 fields below */+ private int size_dt_strings;+ /* version 17 fields below */+ private int size_dt_struct;++ private Map<Integer, String> stringsMap = new HashMap<>();++ public FdtHeader(BinaryReader reader) throws IOException {+ if (!reader.isBigEndian()) {+ throw new IOException("FTD is always big endian.");+ }++ magic = reader.readNextInt();++ if (magic != FdtConstants.FDT_MAGIC) {+ throw new IOException("Invalid FDT Header magic.");+ }++ totalsize = reader.readNextInt();+ off_dt_struct = reader.readNextInt();+ off_dt_strings = reader.readNextInt();+ off_mem_rsvmap = reader.readNextInt();+ version = reader.readNextInt();+ last_comp_version = reader.readNextInt();++ if (version >= FdtConstants.FDT_VERSION_2) {+ boot_cpuid_phys = reader.readNextInt();+ }+ if (version >= FdtConstants.FDT_VERSION_3) {+ size_dt_strings = reader.readNextInt();+ }+ if (version == FdtConstants.FDT_VERSION_17) {+ size_dt_struct = reader.readNextInt();+ }+ if (version > FdtConstants.FDT_VERSION_17) {+ throw new IOException("Unsupported FDT Header version: " + version);+ }+ }++ /**+ * Returns the MAGIC value of this FDT Header.+ * @see FdtConstants.MAGIC.+ * @return the MAGIC value of this FDT Header+ */+ public int getMagic() {+ return magic;+ }++ /**+ * Returns the total size of this FDT, including all sub-structures.+ * @return the total size of this FDT, including all sub-structures+ */+ public int getTotalSize() {+ return totalsize;+ }++ /**+ * Returns the offset to the Device Tree (DT) structure.+ * @return the offset to the Device Tree (DT) structure+ */+ public int getOffsetToDtStruct() {+ return off_dt_struct;+ }++ /**+ * Returns the offset to the Device Tree (DT) strings.+ * @return the offset to the Device Tree (DT) strings+ */+ public int getOffsetToDtStrings() {+ return off_dt_strings;+ }++ /**+ * Returns the offset to the Device Tree (DT) memory reserve map.+ * @return the offset to the Device Tree (DT) memory reserve map+ */+ public int getOffsetToMemoryReserveMap() {+ return off_mem_rsvmap;+ }++ /**+ * Returns the Device Tree (DT) version.+ * @return the Device Tree (DT) version+ */+ public int getVersion() {+ return version;+ }++ /**+ * Returns the last compatible Device Tree (DT) version.+ * @return the last compatible Device Tree (DT) version+ */+ public int getLastCompatibleVersion() {+ return last_comp_version;+ }++ /**+ * Returns the Boot CPU ID.+ * @return the Boot CPU ID+ */+ public int getBootCpuIdPhysical() {+ return boot_cpuid_phys;+ }++ /**+ * Returns the Device Tree (DT) strings size.+ * @return the Device Tree (DT) strings size+ */+ public int getSizeDtStrings() {+ return size_dt_strings;+ }++ /**+ * Returns the Device Tree (DT) structure size.+ * @return the Device Tree (DT) structure size+ */+ public int getSizeDtStruct() {+ return size_dt_struct;+ }++ /**+ * Marks up the program containing this FDT.+ * @param fdtHeaderAddress the address where the FDT starts+ * @param program the program to markup+ * @param monitor the TaskMonitor+ * @param log the MessageLog+ * @throws Exception if an exception occurs+ */+ public void markup(Address fdtHeaderAddress, Program program,+ TaskMonitor monitor,+ MessageLog log) throws Exception {++ FlatProgramAPI programAPI = new FlatProgramAPI(program);++ DataType fdtHeaderDataType = this.toDataType();+ Data fdtHeaderData = program.getListing().createData(fdtHeaderAddress, fdtHeaderDataType);+ programAPI.createFragment(fdtHeaderData.getDataType().getName(), fdtHeaderAddress,+ fdtHeaderData.getLength());++ //process strings first, so we can use them for the structure+ markupStrings(fdtHeaderAddress, fdtHeaderData, programAPI, monitor);+ markupStructure(fdtHeaderAddress, fdtHeaderData, programAPI, monitor);+ markupMemoryReserveMap(fdtHeaderAddress, fdtHeaderData, programAPI, monitor);+ }++ private void markupStructure(Address fdtHeaderAddress,+ Data fdtHeaderData,+ FlatProgramAPI programAPI, TaskMonitor monitor)+ throws IOException, DuplicateNameException, CodeUnitInsertionException,+ NotFoundException {++ Address structAddress = fdtHeaderAddress.add(getOffsetToDtStruct());+ Data structsData = fdtHeaderData.getComponent(OFF_DT_STRUCT_INDEX);+// program.getReferenceManager()+// .addMemoryReference(structsData.getMinAddress(),+// structAddress, RefType.DATA,+// SourceType.ANALYSIS, 0);++ programAPI.createMemoryReference(structsData, structAddress, RefType.DATA);++ markupStructureContents(structAddress, programAPI, monitor);+ }++ private void markupStructureContents(Address address, FlatProgramAPI programAPI,+ TaskMonitor monitor)+ throws IOException, DuplicateNameException, CodeUnitInsertionException,+ NotFoundException {++ Program currentProgram = programAPI.getCurrentProgram();+ ByteProvider provider =+ new MemoryByteProvider(currentProgram.getMemory(), address);+ BinaryReader reader =+ new BinaryReader(provider, !currentProgram.getLanguage().isBigEndian());++ while (!monitor.isCancelled()) {+ DWordDataType dWordDataType = new DWordDataType();+ switch (reader.peekNextInt()) {+ case FdtConstants.FDT_BEGIN_NODE: {+ FdtNodeHeader nodeHeader = new FdtNodeHeader(reader);+ DataType nodeHeaderDataType = nodeHeader.toDataType();+ programAPI.createData(address, nodeHeaderDataType);+ programAPI.createFragment("FDT_BEGIN_NODE", address,+ nodeHeaderDataType.getLength());+ programAPI.setPlateComment(address,+ "FDT_BEGIN_NODE" + ": " + nodeHeader.getName());+ address = address.add(nodeHeaderDataType.getLength());+ break;+ }+ case FdtConstants.FDT_END_NODE: {+ reader.readNextInt();+ programAPI.createData(address, dWordDataType);+ programAPI.createFragment("FDT_END_NODE", address,+ dWordDataType.getLength());+ programAPI.setPlateComment(address, "FDT_END_NODE");+ address = address.add(4);+ break;+ }+ case FdtConstants.FDT_PROP: {+ FdtProperty property = new FdtProperty(reader);+ DataType propertyDataType = property.toDataType();+ programAPI.createData(address, propertyDataType);+ programAPI.createFragment("FDT_PROP", address,+ propertyDataType.getLength());+ programAPI.setPlateComment(address,+ "FDT_PROP" + ": \n" + getString(property) + " = " ++ property.getDataAsString());+ address = address.add(propertyDataType.getLength());+ break;+ }+ case FdtConstants.FDT_NOP: {+ reader.readNextInt();+ programAPI.createData(address, dWordDataType);+ programAPI.createFragment("FDT_NOP", address,+ dWordDataType.getLength());+ programAPI.setPlateComment(address, "FDT_NOP");+ address = address.add(4);+ break;+ }+ case FdtConstants.FDT_END: {+ reader.readNextInt();+ programAPI.createData(address, dWordDataType);+ programAPI.createFragment("FDT_END", address,+ dWordDataType.getLength());+ programAPI.setPlateComment(address, "FDT_END");+ address = address.add(4);+ return;+ }+ }+ }+ }++ private void markupStrings(Address fdtHeaderAddress, Data fdtHeaderData,+ FlatProgramAPI programAPI, TaskMonitor monitor) throws Exception {++ Address stringsAddress = fdtHeaderAddress.add(getOffsetToDtStrings());+ Data stringsData = fdtHeaderData.getComponent(OFF_DT_STRINGS_INDEX);+ programAPI.createMemoryReference(stringsData, stringsAddress, RefType.DATA);++ int stringSize = 0;+ while (!monitor.isCancelled()) {+ Data stringData = programAPI.createData(stringsAddress, StringDataType.dataType);+ programAPI.createFragment(StringDataType.dataType.getName(), stringsAddress,+ stringData.getLength());+ String string = (String) stringData.getValue();+ storeString(fdtHeaderAddress, stringsAddress, string);+ stringsAddress = stringsAddress.add(stringData.getLength());+ stringSize += stringData.getLength();+ if (stringSize >= getSizeDtStrings()) {+ break;+ }+ }+ }++ private void markupMemoryReserveMap(Address fdtHeaderAddress, Data fdtHeaderData,+ FlatProgramAPI programAPI, TaskMonitor monitor) {++ Address structAddress = fdtHeaderAddress.add(getOffsetToMemoryReserveMap());+ Data structsData = fdtHeaderData.getComponent(OFF_MEM_RSVMAP_INDEX);+ programAPI.createMemoryReference(structsData, structAddress, RefType.DATA);+ }++ private void storeString(Address fdtHeaderAddress, Address stringsAddress, String string) {+ long index = stringsAddress.getOffset() - fdtHeaderAddress.getOffset() - off_dt_strings;+ stringsMap.put((int) index, string);+ }++ /**+ * Look up the string for this property.+ */+ private String getString(FdtProperty property) {+ return stringsMap.getOrDefault(property.getNameOffset(), "");+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType structure = new StructureDataType("fdt_header", 0);+ structure.add(DWORD, "magic", null);+ structure.add(DWORD, "totalsize", null);+ structure.add(DWORD, "off_dt_struct", null);+ structure.add(DWORD, "off_dt_strings", null);+ structure.add(DWORD, "off_mem_rsvmap", null);+ structure.add(DWORD, "version", null);+ structure.add(DWORD, "last_comp_version", null);++ if (version >= FdtConstants.FDT_VERSION_2) {+ structure.add(DWORD, "boot_cpuid_phys", null);+ }+ if (version >= FdtConstants.FDT_VERSION_3) {+ structure.add(DWORD, "size_dt_strings", null);+ }+ if (version >= FdtConstants.FDT_VERSION_17) {+ structure.add(DWORD, "size_dt_struct", null);+ }+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtNodeHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtNodeHeader.javanew file mode 100644index 0000000000..6ab3bd02d0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtNodeHeader.java@@ -0,0 +1,74 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.StructureDataType;+import ghidra.util.NumericUtilities;+import ghidra.util.exception.DuplicateNameException;++/**+ * Class to represent a Flattened Device Tree (FDT) Node.+ *+ * @see <a href="https://android.googlesource.com/platform/external/dtc/+/refs/heads/master/libfdt/fdt.h#36">include/fdt.h</a>+ */+public class FdtNodeHeader implements StructConverter {++ private int tag;+ private String name;++ private int nameLength = 0;++ public FdtNodeHeader(BinaryReader reader) throws IOException {+ tag = reader.readNextInt();+ name = reader.readAsciiString(reader.getPointerIndex());//peek it++ nameLength = (int) NumericUtilities.getUnsignedAlignedValue(name.length() + 1, 4);++ name = reader.readNextAsciiString(nameLength);+ }++ /**+ * Returns the FDT Node Tag.+ * @see FdtConstants+ * @return the FDT Node Tag+ */+ public int getTag() {+ return tag;+ }++ /**+ * Returns the FDT Node Name.+ * @return the FDT Node name+ */+ public String getName() {+ return name;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String structureName = "fdt_node_header_" + name.length();+ StructureDataType structure = new StructureDataType(structureName, 0);+ structure.add(DWORD, "tag", null);+ structure.add(STRING, nameLength, "name", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtProperty.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtProperty.javanew file mode 100644index 0000000000..4c8d0b96ab--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtProperty.java@@ -0,0 +1,129 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.program.model.data.*;+import ghidra.util.NumericUtilities;+import ghidra.util.StringUtilities;+import ghidra.util.exception.DuplicateNameException;++/**+ * Class to represent a Flattened Device Tree (FDT) Property.+ *+ * @see <a href="https://android.googlesource.com/platform/external/dtc/+/refs/heads/master/libfdt/fdt.h#41">include/fdt.h</a>+ */+public class FdtProperty implements StructConverter {++ private int tag;+ private int length;+ private int nameOffset;+ private byte[] data;++ public FdtProperty(BinaryReader reader) throws IOException {+ tag = reader.readNextInt();+ length = reader.readNextInt();+ nameOffset = reader.readNextInt();++ length = (int) NumericUtilities.getUnsignedAlignedValue(length, 4);++ data = (length == 0) ? new byte[0] : reader.readNextByteArray(length);+ }++ /**+ * Returns the FDT Property Tag.+ * @see FdtConstants+ * @return the FDT Property Tag+ */+ public int getTag() {+ return tag;+ }++ /**+ * Returns the FDT Property length.+ * @return the FDT Property length+ */+ public int getLength() {+ return length;+ }++ /**+ * Returns the offset to the FDT Property name.+ * @return the offset to the FDT Property name+ */+ public int getNameOffset() {+ return nameOffset;+ }++ /**+ * Returns the FDT Property data bytes.+ * @return the FDT Property data bytes+ */+ public byte[] getData() {+ return data;+ }++ /**+ * Returns the FDT Property data bytes as a readable string.+ * @return the FDT Property data bytes as a readable string+ */+ public String getDataAsString() {+ if (length > 0) {+ if (StringUtilities.isAsciiChar(data[0])) {+ return new String(data).trim();+ }+ else {+ return NumericUtilities.convertBytesToString(data);+ }+ }+ return "<empty>";+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType structure =+ new StructureDataType(getDataTypeName(), 0);+ structure.add(DWORD, "tag", null);+ structure.add(DWORD, "len", null);+ structure.add(DWORD, "nameoff", null);+ if (length > 0) {+ if (StringUtilities.isAsciiChar(data[0])) {+ structure.add(STRING, length, "data", null);+ }+ else {+ DataType array = new ArrayDataType(BYTE, length, BYTE.getLength());+ structure.add(array, length, "data", null);+ }+ }+ return structure;+ }++ /**+ * Generates the name for this FDT property.+ * @return the name for this FDT property+ */+ private String getDataTypeName() {+ String name = "fdt_property_" + length;+ if (length > 0 && StringUtilities.isAsciiChar(data[0])) {+ return name + "_s";+ }+ return name;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtReserveEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtReserveEntry.javanew file mode 100644index 0000000000..1550997e01--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/dtb/FdtReserveEntry.java@@ -0,0 +1,59 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.dtb;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * Class to represent a Flattened Device Tree (FDT) Reserve Entry.+ *+ */+public class FdtReserveEntry implements StructConverter {++ private long address;+ private long size;++ FdtReserveEntry(BinaryReader reader) throws IOException {+ address = reader.readNextLong();+ size = reader.readNextLong();+ }++ /**+ * Returns FDT Reserve Entry address.+ * @return FDT Reserve Entry address+ */+ public long getAddress() {+ return address;+ }++ /**+ * Returns FDT Reserve Entry size.+ * @return FDT Reserve Entry size+ */+ public long getSize() {+ return size;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(this);+ }++}