Ghidra is a software reverse engineering (SRE) framework
GP-1088 Fix / improve Ext4 inline data handling, mounting
dev7473687b73b4e45f4e
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.javaindex c7006f9a4f..17c212513c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/BinaryReader.java@@ -43,13 +43,12 @@ public class BinaryReader {*/public final static int SIZEOF_LONG = 8;- private ByteProvider provider;+ private final ByteProvider provider;private DataConverter converter;private long currentIndex;/**- * Constructs a reader using the given- * file and endian-order.+ * Constructs a reader using the given ByteProvider and endian-order.** If isLittleEndian is true, then all values read* from the file will be done so assuming@@ -63,10 +62,22 @@ public class BinaryReader {* @param isLittleEndian the endian-order*/public BinaryReader(ByteProvider provider, boolean isLittleEndian) {- this.provider = provider;- setLittleEndian(isLittleEndian);+ this(provider, DataConverter.getInstance(!isLittleEndian), 0);}+ /**+ * Creates a BinaryReader instance.+ *+ * @param provider the ByteProvider to use+ * @param converter the {@link DataConverter} to use+ * @param initialIndex the initial offset+ */+ public BinaryReader(ByteProvider provider, DataConverter converter, long initialIndex) {+ this.provider = provider;+ this.converter = converter;+ this.currentIndex = initialIndex;+ }+/*** Returns a clone of this reader, with its own independent current position,* positioned at the new index.@@ -75,9 +86,7 @@ public class BinaryReader {* @return an independent clone of this reader positioned at the new index*/public BinaryReader clone(long newIndex) {- BinaryReader clone = new BinaryReader(provider, isLittleEndian());- clone.currentIndex = newIndex;- return clone;+ return new BinaryReader(provider, converter, newIndex);}/**@@ -93,31 +102,19 @@ public class BinaryReader {/*** Returns a BinaryReader that is in BigEndian mode.*- * @return either this same instance (if already BigEndian), or a new instance- * (at the same location) in BigEndian mode+ * @return a new independent BinaryReader, at the same position, in BigEndian mode*/public BinaryReader asBigEndian() {- if (isBigEndian()) {- return this;- }- BinaryReader result = clone(currentIndex);- result.setLittleEndian(false);- return result;+ return new BinaryReader(provider, BigEndianDataConverter.INSTANCE, currentIndex);}/*** Returns a BinaryReader that is in LittleEndian mode.*- * @return either this same instance (if already LittleEndian), or a new instance- * (at the same location) in LittleEndian mode+ * @return a new independent instance, at the same position, in LittleEndian mode*/public BinaryReader asLittleEndian() {- if (!isBigEndian()) {- return this;- }- BinaryReader result = clone(currentIndex);- result.setLittleEndian(true);- return result;+ return new BinaryReader(provider, LittleEndianDataConverter.INSTANCE, currentIndex);}/**@@ -196,11 +193,12 @@ public class BinaryReader {/////////////////////////////////////////////////////////////////////**- * A convenience method for setting the index using- * an integer.+ * A convenience method for setting the index using a 32 bit integer.+ *+ * @param index new index, treated as a 32 bit unsigned integer*/public void setPointerIndex(int index) {- this.currentIndex = index & Conv.INT_MASK;+ this.currentIndex = Integer.toUnsignedLong(index);}/**diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ExtentsByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ExtentsByteProvider.javaindex 4e72eda7c4..4c18e4651e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ExtentsByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/ExtentsByteProvider.java@@ -16,6 +16,7 @@package ghidra.app.util.bin;import java.io.*;+import java.util.Arrays;import java.util.Map.Entry;import java.util.TreeMap;@@ -25,7 +26,9 @@ import ghidra.formats.gfilesystem.FSRL;* A {@link ByteProvider} that is a concatenation of sub-ranges of another ByteProvider, also* allowing for non-initialized (sparse) regions.* <p>- * Not thread-safe when extents are being added.+ * Not thread-safe when extents are being added.+ * <p>+ * Does not assume ownership of wrapped ByteProvider.*/public class ExtentsByteProvider implements ByteProvider {@@ -45,7 +48,7 @@ public class ExtentsByteProvider implements ByteProvider {* Creates a new {@link ExtentsByteProvider}.** @param provider {@link ByteProvider} to wrap- * @param fsrl {@link FSRL} of the byte provider+ * @param fsrl {@link FSRL} of this new byte provider*/public ExtentsByteProvider(ByteProvider provider, FSRL fsrl) {this.delegate = provider;@@ -82,7 +85,7 @@ public class ExtentsByteProvider implements ByteProvider {@Overridepublic String getName() {- return null;+ return fsrl != null ? fsrl.getName() : null;}@Override@@ -92,7 +95,7 @@ public class ExtentsByteProvider implements ByteProvider {@Overridepublic String getAbsolutePath() {- return null;+ return fsrl != null ? fsrl.getPath() : null;}@Override@@ -107,7 +110,7 @@ public class ExtentsByteProvider implements ByteProvider {@Overridepublic void close() throws IOException {- delegate.close();+ // do not close wrapped delegate ByteProvider}@Override@@ -133,31 +136,60 @@ public class ExtentsByteProvider implements ByteProvider {int count = (int) longCount;byte[] result = new byte[count];- int bytesRead = 0;- while (bytesRead < count) {- long offsetToRead = index + bytesRead;- Entry<Long, Long> entry = offsetMap.floorEntry(offsetToRead);+ int bytesRead = readBytes(index, result, 0, count);+ if (bytesRead != count) {+ throw new IOException("Unable to read " + count + " bytes at " + index);+ }+ return result;+ }++ /**+ * Read bytes at the specified index into the given byte array.+ * <p>+ * See {@link InputStream#read(byte[], int, int)}.+ * <p>+ *+ * @param index file offset to start reading+ * @param buffer byte array that will receive the bytes+ * @param offset offset inside the byte array to place the bytes+ * @param len number of bytes to read+ * @return number of actual bytes read+ * @throws IOException if error+ */+ public int readBytes(long index, byte[] buffer, int offset, int len) throws IOException {+ ensureBounds(index, 0);+ len = (int) Math.min(length - index, len);+ int totalBytesRead = 0;+ int bufferDest = offset;+ long currentIndex = index;+ while (totalBytesRead < len) {+ Entry<Long, Long> entry = offsetMap.floorEntry(currentIndex);Entry<Long, Long> nextEntry = offsetMap.higherEntry(entry.getKey());long extentStart = entry.getKey();- long extentOffset = offsetToRead - extentStart;+ long extentOffset = currentIndex - extentStart;long extentEnd = (nextEntry != null) ? nextEntry.getKey() : length;long delegateExtentStart = entry.getValue();int bytesToRead =- (int) Math.min(count - bytesRead, extentEnd - extentStart - extentOffset);+ (int) Math.min(len - totalBytesRead, extentEnd - extentStart - extentOffset);if (delegateExtentStart != -1) {long delegateOffsetToRead = delegateExtentStart + extentOffset;+ // TODO: when ByteProvider interface has better readBytes() method, use it herebyte[] extentBytes = delegate.readBytes(delegateOffsetToRead, bytesToRead);- System.arraycopy(extentBytes, 0, result, bytesRead, bytesToRead);+ System.arraycopy(extentBytes, 0, buffer, bufferDest, bytesToRead);}else {// the extent was not present, result will be 0's+ Arrays.fill(buffer, bufferDest, bufferDest + bytesToRead,+ (byte) 0 /* fill value */);}- bytesRead += bytesToRead;+ totalBytesRead += bytesToRead;+ bufferDest += bytesToRead;+ currentIndex += bytesToRead;}- return result;+ return totalBytesRead;}-+@Overridepublic InputStream getInputStream(long index) throws IOException {return new ByteProviderInputStream(this, 0, length);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FSUtilities.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FSUtilities.javaindex a8871bd11d..e29902b1cc 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FSUtilities.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FSUtilities.java@@ -21,6 +21,7 @@ import java.net.MalformedURLException;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;import java.security.NoSuchAlgorithmException;+import java.text.SimpleDateFormat;import java.util.*;import java.util.Map.Entry;@@ -42,6 +43,7 @@ public class FSUtilities {public static final String SEPARATOR_CHARS = "/\\:";public static final String SEPARATOR = "/";private static final char DOT = '.';+ private static final TimeZone GMT = TimeZone.getTimeZone("GMT");public static class StreamCopyResult {public long bytesCopied;@@ -504,4 +506,32 @@ public class FSUtilities {public static String normalizeNativePath(String path) {return appendPath("/", FilenameUtils.separatorsToUnix(path));}++ /**+ * Common / unified date formatting for all file system information strings.+ *+ * @param d {@link Date} to format, or null+ * @return formatted date string, or "NA" if date was null+ */+ public static String formatFSTimestamp(Date d) {+ if (d == null) {+ return "NA";+ }+ SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");+ df.setTimeZone(GMT);+ return df.format(d);+ }++ /**+ * Common / unified size formatting for all file system information strings.+ *+ * @param length {@link Long} length, null ok+ * @return pretty'ish length format string, or "NA" if length was null+ */+ public static String formatSize(Long length) {+ return (length != null)+ ? String.format("%d (%s)", length, FileUtilities.formatLength(length))+ : "NA";+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.javaindex 42283008f4..21efefa456 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.java@@ -203,7 +203,7 @@ public class Ext4Analyzer extends FileFormatAnalyzer {Address address = toAddr(program, offset);if( isDirEntry2 ) {while( (reader.getPointerIndex() - offset) < (extent.getEe_len() * blockSize)) {- Ext4DirEntry2 dirEnt2 = new Ext4DirEntry2(reader);+ Ext4DirEntry2 dirEnt2 = Ext4DirEntry2.read(reader);DataType dataType = dirEnt2.toDataType();createData(program, address, dataType);address = address.add(dataType.getLength());diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Constants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Constants.javaindex bdf62ec74e..5cc250f475 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Constants.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Constants.java@@ -17,7 +17,8 @@ package ghidra.file.formats.ext4;public final class Ext4Constants {- public final static int SUPER_BLOCK_MAGIC = 0xEF53;+ public final static int SUPER_BLOCK_START = 0x400;+ public final static int SUPER_BLOCK_MAGIC = 0xEF53; // LE//Super Block Compatible Feature Flagspublic final static int COMPAT_DIR_PREALLOC = 0x1;@@ -152,4 +153,37 @@ public final class Ext4Constants {public final static byte EXT4_FT_MAX = 8;public final static byte EXT4_FT_DIR_CSUM = (byte) 0xDE;++ // ---------------------------------------------------------+ // index of special inodes that are statically assigned by convention++ public final static int EXT4_INODE_INDEX_NULL = 0;+ public final static int EXT4_INODE_INDEX_BADBLOCKS = 1; // this file holds info about bad blocks+ public final static int EXT4_INODE_INDEX_ROOTDIR = 2; // the root directory+ public final static int EXT4_INODE_INDEX_USERQUOTA = 3;+ public final static int EXT4_INODE_INDEX_GROUPQUOTA = 4;+ public final static int EXT4_INODE_INDEX_BOOTLOADER = 5;+ public final static int EXT4_INODE_INDEX_UNDELETEDIR = 6;+ public final static int EXT4_INODE_INDEX_RESERVED_GROUPDESCRIPTORS = 7;+ public final static int EXT4_INODE_INDEX_JOURNALINODE = 8;+ public final static int EXT4_INODE_INDEX_EXCLUDEINODE = 9;+ public final static int EXT4_INODE_INDEX_REPLICAINODE = 10;+ public final static int EXT4_INODE_INDEX_NORMAL_FIRSTUSED = 11; // typically the first non-reserved inode, "lost+found" dir++ // ---------------------------------------------------------+ //+ public final static int EXT4_XATTR_MAGIC = 0xEA020000;++ // prefixes inserted before the Ext4XattrEntry name value, looked up by Ext4XattrEntry.e_name_index+ public final static String[] EXT4_XATTR_NAMEINDEX_STRINGS = {+ "",+ "user.",+ "system.posix_acl_access.",+ "system.posix_acl_default",+ "trusted.",+ "lustre.", // guessing about this string+ "security.",+ "system.",+ "system.richacl"+ };}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry.javaindex a1ba54bd78..e722344480 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry.java@@ -15,41 +15,52 @@*/package ghidra.file.formats.ext4;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.bin.StructConverter;-import ghidra.program.model.data.ArrayDataType;-import ghidra.program.model.data.DataType;-import ghidra.program.model.data.Structure;-import ghidra.program.model.data.StructureDataType;+import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;-public class Ext4DirEntry implements StructConverter {+ protected static final int SIZEOF_FIXEDFIELDS = 8;- private int inode;- private short rec_len;- private short name_len;- private String name;- private byte[] extra;+ protected int inode;+ protected short rec_len;+ protected short name_len;+ protected String name;+ protected byte[] extra;- public Ext4DirEntry( ByteProvider provider ) throws IOException {- this( new BinaryReader( provider, true) );- }-- public Ext4DirEntry( BinaryReader reader ) throws IOException {- inode = reader.readNextInt();- rec_len = reader.readNextShort();- name_len = reader.readNextShort();- name = reader.readNextAsciiString(name_len);+ /**+ * Reads a Ext4DirEntry from the stream.+ *+ * @param reader BinaryReader to read from+ * @return new Ext4DirEntry, or null if eof+ * @throws IOException if error when reading+ */+ public static Ext4DirEntry read(BinaryReader reader) throws IOException {+ if (reader.getPointerIndex() + SIZEOF_FIXEDFIELDS >= reader.length()) {+ return null;+ }+ Ext4DirEntry result = new Ext4DirEntry();+ result.inode = reader.readNextInt();+ result.rec_len = reader.readNextShort();+ result.name_len = reader.readNextShort();+ result.name = new String(reader.readNextByteArray(result.name_len), StandardCharsets.UTF_8);- int extraSize = rec_len - (8 + name_len);+ int extraSize =+ Short.toUnsignedInt(result.rec_len) - (SIZEOF_FIXEDFIELDS + result.name_len);if( extraSize > 0 ) {- extra = reader.readNextByteArray(extraSize);+ result.extra = reader.readNextByteArray(extraSize);}+ return result;}+ protected Ext4DirEntry() {+ // empty+ }+public int getInode() {return inode;}@@ -70,6 +81,10 @@ public class Ext4DirEntry implements StructConverter {return extra;}+ public boolean isUnused() {+ return inode == Ext4Constants.EXT4_INODE_INDEX_NULL;+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {Structure structure = new StructureDataType("ext4_dir_entry", 0);diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry2.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry2.javaindex c5ea755efa..e82312ee41 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry2.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4DirEntry2.java@@ -15,67 +15,52 @@*/package ghidra.file.formats.ext4;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.bin.StructConverter;-import ghidra.program.model.data.ArrayDataType;-import ghidra.program.model.data.DataType;-import ghidra.program.model.data.Structure;-import ghidra.program.model.data.StructureDataType;+import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;--public class Ext4DirEntry2 implements StructConverter {+public class Ext4DirEntry2 extends Ext4DirEntry implements StructConverter {+ protected byte file_type;- private int inode;- private short rec_len;- private byte name_len;- private byte file_type;- private String name;- private byte[] extra;+ /**+ * Reads a Ext4DirEntry2 from the stream.+ *+ * @param reader BinaryReader to read from+ * @return new Ext4DirEntry2, or null if eof+ * @throws IOException if error when reading+ */+ public static Ext4DirEntry2 read(BinaryReader reader) throws IOException {+ if (reader.getPointerIndex() + 8 >= reader.length()) {+ return null;+ }+ Ext4DirEntry2 result = new Ext4DirEntry2();+ result.inode = reader.readNextInt();+ result.rec_len = reader.readNextShort();+ int uNameLen = reader.readNextUnsignedByte();+ result.name_len = (short) uNameLen; // direntry2's only have a byte for name_len+ result.file_type = reader.readNextByte();+ result.name = new String(reader.readNextByteArray(uNameLen), StandardCharsets.UTF_8);- public Ext4DirEntry2( ByteProvider provider ) throws IOException {- this( new BinaryReader( provider, true ) );- }-- public Ext4DirEntry2( BinaryReader reader ) throws IOException {- inode = reader.readNextInt( );- rec_len = reader.readNextShort( );- name_len = reader.readNextByte( );- file_type = reader.readNextByte( );- name = reader.readNextAsciiString( name_len & 0xff );-- int extraSize = ( rec_len & 0xffff ) - ( 8 + ( name_len & 0xff ) );- if ( extraSize > 0 ) {- extra = reader.readNextByteArray( extraSize );+ int extraSize = Short.toUnsignedInt(result.rec_len) - (SIZEOF_FIXEDFIELDS + uNameLen);+ if (extraSize > 0) {+ result.extra = reader.readNextByteArray(extraSize);}- }-- public int getInode() {- return inode;- }- public short getRec_len() {- return rec_len;+ return result;}- public byte getName_len() {- return name_len;+ private Ext4DirEntry2() {+ // nothing}public byte getFile_type() {return file_type;}- public String getName() {- return name;- }-- public byte[] getExtra() {- return extra;- }-@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {String nameEnd = rec_len + "_" + (extra == null ? "0" : extra.length );diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4File.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4File.javaindex 9590a99fa8..70244ba6e3 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4File.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4File.java@@ -17,40 +17,20 @@ package ghidra.file.formats.ext4;public class Ext4File {- private String name;- private Ext4Inode inode;+ private final String name;+ private final Ext4Inode inode;public Ext4File(String name, Ext4Inode inode) {this.name = name;this.inode = inode;}- public Ext4File(String name) {- this.name = name;- }-- public Ext4File(Ext4Inode inode) {- this.inode = inode;- }-- public Ext4File() {-- }-public String getName() {return name;}- public void setName(String name) {- this.name = name;- }-public Ext4Inode getInode() {return inode;}- public void setInode(Ext4Inode inode) {- this.inode = inode;- }-}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4FileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4FileSystem.javaindex 118a6318e3..795904a401 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4FileSystem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4FileSystem.java@@ -19,11 +19,13 @@ import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;+import java.util.BitSet;import java.util.List;import ghidra.app.util.bin.*;import ghidra.formats.gfilesystem.*;import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.util.Msg;import ghidra.util.NumericUtilities;import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;@@ -50,8 +52,7 @@ public class Ext4FileSystem implements GFileSystem {public void mountFS(TaskMonitor monitor) throws IOException, CancelledException {BinaryReader reader = new BinaryReader(provider, true);- reader.setPointerIndex(0x400);-+ reader.setPointerIndex(Ext4Constants.SUPER_BLOCK_START);this.superBlock = new Ext4SuperBlock(reader);this.volumeName = superBlock.getVolumeName();this.uuid = NumericUtilities.convertBytesToString(superBlock.getS_uuid());@@ -69,62 +70,46 @@ public class Ext4FileSystem implements GFileSystem {numGroups++;}- boolean is64Bit =- (superBlock.getS_desc_size() > 32) && ((superBlock.getS_feature_incompat() & 0x80) > 0);-int groupDescriptorOffset = blockSize;reader.setPointerIndex(groupDescriptorOffset);+ monitor.initialize(numGroups);+ monitor.setMessage("Reading inode tables");Ext4GroupDescriptor[] groupDescriptors = new Ext4GroupDescriptor[numGroups];for (int i = 0; i < numGroups; i++) {monitor.checkCanceled();- groupDescriptors[i] = new Ext4GroupDescriptor(reader, is64Bit);+ groupDescriptors[i] = new Ext4GroupDescriptor(reader, superBlock.is64Bit());monitor.incrementProgress(1);}Ext4Inode[] inodes = getInodes(reader, groupDescriptors, monitor);- int s_inodes_count = superBlock.getS_inodes_count();- for (int i = 0; i < s_inodes_count; i++) {- Ext4Inode inode = inodes[i];- if (inode == null) {- continue;- }- if ((inode.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFDIR) {- processDirectory(reader, inodes, i, null, null, monitor);- }- else if ((inode.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFREG) {- // TODO: handle files if needed here- }+ // process entries in root directory+ Ext4Inode rootDirInode = inodes[Ext4Constants.EXT4_INODE_INDEX_ROOTDIR];+ if (!rootDirInode.isDir()) {+ throw new IOException("Unable to find root directory inode");}+ int usedInodeCount = superBlock.getS_inodes_count() - superBlock.getS_free_inodes_count();+ monitor.setMessage("Indexing files");+ monitor.initialize(usedInodeCount);++ BitSet processedInodes = new BitSet(inodes.length);+ processDirectory(inodes[Ext4Constants.EXT4_INODE_INDEX_ROOTDIR], fsih.getRootDir(), inodes,+ processedInodes, monitor);+ checkUnprocessedInodes(inodes, processedInodes);}- private void processDirectory(BinaryReader reader, Ext4Inode[] inodes, int index, String name,- GFile parent, TaskMonitor monitor) throws IOException, CancelledException {-- if (name != null && (name.equals(".") || name.equals(".."))) {- return;- }- Ext4Inode inode = inodes[index];- if (name == null && parent == null) {- parent = fsih.getRootDir();- }- else {- if (parent == null) {- parent = fsih.getRootDir();+ private void checkUnprocessedInodes(Ext4Inode[] inodes, BitSet processedInodes) {+ int count = 0;+ for (int inodeNum = processedInodes+ .nextClearBit(superBlock.getS_first_ino()); inodeNum < inodes.length; inodeNum =+ processedInodes.nextClearBit(inodeNum + 1)) {+ if (!inodes[inodeNum].isUnused()) {+ count++;}- parent = fsih.storeFileWithParent(name, parent, -1, true, inode.getSize(),- new Ext4File(name, inode));}- if ((inode.getI_flags() & Ext4Constants.EXT4_EXTENTS_FL) == 0) {- return;+ if (count > 0) {+ Msg.warn(this, "Unprocessed inodes: " + count);}- boolean isDirEntry2 =- (superBlock.getS_feature_incompat() & Ext4Constants.INCOMPAT_FILETYPE) != 0;- Ext4IBlock i_block = inode.getI_block();- processDirectoryIBlock(reader, inodes, parent, isDirEntry2, i_block, monitor);-- // null out directories that have already been processed- inodes[index] = null;}interface Checked2Consumer<T, E1 extends Throwable, E2 extends Throwable> {@@ -162,97 +147,63 @@ public class Ext4FileSystem implements GFileSystem {}}- private void processDirectoryIBlock(BinaryReader reader, Ext4Inode[] inodes, GFile parent,- boolean isDirEntry2, Ext4IBlock i_block, TaskMonitor monitor)- throws CancelledException, IOException {- forEachExtentEntry(i_block, extent -> {- long offset = extent.getExtentStartBlockNumber() * blockSize;- reader.setPointerIndex(offset);- if (isDirEntry2) {- processDirEntry2(reader, inodes, parent, monitor, extent, offset);- }- else {- processDirEntry(reader, inodes, parent, monitor, extent, offset);- }- }, monitor);- }-- private void processDirEntry(BinaryReader reader, Ext4Inode[] inodes, GFile parent,- TaskMonitor monitor, Ext4Extent extent, long offset)- throws CancelledException, IOException {-- while ((reader.getPointerIndex() - offset) < ((long) extent.getEe_len() * blockSize)) {- monitor.checkCanceled();- if (reader.peekNextInt() == 0) {- return;- }- Ext4DirEntry dirEnt = new Ext4DirEntry(reader);- int childIndex = dirEnt.getInode();- Ext4Inode child = inodes[childIndex];- if ((child.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFDIR) {- String childName = dirEnt.getName();- long readerOffset = reader.getPointerIndex();- processDirectory(reader, inodes, childIndex, childName, parent, monitor);- reader.setPointerIndex(readerOffset);- }- else if ((child.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFREG ||- (child.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFLNK) {- storeFile(inodes, dirEnt, parent);- }- else {- throw new IOException("Inode " + dirEnt.getInode() + " has unhandled file type: " +- (child.getI_mode() & 0xF000));- }+ private void processDirectory(Ext4Inode inode, GFile dirFile, Ext4Inode[] inodes,+ BitSet processedInodes, TaskMonitor monitor) throws IOException, CancelledException {+ try (ByteProvider bp = getInodeByteProvider(inode, dirFile.getFSRL(), monitor)) {+ processDirectoryStream(bp, dirFile, inodes, processedInodes, monitor);}}- private void processDirEntry2(BinaryReader reader, Ext4Inode[] inodes, GFile parent,- TaskMonitor monitor, Ext4Extent extent, long offset)+ private void processDirectoryStream(ByteProvider directoryStream, GFile dirGFile,+ Ext4Inode[] inodes, BitSet processedInodes, TaskMonitor monitor)throws CancelledException, IOException {-- while ((reader.getPointerIndex() - offset) < ((long) extent.getEe_len() * blockSize)) {+ boolean isdir2 = superBlock.isDirEntry2();+ BinaryReader reader = new BinaryReader(directoryStream, true /* LE */);+ Ext4DirEntry dirEnt;+ while ((dirEnt = isdir2 ? Ext4DirEntry2.read(reader) : Ext4DirEntry.read(reader)) != null) {monitor.checkCanceled();- if (reader.peekNextInt() == 0) {- return;- }- Ext4DirEntry2 dirEnt2 = new Ext4DirEntry2(reader);- if (dirEnt2.getFile_type() == Ext4Constants.FILE_TYPE_DIRECTORY) {- int childInode = dirEnt2.getInode();- String childName = dirEnt2.getName();- long readerOffset = reader.getPointerIndex();- processDirectory(reader, inodes, childInode, childName, parent, monitor);- reader.setPointerIndex(readerOffset);- }- else if (dirEnt2.getFile_type() == Ext4Constants.FILE_TYPE_REGULAR_FILE ||- dirEnt2.getFile_type() == Ext4Constants.FILE_TYPE_SYMBOLIC_LINK) {- storeFile(inodes, dirEnt2, parent);- }- else {- throw new IOException("Inode " + dirEnt2.getInode() + " has unhandled file type: " +- dirEnt2.getFile_type());+ if (dirEnt.isUnused()) {+ continue;}+ processDirEntry(dirEnt, dirGFile, inodes, processedInodes, monitor);+ monitor.incrementProgress(1);}}- private void storeFile(Ext4Inode[] inodes, Ext4DirEntry dirEnt, GFile parent) {- int fileInodeNum = dirEnt.getInode();- Ext4Inode fileInode = inodes[fileInodeNum];- fsih.storeFileWithParent(dirEnt.getName(), parent, -1,- (fileInode.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFDIR,- fileInode.getSize(), new Ext4File(dirEnt.getName(), fileInode));- inodes[fileInodeNum] = null;- }+ private void processDirEntry(Ext4DirEntry dirEntry, GFile parentDir, Ext4Inode[] inodes,+ BitSet processedInodes, TaskMonitor monitor) throws IOException, CancelledException {+ int inodeNumber = dirEntry.getInode();+ if (inodeNumber <= 0 || inodeNumber >= inodes.length) {+ Msg.warn(this, "Invalid inode number: " + inodeNumber);+ return;+ }+ Ext4Inode inode = inodes[inodeNumber];+ if (inode == null || inode.isUnused()) {+ Msg.warn(this, "Reference to bad inode: " + inodeNumber);+ return;+ }+ if (!(inode.isDir() || inode.isFile() || inode.isSymLink())) {+ throw new IOException("Inode " + inode + " has unhandled file type: " ++ Integer.toHexString(inode.getFileType()));+ }+ String name = dirEntry.getName();+ if (".".equals(name) || "..".equals(name)) {+ // skip the ".", and ".." self-reference directories+ return;+ }- private void storeFile(Ext4Inode[] inodes, Ext4DirEntry2 dirEnt2, GFile parent) {- int fileInodeNum = dirEnt2.getInode();- Ext4Inode fileInode = inodes[fileInodeNum];- if (fileInode == null) {- return;//TODO+ GFile gfile = fsih.storeFileWithParent(name, parentDir, -1, inode.isDir(), inode.getSize(),+ new Ext4File(name, inode));+ if (processedInodes.get(inodeNumber)) {+ // this inode was already seen and handled earlier. adding a second filename to the fsih is+ // okay, but don't try to process as a directory, which shouldn't normally be possible+ // anyway.+ return;+ }+ processedInodes.set(inodeNumber);+ if (inode.isDir()) {+ processDirectory(inode, gfile, inodes, processedInodes, monitor);}- fsih.storeFileWithParent(dirEnt2.getName(), parent, -1,- dirEnt2.getFile_type() == Ext4Constants.FILE_TYPE_DIRECTORY, fileInode.getSize(),- new Ext4File(dirEnt2.getName(), fileInode));- inodes[fileInodeNum] = null;}@Override@@ -273,15 +224,16 @@ public class Ext4FileSystem implements GFileSystem {}Ext4Inode inode = ext4File.getInode();String info = "";- long size = inode.getSize();- if ((inode.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFLNK) {- Ext4IBlock block = inode.getI_block();- byte[] extra = block.getExtra();- info = "Symlink to \"" + new String(extra).trim() + "\"\n";- }- else {- info = "File size: 0x" + Long.toHexString(size);+ if (inode.isSymLink()) {+ try {+ info += "Symlink to \"" + readLink(file, ext4File, monitor) + "\"\n";+ }+ catch (IOException e) {+ // ignore+ }}+ long size = inode.getSize();+ info += "File size: " + FSUtilities.formatSize(size) + "\n";return info;}@@ -294,34 +246,51 @@ public class Ext4FileSystem implements GFileSystem {private static final int MAX_SYMLINK_LOOKUP_COUNT = 100;- private Ext4Inode resolveSymLink(GFile file) throws IOException {+ private Ext4Inode resolveSymLink(GFile file, TaskMonitor monitor) throws IOException {int lookupCount = 0;- while (file != null && lookupCount < MAX_SYMLINK_LOOKUP_COUNT) {- Ext4File extFile = fsih.getMetadata(file);+ GFile currentFile = file;+ StringBuilder symlinkDebugPath = new StringBuilder();+ while (true) {+ if (lookupCount++ > MAX_SYMLINK_LOOKUP_COUNT) {+ throw new IOException(+ "Symlink too long: " + file.getPath() + ", " + symlinkDebugPath);+ }+ Ext4File extFile = fsih.getMetadata(currentFile);+ if (extFile == null) {+ throw new IOException("Missing Ext4 metadata for " + currentFile.getPath());+ }Ext4Inode inode = extFile.getInode();- if ((inode.getI_mode() & Ext4Constants.I_MODE_MASK) != Ext4Constants.S_IFLNK) {+ if (!inode.isSymLink()) {return inode;}-- Ext4IBlock block = inode.getI_block();- byte[] extra = block.getExtra();-- String symlinkDestPath = new String(extra).trim();++ String symlinkDestPath = readLink(file, extFile, monitor);+ symlinkDebugPath.append(" -> ").append(symlinkDestPath);if (!symlinkDestPath.startsWith("/")) {- if (file.getParentFile() == null) {- throw new IOException("Not parent file for " + file);+ if (currentFile.getParentFile() == null) {+ throw new IOException("No parent file for " + currentFile);}symlinkDestPath =- FSUtilities.appendPath(file.getParentFile().getPath(), symlinkDestPath);+ FSUtilities.appendPath(currentFile.getParentFile().getPath(),+ symlinkDestPath);+ }++ currentFile = lookup(symlinkDestPath);+ if (currentFile == null) {+ throw new IOException("Missing symlink dest: " + file.getPath() ++ ", broken symlink: " + symlinkDebugPath);}+ }+ }- file = lookup(symlinkDestPath);- lookupCount++;+ private String readLink(GFile file, Ext4File extFile, TaskMonitor monitor) throws IOException {+ try (ByteProvider bp = getInodeByteProvider(extFile.getInode(), file.getFSRL(), monitor)) {+ byte[] tmp = bp.readBytes(0, bp.length());+ return new String(tmp, StandardCharsets.UTF_8);}- return null;}- private Ext4Inode getInodeFor(GFile file) throws IOException {+ private Ext4Inode getInodeFor(GFile file, TaskMonitor monitor) throws IOException {Ext4File extFile = fsih.getMetadata(file);if (extFile == null) {return null;@@ -331,11 +300,8 @@ public class Ext4FileSystem implements GFileSystem {return null;}- if ((inode.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFLNK) {- inode = resolveSymLink(file);- if (inode == null) {- throw new IOException(extFile.getName() + " is a broken symlink.");- }+ if (inode.isSymLink()) {+ inode = resolveSymLink(file, monitor);}return inode;}@@ -350,23 +316,42 @@ public class Ext4FileSystem implements GFileSystem {* @throws IOException if error*/public ByteProvider getByteProvider(GFile file, TaskMonitor monitor) throws IOException {- Ext4Inode inode = getInodeFor(file);+ Ext4Inode inode = getInodeFor(file, monitor);if (inode == null) {return null;}- if ((inode.getI_mode() & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFDIR) {+ if (inode.isDir()) {throw new IOException(file.getName() + " is a directory.");}- boolean usesExtents = (inode.getI_flags() & Ext4Constants.EXT4_EXTENTS_FL) != 0;- if (!usesExtents) {- throw new IOException("Unsupported file storage: not EXT4_EXTENTS: " + file.getPath());+ return getInodeByteProvider(inode, file.getFSRL(), monitor);+ }++ private ByteProvider getInodeByteProvider(Ext4Inode inode, FSRL inodeFSRL, TaskMonitor monitor)+ throws IOException {+ if (inode.isFlagExtents()) {+ return getExtentsByteProvider(inodeFSRL, inode, monitor);+ }+ else if (inode.isFlagInlineData() || inode.isSymLink()) {+ return getInlineDataProvider(inodeFSRL, inode, monitor);+ }+ else {+ throw new IOException("Unsupported file storage: " + inodeFSRL.getPath());}+ }++ private ByteProvider getInlineDataProvider(FSRL fileFSRL, Ext4Inode inode, TaskMonitor monitor)+ throws IOException {+ byte[] data = inode.getInlineDataValue();+ return new ByteArrayProvider(data, fileFSRL);+ }+ private ByteProvider getExtentsByteProvider(FSRL fileFSRL, Ext4Inode inode, TaskMonitor monitor)+ throws IOException {try {long fileSize = inode.getSize();- ExtentsByteProvider result = new ExtentsByteProvider(provider, file.getFSRL());+ ExtentsByteProvider result = new ExtentsByteProvider(provider, fileFSRL);Ext4IBlock i_block = inode.getI_block();forEachExtentEntry(i_block, extent -> {@@ -392,6 +377,7 @@ public class Ext4FileSystem implements GFileSystem {catch (CancelledException e) {throw new IOException(e);}+}private Ext4Inode[] getInodes(BinaryReader reader, Ext4GroupDescriptor[] groupDescriptors,@@ -409,17 +395,16 @@ public class Ext4FileSystem implements GFileSystem {reader.setPointerIndex(offset);monitor.setMessage("Reading inode table " + i + " of " + (groupDescriptors.length - 1) + "...");- monitor.setMaximum(inodesPerGroup);- monitor.setProgress(0);+ monitor.initialize(inodesPerGroup);for (int j = 0; j < inodesPerGroup; j++) {monitor.checkCanceled();monitor.incrementProgress(1);- Ext4Inode inode = new Ext4Inode(reader);+ Ext4Inode inode = new Ext4Inode(reader, superBlock.getS_inode_size());offset = offset + superBlock.getS_inode_size();reader.setPointerIndex(offset);- inodes[inodeIndex++] = inode; //inodes[ inodesPerGroup * i + j ] = inode;+ inodes[inodeIndex++] = inode;}}return inodes;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4IBlock.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4IBlock.javaindex 9c33f95947..a729ce4f47 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4IBlock.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4IBlock.java@@ -15,18 +15,13 @@*/package ghidra.file.formats.ext4;-import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.ByteProvider;-import ghidra.app.util.bin.StructConverter;-import ghidra.program.model.data.ArrayDataType;-import ghidra.program.model.data.DataType;-import ghidra.program.model.data.Structure;-import ghidra.program.model.data.StructureDataType;-import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;import java.util.*;+import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;+public class Ext4IBlock implements StructConverter {private Ext4ExtentHeader header;@@ -58,32 +53,33 @@ public class Ext4IBlock implements StructConverter {public Ext4IBlock(BinaryReader reader, boolean isExtentTree) throws IOException {this.isExtentTree = isExtentTree;int count = 0;- if( isExtentTree ) {+ if (isExtentTree) {header = new Ext4ExtentHeader(reader);count++;short numEntries = header.getEh_entries();- if( header.getEh_depth() > 0 ) {+ boolean isIdxEntries = header.getEh_depth() > 0;+ if (isIdxEntries) {indexEntries = new ArrayList<>();- for( int i = 0; i < numEntries; i++ ) {- indexEntries.add( new Ext4ExtentIdx(reader) );- count++;- }}else {extentEntries = new ArrayList<>();- for( int i = 0; i < numEntries; i++ ) {- extentEntries.add( new Ext4Extent(reader) );- count++;+ }+ for (int i = 0; i < numEntries; i++, count++) {+ if (isIdxEntries) {+ indexEntries.add(new Ext4ExtentIdx(reader));+ }+ else {+ extentEntries.add(new Ext4Extent(reader));}}}-+int extraBytes = 60 - (count * 12);- if ( extraBytes > 0 ) {+ if (extraBytes > 0) {extra = reader.readNextByteArray(extraBytes);}else {- extra = new byte[ 0 ];+ extra = new byte[0];}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Inode.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Inode.javaindex 494b5f9449..071dd1241e 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Inode.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Inode.java@@ -17,45 +17,59 @@ package ghidra.file.formats.ext4;import java.io.IOException;-import ghidra.app.util.bin.*;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;public class Ext4Inode implements StructConverter {-- private short i_mode;- private short i_uid;- private int i_size_lo;- private int i_atime;- private int i_ctime;- private int i_mtime;- private int i_dtime;- private short i_gid;- private short i_links_count;- private int i_blocks_lo;- private int i_flags;- private int i_osd1;- private Ext4IBlock i_block; //15 ints long- private int i_generation;- private int i_file_acl_lo;- private int i_size_high;- private int i_obso_faddr;- private byte[] i_osd2; //12 bytes long- private short i_extra_isize;- private short i_checksum_hi;- private int i_ctime_extra;- private int i_mtime_extra;- private int i_atime_extra;- private int i_crtime;- private int i_crtime_extra;- private int i_version_hi;- private int i_projid;-- public Ext4Inode( ByteProvider provider ) throws IOException {- this( new BinaryReader( provider, true ) );+ private static final int INODE_BASE_SIZE = 128; // by definition+ private static final int MINIMAL_SIZEOF_INODE = 0xa0; // sizeof the fields we try to read++ //@formatter:off+ // Offset (hex) Length Comment+ private short i_mode; // 0 2 see Ext4Constants.S_IXOTH...S_IFSOCK+ private short i_uid; // 2 2+ private int i_size_lo; // 4 4+ private int i_atime; // 8 4+ private int i_ctime; // C 4+ private int i_mtime; // 10 4+ private int i_dtime; // 14 4+ private short i_gid; // 18 2+ private short i_links_count; // 1A 2+ private int i_blocks_lo; // 1C 4+ private int i_flags; // 20 4 see Ext4Constants.EXT4_SECRM_FL...EXT4_RESERVED_FL+ private int i_osd1; // 24 4+ private Ext4IBlock i_block; // 28 60+ private int i_generation; // 64 4+ private int i_file_acl_lo; // 68 4+ private int i_size_high; // 6C 4+ private int i_obso_faddr; // 70 4+ private byte[] i_osd2; // 74 12 last of the base fields, everything after is counted in i_extra_isize+ private short i_extra_isize; // 80 2 number of bytes to the end of the defined fields+ private short i_checksum_hi; // 82 2+ private int i_ctime_extra; // 84 4+ private int i_mtime_extra; // 88 4+ private int i_atime_extra; // 8C 4+ private int i_crtime; // 90 4+ private int i_crtime_extra; // 94 4+ private int i_version_hi; // 98 4+ private int i_projid; // 9C 4+ //unknown_fields // A0 i_extra_isize-32+ //extended_attributes // 80+i_extra_size, inodeSize-0x80-i_extra_isize+ //@formatter:on++ private Ext4Xattributes xAttributes;++ public Ext4Inode(BinaryReader reader) throws IOException {+ this(reader, MINIMAL_SIZEOF_INODE);}- public Ext4Inode( BinaryReader reader ) throws IOException {+ public Ext4Inode(BinaryReader reader, int inodeSize) throws IOException {+ if (inodeSize < MINIMAL_SIZEOF_INODE) {+ throw new IOException("Bad inodeSize: " + inodeSize);+ }+ long inodeStart = reader.getPointerIndex();i_mode = reader.readNextShort();i_uid = reader.readNextShort();i_size_lo = reader.readNextInt();@@ -68,7 +82,7 @@ public class Ext4Inode implements StructConverter {i_blocks_lo = reader.readNextInt();i_flags = reader.readNextInt();i_osd1 = reader.readNextInt();- i_block = new Ext4IBlock(reader, (i_flags & 0x80000) != 0 );+ i_block = new Ext4IBlock(reader, isFlagExtents());i_generation = reader.readNextInt();i_file_acl_lo = reader.readNextInt();i_size_high = reader.readNextInt();@@ -83,6 +97,12 @@ public class Ext4Inode implements StructConverter {i_crtime_extra = reader.readNextInt();i_version_hi = reader.readNextInt();i_projid = reader.readNextInt();++ // skipping unknown fields here++ // read EAs if present+ reader.setPointerIndex(inodeStart + INODE_BASE_SIZE + i_extra_isize);+ xAttributes = Ext4Xattributes.readInodeXAttributes(reader, inodeStart + inodeSize);}@@ -203,6 +223,77 @@ public class Ext4Inode implements StructConverter {return Integer.toUnsignedLong(i_size_high) << 32 | Integer.toUnsignedLong(i_size_lo);}+ /**+ * Returns true if the inode appears to be unused.+ *+ * @return boolean true if the inode appears to be unused+ */+ public boolean isUnused() {+ return i_links_count == 0;+ }++ public boolean isSymLink() {+ return (i_mode & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFLNK;+ }++ public boolean isFile() {+ return (i_mode & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFREG;+ }++ public boolean isDir() {+ return (i_mode & Ext4Constants.I_MODE_MASK) == Ext4Constants.S_IFDIR;+ }++ public int getFileType() {+ return i_mode & Ext4Constants.I_MODE_MASK;+ }++ public boolean isFlagExtents() {+ return (i_flags & Ext4Constants.EXT4_EXTENTS_FL) != 0;+ }++ public boolean isFlagInlineData() {+ return (i_flags & Ext4Constants.EXT4_INLINE_DATA_FL) != 0;+ }++ /**+ * Returns the bytes in this inode's iblock.extra and the system.data+ * extended attribute.+ *+ * @return bytes of this file that were stored inline in the inode+ * @throws IOException if not able to assemble enough bytes to match+ * the file size+ */+ public byte[] getInlineDataValue() throws IOException {+ int bytesRemaining = (int) getSize();+ byte[] result = new byte[bytesRemaining];+ byte[] iblockExtra = i_block.getExtra();+ byte[] eaSystemData = getEAValue("system.data");+ if (eaSystemData == null) {+ eaSystemData = new byte[0];+ }+ int bytesCopied = 0;+ int copyLen = Math.min(bytesRemaining, iblockExtra.length);+ System.arraycopy(i_block.getExtra(), 0, result, 0, copyLen);+ bytesCopied += copyLen;+ bytesRemaining -= copyLen;+ if (bytesRemaining > 0) {+ copyLen = Math.min(bytesRemaining, eaSystemData.length);+ System.arraycopy(eaSystemData, 0, result, bytesCopied, copyLen);+ bytesCopied += copyLen;+ bytesRemaining -= copyLen;+ }+ if (bytesRemaining != 0) {+ throw new IOException("Unable to read inline data");+ }+ return result;+ }++ byte[] getEAValue(String name) {+ Ext4XattrEntry attr = (xAttributes != null) ? xAttributes.getAttribute(name) : null;+ return attr != null ? attr.getValue() : null;+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {DataType iBlockDataType = i_block.toDataType();diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4SuperBlock.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4SuperBlock.javaindex cb20ba2544..39c9e11f72 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4SuperBlock.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4SuperBlock.java@@ -598,6 +598,22 @@ public class Ext4SuperBlock implements StructConverter {return s_checksum;}+ public boolean isValid() {+ return Short.toUnsignedInt(s_magic) == Ext4Constants.SUPER_BLOCK_MAGIC;+ }++ public boolean is64Bit() {+ return (s_desc_size > 32) && ((s_feature_incompat & Ext4Constants.INCOMPAT_64BIT) != 0);+ }++ public boolean isInlineData() {+ return (s_feature_incompat & Ext4Constants.INCOMPAT_INLINE_DATA) != 0;+ }++ public boolean isDirEntry2() {+ return (s_feature_incompat & Ext4Constants.INCOMPAT_FILETYPE) != 0;+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {Structure structure = new StructureDataType("ext4_super_block", 0);diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrEntry.javaindex 3d6263c2d0..e066c690aa 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrEntry.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrEntry.java@@ -15,16 +15,12 @@*/package ghidra.file.formats.ext4;-import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.ByteProvider;-import ghidra.app.util.bin.StructConverter;-import ghidra.program.model.data.ArrayDataType;-import ghidra.program.model.data.DataType;-import ghidra.program.model.data.Structure;-import ghidra.program.model.data.StructureDataType;-import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;+import java.nio.charset.StandardCharsets;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;public class Ext4XattrEntry implements StructConverter {@@ -36,6 +32,8 @@ public class Ext4XattrEntry implements StructConverter {private int e_hash;private byte[] e_name;+ private byte[] value; // calculated value supplied by external logic+public Ext4XattrEntry(ByteProvider provider) throws IOException {this( new BinaryReader( provider, true ) );}@@ -78,6 +76,38 @@ public class Ext4XattrEntry implements StructConverter {return e_name;}+ public boolean isEndOfListMarker() {+ return e_name_len == 0 && e_name_index == 0 && e_value_offs == 0 && e_value_block == 0;+ }++ public boolean isValid() {+ return 0 <= e_name_index &&+ e_name_index < Ext4Constants.EXT4_XATTR_NAMEINDEX_STRINGS.length;+ }++ public String getName() {+ return Ext4Constants.EXT4_XATTR_NAMEINDEX_STRINGS[e_name_index] ++ new String(e_name, StandardCharsets.UTF_8);+ }++ /**+ * Returns the value of this external attribute entry+ *+ * @return value of this external attribute entry+ */+ public byte[] getValue() {+ return value;+ }++ /**+ * Sets the value of this external attribute entry+ *+ * @param value byte[] array+ */+ public void setValue(byte[] value) {+ this.value = value;+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {Structure structure = new StructureDataType("ext4_xattr_entry", 0);diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrIbodyHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrIbodyHeader.javaindex 4d34052b09..45d62db875 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrIbodyHeader.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4XattrIbodyHeader.java@@ -15,17 +15,14 @@*/package ghidra.file.formats.ext4;-import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.ByteProvider;-import ghidra.app.util.bin.StructConverter;-import ghidra.program.model.data.DataType;-import ghidra.program.model.data.Structure;-import ghidra.program.model.data.StructureDataType;-import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;+import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;+public class Ext4XattrIbodyHeader implements StructConverter {+ static final int SIZEOF = 4;private int h_magic;@@ -50,4 +47,8 @@ public class Ext4XattrIbodyHeader implements StructConverter {return structure;}+ public boolean isValid() {+ return h_magic == Ext4Constants.EXT4_XATTR_MAGIC;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Xattributes.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Xattributes.javanew file mode 100644index 0000000000..093f66a9b1--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Xattributes.java@@ -0,0 +1,80 @@+/* ###+ * 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.ext4;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.util.Msg;++/**+ * Container of parsed Ext4 extended attribute entries+ */+public class Ext4Xattributes {+ /**+ * Parses extended attributes found at the end of an Inode.+ *+ * @param reader {@link BinaryReader} positioned at the end of the used inode fields+ * @param endOfInode file position of the end of inode+ * @return new {@link Ext4Xattributes} instance, or null if not present+ * @throws IOException if error when reading+ */+ public static Ext4Xattributes readInodeXAttributes(BinaryReader reader, long endOfInode)+ throws IOException {+ if (reader.getPointerIndex() + Ext4XattrIbodyHeader.SIZEOF >= endOfInode) {+ return null;+ }+ Ext4XattrIbodyHeader eaHeader = new Ext4XattrIbodyHeader(reader);+ if (!eaHeader.isValid()) {+ return null;+ }+ long eaEntriesStart = reader.getPointerIndex();+ List<Ext4XattrEntry> eaEntries = new ArrayList<>();+ while (reader.getPointerIndex() < endOfInode) {+ Ext4XattrEntry eaEntry = new Ext4XattrEntry(reader);+ if (eaEntry.isEndOfListMarker()) {+ break;+ }+ if (!eaEntry.isValid()) {+ Msg.debug(Ext4Xattributes.class, "Bad Ext4XattrEntry: " + reader.getPointerIndex());+ break;+ }+ if (eaEntry.getE_value_offs() > 0 && eaEntry.getE_value_size() > 0) {+ eaEntry.setValue(reader.readByteArray(eaEntriesStart + eaEntry.getE_value_offs(),+ eaEntry.getE_value_size()));+ }+ eaEntries.add(eaEntry);+ }+ return new Ext4Xattributes(eaEntries);+ }++ private List<Ext4XattrEntry> eaEntries;++ private Ext4Xattributes(List<Ext4XattrEntry> eaEntries) {+ this.eaEntries = eaEntries;+ }++ public Ext4XattrEntry getAttribute(String attributeName) {+ for (Ext4XattrEntry eaEntry : eaEntries) {+ if (eaEntry.getName().equals(attributeName)) {+ return eaEntry;+ }+ }+ return null;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.javaindex 663aecff16..9ecabc45f2 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.java@@ -344,7 +344,7 @@ public class NewExt4Analyzer extends FileFormatAnalyzer {Address address = toAddr( program, offset );if ( isDirEntry2 ) {while ( ( reader.getPointerIndex( ) - offset ) < ( extent.getEe_len( ) * blockSize ) ) {- Ext4DirEntry2 dirEnt2 = new Ext4DirEntry2( reader );+ Ext4DirEntry2 dirEnt2 = Ext4DirEntry2.read(reader);DataType dataType = dirEnt2.toDataType( );createData( program, address, dataType );String comment = "Name: " + dirEnt2.getName( ) + "\n";