Ghidra is a software reverse engineering (SRE) framework
GP-804: Added support for Android formats (ART, OAT, ODEX, DEX, CDEX, VDEX) and Dalvik VM SLEIGH modules for each major Android release up to 11.x (R)
GhidraKnightac5d2cfadaff
diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.javaindex 988726d24c..e999a606d3 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.java@@ -23,6 +23,7 @@ import ghidra.app.util.Option;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.dex.DexHeaderFactory;import ghidra.file.formats.android.dex.format.*;import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.address.Address;@@ -46,7 +47,7 @@ public class DexLoader extends AbstractLibrarySupportLoader {BinaryReader reader = new BinaryReader(provider, true);try {- DexHeader header = new DexHeader(reader);+ DexHeader header = DexHeaderFactory.getDexHeader(reader);if (DexConstants.DEX_MAGIC_BASE.equals(new String(header.getMagic()))) {List<QueryResult> queries =QueryOpinionService.query(getName(), DexConstants.MACHINE, null);@@ -80,7 +81,7 @@ public class DexLoader extends AbstractLibrarySupportLoader {}BinaryReader reader = new BinaryReader( provider, true );- DexHeader header = new DexHeader( reader );+ DexHeader header = DexHeaderFactory.getDexHeader( reader );monitor.setMessage( "DEX Loader: creating method byte code" );diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/apex/ApexContants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/apex/ApexContants.javanew file mode 100644index 0000000000..2971213f20--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/apex/ApexContants.java@@ -0,0 +1,27 @@+/* ###+ * 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.android.apex;++/**+ * Android Pony EXpress (ApexContants)+ *+ * https://source.android.com/devices/tech/ota/apex+ *+ * https://android.googlesource.com/platform/system/apex/+/refs/heads/master/apexd/apex_constants.h+ */+public class ApexContants {++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtAnalyzer.javanew file mode 100644index 0000000000..1ecfb7a5ec--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtAnalyzer.java@@ -0,0 +1,102 @@+/* ###+ * 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.android.art;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.app.util.opinion.BinaryLoader;+import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.file.formats.android.oat.OatConstants;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSetView;+import ghidra.program.model.data.DataType;+import ghidra.program.model.listing.Program;+import ghidra.util.task.TaskMonitor;++public class ArtAnalyzer extends FileFormatAnalyzer {++ @Override+ public String getName() {+ return "Android ART Header Format";+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return true;+ }++ @Override+ public String getDescription() {+ return "Analyzes the Android ART information in this program.";+ }++ @Override+ public boolean canAnalyze(Program program) {+ return ArtConstants.isART(program)+ //HACK:+ //Make analyzer appear after ART is merged with OAT program+ //Currently, analyzers will not recognize the new ART block being added+ || OatConstants.isOAT(program);+ }++ @Override+ public boolean isPrototype() {+ return true;+ }++ @Override+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {+ Address address = ArtConstants.findART(program);++ if (address == null) {//ART does not exist so quit, could be OAT+ return false;+ }++ ByteProvider provider = new MemoryByteProvider(program.getMemory(), address);+ BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());++ try {+ ArtHeader header = ArtFactory.newArtHeader(reader);++ DataType headerDataType = header.toDataType();++ //only set "image base" when ART header not defined at "image begin"+ //---this really only opens when ART is "added to" OAT program+ Address imageBase = toAddr(program, header.getImageBegin());++ if (BinaryLoader.BINARY_NAME.equals(program.getExecutableFormat())) {+ program.setImageBase(imageBase, true);+ createData(program, imageBase, headerDataType);+ }+ else {+ createData(program, address, headerDataType);+ }++ header.markup(program, monitor);++ return true;+ }+ catch (UnsupportedArtVersionException e) {+ log.appendException(e);+ }+ catch (Exception e) {+ throw e;+ }+ return false;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtBlock.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtBlock.javanew file mode 100644index 0000000000..b324b04617--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtBlock.java@@ -0,0 +1,99 @@+/* ###+ * 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.android.art;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/image.h+ *+ *+ */+public class ArtBlock implements StructConverter, ArtCompression {++ private ArtStorageMode storage_mode_ = ArtStorageMode.kDefaultStorageMode;+ private int data_offset_;+ private int data_size_;+ private int image_offset_;+ private int image_size_;++ public ArtBlock(BinaryReader reader) throws IOException {+ storage_mode_ = ArtStorageMode.get(reader.readNextInt());+ data_offset_ = reader.readNextInt();+ data_size_ = reader.readNextInt();+ image_offset_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ }++ @Override+ public ArtStorageMode getStorageMode() {+ return storage_mode_;+ }++ @Override+ public long getCompressedOffset() {+ return Integer.toUnsignedLong(data_offset_);+ }++ @Override+ public int getCompressedSize() {+ return data_size_;+ }++ @Override+ public long getDecompressedOffset() {+ return Integer.toUnsignedLong(image_offset_);+ }++ @Override+ public int getDecompressedSize() {+ return image_size_;+ }++ public int getDataOffset() {+ return data_offset_;+ }++ public int getDataSize() {+ return data_size_;+ }++ public int getImageOffset() {+ return image_offset_;+ }++ public int getImageSize() {+ return image_size_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String name = StructConverterUtil.parseName(ArtBlock.class);+ Structure structure = new StructureDataType(name, 0);+ structure.setCategoryPath(new CategoryPath("/art"));+ structure.add(DWORD, "storage_mode_", storage_mode_.name());+ structure.add(DWORD, "data_offset_", null);+ structure.add(DWORD, "data_size_", null);+ structure.add(DWORD, "image_offset_", null);+ structure.add(DWORD, "image_size_", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtCompression.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtCompression.javanew file mode 100644index 0000000000..2679a5130b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtCompression.java@@ -0,0 +1,52 @@+/* ###+ * 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.android.art;++public interface ArtCompression {++ /**+ * Storage method for the image, the image may be compressed.+ * @return the storage method+ * @throws UnknownArtStorageModeException when an unknown storage mode is encountered+ */+ public ArtStorageMode getStorageMode() throws UnknownArtStorageModeException;++ /**+ * Data size for the image data excluding the bitmap and the header.+ * For compressed images, this is the compressed size in the file.+ * @return the compressed size+ */+ public int getCompressedSize();++ /**+ * Offset to the start of the compressed bytes.+ * Also, offset of where to place the decompressed bytes.+ * @return the offset to the compressed bytes+ */+ public long getCompressedOffset();++ /**+ * Expected size of the decompressed bytes.+ * @return the expected decompressed size+ */+ public int getDecompressedSize();++ /**+ * Offset to the start of the decompressed bytes.+ * @return the offset to the dcompressed bytes+ */+ public long getDecompressedOffset();+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtConstants.javanew file mode 100644index 0000000000..499ddf6923--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtConstants.java@@ -0,0 +1,127 @@+/* ###+ * 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.android.art;++import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.MemoryBlock;++/**+ * https://android.googlesource.com/platform/art/+/master/runtime/image.cc+ */+public final class ArtConstants {++ public final static String ART_NAME = "Android Runtime (ART)";++ public final static String MAGIC = "art\n";++ public final static int VERSION_LENGTH = 4;++ public final static String VERSION_KITKAT_RELEASE = "005";+ public final static String VERSION_LOLLIPOP_RELEASE = "009";+ public final static String VERSION_LOLLIPOP_MR1_WFC_RELEASE = "012";+ public final static String VERSION_MARSHMALLOW_RELEASE = "017";+ public final static String VERSION_NOUGAT_RELEASE = "029";+ public final static String VERSION_NOUGAT_MR2_PIXEL_RELEASE = "030";+ public final static String VERSION_OREO_RELEASE = "043";+ public final static String VERSION_OREO_DR1_RELEASE = "044";+ public final static String VERSION_OREO_MR1_RELEASE = "046";+ public final static String VERSION_PIE_RELEASE = "056";+ public final static String VERSION_10_RELEASE = "074";//Q+ public final static String VERSION_11_RELEASE = "085";//R++ // "005",// kitkat-release+ // "009",// lollipop-release+ // "012",// lollipop-mr1-wfc-release+ // "017",// marshmallow-release+ // "029",// nougat-release+ // "030",// nougat-mr2-pixel-release+ // "043",// oreo-release+ // "044",// taimen-op1+ // "046",// oreo-mr1-release+ // "051",//+ // "056",// pie-release+ // "059",// android-o-mr1-iot-release-1.0.0+ // "060",// android-o-mr1-iot-release-1.0.1+ // "061",// android-n-iot-release-polk-at1++ /**+ * NOTE: only going to support RELEASE versions+ */+ public final static String[] SUPPORTED_VERSIONS = new String[] {+ //@formatter:off+ VERSION_KITKAT_RELEASE,+ VERSION_LOLLIPOP_RELEASE,+ VERSION_LOLLIPOP_MR1_WFC_RELEASE,+ VERSION_MARSHMALLOW_RELEASE,+ VERSION_NOUGAT_RELEASE,+ VERSION_NOUGAT_MR2_PIXEL_RELEASE,+ VERSION_OREO_RELEASE,+ VERSION_OREO_DR1_RELEASE,+ VERSION_OREO_MR1_RELEASE,+ VERSION_PIE_RELEASE,+ VERSION_10_RELEASE,+ VERSION_11_RELEASE,+ //@formatter:on+ };++ public final static boolean isSupportedVersion(String version) {+ for (String supportedVersion : SUPPORTED_VERSIONS) {+ if (supportedVersion.equals(version)) {+ return true;+ }+ }+ return false;+ }++ public final static boolean isART(Program program) {+ if (program != null) {+ for (MemoryBlock block : program.getMemory().getBlocks()) {+ try {+ byte[] bytes = new byte[ArtConstants.MAGIC.length()];+ block.getBytes(block.getStart(), bytes);+ String magic = new String(bytes);+ if (ArtConstants.MAGIC.equals(magic)) {+ return true;+ }+ }+ catch (Exception e) {+ //ignore+ }+ }+ }+ return false;+ }++ public final static Address findART(Program program) {+ if (program != null) {+ for (MemoryBlock block : program.getMemory().getBlocks()) {+ try {+ byte[] bytes = new byte[ArtConstants.MAGIC.length()];+ block.getBytes(block.getStart(), bytes);+ String magic = new String(bytes);+ if (ArtConstants.MAGIC.equals(magic)) {+ return block.getStart();+ }+ }+ catch (Exception e) {+ //ignore+ }+ }+ }+ return null;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtFactory.javanew file mode 100644index 0000000000..27e70bce18--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtFactory.java@@ -0,0 +1,79 @@+/* ###+ * 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.android.art;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.android10.ArtHeader_10;+import ghidra.file.formats.android.art.android11.ArtHeader_11;+import ghidra.file.formats.android.art.kitkat.ArtHeader_KitKat;+import ghidra.file.formats.android.art.lollipop.ArtHeader_Lollipop;+import ghidra.file.formats.android.art.lollipop.ArtHeader_LollipopMR1WFC;+import ghidra.file.formats.android.art.marshmallow.ArtHeader_Marshmallow;+import ghidra.file.formats.android.art.nougat.ArtHeader_Nougat;+import ghidra.file.formats.android.art.nougat.ArtHeader_NougatMR2Pixel;+import ghidra.file.formats.android.art.oreo.ArtHeader_Oreo;+import ghidra.file.formats.android.art.oreo.ArtHeader_OreoMR1;+import ghidra.file.formats.android.art.pie.ArtHeader_Pie;++public final class ArtFactory {++ /**+ * Returns an ArtHeader of the correct version.+ * @param reader the BinaryReader to the ART header+ * @return the specific version of the ART header+ * @throws IOException should an error occur during reading or parsing+ * @throws UnsupportedArtVersionException when the provided version is invalid or not yet implemented.+ */+ public final static ArtHeader newArtHeader(BinaryReader reader)+ throws IOException, UnsupportedArtVersionException {+ String magic = new String(reader.readByteArray(0, ArtConstants.MAGIC.length()));+ String version = reader.readAsciiString(4, 4);+ if (magic.equals(ArtConstants.MAGIC)) {+ if (ArtConstants.isSupportedVersion(version)) {+ switch (version ) {+ case ArtConstants.VERSION_KITKAT_RELEASE:+ return new ArtHeader_KitKat(reader);+ case ArtConstants.VERSION_LOLLIPOP_RELEASE:+ return new ArtHeader_Lollipop(reader);+ case ArtConstants.VERSION_LOLLIPOP_MR1_WFC_RELEASE:+ return new ArtHeader_LollipopMR1WFC(reader);+ case ArtConstants.VERSION_MARSHMALLOW_RELEASE:+ return new ArtHeader_Marshmallow(reader);+ case ArtConstants.VERSION_NOUGAT_RELEASE:+ return new ArtHeader_Nougat(reader);+ case ArtConstants.VERSION_NOUGAT_MR2_PIXEL_RELEASE:+ return new ArtHeader_NougatMR2Pixel(reader);+ case ArtConstants.VERSION_OREO_RELEASE:+ return new ArtHeader_Oreo(reader);+ case ArtConstants.VERSION_OREO_DR1_RELEASE:+ return new ArtHeader_Oreo(reader);//v043 and v044 are same format+ case ArtConstants.VERSION_OREO_MR1_RELEASE:+ return new ArtHeader_OreoMR1(reader);+ case ArtConstants.VERSION_PIE_RELEASE:+ return new ArtHeader_Pie(reader);+ case ArtConstants.VERSION_10_RELEASE:+ return new ArtHeader_10(reader);+ case ArtConstants.VERSION_11_RELEASE:+ return new ArtHeader_11(reader);+ }+ }+ }+ throw new UnsupportedArtVersionException(magic, version);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtField.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtField.javanew file mode 100644index 0000000000..81bea98836--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtField.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.android.art;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/art_field.h+ *+ *+ */+public class ArtField implements StructConverter {++ private int declaring_class_;+ private int access_flags_;+ private int field_dex_idx_;+ private int offset_;++ public ArtField(BinaryReader reader) throws IOException {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ field_dex_idx_ = reader.readNextInt();+ offset_ = reader.readNextInt();+ }++ public int getDeclaringClass() {+ return declaring_class_;+ }++ public int getAccessFlags() {+ return access_flags_;+ }++ public int getFieldDexIndex() {+ return field_dex_idx_;+ }++ public int getOffset() {+ return offset_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String name = StructConverterUtil.parseName(ArtField.class);+ Structure structure = new StructureDataType(name, 0);+ structure.setCategoryPath(new CategoryPath("/art"));+ structure.add(new Pointer32DataType(), "declaring_class_", null);+ structure.add(DWORD, "access_flags_", null);+ structure.add(DWORD, "field_dex_idx_", null);+ structure.add(DWORD, "offset_", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtFieldGroup.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtFieldGroup.javanew file mode 100644index 0000000000..32840aa03d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtFieldGroup.java@@ -0,0 +1,66 @@+/* ###+ * 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.android.art;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/art_field.h+ *+ * NOTE: this class does not exist, was created to make field reading easier.+ */+public class ArtFieldGroup implements StructConverter {++ private int fieldCount;+ private List<ArtField> fieldList = new ArrayList<>();++ public ArtFieldGroup(BinaryReader reader) throws IOException {+ fieldCount = reader.readNextInt();+ if (fieldCount > 0xffff) {//sanity check...+ throw new IOException("Too many ART fields: " + fieldCount);+ }+ for (int i = 0; i < fieldCount; ++i) {+ fieldList.add(new ArtField(reader));+ }+ }++ public int getFieldCount() {+ return fieldCount;+ }++ public List<ArtField> getFieldList() {+ return fieldList;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String name = StructConverterUtil.parseName(ArtFieldGroup.class);+ Structure structure = new StructureDataType(name + "_" + fieldCount, 0);+ structure.setCategoryPath(new CategoryPath("/art"));+ structure.add(DWORD, "fieldCount", null);+ for (int i = 0; i < fieldCount; ++i) {+ structure.add(fieldList.get(i).toDataType(), "field_" + i, null);+ }+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtHeader.javanew file mode 100644index 0000000000..13943c9af9--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtHeader.java@@ -0,0 +1,148 @@+/* ###+ * 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.android.art;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/image.h+ */+public abstract class ArtHeader implements StructConverter {++ protected String magic_;+ protected String version_;++ protected List<Long> imageMethodsList = new ArrayList<>();++ protected ArtHeader(BinaryReader reader) throws IOException {+ magic_ = new String(reader.readNextByteArray(ArtConstants.MAGIC.length()));+ version_ = reader.readNextAsciiString(ArtConstants.VERSION_LENGTH);+ }++ /**+ * Returns the magic string: "art\n".+ * @return the magic string+ */+ public final String getMagic() {+ return magic_;+ }++ /**+ * Returns the version string: eg, "001", "017"+ * @return the version+ */+ public final String getVersion() {+ return version_;+ }++ /**+ * Required base address for mapping the image.+ *+ * Base address of the ART file.+ * -1 indicates unsupported+ * @return image base address+ */+ abstract public int getImageBegin();++ /**+ * Required base size for mapping the image.+ * -1 indicates unsupported+ * @return image size+ */+ abstract public int getImageSize();++ /**+ * Returns the checksum of the matching OAT file.+ * The checksum is stored in the OAT header and is generated using Adler32.+ * -1 indicates unsupported+ * @return oat checksum+ */+ abstract public int getOatChecksum();++ /**+ * -1 indicates unsupported+ * @return the oat file begin address+ */+ abstract public int getOatFileBegin();++ /**+ * -1 indicates unsupported+ * @return the oat file end address+ */+ abstract public int getOatFileEnd();++ /**+ * Returns the offset to the start of the .oatdata section,+ * usually defined within the ".rodata" section.+ * -1 indicates unsupported+ * @return the oat data begin address+ */+ abstract public int getOatDataBegin();++ /**+ * -1 indicates unsupported+ * @return the oat data end address+ */+ abstract public int getOatDataEnd();++ /**+ * Pointer size (in bytes).+ * @return the pointer size+ */+ abstract public int getPointerSize();++ abstract public int getArtMethodCountForVersion();++ /**+ * Parses the ART header data.+ * @param reader the binary reader+ * @throws IOException if an error occurs parsing the header+ */+ abstract protected void parse(BinaryReader reader) throws IOException;++ protected final void parseImageMethods(BinaryReader reader) throws IOException {+ for (int i = 0; i < getArtMethodCountForVersion(); ++i) {+ imageMethodsList.add(reader.readNextLong());+ }+ }++ /**+ * Allows each specific version to mark-up the specified program.+ * @param program the program to markup+ * @param monitor the task monitor+ * @throws Exception if an error occurs while marking up the program+ */+ abstract public void markup(Program program, TaskMonitor monitor) throws Exception;++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(ArtHeader.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.setCategoryPath(new CategoryPath("/art"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSection.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSection.javanew file mode 100644index 0000000000..5bffccc7f5--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSection.java@@ -0,0 +1,53 @@+/* ###+ * 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.android.art;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++public class ArtImageSection implements StructConverter {+ private int offset_;+ private int size_;++ public ArtImageSection(BinaryReader reader) throws IOException {+ offset_ = reader.readNextInt();+ size_ = reader.readNextInt();+ }++ public int getOffset() {+ return offset_;+ }++ public int getSize() {+ return size_;+ }++ public int getEnd() {+ return offset_ + size_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(ArtImageSection.class);+ dataType.setCategoryPath(new CategoryPath("/art"));+ return dataType;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSections.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSections.javanew file mode 100644index 0000000000..34afc91c56--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSections.java@@ -0,0 +1,522 @@+/* ###+ * 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.android.art;++import java.io.IOException;+import java.lang.reflect.Field;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.*;+import ghidra.program.model.symbol.SourceType;+import ghidra.util.task.TaskMonitor;++public abstract class ArtImageSections {++ public final static int UNSUPPORTED_SECTION = -1;++ protected ArtHeader header;++ protected List<ArtImageSection> sectionList = new ArrayList<>();+ protected List<ArtFieldGroup> fieldGroupList = new ArrayList<>();+ protected List<ArtMethodGroup> methodGroupList = new ArrayList<>();++ protected List<ArtField> fieldList = new ArrayList<>();+ protected List<ArtMethod> methodList = new ArrayList<>();++ protected ArtImageSections(BinaryReader reader, ArtHeader header) {+ this.header = header;+ }++ /**+ * Returns the section name for the given ordinal.+ * For example, if sectionOrdinal is 0 then return "kSectionObjects".+ * @param sectionOrdinal the original of the ART section+ * @return the ART section name+ */+ protected String getSectionName(int sectionOrdinal) {+ for (Field field : getClass().getDeclaredFields()) {+ if (field.getName().startsWith("kSection")) {+ try {+ Object value = field.get(null);+ if ((int) value == sectionOrdinal) {+ return field.getName();+ }+ }+ catch (Exception e) {+ //ignore+ }+ }+ }+ return "unknown_section_0x" + Integer.toHexString(sectionOrdinal);+ }++ public abstract int get_kSectionObjects();++ public abstract int get_kSectionArtFields();++ public abstract int get_kSectionArtMethods();++ public abstract int get_kSectionRuntimeMethods();++ public abstract int get_kSectionImTables();++ public abstract int get_kSectionIMTConflictTables();++ public abstract int get_kSectionDexCacheArrays();++ public abstract int get_kSectionInternedStrings();++ public abstract int get_kSectionClassTable();++ public abstract int get_kSectionStringReferenceOffsets();++ public abstract int get_kSectionMetadata();++ public abstract int get_kSectionImageBitmap();++ public abstract int get_kSectionCount(); // Number of elements in enum.++ public final List<ArtImageSection> getSectionList() {+ return sectionList;+ }++ public final void parseSections(BinaryReader reader) throws IOException {+ for (int i = 0; i < get_kSectionCount(); ++i) {+ sectionList.add(new ArtImageSection(reader));+ }+ }++ public final void parse(BinaryReader reader) throws IOException {+ parseArtFields(reader);+ parseArtMethods(reader);+ }++ private void parseArtFields(BinaryReader reader) throws IOException {+ ArtImageSection kSectionArtFields = sectionList.get(get_kSectionArtFields());+ if (kSectionArtFields.getSize() > 0) {+ if (reader.length() > kSectionArtFields.getOffset()) {//out of bounds+ reader.setPointerIndex(kSectionArtFields.getOffset());+ while (reader.getPointerIndex() < Integer+ .toUnsignedLong(kSectionArtFields.getEnd())) {+ if (ArtConstants.VERSION_MARSHMALLOW_RELEASE.equals(header.getVersion())) {+ ArtField field = new ArtField(reader);+ fieldList.add(field);+ }+ else {+ ArtFieldGroup group = new ArtFieldGroup(reader);+ fieldGroupList.add(group);+ }+ }+ }+ }+ }++ private void parseArtMethods(BinaryReader reader) throws IOException {+ ArtImageSection kSectionArtMethods = sectionList.get(get_kSectionArtMethods());+ if (kSectionArtMethods.getSize() > 0) {+ if (reader.length() > kSectionArtMethods.getOffset()) {//out of bounds+ reader.setPointerIndex(kSectionArtMethods.getOffset());+ while (reader.getPointerIndex() < Integer+ .toUnsignedLong(kSectionArtMethods.getEnd())) {+ if (ArtConstants.VERSION_MARSHMALLOW_RELEASE.equals(header.getVersion())) {+ ArtMethod method =+ new ArtMethod(reader, header.getPointerSize(), header.getVersion());+ methodList.add(method);+ }+ else {+ ArtMethodGroup group = new ArtMethodGroup(reader, header.getPointerSize(),+ header.getVersion());+ methodGroupList.add(group);+ }+ }+ }+ }+ }++ public void markup(Program program, TaskMonitor monitor) throws Exception {+ markupSections(program, monitor);+ markupFields(program, monitor);+ markupMethods(program, monitor);+ markupImTables(program, monitor);+ markupIMTConflictTables(program, monitor);+ markupRuntimeMethods(program, monitor);+ markupDexCacheArrays(program, monitor);+ markupInternedStrings(program, monitor);+ markupClassTables(program, monitor);+ }++ private void markupSections(Program program, TaskMonitor monitor) throws Exception {+ monitor.setMessage("ART - markup sections...");+ monitor.setProgress(0);+ monitor.setMaximum(sectionList.size());++ for (int i = 0; i < sectionList.size(); ++i) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ ArtImageSection section = sectionList.get(i);++ if (section.getSize() == 0) {+ continue;+ }+ String name = getSectionName(i);+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());+ program.getSymbolTable().createLabel(address, name, SourceType.ANALYSIS);+ program.getListing()+ .setComment(address, CodeUnit.PLATE_COMMENT, "Size: " + section.getSize());++ createFragment(program, address, section, name, monitor);+ }+ }++ private void markupFields(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionArtFields() == UNSUPPORTED_SECTION) {+ return;+ }++ monitor.setMessage("ART - markup fields...");+ monitor.setProgress(0);+ monitor.setMaximum(fieldList.size());++ ArtImageSection section = sectionList.get(get_kSectionArtFields());++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());++ for (int i = 0; i < fieldList.size(); ++i) {+ monitor.checkCanceled();+ ArtField field = fieldList.get(i);+ DataType dataType = field.toDataType();+ program.getListing().createData(address, dataType);++ String comment =+ "Declaring Class: 0x" + Integer.toHexString(field.getDeclaringClass());+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);++ address = address.add(dataType.getLength());++ monitor.incrementProgress(1);+ }+ }++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());+ for (int i = 0; i < fieldGroupList.size(); ++i) {+ monitor.checkCanceled();+ ArtFieldGroup fieldGroup = fieldGroupList.get(i);+ DataType dataType = fieldGroup.toDataType();+ program.getListing().createData(address, dataType);+ if (fieldGroup.getFieldCount() > 0) {+ ArtField artField = fieldGroup.getFieldList().get(0);+ String comment =+ "Declaring Class: 0x" + Integer.toHexString(artField.getDeclaringClass());+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);+ }+ address = address.add(dataType.getLength());++ monitor.incrementProgress(1);+ }+ }+ }++ private void markupMethods(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionArtMethods() == UNSUPPORTED_SECTION) {+ return;+ }++ monitor.setMessage("ART - markup methods...");+ monitor.setProgress(0);+ monitor.setMaximum(methodGroupList.size());++ ArtImageSection section = sectionList.get(get_kSectionArtMethods());++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());+ for (int i = 0; i < methodList.size(); ++i) {+ monitor.checkCanceled();++ ArtMethod method = methodList.get(i);+ DataType dataType = method.toDataType();+ program.getListing().createData(address, dataType);+ String comment =+ "Declaring Class: 0x" + Integer.toHexString(method.getDeclaringClass());+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);++ address = address.add(dataType.getLength());++ monitor.incrementProgress(1);+ }+ }++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());+ for (int i = 0; i < methodGroupList.size(); ++i) {+ monitor.checkCanceled();++ ArtMethodGroup methodGroup = methodGroupList.get(i);+ DataType dataType = methodGroup.toDataType();+ program.getListing().createData(address, dataType);+ if (methodGroup.getMethodCount() > 0) {+ ArtMethod artMethod = methodGroup.getMethodList().get(0);+ String comment =+ "Declaring Class: 0x" + Integer.toHexString(artMethod.getDeclaringClass());+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);+ }+ address = address.add(dataType.getLength());++ monitor.incrementProgress(1);+ }+ }+ }++ /**+ * Interface Methods Tables+ */+ private void markupImTables(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionImTables() == UNSUPPORTED_SECTION) {+ return;+ }+ ArtImageSection section = sectionList.get(get_kSectionImTables());++ monitor.setMessage("ART - markup IM tables...");+ monitor.setProgress(0);+ monitor.setMaximum(section.getSize());++ int pointerSize = header.getPointerSize();++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());++ if (!program.getMemory().contains(address)) {//outside of ART file+ return;+ }++ Address endAddress = address.add(section.getSize());+ while (address.compareTo(endAddress) < 0) {+ monitor.checkCanceled();+ monitor.incrementProgress(pointerSize);++ createDataAt(program, address, pointerSize);+ address = address.add(pointerSize);+ }+ }+ }++ /**+ * IMT Conflict Tables+ */+ private void markupIMTConflictTables(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionIMTConflictTables() == UNSUPPORTED_SECTION) {+ return;+ }++ ArtImageSection section = sectionList.get(get_kSectionIMTConflictTables());++ monitor.setMessage("ART - markup IMT conflict tables...");+ monitor.setProgress(0);+ monitor.setMaximum(section.getSize());++ int pointerSize = header.getPointerSize();++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());++ if (!program.getMemory().contains(address)) {//outside of ART file+ return;+ }++ Address endAddress = address.add(section.getSize());+ while (address.compareTo(endAddress) < 0) {+ monitor.checkCanceled();+ monitor.incrementProgress(pointerSize);++ createDataAt(program, address, pointerSize);+ address = address.add(pointerSize);+ }+ }+ }++ private void markupRuntimeMethods(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionRuntimeMethods() == UNSUPPORTED_SECTION) {+ return;+ }++ ArtImageSection section = sectionList.get(get_kSectionRuntimeMethods());++ monitor.setMessage("ART - markup runtime methods...");+ monitor.setProgress(0);+ monitor.setMaximum(section.getSize());++ int pointerSize = header.getPointerSize();+ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());++ if (!program.getMemory().contains(address)) {//outside of ART file+ return;+ }++ Address endAddress = address.add(section.getSize());+ while (address.compareTo(endAddress) < 0) {+ monitor.checkCanceled();+ monitor.incrementProgress(pointerSize);++ createDataAt(program, address, pointerSize);+ address = address.add(pointerSize);+ }+ }+ }++ private void markupDexCacheArrays(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionDexCacheArrays() == UNSUPPORTED_SECTION) {+ return;+ }++ ArtImageSection section = sectionList.get(get_kSectionDexCacheArrays());++ monitor.setMessage("ART - markup dex cache arrays...");+ monitor.setProgress(0);+ monitor.setMaximum(section.getSize());++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());++ if (!program.getMemory().contains(address)) {//outside of ART file+ return;+ }++ Address endAddress = address.add(section.getSize());+ while (address.compareTo(endAddress) < 0) {+ monitor.checkCanceled();+ monitor.incrementProgress(4);++ createDataAt(program, address, 4);+ address = address.add(4);+ }+ }+ }++ private void markupInternedStrings(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionInternedStrings() == UNSUPPORTED_SECTION) {+ return;+ }++ ArtImageSection section = sectionList.get(get_kSectionInternedStrings());++ monitor.setMessage("ART - markup interned strings...");+ monitor.setProgress(0);+ monitor.setMaximum(section.getSize());++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());++ if (!program.getMemory().contains(address)) {//outside of ART file+ return;+ }++ Address endAddress = address.add(section.getSize());+ while (address.compareTo(endAddress) < 0) {+ monitor.checkCanceled();+ monitor.incrementProgress(4);++ createDataAt(program, address, 4);+ address = address.add(4);+ }+ }+ }++ private void markupClassTables(Program program, TaskMonitor monitor) throws Exception {+ if (get_kSectionClassTable() == UNSUPPORTED_SECTION) {+ return;+ }++ ArtImageSection section = sectionList.get(get_kSectionClassTable());++ monitor.setMessage("ART - markup class tables...");+ monitor.setProgress(0);+ monitor.setMaximum(section.getSize());++ if (section.getSize() > 0) {+ Address address =+ program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset());++ if (!program.getMemory().contains(address)) {//outside of ART file+ return;+ }++ Address endAddress = address.add(section.getSize());+ while (address.compareTo(endAddress) < 0) {+ monitor.checkCanceled();+ monitor.incrementProgress(4);++ address = address.add(4);+ }+ }+ }++ private void createDataAt(Program program, Address address, int pointerSize) throws Exception {+ if (pointerSize == 4) {+ program.getListing().createData(address, new DWordDataType());+ }+ else if (pointerSize == 8) {+ program.getListing().createData(address, new QWordDataType());+ }+ else {+ throw new RuntimeException("invalid pointer size");+ }+ }++ private void createFragment(Program program, Address address, ArtImageSection section,+ String sectionName, TaskMonitor monitor) {+ try {+ ProgramModule rootModule = program.getListing().getDefaultRootModule();++ ProgramFragment fragment = null;+ for (Group group : rootModule.getChildren()) {+ if (group.getName().equals(sectionName)) {+ fragment = (ProgramFragment) group;+ }+ }+ if (fragment == null) {+ fragment = rootModule.createFragment(sectionName);+ }++ Address endAddress = address.add((Integer.toUnsignedLong(section.getSize()) - 1));+ if (sectionList.indexOf(section) == sectionList.size() - 1) {//last section might extend past the end of the program+ if (endAddress.compareTo(program.getMaxAddress()) > 0) {+ endAddress = program.getMaxAddress();+ }+ }+ fragment.move(address, endAddress);+ }+ catch (Exception e) {+ //ignore...+ }+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtMethod.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtMethod.javanew file mode 100644index 0000000000..dd34ff2582--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtMethod.java@@ -0,0 +1,402 @@+/* ###+ * 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.android.art;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/art_method.h+ *+ *+ */+public class ArtMethod implements StructConverter {+ private final int pointerSize;+ private final String artVersion;++ private int declaring_class_;+ private int access_flags_;+ private int dex_code_item_offset_;+ private int dex_method_index_;+ private short method_index_;+ private short hotness_count_;+ private short imt_index_;+ private short padding_;++ private long dex_cache_resolved_methods_;+ private long dex_cache_resolved_types_;+ private long entry_point_from_interpreter_;+ private long entry_point_from_jni_;+ private long data_;+ private long unknown1_;+ private long entry_point_from_quick_compiled_code_;+ private int unknown2_;++ public ArtMethod(BinaryReader reader, int pointerSize, String artVersion) throws IOException {+ this.pointerSize = pointerSize;+ this.artVersion = artVersion;++ if (ArtConstants.VERSION_MARSHMALLOW_RELEASE.equals(artVersion)) {+ if (pointerSize == 4) {+ declaring_class_ = reader.readNextInt();+ dex_cache_resolved_methods_ = Integer.toUnsignedLong(reader.readNextInt());+ dex_cache_resolved_types_ = Integer.toUnsignedLong(reader.readNextInt());+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ padding_ = reader.readNextShort();+ entry_point_from_interpreter_ = Integer.toUnsignedLong(reader.readNextInt());+ entry_point_from_jni_ = Integer.toUnsignedLong(reader.readNextInt());+ entry_point_from_quick_compiled_code_ =+ Integer.toUnsignedLong(reader.readNextInt());+ }+ else if (pointerSize == 8) {+ throw new IOException("Unsupported 64-bit ART method format: " + artVersion);+ }+ }+ else if (ArtConstants.VERSION_NOUGAT_RELEASE.equals(artVersion) ||+ ArtConstants.VERSION_NOUGAT_MR2_PIXEL_RELEASE.equals(artVersion)) {++ if (pointerSize == 4) {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ hotness_count_ = reader.readNextShort();+ dex_cache_resolved_methods_ = Integer.toUnsignedLong(reader.readNextInt());+ dex_cache_resolved_types_ = Integer.toUnsignedLong(reader.readNextInt());+ entry_point_from_jni_ = Integer.toUnsignedLong(reader.readNextInt());+ entry_point_from_quick_compiled_code_ =+ Integer.toUnsignedLong(reader.readNextInt());+ }+ else if (pointerSize == 8) {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ hotness_count_ = reader.readNextShort();+ imt_index_ = reader.readNextShort();+ padding_ = reader.readNextShort();+ dex_cache_resolved_methods_ = reader.readNextLong();+ dex_cache_resolved_types_ = reader.readNextLong();+ entry_point_from_jni_ = reader.readNextLong();+ entry_point_from_quick_compiled_code_ = reader.readNextLong();+ }+ }+ else if (ArtConstants.VERSION_OREO_RELEASE.equals(artVersion) ||+ ArtConstants.VERSION_OREO_DR1_RELEASE.equals(artVersion) ||+ ArtConstants.VERSION_OREO_MR1_RELEASE.equals(artVersion)) {++ if (pointerSize == 4) {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ hotness_count_ = reader.readNextShort();+ data_ = reader.readNextLong();+ entry_point_from_quick_compiled_code_ =+ Integer.toUnsignedLong(reader.readNextInt());+ }+ else if (pointerSize == 8) {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ hotness_count_ = reader.readNextShort();+ imt_index_ = reader.readNextShort();+ padding_ = reader.readNextShort();+ data_ = reader.readNextLong();+ unknown1_ = reader.readNextLong();+ entry_point_from_quick_compiled_code_ = reader.readNextLong();+ }+ }+ else if (ArtConstants.VERSION_PIE_RELEASE.equals(artVersion)) {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ hotness_count_ = reader.readNextShort();+ imt_index_ = reader.readNextShort();+ padding_ = reader.readNextShort();++ if (pointerSize == 4) {+ data_ = Integer.toUnsignedLong(reader.readNextInt());+ }+ else if (pointerSize == 8) {+ data_ = reader.readNextLong();+ entry_point_from_quick_compiled_code_ = reader.readNextLong();+ }+ }+ else if (ArtConstants.VERSION_10_RELEASE.equals(artVersion)) {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ hotness_count_ = reader.readNextShort();+ imt_index_ = reader.readNextShort();+ padding_ = reader.readNextShort();++ if (pointerSize == 4) {+ data_ = Integer.toUnsignedLong(reader.readNextInt());+ }+ else if (pointerSize == 8) {+ data_ = reader.readNextLong();+ entry_point_from_quick_compiled_code_ = reader.readNextLong();+ }+ }+ else if (ArtConstants.VERSION_11_RELEASE.equals(artVersion)) {+ declaring_class_ = reader.readNextInt();+ access_flags_ = reader.readNextInt();+ dex_code_item_offset_ = reader.readNextInt();+ dex_method_index_ = reader.readNextInt();+ method_index_ = reader.readNextShort();+ hotness_count_ = reader.readNextShort();+ imt_index_ = reader.readNextShort();+ padding_ = reader.readNextShort();++ if (pointerSize == 4) {+ data_ = Integer.toUnsignedLong(reader.readNextInt());+ }+ else if (pointerSize == 8) {+ data_ = reader.readNextLong();+ entry_point_from_quick_compiled_code_ = reader.readNextLong();+ }+ }+ else {+ throw new IOException("Unsupported ART method format: " + artVersion);+ }+ }++ public int getDeclaringClass() {+ return declaring_class_;+ }++ public int getAccessFlags() {+ return access_flags_;+ }++ public int getDexCodeItemOffset() {+ return dex_code_item_offset_;+ }++ public int getDexMethodIndex() {+ return dex_method_index_;+ }++ public short getMethodIndex() {+ return method_index_;+ }++ public short getHotnessCount() {+ return hotness_count_;+ }++ public short getImtIndex() {+ return imt_index_;+ }++ public short getPadding() {+ return padding_;+ }++ public long getData() {+ return data_;+ }++ public long getEntryPointFromInterpreter() {+ return entry_point_from_interpreter_;+ }++ public long getEntryPointFromQuickCompiledCode() {+ return entry_point_from_quick_compiled_code_;+ }++ public long getDexCacheResolvedMethods() {+ return dex_cache_resolved_methods_;+ }++ public long getDexCacheResolvedTypes() {+ return dex_cache_resolved_types_;+ }++ public long getEntryPointFromJNI() {+ return entry_point_from_jni_;+ }++ public long getUnknown1() {+ return unknown1_;+ }++ public int getUnknown2() {+ return unknown2_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType ptr32 = new Pointer32DataType();+ DataType ptr64 = new Pointer64DataType();++ String name = StructConverterUtil.parseName(ArtMethod.class);+ Structure struct = new StructureDataType(name, 0);+ struct.setCategoryPath(new CategoryPath("/art"));++ if (ArtConstants.VERSION_MARSHMALLOW_RELEASE.equals(artVersion)) {+ if (pointerSize == 4) {+ struct.add(DWORD, "declaring_class_", null);+ struct.add(DWORD, "dex_cache_resolved_methods_", null);+ struct.add(DWORD, "dex_cache_resolved_types_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "padding_", null);+ struct.add(DWORD, "entry_point_from_interpreter_", null);+ struct.add(DWORD, "entry_point_from_jni_", null);+ struct.add(DWORD, "entry_point_from_quick_compiled_code_", null);+ }+ else if (pointerSize == 8) {+ throw new IOException("Unsupported 64-bit ART method format: " + artVersion);+ }+ }+ else if (ArtConstants.VERSION_NOUGAT_RELEASE.equals(artVersion) ||+ ArtConstants.VERSION_NOUGAT_MR2_PIXEL_RELEASE.equals(artVersion)) {++ if (pointerSize == 4) {+ struct.add(ptr32, "declaring_class_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "hotness_count_", null);+ struct.add(DWORD, "dex_cache_resolved_methods_", null);+ struct.add(DWORD, "dex_cache_resolved_types_", null);+ struct.add(ptr32, "entry_point_from_jni_", null);+ struct.add(ptr32, "entry_point_from_quick_compiled_code_", null);+ }+ else if (pointerSize == 8) {+ struct.add(ptr32, "declaring_class_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "hotness_count_", null);+ struct.add(WORD, "imt_index_", null);+ struct.add(WORD, "padding", null);+ struct.add(QWORD, "dex_cache_resolved_methods_", null);+ struct.add(QWORD, "dex_cache_resolved_types_", null);+ struct.add(ptr64, "entry_point_from_jni_", null);+ struct.add(ptr64, "entry_point_from_quick_compiled_code_", null);+ }+ }+ else if (ArtConstants.VERSION_OREO_RELEASE.equals(artVersion) ||+ ArtConstants.VERSION_OREO_DR1_RELEASE.equals(artVersion) ||+ ArtConstants.VERSION_OREO_MR1_RELEASE.equals(artVersion)) {++ if (pointerSize == 4) {+ struct.add(ptr32, "declaring_class_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "hotness_count_", null);+ struct.add(QWORD, "data", null);+ struct.add(ptr32, "entry_point_from_quick_compiled_code_", null);+ }+ else if (pointerSize == 8) {+ struct.add(ptr32, "declaring_class_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "hotness_count_", null);+ struct.add(WORD, "imt_index_", null);+ struct.add(WORD, "padding", null);+ struct.add(QWORD, "data", null);+ struct.add(QWORD, "unknown1_", null);+ struct.add(ptr64, "entry_point_from_quick_compiled_code_", null);+ }+ }+ else if (ArtConstants.VERSION_PIE_RELEASE.equals(artVersion)) {+ struct.add(ptr32, "declaring_class_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "hotness_count_", null);+ struct.add(WORD, "imt_index_", null);+ struct.add(WORD, "padding", null);++ if (pointerSize == 4) {+ struct.add(DWORD, "data", null);+ }+ else if (pointerSize == 8) {+ struct.add(QWORD, "data", null);+ struct.add(QWORD, "entry_point_from_quick_compiled_code_", null);+ }+ }+ else if (ArtConstants.VERSION_10_RELEASE.equals(artVersion)) {+ struct.add(ptr32, "declaring_class_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "hotness_count_", null);+ struct.add(WORD, "imt_index_", null);+ struct.add(WORD, "padding", null);++ if (pointerSize == 4) {+ struct.add(DWORD, "data", null);+ }+ else if (pointerSize == 8) {+ struct.add(QWORD, "data", null);+ struct.add(ptr64, "entry_point_from_quick_compiled_code_", null);+ }+ }+ else if (ArtConstants.VERSION_11_RELEASE.equals(artVersion)) {+ struct.add(ptr32, "declaring_class_", null);+ struct.add(DWORD, "access_flags_", null);+ struct.add(DWORD, "dex_code_item_offset_", null);+ struct.add(DWORD, "dex_method_index_", null);+ struct.add(WORD, "method_index_", null);+ struct.add(WORD, "hotness_count_", null);+ struct.add(WORD, "imt_index_", null);+ struct.add(WORD, "padding", null);++ if (pointerSize == 4) {+ struct.add(DWORD, "data", null);+ }+ else if (pointerSize == 8) {+ struct.add(QWORD, "data", null);+ struct.add(QWORD, "entry_point_from_quick_compiled_code_", null);+ }+ }+ else {+ throw new IOException("Unsupported ART method format: " + artVersion);+ }+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtMethodGroup.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtMethodGroup.javanew file mode 100644index 0000000000..7b7f98e603--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtMethodGroup.java@@ -0,0 +1,83 @@+/* ###+ * 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.android.art;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/art_method.h+ *+ * NOTE: this class does not exist, was created to make method reading easier.+ */+public class ArtMethodGroup implements StructConverter {++ private int pointerSize;++ private long methodCount;+ private List<ArtMethod> methodList = new ArrayList<>();++ public ArtMethodGroup(BinaryReader reader, int pointerSize, String artVersion)+ throws IOException {+ this.pointerSize = pointerSize;++ if (pointerSize == 8) {+ methodCount = reader.readNextLong();+ }+ else if (pointerSize == 4) {+ methodCount = Integer.toUnsignedLong(reader.readNextInt());+ }++ if (methodCount > 0xffff) {//sanity check...+ throw new IOException("Too many ART methods: " + methodCount);+ }++ for (int i = 0; i < methodCount; ++i) {+ methodList.add(new ArtMethod(reader, pointerSize, artVersion));+ }+ }++ public long getMethodCount() {+ return methodCount;+ }++ public List<ArtMethod> getMethodList() {+ return methodList;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String name = StructConverterUtil.parseName(ArtMethodGroup.class);+ Structure structure = new StructureDataType(name + "_" + methodCount, 0);+ structure.setCategoryPath(new CategoryPath("/art"));+ if (pointerSize == 8) {+ structure.add(QWORD, "methodCount", null);+ }+ else if (pointerSize == 4) {+ structure.add(DWORD, "methodCount", null);+ }+ for (int i = 0; i < methodCount; ++i) {+ structure.add(methodList.get(i).toDataType(), "method_" + i, null);+ }+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtStorageMode.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtStorageMode.javanew file mode 100644index 0000000000..fcc32ac0e0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtStorageMode.java@@ -0,0 +1,36 @@+/* ###+ * 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.android.art;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/image.h+ */+public enum ArtStorageMode {+ kStorageModeUncompressed, kStorageModeLZ4, kStorageModeLZ4HC, kStorageModeCount; // Number of elements in enum.++ public final static ArtStorageMode kDefaultStorageMode = kStorageModeUncompressed;++ public final static int SIZE = 32;//bits++ public static ArtStorageMode get(int value) throws UnknownArtStorageModeException {+ for (ArtStorageMode mode : values()) {+ if (mode.ordinal() == value) {+ return mode;+ }+ }+ throw new UnknownArtStorageModeException(value);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtUtilities.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtUtilities.javanew file mode 100644index 0000000000..e8372e131c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtUtilities.java@@ -0,0 +1,68 @@+/* ###+ * 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.android.art;++import java.math.BigInteger;++import ghidra.program.model.address.Address;+import ghidra.program.model.lang.*;+import ghidra.program.model.listing.*;++public final class ArtUtilities {++ static void createFragment(Program program, String fragmentName, Address start,+ Address end) throws Exception {+ ProgramModule module = program.getListing().getRootModule(0);+ ProgramFragment fragment = getFragment(module, fragmentName);+ if (fragment == null) {+ fragment = module.createFragment(fragmentName);+ }+ fragment.move(start, end.subtract(1));+ }++ static ProgramFragment getFragment(ProgramModule module, String fragmentName) {+ Group[] groups = module.getChildren();+ for (Group group : groups) {+ if (group.getName().equals(fragmentName)) {+ return (ProgramFragment) group;+ }+ }+ return null;+ }++ public static Address adjustForThumbAsNeeded(ArtHeader artHeader, Program program,+ Address address) {+ long displacement = address.getOffset();+ if (program.getLanguage()+ .getProcessor()+ .equals(Processor.findOrPossiblyCreateProcessor("ARM"))) {+ if ((displacement & 0x1) == 0x1) {//thumb code?+ address = address.subtract(1);++ Register register = program.getLanguage().getRegister("TMode");+ RegisterValue value = new RegisterValue(register, BigInteger.valueOf(1));+ try {+ program.getProgramContext().setRegisterValue(address, address, value);+ }+ catch (ContextChangeException e) {+ //log.appendException( e );+ //ignore...+ }+ }+ }+ return address;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/UnknownArtStorageModeException.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/UnknownArtStorageModeException.javanew file mode 100644index 0000000000..61384ec0c8--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/UnknownArtStorageModeException.java@@ -0,0 +1,26 @@+/* ###+ * 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.android.art;++import java.io.IOException;++public class UnknownArtStorageModeException extends IOException {++ public UnknownArtStorageModeException(int storageMode) {+ super("Unrecognized storage mode: 0x" + Integer.toHexString(storageMode));+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/UnsupportedArtVersionException.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/UnsupportedArtVersionException.javanew file mode 100644index 0000000000..2c1975aaaf--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/UnsupportedArtVersionException.java@@ -0,0 +1,23 @@+/* ###+ * 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.android.art;++final class UnsupportedArtVersionException extends Exception {++ UnsupportedArtVersionException(String magic, String version) {+ super("Unsupported ART version: " + version);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ArtHeader_10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ArtHeader_10.javanew file mode 100644index 0000000000..b49e180ce2--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ArtHeader_10.java@@ -0,0 +1,234 @@+/* ###+ * 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.android.art.android10;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.*;+import ghidra.file.formats.android.util.DecompressionManager;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/image.h+ */+public class ArtHeader_10 extends ArtHeader {++ private int image_reservation_size_;+ private int component_count_;+ private int image_begin_;+ private int image_size_;+ private int image_checksum_;+ private int oat_checksum_;+ private int oat_file_begin_;+ private int oat_data_begin_;+ private int oat_data_end_;+ private int oat_file_end_;+ private int boot_image_begin_;+ private int boot_image_size_;+ private int image_roots_;+ private int pointer_size_;+ private long[] image_methods_ = new long[ImageMethod_10.kImageMethodsCount.ordinal()];+ private int data_size_;+ private int blocks_offset_;+ private int blocks_count_;+ private List<ArtBlock> blocks = new ArrayList<>();++ private ArtImageSections sections;++ public ArtHeader_10(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_reservation_size_ = reader.readNextInt();+ component_count_ = reader.readNextInt();+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ image_checksum_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ boot_image_begin_ = reader.readNextInt();+ boot_image_size_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ pointer_size_ = reader.readNextInt();++ sections = new ImageSections_10(reader, this);+ sections.parseSections(reader);++ parseImageMethods(reader);++ data_size_ = reader.readNextInt();+ blocks_offset_ = reader.readNextInt();+ blocks_count_ = reader.readNextInt();++ if (blocks_offset_ > 0 && blocks_count_ > 0) {+ reader.setPointerIndex(blocks_offset_);+ for (int i = 0; i < blocks_count_; ++i) {+ blocks.add(new ArtBlock(reader));+ }+ }++ reader = DecompressionManager.decompress(reader, blocks, TaskMonitor.DUMMY);++ // NOTE:+ // cannot parse the sections until after the blocks are decompressed!++ sections.parse(reader);+ }++ @Override+ public int getArtMethodCountForVersion() {+ return ImageMethod_10.kImageMethodsCount.ordinal();+ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ public int getImageChecksum_() {+ return image_checksum_;+ }++ @Override+ public int getOatChecksum() {+ return oat_checksum_;+ }++ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ @Override+ public int getPointerSize() {+ return pointer_size_;+ }++ public int getBootImageBegin() {+ return boot_image_begin_;+ }++ /**+ * App images currently require a boot image,+ * if the size is non zero then it is an app image header.+ * @return true if this header represents an app image+ */+ public boolean isAppImage() {+ return boot_image_size_ != 0x0;+ }++ public int getImageReservationSize() {+ return image_reservation_size_;+ }++ public int getComponentCount() {+ return component_count_;+ }++ public int getImageRoots() {+ return image_roots_;+ }++ public int getDataSize() {+ return data_size_;+ }++ public List<ArtBlock> getBlocks() {+ return blocks;+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {+ DecompressionManager.decompressOverMemory(program, blocks, monitor);++ sections.markup(program, monitor);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_10.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ //ignore, just use original name should this fail+ }++ structure.add(DWORD, "image_reservation_size_", null);+ structure.add(DWORD, "component_count_", null);+ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "image_checksum_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "boot_image_begin_", null);+ structure.add(DWORD, "boot_image_size_", null);+ structure.add(DWORD, "image_roots_", null);+ structure.add(DWORD, "pointer_size_", null);++ for (int i = 0; i < sections.getSectionList().size(); ++i) {+ structure.add(sections.getSectionList().get(i).toDataType(), "section_" + i, null);+ }+ for (int i = 0; i < image_methods_.length; ++i) {+ structure.add(QWORD, "image_method_" + i, null);+ }++ structure.add(DWORD, "data_size_", null);+ structure.add(DWORD, "blocks_offset_", null);+ structure.add(DWORD, "blocks_count_", null);+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageMethod_10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageMethod_10.javanew file mode 100644index 0000000000..793c3ffb59--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageMethod_10.java@@ -0,0 +1,32 @@+/* ###+ * 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.android.art.android10;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/image.h+ */+public enum ImageMethod_10 {+ kResolutionMethod,+ kImtConflictMethod,+ kImtUnimplementedMethod,+ kSaveAllCalleeSavesMethod,+ kSaveRefsOnlyMethod,+ kSaveRefsAndArgsMethod,+ kSaveEverythingMethod,+ kSaveEverythingMethodForClinit,+ kSaveEverythingMethodForSuspendCheck,+ kImageMethodsCount, // Number of elements in enum.+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageRoot_10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageRoot_10.javanew file mode 100644index 0000000000..315fa68b4e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageRoot_10.java@@ -0,0 +1,43 @@+/* ###+ * 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.android.art.android10;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/image.h+ */+public enum ImageRoot_10 {+ kDexCaches,+ kClassRoots,+ /** Pre-allocated OOME when throwing exception.*/+ kOomeWhenThrowingException,+ /** Pre-allocated OOME when throwing OOME. */+ kOomeWhenThrowingOome,+ /** Pre-allocated OOME when handling StackOverflowError. */+ kOomeWhenHandlingStackOverflow,+ /** Pre-allocated NoClassDefFoundError. */+ kNoClassDefFoundError,+ /** Different for boot image and app image, see aliases below. */+ kSpecialRoots,+ kImageRootsMax;++ //Aliases++ /** The class loader used to build the app image.*/+ public final static ImageRoot_10 kAppImageClassLoader = kSpecialRoots;++ /** Array of boot image objects that must be kept live. */+ public final static ImageRoot_10 kBootImageLiveObjects = kSpecialRoots;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageSections_10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageSections_10.javanew file mode 100644index 0000000000..b61d930d14--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android10/ImageSections_10.java@@ -0,0 +1,109 @@+/* ###+ * 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.android.art.android10;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/image.h+ */+public class ImageSections_10 extends ArtImageSections {+ public final static int kSectionObjects = 0;+ public final static int kSectionArtFields = 1;+ public final static int kSectionArtMethods = 2;+ public final static int kSectionRuntimeMethods = 3;+ public final static int kSectionImTables = 4;+ public final static int kSectionIMTConflictTables = 5;+ public final static int kSectionDexCacheArrays = 6;+ public final static int kSectionInternedStrings = 7;+ public final static int kSectionClassTable = 8;+ public final static int kSectionStringReferenceOffsets = 9;+ public final static int kSectionMetadata = 10;+ public final static int kSectionImageBitmap = 11;+ public final static int kSectionCount = 12; // Number of elements in enum.++ public ImageSections_10(BinaryReader reader, ArtHeader header) {+ super(reader, header);+ }++ @Override+ public int get_kSectionObjects() {+ return kSectionObjects;+ }++ @Override+ public int get_kSectionArtFields() {+ return kSectionArtFields;+ }++ @Override+ public int get_kSectionArtMethods() {+ return kSectionArtMethods;+ }++ @Override+ public int get_kSectionRuntimeMethods() {+ return kSectionRuntimeMethods;+ }++ @Override+ public int get_kSectionImTables() {+ return kSectionImTables;+ }++ @Override+ public int get_kSectionIMTConflictTables() {+ return kSectionIMTConflictTables;+ }++ @Override+ public int get_kSectionDexCacheArrays() {+ return kSectionDexCacheArrays;+ }++ @Override+ public int get_kSectionInternedStrings() {+ return kSectionInternedStrings;+ }++ @Override+ public int get_kSectionClassTable() {+ return kSectionClassTable;+ }++ @Override+ public int get_kSectionStringReferenceOffsets() {+ return kSectionStringReferenceOffsets;+ }++ @Override+ public int get_kSectionMetadata() {+ return kSectionMetadata;+ }++ @Override+ public int get_kSectionImageBitmap() {+ return kSectionImageBitmap;+ }++ @Override+ public int get_kSectionCount() {+ return kSectionCount;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/ArtHeader_11.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/ArtHeader_11.javanew file mode 100644index 0000000000..2f625b404a--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/ArtHeader_11.java@@ -0,0 +1,250 @@+/* ###+ * 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.android.art.android11;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.*;+import ghidra.file.formats.android.art.android10.ImageMethod_10;+import ghidra.file.formats.android.art.android10.ImageSections_10;+import ghidra.file.formats.android.util.DecompressionManager;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/image.h+ */+public class ArtHeader_11 extends ArtHeader {++ private int image_reservation_size_;+ private int component_count_;+ private int image_begin_;+ private int image_size_;+ private int image_checksum_;+ private int oat_checksum_;+ private int oat_file_begin_;+ private int oat_data_begin_;+ private int oat_data_end_;+ private int oat_file_end_;+ private int boot_image_begin_;+ private int boot_image_size_;+ private int boot_image_component_count_;+ private int boot_image_checksum_;+ private int image_roots_;+ private int pointer_size_;+ private long[] image_methods_ = new long[ImageMethod_10.kImageMethodsCount.ordinal()];+ private int data_size_;+ private int blocks_offset_;+ private int blocks_count_;+ private List<ArtBlock> blocks = new ArrayList<>();++ private ArtImageSections sections;++ public ArtHeader_11(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_reservation_size_ = reader.readNextInt();+ component_count_ = reader.readNextInt();+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ image_checksum_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ boot_image_begin_ = reader.readNextInt();+ boot_image_size_ = reader.readNextInt();+ boot_image_component_count_ = reader.readNextInt();+ boot_image_checksum_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ pointer_size_ = reader.readNextInt();++ sections = new ImageSections_10(reader, this);+ sections.parseSections(reader);++ parseImageMethods(reader);++ data_size_ = reader.readNextInt();+ blocks_offset_ = reader.readNextInt();+ blocks_count_ = reader.readNextInt();++ if (blocks_offset_ > 0 && blocks_count_ > 0) {+ reader.setPointerIndex(blocks_offset_);+ for (int i = 0; i < blocks_count_; ++i) {+ blocks.add(new ArtBlock(reader));+ }+ }++ reader = DecompressionManager.decompress(reader, blocks, TaskMonitor.DUMMY);++ // NOTE:+ // cannot parse the sections until after the blocks are decompressed!++ sections.parse(reader);+ }++ @Override+ public int getArtMethodCountForVersion() {+ return ImageMethod_10.kImageMethodsCount.ordinal();+ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ public int getImageChecksum_() {+ return image_checksum_;+ }++ @Override+ public int getOatChecksum() {+ return oat_checksum_;+ }++ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ @Override+ public int getPointerSize() {+ return pointer_size_;+ }++ public int getBootImageBegin() {+ return boot_image_begin_;+ }++ public int getBootImageComponentCount() {+ return boot_image_component_count_;+ }++ public int getBootImageChecksum() {+ return boot_image_checksum_;+ }++ /**+ * App images currently require a boot image,+ * if the size is non zero then it is an app image header.+ * @return true if app image+ */+ public boolean isAppImage() {+ return boot_image_size_ != 0x0;+ }++ public int getImageReservationSize() {+ return image_reservation_size_;+ }++ public int getComponentCount() {+ return component_count_;+ }++ public int getImageRoots() {+ return image_roots_;+ }++ public int getDataSize() {+ return data_size_;+ }++ public List<ArtBlock> getBlocks() {+ return blocks;+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {+ DecompressionManager.decompressOverMemory(program, blocks, monitor);++ sections.markup(program, monitor);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_11.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ //ignore+ }++ structure.add(DWORD, "image_reservation_size_", null);+ structure.add(DWORD, "component_count_", null);+ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "image_checksum_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "boot_image_begin_", null);+ structure.add(DWORD, "boot_image_size_", null);+ structure.add(DWORD, "boot_image_component_count_", null);+ structure.add(DWORD, "boot_image_checksum_", null);+ structure.add(DWORD, "image_roots_", null);+ structure.add(DWORD, "pointer_size_", null);++ for (int i = 0; i < sections.getSectionList().size(); ++i) {+ structure.add(sections.getSectionList().get(i).toDataType(), "section_" + i, null);+ }+ for (int i = 0; i < image_methods_.length; ++i) {+ structure.add(QWORD, "image_method_" + i, null);+ }++ structure.add(DWORD, "data_size_", null);+ structure.add(DWORD, "blocks_offset_", null);+ structure.add(DWORD, "blocks_count_", null);+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/BootImageLiveObjects.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/BootImageLiveObjects.javanew file mode 100644index 0000000000..525912411b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/BootImageLiveObjects.java@@ -0,0 +1,34 @@+/* ###+ * 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.android.art.android11;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android11-release/runtime/image.h+ */+public enum BootImageLiveObjects {++ /** Pre-allocated OOME when throwing exception. */+ kOomeWhenThrowingException,+ /** Pre-allocated OOME when throwing OOME. */+ kOomeWhenThrowingOome,+ /** Pre-allocated OOME when handling StackOverflowError. */+ kOomeWhenHandlingStackOverflow,+ /** Pre-allocated NoClassDefFoundError. */+ kNoClassDefFoundError,+ /** Pre-allocated sentinel for cleared weak JNI references. */+ kClearedJniWeakSentinel,+ kIntrinsicObjectsStart;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/ImageRoot_11.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/ImageRoot_11.javanew file mode 100644index 0000000000..c91c821b59--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/android11/ImageRoot_11.java@@ -0,0 +1,31 @@+/* ###+ * 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.android.art.android11;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android11-release/runtime/image.h+ */+public enum ImageRoot_11 {+ kDexCaches, kClassRoots, kSpecialRoots, kImageRootsMax;++ //Aliases++ /** The class loader used to build the app image.*/+ public final static ImageRoot_11 kAppImageClassLoader = kSpecialRoots;++ /** Array of boot image objects that must be kept live. */+ public final static ImageRoot_11 kBootImageLiveObjects = kSpecialRoots;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/kitkat/ArtHeader_KitKat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/kitkat/ArtHeader_KitKat.javanew file mode 100644index 0000000000..45106f2bec--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/kitkat/ArtHeader_KitKat.java@@ -0,0 +1,176 @@+/* ###+ * 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.android.art.kitkat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * @see https://android.googlesource.com/platform/art/+/refs/heads/kitkat-release/runtime/image.cc+ */+public class ArtHeader_KitKat extends ArtHeader {++ protected int image_begin_;+ protected int image_size_;+ protected int image_bitmap_offset_;+ protected int image_bitmap_size_;+ protected int oat_checksum_;+ protected int oat_file_begin_;+ protected int oat_data_begin_;+ protected int oat_data_end_;+ protected int oat_file_end_;+ protected int image_roots_;++ public ArtHeader_KitKat(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ image_bitmap_offset_ = reader.readNextInt();+ image_bitmap_size_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ /**+ * Image bitmap offset in the file.+ */+ public int getImageBitmapOffset() {+ return image_bitmap_offset_;+ }++ /**+ * Size of the image bitmap.+ */+ public int getImageBitmapSize() {+ return image_bitmap_size_;+ }++ /**+ * Checksum of the oat file we link to for load time sanity check.+ */+ public int getOatChecksum() {+ return oat_checksum_;+ }++ /**+ * Start address for oat file. Will be before oat_data_begin_ for .so files.+ */+ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ /**+ * Required oat address expected by image Method::GetCode() pointers.+ */+ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ /**+ * End of oat data address range for this image file.+ */+ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ /**+ * End of oat file address range. will be after oat_data_end_ for+ * .so files. Used for positioning a following alloc spaces.+ */+ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ /**+ * Absolute address of an Object[] of objects needed to reinitialize from an image.+ */+ public int getImageRoots() {+ return image_roots_;+ }++ @Override+ public int getPointerSize() {+ return -1; //unsupported+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {+ //do nothing for now+ }++ @Override+ public int getArtMethodCountForVersion() {+ throw new UnsupportedOperationException();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_KitKat.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ }++ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "image_bitmap_offset_", null);+ structure.add(DWORD, "image_bitmap_size_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "image_roots_", null);++ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/kitkat/ImageRoot_KitKat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/kitkat/ImageRoot_KitKat.javanew file mode 100644index 0000000000..cf871d2ae1--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/kitkat/ImageRoot_KitKat.java@@ -0,0 +1,30 @@+/* ###+ * 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.android.art.kitkat;++/**+ * @see https://android.googlesource.com/platform/art/+/refs/heads/kitkat-release/runtime/image.h+ */+public enum ImageRoot_KitKat {+ kResolutionMethod,+ kCalleeSaveMethod,+ kRefsOnlySaveMethod,+ kRefsAndArgsSaveMethod,+ kOatLocation,+ kDexCaches,+ kClassRoots,+ kImageRootsMax,+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ArtHeader_Lollipop.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ArtHeader_Lollipop.javanew file mode 100644index 0000000000..73861ccb85--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ArtHeader_Lollipop.java@@ -0,0 +1,153 @@+/* ###+ * 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.android.art.lollipop;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * @see https://android.googlesource.com/platform/art/+/refs/heads/lollipop-release/runtime/image.cc+ */+public class ArtHeader_Lollipop extends ArtHeader {++ protected int image_begin_;+ protected int image_size_;+ protected int image_bitmap_offset_;+ protected int image_bitmap_size_;+ protected int oat_checksum_;+ protected int oat_file_begin_;+ protected int oat_data_begin_;+ protected int oat_data_end_;+ protected int oat_file_end_;+ protected int patch_delta_;+ protected int image_roots_;++ public ArtHeader_Lollipop(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ image_bitmap_offset_ = reader.readNextInt();+ image_bitmap_size_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ patch_delta_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ /**+ * The total delta that this image has been patched.+ */+ public int getPatchDelta() {+ return patch_delta_;+ }++ /**+ * Checksum of the oat file we link to for load time sanity check.+ */+ @Override+ public int getOatChecksum() {+ return oat_checksum_;+ }++ @Override+ public int getPointerSize() {+ return -1; //unsupported+ }++ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {+ //do nothing for now+ }++ @Override+ public int getArtMethodCountForVersion() {+ throw new UnsupportedOperationException();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_Lollipop.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ }++ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "image_bitmap_offset_", null);+ structure.add(DWORD, "image_bitmap_size_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "patch_delta_", null);+ structure.add(DWORD, "image_roots_", null);++ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ArtHeader_LollipopMR1WFC.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ArtHeader_LollipopMR1WFC.javanew file mode 100644index 0000000000..03d597e387--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ArtHeader_LollipopMR1WFC.java@@ -0,0 +1,153 @@+/* ###+ * 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.android.art.lollipop;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * @see https://android.googlesource.com/platform/art/+/lollipop-mr1-wfc-release/runtime/image.h+ */+public class ArtHeader_LollipopMR1WFC extends ArtHeader {++ protected int image_begin_;+ protected int image_size_;+ protected int image_bitmap_offset_;+ protected int image_bitmap_size_;+ protected int oat_checksum_;+ protected int oat_file_begin_;+ protected int oat_data_begin_;+ protected int oat_data_end_;+ protected int oat_file_end_;+ protected int patch_delta_;+ protected int image_roots_;+ protected int compile_pic_;++ public ArtHeader_LollipopMR1WFC(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ image_bitmap_offset_ = reader.readNextInt();+ image_bitmap_size_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ patch_delta_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ compile_pic_ = reader.readNextInt();+ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ /**+ * Boolean (0 or 1) to denote if the image was compiled with --compile-pic option.+ */+ public int getCompilePic() {+ return compile_pic_;+ }++ @Override+ public int getOatChecksum() {+ return oat_checksum_;+ }++ @Override+ public int getPointerSize() {+ return -1; //unsupported+ }++ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {++ }++ @Override+ public int getArtMethodCountForVersion() {+ throw new UnsupportedOperationException();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_LollipopMR1WFC.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ }++ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "image_bitmap_offset_", null);+ structure.add(DWORD, "image_bitmap_size_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "patch_delta_", null);+ structure.add(DWORD, "image_roots_", null);+ structure.add(DWORD, "compile_pic_", null);++ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ImageRoot_Lollipop.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ImageRoot_Lollipop.javanew file mode 100644index 0000000000..c979bf59c1--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ImageRoot_Lollipop.java@@ -0,0 +1,31 @@+/* ###+ * 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.android.art.lollipop;++/**+ * @see https://android.googlesource.com/platform/art/+/refs/heads/lollipop-release/runtime/image.h+ */+public enum ImageRoot_Lollipop {+ kResolutionMethod,+ kImtConflictMethod,+ kDefaultImt,+ kCalleeSaveMethod,+ kRefsOnlySaveMethod,+ kRefsAndArgsSaveMethod,+ kDexCaches,+ kClassRoots,+ kImageRootsMax,+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ImageRoot_LollipopMR1WRC.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ImageRoot_LollipopMR1WRC.javanew file mode 100644index 0000000000..28d713e5ad--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/lollipop/ImageRoot_LollipopMR1WRC.java@@ -0,0 +1,32 @@+/* ###+ * 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.android.art.lollipop;++/**+ * @see https://android.googlesource.com/platform/art/+/lollipop-mr1-wfc-release/runtime/image.h+ */+public enum ImageRoot_LollipopMR1WRC {+ kResolutionMethod,+ kImtConflictMethod,+ kImtUnimplementedMethod,+ kDefaultImt,+ kCalleeSaveMethod,+ kRefsOnlySaveMethod,+ kRefsAndArgsSaveMethod,+ kDexCaches,+ kClassRoots,+ kImageRootsMax,+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ArtHeader_Marshmallow.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ArtHeader_Marshmallow.javanew file mode 100644index 0000000000..24e2a337b1--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ArtHeader_Marshmallow.java@@ -0,0 +1,175 @@+/* ###+ * 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.android.art.marshmallow;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * @see https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/image.h+ */+public class ArtHeader_Marshmallow extends ArtHeader {++ protected int image_begin_;+ protected int image_size_;+ protected int oat_checksum_;+ protected int oat_file_begin_;+ protected int oat_data_begin_;+ protected int oat_data_end_;+ protected int oat_file_end_;+ protected int patch_delta_;+ protected int image_roots_;+ protected int pointer_size_;+ protected int compile_pic_;++ protected long[] image_methods_ =+ new long[ImageMethod_Marshmallow.kImageMethodsCount.ordinal()];++ protected ArtImageSections sections;++ public ArtHeader_Marshmallow(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ patch_delta_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ pointer_size_ = reader.readNextInt();+ compile_pic_ = reader.readNextInt();++ sections = new ImageSections_Marshmallow(reader, this);+ sections.parseSections(reader);++ for (int i = 0; i < image_methods_.length; ++i) {+ image_methods_[i] = reader.readNextLong();+ }++ sections.parse(reader);+ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ @Override+ public int getPointerSize() {+ return pointer_size_;+ }++ /**+ * Image methods.+ */+ public long[] getImageMethods() {+ return image_methods_;+ }++ /**+ * Checksum of the oat file we link to for load time sanity check.+ */+ @Override+ public int getOatChecksum() {+ return oat_checksum_;+ }++ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {++ sections.markup(program, monitor);+ }++ @Override+ public int getArtMethodCountForVersion() {+ throw new UnsupportedOperationException();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_Marshmallow.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ }++ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "patch_delta_", null);+ structure.add(DWORD, "image_roots_", null);+ structure.add(DWORD, "pointer_size_", null);+ structure.add(DWORD, "compile_pic_", null);++ for (int i = 0; i < sections.getSectionList().size(); ++i) {+ structure.add(sections.getSectionList().get(i).toDataType(), "section_" + i, null);+ }+ for (int i = 0; i < image_methods_.length; ++i) {+ structure.add(QWORD, "image_method_" + i, null);+ }+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageMethod_Marshmallow.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageMethod_Marshmallow.javanew file mode 100644index 0000000000..698e0c8908--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageMethod_Marshmallow.java@@ -0,0 +1,29 @@+/* ###+ * 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.android.art.marshmallow;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/image.h+ */+public enum ImageMethod_Marshmallow {+ kResolutionMethod,+ kImtConflictMethod,+ kImtUnimplementedMethod,+ kCalleeSaveMethod,+ kRefsOnlySaveMethod,+ kRefsAndArgsSaveMethod,+ kImageMethodsCount, // Number of elements in enum.+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageRoot_Marshmallow.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageRoot_Marshmallow.javanew file mode 100644index 0000000000..4cc6b89304--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageRoot_Marshmallow.java@@ -0,0 +1,31 @@+/* ###+ * 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.android.art.marshmallow;++/**+ * @see https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/image.h+ */+public enum ImageRoot_Marshmallow {+ kResolutionMethod,+ kImtConflictMethod,+ kDefaultImt,+ kCalleeSaveMethod,+ kRefsOnlySaveMethod,+ kRefsAndArgsSaveMethod,+ kDexCaches,+ kClassRoots,+ kImageRootsMax,+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageSections_Marshmallow.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageSections_Marshmallow.javanew file mode 100644index 0000000000..3bf5606ff0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/marshmallow/ImageSections_Marshmallow.java@@ -0,0 +1,98 @@+/* ###+ * 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.android.art.marshmallow;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;++public class ImageSections_Marshmallow extends ArtImageSections {+ public final static int kSectionObjects = 0;+ public final static int kSectionArtFields = 1;+ public final static int kSectionArtMethods = 2;+ public final static int kSectionInternedStrings = 3;+ public final static int kSectionImageBitmap = 4;+ public final static int kSectionCount = 5; // Number of elements in enum.++ public ImageSections_Marshmallow(BinaryReader reader, ArtHeader header) {+ super(reader, header);+ }++ @Override+ public int get_kSectionObjects() {+ return kSectionObjects;+ }++ @Override+ public int get_kSectionArtFields() {+ return kSectionArtFields;+ }++ @Override+ public int get_kSectionArtMethods() {+ return kSectionArtMethods;+ }++ @Override+ public int get_kSectionRuntimeMethods() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionImTables() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionIMTConflictTables() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionDexCacheArrays() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionInternedStrings() {+ return kSectionInternedStrings;+ }++ @Override+ public int get_kSectionClassTable() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionStringReferenceOffsets() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionMetadata() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionImageBitmap() {+ return kSectionImageBitmap;+ }++ @Override+ public int get_kSectionCount() {+ return kSectionCount;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ArtHeader_Nougat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ArtHeader_Nougat.javanew file mode 100644index 0000000000..6c8c64d0f4--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ArtHeader_Nougat.java@@ -0,0 +1,251 @@+/* ###+ * 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.android.art.nougat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.*;+import ghidra.file.formats.android.util.DecompressionManager;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/nougat-release/runtime/image.h+ * https://android.googlesource.com/platform/art/+/nougat-release/runtime/image.cc+ */+public class ArtHeader_Nougat extends ArtHeader implements ArtCompression {++ protected int image_begin_;+ protected int image_size_;+ protected int oat_checksum_;+ protected int oat_file_begin_;+ protected int oat_data_begin_;+ protected int oat_data_end_;+ protected int oat_file_end_;+ protected int boot_image_begin_;+ protected int boot_image_size_;+ protected int boot_oat_begin_;+ protected int boot_oat_size_;+ protected int patch_delta_;+ protected int image_roots_;+ protected int pointer_size_;+ protected int compile_pic_;+ protected int is_pic_;+ protected int storage_mode_;+ protected int data_size_;++ protected ArtImageSections sections;++ private long _compressedOffset;++ public ArtHeader_Nougat(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ protected ArtImageSections getImageSections(BinaryReader reader) {+ return new ImageSections_Nougat(reader, this);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ boot_image_begin_ = reader.readNextInt();+ boot_image_size_ = reader.readNextInt();+ boot_oat_begin_ = reader.readNextInt();+ boot_oat_size_ = reader.readNextInt();+ patch_delta_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ pointer_size_ = reader.readNextInt();+ compile_pic_ = reader.readNextInt();+ is_pic_ = reader.readNextInt();++ sections = getImageSections(reader);++ sections.parseSections(reader);+ parseImageMethods(reader);++ storage_mode_ = reader.readNextInt();+ data_size_ = reader.readNextInt();++ //The compressed offset is immediately following this header.+ _compressedOffset = reader.getPointerIndex();++ reader = DecompressionManager.decompress(reader, this, TaskMonitor.DUMMY);++ sections.parse(reader);+ }++ @Override+ public int getArtMethodCountForVersion() {+ return ImageMethod_Nougat.kImageMethodsCount.ordinal();+ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ /**+ * Boot oat begin and end (app image headers only).+ * @return the boot oat begin address+ */+ public int getBootOatBegin() {+ return boot_oat_begin_;+ }++ /**+ * Boot oat begin and end (app image headers only).+ * @return the boot oat size+ */+ public int getBootOatSize() {+ return boot_oat_size_;+ }++ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ /**+ * Boolean (0 or 1) to denote if the image can be mapped at a random address,+ * this only refers to the .art file.+ * Currently, app oat files do not depend on their app image.+ * There are no pointers from the app oat code to the app image.+ * @return true of position independent code, or false if dependent.+ */+ public int getIsPic() {+ return is_pic_;+ }++ @Override+ public ArtStorageMode getStorageMode() throws UnknownArtStorageModeException {+ return ArtStorageMode.get(storage_mode_);+ }++ @Override+ public long getCompressedOffset() {+ return _compressedOffset;+ }++ @Override+ public int getCompressedSize() {+ return data_size_;+ }++ @Override+ public long getDecompressedOffset() {+ return getCompressedOffset();+ }++ @Override+ public int getDecompressedSize() {+ return image_size_;+ }++ /**+ * Checksum of the oat file we link to for load time sanity check.+ */+ @Override+ public int getOatChecksum() {+ return oat_checksum_;+ }++ @Override+ public int getPointerSize() {+ return pointer_size_;+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {+ DecompressionManager.decompressOverMemory(program, this, monitor);++ sections.markup(program, monitor);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_Nougat.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ //ignore, just use original name should this fail+ }++ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "boot_image_begin_", null);+ structure.add(DWORD, "boot_image_size_", null);+ structure.add(DWORD, "boot_oat_begin_", null);+ structure.add(DWORD, "boot_oat_size_", null);+ structure.add(DWORD, "patch_delta_", null);+ structure.add(DWORD, "image_roots_", null);+ structure.add(DWORD, "pointer_size_", null);+ structure.add(DWORD, "compile_pic_", null);+ structure.add(DWORD, "is_pic_", null);++ for (int i = 0; i < sections.getSectionList().size(); ++i) {+ structure.add(sections.getSectionList().get(i).toDataType(), "section_" + i, null);+ }+ for (int i = 0; i < imageMethodsList.size(); ++i) {+ structure.add(QWORD, "image_method_" + i, null);+ }+ structure.add(DWORD, "storage_mode_", null);+ structure.add(DWORD, "data_size_", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ArtHeader_NougatMR2Pixel.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ArtHeader_NougatMR2Pixel.javanew file mode 100644index 0000000000..31bbf6bf37--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ArtHeader_NougatMR2Pixel.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.android.art.nougat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.ArtImageSections;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/nougat-mr2-pixel-release/runtime/image.h+ */+public class ArtHeader_NougatMR2Pixel extends ArtHeader_Nougat {++ public ArtHeader_NougatMR2Pixel(BinaryReader reader) throws IOException {+ super(reader);+ }++ protected ArtImageSections getImageSections(BinaryReader reader) {+ return new ImageSections_NougatMR2Pixel(reader, this);+ }++ @Override+ public int getArtMethodCountForVersion() {+ return ImageMethod_Nougat.kImageMethodsCount.ordinal();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ String className = StructConverterUtil.parseName(ArtHeader_NougatMR2Pixel.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ //ignore+ }+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageMethod_Nougat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageMethod_Nougat.javanew file mode 100644index 0000000000..fa635f90ef--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageMethod_Nougat.java@@ -0,0 +1,29 @@+/* ###+ * 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.android.art.nougat;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/image.h+ */+public enum ImageMethod_Nougat {+ kResolutionMethod,+ kImtConflictMethod,+ kImtUnimplementedMethod,+ kCalleeSaveMethod,+ kRefsOnlySaveMethod,+ kRefsAndArgsSaveMethod,+ kImageMethodsCount, // Number of elements in enum.+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageRoot_Nougat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageRoot_Nougat.javanew file mode 100644index 0000000000..0a362685c0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageRoot_Nougat.java@@ -0,0 +1,23 @@+/* ###+ * 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.android.art.nougat;++/**+ * @see https://android.googlesource.com/platform/art/+/nougat-release/runtime/image.h+ */+public enum ImageRoot_Nougat {+ kDexCaches, kClassRoots, kImageRootsMax,+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageSections_Nougat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageSections_Nougat.javanew file mode 100644index 0000000000..3452f4ff8a--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageSections_Nougat.java@@ -0,0 +1,102 @@+/* ###+ * 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.android.art.nougat;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;++public class ImageSections_Nougat extends ArtImageSections {+ public final static int kSectionObjects = 0;+ public final static int kSectionArtFields = 1;+ public final static int kSectionArtMethods = 2;+ public final static int kSectionRuntimeMethods = 3;+ public final static int kSectionIMTConflictTables = 4;+ public final static int kSectionDexCacheArrays = 5;+ public final static int kSectionInternedStrings = 6;+ public final static int kSectionClassTable = 7;+ public final static int kSectionImageBitmap = 8;+ public final static int kSectionCount = 9; // Number of elements in enum.++ public ImageSections_Nougat(BinaryReader reader, ArtHeader header) {+ super(reader, header);+ }++ @Override+ public int get_kSectionObjects() {+ return kSectionObjects;+ }++ @Override+ public int get_kSectionArtFields() {+ return kSectionArtFields;+ }++ @Override+ public int get_kSectionArtMethods() {+ return kSectionArtMethods;+ }++ @Override+ public int get_kSectionRuntimeMethods() {+ return kSectionRuntimeMethods;+ }++ @Override+ public int get_kSectionImTables() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionIMTConflictTables() {+ return kSectionIMTConflictTables;+ }++ @Override+ public int get_kSectionDexCacheArrays() {+ return kSectionDexCacheArrays;+ }++ @Override+ public int get_kSectionInternedStrings() {+ return kSectionInternedStrings;+ }++ @Override+ public int get_kSectionClassTable() {+ return kSectionClassTable;+ }++ @Override+ public int get_kSectionStringReferenceOffsets() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionMetadata() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionImageBitmap() {+ return kSectionImageBitmap;+ }++ @Override+ public int get_kSectionCount() {+ return kSectionCount;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageSections_NougatMR2Pixel.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageSections_NougatMR2Pixel.javanew file mode 100644index 0000000000..8886244da8--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/nougat/ImageSections_NougatMR2Pixel.java@@ -0,0 +1,103 @@+/* ###+ * 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.android.art.nougat;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;++public class ImageSections_NougatMR2Pixel extends ArtImageSections {+ public final static int kSectionObjects = 0;+ public final static int kSectionArtFields = 1;+ public final static int kSectionArtMethods = 2;+ public final static int kSectionRuntimeMethods = 3;+ public final static int kSectionImTables = 4;+ public final static int kSectionIMTConflictTables = 5;+ public final static int kSectionDexCacheArrays = 6;+ public final static int kSectionInternedStrings = 7;+ public final static int kSectionClassTable = 8;+ public final static int kSectionImageBitmap = 9;+ public final static int kSectionCount = 10; // Number of elements in enum.++ public ImageSections_NougatMR2Pixel(BinaryReader reader, ArtHeader header) {+ super(reader, header);+ }++ @Override+ public int get_kSectionObjects() {+ return kSectionObjects;+ }++ @Override+ public int get_kSectionArtFields() {+ return kSectionArtFields;+ }++ @Override+ public int get_kSectionArtMethods() {+ return kSectionArtMethods;+ }++ @Override+ public int get_kSectionRuntimeMethods() {+ return kSectionRuntimeMethods;+ }++ @Override+ public int get_kSectionImTables() {+ return kSectionImTables;+ }++ @Override+ public int get_kSectionIMTConflictTables() {+ return kSectionIMTConflictTables;+ }++ @Override+ public int get_kSectionDexCacheArrays() {+ return kSectionDexCacheArrays;+ }++ @Override+ public int get_kSectionInternedStrings() {+ return kSectionInternedStrings;+ }++ @Override+ public int get_kSectionClassTable() {+ return kSectionClassTable;+ }++ @Override+ public int get_kSectionStringReferenceOffsets() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionMetadata() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionImageBitmap() {+ return kSectionImageBitmap;+ }++ @Override+ public int get_kSectionCount() {+ return kSectionCount;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ArtHeader_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ArtHeader_Oreo.javanew file mode 100644index 0000000000..d3837fcce8--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ArtHeader_Oreo.java@@ -0,0 +1,60 @@+/* ###+ * 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.android.art.oreo;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.ArtImageSections;+import ghidra.file.formats.android.art.nougat.ArtHeader_NougatMR2Pixel;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/oreo-release/runtime/image.h+ */+public class ArtHeader_Oreo extends ArtHeader_NougatMR2Pixel {++ public ArtHeader_Oreo(BinaryReader reader) throws IOException {+ super(reader);+ }++ protected ArtImageSections getImageSections(BinaryReader reader) {+ return new ImageSections_Oreo(reader, this);+ }++ @Override+ public int getArtMethodCountForVersion() {+ return ImageMethod_Oreo.kImageMethodsCount.ordinal();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ String className = StructConverterUtil.parseName(ArtHeader_Oreo.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ //ignore+ }+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ArtHeader_OreoMR1.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ArtHeader_OreoMR1.javanew file mode 100644index 0000000000..e61493ad68--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ArtHeader_OreoMR1.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.android.art.oreo;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.ArtImageSections;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/oreo-mr1-release/runtime/image.h+ */+public class ArtHeader_OreoMR1 extends ArtHeader_Oreo {++ public ArtHeader_OreoMR1(BinaryReader reader) throws IOException {+ super(reader);+ }++ protected ArtImageSections getImageSections(BinaryReader reader) {+ return new ImageSections_OreoMR1(reader, this);+ }++ @Override+ public int getArtMethodCountForVersion() {+ return ImageMethod_Oreo.kImageMethodsCount.ordinal();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ String className = StructConverterUtil.parseName(ArtHeader_OreoMR1.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ //ignore+ }+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageMethod_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageMethod_Oreo.javanew file mode 100644index 0000000000..34b84ca9de--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageMethod_Oreo.java@@ -0,0 +1,30 @@+/* ###+ * 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.android.art.oreo;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-release/runtime/image.h+ */+public enum ImageMethod_Oreo {+ kResolutionMethod,+ kImtConflictMethod,+ kImtUnimplementedMethod,+ kSaveAllCalleeSavesMethod,+ kSaveRefsOnlyMethod,+ kSaveRefsAndArgsMethod,+ kSaveEverythingMethod,+ kImageMethodsCount, // Number of elements in enum.+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageRoot_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageRoot_Oreo.javanew file mode 100644index 0000000000..fee0334063--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageRoot_Oreo.java@@ -0,0 +1,26 @@+/* ###+ * 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.android.art.oreo;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-release/runtime/image.h+ */+public enum ImageRoot_Oreo {+ kDexCaches,+ kClassRoots,+ kClassLoader, // App image only.+ kImageRootsMax,+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageSections_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageSections_Oreo.javanew file mode 100644index 0000000000..c046b0050e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageSections_Oreo.java@@ -0,0 +1,117 @@+/* ###+ * 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.android.art.oreo;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;++public class ImageSections_Oreo extends ArtImageSections {+ public final static int kSectionObjects = 0;+ public final static int kSectionArtFields = 1;+ public final static int kSectionArtMethods = 2;+ public final static int kSectionRuntimeMethods = 3;+ public final static int kSectionImTables = 4;+ public final static int kSectionIMTConflictTables = 5;+ public final static int kSectionDexCacheArrays = 6;+ public final static int kSectionInternedStrings = 7;+ public final static int kSectionClassTable = 8;+ public final static int kSectionImageBitmap = 9;+ public final static int kSectionCount = 10; // Number of elements in enum.++ enum ImageSections {+ kSectionObjects,+ kSectionArtFields,+ kSectionArtMethods,+ kSectionRuntimeMethods,+ kSectionImTables,+ kSectionIMTConflictTables,+ kSectionDexCacheArrays,+ kSectionInternedStrings,+ kSectionClassTable,+ kSectionImageBitmap,+ kSectionCount, // Number of elements in enum.+ };++ public ImageSections_Oreo(BinaryReader reader, ArtHeader header) {+ super(reader, header);+ }++ @Override+ public int get_kSectionObjects() {+ return kSectionObjects;+ }++ @Override+ public int get_kSectionArtFields() {+ return kSectionArtFields;+ }++ @Override+ public int get_kSectionArtMethods() {+ return kSectionArtMethods;+ }++ @Override+ public int get_kSectionRuntimeMethods() {+ return kSectionRuntimeMethods;+ }++ @Override+ public int get_kSectionImTables() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionIMTConflictTables() {+ return kSectionIMTConflictTables;+ }++ @Override+ public int get_kSectionDexCacheArrays() {+ return kSectionDexCacheArrays;+ }++ @Override+ public int get_kSectionInternedStrings() {+ return kSectionInternedStrings;+ }++ @Override+ public int get_kSectionClassTable() {+ return kSectionClassTable;+ }++ @Override+ public int get_kSectionStringReferenceOffsets() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionMetadata() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionImageBitmap() {+ return kSectionImageBitmap;+ }++ @Override+ public int get_kSectionCount() {+ return kSectionCount;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageSections_OreoMR1.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageSections_OreoMR1.javanew file mode 100644index 0000000000..657de24612--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/oreo/ImageSections_OreoMR1.java@@ -0,0 +1,103 @@+/* ###+ * 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.android.art.oreo;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;++public class ImageSections_OreoMR1 extends ArtImageSections {+ public final static int kSectionObjects = 0;+ public final static int kSectionArtFields = 1;+ public final static int kSectionArtMethods = 2;+ public final static int kSectionRuntimeMethods = 3;+ public final static int kSectionImTables = 4;+ public final static int kSectionIMTConflictTables = 5;+ public final static int kSectionDexCacheArrays = 6;+ public final static int kSectionInternedStrings = 7;+ public final static int kSectionClassTable = 8;+ public final static int kSectionImageBitmap = 9;+ public final static int kSectionCount = 10; // Number of elements in enum.++ public ImageSections_OreoMR1(BinaryReader reader, ArtHeader header) {+ super(reader, header);+ }++ @Override+ public int get_kSectionObjects() {+ return kSectionObjects;+ }++ @Override+ public int get_kSectionArtFields() {+ return kSectionArtFields;+ }++ @Override+ public int get_kSectionArtMethods() {+ return kSectionArtMethods;+ }++ @Override+ public int get_kSectionRuntimeMethods() {+ return kSectionRuntimeMethods;+ }++ @Override+ public int get_kSectionImTables() {+ return kSectionImTables;+ }++ @Override+ public int get_kSectionIMTConflictTables() {+ return kSectionIMTConflictTables;+ }++ @Override+ public int get_kSectionDexCacheArrays() {+ return kSectionDexCacheArrays;+ }++ @Override+ public int get_kSectionInternedStrings() {+ return kSectionInternedStrings;+ }++ @Override+ public int get_kSectionClassTable() {+ return kSectionClassTable;+ }++ @Override+ public int get_kSectionStringReferenceOffsets() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionMetadata() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionImageBitmap() {+ return kSectionImageBitmap;+ }++ @Override+ public int get_kSectionCount() {+ return kSectionCount;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ArtHeader_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ArtHeader_Pie.javanew file mode 100644index 0000000000..ea3c5bff2f--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ArtHeader_Pie.java@@ -0,0 +1,244 @@+/* ###+ * 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.android.art.pie;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.art.*;+import ghidra.file.formats.android.util.DecompressionManager;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.listing.Program;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/image.h+ */+public class ArtHeader_Pie extends ArtHeader implements ArtCompression {++ protected int image_begin_;+ protected int image_size_;+ protected int oat_checksum_;+ protected int oat_file_begin_;+ protected int oat_data_begin_;+ protected int oat_data_end_;+ protected int oat_file_end_;+ private int boot_image_begin_;+ private int boot_image_size_;+ private int boot_oat_begin_;+ private int boot_oat_size_;+ protected int patch_delta_;+ protected int image_roots_;+ protected int pointer_size_;+ protected int compile_pic_;+ private int is_pic_;++ protected long[] image_methods_ = new long[ImageMethod_Pie.kImageMethodsCount.ordinal()];+ private int storage_mode_;+ private int data_size_;++ private ArtImageSections sections;++ private long _compressedOffset;++ public ArtHeader_Pie(BinaryReader reader) throws IOException {+ super(reader);+ parse(reader);+ }++ @Override+ protected void parse(BinaryReader reader) throws IOException {+ image_begin_ = reader.readNextInt();+ image_size_ = reader.readNextInt();+ oat_checksum_ = reader.readNextInt();+ oat_file_begin_ = reader.readNextInt();+ oat_data_begin_ = reader.readNextInt();+ oat_data_end_ = reader.readNextInt();+ oat_file_end_ = reader.readNextInt();+ boot_image_begin_ = reader.readNextInt();+ boot_image_size_ = reader.readNextInt();+ boot_oat_begin_ = reader.readNextInt();+ boot_oat_size_ = reader.readNextInt();+ patch_delta_ = reader.readNextInt();+ image_roots_ = reader.readNextInt();+ pointer_size_ = reader.readNextInt();+ compile_pic_ = reader.readNextInt();+ is_pic_ = reader.readNextInt();++ sections = new ImageSections_Pie(reader, this);+ sections.parseSections(reader);+ parseImageMethods(reader);++ storage_mode_ = reader.readNextInt();+ data_size_ = reader.readNextInt();++ _compressedOffset = reader.getPointerIndex();++ reader = DecompressionManager.decompress(reader, this, TaskMonitor.DUMMY);++ // NOTE:+ // cannot parse the sections until after the blocks are decompressed!++ sections.parse(reader);++ }++ @Override+ public int getImageBegin() {+ return image_begin_;+ }++ @Override+ public int getImageSize() {+ return image_size_;+ }++ @Override+ public int getOatChecksum() {+ return oat_checksum_;+ }++ @Override+ public int getOatFileBegin() {+ return oat_file_begin_;+ }++ @Override+ public int getOatFileEnd() {+ return oat_file_end_;+ }++ @Override+ public int getOatDataBegin() {+ return oat_data_begin_;+ }++ @Override+ public int getOatDataEnd() {+ return oat_data_end_;+ }++ public int getBootOatBegin() {+ return boot_oat_begin_;+ }++ public int getBootOatSize() {+ return boot_oat_size_;+ }++ public int getBootImageBegin() {+ return boot_image_begin_;+ }++ public int getBootImageSize() {+ return boot_image_size_;+ }++ public int isPIC() {+ return is_pic_;+ }++ public int getCompilePIC() {+ return compile_pic_;+ }++ @Override+ public ArtStorageMode getStorageMode() throws UnknownArtStorageModeException {+ return ArtStorageMode.get(storage_mode_);+ }++ @Override+ public long getCompressedOffset() {+ return _compressedOffset;+ }++ @Override+ public int getCompressedSize() {+ return data_size_;+ }++ @Override+ public long getDecompressedOffset() {+ return getCompressedOffset();+ }++ @Override+ public int getDecompressedSize() {+ return image_size_;+ }++ @Override+ public int getPointerSize() {+ return pointer_size_;+ }++ @Override+ public void markup(Program program, TaskMonitor monitor) throws Exception {+ DecompressionManager.decompressOverMemory(program, this, monitor);++ sections.markup(program, monitor);+ }++ @Override+ public int getArtMethodCountForVersion() {+ return ImageMethod_Pie.kImageMethodsCount.ordinal();+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();++ String className = StructConverterUtil.parseName(ArtHeader_Pie.class);+ try {+ structure.setName(className);+ }+ catch (InvalidNameException e) {+ //ignore+ }++ structure.add(DWORD, "image_begin_", null);+ structure.add(DWORD, "image_size_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, "oat_file_begin_", null);+ structure.add(DWORD, "oat_data_begin_", null);+ structure.add(DWORD, "oat_data_end_", null);+ structure.add(DWORD, "oat_file_end_", null);+ structure.add(DWORD, "boot_image_begin_", null);+ structure.add(DWORD, "boot_image_size_", null);+ structure.add(DWORD, "boot_oat_begin_", null);+ structure.add(DWORD, "boot_oat_size_", null);+ structure.add(DWORD, "patch_delta_", null);+ structure.add(DWORD, "image_roots_", null);+ structure.add(DWORD, "pointer_size_", null);+ structure.add(DWORD, "compile_pic_", null);+ structure.add(DWORD, "is_pic_", null);++ for (int i = 0; i < sections.getSectionList().size(); ++i) {+ structure.add(sections.getSectionList().get(i).toDataType(), "section_" + i, null);+ }+ for (int i = 0; i < image_methods_.length; ++i) {+ structure.add(QWORD, "image_method_" + i, null);+ }+ structure.add(DWORD, "storage_mode_", null);+ structure.add(DWORD, "data_size_", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageMethod_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageMethod_Pie.javanew file mode 100644index 0000000000..dc6103b4c7--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageMethod_Pie.java@@ -0,0 +1,32 @@+/* ###+ * 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.android.art.pie;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/image.h+ */+public enum ImageMethod_Pie {+ kResolutionMethod,+ kImtConflictMethod,+ kImtUnimplementedMethod,+ kSaveAllCalleeSavesMethod,+ kSaveRefsOnlyMethod,+ kSaveRefsAndArgsMethod,+ kSaveEverythingMethod,+ kSaveEverythingMethodForClinit,+ kSaveEverythingMethodForSuspendCheck,+ kImageMethodsCount, // Number of elements in enum.+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageRoot_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageRoot_Pie.javanew file mode 100644index 0000000000..9cfca767e5--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageRoot_Pie.java@@ -0,0 +1,26 @@+/* ###+ * 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.android.art.pie;++/**+ * https://android.googlesource.com/platform/art/+/nougat-release/runtime/image.h+ */+public enum ImageRoot_Pie {+ kDexCaches,+ kClassRoots,+ kClassLoader, // App image only.+ kImageRootsMax,+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageSections_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageSections_Pie.javanew file mode 100644index 0000000000..3cf9f8beb0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/pie/ImageSections_Pie.java@@ -0,0 +1,103 @@+/* ###+ * 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.android.art.pie;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.ArtHeader;+import ghidra.file.formats.android.art.ArtImageSections;++public class ImageSections_Pie extends ArtImageSections {+ public final static int kSectionObjects = 0;+ public final static int kSectionArtFields = 1;+ public final static int kSectionArtMethods = 2;+ public final static int kSectionRuntimeMethods = 3;+ public final static int kSectionImTables = 4;+ public final static int kSectionIMTConflictTables = 5;+ public final static int kSectionDexCacheArrays = 6;+ public final static int kSectionInternedStrings = 7;+ public final static int kSectionClassTable = 8;+ public final static int kSectionImageBitmap = 9;+ public final static int kSectionCount = 10; // Number of elements in enum.++ public ImageSections_Pie(BinaryReader reader, ArtHeader header) {+ super(reader, header);+ }++ @Override+ public int get_kSectionObjects() {+ return kSectionObjects;+ }++ @Override+ public int get_kSectionArtFields() {+ return kSectionArtFields;+ }++ @Override+ public int get_kSectionArtMethods() {+ return kSectionArtMethods;+ }++ @Override+ public int get_kSectionRuntimeMethods() {+ return kSectionRuntimeMethods;+ }++ @Override+ public int get_kSectionImTables() {+ return kSectionImTables;+ }++ @Override+ public int get_kSectionIMTConflictTables() {+ return kSectionIMTConflictTables;+ }++ @Override+ public int get_kSectionDexCacheArrays() {+ return kSectionDexCacheArrays;+ }++ @Override+ public int get_kSectionInternedStrings() {+ return kSectionInternedStrings;+ }++ @Override+ public int get_kSectionClassTable() {+ return kSectionClassTable;+ }++ @Override+ public int get_kSectionStringReferenceOffsets() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionMetadata() {+ return UNSUPPORTED_SECTION;+ }++ @Override+ public int get_kSectionImageBitmap() {+ return kSectionImageBitmap;+ }++ @Override+ public int get_kSectionCount() {+ return kSectionCount;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImage.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImage.javaindex dad9f25ee0..7899efc8f7 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImage.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImage.java@@ -32,29 +32,29 @@ public class BootImage implements StructConverter {private int secondStageAddress;private int tagsAddress;private int pageSize;- private int [] unused;+ private int[] unused;private String name;private String commandLine;- private int [] id;+ private int[] id;public BootImage(ByteProvider provider) throws IOException {- this( new BinaryReader( provider, true ) );+ this(new BinaryReader(provider, true));}public BootImage(BinaryReader reader) throws IOException {- magic = reader.readNextAsciiString( BootImageConstants.BOOT_IMAGE_MAGIC_SIZE );- kernelSize = reader.readNextInt();- kernelAddress = reader.readNextInt();- ramDiskSize = reader.readNextInt();- ramDiskAddress = reader.readNextInt();- secondStageSize = reader.readNextInt();- secondStageAddress = reader.readNextInt();- tagsAddress = reader.readNextInt();- pageSize = reader.readNextInt();- unused = reader.readNextIntArray( 2 );- name = reader.readNextAsciiString( BootImageConstants.BOOT_NAME_SIZE );- commandLine = reader.readNextAsciiString( BootImageConstants.BOOT_ARGS_SIZE );- id = reader.readNextIntArray( 8 );+ magic = reader.readNextAsciiString(BootImageConstants.BOOT_MAGIC_SIZE);+ kernelSize = reader.readNextInt();+ kernelAddress = reader.readNextInt();+ ramDiskSize = reader.readNextInt();+ ramDiskAddress = reader.readNextInt();+ secondStageSize = reader.readNextInt();+ secondStageAddress = reader.readNextInt();+ tagsAddress = reader.readNextInt();+ pageSize = reader.readNextInt();+ unused = reader.readNextIntArray(2);+ name = reader.readNextAsciiString(BootImageConstants.BOOT_NAME_SIZE);+ commandLine = reader.readNextAsciiString(BootImageConstants.BOOT_ARGS_SIZE);+ id = reader.readNextIntArray(8);}public String getMagic() {@@ -74,7 +74,7 @@ public class BootImage implements StructConverter {}public int getKernelSizePageAligned() {- int remainder = getPageSize() - ( getKernelSize() % getPageSize() );+ int remainder = getPageSize() - (getKernelSize() % getPageSize());return getKernelSize() + remainder;}@@ -91,7 +91,7 @@ public class BootImage implements StructConverter {}public int getRamDiskSizePageAligned() {- int remainder = getPageSize() - ( getRamDiskSize() % getPageSize() );+ int remainder = getPageSize() - (getRamDiskSize() % getPageSize());return getRamDiskSize() + remainder;}@@ -104,11 +104,11 @@ public class BootImage implements StructConverter {}public int getSecondStageOffset() {- return getRamDiskOffset() + ( getRamDiskSizePageAligned() * getPageSize() );+ return getRamDiskOffset() + (getRamDiskSizePageAligned() * getPageSize());}public int getSecondStageSizePageAligned() {- int remainder = getPageSize() - ( getSecondStageSize() % getPageSize() );+ int remainder = getPageSize() - (getSecondStageSize() % getPageSize());return getSecondStageSize() + remainder;}@@ -120,7 +120,7 @@ public class BootImage implements StructConverter {return pageSize;}- public int [] getUnused() {+ public int[] getUnused() {return unused;}@@ -132,25 +132,25 @@ public class BootImage implements StructConverter {return commandLine;}- public int [] getId() {+ public int[] getId() {return id;}@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "boot_img_hdr", 0 );- structure.add( UTF8, BootImageConstants.BOOT_IMAGE_MAGIC_SIZE, "magic", null );- structure.add( DWORD, "kernelSize", null );- structure.add( DWORD, "kernelAddress", null );- structure.add( DWORD, "ramDiskSize", null );- structure.add( DWORD, "ramDiskAddress", null );- structure.add( DWORD, "secondStageSize", null );- structure.add( DWORD, "secondStageAddress", null );- structure.add( DWORD, "tagsAddress", null );- structure.add( DWORD, "pageSize", null );+ Structure structure = new StructureDataType("boot_img_hdr", 0);+ structure.add(UTF8, BootImageConstants.BOOT_MAGIC_SIZE, "magic", null);+ structure.add(DWORD, "kernelSize", null);+ structure.add(DWORD, "kernelAddress", null);+ structure.add(DWORD, "ramDiskSize", null);+ structure.add(DWORD, "ramDiskAddress", null);+ structure.add(DWORD, "secondStageSize", null);+ structure.add(DWORD, "secondStageAddress", null);+ structure.add(DWORD, "tagsAddress", null);+ structure.add(DWORD, "pageSize", null);structure.add(new ArrayDataType(DWORD, 2, DWORD.getLength()), "unused", null);- structure.add( UTF8, BootImageConstants.BOOT_NAME_SIZE, "name", null );- structure.add( UTF8, BootImageConstants.BOOT_ARGS_SIZE, "commandLine", null );+ structure.add(UTF8, BootImageConstants.BOOT_NAME_SIZE, "name", null);+ structure.add(UTF8, BootImageConstants.BOOT_ARGS_SIZE, "commandLine", null);structure.add(new ArrayDataType(DWORD, 8, DWORD.getLength()), "id", null);return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageAnalyzer.javaindex d1dd456b6a..ebff5bb123 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageAnalyzer.java@@ -17,7 +17,9 @@ package ghidra.file.formats.android.bootimg;import ghidra.app.plugin.core.analysis.AnalysisWorker;import ghidra.app.plugin.core.analysis.AutoAnalysisManager;-import ghidra.app.util.bin.*;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.MemoryByteProvider;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;import ghidra.program.model.address.Address;@@ -32,7 +34,7 @@ public class BootImageAnalyzer extends FileFormatAnalyzer implements AnalysisWor@Overridepublic String getName() {- return "Android Boot or Recovery Image Annotation";+ return "Android Boot, Recovery, or Vendor Image Annotation";}@Override@@ -42,13 +44,13 @@ public class BootImageAnalyzer extends FileFormatAnalyzer implements AnalysisWor@Overridepublic String getDescription() {- return "Annotates Android Boot and Recovery Image files.";+ return "Annotates Android Boot, Recovery, or Vendor Image files.";}@Overridepublic boolean canAnalyze(Program program) {try {- return BootImageUtil.isBootImage(program);+ return BootImageUtil.isBootImage(program) || BootImageUtil.isVendorBootImage(program);}catch (Exception e) {// not a boot image@@ -61,62 +63,97 @@ public class BootImageAnalyzer extends FileFormatAnalyzer implements AnalysisWorreturn true;}- private MessageLog log;+ private MessageLog messageLog;@Overridepublic boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)throws Exception {- this.log = log;+ this.messageLog = log;AutoAnalysisManager manager = AutoAnalysisManager.getAnalysisManager(program);return manager.scheduleWorker(this, null, false, monitor);}@Override- public boolean analysisWorkerCallback(Program program, Object workerContext, TaskMonitor monitor)- throws Exception, CancelledException {+ public boolean analysisWorkerCallback(Program program, Object workerContext,+ TaskMonitor monitor) throws Exception, CancelledException {Address address = program.getMinAddress();ByteProvider provider = new MemoryByteProvider(program.getMemory(), address);BinaryReader reader = new BinaryReader(provider, true);- BootImage header = new BootImage(reader);+ if (BootImageUtil.isBootImage(program)) {- if (!header.getMagic().equals(BootImageConstants.BOOT_IMAGE_MAGIC)) {- return false;- }+ BootImageHeader header = BootImageHeaderFactory.getBootImageHeader(reader);- DataType headerDataType = header.toDataType();+ if (!BootImageConstants.BOOT_MAGIC.equals(header.getMagic())) {+ return false;+ }- Data headerData = createData(program, address, headerDataType);+ DataType headerDataType = header.toDataType();- if (headerData == null) {- log.appendMsg("Unable to create header data.");- }+ Data headerData = createData(program, address, headerDataType);- createFragment(program, headerDataType.getName(), toAddr(program, 0),- toAddr(program, header.getPageSize()));+ if (headerData == null) {+ messageLog.appendMsg("Unable to create header data.");+ return false;+ }- if (header.getKernelSize() > 0) {- Address start = toAddr(program, header.getKernelOffset());- Address end = toAddr(program, header.getKernelOffset() + header.getKernelSize());- createFragment(program, BootImageConstants.KERNEL, start, end);- }+ createFragment(program, headerDataType.getName(), toAddr(program, 0),+ toAddr(program, header.getPageSize()));- if (header.getRamDiskSize() > 0) {- Address start = toAddr(program, header.getRamDiskOffset());- Address end = toAddr(program, header.getRamDiskOffset() + header.getRamDiskSize());- createFragment(program, BootImageConstants.RAMDISK, start, end);- }+ if (header.getKernelSize() > 0) {+ Address start = toAddr(program, header.getKernelOffset());+ Address end = toAddr(program, header.getKernelOffset() + header.getKernelSize());+ createFragment(program, BootImageConstants.KERNEL, start, end);+ }- if (header.getSecondStageSize() > 0) {- Address start = toAddr(program, header.getSecondStageOffset());- Address end =- toAddr(program, header.getSecondStageOffset() + header.getSecondStageSize());- createFragment(program, BootImageConstants.SECOND_STAGE, start, end);+ if (header.getRamdiskSize() > 0) {+ Address start = toAddr(program, header.getRamdiskOffset());+ Address end = toAddr(program, header.getRamdiskOffset() + header.getRamdiskSize());+ createFragment(program, BootImageConstants.RAMDISK, start, end);+ }++ if (header.getSecondSize() > 0) {+ Address start = toAddr(program, header.getSecondOffset());+ Address end = toAddr(program, header.getSecondOffset() + header.getSecondSize());+ createFragment(program, BootImageConstants.SECOND_STAGE, start, end);+ }++ changeDataSettings(program, monitor);}+ else if (BootImageUtil.isVendorBootImage(program)) {+ VendorBootImageHeader header =+ VendorBootImageHeaderFactory.getVendorBootImageHeader(reader);++ if (!header.getMagic().equals(BootImageConstants.VENDOR_BOOT_MAGIC)) {+ return false;+ }- changeDataSettings(program, monitor);+ DataType headerDataType = header.toDataType();++ Data headerData = createData(program, address, headerDataType);++ if (headerData == null) {+ messageLog.appendMsg("Unable to create header data.");+ }++ createFragment(program, headerDataType.getName(), toAddr(program, 0),+ toAddr(program, headerData.getLength()));++ if (header.getVendorRamdiskSize() > 0) {+ Address start = toAddr(program, header.getVendorRamdiskOffset());+ Address end = toAddr(program,+ header.getVendorRamdiskOffset() + header.getVendorRamdiskSize());+ createFragment(program, BootImageConstants.RAMDISK, start, end);+ }++ if (header.getDtbSize() > 0) {+ Address start = toAddr(program, header.getDtbOffset());+ Address end = toAddr(program, header.getDtbOffset() + header.getDtbSize());+ createFragment(program, BootImageConstants.DTB, start, end);+ }+ }removeEmptyFragments(program);diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageConstants.javaindex 892471a5a6..4ecf6695db 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageConstants.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageConstants.java@@ -15,22 +15,42 @@*/package ghidra.file.formats.android.bootimg;+/**+ *+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h+ *+ */public final class BootImageConstants {- public final static String BOOT_IMAGE_MAGIC = "ANDROID!";-- public final static byte [] BOOT_IMAGE_MAGIC_BYTES = BOOT_IMAGE_MAGIC.getBytes();-- public final static int BOOT_IMAGE_MAGIC_SIZE = BOOT_IMAGE_MAGIC.length();-- public final static int BOOT_NAME_SIZE = 16;-- public final static int BOOT_ARGS_SIZE = 512;-- public final static String SECOND_STAGE = "second stage";-- public final static String RAMDISK = "ramdisk";-- public final static String KERNEL = "kernel";-+ public final static String BOOT_MAGIC = "ANDROID!";+ public final static int BOOT_MAGIC_SIZE = 8;+ public final static int BOOT_NAME_SIZE = 16;+ public final static int BOOT_ARGS_SIZE = 512;+ public final static int BOOT_EXTRA_ARGS_SIZE = 1024;++ public final static int ID_SIZE = 8;++ public final static int V3_HEADER_SIZE = 4096;+ public final static int V3_PAGE_SIZE = 4096;+ public final static int V4_HEADER_SIZE = V3_HEADER_SIZE;+ public final static int V4_PAGE_SIZE = V3_PAGE_SIZE;++ public final static String VENDOR_BOOT_MAGIC = "VNDRBOOT";+ public final static int VENDOR_BOOT_MAGIC_SIZE = 8;+ public final static int VENDOR_BOOT_ARGS_SIZE = 2048;+ public final static int VENDOR_BOOT_NAME_SIZE = 16;++ public final static int VENDOR_RAMDISK_TYPE_NONE = 0;+ public final static int VENDOR_RAMDISK_TYPE_PLATFORM = 1;+ public final static int VENDOR_RAMDISK_TYPE_RECOVERY = 2;+ public final static int VENDOR_RAMDISK_TYPE_DLKM = 3;+ public final static int VENDOR_RAMDISK_NAME_SIZE = 32;+ public final static int VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE = 16;++ public final static String SECOND_STAGE = "second stage";+ public final static String RAMDISK = "ramdisk";+ public final static String KERNEL = "kernel";+ public final static String DTB = "dtb";++ public final static int HEADER_VERSION_OFFSET = 0x28;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageFileSystem.javaindex c774026204..ede551438d 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageFileSystem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageFileSystem.java@@ -15,11 +15,18 @@*/package ghidra.file.formats.android.bootimg;-import java.io.*;-import java.util.*;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;import ghidra.app.util.bin.ByteProvider;-import ghidra.formats.gfilesystem.*;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;import ghidra.formats.gfilesystem.annotations.FileSystemInfo;import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;import ghidra.util.exception.CancelledException;@@ -29,7 +36,7 @@ import ghidra.util.task.TaskMonitor;@FileSystemInfo(type = "androidbootimg", description = "Android Boot and Recovery Images", factory = GFileSystemBaseFactory.class)public class BootImageFileSystem extends GFileSystemBase {- private BootImage header;+ private BootImageHeader header;private GFileImpl kernelFile;private GFileImpl ramdiskFile;private GFileImpl secondStageFile;@@ -41,15 +48,16 @@ public class BootImageFileSystem extends GFileSystemBase {@Overridepublic boolean isValid(TaskMonitor monitor) throws IOException {- byte[] bytes = provider.readBytes(0, BootImageConstants.BOOT_IMAGE_MAGIC_SIZE);- return Arrays.equals(bytes, BootImageConstants.BOOT_IMAGE_MAGIC_BYTES);+ byte[] bytes = provider.readBytes(0, BootImageConstants.BOOT_MAGIC_SIZE);+ return Arrays.equals(bytes, BootImageConstants.BOOT_MAGIC.getBytes());}@Overridepublic void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {- this.header = new BootImage(provider);- if (!header.getMagic().equals(BootImageConstants.BOOT_IMAGE_MAGIC)) {+ this.header = BootImageHeaderFactory.getBootImageHeader(provider, true);++ if (!header.getMagic().equals(BootImageConstants.BOOT_MAGIC)) {throw new IOException("Invalid Android boot image file!");}@@ -58,14 +66,15 @@ public class BootImageFileSystem extends GFileSystemBase {header.getKernelSize(), null);fileList.add(kernelFile);}- if (header.getRamDiskSize() > 0) {++ if (header.getRamdiskSize() > 0) {ramdiskFile = GFileImpl.fromFilename(this, root, BootImageConstants.RAMDISK, false,- header.getKernelSize(), null);+ header.getRamdiskSize(), null);fileList.add(ramdiskFile);}- if (header.getSecondStageSize() > 0) {+ if (header.getSecondSize() > 0) {secondStageFile = GFileImpl.fromFilename(this, root, BootImageConstants.SECOND_STAGE,- false, header.getKernelSize(), null);+ false, header.getSecondSize(), null);fileList.add(secondStageFile);}}@@ -109,12 +118,12 @@ public class BootImageFileSystem extends GFileSystemBase {}else if (file == ramdiskFile) {byte[] ramDiskBytes =- provider.readBytes(header.getRamDiskOffset(), header.getRamDiskSize());+ provider.readBytes(header.getRamdiskOffset(), header.getRamdiskSize());return new ByteArrayInputStream(ramDiskBytes);}else if (file == secondStageFile) {byte[] secondStageBytes =- provider.readBytes(header.getSecondStageOffset(), header.getSecondStageSize());+ provider.readBytes(header.getSecondOffset(), header.getSecondSize());return new ByteArrayInputStream(secondStageBytes);}return null;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeader.javanew file mode 100644index 0000000000..3920da986b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeader.java@@ -0,0 +1,93 @@+/* ###+ * 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.android.bootimg;++import ghidra.app.util.bin.StructConverter;++public abstract class BootImageHeader implements StructConverter {+ /**+ * Returns the Boot Image MAGIC value.+ * @see BootImageConstants+ * @return the Boot Image MAGIC value+ */+ public abstract String getMagic();++ /**+ * Returns the page size, as defined in the header.+ * @return the page size, as defined in the header+ */+ public abstract int getPageSize();++ /**+ * Returns the kernel size, as defined in the header.+ * @return the kernel size, as defined in the header+ */+ public abstract int getKernelSize();++ /**+ * Returns the number of pages used to store the kernel.+ * @return the number of pages used to store the kernel+ */+ public abstract int getKernelPageCount();++ /**+ * Returns the kernel file offset+ * @return the kernel file offset+ */+ public abstract long getKernelOffset();++ /**+ * Returns the ramdisk size, as defined in the header.+ * @return the ramdisk size, as defined in the header+ */+ public abstract int getRamdiskSize();++ /**+ * Returns the number of pages used to store the ramdisk.+ * @return the number of pages used to store the ramdisk+ */+ public abstract int getRamdiskPageCount();++ /**+ * Returns the ramdisk file offset.+ * @return the ramdisk file offset+ */+ public abstract int getRamdiskOffset();++ /**+ * Returns the second stage size, as defined in the header.+ * @return the second stage size, as defined in the header+ */+ public abstract int getSecondSize();++ /**+ * Returns the number of pages used to store the second stage.+ * @return the number of pages used to store the second stage+ */+ public abstract int getSecondPageCount();++ /**+ * Returns the second stage file offset.+ * @return the second stage file offset+ */+ public abstract long getSecondOffset();++ /**+ * Returns the kernel commandline.+ * @return the kernel commandline+ */+ public abstract String getCommandLine();+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderFactory.javanew file mode 100644index 0000000000..f86260a17d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderFactory.java@@ -0,0 +1,54 @@+/* ###+ * 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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;++public final class BootImageHeaderFactory {++ public final static BootImageHeader getBootImageHeader(ByteProvider provider,+ boolean littleEndian) throws IOException {+ return getBootImageHeader(new BinaryReader(provider, littleEndian));+ }++ public final static BootImageHeader getBootImageHeader(BinaryReader reader) throws IOException {++ if (!BootImageUtil.isBootImage(reader)) {+ throw new IOException("BootImageHeader magic not found.");+ }++ int version = reader.readInt(BootImageConstants.HEADER_VERSION_OFFSET);++ switch (version) {+ case 0:+ return new BootImageHeaderV0(reader);+ case 1:+ return new BootImageHeaderV1(reader);+ case 2:+ return new BootImageHeaderV2(reader);+ case 3:+ return new BootImageHeaderV3(reader);+ case 4:+ return new BootImageHeaderV4(reader);+ default:+ throw new IOException("BootImageHeader unsupported version found: " + version);+ }+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV0.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV0.javanew file mode 100644index 0000000000..b93ace0256--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV0.java@@ -0,0 +1,207 @@+/* ###+ * 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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.*;+import ghidra.util.NumericUtilities;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h#67+ */+public class BootImageHeaderV0 extends BootImageHeader {++ private String magic;+ private int kernel_size;+ private int kernel_addr;+ private int ramdisk_size;+ private int ramdisk_addr;+ private int second_size;+ private int second_addr;+ private int tags_addr;+ private int page_size;+ private int header_version;+ private int os_version;+ private String name;+ private String cmdline;+ private int[] id;+ private String extra_cmdline;++ public BootImageHeaderV0(BinaryReader reader) throws IOException {+ magic = reader.readNextAsciiString(BootImageConstants.BOOT_MAGIC_SIZE);+ kernel_size = reader.readNextInt();+ kernel_addr = reader.readNextInt();+ ramdisk_size = reader.readNextInt();+ ramdisk_addr = reader.readNextInt();+ second_size = reader.readNextInt();+ second_addr = reader.readNextInt();+ tags_addr = reader.readNextInt();+ page_size = reader.readNextInt();+ header_version = reader.readNextInt();+ os_version = reader.readNextInt();+ name = reader.readNextAsciiString(BootImageConstants.BOOT_NAME_SIZE);+ cmdline = reader.readNextAsciiString(BootImageConstants.BOOT_ARGS_SIZE);+ id = reader.readNextIntArray(BootImageConstants.ID_SIZE);+ extra_cmdline = reader.readNextAsciiString(BootImageConstants.BOOT_EXTRA_ARGS_SIZE);+ }++ @Override+ public String getMagic() {+ return magic;+ }++ @Override+ public int getKernelSize() {+ return kernel_size;+ }++ @Override+ public long getKernelOffset() {+ return page_size;//see header comment...+ }++ public int getKernelAddress() {+ return kernel_addr;+ }++ /**+ * n = (kernel_size + page_size - 1) / page_size+ */+ public int getKernelPageCount() {+ return (int) NumericUtilities.getUnsignedAlignedValue(Integer.toUnsignedLong(kernel_size),+ Integer.toUnsignedLong(page_size));+ }++ @Override+ public int getRamdiskSize() {+ return ramdisk_size;+ }++ @Override+ public int getRamdiskOffset() {+ return page_size + getKernelPageCount() * page_size;//see header comment...+ }++ public int getRamdiskAddress() {+ return ramdisk_addr;+ }++ /**+ * m = (ramdisk_size + page_size - 1) / page_size+ */+ public int getRamdiskPageCount() {+ return (int) NumericUtilities.getUnsignedAlignedValue(Integer.toUnsignedLong(ramdisk_size),+ Integer.toUnsignedLong(page_size));+ }++ @Override+ public int getSecondSize() {+ return second_size;+ }++ @Override+ public long getSecondOffset() {+ return page_size + (getKernelPageCount() + getRamdiskPageCount()) * page_size;//see header comment...+ }++ public int getSecondAddress() {+ return second_addr;+ }++ /**+ * o = (second_size + page_size - 1) / page_size+ */+ public int getSecondPageCount() {+ return (int) NumericUtilities.getUnsignedAlignedValue(Integer.toUnsignedLong(second_size),+ Integer.toUnsignedLong(page_size));+ }++ /**+ * Physical address for kernel tags (if required)+ * @return physical address for kernel tags+ */+ public int getTagsAddress() {+ return tags_addr;+ }++ @Override+ public int getPageSize() {+ return page_size;+ }++ /**+ * Version of the boot image header.+ * @return version of the boot image header+ */+ public int getHeaderVersion() {+ return header_version;+ }++ /**+ * Operating system version and security patch level.+ * For version "A.B.C" and patch level "Y-M-D":+ * (7 bits for each of A, B, C; 7 bits for (Y-2000), 4 bits for M)+ * os_version = A[31:25] B[24:18] C[17:11] (Y-2000)[10:4] M[3:0]+ * @return OS version+ */+ public int getOSVersion() {+ return os_version;+ }++ public String getName() {+ return name;+ }++ @Override+ public String getCommandLine() {+ return cmdline;+ }++ public int[] getId() {+ return id;+ }++ public String getExtraCommandLine() {+ return extra_cmdline;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("boot_img_hdr_v0", 0);+ structure.add(UTF8, BootImageConstants.BOOT_MAGIC_SIZE, "magic", null);+ structure.add(DWORD, "kernel_size", null);+ structure.add(DWORD, "kernel_addr", null);+ structure.add(DWORD, "ramdisk_size", null);+ structure.add(DWORD, "ramdisk_addr", null);+ structure.add(DWORD, "second_size", null);+ structure.add(DWORD, "second_addr", null);+ structure.add(DWORD, "tags_addr", null);+ structure.add(DWORD, "page_size", null);+ structure.add(DWORD, "header_version", null);+ structure.add(DWORD, "os_version", BootImageUtil.getOSVersionString(os_version));+ structure.add(UTF8, BootImageConstants.BOOT_NAME_SIZE, "name", null);+ structure.add(UTF8, BootImageConstants.BOOT_ARGS_SIZE, "cmdline", null);+ ArrayDataType array =+ new ArrayDataType(DWORD, BootImageConstants.ID_SIZE, DWORD.getLength());+ structure.add(array, "id", null);+ structure.add(UTF8, BootImageConstants.BOOT_EXTRA_ARGS_SIZE, "extra_cmdline", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV1.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV1.javanew file mode 100644index 0000000000..2fa1d2cb4e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV1.java@@ -0,0 +1,75 @@+/* ###+ * IP: LICENSE+ */+package ghidra.file.formats.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.util.InvalidNameException;+import ghidra.util.NumericUtilities;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h#156+ */+public class BootImageHeaderV1 extends BootImageHeaderV0 {++ private int recovery_dtbo_size;+ private long recovery_dtbo_offset;+ private int header_size;++ public BootImageHeaderV1(BinaryReader reader) throws IOException {+ super(reader);+ recovery_dtbo_size = reader.readNextInt();+ recovery_dtbo_offset = reader.readNextLong();+ header_size = reader.readNextInt();+ }++ /**+ * Size in bytes for recovery DTBO/ACPIO image+ * @return recovery DTBO/ACPIO image byte size+ */+ public int getRecoveryDtboSize() {+ return recovery_dtbo_size;+ }++ /**+ * p = (recovery_dtbo_size + page_size - 1) / page_size+ * @return the recovery DTBO adjusted size+ */+ public int getRecoveryDtboSizeAdjusted() {+ return (int) NumericUtilities.getUnsignedAlignedValue(+ Integer.toUnsignedLong(recovery_dtbo_size), Integer.toUnsignedLong(getPageSize()));+ }++ /**+ * Offset to recovery dtbo/acpio in boot image+ * @return the recover DTBO offset+ */+ public long getRecoveryDtboOffset() {+ return recovery_dtbo_offset;+ }++ public int getHeaderSize() {+ return header_size;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ try {+ structure.setName("boot_img_hdr_v1");+ }+ catch (InvalidNameException e) {+ //ignore+ }+ structure.add(DWORD, "recovery_dtbo_size", null);+ structure.add(QWORD, "recovery_dtbo_offset", null);+ structure.add(DWORD, "header_size", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV2.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV2.javanew file mode 100644index 0000000000..0f0075f238--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV2.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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.util.InvalidNameException;+import ghidra.util.NumericUtilities;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h#199+ */+public class BootImageHeaderV2 extends BootImageHeaderV1 {++ private int dtb_size;+ private long dtb_addr;++ public BootImageHeaderV2(BinaryReader reader) throws IOException {+ super(reader);+ dtb_size = reader.readNextInt();+ dtb_addr = reader.readNextLong();+ }++ /**+ * Size in bytes for DTB image+ * @return size in bytes for DTB image+ */+ public int getDtbSize() {+ return dtb_size;+ }++ /**+ * q = (dtb_size + page_size - 1) / page_size+ * @return the DTB adjusted size+ */+ public int getDtbSizeAdjusted() {+ return (int) NumericUtilities.getUnsignedAlignedValue(Integer.toUnsignedLong(dtb_size),+ Integer.toUnsignedLong(getPageSize()));+ }++ /**+ * Physical load address for DTB image+ * @return physical load address for DTB image+ */+ public long getDtbAddress() {+ return dtb_addr;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ try {+ structure.setName("boot_img_hdr_v2");+ }+ catch (InvalidNameException e) {+ //ignore+ }+ structure.add(DWORD, "dtb_size", null);+ structure.add(QWORD, "dtb_addr", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV3.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV3.javanew file mode 100644index 0000000000..550d56dd5d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV3.java@@ -0,0 +1,158 @@+/* ###+ * 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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+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.NumericUtilities;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h#250+ */+public class BootImageHeaderV3 extends BootImageHeader {++ private String magic;+ private int kernel_size;+ private int ramdisk_size;+ private int os_version;+ private int header_size;+ private int[] reserved;// 4 elements+ private int header_version;+ private String cmdline;++ public BootImageHeaderV3(BinaryReader reader) throws IOException {+ magic = reader.readNextAsciiString(BootImageConstants.BOOT_MAGIC_SIZE);+ kernel_size = reader.readNextInt();+ ramdisk_size = reader.readNextInt();+ os_version = reader.readNextInt();+ header_size = reader.readNextInt();+ reserved = reader.readNextIntArray(4);+ header_version = reader.readNextInt();+ cmdline = reader.readNextAsciiString(+ BootImageConstants.BOOT_ARGS_SIZE + BootImageConstants.BOOT_EXTRA_ARGS_SIZE);+ }++ @Override+ public String getMagic() {+ return magic;+ }++ @Override+ public int getPageSize() {+ return BootImageConstants.V3_PAGE_SIZE;+ }++ @Override+ public int getKernelSize() {+ return kernel_size;+ }++ /**+ * n = (kernel_size + page_size - 1) / page_size+ */+ @Override+ public int getKernelPageCount() {+ return (int) NumericUtilities.getUnsignedAlignedValue(Integer.toUnsignedLong(kernel_size),+ Integer.toUnsignedLong(BootImageConstants.V3_PAGE_SIZE));+ }++ @Override+ public long getKernelOffset() {+ return BootImageConstants.V3_PAGE_SIZE;//see header comment...+ }++ @Override+ public int getRamdiskSize() {+ return ramdisk_size;+ }++ /**+ * m = (ramdisk_size + page_size - 1) / page_size+ */+ @Override+ public int getRamdiskPageCount() {+ return (int) NumericUtilities.getUnsignedAlignedValue(Integer.toUnsignedLong(ramdisk_size),+ Integer.toUnsignedLong(BootImageConstants.V3_PAGE_SIZE));+ }++ @Override+ public int getRamdiskOffset() {+ return BootImageConstants.V3_PAGE_SIZE ++ (getKernelPageCount() * BootImageConstants.V3_PAGE_SIZE);+ }++ @Override+ public long getSecondOffset() {+ // v3 does not contain 2nd stage, just return 0+ return 0;+ }++ @Override+ public int getSecondSize() {+ // v3 does not contain 2nd stage, just return 0+ return 0;+ }++ @Override+ public int getSecondPageCount() {+ // v3 does not contain 2nd stage, just return 0+ return 0;+ }++ public int getOSVersion() {+ return os_version;+ }++ public int getHeaderSize() {+ return header_size;+ }++ public int[] getReserved() {+ return reserved;+ }++ public int getHeaderVersion() {+ return header_version;+ }++ public String getCommandLine() {+ return cmdline;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("boot_img_hdr_v3", 0);+ structure.add(UTF8, BootImageConstants.BOOT_MAGIC_SIZE, "magic", null);+ structure.add(DWORD, "kernel_size", null);+ structure.add(DWORD, "ramdisk_size", null);+ structure.add(DWORD, "os_version", BootImageUtil.getOSVersionString(os_version));+ structure.add(DWORD, "header_size", null);+ ArrayDataType array = new ArrayDataType(DWORD, 4, DWORD.getLength());+ structure.add(array, "reserved", null);+ structure.add(DWORD, "header_version", null);+ structure.add(UTF8,+ BootImageConstants.BOOT_ARGS_SIZE + BootImageConstants.BOOT_EXTRA_ARGS_SIZE, "cmdline",+ null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV4.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV4.javanew file mode 100644index 0000000000..8ae1ef951d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageHeaderV4.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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h#397+ */+public class BootImageHeaderV4 extends BootImageHeaderV3 {++ private int signature_size;++ public BootImageHeaderV4(BinaryReader reader) throws IOException {+ super(reader);+ }++ public int getSignatureSize() {+ return signature_size;+ }++ @Override+ public int getPageSize() {+ return BootImageConstants.V4_PAGE_SIZE;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ try {+ structure.setName("boot_img_hdr_v4");+ }+ catch (InvalidNameException e) {+ //ignore+ }+ structure.add(DWORD, "signature_size", null);+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageUtil.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageUtil.javaindex fa5fe6a3c1..23465a9ac4 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageUtil.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/BootImageUtil.java@@ -15,21 +15,67 @@*/package ghidra.file.formats.android.bootimg;+import java.util.Arrays;++import ghidra.app.util.bin.BinaryReader;import ghidra.program.model.address.Address;import ghidra.program.model.listing.Program;-import java.util.Arrays;+public final class BootImageUtil {++ public final static boolean isBootImage(Program program) {+ byte[] bytes = new byte[BootImageConstants.BOOT_MAGIC_SIZE];+ try {+ Address address = program.getMinAddress();+ program.getMemory().getBytes(address, bytes);+ }+ catch (Exception e) {+ //ignore+ }+ return Arrays.equals(bytes, BootImageConstants.BOOT_MAGIC.getBytes());+ }++ public final static boolean isBootImage(BinaryReader reader) {+ try {+ String magic = reader.readAsciiString(0, BootImageConstants.BOOT_MAGIC_SIZE);+ return BootImageConstants.BOOT_MAGIC.equals(magic);+ }+ catch (Exception e) {+ //ignore+ }+ return false;+ }-public class BootImageUtil {-- public final static boolean isBootImage( Program program ) {- byte [] bytes = new byte[ 8 ];+ public final static boolean isVendorBootImage(Program program) {+ byte[] bytes = new byte[BootImageConstants.VENDOR_BOOT_MAGIC_SIZE];try {Address address = program.getMinAddress();- program.getMemory().getBytes( address, bytes );+ program.getMemory().getBytes(address, bytes);}- catch (Exception e) {}- return Arrays.equals( bytes, BootImageConstants.BOOT_IMAGE_MAGIC_BYTES );+ catch (Exception e) {+ //ignore+ }+ return Arrays.equals(bytes, BootImageConstants.VENDOR_BOOT_MAGIC.getBytes());+ }++ public final static boolean isVendorBootImage(BinaryReader reader) {+ try {+ String magic = reader.readAsciiString(0, BootImageConstants.VENDOR_BOOT_MAGIC_SIZE);+ return BootImageConstants.VENDOR_BOOT_MAGIC.equals(magic);+ }+ catch (Exception e) {+ //ignore+ }+ return false;+ }++ public final static String getOSVersionString(int os_version) {+ int a = (os_version & 0xfe000000) >>> 25;+ int b = (os_version & 0x01fc0000) >>> 18;+ int c = (os_version & 0x0003f800) >>> 11;+ int y = (os_version & 0x000007f0) >>> 4;+ int m = (os_version & 0x0000000f);+ return a + "." + b + "." + c + "_" + y + "_" + m;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/PartitionTableEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/PartitionTableEntry.javaindex d7f213194d..36784c2580 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/PartitionTableEntry.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/PartitionTableEntry.java@@ -22,31 +22,34 @@ import java.io.IOException;public class PartitionTableEntry {- private byte [] name;+ private byte[] name;private int start;private int length;private int flags;public PartitionTableEntry(ByteProvider provider) throws IOException {- this( new BinaryReader( provider, true ) );+ this(new BinaryReader(provider, true));}public PartitionTableEntry(BinaryReader reader) throws IOException {- name = reader.readNextByteArray( 16 );- start = reader.readNextInt();- length = reader.readNextInt();- flags = reader.readNextInt();+ name = reader.readNextByteArray(16);+ start = reader.readNextInt();+ length = reader.readNextInt();+ flags = reader.readNextInt();}public String getName() {- return new String( name );+ return new String(name);}+public int getStart() {return start;}+public int getLength() {return length;}+public int getFlags() {return flags;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageFileSystem.javanew file mode 100644index 0000000000..33d2f0a840--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageFileSystem.java@@ -0,0 +1,116 @@+/* ###+ * 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.android.bootimg;++import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;++import ghidra.app.util.bin.ByteProvider;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.CryptoException;+import ghidra.util.task.TaskMonitor;++@FileSystemInfo(type = "androidvendorbootimg", description = "Android Vendor Boot Images", factory = GFileSystemBaseFactory.class)+public class VendorBootImageFileSystem extends GFileSystemBase {++ private VendorBootImageHeader header;+ private GFileImpl ramdiskFile;+ private GFileImpl dtbFile;+ private List<GFileImpl> fileList = new ArrayList<>();++ public VendorBootImageFileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ byte[] bytes = provider.readBytes(0, BootImageConstants.VENDOR_BOOT_MAGIC_SIZE);+ return Arrays.equals(bytes, BootImageConstants.VENDOR_BOOT_MAGIC.getBytes());+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {++ this.header = VendorBootImageHeaderFactory.getVendorBootImageHeader(provider, true);++ if (!header.getMagic().equals(BootImageConstants.VENDOR_BOOT_MAGIC)) {+ throw new IOException("Invalid Android boot image file!");+ }++ if (header.getVendorRamdiskSize() > 0) {+ ramdiskFile = GFileImpl.fromFilename(this, root, BootImageConstants.RAMDISK, false,+ header.getVendorRamdiskSize(), null);+ fileList.add(ramdiskFile);+ }+ if (header.getDtbSize() > 0) {+ dtbFile = GFileImpl.fromFilename(this, root, BootImageConstants.DTB, false,+ header.getDtbSize(), null);+ fileList.add(dtbFile);+ }+ }++ @Override+ public void close() throws IOException {+ ramdiskFile = null;+ dtbFile = null;+ header = null;+ super.close();+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ return (directory == null || directory.equals(root)) ? new ArrayList<>(fileList)+ : Collections.emptyList();+ }++ @Override+ public String getInfo(GFile file, TaskMonitor monitor) {+ if (file == ramdiskFile) {+ return "This is a ramdisk, it is a GZIP file containing a CPIO archive.";+ }+ else if (file == dtbFile) {+ return "This is a DTB file. It appears unused at this time.";+ }+ return null;+ }++ @Override+ protected InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException, CryptoException {++ if (file == ramdiskFile) {+ byte[] ramDiskBytes =+ provider.readBytes(header.getVendorRamdiskOffset(), header.getVendorRamdiskSize());+ return new ByteArrayInputStream(ramDiskBytes);+ }+ else if (file == dtbFile) {+ byte[] dtbBytes = provider.readBytes(header.getDtbOffset(), header.getDtbSize());+ return new ByteArrayInputStream(dtbBytes);+ }+ return null;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeader.javanew file mode 100644index 0000000000..120f1df42f--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeader.java@@ -0,0 +1,34 @@+/* ###+ * 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.android.bootimg;++import ghidra.app.util.bin.StructConverter;++/**+ *+ */+public abstract class VendorBootImageHeader implements StructConverter {++ public abstract String getMagic();++ public abstract long getVendorRamdiskOffset();++ public abstract int getVendorRamdiskSize();++ public abstract long getDtbOffset();++ public abstract int getDtbSize();+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderFactory.javanew file mode 100644index 0000000000..11e9acadef--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderFactory.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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;++public final class VendorBootImageHeaderFactory {++ public final static VendorBootImageHeader getVendorBootImageHeader(ByteProvider provider,+ boolean littleEndian) throws IOException {+ return getVendorBootImageHeader(new BinaryReader(provider, littleEndian));+ }++ public final static VendorBootImageHeader getVendorBootImageHeader(BinaryReader reader)+ throws IOException {++ if (!BootImageUtil.isVendorBootImage(reader)) {+ throw new IOException("VendorBootImageHeader magic not found.");+ }++ int version = reader.readInt(BootImageConstants.VENDOR_BOOT_MAGIC_SIZE);++ switch (version) {+ case 3:+ return new VendorBootImageHeaderV3(reader);+ case 4:+ return new VendorBootImageHeaderV4(reader);+ default:+ throw new IOException(+ "VendorBootImageHeader unsupported version found: " + version);+ }+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderV3.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderV3.javanew file mode 100644index 0000000000..235e572dae--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderV3.java@@ -0,0 +1,166 @@+/* ###+ * 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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.data.StructureDataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h#286+ * <pre>+ * The structure of the vendor boot image (introduced with version 3 and+ * required to be present when a v3 boot image is used) is as follows:+ *+ * +---------------------++ * | vendor boot header | o pages+ * +---------------------++ * | vendor ramdisk | p pages+ * +---------------------++ * | dtb | q pages+ * +---------------------++ * o = (2112 + page_size - 1) / page_size+ * p = (vendor_ramdisk_size + page_size - 1) / page_size+ * q = (dtb_size + page_size - 1) / page_size+ *+ * 0. all entities in the boot image are 4096-byte aligned in flash, all+ * entities in the vendor boot image are page_size (determined by the vendor+ * and specified in the vendor boot image header) aligned in flash+ * 1. kernel, ramdisk, vendor ramdisk, and DTB are required (size != 0)+ * 2. load the kernel and DTB at the specified physical address (kernel_addr,+ * dtb_addr)+ * 3. load the vendor ramdisk at ramdisk_addr+ * 4. load the generic ramdisk immediately following the vendor ramdisk in+ * memory+ * 5. set up registers for kernel entry as required by your architecture+ * 6. if the platform has a second stage bootloader jump to it (must be+ * contained outside boot and vendor boot partitions), otherwise+ * jump to kernel_addr+ * </pre>+ *+ */+public class VendorBootImageHeaderV3 extends VendorBootImageHeader {++ private String magic;+ private int header_version;+ private int page_size;+ private int kernel_addr;+ private int ramdisk_addr;+ private int vendor_ramdisk_size;+ private String cmdline;+ private int tags_addr;+ private String name;+ private int header_size;+ private int dtb_size;+ private long dtb_addr;++ public VendorBootImageHeaderV3(BinaryReader reader) throws IOException {+ magic = reader.readNextAsciiString(BootImageConstants.VENDOR_BOOT_MAGIC_SIZE);+ header_version = reader.readNextInt();+ page_size = reader.readNextInt();+ kernel_addr = reader.readNextInt();+ ramdisk_addr = reader.readNextInt();+ vendor_ramdisk_size = reader.readNextInt();+ cmdline = reader.readNextAsciiString(BootImageConstants.VENDOR_BOOT_ARGS_SIZE);+ tags_addr = reader.readNextInt();+ name = reader.readNextAsciiString(BootImageConstants.VENDOR_BOOT_NAME_SIZE);+ header_size = reader.readNextInt();+ dtb_size = reader.readNextInt();+ dtb_addr = reader.readNextLong();+ }++ public String getMagic() {+ return magic;+ }++ public int getHeaderVersion() {+ return header_version;+ }++ public int getPageSize() {+ return page_size;+ }++ public int getKernelAddress() {+ return kernel_addr;+ }++ public int getRamdiskAddress() {+ return ramdisk_addr;+ }++ public int getVendorRamdiskSize() {+ return vendor_ramdisk_size;+ }++ @Override+ public long getVendorRamdiskOffset() {+ return page_size;+ }++ public String getCmdline() {+ return cmdline;+ }++ public int getTagsAddress() {+ return tags_addr;+ }++ public String getName() {+ return name;+ }++ public int getHeaderSize() {+ return header_size;+ }++ public int getDtbSize() {+ return dtb_size;+ }++ public long getDtbAddress() {+ return dtb_addr;+ }++ @Override+ public long getDtbOffset() {+ int o = ((2112 + page_size - 1) / page_size);+ int p = ((vendor_ramdisk_size + page_size - 1) / page_size);+ return (o + p) * page_size;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("vendor_boot_img_hdr_v3", 0);+ structure.add(UTF8, BootImageConstants.VENDOR_BOOT_MAGIC_SIZE, "magic", null);+ structure.add(DWORD, "header_version", null);+ structure.add(DWORD, "page_size", null);+ structure.add(DWORD, "kernel_addr", null);+ structure.add(DWORD, "ramdisk_addr", null);+ structure.add(DWORD, "vendor_ramdisk_size", null);+ structure.add(UTF8, BootImageConstants.VENDOR_BOOT_ARGS_SIZE, "cmdline", null);+ structure.add(DWORD, "tags_addr", null);+ structure.add(UTF8, BootImageConstants.VENDOR_BOOT_NAME_SIZE, "name", null);+ structure.add(DWORD, "header_size", null);+ structure.add(DWORD, "dtb_size", null);+ structure.add(QWORD, "dtb_addr", null);+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderV4.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderV4.javanew file mode 100644index 0000000000..d82d162abd--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorBootImageHeaderV4.java@@ -0,0 +1,159 @@+/* ###+ * 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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h#401+ * <pre>+ * The structure of the vendor boot image version 4, which is required to be+ * present when a version 4 boot image is used, is as follows:+ *+ * +------------------------++ * | vendor boot header | o pages+ * +------------------------++ * | vendor ramdisk section | p pages+ * +------------------------++ * | dtb | q pages+ * +------------------------++ * | vendor ramdisk table | r pages+ * +------------------------++ * | bootconfig | s pages+ * +------------------------++ *+ * o = (2128 + page_size - 1) / page_size+ * p = (vendor_ramdisk_size + page_size - 1) / page_size+ * q = (dtb_size + page_size - 1) / page_size+ * r = (vendor_ramdisk_table_size + page_size - 1) / page_size+ * s = (vendor_bootconfig_size + page_size - 1) / page_size+ *+ * Note that in version 4 of the vendor boot image, multiple vendor ramdisks can+ * be included in the vendor boot image. The bootloader can select a subset of+ * ramdisks to load at runtime. To help the bootloader select the ramdisks, each+ * ramdisk is tagged with a type tag and a set of hardware identifiers+ * describing the board, soc or platform that this ramdisk is intended for.+ *+ * The vendor ramdisk section is consist of multiple ramdisk images concatenated+ * one after another, and vendor_ramdisk_size is the size of the section, which+ * is the total size of all the ramdisks included in the vendor boot image.+ *+ * The vendor ramdisk table holds the size, offset, type, name and hardware+ * identifiers of each ramdisk. The type field denotes the type of its content.+ * The hardware identifiers are specified in the board_id field in each table+ * entry. The board_id field is consist of a vector of unsigned integer words,+ * and the encoding scheme is defined by the hardware vendor.+ *+ * For the different type of ramdisks, there are:+ * - VENDOR_RAMDISK_TYPE_NONE indicates the value is unspecified.+ * - VENDOR_RAMDISK_TYPE_PLATFORM ramdisk contains platform specific bits.+ * - VENDOR_RAMDISK_TYPE_RECOVERY ramdisk contains recovery resources.+ * - VENDOR_RAMDISK_TYPE_DLKM ramdisk contains dynamic loadable kernel+ * modules.+ *+ * Version 4 of the vendor boot image also adds a bootconfig section to the end+ * of the image. This section contains Boot Configuration parameters known at+ * build time. The bootloader is responsible for placing this section directly+ * after the generic ramdisk, followed by the bootconfig trailer, before+ * entering the kernel.+ *+ * 0. all entities in the boot image are 4096-byte aligned in flash, all+ * entities in the vendor boot image are page_size (determined by the vendor+ * and specified in the vendor boot image header) aligned in flash+ * 1. kernel, ramdisk, and DTB are required (size != 0)+ * 2. load the kernel and DTB at the specified physical address (kernel_addr,+ * dtb_addr)+ * 3. load the vendor ramdisks at ramdisk_addr+ * 4. load the generic ramdisk immediately following the vendor ramdisk in+ * memory+ * 5. load the bootconfig immediately following the generic ramdisk. Add+ * additional bootconfig parameters followed by the bootconfig trailer.+ * 6. set up registers for kernel entry as required by your architecture+ * 7. if the platform has a second stage bootloader jump to it (must be+ * contained outside boot and vendor boot partitions), otherwise+ * jump to kernel_addr+ * </pre>+ *+ */+public class VendorBootImageHeaderV4 extends VendorBootImageHeaderV3 {++ private int vendor_ramdisk_table_size;+ private int vendor_ramdisk_table_entry_num;+ private int vendor_ramdisk_table_entry_size;+ private int bootconfig_size;++ public VendorBootImageHeaderV4(BinaryReader reader) throws IOException {+ super(reader);+ vendor_ramdisk_table_size = reader.readNextInt();+ vendor_ramdisk_table_entry_num = reader.readNextInt();+ vendor_ramdisk_table_entry_size = reader.readNextInt();+ bootconfig_size = reader.readNextInt();+ }++ /**+ * Size in bytes for the vendor ramdisk table+ * @return size in bytes for the vendor ramdisk table+ */+ public int getVendorRamdiskTableSize() {+ return vendor_ramdisk_table_size;+ }++ /**+ * Number of entries in the vendor ramdisk table+ * @return number of entries in the vendor ramdisk table+ */+ public int getVendorRamdiskTableEntryNum() {+ return vendor_ramdisk_table_entry_num;+ }++ /**+ * Size in bytes for a vendor ramdisk table entry+ * @return size in bytes for a vendor ramdisk table entry+ */+ public int getVendorRamdiskTableEntrySize() {+ return vendor_ramdisk_table_entry_size;+ }++ /**+ * Size in bytes for the bootconfig section+ * @return size in bytes for the bootconfig section+ */+ public int getBootConfigSize() {+ return bootconfig_size;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ try {+ structure.setName("vendor_boot_img_hdr_v4");+ }+ catch (InvalidNameException e) {+ //ignore+ }+ structure.add(DWORD, "vendor_ramdisk_table_size", null);+ structure.add(DWORD, "vendor_ramdisk_table_entry_num", null);+ structure.add(DWORD, "vendor_ramdisk_table_entry_size", null);+ structure.add(DWORD, "bootconfig_size", null);+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorRamdiskTableEntryV4.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorRamdiskTableEntryV4.javanew file mode 100644index 0000000000..096a34f00b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootimg/VendorRamdiskTableEntryV4.java@@ -0,0 +1,97 @@+/* ###+ * 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.android.bootimg;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class VendorRamdiskTableEntryV4 implements StructConverter {++ private int ramdisk_size;+ private int ramdisk_offset;+ private int ramdisk_type;+ private String ramdisk_name;++ private int[] board_id;++ public VendorRamdiskTableEntryV4(BinaryReader reader) throws IOException {+ ramdisk_size = reader.readNextInt();+ ramdisk_offset = reader.readNextInt();+ ramdisk_type = reader.readNextInt();+ ramdisk_name = reader.readNextAsciiString(BootImageConstants.VENDOR_RAMDISK_NAME_SIZE);+ board_id =+ reader.readNextIntArray(BootImageConstants.VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE);+ }++ /**+ * Size in bytes for the ramdisk image+ * @return ramdisk size+ */+ public int getRamdiskSize() {+ return ramdisk_size;+ }++ /**+ * Offset to the ramdisk image in vendor ramdisk section+ * @return ramdisk offset+ */+ public int getRamdiskOffset() {+ return ramdisk_offset;+ }++ /**+ * Type of the ramdisk+ * @return ramdisk type+ */+ public int getRamdiskType() {+ return ramdisk_type;+ }++ /**+ * Ascii ramdisk name+ * @return the ascii ramdisk name+ */+ public String getRamdiskName() {+ return ramdisk_name;+ }++ /**+ * Hardware identifiers describing the board, soc or platform+ * which this ramdisk is intended to be loaded on.+ * @return the board ID+ */+ public int[] getBoardID() {+ return board_id;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("vendor_ramdisk_table_entry_v4", 0);+ structure.add(DWORD, "ramdisk_size", null);+ structure.add(DWORD, "ramdisk_offset", null);+ structure.add(DWORD, "ramdisk_type", null);+ structure.add(UTF8, BootImageConstants.VENDOR_RAMDISK_NAME_SIZE, "ramdisk_name", null);+ for (int i = 0; i < BootImageConstants.VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE; ++i) {+ structure.add(DWORD, "board_id_" + i, null);+ }+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderAnalyzer.javanew file mode 100644index 0000000000..4bff86449c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderAnalyzer.java@@ -0,0 +1,94 @@+/* ###+ * 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.android.bootldr;++import ghidra.app.services.AbstractAnalyzer;+import ghidra.app.services.AnalyzerType;+import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.framework.options.Options;+import ghidra.program.model.address.*;+import ghidra.program.model.data.DataType;+import ghidra.program.model.listing.*;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Annotates the structures contained in an Android Boot Loader image.+ */+public class AndroidBootLoaderAnalyzer extends AbstractAnalyzer {++ public AndroidBootLoaderAnalyzer() {+ super("Android Boot Loader", "Annotates the Android Boot Loader header components",+ AnalyzerType.BYTE_ANALYZER);+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return AndroidBootLoaderConstants.isBootLoader(program);+ }++ @Override+ public boolean canAnalyze(Program program) {+ return AndroidBootLoaderConstants.isBootLoader(program);+ }++ @Override+ public void registerOptions(Options options, Program program) {+ }++ @Override+ public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws CancelledException {++ AddressSpace addressSpace = program.getAddressFactory().getDefaultAddressSpace();++ Address headerAddress = program.getMinAddress();+ ByteProvider provider = new MemoryByteProvider(program.getMemory(), headerAddress);+ BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());+ try {+ AndroidBootLoaderHeader header = new AndroidBootLoaderHeader(reader);+ DataType headerDataType = header.toDataType();+ Data headerData = program.getListing().createData(headerAddress, headerDataType);+ if (headerData == null) {+ log.appendMsg("Unable to apply header data, stopping.");+ return false;+ }+ SymbolTable symbolTable = program.getSymbolTable();+ Symbol headerSymbol = symbolTable.getPrimarySymbol(headerAddress);+ if (headerSymbol == null) {+ symbolTable.createLabel(headerAddress, header.getMagic(), SourceType.ANALYSIS);+ }+ else {+ headerSymbol.setName(header.getMagic(), SourceType.ANALYSIS);+ }+ int runningOffset = header.getStartOffset();+ for (AndroidBootLoaderImageInfo imageInfo : header.getImageInfoList()) {+ Address address = addressSpace.getAddress(runningOffset);+ symbolTable.createLabel(address, imageInfo.getName(), SourceType.ANALYSIS);+ program.getBookmarkManager()+ .setBookmark(address, BookmarkType.ANALYSIS, "boot", imageInfo.getName());+ runningOffset += imageInfo.getSize();+ }+ return true;+ }+ catch (Exception e) {+ log.appendException(e);+ }+ return false;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderConstants.javanew file mode 100644index 0000000000..c9168581b0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderConstants.java@@ -0,0 +1,63 @@+/* ###+ * 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.android.bootldr;++import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.Memory;++/**+ * Source: https://android.googlesource.com/device/lge/mako/+/android-4.2.2_r1/releasetools.py+ * #+ * # #define BOOTLDR_MAGIC "BOOTLDR!"+ * # #define BOOTLDR_MAGIC_SIZE 8+ * #+ * # struct bootloader_images_header {+ * # char magic[BOOTLDR_MAGIC_SIZE];+ * # unsigned int num_images;+ * # unsigned int start_offset;+ * # unsigned int bootldr_size;+ * # struct {+ * # char name[64];+ * # unsigned int size;+ * # } img_info[];+ * # };+ */+public final class AndroidBootLoaderConstants {++ public static final String BOOTLDR_NAME = "bootloader_images_header";++ public static final String BOOTLDR_MAGIC = "BOOTLDR!";++ public static final int BOOTLDR_MAGIC_SIZE = BOOTLDR_MAGIC.length();++ public static final String IMG_INFO_NAME = "img_info";++ public static final int IMG_INFO_NAME_LENGTH = 64;++ public static boolean isBootLoader(Program program) {+ try {+ Memory memory = program.getMemory();+ byte[] bytes = new byte[AndroidBootLoaderConstants.BOOTLDR_MAGIC_SIZE];+ memory.getBytes(program.getMinAddress(), bytes);+ String magic = new String(bytes).trim();+ return AndroidBootLoaderConstants.BOOTLDR_MAGIC.equals(magic);+ }+ catch (Exception e) {+ //ignore+ }+ return false;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderFileSystem.javanew file mode 100644index 0000000000..f3b5996569--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderFileSystem.java@@ -0,0 +1,88 @@+/* ###+ * 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.android.bootldr;++import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.CryptoException;+import ghidra.util.task.TaskMonitor;++@FileSystemInfo(type = "androidbootloader", // ([a-z0-9]+ only)+ description = "Android Boot Loader Image", factory = GFileSystemBaseFactory.class)++public class AndroidBootLoaderFileSystem extends GFileSystemBase {+ private List<GFileImpl> fileList = new ArrayList<>();+ private List<Integer> offsetList = new ArrayList<>();++ public AndroidBootLoaderFileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ byte[] bytes = provider.readBytes(0, AndroidBootLoaderConstants.BOOTLDR_MAGIC_SIZE);+ return AndroidBootLoaderConstants.BOOTLDR_MAGIC.equals(new String(bytes).trim());+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {+ BinaryReader reader = new BinaryReader(provider, true /*might not always be LE*/ );+ AndroidBootLoaderHeader header = new AndroidBootLoaderHeader(reader);+ int runningOffset = header.getStartOffset();+ for (AndroidBootLoaderImageInfo imageInfo : header.getImageInfoList()) {++ GFileImpl file = GFileImpl.fromFilename(this, root, imageInfo.getName(), false,+ imageInfo.getSize(), null);++ fileList.add(file);+ offsetList.add(runningOffset);++ runningOffset += imageInfo.getSize();+ }+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ return new ArrayList<>(fileList);+ }++ @Override+ public String getInfo(GFile file, TaskMonitor monitor) {+ return null;+ }++ @Override+ protected InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException, CryptoException {++ int index = fileList.indexOf(file);+ int offset = offsetList.get(index);++ return provider.getInputStream(offset);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderHeader.javanew file mode 100644index 0000000000..bfed825e5e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderHeader.java@@ -0,0 +1,86 @@+/* ###+ * 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.android.bootldr;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+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;++/**+ * Class to represent the Android boot loader header.+ *+ */+public class AndroidBootLoaderHeader implements StructConverter {++ private String magic;+ private int numberOfImages;+ private int startOffset;+ private int bootLoaderSize;+ private List<AndroidBootLoaderImageInfo> imageInfoList =+ new ArrayList<AndroidBootLoaderImageInfo>();++ public AndroidBootLoaderHeader(BinaryReader reader) throws IOException {+ magic = reader.readNextAsciiString(AndroidBootLoaderConstants.BOOTLDR_MAGIC_SIZE);+ numberOfImages = reader.readNextInt();+ startOffset = reader.readNextInt();+ bootLoaderSize = reader.readNextInt();+ for (int i = 0; i < numberOfImages; ++i) {+ imageInfoList.add(new AndroidBootLoaderImageInfo(reader));+ }+ }++ public String getMagic() {+ return magic;+ }++ public int getNumberOfImages() {+ return numberOfImages;+ }++ public int getStartOffset() {+ return startOffset;+ }++ public int getBootLoaderSize() {+ return bootLoaderSize;+ }++ public List<AndroidBootLoaderImageInfo> getImageInfoList() {+ return new ArrayList<AndroidBootLoaderImageInfo>(imageInfoList);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure struct = new StructureDataType(+ AndroidBootLoaderConstants.BOOTLDR_NAME + "_" + numberOfImages, 0);+ struct.add(STRING, AndroidBootLoaderConstants.BOOTLDR_MAGIC_SIZE, "magic", null);+ struct.add(DWORD, "num_images", null);+ struct.add(DWORD, "start_offset", null);+ struct.add(DWORD, "bootldr_size", null);+ for (int i = 0; i < numberOfImages; ++i) {+ struct.add(imageInfoList.get(i).toDataType(), "img_info[" + i + "]", null);+ }+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderImageInfo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderImageInfo.javanew file mode 100644index 0000000000..b9a88fa5f6--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/bootldr/AndroidBootLoaderImageInfo.java@@ -0,0 +1,53 @@+/* ###+ * 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.android.bootldr;++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.Structure;+import ghidra.program.model.data.StructureDataType;+import ghidra.util.exception.DuplicateNameException;++public class AndroidBootLoaderImageInfo implements StructConverter {++ private String name;+ private int size;++ public AndroidBootLoaderImageInfo(BinaryReader reader) throws IOException {+ name = reader.readNextAsciiString(AndroidBootLoaderConstants.IMG_INFO_NAME_LENGTH).trim();+ size = reader.readNextInt();+ }++ public String getName() {+ return name;+ }++ public int getSize() {+ return size;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure struct = new StructureDataType(AndroidBootLoaderConstants.IMG_INFO_NAME, 0);+ struct.add(STRING, AndroidBootLoaderConstants.IMG_INFO_NAME_LENGTH, "magic", null);+ struct.add(DWORD, "size", null);+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexCodeItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexCodeItem.javanew file mode 100644index 0000000000..d8d79beebd--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexCodeItem.java@@ -0,0 +1,137 @@+/* ###+ * 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.android.cdex;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.dex.format.CodeItem;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/libdexfile/dex/compact_dex_file.h+ * <br>+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/compact_dex_file.h+ */+public class CDexCodeItem extends CodeItem {++ public final static short kRegistersSizeShift = 12;+ public final static short kInsSizeShift = 8;+ public final static short kOutsSizeShift = 4;+ public final static short kTriesSizeSizeShift = 0;+ public final static short kInsnsSizeShift = 5;++ public final static short kBitPreHeaderRegisterSize = 0;+ public final static short kBitPreHeaderInsSize = 1;+ public final static short kBitPreHeaderOutsSize = 2;+ public final static short kBitPreHeaderTriesSize = 3;+ public final static short kBitPreHeaderInsnsSize = 4;+ public final static short kFlagPreHeaderRegisterSize = 0x1 << kBitPreHeaderRegisterSize;+ public final static short kFlagPreHeaderInsSize = 0x1 << kBitPreHeaderInsSize;+ public final static short kFlagPreHeaderOutsSize = 0x1 << kBitPreHeaderOutsSize;+ public final static short kFlagPreHeaderTriesSize = 0x1 << kBitPreHeaderTriesSize;+ public final static short kFlagPreHeaderInsnsSize = 0x1 << kBitPreHeaderInsnsSize;++ public final static short kFlagPreHeaderCombined =+ kFlagPreHeaderRegisterSize | kFlagPreHeaderInsSize | kFlagPreHeaderOutsSize |+ kFlagPreHeaderTriesSize | kFlagPreHeaderInsnsSize;++ private short fields_;+ private short insns_count_and_flags_;++ public CDexCodeItem(BinaryReader reader) throws IOException {+ super();++ long startIndex = reader.getPointerIndex();//used for reading preheaders...++ /*+ * Packed code item data,+ * 4 bits each: [registers_size, ins_size, outs_size, tries_size]+ */+ fields_ = reader.readNextShort();++ registersSize = (short) ((fields_ >> kRegistersSizeShift) & 0xf);+ incomingSize = (short) ((fields_ >> kInsSizeShift) & 0xf);+ outgoingSize = (short) ((fields_ >> kOutsSizeShift) & 0xf);+ triesSize = (short) ((fields_ >> kOutsSizeShift) & 0xf);++ /*+ * 5 bits, if either of the fields required preheader extension,+ * 11 bits for the number of instruction code units.+ */+ insns_count_and_flags_ = reader.readNextShort();++ instructionSize = (Short.toUnsignedInt(insns_count_and_flags_) >> kInsnsSizeShift);++ if (hasPreHeader()) {+ if (hasPreHeader(kFlagPreHeaderInsnsSize)) {+ startIndex -= 2;+ instructionSize += reader.readShort(startIndex);+ startIndex -= 2;+ instructionSize += (reader.readShort(startIndex) << 16);+ }+ if (hasPreHeader(kFlagPreHeaderRegisterSize)) {+ startIndex -= 2;+ registersSize += reader.readShort(startIndex);+ }+ if (hasPreHeader(kFlagPreHeaderInsSize)) {+ startIndex -= 2;+ incomingSize += reader.readShort(startIndex);+ }+ if (hasPreHeader(kFlagPreHeaderOutsSize)) {+ startIndex -= 2;+ outgoingSize += reader.readShort(startIndex);+ }+ if (hasPreHeader(kFlagPreHeaderTriesSize)) {+ startIndex -= 2;+ triesSize += reader.readShort(startIndex);+ }+ }++ if (getInstructionSize() == 0) {+ instructionBytes = new byte[0];+ instructions = new short[0];+ }+ else {+ instructionBytes = reader.readNextByteArray(getInstructionSize() * 2);+ instructions = reader.readNextShortArray(getInstructionSize());+ }++ }++ public boolean hasPreHeader() {+ return (insns_count_and_flags_ & kFlagPreHeaderCombined) != 0;+ }++ public boolean hasPreHeader(short flag) {+ return (insns_count_and_flags_ & flag) != 0;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String name = "cdex_code_item" + "_" + (getInstructionSize() * 2);+ Structure structure = new StructureDataType(name, 0);+ structure.add(WORD, "fields_", null);+ structure.add(WORD, "insns_count_and_flags_", null);+ if (getInstructionSize() > 0) {+ structure.add(new ArrayDataType(WORD, getInstructionSize(), WORD.getLength()), "insns_",+ null);+ }+ structure.setCategoryPath(new CategoryPath("/dex/cdex_code_item"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexConstants.javanew file mode 100644index 0000000000..8a068cfa9b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexConstants.java@@ -0,0 +1,73 @@+/* ###+ * 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.android.cdex;++import ghidra.program.model.listing.Program;++/**+ * Android .CDEX files.+ *+ * CompactDex is a currently ART internal dex file format that aims to reduce+ * storage/RAM usage.+ *+ * https://android.googlesource.com/platform/art/+/master/runtime/dex/compact_dex_file.h+ *+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/compact_dex_file.h+ */+public final class CDexConstants {++ public final static String NAME = "Compact Dalvik Executable (CDEX)";++ /**+ * <pre>+ * static constexpr uint8_t kDexMagic[kDexMagicSize] = { 'c', 'd', 'e', 'x' };+ * </pre>+ */+ public final static String MAGIC = "cdex";++ /**+ * <pre>+ * static constexpr uint8_t kDexMagicVersion[] = {'0', '0', '1', '\0'};+ * </pre>+ */+ public final static String VERSION_001 = "001";++ /**+ * <pre>+ * static constexpr uint8_t kDexMagicVersion[] = {'0', '0', '2', '\0'};+ * </pre>+ */+ public final static String VERSION_002 = "002";++ /**+ * Returns true if the given program contain CDEX information.+ * @param program the program to inspect+ * @return true if the given program contain CDEX information+ */+ public final static boolean isCDEX(Program program) {+ if (program != null) {+ try {+ byte[] bytes = new byte[MAGIC.length()];+ program.getMemory().getBytes(program.getMinAddress(), bytes);+ return MAGIC.equals(new String(bytes));+ }+ catch (Exception e) {+ //ignore+ }+ }+ return false;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexHeader.javanew file mode 100644index 0000000000..ba377ee41b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexHeader.java@@ -0,0 +1,136 @@+/* ###+ * 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.android.cdex;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.program.model.data.*;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;++/**+ * CDEX Header extends DEX header, but adds additional members+ *+ * class Header : public DexFile::Header {+ *+ *+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/compact_dex_file.h+ */+public class CDexHeader extends DexHeader {++ private int feature_flags_;+ private int debug_info_offsets_pos_;+ private int debug_info_offsets_table_offset_;+ private int debug_info_base_;+ private int owned_data_begin_;+ private int owned_data_end_;++ public CDexHeader(BinaryReader reader) throws IOException {+ super(reader);++ feature_flags_ = reader.readNextInt();+ debug_info_offsets_pos_ = reader.readNextInt();+ debug_info_offsets_table_offset_ = reader.readNextInt();+ debug_info_base_ = reader.readNextInt();+ owned_data_begin_ = reader.readNextInt();+ owned_data_end_ = reader.readNextInt();+ }++ public int getFeatureFlags() {+ return feature_flags_;+ }++ /**+ * Position in the compact dex file for the debug info table data starts.+ * @return position in the compact dex file for the debug info table data starts+ */+ public int getDebugInfoOffsetsPos() {+ return debug_info_offsets_pos_;+ }++ /**+ * Offset into the debug info table data where the lookup table exists.+ * @return offset into the debug info table data where the lookup table is.+ */+ public int getDebugInfoOffsetsTableOffset() {+ return debug_info_offsets_table_offset_;+ }++ /**+ * Base offset of where debug info starts in the dex file.+ * @return base offset of where debug info starts in the dex file+ */+ public int getDebugInfoBase() {+ return debug_info_base_;+ }++ /**+ * Range of the shared data section owned by the dex file.+ * @return range of the shared data section owned by the dex file+ */+ public int getOwnedDataBegin() {+ return owned_data_begin_;+ }++ /**+ * Range of the shared data section owned by the dex file.+ * @return range of the shared data section owned by the dex file.+ */+ public int getOwnedDataEnd() {+ return owned_data_end_;+ }++ @Override+ public boolean isDataOffsetRelative() {+ return true;+ }++ @Override+ protected void checkMagic() throws IOException {+ if (!CDexConstants.MAGIC.equals(new String(getMagic()))) {+ throw new IOException("not a cdex file.");+ }+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ try {+ structure.setName("cdex_header");+ }+ catch (InvalidNameException e) {+ //ignore, can't happen+ }+ structure.setCategoryPath(new CategoryPath("/cdex"));++ structure.add(DWORD, "feature_flags_", null);+ structure.add(DWORD, "debug_info_offsets_pos_", null);+ structure.add(DWORD, "debug_info_offsets_table_offset_", null);+ structure.add(DWORD, "debug_info_base_", null);+ structure.add(DWORD, "owned_data_begin_", null);+ structure.add(DWORD, "owned_data_end_", null);++ // remove comments to prevent data type conflicts+ for (DataTypeComponent component : structure.getComponents()) {+ component.setComment(null);+ }++ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexLoader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexLoader.javanew file mode 100644index 0000000000..e92522141d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/CDexLoader.java@@ -0,0 +1,179 @@+/* ###+ * 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.android.cdex;++import java.io.IOException;+import java.io.InputStream;+import java.util.*;++import ghidra.app.util.Option;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.importer.MessageLog;+import ghidra.app.util.opinion.*;+import ghidra.file.formats.android.dex.DexHeaderFactory;+import ghidra.file.formats.android.dex.format.*;+import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.MemoryBlock;+import ghidra.util.task.TaskMonitor;++public class CDexLoader extends DexLoader {++ @Override+ public String getName() {+ return CDexConstants.NAME;+ }++ @Override+ public LoaderTier getTier() {+ return LoaderTier.UNTARGETED_LOADER;+ }++ @Override+ public int getTierPriority() {+ return 100;+ }++ @Override+ public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {+ List<LoadSpec> loadSpecs = new ArrayList<>();++ BinaryReader reader = new BinaryReader(provider, true);+ try {+ byte[] magicBytes = provider.readBytes(0, CDexConstants.MAGIC.length());+ if (CDexConstants.MAGIC.equals(new String(magicBytes))) {+ DexHeader header = DexHeaderFactory.getDexHeader(reader);//should be CDEX+ if (CDexConstants.MAGIC.equals(new String(header.getMagic()))) {+ List<QueryResult> queries =+ QueryOpinionService.query(getName(), DexConstants.MACHINE, null);+ for (QueryResult result : queries) {+ loadSpecs.add(new LoadSpec(this, 0, result));+ }+ if (loadSpecs.isEmpty()) {+ loadSpecs.add(new LoadSpec(this, 0, true));+ }+ }+ }+ }+ catch (Exception e) {+ //ignore+ }+ return loadSpecs;+ }++ @Override+ public boolean supportsLoadIntoProgram() {+ return true;+ }++ @Override+ public void load(ByteProvider provider, LoadSpec loadSpec, List<Option> options,+ Program program, TaskMonitor monitor, MessageLog log) throws IOException {++ monitor.setMessage("CDEX Loader: creating cdex memory");+ try {+ Address start = program.getAddressFactory().getDefaultAddressSpace().getAddress(0x0);+ long length = provider.length();++ try (InputStream inputStream = provider.getInputStream(0)) {+ program.getMemory()+ .createInitializedBlock(".cdex", start, inputStream, length, monitor,+ false);+ }++ BinaryReader reader = new BinaryReader(provider, true);+ DexHeader header = DexHeaderFactory.getDexHeader(reader);++ monitor.setMessage("CDEX Loader: creating method byte code");++ createMethodLookupMemoryBlock(program, monitor);+ createMethodByteCodeBlock(program, length, monitor);++ for (ClassDefItem item : header.getClassDefs()) {+ monitor.checkCanceled();++ ClassDataItem classDataItem = item.getClassDataItem();+ if (classDataItem == null) {+ continue;+ }++ createMethods(program, header, item, classDataItem.getDirectMethods(), monitor,+ log);+ createMethods(program, header, item, classDataItem.getVirtualMethods(), monitor,+ log);+ }+ }+ catch (Exception e) {+ log.appendException(e);+ }+ }++ private void createMethodByteCodeBlock(Program program, long length, TaskMonitor monitor)+ throws Exception {+ Address address = toAddr(program, DexUtil.METHOD_ADDRESS);+ MemoryBlock block = program.getMemory()+ .createInitializedBlock("method_bytecode", address, length, (byte) 0xff, monitor,+ false);+ block.setRead(true);+ block.setWrite(false);+ block.setExecute(true);+ }++ private void createMethodLookupMemoryBlock(Program program, TaskMonitor monitor)+ throws Exception {+ Address address = toAddr(program, DexUtil.LOOKUP_ADDRESS);+ MemoryBlock block = program.getMemory()+ .createInitializedBlock("method_lookup", address, DexUtil.MAX_METHOD_LENGTH,+ (byte) 0xff, monitor, false);+ block.setRead(true);+ block.setWrite(false);+ block.setExecute(false);+ }++ private void createMethods(Program program, DexHeader header, ClassDefItem item,+ List<EncodedMethod> methods, TaskMonitor monitor, MessageLog log) throws Exception {+ for (int i = 0; i < methods.size(); ++i) {+ monitor.checkCanceled();++ EncodedMethod encodedMethod = methods.get(i);++ CodeItem codeItem = encodedMethod.getCodeItem();++ Address methodIndexAddress =+ DexUtil.toLookupAddress(program, encodedMethod.getMethodIndex());++ if (codeItem == null) {+ //external method, ignore+ }+ else {+ Address methodAddress =+ toAddr(program, DexUtil.METHOD_ADDRESS + encodedMethod.getCodeOffset());++ byte[] instructionBytes = codeItem.getInstructionBytes();+ program.getMemory().setBytes(methodAddress, instructionBytes);++ program.getMemory().setInt(methodIndexAddress, (int) methodAddress.getOffset());+ }+ }+ }++ private Address toAddr(Program program, long offset) {+ return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/FeatureFlags.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/FeatureFlags.javanew file mode 100644index 0000000000..97ff4f8a42--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/cdex/FeatureFlags.java@@ -0,0 +1,21 @@+/* ###+ * 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.android.cdex;++public final class FeatureFlags {++ public final static int kDefaultMethods = 0x1;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/DexHeaderFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/DexHeaderFactory.javanew file mode 100644index 0000000000..76f9ab91a7--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/DexHeaderFactory.java@@ -0,0 +1,91 @@+/* ###+ * 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.android.dex;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.MemoryByteProvider;+import ghidra.file.formats.android.cdex.CDexConstants;+import ghidra.file.formats.android.cdex.CDexHeader;+import ghidra.file.formats.android.dex.format.DexConstants;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Program;++public final class DexHeaderFactory {++ /**+ * Attempts to create DEX header starting at minimum address of the program.+ * @param program the program to use to create DEX header+ * @return the DEX header+ * @throws IOException should an error occur reading DEX bytes+ */+ public final static DexHeader getDexHeader(Program program) throws IOException {+ return getDexHeader(program, program.getMinAddress());+ }++ /**+ * Attempts to create DEX header starting at the specified address of the program.+ * @param program the program to use to create DEX header+ * @param address the address in the program to look for DEX header+ * @return the DEX header+ * @throws IOException should an error occur reading DEX bytes+ */+ public final static DexHeader getDexHeader(Program program, Address address)+ throws IOException {+ ByteProvider provider = new MemoryByteProvider(program.getMemory(), address);+ return getDexHeader(provider, !program.getLanguage().isBigEndian());+ }++ /**+ * Attempts to create DEX header using the specified Byte Provider.+ * @param provider the byte provider to use to create DEX header+ * @param isLittleEndian true if LE, false if BE+ * @return the DEX header+ * @throws IOException should an error occur reading DEX bytes+ */+ public final static DexHeader getDexHeader(ByteProvider provider, boolean isLittleEndian)+ throws IOException {+ BinaryReader reader = new BinaryReader(provider, isLittleEndian);+ return getDexHeader(reader);+ }++ /**+ * Attempts to create DEX header using the specified Byte Provider.+ * NOTE: Use a new binary reader instance, where the underlying ByteProvider is+ * based to start of DEX/CDEX. Reading CDEX format requires lots of re-indexing.+ * @param reader the binary reader to use to create DEX header+ * @return the DEX header+ * @throws IOException should an error occur reading DEX bytes+ */+ public final static DexHeader getDexHeader(BinaryReader reader) throws IOException {+ long index = reader.getPointerIndex();+ String magic = new String(reader.readByteArray(index, 4));+ if (DexConstants.DEX_MAGIC_BASE.equals(magic)) {+ DexHeader header = new DexHeader(reader);+ header.parse(reader);+ return header;+ }+ if (CDexConstants.MAGIC.equals(magic)) {+ CDexHeader header = new CDexHeader(reader);+ header.parse(reader);+ return header;+ }+ throw new IOException("Not a recognized DEX/CDEX variant: " + magic);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/DexToJarExceptionHandler.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/DexToJarExceptionHandler.javaindex 1bcc07eb66..bc250296c3 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/DexToJarExceptionHandler.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/DexToJarExceptionHandler.java@@ -25,7 +25,8 @@ class DexToJarExceptionHandler implements DexExceptionHandler {private Exception e;@Override- public void handleMethodTranslateException(Method method, DexMethodNode node, MethodVisitor visitor, Exception e) {+ public void handleMethodTranslateException(Method method, DexMethodNode node,+ MethodVisitor visitor, Exception e) {this.e = e;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexAnalysisState.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexAnalysisState.javaindex 9c13c57439..366cb893c4 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexAnalysisState.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexAnalysisState.java@@ -21,12 +21,14 @@ import java.util.TreeMap;import ghidra.app.plugin.core.analysis.AnalysisState;import ghidra.app.plugin.core.analysis.AnalysisStateInfo;-import ghidra.app.util.bin.*;+import ghidra.file.formats.android.dex.DexHeaderFactory;import ghidra.file.formats.android.dex.format.*;import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.framework.main.AppInfo;import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressSpace;import ghidra.program.model.listing.Program;+import ghidra.util.SystemUtilities;/*** This class is used to cache the {@link DexHeader} which holds constant pool and method information.@@ -52,8 +54,8 @@ final public class DexAnalysisState implements AnalysisState {private void installMethodList(AddressSpace defaultAddressSpace,List<EncodedMethod> methodList) {for (EncodedMethod encodedMethod : methodList) {- Address methodAddress = defaultAddressSpace.getAddress(- DexUtil.METHOD_ADDRESS + encodedMethod.getCodeOffset());+ Address methodAddress = defaultAddressSpace+ .getAddress(DexUtil.METHOD_ADDRESS + encodedMethod.getCodeOffset());methodMap.put(methodAddress, encodedMethod);}}@@ -108,10 +110,21 @@ final public class DexAnalysisState implements AnalysisState {DexAnalysisState analysisState =AnalysisStateInfo.getAnalysisState(program, DexAnalysisState.class);if (analysisState == null) {- ByteProvider provider =- new MemoryByteProvider(program.getMemory(), program.getMinAddress());- BinaryReader reader = new BinaryReader(provider, true);- DexHeader dexHeader = new DexHeader(reader);+ DexHeader dexHeader = DexHeaderFactory.getDexHeader(program);+ analysisState = new DexAnalysisState(program, dexHeader);+ AnalysisStateInfo.putAnalysisState(program, analysisState);+ }+ return analysisState;+ }++ public static DexAnalysisState getState(Program program, Address address) throws IOException {+ DexAnalysisState analysisState =+ AnalysisStateInfo.getAnalysisState(program, DexAnalysisState.class);+ if (SystemUtilities.isInDevelopmentMode()) {+ analysisState = null; //always generate when in debug mode+ }+ if (analysisState == null) {+ DexHeader dexHeader = DexHeaderFactory.getDexHeader(program, address);analysisState = new DexAnalysisState(program, dexHeader);AnalysisStateInfo.putAnalysisState(program, analysisState);}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexCondenseFillerBytesAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexCondenseFillerBytesAnalyzer.javaindex e743d729a2..154b46c608 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexCondenseFillerBytesAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexCondenseFillerBytesAnalyzer.java@@ -21,6 +21,7 @@ import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.bin.MemoryByteProvider;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.file.formats.android.cdex.CDexConstants;import ghidra.file.formats.android.dex.format.DexConstants;import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.address.*;@@ -33,32 +34,36 @@ import ghidra.util.task.TaskMonitor;public class DexCondenseFillerBytesAnalyzer extends FileFormatAnalyzer {@Override- public boolean analyze( Program program, AddressSetView set, TaskMonitor monitor, MessageLog log ) throws Exception {- AlignmentDataType alignmentDataType = new AlignmentDataType( );+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {+ AlignmentDataType alignmentDataType = new AlignmentDataType();- Address address = toAddr( program, DexUtil.METHOD_ADDRESS );- MemoryBlock block = program.getMemory().getBlock( address );+ Address address = toAddr(program, DexUtil.METHOD_ADDRESS);+ MemoryBlock block = program.getMemory().getBlock(address);- if ( block == null ) {- log.appendMsg( "Can't locate block with method byte code!" );+ if (block == null) {+ log.appendMsg("Can't locate block with method byte code!");return false;}- AddressSet blockSet = new AddressSet( block.getStart( ), block.getEnd( ) );+ AddressSet blockSet = new AddressSet(block.getStart(), block.getEnd());- AddressSetView undefinedSet = program.getListing().getUndefinedRanges( blockSet, true, monitor );+ AddressSetView undefinedSet =+ program.getListing().getUndefinedRanges(blockSet, true, monitor);- monitor.setMaximum( undefinedSet.getNumAddressRanges() );- monitor.setProgress( 0 );- monitor.setMessage( "DEX: condensing filler bytes" );+ monitor.setMaximum(undefinedSet.getNumAddressRanges());+ monitor.setProgress(0);+ monitor.setMessage("DEX: condensing filler bytes");AddressRangeIterator addressRanges = undefinedSet.getAddressRanges();- while ( addressRanges.hasNext( ) ) {- monitor.checkCanceled( );- monitor.incrementProgress( 1 );+ while (addressRanges.hasNext()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);AddressRange addressRange = addressRanges.next();- if ( isRangeAllSameBytes( program, addressRange, (byte) 0xff, monitor ) ) {- program.getListing().createData( addressRange.getMinAddress(), alignmentDataType, (int)addressRange.getLength() );+ if (isRangeAllSameBytes(program, addressRange, (byte) 0xff, monitor)) {+ program.getListing()+ .createData(addressRange.getMinAddress(), alignmentDataType,+ (int) addressRange.getLength());}}@@ -68,53 +73,55 @@ public class DexCondenseFillerBytesAnalyzer extends FileFormatAnalyzer {}@Override- public boolean canAnalyze( Program program ) {- ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getMinAddress( ) );- return DexConstants.isDexFile( provider );+ public boolean canAnalyze(Program program) {+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), program.getMinAddress());+ return DexConstants.isDexFile(provider) || CDexConstants.isCDEX(program);}@Override- public AnalyzerType getAnalysisType( ) {+ public AnalyzerType getAnalysisType() {return AnalyzerType.BYTE_ANALYZER;}@Override- public boolean getDefaultEnablement( Program program ) {+ public boolean getDefaultEnablement(Program program) {return true;}@Override- public String getDescription( ) {- return "Condenses all filler bytes in a DEX file";+ public String getDescription() {+ return "Condenses all filler bytes in a DEX/CDEX file";}@Override- public String getName( ) {- return "Android DEX Condense Filler Bytes";+ public String getName() {+ return "Android DEX/CDEX Condense Filler Bytes";}@Override- public AnalysisPriority getPriority( ) {- return new AnalysisPriority( Integer.MAX_VALUE );+ public AnalysisPriority getPriority() {+ return new AnalysisPriority(Integer.MAX_VALUE);}@Override- public boolean isPrototype( ) {+ public boolean isPrototype() {return false;}- private boolean isRangeAllSameBytes( Program program, AddressRange addressRange, byte value, TaskMonitor monitor ) throws CancelledException {- byte [] bytes = new byte[ (int) addressRange.getLength() ];+ private boolean isRangeAllSameBytes(Program program, AddressRange addressRange, byte value,+ TaskMonitor monitor) throws CancelledException {+ byte[] bytes = new byte[(int) addressRange.getLength()];try {- program.getMemory().getBytes( addressRange.getMinAddress(), bytes ) ;+ program.getMemory().getBytes(addressRange.getMinAddress(), bytes);}- catch ( Exception e ) {+ catch (Exception e) {return false;//ignore}- for ( byte b : bytes ) {- monitor.checkCanceled( );- if ( b != value ) {+ for (byte b : bytes) {+ monitor.checkCanceled();+ if (b != value) {return false;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexExceptionHandlersAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexExceptionHandlersAnalyzer.javaindex 15a9665b95..15ce673ca4 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexExceptionHandlersAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexExceptionHandlersAnalyzer.java@@ -24,6 +24,7 @@ import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.bin.MemoryByteProvider;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.file.formats.android.cdex.CDexConstants;import ghidra.file.formats.android.dex.format.*;import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.address.*;@@ -50,7 +51,7 @@ public class DexExceptionHandlersAnalyzer extends FileFormatAnalyzer {public boolean canAnalyze(Program program) {ByteProvider provider =new MemoryByteProvider(program.getMemory(), program.getMinAddress());- return DexConstants.isDexFile(provider);+ return DexConstants.isDexFile(provider) || CDexConstants.isCDEX(program);}@Override@@ -65,12 +66,12 @@ public class DexExceptionHandlersAnalyzer extends FileFormatAnalyzer {@Overridepublic String getDescription() {- return "Disassembles the exception handlers in a DEX file";+ return "Disassembles the exception handlers in a DEX/CDEX file";}@Overridepublic String getName() {- return "Android DEX Exception Handlers";+ return "Android DEX/CDEX Exception Handlers";}@Override@@ -176,8 +177,8 @@ public class DexExceptionHandlersAnalyzer extends FileFormatAnalyzer {private void createCatchSymbol(Program program, String catchName, Address catchAddress) {Namespace catchNameSpace = DexUtil.getOrCreateNameSpace(program, "CatchHandlers");try {- program.getSymbolTable().createLabel(catchAddress, catchName, catchNameSpace,- SourceType.ANALYSIS);+ program.getSymbolTable()+ .createLabel(catchAddress, catchName, catchNameSpace, SourceType.ANALYSIS);}catch (Exception e) {Msg.error(this, "Error creating label", e);diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexHeaderFormatAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexHeaderFormatAnalyzer.javaindex f7349e2169..0955a35b14 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexHeaderFormatAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexHeaderFormatAnalyzer.java@@ -15,31 +15,17 @@*/package ghidra.file.formats.android.dex.analyzer;-import java.io.IOException;-import java.util.ArrayList;-import java.util.List;--import ghidra.app.cmd.disassemble.DisassembleCommand;import ghidra.app.services.AnalysisPriority;import ghidra.app.services.AnalyzerType;import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.bin.MemoryByteProvider;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;-import ghidra.file.formats.android.dex.format.*;-import ghidra.file.formats.android.dex.util.DexUtil;-import ghidra.program.database.ProgramCompilerSpec;+import ghidra.file.formats.android.cdex.CDexConstants;+import ghidra.file.formats.android.dex.format.DexConstants;import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressSetView;-import ghidra.program.model.data.*;-import ghidra.program.model.lang.Language;-import ghidra.program.model.lang.Register;-import ghidra.program.model.listing.*;-import ghidra.program.model.listing.Function.FunctionUpdateType;-import ghidra.program.model.mem.Memory;-import ghidra.program.model.mem.MemoryBlock;-import ghidra.program.model.symbol.*;-import ghidra.util.exception.*;+import ghidra.program.model.listing.Program;import ghidra.util.task.TaskMonitor;public class DexHeaderFormatAnalyzer extends FileFormatAnalyzer {@@ -48,40 +34,15 @@ public class DexHeaderFormatAnalyzer extends FileFormatAnalyzer {public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)throws Exception {- Address startAddress = toAddr(program, 0x0);+ Address baseAddress = toAddr(program, 0x0);- if (getDataAt(program, startAddress) != null) {+ if (getDataAt(program, baseAddress) != null) {log.appendMsg("data already exists.");return true;}- Memory memory = program.getMemory();- MemoryBlock block = memory.getBlock(startAddress);- block.setRead(true);- block.setWrite(false);- block.setExecute(false);-- DexAnalysisState analysisState = DexAnalysisState.getState(program);- DexHeader header = analysisState.getHeader();- processHeader(program, header);-- createInitialFragments(program, header, monitor);-- ProgramCompilerSpec.enableJavaLanguageDecompilation(program);- createNamespaces(program, header, monitor, log);- processMap(program, header, monitor, log);- processStrings(program, header, monitor, log);- processTypes(program, header, monitor, log);- processPrototypes(program, header, monitor, log);- processFields(program, header, monitor, log);- processMethods(program, header, monitor, log);- processClassDefs(program, header, monitor, log);- createProgramDataTypes(program, header, monitor, log);-- createMethods(program, header, monitor, log);-- monitor.setMessage("DEX: cleaning up tree");- removeEmptyFragments(program);+ DexHeaderFormatMarkup markup = new DexHeaderFormatMarkup(program, baseAddress);+ markup.markup(monitor, log);return true;}@@ -90,7 +51,7 @@ public class DexHeaderFormatAnalyzer extends FileFormatAnalyzer {public boolean canAnalyze(Program program) {ByteProvider provider =new MemoryByteProvider(program.getMemory(), program.getMinAddress());- return DexConstants.isDexFile(provider);+ return DexConstants.isDexFile(provider) || CDexConstants.isCDEX(program);}@Override@@ -105,12 +66,12 @@ public class DexHeaderFormatAnalyzer extends FileFormatAnalyzer {@Overridepublic String getDescription() {- return "Android DEX Header Format";+ return "Android Dalvik EXecutable (DEX) / Compact DEX (CDEX) Header Format";}@Overridepublic String getName() {- return "Android DEX Header Format";+ return "Android DEX/CDEX Header Format";}@Override@@ -122,865 +83,4 @@ public class DexHeaderFormatAnalyzer extends FileFormatAnalyzer {public boolean isPrototype() {return false;}-- private void createNamespaces(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: creating namespaces");- monitor.setMaximum(header.getClassDefsIdsSize());- monitor.setProgress(0);-- // NOTE:- // MUST CREATE ALL OF THE CLASSES AND NAMESPACES FIRST- // OTHERWISE GHIDRA CANNOT HANDLE OBFUSCATED PACKAGES NAMES- // FOR EXAMPLE, "a.a.a.a" and "a.a.a" WHERE THE LAST A IS A METHOD- for (ClassDefItem item : header.getClassDefs()) {- monitor.checkCanceled();- monitor.incrementProgress(1);-- String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());- Namespace classNameSpace =- DexUtil.createNameSpaceFromMangledClassName(program, className);- if (classNameSpace == null) {- log.appendMsg("Failed to create namespace: " + className);- }- }- }-- private void createMethods(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: creating methods");- monitor.setMaximum(header.getClassDefsIdsSize());- monitor.setProgress(0);- for (ClassDefItem item : header.getClassDefs()) {- monitor.checkCanceled();- monitor.incrementProgress(1);-- ClassDataItem classDataItem = item.getClassDataItem();- if (classDataItem == null) {- continue;- }-- createMethods(program, header, item, classDataItem.getDirectMethods(), monitor, log);- createMethods(program, header, item, classDataItem.getVirtualMethods(), monitor, log);- }- }-- private void createMethods(Program program, DexHeader header, ClassDefItem item,- List<EncodedMethod> methods, TaskMonitor monitor, MessageLog log) throws Exception {- String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());- Namespace classNameSpace = DexUtil.createNameSpaceFromMangledClassName(program, className);- if (classNameSpace == null) {- log.appendMsg("No namespace: Skipping methods for " + className);- return;- }-- for (EncodedMethod encodedMethod : methods) {- monitor.checkCanceled();-- MethodIDItem methodID = header.getMethods().get(encodedMethod.getMethodIndex());- String methodName = DexUtil.convertToString(header, methodID.getNameIndex());-- if ((AccessFlags.ACC_CONSTRUCTOR & encodedMethod.getAccessFlags()) != 0) {- methodName = classNameSpace.getName();- }- CodeItem codeItem = encodedMethod.getCodeItem();-- if (codeItem == null) {//external-// Address externalAddress = toAddr( program, DexUtil.EXTERNAL_ADDRESS + ( 4 * methodIndex ) );-// createMethodSymbol( program, externalAddress, methodName, classNameSpace );-// createMethodComment( program, externalAddress, header, item, methodID, encodedMethod, codeItem, monitor );-// createData( program, externalAddress, new PointerDataType( ) );-// Function method = createFunction( program, externalAddress );-// method.setCustomVariableStorage( true );-//-// Address methodIndexAddress = toAddr( program, DexUtil.LOOKUP_ADDRESS + ( methodIndex * 4 ) );-// Symbol primarySymbol = program.getSymbolTable().getPrimarySymbol( methodIndexAddress );-// program.getReferenceManager().addExternalReference( methodIndexAddress, (Namespace) null, primarySymbol.getName( ), null, SourceType.ANALYSIS, 0, RefType.EXTERNAL_REF );- }- else {- Address methodAddress =- toAddr(program, DexUtil.METHOD_ADDRESS + encodedMethod.getCodeOffset());- createMethodSymbol(program, methodAddress, methodName, classNameSpace, log);- createMethodComment(program, methodAddress, header, item, methodID, encodedMethod,- codeItem, monitor);- disassembleMethod(program, header, className, encodedMethod.isStatic(),- methodAddress, methodID, codeItem, monitor, log);- }- }- }-- private Symbol createMethodSymbol(Program program, Address methodAddress, String methodName,- Namespace classNameSpace, MessageLog log) {- program.getSymbolTable().addExternalEntryPoint(methodAddress);- try {- return program.getSymbolTable()- .createLabel(methodAddress, methodName, classNameSpace, SourceType.ANALYSIS);- }- catch (InvalidInputException e) {- log.appendException(e);- return null;- }- }-- private void createMethodComment(Program program, Address methodAddress, DexHeader header,- ClassDefItem item, MethodIDItem methodID, EncodedMethod encodedMethod,- CodeItem codeItem, TaskMonitor monitor) throws CancelledException {-- String methodSignature =- DexUtil.convertPrototypeIndexToString(header, methodID.getProtoIndex());- StringBuilder commentBuilder = new StringBuilder();- commentBuilder.append(item.toString(header, -1, monitor) + "\n");- commentBuilder.append("Method Signature: " + methodSignature + "\n");- commentBuilder.append("Method Access Flags:\n");- commentBuilder.append(AccessFlags.toString(encodedMethod.getAccessFlags()) + "\n");- if (codeItem != null) {- commentBuilder.append("Method Register Size: " + codeItem.getRegistersSize() + "\n");- commentBuilder.append("Method Incoming Size: " + codeItem.getIncomingSize() + "\n");- commentBuilder.append("Method Outgoing Size: " + codeItem.getOutgoingSize() + "\n");- commentBuilder.append("Method Debug Info Offset: 0x" +- Integer.toHexString(codeItem.getDebugInfoOffset()) + "\n");- }- commentBuilder- .append("Method ID Offset: 0x" + Long.toHexString(methodID.getFileOffset()) + "\n");- setPlateComment(program, methodAddress, commentBuilder.toString());- }-- private void disassembleMethod(Program program, DexHeader header, String className,- boolean isStatic, Address methodAddress, MethodIDItem methodID, CodeItem codeItem,- TaskMonitor monitor, MessageLog log) throws CancelledException {-- Language language = program.getLanguage();-- DisassembleCommand dCommand = new DisassembleCommand(methodAddress, null, true);- dCommand.applyTo(program);-- Function method = createFunction(program, methodAddress);- if (method == null) {- log.appendMsg("Failed to create method at " + methodAddress);- return;- }-- int registerIndex = codeItem.getRegistersSize() - codeItem.getIncomingSize();-- //TODO create local variables in between- for (int i = 0; i < registerIndex; ++i) {- DataType localDataType = null;//TODO- Register localRegister = language.getRegister("v" + i);- try {- LocalVariableImpl local =- new LocalVariableImpl("local_" + i, 0, localDataType, localRegister, program);- method.addLocalVariable(local, SourceType.ANALYSIS);- }- catch (Exception e) {- log.appendException(e);- }- }-- Variable returnVar = null;- ArrayList<Variable> paramList = new ArrayList<>();-- int prototypeIndex = methodID.getProtoIndex() & 0xffff;- PrototypesIDItem prototype = header.getPrototypes().get(prototypeIndex);-- try {- String returnTypeString =- DexUtil.convertTypeIndexToString(header, prototype.getReturnTypeIndex());- DataType returnDataType =- DexUtil.toDataType(program.getDataTypeManager(), returnTypeString);- returnVar = new ReturnParameterImpl(returnDataType, program);-- if (!isStatic) {- String classString =- DexUtil.convertTypeIndexToString(header, methodID.getClassIndex());- DataType thisDataType =- DexUtil.toDataType(program.getDataTypeManager(), classString);- String parameterName = "this";- Variable param = new ParameterImpl(parameterName, thisDataType, program);- paramList.add(param);- }-- TypeList parameters = prototype.getParameters();- if (parameters != null) {- for (TypeItem parameterTypeItem : parameters.getItems()) {- monitor.checkCanceled();- String parameterTypeString =- DexUtil.convertTypeIndexToString(header, parameterTypeItem.getType());- DataType parameterDataType =- DexUtil.toDataType(program.getDataTypeManager(), parameterTypeString);- String parameterName =- getParameterName(header, codeItem, paramList.size() - (isStatic ? 0 : 1));- if (parameterName == null) {- parameterName = "p" + paramList.size();- }- Variable param = new ParameterImpl(parameterName, parameterDataType, program);- paramList.add(param);- }- }- method.updateFunction("__stdcall", returnVar, paramList,- FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS);- }- catch (InvalidInputException ex) {- log.appendException(ex);- }- catch (DuplicateNameException ex) {- log.appendException(ex);- }- }-- private String getParameterName(DexHeader header, CodeItem codeItem, int parameterOrdinal) {- try {- DebugInfoItem debugInfo = codeItem.getDebugInfo();- int[] debugParameterNames = debugInfo.getParameterNames();- List<StringIDItem> strings = header.getStrings();- StringIDItem stringIDItem = strings.get(debugParameterNames[parameterOrdinal]);- StringDataItem stringDataItem = stringIDItem.getStringDataItem();- return stringDataItem.getString();- }- catch (Exception e) {- // IndexOutOfBoundsException- }- return null;- }-- private void processHeader(Program program, DexHeader header) throws Exception {- Address headerAddress = toAddr(program, 0x0);- DataType headerDataType = header.toDataType();- createData(program, headerAddress, headerDataType);- createFragment(program, "header", headerAddress,- headerAddress.add(headerDataType.getLength()));- }-- private void processClassDefs(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: processing class definitions");- monitor.setMaximum(header.getClassDefsIdsSize());- monitor.setProgress(0);-- Address address = toAddr(program, header.getClassDefsIdsOffset());-- int index = 0;-- for (ClassDefItem item : header.getClassDefs()) {- monitor.checkCanceled();- monitor.incrementProgress(1);-- DataType dataType = item.toDataType();- createData(program, address, dataType);- createFragment(program, "classes", address, address.add(dataType.getLength()));- createClassDefSymbol(program, header, item, address);-- processClassInterfaces(program, header, item, monitor);- processClassAnnotations(program, item, monitor, log);- processClassDataItem(program, header, item, monitor);- processClassStaticValues(program, header, item, monitor);-- setPlateComment(program, address, item.toString(header, index, monitor));-- address = address.add(dataType.getLength());- ++index;- }- }-- private void createProgramDataTypes(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws CancelledException {- monitor.setMessage("DEX: creating program datatypes");- monitor.setMaximum(header.getTypeIdsSize());- monitor.setProgress(0);- DataTypeManager dtm = program.getDataTypeManager();- int curGroup = -1;- CategoryPath handlePath = null;- List<TypeIDItem> types = header.getTypes();- for (int typeID = 0; typeID < header.getTypeIdsSize(); ++typeID) {- TypeIDItem item = types.get(typeID);- monitor.checkCanceled();- monitor.incrementProgress(1);- String name = DexUtil.convertToString(header, item.getDescriptorIndex());- String[] path = DexUtil.convertClassStringToPathArray(DexUtil.CATEGORY_PATH, name);- if (path == null) {- continue;- }-- StringBuilder builder = new StringBuilder();- for (int i = 0; i < path.length - 1; ++i) {- builder.append(CategoryPath.DELIMITER_CHAR);- builder.append(path[i]);- }- CategoryPath catPath = new CategoryPath(builder.toString());- DataType dataType =- new TypedefDataType(catPath, path[path.length - 1], DWordDataType.dataType);- dataType = dtm.resolve(dataType, DataTypeConflictHandler.DEFAULT_HANDLER);-- // Create unchanging typedef to each class based on typeID, so we can find class type even if name changes- if (typeID / 100 != curGroup) {- curGroup = typeID / 100;- builder = new StringBuilder();- builder.append(DexUtil.HANDLE_PATH);- builder.append("group").append(curGroup);- handlePath = new CategoryPath(builder.toString());- }- DataType handleType = new TypedefDataType(handlePath, "type" + typeID, dataType);- dtm.resolve(handleType, DataTypeConflictHandler.DEFAULT_HANDLER);- }- }-- private void createClassDefSymbol(Program program, DexHeader header, ClassDefItem item,- Address address) {- String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());- SymbolTable symbolTable = program.getSymbolTable();- try {- Namespace nameSpace = DexUtil.createNameSpaceFromMangledClassName(program, className);- if (nameSpace != null) {- symbolTable.createLabel(address, DexUtil.CLASSDEF_NAME, nameSpace,- SourceType.ANALYSIS);- }- }- catch (Exception ex) {- // Don't worry if we can't laydown this symbol- }- }-- private void processClassStaticValues(Program program, DexHeader header, ClassDefItem item,- TaskMonitor monitor) throws DuplicateNameException, IOException, Exception {- if (item.getStaticValuesOffset() > 0) {- EncodedArrayItem staticValues = item.getStaticValues();- Address staticAddress = toAddr(program, item.getStaticValuesOffset());- DataType staticDataType = staticValues.toDataType();- createData(program, staticAddress, staticDataType);- createFragment(program, "class_static_values", staticAddress,- staticAddress.add(staticDataType.getLength()));-- StringBuilder builder = new StringBuilder();- builder.append("Class: " +- DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n\n");- builder.append("Static Values:" + "\n");- for (byte b : staticValues.getArray().getValues()) {- builder.append(Integer.toHexString(b & 0xff) + " ");- }- setPlateComment(program, staticAddress, builder.toString());- }- }-- private void processClassDataItem(Program program, DexHeader header, ClassDefItem item,- TaskMonitor monitor) throws DuplicateNameException, IOException, Exception {- if (item.getClassDataOffset() > 0) {- ClassDataItem classDataItem = item.getClassDataItem();- Address classDataAddress = toAddr(program, item.getClassDataOffset());- DataType classDataDataType = classDataItem.toDataType();- createData(program, classDataAddress, classDataDataType);- createFragment(program, "class_data", classDataAddress,- classDataAddress.add(classDataDataType.getLength()));-- StringBuilder builder = new StringBuilder();- builder.append("Class: " +- DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n\n");-- builder.append("Static Fields: " + classDataItem.getStaticFieldsSize() + "\n");- builder.append("Instance Fields: " + classDataItem.getInstanceFieldsSize() + "\n");- builder.append("Direct Methods: " + classDataItem.getDirectMethodsSize() + "\n");- builder.append("Virtual Methods: " + classDataItem.getVirtualMethodsSize() + "\n");-- processEncodedFields(program, header, classDataItem.getStaticFields(), monitor);- processEncodedFields(program, header, classDataItem.getInstancesFields(), monitor);- processEncodedMethods(program, header, item, classDataItem.getDirectMethods(), monitor);- processEncodedMethods(program, header, item, classDataItem.getVirtualMethods(),- monitor);-- setPlateComment(program, classDataAddress, builder.toString());- }- }-- private void processEncodedFields(Program program, DexHeader header,- List<EncodedField> instanceFields, TaskMonitor monitor) throws Exception {- int index = 0;- for (int i = 0; i < instanceFields.size(); ++i) {- monitor.checkCanceled();-- EncodedField field = instanceFields.get(i);-- int diff = field.getFieldIndexDifference();- if (i == 0) {- index = diff;- }- else {- index += diff;- }-- FieldIDItem fieldID = header.getFields().get(index);-- StringBuilder builder = new StringBuilder();- builder.append(DexUtil.convertToString(header, fieldID.getNameIndex()) + "\n");- builder.append(AccessFlags.toString(field.getAccessFlags()) + "\n");- builder.append("\n");-- Address address = toAddr(program, field.getFileOffset());- DataType dataType = field.toDataType();- createData(program, address, dataType);- setPlateComment(program, address, builder.toString());- createFragment(program, "encoded_fields", address, address.add(dataType.getLength()));- }- }-- private void processEncodedMethods(Program program, DexHeader header, ClassDefItem item,- List<EncodedMethod> methods, TaskMonitor monitor) throws Exception {- for (EncodedMethod method : methods) {- monitor.checkCanceled();-- MethodIDItem methodID = header.getMethods().get(method.getMethodIndex());-- StringBuilder builder = new StringBuilder();- builder.append(- "Method Name: " + DexUtil.convertToString(header, methodID.getNameIndex()) + "\n");- builder.append("Method Offset: 0x" + Long.toHexString(methodID.getFileOffset()) + "\n");- builder.append("Method Flags:\n");- builder.append(AccessFlags.toString(method.getAccessFlags()) + "\n");- builder.append("Code Offset: 0x" + Integer.toHexString(method.getCodeOffset()) + "\n");- builder.append("\n");-- Address address = toAddr(program, method.getFileOffset());- DataType dataType = method.toDataType();- createData(program, address, dataType);- setPlateComment(program, address, builder.toString());- createFragment(program, "encoded_methods", address, address.add(dataType.getLength()));-- processCodeItem(program, header, item, method, methodID);- }- }-- private void processCodeItem(Program program, DexHeader header, ClassDefItem item,- EncodedMethod method, MethodIDItem methodID)- throws DuplicateNameException, IOException, Exception {- if (method.getCodeOffset() > 0) {- Address codeAddress = toAddr(program, method.getCodeOffset());-- StringBuilder builder = new StringBuilder();- builder.append(DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + " " +- DexUtil.convertToString(header, methodID.getNameIndex()) + "\n");- setPlateComment(program, codeAddress, builder.toString());-- CodeItem codeItem = method.getCodeItem();- DataType codeItemDataType = codeItem.toDataType();- try {- createData(program, codeAddress, codeItemDataType);-- int codeItemDataTypeLength = codeItemDataType.getLength();-- createFragment(program, "code_item", codeAddress,- codeAddress.add(codeItemDataTypeLength));- Address tempAddress = codeAddress.add(codeItemDataTypeLength);- tempAddress = processCodeItemTrys(program, tempAddress, codeItem);- processCodeItemHandlers(program, codeItem, tempAddress);- }- catch (Exception e) {- //happens when "padding" member has been removed, so struct won't fit- //just ignore it- }-- if (codeItem.getDebugInfoOffset() > 0) {- Address debugAddress = toAddr(program, codeItem.getDebugInfoOffset());- DebugInfoItem debug = codeItem.getDebugInfo();- DataType debugDataType = debug.toDataType();- createData(program, debugAddress, debugDataType);- createFragment(program, "debug_info", debugAddress,- debugAddress.add(debugDataType.getLength()));- }- }- }-- private void processCodeItemHandlers(Program program, CodeItem codeItem, Address tempAddress)- throws DuplicateNameException, IOException, Exception {- EncodedCatchHandlerList handlerList = codeItem.getHandlerList();- if (handlerList == null) {- return;- }-- DataType handlerDataType = handlerList.toDataType();- createData(program, tempAddress, handlerDataType);- createFragment(program, "handlers", tempAddress,- tempAddress.add(handlerDataType.getLength()));- tempAddress = tempAddress.add(handlerDataType.getLength());-- for (EncodedCatchHandler handler : handlerList.getHandlers()) {- DataType dataType = handler.toDataType();- createData(program, tempAddress, dataType);- createFragment(program, "handlers", tempAddress, tempAddress.add(dataType.getLength()));- tempAddress = tempAddress.add(dataType.getLength());- }- }-- private Address processCodeItemTrys(Program program, Address codeAddress, CodeItem codeItem)- throws DuplicateNameException, IOException, Exception {- Address tempAddress = codeAddress;- for (TryItem tryItem : codeItem.getTries()) {- DataType dataType = tryItem.toDataType();- createData(program, tempAddress, dataType);- createFragment(program, "try", tempAddress, tempAddress.add(dataType.getLength()));- tempAddress = tempAddress.add(dataType.getLength());- }- return tempAddress;- }-- private void processClassAnnotations(Program program, ClassDefItem item, TaskMonitor monitor,- MessageLog log)- throws DuplicateNameException, IOException, Exception, CancelledException {- if (item.getAnnotationsOffset() > 0) {- AnnotationsDirectoryItem annotationsDirectoryItem = item.getAnnotationsDirectoryItem();- Address annotationsAddress = toAddr(program, item.getAnnotationsOffset());- DataType annotationsDataType = annotationsDirectoryItem.toDataType();- createData(program, annotationsAddress, annotationsDataType);- createFragment(program, "annotations", annotationsAddress,- annotationsAddress.add(annotationsDataType.getLength()));-- if (annotationsDirectoryItem.getClassAnnotationsOffset() > 0) {- Address classAddress =- toAddr(program, annotationsDirectoryItem.getClassAnnotationsOffset());- AnnotationSetItem setItem = annotationsDirectoryItem.getClassAnnotations();- DataType setItemDataType = setItem.toDataType();- createData(program, classAddress, setItemDataType);- createFragment(program, "class_annotations", classAddress,- classAddress.add(setItemDataType.getLength()));- processAnnotationSetItem(program, setItem, monitor, log);- }- for (FieldAnnotation field : annotationsDirectoryItem.getFieldAnnotations()) {- monitor.checkCanceled();- Address fieldAddress = toAddr(program, field.getAnnotationsOffset());- AnnotationSetItem setItem = field.getAnnotationSetItem();- DataType setItemDataType = setItem.toDataType();- createData(program, fieldAddress, setItemDataType);- createFragment(program, "annotation_fields", fieldAddress,- fieldAddress.add(setItemDataType.getLength()));- processAnnotationSetItem(program, setItem, monitor, log);- }- for (MethodAnnotation method : annotationsDirectoryItem.getMethodAnnotations()) {- monitor.checkCanceled();- Address methodAddress = toAddr(program, method.getAnnotationsOffset());- AnnotationSetItem setItem = method.getAnnotationSetItem();- DataType setItemDataType = setItem.toDataType();- createData(program, methodAddress, setItemDataType);- createFragment(program, "annotation_methods", methodAddress,- methodAddress.add(setItemDataType.getLength()));- processAnnotationSetItem(program, setItem, monitor, log);- }- for (ParameterAnnotation parameter : annotationsDirectoryItem- .getParameterAnnotations()) {- monitor.checkCanceled();- Address parameterAddress = toAddr(program, parameter.getAnnotationsOffset());- AnnotationSetReferenceList annotationSetReferenceList =- parameter.getAnnotationSetReferenceList();- DataType listDataType = annotationSetReferenceList.toDataType();- createData(program, parameterAddress, listDataType);- createFragment(program, "annotation_parameters", parameterAddress,- parameterAddress.add(listDataType.getLength()));-- for (AnnotationSetReferenceItem refItem : annotationSetReferenceList.getItems()) {- AnnotationItem annotationItem = refItem.getItem();- if (annotationItem != null) {- int annotationsItemOffset = refItem.getAnnotationsOffset();- Address annotationItemAddress = toAddr(program, annotationsItemOffset);- DataType annotationItemDataType = annotationItem.toDataType();- createData(program, annotationItemAddress, annotationItemDataType);- createFragment(program, "annotation_item", annotationItemAddress,- annotationItemAddress.add(annotationItemDataType.getLength()));- }- }- }- }- }-- private void processClassInterfaces(Program program, DexHeader header, ClassDefItem item,- TaskMonitor monitor) throws Exception {- if (item.getInterfacesOffset() > 0) {- TypeList interfaces = item.getInterfaces();- Address interfaceAddress = toAddr(program, item.getInterfacesOffset());- DataType interfaceDataType = interfaces.toDataType();- createData(program, interfaceAddress, interfaceDataType);- createFragment(program, "interfaces", interfaceAddress,- interfaceAddress.add(interfaceDataType.getLength()));-- StringBuilder builder = new StringBuilder();- builder.append("Class: " +- DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n\n");- builder.append("Implements:" + "\n");- for (TypeItem interfaceItem : interfaces.getItems()) {- monitor.checkCanceled();- builder.append("\t" +- DexUtil.convertTypeIndexToString(header, interfaceItem.getType()) + "\n");- }- setPlateComment(program, interfaceAddress, builder.toString());- }- }-- private void processAnnotationSetItem(Program program, AnnotationSetItem setItem,- TaskMonitor monitor, MessageLog log) {- try {- for (AnnotationOffsetItem offsetItem : setItem.getItems()) {- monitor.checkCanceled();- Address aAddress = toAddr(program, offsetItem.getAnnotationsOffset());- AnnotationItem aItem = offsetItem.getItem();- DataType aDataType = aItem.toDataType();- createData(program, aAddress, aDataType);- createFragment(program, "annotation_items", aAddress,- aAddress.add(aDataType.getLength()));- }- }- catch (Exception e) {- log.appendException(e);- }- }-- private void processMethods(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: processing methods");- monitor.setMaximum(header.getMethodIdsSize());- monitor.setProgress(0);- Address address = toAddr(program, header.getMethodIdsOffset());- int methodIndex = 0;- for (MethodIDItem item : header.getMethods()) {- monitor.checkCanceled();- monitor.incrementProgress(1);-- DataType dataType = item.toDataType();- createData(program, address, dataType);- createFragment(program, "methods", address, address.add(dataType.getLength()));-- StringBuilder builder = new StringBuilder();- builder.append("Method Index: 0x" + Integer.toHexString(methodIndex) + "\n");- builder.append(- "Class: " + DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n");- builder.append("Prototype: " +- DexUtil.convertPrototypeIndexToString(header, item.getProtoIndex()) + "\n");- builder.append("Name: " + DexUtil.convertToString(header, item.getNameIndex()) + "\n");-- setPlateComment(program, address, builder.toString());-- Address methodIndexAddress = DexUtil.toLookupAddress(program, methodIndex);-- if (program.getMemory().getInt(methodIndexAddress) == -1) {- // Add placeholder symbol for external functions- String methodName = DexUtil.convertToString(header, item.getNameIndex());- String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());- Namespace classNameSpace =- DexUtil.createNameSpaceFromMangledClassName(program, className);- if (classNameSpace != null) {- Address externalAddress = DexUtil.toLookupAddress(program, methodIndex);- Symbol methodSymbol = createMethodSymbol(program, externalAddress, methodName,- classNameSpace, log);- if (methodSymbol != null) {- String externalName = methodSymbol.getName(true);- program.getReferenceManager()- .addExternalReference(methodIndexAddress, "EXTERNAL.dex",- externalName, null, SourceType.ANALYSIS, 0, RefType.DATA);- }- }- }- createData(program, methodIndexAddress, new PointerDataType());-- ++methodIndex;-- address = address.add(dataType.getLength());- }- }-- private void processFields(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: processing fields");- monitor.setMaximum(header.getFieldIdsSize());- monitor.setProgress(0);- Address address = toAddr(program, header.getFieldIdsOffset());- int index = 0;- for (FieldIDItem item : header.getFields()) {- monitor.checkCanceled();- monitor.incrementProgress(1);- DataType dataType = item.toDataType();- createData(program, address, dataType);- createFragment(program, "fields", address, address.add(dataType.getLength()));-- StringBuilder builder = new StringBuilder();- builder.append("Field Index: 0x" + Integer.toHexString(index) + "\n");- builder.append(- "Class: " + DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n");- builder.append(- "Type: " + DexUtil.convertTypeIndexToString(header, item.getTypeIndex()) + "\n");- builder.append("Name: " + DexUtil.convertToString(header, item.getNameIndex()) + "\n");- setPlateComment(program, address, builder.toString());-- ++index;-- address = address.add(dataType.getLength());- }- }-- private void processPrototypes(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: processing prototypes");- monitor.setMaximum(header.getProtoIdsSize());- monitor.setProgress(0);- Address address = toAddr(program, header.getProtoIdsOffset());- int index = 0;- for (PrototypesIDItem item : header.getPrototypes()) {- monitor.checkCanceled();- monitor.incrementProgress(1);- DataType dataType = item.toDataType();- createData(program, address, dataType);- createFragment(program, "prototypes", address, address.add(dataType.getLength()));-- StringBuilder builder = new StringBuilder();- builder.append("Prototype Index: 0x" + Integer.toHexString(index) + "\n");- builder.append(- "Shorty: " + DexUtil.convertToString(header, item.getShortyIndex()) + "\n");- builder.append("Return Type: " +- DexUtil.convertTypeIndexToString(header, item.getReturnTypeIndex()) + "\n");-- if (item.getParametersOffset() > 0) {- builder.append("Parameters: " + "\n");- TypeList parameters = item.getParameters();- for (TypeItem parameter : parameters.getItems()) {- monitor.checkCanceled();- builder.append(- DexUtil.convertTypeIndexToString(header, parameter.getType()) + " ");- }-- DataType parametersDT = parameters.toDataType();- Address parametersAddress = toAddr(program, item.getParametersOffset());- createData(program, parametersAddress, parametersDT);- }-- setPlateComment(program, address, builder.toString());-- ++index;-- address = address.add(dataType.getLength());- }- }-- private void processTypes(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: processing types");- monitor.setMaximum(header.getTypeIdsSize());- monitor.setProgress(0);- Address address = toAddr(program, header.getTypeIdsOffset());- int index = 0;- for (TypeIDItem item : header.getTypes()) {- monitor.checkCanceled();- monitor.incrementProgress(1);- DataType dataType = item.toDataType();- createData(program, address, dataType);- createFragment(program, "types", address, address.add(dataType.getLength()));-- StringBuilder builder = new StringBuilder();- builder.append("Type Index: 0x" + Integer.toHexString(index) + "\n");- builder.append(- "\t" + "->" + DexUtil.convertToString(header, item.getDescriptorIndex()));- setPlateComment(program, address, builder.toString());- ++index;-- address = address.add(dataType.getLength());- }- }-- private void processMap(Program program, DexHeader header, TaskMonitor monitor, MessageLog log)- throws Exception {- MapList mapList = header.getMapList();- if (mapList == null) {- return;- }- monitor.setMessage("DEX: processing map");- monitor.setMaximum(mapList.getSize());- monitor.setProgress(0);- Address mapListAddress = toAddr(program, header.getMapOffset());- DataType mapListDataType = mapList.toDataType();- createData(program, mapListAddress, mapListDataType);- createFragment(program, "map", mapListAddress,- mapListAddress.add(mapListDataType.getLength()));- StringBuilder builder = new StringBuilder();- for (MapItem item : header.getMapList().getItems()) {- monitor.checkCanceled();- builder.append(MapItemTypeCodes.toString(item.getType()) + "\n");- }- setPlateComment(program, mapListAddress, builder.toString());- }-- private void createInitialFragments(Program program, DexHeader header, TaskMonitor monitor)- throws Exception {- monitor.setMessage("DEX: creating fragments");-- if (header.getDataSize() > 0) {- Address start = toAddr(program, header.getDataOffset());- Address end = start.add(header.getDataSize());- createFragment(program, "data", start, end);- }- }-- private void processStrings(Program program, DexHeader header, TaskMonitor monitor,- MessageLog log) throws Exception {- monitor.setMessage("DEX: processing strings");- monitor.setMaximum(header.getStringIdsSize());- monitor.setProgress(0);- Address address = toAddr(program, header.getStringIdsOffset());- int index = 0;- for (StringIDItem item : header.getStrings()) {- monitor.checkCanceled();- monitor.incrementProgress(1);-- // markup string data items- Address stringDataAddress = toAddr(program, item.getStringDataOffset());- StringDataItem stringDataItem = item.getStringDataItem();-- String string = stringDataItem.getString();-- try {- DataType stringDataType = stringDataItem.toDataType();- createData(program, stringDataAddress, stringDataType);- setPlateComment(program, stringDataAddress,- Integer.toHexString(index) + "\n\n" + string);- createFragment(program, "string_data", stringDataAddress,- stringDataAddress.add(stringDataType.getLength()));-- createStringSymbol(program, stringDataAddress, string, "strings");- }- catch (DuplicateNameException e) {- log.appendException(e); // Report the exception but keep going- }- catch (InvalidInputException e) {- log.appendException(e);- }-- // markup string Id items- DataType dataType = item.toDataType();- try {- createData(program, address, dataType);- createFragment(program, "strings", address, address.add(dataType.getLength()));- setPlateComment(program, address,- "String Index: 0x" + Integer.toHexString(index) + "\n\n" + string);- createStringSymbol(program, address, string, "string_data");- }- catch (DuplicateNameException e) {- log.appendException(e); // Report the exception but keep going- }- catch (InvalidInputException e) {- log.appendException(e);- }- ++index;-- address = address.add(dataType.getLength());- }- }-- private void createStringSymbol(Program program, Address address, String string,- String namespace) {- SymbolTable symbolTable = program.getSymbolTable();- if (string.length() > 0) {- Namespace nameSpace = DexUtil.getOrCreateNameSpace(program, namespace);- String symbolName = SymbolUtilities.replaceInvalidChars(string, true);- if (symbolName.length() > SymbolUtilities.MAX_SYMBOL_NAME_LENGTH) {- symbolName = symbolName.substring(0, SymbolUtilities.MAX_SYMBOL_NAME_LENGTH - 20);- }- try {- symbolTable.createLabel(address, symbolName, nameSpace, SourceType.ANALYSIS);- }- catch (InvalidInputException e) {- // TODO Symbol name matches possible default symbol name: BYTE_0- }- }- }-}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexHeaderFormatMarkup.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexHeaderFormatMarkup.javanew file mode 100644index 0000000000..b43c7fc575--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexHeaderFormatMarkup.java@@ -0,0 +1,1070 @@+/* ###+ * 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.android.dex.analyzer;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.cmd.disassemble.DisassembleCommand;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.cdex.CDexCodeItem;+import ghidra.file.formats.android.dex.format.AccessFlags;+import ghidra.file.formats.android.dex.format.AnnotationItem;+import ghidra.file.formats.android.dex.format.AnnotationSetItem;+import ghidra.file.formats.android.dex.format.AnnotationSetReferenceItem;+import ghidra.file.formats.android.dex.format.AnnotationSetReferenceList;+import ghidra.file.formats.android.dex.format.AnnotationsDirectoryItem;+import ghidra.file.formats.android.dex.format.ClassDataItem;+import ghidra.file.formats.android.dex.format.ClassDefItem;+import ghidra.file.formats.android.dex.format.CodeItem;+import ghidra.file.formats.android.dex.format.DebugInfoItem;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.file.formats.android.dex.format.EncodedArrayItem;+import ghidra.file.formats.android.dex.format.EncodedCatchHandler;+import ghidra.file.formats.android.dex.format.EncodedCatchHandlerList;+import ghidra.file.formats.android.dex.format.EncodedField;+import ghidra.file.formats.android.dex.format.EncodedMethod;+import ghidra.file.formats.android.dex.format.FieldAnnotationsItem;+import ghidra.file.formats.android.dex.format.FieldIDItem;+import ghidra.file.formats.android.dex.format.MapItem;+import ghidra.file.formats.android.dex.format.MapItemTypeCodes;+import ghidra.file.formats.android.dex.format.MapList;+import ghidra.file.formats.android.dex.format.MethodAnnotationsItem;+import ghidra.file.formats.android.dex.format.MethodIDItem;+import ghidra.file.formats.android.dex.format.ParameterAnnotationsItem;+import ghidra.file.formats.android.dex.format.PrototypesIDItem;+import ghidra.file.formats.android.dex.format.StringDataItem;+import ghidra.file.formats.android.dex.format.StringIDItem;+import ghidra.file.formats.android.dex.format.TryItem;+import ghidra.file.formats.android.dex.format.TypeIDItem;+import ghidra.file.formats.android.dex.format.TypeItem;+import ghidra.file.formats.android.dex.format.TypeList;+import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.program.database.ProgramCompilerSpec;+import ghidra.program.flatapi.FlatProgramAPI;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DWordDataType;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.DataTypeConflictHandler;+import ghidra.program.model.data.DataTypeManager;+import ghidra.program.model.data.PointerDataType;+import ghidra.program.model.data.TypedefDataType;+import ghidra.program.model.lang.Language;+import ghidra.program.model.lang.Register;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Function;+import ghidra.program.model.listing.Function.FunctionUpdateType;+import ghidra.program.model.listing.Group;+import ghidra.program.model.listing.LocalVariableImpl;+import ghidra.program.model.listing.ParameterImpl;+import ghidra.program.model.listing.Program;+import ghidra.program.model.listing.ProgramFragment;+import ghidra.program.model.listing.ProgramModule;+import ghidra.program.model.listing.ReturnParameterImpl;+import ghidra.program.model.listing.Variable;+import ghidra.program.model.mem.Memory;+import ghidra.program.model.mem.MemoryBlock;+import ghidra.program.model.symbol.Namespace;+import ghidra.program.model.symbol.RefType;+import ghidra.program.model.symbol.SourceType;+import ghidra.program.model.symbol.Symbol;+import ghidra.program.model.symbol.SymbolTable;+import ghidra.program.model.symbol.SymbolUtilities;+import ghidra.util.NumericUtilities;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.exception.InvalidInputException;+import ghidra.util.exception.NotEmptyException;+import ghidra.util.task.TaskMonitor;++public class DexHeaderFormatMarkup {++ private Program program;+ private Address baseAddress;+ private FlatProgramAPI api;++ public DexHeaderFormatMarkup(Program program, Address baseAddress) {+ this.program = program;+ this.baseAddress = baseAddress;+ this.api = new FlatProgramAPI(program);+ }++ public boolean markup(TaskMonitor monitor, MessageLog log) throws Exception {++ if (api.getDataAt(baseAddress) != null) {+ log.appendMsg("data already exists.");+ return true;+ }++ Memory memory = program.getMemory();+ MemoryBlock block = memory.getBlock(baseAddress);+ block.setRead(true);+ block.setWrite(false);+ block.setExecute(false);++ DexAnalysisState analysisState = DexAnalysisState.getState(program, baseAddress);+ DexHeader header = analysisState.getHeader();+ processHeader(header);++ createInitialFragments(header, monitor);++ ProgramCompilerSpec.enableJavaLanguageDecompilation(program);+ createNamespaces(header, monitor, log);+ processMap(header, monitor, log);+ processStrings(header, monitor, log);+ processTypes(header, monitor, log);+ processPrototypes(header, monitor, log);+ processFields(header, monitor, log);+ processMethods(header, monitor, log);+ processClassDefs(header, monitor, log);+ createProgramDataTypes(header, monitor, log);++ createMethods(header, monitor, log);++ monitor.setMessage("DEX: cleaning up tree");+ removeEmptyFragments();++ return true;+ }++ private void createNamespaces(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMessage("DEX: creating namespaces");+ monitor.setMaximum(header.getClassDefsIdsSize());+ monitor.setProgress(0);++ // NOTE:+ // MUST CREATE ALL OF THE CLASSES AND NAMESPACES FIRST+ // OTHERWISE GHIDRA CANNOT HANDLE OBFUSCATED PACKAGES NAMES+ // FOR EXAMPLE, "a.a.a.a" and "a.a.a" WHERE THE LAST A IS A METHOD+ for (ClassDefItem item : header.getClassDefs()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());+ Namespace classNameSpace =+ DexUtil.createNameSpaceFromMangledClassName(program, className);+ if (classNameSpace == null) {+ log.appendMsg("Failed to create namespace: " + className);+ }+ }+ }++ private void createMethods(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMessage("DEX: creating methods");+ monitor.setMaximum(header.getClassDefsIdsSize());+ monitor.setProgress(0);+ for (ClassDefItem item : header.getClassDefs()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ ClassDataItem classDataItem = item.getClassDataItem();+ if (classDataItem == null) {+ continue;+ }++ createMethods(header, item, classDataItem.getDirectMethods(), monitor, log);+ createMethods(header, item, classDataItem.getVirtualMethods(), monitor, log);+ }+ }++ private void createMethods(DexHeader header, ClassDefItem item, List<EncodedMethod> methods,+ TaskMonitor monitor, MessageLog log) throws Exception {+ String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());+ Namespace classNameSpace = DexUtil.createNameSpaceFromMangledClassName(program, className);+ if (classNameSpace == null) {+ log.appendMsg("No namespace: Skipping methods for " + className);+ return;+ }++ for (int i = 0; i < methods.size(); ++i) {+ monitor.checkCanceled();++ EncodedMethod encodedMethod = methods.get(i);++ MethodIDItem methodID = header.getMethods().get(encodedMethod.getMethodIndex());+ String methodName = DexUtil.convertToString(header, methodID.getNameIndex());++ if ((AccessFlags.ACC_CONSTRUCTOR & encodedMethod.getAccessFlags()) != 0) {+ methodName = classNameSpace.getName();+ }+ CodeItem codeItem = encodedMethod.getCodeItem();++ if (codeItem == null) {//external+// Address externalAddress = baseAddress.add( DexUtil.EXTERNAL_ADDRESS + ( 4 * methodIndex ) );+// createMethodSymbol( program, externalAddress, methodName, classNameSpace );+// createMethodComment( program, externalAddress, header, item, methodID, encodedMethod, codeItem, monitor );+// createData( program, externalAddress, new PointerDataType( ) );+// Function method = createFunction( program, externalAddress );+// method.setCustomVariableStorage( true );+//+// Address methodIndexAddress = baseAddress.add( DexUtil.LOOKUP_ADDRESS + ( methodIndex * 4 ) );+// Symbol primarySymbol = program.getSymbolTable().getPrimarySymbol( methodIndexAddress );+// program.getReferenceManager().addExternalReference( methodIndexAddress, (Namespace) null, primarySymbol.getName( ), null, SourceType.ANALYSIS, 0, RefType.EXTERNAL_REF );+ }+ else {+ Address methodAddress =+ baseAddress.add(DexUtil.METHOD_ADDRESS + encodedMethod.getCodeOffset());+ createMethodSymbol(methodAddress, methodName, classNameSpace, log);+ createMethodComment(methodAddress, header, item, methodID, encodedMethod, codeItem,+ monitor);+ disassembleMethod(header, className, encodedMethod.isStatic(), methodAddress,+ methodID, codeItem, monitor, log);+ }+ }+ }++ private Symbol createMethodSymbol(Address methodAddress, String methodName,+ Namespace classNameSpace, MessageLog log) {+ program.getSymbolTable().addExternalEntryPoint(methodAddress);+ try {+ return program.getSymbolTable()+ .createLabel(methodAddress, methodName, classNameSpace, SourceType.ANALYSIS);+ }+ catch (InvalidInputException e) {+ log.appendException(e);+ return null;+ }+ }++ private void createMethodComment(Address methodAddress, DexHeader header, ClassDefItem item,+ MethodIDItem methodID, EncodedMethod encodedMethod, CodeItem codeItem,+ TaskMonitor monitor) throws CancelledException {++ String methodSignature =+ DexUtil.convertPrototypeIndexToString(header, methodID.getProtoIndex());+ StringBuilder commentBuilder = new StringBuilder();+ commentBuilder.append(item.toString(header, -1, monitor) + "\n");+ commentBuilder.append("Method Signature: " + methodSignature + "\n");+ commentBuilder.append("Method Access Flags:\n");+ commentBuilder.append(AccessFlags.toString(encodedMethod.getAccessFlags()) + "\n");+ if (codeItem != null) {+ commentBuilder.append("Method Register Size: " + codeItem.getRegistersSize() + "\n");+ commentBuilder.append("Method Incoming Size: " + codeItem.getIncomingSize() + "\n");+ commentBuilder.append("Method Outgoing Size: " + codeItem.getOutgoingSize() + "\n");+ commentBuilder.append("Method Debug Info Offset: 0x" ++ Integer.toHexString(codeItem.getDebugInfoOffset()) + "\n");+ }+ commentBuilder+ .append("Method ID Offset: 0x" + Long.toHexString(methodID.getFileOffset()) + "\n");+ api.setPlateComment(methodAddress, commentBuilder.toString());+ }++ private void disassembleMethod(DexHeader header, String className, boolean isStatic,+ Address methodAddress, MethodIDItem methodID, CodeItem codeItem, TaskMonitor monitor,+ MessageLog log) throws CancelledException {++ Language language = program.getLanguage();++ DisassembleCommand dCommand = new DisassembleCommand(methodAddress, null, true);+ dCommand.applyTo(program);++ Function method = api.createFunction(methodAddress, null);+ if (method == null) {//maybe function already created? ...due to compiler optimizations+ if (api.getFunctionAt(methodAddress) != null) {+ log.appendMsg("Duplicate method at " + methodAddress);+ return;+ }+ }+ if (method == null) {+ log.appendMsg("Failed to create method at " + methodAddress);+ return;+ }++ int registerIndex = codeItem.getRegistersSize() - codeItem.getIncomingSize();++ //TODO create local variables in between+ for (int i = 0; i < registerIndex; ++i) {+ DataType localDataType = null;//TODO+ Register localRegister = language.getRegister("v" + i);+ try {+ LocalVariableImpl local =+ new LocalVariableImpl("local_" + i, 0, localDataType, localRegister, program);+ method.addLocalVariable(local, SourceType.ANALYSIS);+ }+ catch (Exception e) {+ log.appendException(e);+ }+ }++ Variable returnVar = null;+ List<Variable> paramList = new ArrayList<>();++ int prototypeIndex = Short.toUnsignedInt(methodID.getProtoIndex());+ PrototypesIDItem prototype = header.getPrototypes().get(prototypeIndex);++ try {+ String returnTypeString =+ DexUtil.convertTypeIndexToString(header, prototype.getReturnTypeIndex());+ DataType returnDataType =+ DexUtil.toDataType(program.getDataTypeManager(), returnTypeString);+ returnVar = new ReturnParameterImpl(returnDataType, program);++ if (!isStatic) {+ String classString =+ DexUtil.convertTypeIndexToString(header, methodID.getClassIndex());+ DataType thisDataType =+ DexUtil.toDataType(program.getDataTypeManager(), classString);+ String parameterName = "this";+ Variable param = new ParameterImpl(parameterName, thisDataType, program);+ paramList.add(param);+ }++ TypeList parameters = prototype.getParameters();+ if (parameters != null) {+ for (TypeItem parameterTypeItem : parameters.getItems()) {+ monitor.checkCanceled();+ String parameterTypeString =+ DexUtil.convertTypeIndexToString(header, parameterTypeItem.getType());+ DataType parameterDataType =+ DexUtil.toDataType(program.getDataTypeManager(), parameterTypeString);+ String parameterName =+ getParameterName(header, codeItem, paramList.size() - (isStatic ? 0 : 1));+ if (parameterName == null) {+ parameterName = "p" + paramList.size();+ }+ Variable param = new ParameterImpl(parameterName, parameterDataType, program);+ paramList.add(param);+ }+ }+ method.updateFunction("__stdcall", returnVar, paramList,+ FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS);+ }+ catch (InvalidInputException ex) {+ log.appendException(ex);+ }+ catch (DuplicateNameException ex) {+ log.appendException(ex);+ }+ }++ private String getParameterName(DexHeader header, CodeItem codeItem, int parameterOrdinal) {+ try {+ DebugInfoItem debugInfo = codeItem.getDebugInfo();+ int[] debugParameterNames = debugInfo.getParameterNames();+ List<StringIDItem> strings = header.getStrings();+ StringIDItem stringIDItem = strings.get(debugParameterNames[parameterOrdinal]);+ StringDataItem stringDataItem = stringIDItem.getStringDataItem();+ return stringDataItem.getString();+ }+ catch (Exception e) {+ // ignore IndexOutOfBoundsException+ }+ return null;+ }++ private void processHeader(DexHeader header) throws Exception {+ Address headerAddress = baseAddress.add(0x0);+ DataType headerDataType = header.toDataType();+ api.createData(headerAddress, headerDataType);+ api.createFragment("header", headerAddress, headerDataType.getLength());+ }++ private void processClassDefs(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMessage("DEX: processing class definitions");+ monitor.setMaximum(header.getClassDefsIdsSize());+ monitor.setProgress(0);++ Address address = baseAddress.add(header.getClassDefsIdsOffset());++ int index = 0;++ for (ClassDefItem item : header.getClassDefs()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ DataType dataType = item.toDataType();+ api.createData(address, dataType);+ api.createFragment("classes", address, dataType.getLength());+ createClassDefSymbol(header, item, address);++ processClassInterfaces(header, item, monitor);+ processClassAnnotations(header, item, monitor, log);+ processClassDataItem(header, item, monitor, log);+ processClassStaticValues(header, item, monitor);++ api.setPlateComment(address, item.toString(header, index, monitor));++ address = address.add(dataType.getLength());+ ++index;+ }+ }++ private void createProgramDataTypes(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws CancelledException {+ monitor.setMessage("DEX: creating program datatypes");+ monitor.setMaximum(header.getTypeIdsSize());+ monitor.setProgress(0);+ DataTypeManager dtm = program.getDataTypeManager();+ int curGroup = -1;+ CategoryPath handlePath = null;+ List<TypeIDItem> types = header.getTypes();+ for (int typeID = 0; typeID < header.getTypeIdsSize(); ++typeID) {+ if (typeID > types.size() - 1) {+ continue;//not in scope... CDEX issue+ }+ TypeIDItem item = types.get(typeID);+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ String name = DexUtil.convertToString(header, item.getDescriptorIndex());+ String[] path = DexUtil.convertClassStringToPathArray(DexUtil.CATEGORY_PATH, name);+ if (path == null) {+ continue;+ }++ StringBuilder builder = new StringBuilder();+ for (int i = 0; i < path.length - 1; ++i) {+ builder.append(CategoryPath.DELIMITER_CHAR);+ builder.append(path[i]);+ }+ CategoryPath catPath = new CategoryPath(builder.toString());+ DataType dataType =+ new TypedefDataType(catPath, path[path.length - 1], DWordDataType.dataType);+ dataType = dtm.resolve(dataType, DataTypeConflictHandler.DEFAULT_HANDLER);++ // Create unchanging typedef to each class based on typeID, so we can find class type even if name changes+ if (typeID / 100 != curGroup) {+ curGroup = typeID / 100;+ builder = new StringBuilder();+ builder.append(DexUtil.HANDLE_PATH);+ builder.append("group").append(curGroup);+ handlePath = new CategoryPath(builder.toString());+ }+ DataType handleType = new TypedefDataType(handlePath, "type" + typeID, dataType);+ dtm.resolve(handleType, DataTypeConflictHandler.DEFAULT_HANDLER);+ }+ }++ private void createClassDefSymbol(DexHeader header, ClassDefItem item, Address address) {+ String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());+ SymbolTable symbolTable = program.getSymbolTable();+ try {+ Namespace nameSpace = DexUtil.createNameSpaceFromMangledClassName(program, className);+ if (nameSpace != null) {+ symbolTable.createLabel(address, DexUtil.CLASSDEF_NAME, nameSpace,+ SourceType.ANALYSIS);+ }+ }+ catch (Exception ex) {+ // Don't worry if we can't laydown this symbol+ }+ }++ private void processClassStaticValues(DexHeader header, ClassDefItem item, TaskMonitor monitor)+ throws DuplicateNameException, IOException, Exception {+ if (item.getStaticValuesOffset() > 0) {+ EncodedArrayItem staticValues = item.getStaticValues();+ Address staticAddress =+ baseAddress.add(DexUtil.adjustOffset(item.getStaticValuesOffset(), header));+ DataType staticDataType = staticValues.toDataType();+ api.createData(staticAddress, staticDataType);+ api.createFragment("class_static_values", staticAddress, staticDataType.getLength());++ StringBuilder builder = new StringBuilder();+ builder.append("Class: " ++ DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n\n");+ builder.append("Static Values:" + "\n");+ builder.append(+ NumericUtilities.convertBytesToString(staticValues.getArray().getValues(), " "));+ api.setPlateComment(staticAddress, builder.toString());+ }+ }++ private void processClassDataItem(DexHeader header, ClassDefItem item, TaskMonitor monitor,+ MessageLog log) throws DuplicateNameException, IOException, Exception {+ if (item.getClassDataOffset() > 0) {+ ClassDataItem classDataItem = item.getClassDataItem();+ Address classDataAddress =+ baseAddress.add(DexUtil.adjustOffset(item.getClassDataOffset(), header));+ DataType classDataDataType = classDataItem.toDataType();+ try {+ api.createData(classDataAddress, classDataDataType);+ }+ catch (Exception e) {+ log.appendMsg("Unable to create class data item at " + classDataAddress);+ return;+ }+ api.createFragment("class_data", classDataAddress, classDataDataType.getLength());++ StringBuilder builder = new StringBuilder();+ builder.append("Class: " ++ DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n\n");++ builder.append("Static Fields: " + classDataItem.getStaticFieldsSize() + "\n");+ builder.append("Instance Fields: " + classDataItem.getInstanceFieldsSize() + "\n");+ builder.append("Direct Methods: " + classDataItem.getDirectMethodsSize() + "\n");+ builder.append("Virtual Methods: " + classDataItem.getVirtualMethodsSize() + "\n");++ processEncodedFields(header, classDataItem.getStaticFields(), monitor);+ processEncodedFields(header, classDataItem.getInstancesFields(), monitor);+ processEncodedMethods(header, item, classDataItem.getDirectMethods(), monitor);+ processEncodedMethods(header, item, classDataItem.getVirtualMethods(), monitor);++ api.setPlateComment(classDataAddress, builder.toString());+ }+ }++ private void processEncodedFields(DexHeader header, List<EncodedField> instanceFields,+ TaskMonitor monitor) throws Exception {+ int index = 0;+ for (int i = 0; i < instanceFields.size(); ++i) {+ monitor.checkCanceled();++ EncodedField field = instanceFields.get(i);++ int diff = field.getFieldIndexDifference();+ if (i == 0) {+ index = diff;+ }+ else {+ index += diff;+ }++ FieldIDItem fieldID = header.getFields().get(index);++ StringBuilder builder = new StringBuilder();+ builder.append(DexUtil.convertToString(header, fieldID.getNameIndex()) + "\n");+ builder.append(AccessFlags.toString(field.getAccessFlags()) + "\n");+ builder.append("\n");++ Address address = baseAddress.add(field.getFileOffset());+ DataType dataType = field.toDataType();+ api.createData(address, dataType);+ api.setPlateComment(address, builder.toString());+ api.createFragment("encoded_fields", address, dataType.getLength());+ }+ }++ private void processEncodedMethods(DexHeader header, ClassDefItem item,+ List<EncodedMethod> methods, TaskMonitor monitor) throws Exception {+ for (int i = 0; i < methods.size(); ++i) {+ monitor.checkCanceled();++ EncodedMethod method = methods.get(i);++ MethodIDItem methodID = header.getMethods().get(method.getMethodIndex());++ StringBuilder builder = new StringBuilder();+ builder.append(+ "Method Name: " + DexUtil.convertToString(header, methodID.getNameIndex()) + "\n");+ builder.append("Method Offset: 0x" + Long.toHexString(methodID.getFileOffset()) + "\n");+ builder.append("Method Flags:\n");+ builder.append(AccessFlags.toString(method.getAccessFlags()) + "\n");+ builder.append("Code Offset: 0x" + Integer.toHexString(method.getCodeOffset()) + "\n");+ builder.append("\n");++ Address address = baseAddress.add(method.getFileOffset());+ DataType dataType = method.toDataType();+ api.createData(address, dataType);+ api.setPlateComment(address, builder.toString());+ api.createFragment("encoded_methods", address, dataType.getLength());++ processCodeItem(header, item, method, methodID);+ }+ }++ private void processCodeItem(DexHeader header, ClassDefItem item, EncodedMethod method,+ MethodIDItem methodID) throws DuplicateNameException, IOException, Exception {++ if (method.getCodeOffset() > 0) {+ Address codeAddress =+ baseAddress.add(DexUtil.adjustOffset(method.getCodeOffset(), header));++ CodeItem codeItem = method.getCodeItem();++ StringBuilder builder = new StringBuilder();+ builder.append(DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + " " ++ DexUtil.convertToString(header, methodID.getNameIndex()) + "\n");++ if (codeItem != null) {+ builder.append("\n");+ builder.append("Instruction Bytes: 0x" ++ Integer.toHexString(codeItem.getInstructionBytes().length) + "\n");+ builder.append(+ "Registers Size: 0x" + Integer.toHexString(codeItem.getRegistersSize()) + "\n");+ builder.append(+ "Incoming Size: 0x" + Integer.toHexString(codeItem.getIncomingSize()) + "\n");+ builder.append(+ "Outgoing Size: 0x" + Integer.toHexString(codeItem.getOutgoingSize()) + "\n");+ builder.append(+ "Tries Size: 0x" + Integer.toHexString(codeItem.getTriesSize()) + "\n");+ }++ if (codeItem instanceof CDexCodeItem) {+ CDexCodeItem cdexCodeItem = (CDexCodeItem) codeItem;+ builder.append("\n" + (cdexCodeItem.hasPreHeader() ? "PREHEADER" : ""));+ }++ api.setPlateComment(codeAddress, builder.toString());++ if (codeItem != null) {//external+ DataType codeItemDataType = codeItem.toDataType();+ try {+ api.createData(codeAddress, codeItemDataType);++ int codeItemDataTypeLength = codeItemDataType.getLength();++ api.createFragment("code_item", codeAddress, codeItemDataTypeLength);+ Address tempAddress = codeAddress.add(codeItemDataTypeLength);+ tempAddress = processCodeItemTrys(tempAddress, codeItem);+ processCodeItemHandlers(codeItem, tempAddress);+ }+ catch (Exception e) {+ //happens when "padding" member has been removed, so struct won't fit+ //just ignore it+ }++ if (codeItem.getDebugInfoOffset() > 0) {+ Address debugAddress = baseAddress.add(codeItem.getDebugInfoOffset());+ DebugInfoItem debug = codeItem.getDebugInfo();+ DataType debugDataType = debug.toDataType();+ api.createData(debugAddress, debugDataType);+ api.createFragment("debug_info", debugAddress, debugDataType.getLength());+ }+ }+ }+ }++ private void processCodeItemHandlers(CodeItem codeItem, Address tempAddress)+ throws DuplicateNameException, IOException, Exception {+ EncodedCatchHandlerList handlerList = codeItem.getHandlerList();+ if (handlerList == null) {+ return;+ }++ DataType handlerDataType = handlerList.toDataType();+ api.createData(tempAddress, handlerDataType);+ api.createFragment("handlers", tempAddress, handlerDataType.getLength());+ tempAddress = tempAddress.add(handlerDataType.getLength());++ for (EncodedCatchHandler handler : handlerList.getHandlers()) {+ DataType dataType = handler.toDataType();+ api.createData(tempAddress, dataType);+ api.createFragment("handlers", tempAddress, dataType.getLength());+ tempAddress = tempAddress.add(dataType.getLength());+ }+ }++ private Address processCodeItemTrys(Address codeAddress, CodeItem codeItem)+ throws DuplicateNameException, IOException, Exception {+ Address tempAddress = codeAddress;+ for (TryItem tryItem : codeItem.getTries()) {+ DataType dataType = tryItem.toDataType();+ api.createData(tempAddress, dataType);+ api.createFragment("try", tempAddress, dataType.getLength());+ tempAddress = tempAddress.add(dataType.getLength());+ }+ return tempAddress;+ }++ private void processClassAnnotations(DexHeader header, ClassDefItem item, TaskMonitor monitor,+ MessageLog log)+ throws DuplicateNameException, IOException, Exception, CancelledException {+ if (item.getAnnotationsOffset() > 0) {+ AnnotationsDirectoryItem annotationsDirectoryItem = item.getAnnotationsDirectoryItem();+ Address annotationsAddress =+ baseAddress.add(DexUtil.adjustOffset(item.getAnnotationsOffset(), header));+ DataType annotationsDataType = annotationsDirectoryItem.toDataType();+ api.createData(annotationsAddress, annotationsDataType);+ api.createFragment("annotations", annotationsAddress, annotationsDataType.getLength());++ if (annotationsDirectoryItem.getClassAnnotationsOffset() > 0) {+ Address classAddress = baseAddress.add(DexUtil.adjustOffset(+ annotationsDirectoryItem.getClassAnnotationsOffset(), header));+ AnnotationSetItem setItem = annotationsDirectoryItem.getClassAnnotations();+ DataType setItemDataType = setItem.toDataType();+ api.createData(classAddress, setItemDataType);+ api.createFragment("class_annotations", classAddress, setItemDataType.getLength());+ processAnnotationSetItem(setItem, monitor, log);+ }+ for (FieldAnnotationsItem field : annotationsDirectoryItem.getFieldAnnotations()) {+ monitor.checkCanceled();+ Address fieldAddress =+ baseAddress.add(DexUtil.adjustOffset(field.getAnnotationsOffset(), header));+ AnnotationSetItem setItem = field.getAnnotationSetItem();+ DataType setItemDataType = setItem.toDataType();+ api.createData(fieldAddress, setItemDataType);+ api.createFragment("annotation_fields", fieldAddress, setItemDataType.getLength());+ processAnnotationSetItem(setItem, monitor, log);+ }+ for (MethodAnnotationsItem method : annotationsDirectoryItem.getMethodAnnotations()) {+ monitor.checkCanceled();+ Address methodAddress =+ baseAddress.add(DexUtil.adjustOffset(method.getAnnotationsOffset(), header));+ AnnotationSetItem setItem = method.getAnnotationSetItem();+ DataType setItemDataType = setItem.toDataType();+ api.createData(methodAddress, setItemDataType);+ api.createFragment("annotation_methods", methodAddress,+ setItemDataType.getLength());+ processAnnotationSetItem(setItem, monitor, log);+ }+ for (ParameterAnnotationsItem parameter : annotationsDirectoryItem+ .getParameterAnnotations()) {+ monitor.checkCanceled();+ Address parameterAddress =+ baseAddress.add(DexUtil.adjustOffset(parameter.getAnnotationsOffset(), header));+ AnnotationSetReferenceList annotationSetReferenceList =+ parameter.getAnnotationSetReferenceList();+ DataType listDataType = annotationSetReferenceList.toDataType();+ api.createData(parameterAddress, listDataType);+ api.createFragment("annotation_parameters", parameterAddress,+ listDataType.getLength());++ for (AnnotationSetReferenceItem refItem : annotationSetReferenceList.getItems()) {+ AnnotationItem annotationItem = refItem.getItem();+ if (annotationItem != null) {+ int annotationsItemOffset = refItem.getAnnotationsOffset();+ Address annotationItemAddress =+ baseAddress.add(DexUtil.adjustOffset(annotationsItemOffset, header));+ DataType annotationItemDataType = annotationItem.toDataType();+ api.createData(annotationItemAddress, annotationItemDataType);+ api.createFragment("annotation_item", annotationItemAddress,+ annotationItemDataType.getLength());+ }+ }+ }+ }+ }++ private void processClassInterfaces(DexHeader header, ClassDefItem item, TaskMonitor monitor)+ throws Exception {+ if (item.getInterfacesOffset() > 0) {+ TypeList interfaces = item.getInterfaces();+ Address interfaceAddress =+ baseAddress.add(DexUtil.adjustOffset(item.getInterfacesOffset(), header));+ DataType interfaceDataType = interfaces.toDataType();+ api.createData(interfaceAddress, interfaceDataType);+ api.createFragment("interfaces", interfaceAddress, interfaceDataType.getLength());++ StringBuilder builder = new StringBuilder();+ builder.append("Class: " ++ DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n\n");+ builder.append("Implements:" + "\n");+ for (TypeItem interfaceItem : interfaces.getItems()) {+ monitor.checkCanceled();+ builder.append("\t" ++ DexUtil.convertTypeIndexToString(header, interfaceItem.getType()) + "\n");+ }+ api.setPlateComment(interfaceAddress, builder.toString());+ }+ }++ private void processAnnotationSetItem(AnnotationSetItem setItem, TaskMonitor monitor,+ MessageLog log) {+ try {+// for (AnnotationOffsetItem offsetItem : setItem.getItems()) {+// monitor.checkCanceled();+// Address aAddress = baseAddress.add( offsetItem.getAnnotationsOffset() );+// AnnotationItem aItem = offsetItem.getItem();+// DataType aDataType = aItem.toDataType();+// api.createData( aAddress, aDataType);+// api.createFragment( "annotation_items", aAddress, aDataType.getLength());+// }+ }+ catch (Exception e) {+ log.appendException(e);+ }+ }++ private void processMethods(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {++ monitor.setMessage("DEX: processing methods");+ monitor.setMaximum(header.getMethodIdsSize());+ monitor.setProgress(0);+ Address address = baseAddress.add(header.getMethodIdsOffset());+ int methodIndex = 0;+ for (MethodIDItem item : header.getMethods()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ DataType dataType = item.toDataType();+ api.createData(address, dataType);+ api.createFragment("methods", address, dataType.getLength());++ StringBuilder builder = new StringBuilder();+ builder.append("Method Index: 0x" + Integer.toHexString(methodIndex) + "\n");+ builder.append(+ "Class: " + DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n");+ builder.append("Prototype: " ++ DexUtil.convertPrototypeIndexToString(header, item.getProtoIndex()) + "\n");+ builder.append("Name: " + DexUtil.convertToString(header, item.getNameIndex()) + "\n");++ api.setPlateComment(address, builder.toString());++ Address methodIndexAddress = DexUtil.toLookupAddress(program, methodIndex);++ if (program.getMemory().getInt(methodIndexAddress) == -1) {+ // Add placeholder symbol for external functions+ String methodName = DexUtil.convertToString(header, item.getNameIndex());+ String className = DexUtil.convertTypeIndexToString(header, item.getClassIndex());+ Namespace classNameSpace =+ DexUtil.createNameSpaceFromMangledClassName(program, className);+ if (classNameSpace != null) {+ Address externalAddress = DexUtil.toLookupAddress(program, methodIndex);+ Symbol methodSymbol =+ createMethodSymbol(externalAddress, methodName, classNameSpace, log);+ if (methodSymbol != null) {+ String externalName = methodSymbol.getName(true);+ program.getReferenceManager()+ .addExternalReference(methodIndexAddress,+ "EXTERNAL.dex-" + methodIndex, externalName, null,+ SourceType.ANALYSIS, 0, RefType.DATA);+ }+ }+ }+ api.createData(methodIndexAddress, new PointerDataType());++ ++methodIndex;++ address = address.add(dataType.getLength());+ }+ }++ private void processFields(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMessage("DEX: processing fields");+ monitor.setMaximum(header.getFieldIdsSize());+ monitor.setProgress(0);+ Address address = baseAddress.add(header.getFieldIdsOffset());+ int index = 0;+ for (FieldIDItem item : header.getFields()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ DataType dataType = item.toDataType();+ api.createData(address, dataType);+ api.createFragment("fields", address, dataType.getLength());++ StringBuilder builder = new StringBuilder();+ builder.append("Field Index: 0x" + Integer.toHexString(index) + "\n");+ builder.append(+ "Class: " + DexUtil.convertTypeIndexToString(header, item.getClassIndex()) + "\n");+ builder.append(+ "Type: " + DexUtil.convertTypeIndexToString(header, item.getTypeIndex()) + "\n");+ builder.append("Name: " + DexUtil.convertToString(header, item.getNameIndex()) + "\n");+ api.setPlateComment(address, builder.toString());++ ++index;++ address = address.add(dataType.getLength());+ }+ }++ private void processPrototypes(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMessage("DEX: processing prototypes");+ monitor.setMaximum(header.getProtoIdsSize());+ monitor.setProgress(0);+ Address address = baseAddress.add(header.getProtoIdsOffset());+ int index = 0;+ for (PrototypesIDItem item : header.getPrototypes()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ DataType dataType = item.toDataType();+ Data data = api.createData(address, dataType);+ api.createFragment("prototypes", address, dataType.getLength());++ StringBuilder builder = new StringBuilder();+ builder.append("Prototype Index: 0x" + Integer.toHexString(index) + "\n");+ builder.append(+ "Shorty: " + DexUtil.convertToString(header, item.getShortyIndex()) + "\n");+ builder.append("Return Type: " ++ DexUtil.convertTypeIndexToString(header, item.getReturnTypeIndex()) + "\n");++ if (item.getParametersOffset() > 0) {+ builder.append("Parameters: " + "\n");+ TypeList parameters = item.getParameters();+ for (TypeItem parameter : parameters.getItems()) {+ monitor.checkCanceled();+ builder.append(+ DexUtil.convertTypeIndexToString(header, parameter.getType()) + " ");+ }++ DataType parametersDT = parameters.toDataType();++ Address parametersAddress =+ baseAddress.add(DexUtil.adjustOffset(item.getParametersOffset(), header));++ api.createData(parametersAddress, parametersDT);++ builder.append("\nParameters Address: " + parametersAddress);+ builder.append("\n");++ // add reference to the "parametersOffset" field+ api.createMemoryReference(data.getComponent(2), parametersAddress, RefType.DATA);+ }++ api.setPlateComment(address, builder.toString());++ ++index;++ address = address.add(dataType.getLength());+ }+ }++ private void processTypes(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMessage("DEX: processing types");+ monitor.setMaximum(header.getTypeIdsSize());+ monitor.setProgress(0);+ Address address = baseAddress.add(header.getTypeIdsOffset());+ int index = 0;+ for (TypeIDItem item : header.getTypes()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ DataType dataType = item.toDataType();+ api.createData(address, dataType);+ api.createFragment("types", address, dataType.getLength());++ StringBuilder builder = new StringBuilder();+ builder.append("Type Index: 0x" + Integer.toHexString(index) + "\n");+ builder.append(+ "\t" + "->" + DexUtil.convertToString(header, item.getDescriptorIndex()));+ api.setPlateComment(address, builder.toString());+ ++index;++ address = address.add(dataType.getLength());+ }+ }++ private void processMap(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ MapList mapList = header.getMapList();+ if (mapList == null) {+ return;+ }+ monitor.setMessage("DEX: processing map");+ monitor.setMaximum(mapList.getSize());+ monitor.setProgress(0);+ Address mapListAddress =+ baseAddress.add(DexUtil.adjustOffset(header.getMapOffset(), header));+ DataType mapListDataType = mapList.toDataType();+ api.createData(mapListAddress, mapListDataType);+ api.createFragment("map", mapListAddress, mapListDataType.getLength());+ StringBuilder builder = new StringBuilder();+ for (MapItem item : header.getMapList().getItems()) {+ monitor.checkCanceled();+ builder.append(MapItemTypeCodes.toString(item.getType()) + "\n");+ }+ api.setPlateComment(mapListAddress, builder.toString());+ }++ private void createInitialFragments(DexHeader header, TaskMonitor monitor) throws Exception {+ monitor.setMessage("DEX: creating fragments");++ if (header.getDataSize() > 0) {+ Address start = baseAddress.add(header.getDataOffset());+ api.createFragment("data", start, header.getDataSize());+ }+ }++ private void processStrings(DexHeader header, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMessage("DEX: processing strings");+ monitor.setMaximum(header.getStringIdsSize());+ monitor.setProgress(0);+ Address address = baseAddress.add(header.getStringIdsOffset());+ int index = 0;++ for (StringIDItem item : header.getStrings()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ // markup string data items+ Address stringDataAddress =+ baseAddress.add(DexUtil.adjustOffset(item.getStringDataOffset(), header));+ StringDataItem stringDataItem = item.getStringDataItem();++ if (stringDataItem == null) {+ log.appendMsg("Invalid string detected at " + stringDataAddress);+ continue;+ }++ String string = stringDataItem.getString();++ try {+ DataType stringDataType = stringDataItem.toDataType();+ api.createData(stringDataAddress, stringDataType);+ api.setPlateComment(stringDataAddress,+ Integer.toHexString(index) + "\n" + string.trim());+ api.createFragment("string_data", stringDataAddress, stringDataType.getLength());++ createStringSymbol(stringDataAddress, string, "strings");+ }+ catch (DuplicateNameException e) {+ log.appendException(e); // Report the exception but keep going+ }+ catch (InvalidInputException e) {+ log.appendException(e);+ }++ // markup string Id items+ DataType dataType = item.toDataType();+ try {+ Data data = api.createData(address, dataType);+ api.createFragment("strings", address, dataType.getLength());+ api.setPlateComment(address, "String Index: 0x" + Integer.toHexString(index) ++ "\nString: " + string.trim() + "\nString Data Address: " + stringDataAddress);+ createStringSymbol(address, string, "string_data");++ api.createMemoryReference(data, stringDataAddress, RefType.DATA);+ }+ catch (DuplicateNameException e) {+ log.appendException(e); // Report the exception but keep going+ }+ catch (InvalidInputException e) {+ log.appendException(e);+ }+ ++index;++ address = address.add(dataType.getLength());+ }+ }++ private void createStringSymbol(Address address, String string, String namespace) {+ SymbolTable symbolTable = program.getSymbolTable();+ if (string.length() > 0) {+ Namespace nameSpace = DexUtil.getOrCreateNameSpace(program, namespace);+ String symbolName = SymbolUtilities.replaceInvalidChars(string, true);+ if (symbolName.length() > SymbolUtilities.MAX_SYMBOL_NAME_LENGTH) {+ symbolName = symbolName.substring(0, SymbolUtilities.MAX_SYMBOL_NAME_LENGTH - 20);+ }+ try {+ symbolTable.createLabel(address, symbolName, nameSpace, SourceType.ANALYSIS);+ }+ catch (InvalidInputException e) {+ // TODO Symbol name matches possible default symbol name: BYTE_0+ }+ }+ }++ protected void removeEmptyFragments() throws NotEmptyException {+ ProgramModule rootModule = program.getListing().getRootModule("Program Tree");+ Group[] children = rootModule.getChildren();+ for (Group child : children) {+ if (child instanceof ProgramFragment) {+ ProgramFragment fragment = (ProgramFragment) child;+ if (fragment.isEmpty()) {+ rootModule.removeChild(fragment.getName());+ }+ }+ }+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupDataAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupDataAnalyzer.javaindex abb5ac4b13..676e6e39a8 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupDataAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupDataAnalyzer.java@@ -21,6 +21,7 @@ import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.bin.MemoryByteProvider;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.file.formats.android.cdex.CDexConstants;import ghidra.file.formats.android.dex.format.DexConstants;import ghidra.file.formats.android.dex.format.DexHeader;import ghidra.program.model.address.Address;@@ -33,32 +34,33 @@ import ghidra.util.task.TaskMonitor;public class DexMarkupDataAnalyzer extends FileFormatAnalyzer {@Override- public boolean analyze( Program program, AddressSetView set, TaskMonitor monitor, MessageLog log ) throws Exception {- monitor.setMaximum( set == null ? program.getMemory( ).getSize( ) : set.getNumAddresses( ) );- monitor.setProgress( 0 );+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMaximum(set == null ? program.getMemory().getSize() : set.getNumAddresses());+ monitor.setProgress(0);DexAnalysisState analysisState = DexAnalysisState.getState(program);DexHeader header = analysisState.getHeader();- int headerLength = header.toDataType( ).getLength( );+ int headerLength = header.toDataType().getLength();- Listing listing = program.getListing( );+ Listing listing = program.getListing();- DataIterator dataIterator = listing.getDefinedData( set, true );- while ( dataIterator.hasNext( ) ) {- monitor.checkCanceled( );- monitor.incrementProgress( 1 );+ DataIterator dataIterator = listing.getDefinedData(set, true);+ while (dataIterator.hasNext()) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);- Data data = dataIterator.next( );+ Data data = dataIterator.next();- if ( data.getMinAddress( ).getOffset( ) == 0x0 ) {+ if (data.getMinAddress().getOffset() == 0x0) {continue;// skip the main dex header..}- monitor.setMessage( "DEX: Data markup ... " + data.getMinAddress( ) );+ monitor.setMessage("DEX: Data markup ... " + data.getMinAddress());- if ( data.isStructure( ) ) {- processData( data, headerLength, monitor );+ if (data.isStructure()) {+ processData(data, headerLength, monitor);}}@@ -66,60 +68,63 @@ public class DexMarkupDataAnalyzer extends FileFormatAnalyzer {}@Override- public boolean canAnalyze( Program program ) {- ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getMinAddress( ) );- return DexConstants.isDexFile( provider );+ public boolean canAnalyze(Program program) {+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), program.getMinAddress());+ return DexConstants.isDexFile(provider) || CDexConstants.isCDEX(program);}@Override- public AnalyzerType getAnalysisType( ) {+ public AnalyzerType getAnalysisType() {return AnalyzerType.DATA_ANALYZER;}@Override- public boolean getDefaultEnablement( Program program ) {+ public boolean getDefaultEnablement(Program program) {return true;}@Override- public String getDescription( ) {- return "Android DEX Data Markup";+ public String getDescription() {+ return "Android DEX/CDEX Data Markup";}@Override- public String getName( ) {- return "Android DEX Data Markup";+ public String getName() {+ return "Android DEX/CDEX Data Markup";}@Override- public AnalysisPriority getPriority( ) {- return new AnalysisPriority( 5 );+ public AnalysisPriority getPriority() {+ return new AnalysisPriority(5);}@Override- public boolean isPrototype( ) {+ public boolean isPrototype() {return false;}- private void processData( Data data, int headerLength, TaskMonitor monitor ) throws Exception {- for ( int i = 0 ; i < data.getNumComponents( ) ; ++i ) {- monitor.checkCanceled( );- Data component = data.getComponent( i );- if ( component.getNumComponents( ) > 0 ) {- processData( component, headerLength, monitor );+ private void processData(Data data, int headerLength, TaskMonitor monitor) throws Exception {+ for (int i = 0; i < data.getNumComponents(); ++i) {+ monitor.checkCanceled();+ Data component = data.getComponent(i);+ if (component.getNumComponents() > 0) {+ processData(component, headerLength, monitor);}- if ( component.getReferencesFrom( ).length > 0 ) {+ if (component.getReferencesFrom().length > 0) {continue;}- if ( component.getFieldName( ).toLowerCase( ).indexOf( "offset" ) != -1 ) {- Scalar scalar = component.getScalar( 0 );- if ( scalar.getUnsignedValue( ) < headerLength ) {// skip low number points into dex header+ if (component.getFieldName().toLowerCase().indexOf("offset") != -1) {+ Scalar scalar = component.getScalar(0);+ if (scalar.getUnsignedValue() < headerLength) {// skip low number points into dex headercontinue;}- Address destination = component.getMinAddress( ).getNewAddress( scalar.getUnsignedValue( ) );- Program program = component.getProgram( );- ReferenceManager referenceManager = program.getReferenceManager( );- referenceManager.addMemoryReference( component.getMinAddress( ), destination, RefType.DATA, SourceType.ANALYSIS, 0 );+ Address destination =+ component.getMinAddress().getNewAddress(scalar.getUnsignedValue());+ Program program = component.getProgram();+ ReferenceManager referenceManager = program.getReferenceManager();+ referenceManager.addMemoryReference(component.getMinAddress(), destination,+ RefType.DATA, SourceType.ANALYSIS, 0);}}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupInstructionsAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupInstructionsAnalyzer.javaindex 768e12ce4e..466ddc9095 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupInstructionsAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupInstructionsAnalyzer.java@@ -23,7 +23,9 @@ import ghidra.app.services.AnalyzerType;import ghidra.app.util.bin.*;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.file.formats.android.cdex.CDexConstants;import ghidra.file.formats.android.dex.format.*;+import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.address.*;import ghidra.program.model.data.DataType;import ghidra.program.model.listing.*;@@ -34,101 +36,107 @@ import ghidra.util.task.TaskMonitor;public class DexMarkupInstructionsAnalyzer extends FileFormatAnalyzer {@Override- public boolean analyze( Program program, AddressSetView set, TaskMonitor monitor, MessageLog log ) throws Exception {- monitor.setMaximum( set == null ? program.getMemory( ).getSize( ) : set.getNumAddresses( ) );- monitor.setProgress( 0 );+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {+ monitor.setMaximum(set == null ? program.getMemory().getSize() : set.getNumAddresses());+ monitor.setProgress(0);DexAnalysisState analysisState = DexAnalysisState.getState(program);DexHeader header = analysisState.getHeader();// Set-up reader for fill_array_data- ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getMinAddress( ) );- BinaryReader reader = new BinaryReader( provider, true );+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), program.getMinAddress());+ BinaryReader reader = new BinaryReader(provider, true);- Listing listing = program.getListing( );+ Listing listing = program.getListing();- InstructionIterator instructionIterator = listing.getInstructions( set, true );- while ( instructionIterator.hasNext( ) ) {- Instruction instruction = instructionIterator.next( );+ InstructionIterator instructionIterator = listing.getInstructions(set, true);+ while (instructionIterator.hasNext()) {+ Instruction instruction = instructionIterator.next();- monitor.checkCanceled( );- monitor.incrementProgress( 1 );- monitor.setMessage( "DEX: Instruction markup ... " + instruction.getMinAddress( ) );+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ monitor.setMessage("DEX: Instruction markup ... " + instruction.getMinAddress());- String mnemonicString = instruction.getMnemonicString( );+ String mnemonicString = instruction.getMnemonicString();- if ( mnemonicString.startsWith( "invoke_super_quick" ) ) {+ if (mnemonicString.startsWith("invoke_super_quick")) {//ignore...}- else if ( mnemonicString.startsWith( "invoke_virtual_quick" ) ) {+ else if (mnemonicString.startsWith("invoke_virtual_quick")) {//ignore...}- else if ( mnemonicString.startsWith( "invoke_object_init_range" ) ) {+ else if (mnemonicString.startsWith("invoke_object_init_range")) {//ignore...}- else if ( mnemonicString.indexOf( "quick" ) > 0 ) {+ else if (mnemonicString.indexOf("quick") > 0) {//ignore...}- else if ( mnemonicString.startsWith( "const_string" ) ) {- Scalar scalar = instruction.getScalar( 1 );- processString( program, instruction, 1, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.startsWith("const_string")) {+ Scalar scalar = instruction.getScalar(1);+ processString(program, instruction, 1, header, (int) scalar.getUnsignedValue(),+ log);}- else if ( mnemonicString.equals( "const_class" ) ) {- Scalar scalar = instruction.getScalar( 1 );- processClass( program, instruction, 1, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.equals("const_class")) {+ Scalar scalar = instruction.getScalar(1);+ processClass(program, instruction, 1, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.equals( "instance_of" ) ) {- Scalar scalar = instruction.getScalar( 2 );- processClass( program, instruction, 2, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.equals("instance_of")) {+ Scalar scalar = instruction.getScalar(2);+ processClass(program, instruction, 2, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.equals( "check_cast" ) ) {- Scalar scalar = instruction.getScalar( 1 );- processClass( program, instruction, 1, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.equals("check_cast")) {+ Scalar scalar = instruction.getScalar(1);+ processClass(program, instruction, 1, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.startsWith( "invoke" ) ) {- Scalar scalar = instruction.getScalar( 0 );//method id- processMethod( program, instruction, 0, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.startsWith("invoke")) {+ Scalar scalar = instruction.getScalar(0);//method id+ processMethod(program, instruction, 0, header, (int) scalar.getUnsignedValue(),+ log);}- else if ( mnemonicString.equals( "new_instance" ) ) {- Scalar scalar = instruction.getScalar( 1 );- processClass( program, instruction, 1, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.equals("new_instance")) {+ Scalar scalar = instruction.getScalar(1);+ processClass(program, instruction, 1, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.equals( "new_array" ) ) {- Scalar scalar = instruction.getScalar( 2 );- processClass( program, instruction, 2, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.equals("new_array")) {+ Scalar scalar = instruction.getScalar(2);+ processClass(program, instruction, 2, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.startsWith( "iget" ) ) {- Scalar scalar = instruction.getScalar( 2 );- processField( program, instruction, 2, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.startsWith("iget")) {+ Scalar scalar = instruction.getScalar(2);+ processField(program, instruction, 2, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.startsWith( "iput" ) ) {- Scalar scalar = instruction.getScalar( 2 );- processField( program, instruction, 2, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.startsWith("iput")) {+ Scalar scalar = instruction.getScalar(2);+ processField(program, instruction, 2, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.startsWith( "sget" ) ) {- Scalar scalar = instruction.getScalar( 1 );- processField( program, instruction, 1, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.startsWith("sget")) {+ Scalar scalar = instruction.getScalar(1);+ processField(program, instruction, 1, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.startsWith( "sput" ) ) {- Scalar scalar = instruction.getScalar( 1 );- processField( program, instruction, 1, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.startsWith("sput")) {+ Scalar scalar = instruction.getScalar(1);+ processField(program, instruction, 1, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.startsWith( "filled_new_array" ) ) {- Scalar scalar = instruction.getScalar( 0 );- processClass( program, instruction, 0, header, ( int ) scalar.getUnsignedValue( ), log );+ else if (mnemonicString.startsWith("filled_new_array")) {+ Scalar scalar = instruction.getScalar(0);+ processClass(program, instruction, 0, header, (int) scalar.getUnsignedValue(), log);}- else if ( mnemonicString.startsWith( "fill_array_data" ) ) {- Scalar scalar = instruction.getScalar( 1 );- Address address = instruction.getMinAddress( ).add( scalar.getUnsignedValue( ) * 2 );- if ( program.getMemory( ).getShort( address ) != FilledArrayDataPayload.MAGIC ) {- log.appendMsg( "invalid filled array at " + address );+ else if (mnemonicString.startsWith("fill_array_data")) {+ Scalar scalar = instruction.getScalar(1);+ Address address = instruction.getMinAddress().add(scalar.getUnsignedValue() * 2);+ if (program.getMemory().getShort(address) != FilledArrayDataPayload.MAGIC) {+ log.appendMsg("invalid filled array at " + address);}else {- reader.setPointerIndex( address.getOffset( ) );- FilledArrayDataPayload payload = new FilledArrayDataPayload( reader );- DataType dataType = payload.toDataType( );- createData( program, address, dataType );- program.getReferenceManager( ).addMemoryReference( instruction.getMinAddress( ), address, RefType.DATA, SourceType.ANALYSIS, 1 );+ reader.setPointerIndex(address.getOffset());+ FilledArrayDataPayload payload = new FilledArrayDataPayload(reader);+ DataType dataType = payload.toDataType();+ createData(program, address, dataType);+ program.getReferenceManager()+ .addMemoryReference(instruction.getMinAddress(), address, RefType.DATA,+ SourceType.ANALYSIS, 1);}}}@@ -136,85 +144,89 @@ public class DexMarkupInstructionsAnalyzer extends FileFormatAnalyzer {}@Override- public boolean canAnalyze( Program program ) {- ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getMinAddress( ) );- return DexConstants.isDexFile( provider );+ public boolean canAnalyze(Program program) {+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), program.getMinAddress());+ return DexConstants.isDexFile(provider) || CDexConstants.isCDEX(program);}@Override- public AnalyzerType getAnalysisType( ) {+ public AnalyzerType getAnalysisType() {return AnalyzerType.INSTRUCTION_ANALYZER;}@Override- public boolean getDefaultEnablement( Program program ) {+ public boolean getDefaultEnablement(Program program) {return true;}@Override- public String getDescription( ) {- return "Android DEX Instruction Markup";+ public String getDescription() {+ return "Android DEX/CDEX Instruction Markup";}@Override- public String getName( ) {- return "Android DEX Instruction Markup";+ public String getName() {+ return "Android DEX/CDEX Instruction Markup";}@Override- public AnalysisPriority getPriority( ) {- return new AnalysisPriority( 4 );+ public AnalysisPriority getPriority() {+ return new AnalysisPriority(4);}@Override- public boolean isPrototype( ) {+ public boolean isPrototype() {return false;}- private String getClassName( Program program, DexHeader header, int classTypeIndex, MessageLog log ) {- TypeIDItem typeItem = header.getTypes( ).get( classTypeIndex );- StringIDItem stringItem = header.getStrings( ).get( typeItem.getDescriptorIndex( ) );- return stringItem.getStringDataItem( ).getString( );+ private String getClassName(Program program, DexHeader header, int classTypeIndex,+ MessageLog log) {+ TypeIDItem typeItem = header.getTypes().get(classTypeIndex);+ StringIDItem stringItem = header.getStrings().get(typeItem.getDescriptorIndex());+ return stringItem.getStringDataItem().getString();}- private String format( String className, String methodName ) {- StringBuilder builder = new StringBuilder( );- if ( className.startsWith( "L" ) && className.endsWith( ";" ) ) {- String str = className.substring( 1, className.length( ) - 1 );- StringTokenizer tokenizer = new StringTokenizer( str, "/" );- while ( tokenizer.hasMoreTokens( ) ) {- String token = tokenizer.nextToken( );- builder.append( token + "::" );+ private String format(String className, String methodName) {+ StringBuilder builder = new StringBuilder();+ if (className.startsWith("L") && className.endsWith(";")) {+ String str = className.substring(1, className.length() - 1);+ StringTokenizer tokenizer = new StringTokenizer(str, "/");+ while (tokenizer.hasMoreTokens()) {+ String token = tokenizer.nextToken();+ builder.append(token + "::");}}- builder.append( methodName );- return builder.toString( );+ builder.append(methodName);+ return builder.toString();}- private void setEquate( Program program, Address address, int operand, String equateName, int equateValue ) {- EquateTable equateTable = program.getEquateTable( );- Equate equate = equateTable.getEquate( equateName );- if ( equate == null ) {+ private void setEquate(Program program, Address address, int operand, String equateName,+ int equateValue) {+ EquateTable equateTable = program.getEquateTable();+ Equate equate = equateTable.getEquate(equateName);+ if (equate == null) {try {- equate = equateTable.createEquate( equateName, equateValue );+ equate = equateTable.createEquate(equateName, equateValue);}- catch ( Exception e ) {+ catch (Exception e) {// ignore}}- if ( equate == null ) {// happens when equate name is invalid+ if (equate == null) {// happens when equate name is invalidreturn;}- if ( equate.getValue( ) != equateValue ) {// verify value is same- setEquate( program, address, operand, equateName + "_" + equateValue, equateValue );+ if (equate.getValue() != equateValue) {// verify value is same+ setEquate(program, address, operand, equateName + "_" + equateValue, equateValue);return;}- equate.addReference( address, operand );+ equate.addReference(address, operand);}- private void processMethod( Program program, Instruction instruction, int operand, DexHeader header, int methodIndex, MessageLog log ) {- if ( methodIndex < 0 || methodIndex > header.getMethodIdsSize() ) {- log.appendMsg( "method index not found: " + methodIndex );+ private void processMethod(Program program, Instruction instruction, int operand,+ DexHeader header, int methodIndex, MessageLog log) {+ if (methodIndex < 0 || methodIndex > header.getMethodIdsSize()) {+ log.appendMsg("method index not found: " + methodIndex);return;}@@ -227,57 +239,70 @@ public class DexMarkupInstructionsAnalyzer extends FileFormatAnalyzer {//String valueName = format( className, methodName );- Address methodIndexAddress = header.getMethodAddress( program, methodIndex );+ Address methodIndexAddress = header.getMethodAddress(program, methodIndex);if (methodIndexAddress != Address.NO_ADDRESS)- program.getReferenceManager().addMemoryReference( instruction.getMinAddress(), methodIndexAddress, RefType.UNCONDITIONAL_CALL, SourceType.ANALYSIS, operand );+ program.getReferenceManager()+ .addMemoryReference(instruction.getMinAddress(), methodIndexAddress,+ RefType.UNCONDITIONAL_CALL, SourceType.ANALYSIS, operand);}- private void processClass( Program program, Instruction instruction, int operand, DexHeader header, int classTypeIndex, MessageLog log ) {- TypeIDItem typeItem = header.getTypes( ).get( classTypeIndex );- StringIDItem stringItem = header.getStrings( ).get( typeItem.getDescriptorIndex( ) );- String className = stringItem.getStringDataItem( ).getString( );+ private void processClass(Program program, Instruction instruction, int operand,+ DexHeader header, int classTypeIndex, MessageLog log) {+ if (classTypeIndex < 0 || classTypeIndex > header.getTypes().size()) {+ log.appendMsg("class type index not found: " + classTypeIndex);+ return;+ }+ TypeIDItem typeItem = header.getTypes().get(classTypeIndex);+ StringIDItem stringItem = header.getStrings().get(typeItem.getDescriptorIndex());+ String className = stringItem.getStringDataItem().getString();- setEquate( program, instruction.getMinAddress( ), operand, className, classTypeIndex );- program.getListing( ).setComment( instruction.getMinAddress( ), CodeUnit.EOL_COMMENT, className );+ setEquate(program, instruction.getMinAddress(), operand, className, classTypeIndex);+ program.getListing()+ .setComment(instruction.getMinAddress(), CodeUnit.EOL_COMMENT, className);}- private void processString( Program program, Instruction instruction, int operand, DexHeader header, int stringIndex, MessageLog log ) {- List< StringIDItem > strings = header.getStrings( );- if ( stringIndex < 0 || stringIndex > strings.size( ) ) {- log.appendMsg( "string index not found: " + stringIndex );+ private void processString(Program program, Instruction instruction, int operand,+ DexHeader header, int stringIndex, MessageLog log) {+ List<StringIDItem> strings = header.getStrings();+ if (stringIndex < 0 || stringIndex > strings.size()) {+ log.appendMsg("string index not found: " + stringIndex);return;}- StringIDItem stringIDItem = strings.get( stringIndex );- StringDataItem stringDataItem = stringIDItem.getStringDataItem( );- if ( stringDataItem == null ) {- log.appendMsg( "string data item is null: " + stringIndex );+ StringIDItem stringIDItem = strings.get(stringIndex);+ StringDataItem stringDataItem = stringIDItem.getStringDataItem();+ if (stringDataItem == null) {+ log.appendMsg("string data item is null: " + stringIndex);return;}AddressSpace defaultAddressSpace = program.getAddressFactory().getDefaultAddressSpace();- Address stringAddr = defaultAddressSpace.getAddress(stringIDItem.getStringDataOffset());- program.getReferenceManager().addMemoryReference(instruction.getMinAddress(), stringAddr,- RefType.DATA, SourceType.ANALYSIS, operand);+ Address stringAddr = defaultAddressSpace+ .getAddress(DexUtil.adjustOffset(stringIDItem.getStringDataOffset(), header));+ program.getReferenceManager()+ .addMemoryReference(instruction.getMinAddress(), stringAddr, RefType.DATA,+ SourceType.ANALYSIS, operand);// setEquate( program, instruction.getMinAddress( ), operand, stringDataItem.getString( ), stringIndex );// program.getListing( ).setComment( instruction.getMinAddress( ), CodeUnit.EOL_COMMENT, stringDataItem.getString( ) );}- private void processField( Program program, Instruction instruction, int operand, DexHeader header, int fieldIndex, MessageLog log ) {- List< FieldIDItem > fields = header.getFields( );+ private void processField(Program program, Instruction instruction, int operand,+ DexHeader header, int fieldIndex, MessageLog log) {+ List<FieldIDItem> fields = header.getFields();- if ( fieldIndex < 0 || fieldIndex > fields.size( ) ) {- log.appendMsg( "field index not found: " + fieldIndex );+ if (fieldIndex < 0 || fieldIndex > fields.size()) {+ log.appendMsg("field index not found: " + fieldIndex);return;}- FieldIDItem fieldIDItem = fields.get( fieldIndex );+ FieldIDItem fieldIDItem = fields.get(fieldIndex);- StringIDItem stringItem = header.getStrings( ).get( fieldIDItem.getNameIndex( ) );- String fieldName = stringItem.getStringDataItem( ).getString( );+ StringIDItem stringItem = header.getStrings().get(fieldIDItem.getNameIndex());+ String fieldName = stringItem.getStringDataItem().getString();- String className = getClassName( program, header, fieldIDItem.getClassIndex( ), log );- String valueName = format( className, fieldName );+ String className = getClassName(program, header, fieldIDItem.getClassIndex(), log);+ String valueName = format(className, fieldName);- setEquate( program, instruction.getMinAddress( ), operand, fieldName, fieldIndex );- program.getListing( ).setComment( instruction.getMinAddress( ), CodeUnit.EOL_COMMENT, valueName );+ setEquate(program, instruction.getMinAddress(), operand, fieldName, fieldIndex);+ program.getListing()+ .setComment(instruction.getMinAddress(), CodeUnit.EOL_COMMENT, valueName);}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupSwitchTableAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupSwitchTableAnalyzer.javaindex 203233aeca..bb6b77436c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupSwitchTableAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/analyzer/DexMarkupSwitchTableAnalyzer.java@@ -18,17 +18,29 @@ package ghidra.file.formats.android.dex.analyzer;import ghidra.app.cmd.disassemble.DisassembleCommand;import ghidra.app.services.AnalysisPriority;import ghidra.app.services.AnalyzerType;-import ghidra.app.util.bin.*;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.MemoryByteProvider;import ghidra.app.util.importer.MessageLog;import ghidra.file.analyzers.FileFormatAnalyzer;-import ghidra.file.formats.android.dex.format.*;+import ghidra.file.formats.android.cdex.CDexConstants;+import ghidra.file.formats.android.dex.format.DexConstants;+import ghidra.file.formats.android.dex.format.PackedSwitchPayload;+import ghidra.file.formats.android.dex.format.SparseSwitchPayload;import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressSetView;import ghidra.program.model.data.DataType;-import ghidra.program.model.listing.*;+import ghidra.program.model.listing.CodeUnit;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.listing.InstructionIterator;+import ghidra.program.model.listing.Listing;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.MemoryAccessException;import ghidra.program.model.scalar.Scalar;-import ghidra.program.model.symbol.*;+import ghidra.program.model.symbol.Namespace;+import ghidra.program.model.symbol.RefType;+import ghidra.program.model.symbol.SourceType;import ghidra.util.task.TaskMonitor;public class DexMarkupSwitchTableAnalyzer extends FileFormatAnalyzer {@@ -53,49 +65,59 @@ public class DexMarkupSwitchTableAnalyzer extends FileFormatAnalyzer {monitor.incrementProgress(1);monitor.setMessage("DEX: Instruction markup ... " + instruction.getMinAddress());- if (instruction.getMnemonicString().startsWith("packed_switch")) {- if (instruction.getMnemonicReferences().length > 0) {// already done- continue;+ try {+ if (instruction.getMnemonicString().startsWith("packed_switch")) {+ if (instruction.getMnemonicReferences().length > 0) {// already done+ continue;+ }+ Scalar scalar = instruction.getScalar(1);+ Address address =+ instruction.getMinAddress().add(scalar.getUnsignedValue() * 2);+ if (program.getMemory().getShort(address) != PackedSwitchPayload.MAGIC) {+ log.appendMsg("invalid packed switch at " + address);+ }+ else {+ program.getReferenceManager()+ .addMemoryReference(instruction.getMinAddress(), address,+ RefType.DATA, SourceType.ANALYSIS, 1);++ reader.setPointerIndex(address.getOffset());+ PackedSwitchPayload payload = new PackedSwitchPayload(reader);+ DataType dataType = payload.toDataType();+ createData(program, address, dataType);++ processPacked(program, instruction, payload, monitor);+ //TODO setFallThrough( program, instruction );+ }}- Scalar scalar = instruction.getScalar(1);- Address address = instruction.getMinAddress().add(scalar.getUnsignedValue() * 2);- if (program.getMemory().getShort(address) != PackedSwitchPayload.MAGIC) {- log.appendMsg("invalid packed switch at " + address);- }- else {- program.getReferenceManager().addMemoryReference(instruction.getMinAddress(),- address, RefType.DATA, SourceType.ANALYSIS, 1);-- reader.setPointerIndex(address.getOffset());- PackedSwitchPayload payload = new PackedSwitchPayload(reader);- DataType dataType = payload.toDataType();- createData(program, address, dataType);-- processPacked(program, instruction, payload, monitor);- //TODO setFallThrough( program, instruction );+ else if (instruction.getMnemonicString().startsWith("sparse_switch")) {+ if (instruction.getMnemonicReferences().length > 0) {// already done+ continue;+ }+ Scalar scalar = instruction.getScalar(1);+ Address address =+ instruction.getMinAddress().add(scalar.getUnsignedValue() * 2);++ if (program.getMemory().getShort(address) != SparseSwitchPayload.MAGIC) {+ log.appendMsg("invalid sparse switch at " + address);+ }+ else {+ program.getReferenceManager()+ .addMemoryReference(instruction.getMinAddress(), address,+ RefType.DATA, SourceType.ANALYSIS, 1);++ reader.setPointerIndex(address.getOffset());+ SparseSwitchPayload payload = new SparseSwitchPayload(reader);+ DataType dataType = payload.toDataType();+ createData(program, address, dataType);++ processSparse(program, instruction, payload, monitor);+ //TODO setFallThrough( program, instruction );+ }}}- else if (instruction.getMnemonicString().startsWith("sparse_switch")) {- if (instruction.getMnemonicReferences().length > 0) {// already done- continue;- }- Scalar scalar = instruction.getScalar(1);- Address address = instruction.getMinAddress().add(scalar.getUnsignedValue() * 2);- if (program.getMemory().getShort(address) != SparseSwitchPayload.MAGIC) {- log.appendMsg("invalid sparse switch at " + address);- }- else {- program.getReferenceManager().addMemoryReference(instruction.getMinAddress(),- address, RefType.DATA, SourceType.ANALYSIS, 1);-- reader.setPointerIndex(address.getOffset());- SparseSwitchPayload payload = new SparseSwitchPayload(reader);- DataType dataType = payload.toDataType();- createData(program, address, dataType);-- processSparse(program, instruction, payload, monitor);- //TODO setFallThrough( program, instruction );- }+ catch (MemoryAccessException e) {+ log.appendMsg("unable to process switch at " + instruction.getMinAddress());}}@@ -106,7 +128,7 @@ public class DexMarkupSwitchTableAnalyzer extends FileFormatAnalyzer {public boolean canAnalyze(Program program) {ByteProvider provider =new MemoryByteProvider(program.getMemory(), program.getMinAddress());- return DexConstants.isDexFile(provider);+ return DexConstants.isDexFile(provider) || CDexConstants.isCDEX(program);}@Override@@ -121,12 +143,12 @@ public class DexMarkupSwitchTableAnalyzer extends FileFormatAnalyzer {@Overridepublic String getDescription() {- return "Android DEX Switch Table Markup";+ return "Android DEX/CDEX Switch Table Markup";}@Overridepublic String getName() {- return "Android DEX Switch Table Markup";+ return "Android DEX/CDEX Switch Table Markup";}@Override@@ -157,10 +179,11 @@ public class DexMarkupSwitchTableAnalyzer extends FileFormatAnalyzer {String caseName = "case_0x" + Integer.toHexString(key);Address caseAddress = instruction.getMinAddress().add(target * 2);- program.getSymbolTable().createLabel(caseAddress, caseName, nameSpace,- SourceType.ANALYSIS);- program.getReferenceManager().addMemoryReference(instruction.getMinAddress(),- caseAddress, RefType.COMPUTED_JUMP, SourceType.ANALYSIS, CodeUnit.MNEMONIC);+ program.getSymbolTable()+ .createLabel(caseAddress, caseName, nameSpace, SourceType.ANALYSIS);+ program.getReferenceManager()+ .addMemoryReference(instruction.getMinAddress(), caseAddress,+ RefType.COMPUTED_JUMP, SourceType.ANALYSIS, CodeUnit.MNEMONIC);DisassembleCommand dCommand = new DisassembleCommand(caseAddress, null, true);dCommand.applyTo(program);++key;@@ -177,10 +200,11 @@ public class DexMarkupSwitchTableAnalyzer extends FileFormatAnalyzer {String caseName = "case_0x" + Integer.toHexString(payload.getKeys()[i]);Address caseAddress = instruction.getMinAddress().add(payload.getTargets()[i] * 2);- program.getSymbolTable().createLabel(caseAddress, caseName, nameSpace,- SourceType.ANALYSIS);- program.getReferenceManager().addMemoryReference(instruction.getMinAddress(),- caseAddress, RefType.COMPUTED_JUMP, SourceType.ANALYSIS, CodeUnit.MNEMONIC);+ program.getSymbolTable()+ .createLabel(caseAddress, caseName, nameSpace, SourceType.ANALYSIS);+ program.getReferenceManager()+ .addMemoryReference(instruction.getMinAddress(), caseAddress,+ RefType.COMPUTED_JUMP, SourceType.ANALYSIS, CodeUnit.MNEMONIC);DisassembleCommand dCommand = new DisassembleCommand(caseAddress, null, true);dCommand.applyTo(program);}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AccessFlags.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AccessFlags.javaindex ff0ca26edb..3dba8d052a 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AccessFlags.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AccessFlags.java@@ -19,40 +19,102 @@ import java.lang.reflect.Field;public final class AccessFlags {- public final static int ACC_PUBLIC = 0x1;// public: visible everywhere public: visible everywhere public: visible everywhere- public final static int ACC_PRIVATE = 0x2;// * private: only visible to defining class private: only visible to defining class private: only visible to defining class- public final static int ACC_PROTECTED = 0x4;// * protected: visible to package and subclasses protected: visible to package and subclasses protected: visible to package and subclasses public final- public final static int ACC_STATIC = 0x8;// * static: is not constructed with an outer this reference static: global to defining class static: does not take a this argument- public final static int ACC_FINAL = 0x10;// final: not subclassable final: immutable after construction final: not overridable- public final static int ACC_SYNCHRONIZED = 0x20;// synchronized: associated lock automatically acquired around call to this method. Note: This is only valid to set when ACC_NATIVE is also set.- public final static int ACC_VOLATILE = 0x40;// volatile: special access rules to help with thread safety- public final static int ACC_BRIDGE = 0x40;// bridge method, added automatically by compiler as a type-safe bridge- public final static int ACC_TRANSIENT = 0x80;// transient: not to be saved by default serialization- public final static int ACC_VARARGS = 0x80;// last argument should be treated as a "rest" argument by compiler- public final static int ACC_NATIVE = 0x100;// native: implemented in native code- public final static int ACC_INTERFACE = 0x200;// interface: multiply-implementable abstract class- public final static int ACC_ABSTRACT = 0x400;// abstract: not directly instantiable abstract: unimplemented by this class- public final static int ACC_STRICT = 0x800;// strictfp: strict rules for floating-point arithmetic- public final static int ACC_SYNTHETIC = 0x1000;// not directly defined in source code not directly defined in source code not directly defined in source code- public final static int ACC_ANNOTATION = 0x2000;// declared as an annotation class- public final static int ACC_ENUM = 0x4000;// declared as an enumerated type declared as an enumerated value+ /**+ * public: visible everywhere+ */+ public final static int ACC_PUBLIC = 0x1;+ /**+ * private: only visible to defining class+ */+ public final static int ACC_PRIVATE = 0x2;+ /**+ * protected: visible to package and subclasses+ */+ public final static int ACC_PROTECTED = 0x4;+ /**+ * static: is not constructed with an outer this reference+ */+ public final static int ACC_STATIC = 0x8;+ /**+ * final: not subclassable+ * final: immutable after construction+ * final: not overridable+ */+ public final static int ACC_FINAL = 0x10;+ /**+ * synchronized: associated lock automatically acquired around call to this method.+ * Note: This is only valid to set when ACC_NATIVE is also set.+ */+ public final static int ACC_SYNCHRONIZED = 0x20;+ /**+ * volatile: special access rules to help with thread safety+ */+ public final static int ACC_VOLATILE = 0x40;+ /**+ * bridge method, added automatically by compiler as a type-safe bridge+ */+ public final static int ACC_BRIDGE = 0x40;+ /**+ * transient: not to be saved by default serialization+ */+ public final static int ACC_TRANSIENT = 0x80;+ /**+ * last argument should be treated as a "rest" argument by compiler+ */+ public final static int ACC_VARARGS = 0x80;+ /**+ * native: implemented in native code+ */+ public final static int ACC_NATIVE = 0x100;+ /**+ * interface: multiply-implementable abstract class+ */+ public final static int ACC_INTERFACE = 0x200;+ /**+ * abstract: not directly instantiable+ * abstract: unimplemented by this class+ */+ public final static int ACC_ABSTRACT = 0x400;+ /**+ * strictfp: strict rules for floating-point arithmetic+ */+ public final static int ACC_STRICT = 0x800;+ /**+ * not directly defined in source code+ */+ public final static int ACC_SYNTHETIC = 0x1000;+ /**+ * declared as an annotation class+ */+ public final static int ACC_ANNOTATION = 0x2000;+ /**+ * declared as an enumerated type declared as an enumerated value+ */+ public final static int ACC_ENUM = 0x4000;// (unused) 0x8000- public final static int ACC_CONSTRUCTOR = 0x10000;// constructor method (class or instance initializer)- public final static int ACC_DECLARED_SYNCHRONIZED = 0x20000;// declared synchronized. Note: This has no effect on execution (other than in reflection of this flag, per se).+ /**+ * constructor method (class or instance initializer)+ */+ public final static int ACC_CONSTRUCTOR = 0x10000;+ /**+ * declared synchronized.+ * Note: This has no effect on execution (other than in reflection of this flag, per se).+ */+ public final static int ACC_DECLARED_SYNCHRONIZED = 0x20000;- public final static String toString( int value ) {- StringBuilder builder = new StringBuilder( );+ public final static String toString(int value) {+ StringBuilder builder = new StringBuilder();try {- Field [] fields = AccessFlags.class.getDeclaredFields( );- for ( Field field : fields ) {- if ( ( field.getInt( null ) & value ) != 0 ) {- builder.append( "\t" + field.getName( ) + "\n" );+ Field[] fields = AccessFlags.class.getDeclaredFields();+ for (Field field : fields) {+ if ((field.getInt(null) & value) != 0) {+ builder.append("\t" + field.getName() + "\n");}}}- catch ( Exception e ) {+ catch (Exception e) {// ignore}- return builder.toString( );+ return builder.toString();}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationElement.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationElement.javaindex 6e731e06cb..fd79ae0449 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationElement.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationElement.java@@ -29,35 +29,37 @@ public class AnnotationElement implements StructConverter {private int nameIndexLength;// in bytesprivate EncodedValue value;- public AnnotationElement( BinaryReader reader ) throws IOException {+ public AnnotationElement(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);nameIndex = leb128.asUInt32();nameIndexLength = leb128.getLength();- value = new EncodedValue( reader );+ value = new EncodedValue(reader);}- public int getNameIndex( ) {+ public int getNameIndex() {return nameIndex;}- public EncodedValue getValue( ) {+ public EncodedValue getValue() {return value;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType encodeValueDataType = value.toDataType( );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType encodeValueDataType = value.toDataType();- String name = "annotation_element" + "_" + nameIndexLength + "_" + encodeValueDataType.getName( );+ String name =+ "annotation_element" + "_" + nameIndexLength + "_" + encodeValueDataType.getName();- Structure structure = new StructureDataType( name, 0 );+ Structure structure = new StructureDataType(name, 0);- structure.add( new ArrayDataType( BYTE, nameIndexLength, BYTE.getLength( ) ), "nameIndex", null );+ structure.add(new ArrayDataType(BYTE, nameIndexLength, BYTE.getLength()), "nameIndex",+ null);- structure.add( encodeValueDataType, "value", null );+ structure.add(encodeValueDataType, "value", null);- structure.setCategoryPath( new CategoryPath( "/dex/annotation_element" ) );+ structure.setCategoryPath(new CategoryPath("/dex/annotation_element"));// try {// structure.setName( name + "_" + structure.getLength( ) );// }diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationItem.javaindex f250b5c053..5875bac17c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationItem.java@@ -21,44 +21,49 @@ import ghidra.util.exception.DuplicateNameException;import java.io.IOException;+/**+ *+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/dex_file_structs.h+ *+ */public class AnnotationItem implements StructConverter {private byte visibility;private EncodedAnnotation annotation;- public AnnotationItem( BinaryReader reader ) throws IOException {- visibility = reader.readNextByte( );- annotation = new EncodedAnnotation( reader );+ public AnnotationItem(BinaryReader reader) throws IOException {+ visibility = reader.readNextByte();+ annotation = new EncodedAnnotation(reader);}- public byte getVisibility( ) {+ public byte getVisibility() {return visibility;}- public EncodedAnnotation getAnnotation( ) {+ public EncodedAnnotation getAnnotation() {return annotation;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType annotationDataType = annotation.toDataType( );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType annotationDataType = annotation.toDataType();- StringBuilder builder = new StringBuilder( );- builder.append( "annotation_item" + "_" );- builder.append( visibility + "_" );- builder.append( annotationDataType.getName( ) );+ StringBuilder builder = new StringBuilder();+ builder.append("annotation_item" + "_");+ builder.append(visibility + "_");+ builder.append(annotationDataType.getName());- Structure structure = new StructureDataType( builder.toString( ), 0 );- structure.add( BYTE, "visibility", null );- structure.add( annotationDataType, "annotation", null );+ Structure structure = new StructureDataType(builder.toString(), 0);+ structure.add(BYTE, "visibility", null);+ structure.add(annotationDataType, "annotation", null);- builder.append( structure.getLength( ) + "_" );+ builder.append(structure.getLength() + "_");- structure.setCategoryPath( new CategoryPath( "/dex/annotation_item" ) );+ structure.setCategoryPath(new CategoryPath("/dex/annotation_item"));try {- structure.setName( builder.toString( ) );+ structure.setName(builder.toString());}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return structure;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationOffsetItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationOffsetItem.javaindex 2ae944ddc2..6aad094707 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationOffsetItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationOffsetItem.java@@ -16,6 +16,7 @@package ghidra.file.formats.android.dex.format;import ghidra.app.util.bin.*;+import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;@@ -27,33 +28,33 @@ public class AnnotationOffsetItem implements StructConverter {private AnnotationItem _item;- public AnnotationOffsetItem( BinaryReader reader ) throws IOException {- annotationsOffset = reader.readNextInt( );+ public AnnotationOffsetItem(BinaryReader reader, DexHeader dexHeader) throws IOException {+ annotationsOffset = reader.readNextInt();- if ( annotationsOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (annotationsOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( annotationsOffset );- _item = new AnnotationItem( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(annotationsOffset, dexHeader));+ _item = new AnnotationItem(reader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}- public int getAnnotationsOffset( ) {+ public int getAnnotationsOffset() {return annotationsOffset;}- public AnnotationItem getItem( ) {+ public AnnotationItem getItem() {return _item;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( AnnotationOffsetItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(AnnotationOffsetItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetItem.javaindex c48e6b6d99..ce4ecfd3dd 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetItem.java@@ -15,53 +15,51 @@*/package ghidra.file.formats.android.dex.format;-import ghidra.app.util.bin.*;+import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;-import java.util.*;-/**- * annotation_set_item- *- * referenced from annotations_directory_item, field_annotations_item, method_annotations_item, and annotation_set_ref_item- *- * appears in the data section- *- * alignment: 4 bytes+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/dex_file_structs.h#258*/public class AnnotationSetItem implements StructConverter {- private int size;- private List<AnnotationOffsetItem> items = new ArrayList<AnnotationOffsetItem>();+ private static final int MAX_SANE_COUNT = 0x1000;- public AnnotationSetItem( BinaryReader reader ) throws IOException {- size = reader.readNextInt( );+ private int size_;- for ( int i = 0 ; i < size ; ++i ) {- items.add( new AnnotationOffsetItem( reader ) );+ private int[] entries_;++ public AnnotationSetItem(BinaryReader reader, DexHeader dexHeader) throws IOException {+ size_ = reader.readNextInt();+ if (size_ > MAX_SANE_COUNT) {+ throw new IOException(+ "Too many annotations specified: 0x" + Integer.toHexString(size_));}+ entries_ = reader.readNextIntArray(size_);+}- public int getSize( ) {- return size;+ public int getSize() {+ return size_;}- public List< AnnotationOffsetItem > getItems( ) {- return Collections.unmodifiableList( items );+ public int[] getEntries() {+ return entries_;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "annotation_set_item_" + size, 0 );- structure.add( DWORD, "size", null );- int index = 0;- for ( AnnotationOffsetItem item : items ) {- structure.add( item.toDataType( ), "item" + index, null );- ++index;+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("annotation_set_item_" + size_, 0);+ structure.add(DWORD, "size_", null);+ if (size_ > 0) {+ ArrayDataType array = new ArrayDataType(DWORD, size_, DWORD.getLength());+ structure.add(array, "entries_", null);}- structure.setCategoryPath( new CategoryPath( "/dex/annotation_set_item" ) );+ structure.setCategoryPath(new CategoryPath("/dex/annotation_set_item"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceItem.javaindex a6b20050ec..d4397f80a1 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceItem.java@@ -32,33 +32,33 @@ public class AnnotationSetReferenceItem implements StructConverter {private AnnotationItem _item;- public AnnotationSetReferenceItem( BinaryReader reader ) throws IOException {- annotationsOffset = reader.readNextInt( );+ public AnnotationSetReferenceItem(BinaryReader reader) throws IOException {+ annotationsOffset = reader.readNextInt();- if ( annotationsOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (annotationsOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( annotationsOffset );- _item = new AnnotationItem( reader );+ reader.setPointerIndex(annotationsOffset);+ _item = new AnnotationItem(reader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}- public int getAnnotationsOffset( ) {+ public int getAnnotationsOffset() {return annotationsOffset;}- public AnnotationItem getItem( ) {+ public AnnotationItem getItem() {return _item;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( AnnotationSetReferenceItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(AnnotationSetReferenceItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceList.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceList.javaindex 18cef4a710..9c0ef02a67 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceList.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationSetReferenceList.java@@ -36,26 +36,26 @@ import java.util.List;public class AnnotationSetReferenceList implements StructConverter {private int size;- private List< AnnotationSetReferenceItem > items = new ArrayList< AnnotationSetReferenceItem >( );+ private List<AnnotationSetReferenceItem> items = new ArrayList<AnnotationSetReferenceItem>();- public AnnotationSetReferenceList( BinaryReader reader ) throws IOException {- size = reader.readNextInt( );+ public AnnotationSetReferenceList(BinaryReader reader) throws IOException {+ size = reader.readNextInt();- for ( int i = 0 ; i < size ; ++i ) {- items.add( new AnnotationSetReferenceItem( reader ) );+ for (int i = 0; i < size; ++i) {+ items.add(new AnnotationSetReferenceItem(reader));}}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "annotation_set_ref_list_" + size, 0 );- structure.add( DWORD, "size", null );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("annotation_set_ref_list_" + size, 0);+ structure.add(DWORD, "size", null);int index = 0;- for ( AnnotationSetReferenceItem item : items ) {- structure.add( item.toDataType( ), "item" + index, null );+ for (AnnotationSetReferenceItem item : items) {+ structure.add(item.toDataType(), "item" + index, null);++index;}- structure.setCategoryPath( new CategoryPath( "/dex/annotation_set_ref_list" ) );+ structure.setCategoryPath(new CategoryPath("/dex/annotation_set_ref_list"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationsDirectoryItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationsDirectoryItem.javaindex 853c6b8308..b2ac18d9a7 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationsDirectoryItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/AnnotationsDirectoryItem.java@@ -15,22 +15,17 @@*/package ghidra.file.formats.android.dex.format;+import java.io.IOException;+import java.util.*;+import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;+import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;-import java.util.*;-/**- * annotations_directory_item- *- * referenced from class_def_item- *- * appears in the data section- *- * alignment: 4 bytes+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/dex_file_structs.h#209*/public class AnnotationsDirectoryItem implements StructConverter {@@ -38,95 +33,94 @@ public class AnnotationsDirectoryItem implements StructConverter {private int fieldsSize;private int annotatedMethodsSize;private int annotatedParametersSize;- private List< FieldAnnotation > fieldAnnotations = new ArrayList< FieldAnnotation >( );- private List< MethodAnnotation > methodAnnotations = new ArrayList< MethodAnnotation >( );- private List< ParameterAnnotation > parameterAnnotations = new ArrayList< ParameterAnnotation >( );+ private List<FieldAnnotationsItem> fieldAnnotations = new ArrayList<FieldAnnotationsItem>();+ private List<MethodAnnotationsItem> methodAnnotations = new ArrayList<MethodAnnotationsItem>();+ private List<ParameterAnnotationsItem> parameterAnnotations =+ new ArrayList<ParameterAnnotationsItem>();private AnnotationSetItem _classAnnotations;- public AnnotationsDirectoryItem( BinaryReader reader ) throws IOException {+ public AnnotationsDirectoryItem(BinaryReader reader, DexHeader dexHeader) throws IOException {- classAnnotationsOffset = reader.readNextInt( );- fieldsSize = reader.readNextInt( );- annotatedMethodsSize = reader.readNextInt( );- annotatedParametersSize = reader.readNextInt( );+ classAnnotationsOffset = reader.readNextInt();+ fieldsSize = reader.readNextInt();+ annotatedMethodsSize = reader.readNextInt();+ annotatedParametersSize = reader.readNextInt();- for ( int i = 0 ; i < fieldsSize ; ++i ) {- fieldAnnotations.add( new FieldAnnotation( reader ) );- }- for ( int i = 0 ; i < annotatedMethodsSize ; ++i ) {- methodAnnotations.add( new MethodAnnotation( reader ) );+ for (int i = 0; i < fieldsSize; ++i) {+ fieldAnnotations.add(new FieldAnnotationsItem(reader, dexHeader));}- for ( int i = 0 ; i < annotatedParametersSize ; ++i ) {- parameterAnnotations.add( new ParameterAnnotation( reader ) );+ for (int i = 0; i < annotatedMethodsSize; ++i) {+ methodAnnotations.add(new MethodAnnotationsItem(reader, dexHeader));}- if ( classAnnotationsOffset > 0 ){- long oldIndex = reader.getPointerIndex( );+ if (classAnnotationsOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( classAnnotationsOffset );- _classAnnotations = new AnnotationSetItem( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(classAnnotationsOffset, dexHeader));+ _classAnnotations = new AnnotationSetItem(reader, dexHeader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}- public int getClassAnnotationsOffset( ) {+ public int getClassAnnotationsOffset() {return classAnnotationsOffset;}- public int getFieldsSize( ) {+ public int getFieldsSize() {return fieldsSize;}- public int getAnnotatedMethodsSize( ) {+ public int getAnnotatedMethodsSize() {return annotatedMethodsSize;}- public int getAnnotatedParametersSize( ) {+ public int getAnnotatedParametersSize() {return annotatedParametersSize;}- public List< FieldAnnotation > getFieldAnnotations( ) {- return Collections.unmodifiableList( fieldAnnotations );+ public List<FieldAnnotationsItem> getFieldAnnotations() {+ return Collections.unmodifiableList(fieldAnnotations);}- public List< MethodAnnotation > getMethodAnnotations( ) {- return Collections.unmodifiableList( methodAnnotations );+ public List<MethodAnnotationsItem> getMethodAnnotations() {+ return Collections.unmodifiableList(methodAnnotations);}- public List< ParameterAnnotation > getParameterAnnotations( ) {- return Collections.unmodifiableList( parameterAnnotations );+ public List<ParameterAnnotationsItem> getParameterAnnotations() {+ return Collections.unmodifiableList(parameterAnnotations);}- public AnnotationSetItem getClassAnnotations( ) {+ public AnnotationSetItem getClassAnnotations() {return _classAnnotations;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "annotations_directory_item_" + fieldsSize + "_" + annotatedMethodsSize + "_" + annotatedParametersSize, 0 );- structure.add( DWORD, "class_annotations_off", null );- structure.add( DWORD, "fields_size", null );- structure.add( DWORD, "annotated_methods_size", null );- structure.add( DWORD, "annotated_parameters_size", null );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("annotations_directory_item_" + fieldsSize ++ "_" + annotatedMethodsSize + "_" + annotatedParametersSize, 0);+ structure.add(DWORD, "class_annotations_off", null);+ structure.add(DWORD, "fields_size", null);+ structure.add(DWORD, "annotated_methods_size", null);+ structure.add(DWORD, "annotated_parameters_size", null);int index = 0;- for ( FieldAnnotation field : fieldAnnotations ) {- structure.add( field.toDataType( ), "field_" + index, null );+ for (FieldAnnotationsItem field : fieldAnnotations) {+ structure.add(field.toDataType(), "field_" + index, null);++index;}index = 0;- for ( MethodAnnotation method : methodAnnotations ) {- structure.add( method.toDataType( ), "method_" + index, null );+ for (MethodAnnotationsItem method : methodAnnotations) {+ structure.add(method.toDataType(), "method_" + index, null);++index;}index = 0;- for ( ParameterAnnotation parameter : parameterAnnotations ) {- structure.add( parameter.toDataType( ), "parameter_" + index, null );+ for (ParameterAnnotationsItem parameter : parameterAnnotations) {+ structure.add(parameter.toDataType(), "parameter_" + index, null);++index;}- structure.setCategoryPath( new CategoryPath( "/dex/annotations_directory_item" ) );+ structure.setCategoryPath(new CategoryPath("/dex/annotations_directory_item"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDataItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDataItem.javaindex 065f7702e9..88bbaabb86 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDataItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDataItem.java@@ -16,12 +16,18 @@package ghidra.file.formats.android.dex.format;import java.io.IOException;-import java.util.*;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.dwarf4.LEB128;-import ghidra.program.model.data.*;+import ghidra.program.model.data.ArrayDataType;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.data.StructureDataType;import ghidra.util.exception.DuplicateNameException;public class ClassDataItem implements StructConverter {@@ -36,12 +42,12 @@ public class ClassDataItem implements StructConverter {private int directMethodsSizeLength;// in bytesprivate int virtualMethodsSizeLength;// in bytes- private List< EncodedField > staticFields = new ArrayList< >( );- private List< EncodedField > instancesFields = new ArrayList< >( );- private List< EncodedMethod > directMethods = new ArrayList< >( );- private List< EncodedMethod > virtualMethods = new ArrayList< >( );+ private List<EncodedField> staticFields = new ArrayList<>();+ private List<EncodedField> instancesFields = new ArrayList<>();+ private List<EncodedMethod> directMethods = new ArrayList<>();+ private List<EncodedMethod> virtualMethods = new ArrayList<>();- public ClassDataItem( BinaryReader reader ) throws IOException {+ public ClassDataItem(BinaryReader reader, DexHeader dexHeader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);staticFieldsSize = leb128.asUInt32();staticFieldsSizeLength = leb128.getLength();@@ -58,70 +64,70 @@ public class ClassDataItem implements StructConverter {virtualMethodsSize = leb128.asUInt32();virtualMethodsSizeLength = leb128.getLength();- for ( int i = 0 ; i < staticFieldsSize ; ++i ) {- staticFields.add( new EncodedField( reader ) );+ for (int i = 0; i < staticFieldsSize; ++i) {+ staticFields.add(new EncodedField(reader));}- for ( int i = 0 ; i < instanceFieldsSize ; ++i ) {- instancesFields.add( new EncodedField( reader ) );+ for (int i = 0; i < instanceFieldsSize; ++i) {+ instancesFields.add(new EncodedField(reader));}int methodIndex = 0;- for ( int i = 0 ; i < directMethodsSize ; ++i ) {- EncodedMethod encodedMethod = new EncodedMethod( reader );- directMethods.add( encodedMethod );- methodIndex += encodedMethod.getMethodIndexDifference( );- encodedMethod.setMethodIndex( methodIndex );+ for (int i = 0; i < directMethodsSize; ++i) {+ EncodedMethod encodedMethod = new EncodedMethod(reader, dexHeader);+ directMethods.add(encodedMethod);+ methodIndex += encodedMethod.getMethodIndexDifference();+ encodedMethod.setMethodIndex(methodIndex);}methodIndex = 0;- for ( int i = 0 ; i < virtualMethodsSize ; ++i ) {- EncodedMethod encodedMethod = new EncodedMethod( reader );- virtualMethods.add( encodedMethod );- methodIndex += encodedMethod.getMethodIndexDifference( );- encodedMethod.setMethodIndex( methodIndex );+ for (int i = 0; i < virtualMethodsSize; ++i) {+ EncodedMethod encodedMethod = new EncodedMethod(reader, dexHeader);+ virtualMethods.add(encodedMethod);+ methodIndex += encodedMethod.getMethodIndexDifference();+ encodedMethod.setMethodIndex(methodIndex);}}- public List< EncodedField > getInstancesFields( ) {- return Collections.unmodifiableList( instancesFields );+ public List<EncodedField> getInstancesFields() {+ return Collections.unmodifiableList(instancesFields);}- public List< EncodedField > getStaticFields( ) {- return Collections.unmodifiableList( staticFields );+ public List<EncodedField> getStaticFields() {+ return Collections.unmodifiableList(staticFields);}- public List< EncodedMethod > getDirectMethods( ) {- return Collections.unmodifiableList( directMethods );+ public List<EncodedMethod> getDirectMethods() {+ return Collections.unmodifiableList(directMethods);}- public List< EncodedMethod > getVirtualMethods( ) {- return Collections.unmodifiableList( virtualMethods );+ public List<EncodedMethod> getVirtualMethods() {+ return Collections.unmodifiableList(virtualMethods);}- public int getStaticFieldsSize( ) {+ public int getStaticFieldsSize() {return staticFieldsSize;}- public int getInstanceFieldsSize( ) {+ public int getInstanceFieldsSize() {return instanceFieldsSize;}- public int getDirectMethodsSize( ) {+ public int getDirectMethodsSize() {return directMethodsSize;}- public int getVirtualMethodsSize( ) {+ public int getVirtualMethodsSize() {return virtualMethodsSize;}- public EncodedMethod getMethodByIndex( int index ) {- for ( int i = 0 ; i < directMethods.size() ; ++i ) {- EncodedMethod encodedMethod = directMethods.get( i );- if ( encodedMethod.getMethodIndex( ) == index ) {+ public EncodedMethod getMethodByIndex(int index) {+ for (int i = 0; i < directMethods.size(); ++i) {+ EncodedMethod encodedMethod = directMethods.get(i);+ if (encodedMethod.getMethodIndex() == index) {return encodedMethod;}}- for ( int i = 0 ; i < virtualMethods.size() ; ++i ) {- EncodedMethod encodedMethod = virtualMethods.get( i );- if ( encodedMethod.getMethodIndex( ) == index ) {+ for (int i = 0; i < virtualMethods.size(); ++i) {+ EncodedMethod encodedMethod = virtualMethods.get(i);+ if (encodedMethod.getMethodIndex() == index) {return encodedMethod;}}@@ -129,14 +135,20 @@ public class ClassDataItem implements StructConverter {}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {+ public DataType toDataType() throws DuplicateNameException, IOException {// int unique = 0;- String name = "class_data_item" + "_" + staticFieldsSizeLength + "_" + instanceFieldsSizeLength + "_" + directMethodsSizeLength + "_" + virtualMethodsSizeLength;- Structure structure = new StructureDataType( name, 0 );- structure.add( new ArrayDataType( BYTE, staticFieldsSizeLength, BYTE.getLength( ) ), "static_fields", null );- structure.add( new ArrayDataType( BYTE, instanceFieldsSizeLength, BYTE.getLength( ) ), "instance_fields", null );- structure.add( new ArrayDataType( BYTE, directMethodsSizeLength, BYTE.getLength( ) ), "direct_methods", null );- structure.add( new ArrayDataType( BYTE, virtualMethodsSizeLength, BYTE.getLength( ) ), "virtual_methods", null );+ String name =+ "class_data_item" + "_" + staticFieldsSizeLength + "_" + instanceFieldsSizeLength ++ "_" + directMethodsSizeLength + "_" + virtualMethodsSizeLength;+ Structure structure = new StructureDataType(name, 0);+ structure.add(new ArrayDataType(BYTE, staticFieldsSizeLength, BYTE.getLength()),+ "static_fields", null);+ structure.add(new ArrayDataType(BYTE, instanceFieldsSizeLength, BYTE.getLength()),+ "instance_fields", null);+ structure.add(new ArrayDataType(BYTE, directMethodsSizeLength, BYTE.getLength()),+ "direct_methods", null);+ structure.add(new ArrayDataType(BYTE, virtualMethodsSizeLength, BYTE.getLength()),+ "virtual_methods", null);// int index = 0;// for ( EncodedField field : staticFields ) {// DataType dataType = field.toDataType( );@@ -161,7 +173,7 @@ public class ClassDataItem implements StructConverter {// structure.add( dataType, "virtualMethod" + index, null );// ++index;// }- structure.setCategoryPath( new CategoryPath( "/dex/class_data_item" ) );+ structure.setCategoryPath(new CategoryPath("/dex/class_data_item"));// try {// structure.setName( name + "_" + Integer.toHexString( unique ) );// }diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDefItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDefItem.javaindex e5c38e8ac5..ce50f2983c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDefItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ClassDefItem.java@@ -41,138 +41,147 @@ public class ClassDefItem implements StructConverter {private ClassDataItem _classDataItem;private EncodedArrayItem _staticValues;- public ClassDefItem( BinaryReader reader ) throws IOException {- classIndex = reader.readNextInt( );- accessFlags = reader.readNextInt( );- superClassIndex = reader.readNextInt( );- interfacesOffset = reader.readNextInt( );- sourceFileIndex = reader.readNextInt( );- annotationsOffset = reader.readNextInt( );- classDataOffset = reader.readNextInt( );- staticValuesOffset = reader.readNextInt( );-- if ( interfacesOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ public ClassDefItem(BinaryReader reader, DexHeader dexHeader) throws IOException {+ classIndex = reader.readNextInt();+ accessFlags = reader.readNextInt();+ superClassIndex = reader.readNextInt();+ interfacesOffset = reader.readNextInt();+ sourceFileIndex = reader.readNextInt();+ annotationsOffset = reader.readNextInt();+ classDataOffset = reader.readNextInt();+ staticValuesOffset = reader.readNextInt();++ if (interfacesOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( interfacesOffset );- _interfaces = new TypeList( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(interfacesOffset, dexHeader));+ _interfaces = new TypeList(reader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}- if ( annotationsOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (annotationsOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( annotationsOffset );- _annotationsDirectoryItem = new AnnotationsDirectoryItem( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(annotationsOffset, dexHeader));+ _annotationsDirectoryItem = new AnnotationsDirectoryItem(reader, dexHeader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}- if ( classDataOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (classDataOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( classDataOffset );- _classDataItem = new ClassDataItem( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(classDataOffset, dexHeader));+ _classDataItem = new ClassDataItem(reader, dexHeader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}- if ( staticValuesOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (staticValuesOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( staticValuesOffset );- _staticValues = new EncodedArrayItem( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(staticValuesOffset, dexHeader));+ _staticValues = new EncodedArrayItem(reader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}- public int getClassIndex( ) {+ public int getClassIndex() {return classIndex;}- public int getAccessFlags( ) {+ public int getAccessFlags() {return accessFlags;}- public int getSuperClassIndex( ) {+ public int getSuperClassIndex() {return superClassIndex;}- public int getInterfacesOffset( ) {+ public int getInterfacesOffset() {return interfacesOffset;}- public int getSourceFileIndex( ) {+ public int getSourceFileIndex() {return sourceFileIndex;}- public int getAnnotationsOffset( ) {+ /**+ * NOTE: For CDEX files, this value is relative to DataOffset in DexHeader+ * @return the relative offset to annotations+ */+ public int getAnnotationsOffset() {return annotationsOffset;}- public int getClassDataOffset( ) {+ public int getClassDataOffset() {return classDataOffset;}- public int getStaticValuesOffset( ) {+ public int getStaticValuesOffset() {return staticValuesOffset;}- public TypeList getInterfaces( ) {+ public TypeList getInterfaces() {return _interfaces;}- public AnnotationsDirectoryItem getAnnotationsDirectoryItem( ) {+ public AnnotationsDirectoryItem getAnnotationsDirectoryItem() {return _annotationsDirectoryItem;}- public ClassDataItem getClassDataItem( ) {+ public ClassDataItem getClassDataItem() {return _classDataItem;}- public EncodedArrayItem getStaticValues( ) {+ public EncodedArrayItem getStaticValues() {return _staticValues;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( ClassDefItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(ClassDefItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}- public String toString( DexHeader header, int index, TaskMonitor monitor ) throws CancelledException {- StringBuilder builder = new StringBuilder( );- if ( index != -1 ) {- builder.append( "Class Index: 0x" + Integer.toHexString( index ) + "\n" );+ public String toString(DexHeader header, int index, TaskMonitor monitor)+ throws CancelledException {+ StringBuilder builder = new StringBuilder();+ if (index != -1) {+ builder.append("Class Index: 0x" + Integer.toHexString(index) + "\n");}- builder.append( "Class: " + DexUtil.convertTypeIndexToString( header, getClassIndex( ) ) + "\n" );- builder.append( "Class Access Flags:\n" + AccessFlags.toString( getAccessFlags( ) ) + "\n" );- builder.append( "Superclass: " + DexUtil.convertTypeIndexToString( header, getSuperClassIndex( ) ) + "\n" );-- if ( getInterfacesOffset( ) > 0 ) {- builder.append( "Interfaces: " + "\n" );- TypeList interfaces = getInterfaces( );- for ( TypeItem type : interfaces.getItems( ) ) {- monitor.checkCanceled( );- builder.append( "\t" + DexUtil.convertTypeIndexToString( header, type.getType( ) ) + "\n" );+ builder.append(+ "Class: " + DexUtil.convertTypeIndexToString(header, getClassIndex()) + "\n");+ builder.append("Class Access Flags:\n" + AccessFlags.toString(getAccessFlags()) + "\n");+ builder.append(+ "Superclass: " + DexUtil.convertTypeIndexToString(header, getSuperClassIndex()) + "\n");++ if (getInterfacesOffset() > 0) {+ builder.append("Interfaces: " + "\n");+ TypeList interfaces = getInterfaces();+ for (TypeItem type : interfaces.getItems()) {+ monitor.checkCanceled();+ builder.append(+ "\t" + DexUtil.convertTypeIndexToString(header, type.getType()) + "\n");}}- if ( getSourceFileIndex( ) > 0 ) {- builder.append( "Source File: " + DexUtil.convertToString( header, getSourceFileIndex( ) ) + "\n" );+ if (getSourceFileIndex() > 0) {+ builder.append(+ "Source File: " + DexUtil.convertToString(header, getSourceFileIndex()) + "\n");}- return builder.toString( );+ return builder.toString();}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/CodeItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/CodeItem.javaindex 0f75f22b62..2e5910bf3c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/CodeItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/CodeItem.java@@ -15,200 +15,202 @@*/package ghidra.file.formats.android.dex.format;+import java.io.IOException;+import java.util.*;+import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;-import java.util.*;-/*** code_item- *+ * <br>* referenced from encoded_method- *+ * <br>* appears in the data section- *+ * <br>* alignment: 4 bytes+ * <br>+ * https://source.android.com/devices/tech/dalvik/dex-format#code-item+ * <br>+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/code_item_accessors.h+ * <br>+ * https://android.googlesource.com/platform/art/+/android-9.0.0_r3/libdexfile/dex/compact_dex_file.h*/public class CodeItem implements StructConverter {- private short registersSize;- private short incomingSize;- private short outgoingSize;- private short triesSize;- private int debugInfoOffset;- private int instructionSize;- private short [] instructions;- private byte [] instructionBytes;- private short padding;- private List< TryItem > tries = new ArrayList< TryItem >( );- private EncodedCatchHandlerList handlers;- private DebugInfoItem debugInfo;-- public CodeItem( BinaryReader reader ) throws IOException {- registersSize = reader.readNextShort( );- incomingSize = reader.readNextShort( );- outgoingSize = reader.readNextShort( );- triesSize = reader.readNextShort( );- debugInfoOffset = reader.readNextInt( );- instructionSize = reader.readNextInt( );- if ( instructionSize == 0 ) {- instructionBytes = new byte[ 0 ];- instructions = new short[ 0 ];+ protected short registersSize;+ protected short incomingSize;+ protected short outgoingSize;+ protected short triesSize;+ protected int debugInfoOffset;+ protected int instructionSize;+ protected short[] instructions;+ protected byte[] instructionBytes;+ protected short padding;+ protected List<TryItem> tries = new ArrayList<TryItem>();+ protected EncodedCatchHandlerList handlers;+ protected DebugInfoItem debugInfo;++ protected CodeItem() {+ //do nothing+ }++ public CodeItem(BinaryReader reader) throws IOException {+ registersSize = reader.readNextShort();+ incomingSize = reader.readNextShort();+ outgoingSize = reader.readNextShort();+ triesSize = reader.readNextShort();+ debugInfoOffset = reader.readNextInt();+ instructionSize = reader.readNextInt();+ if (instructionSize == 0) {+ instructionBytes = new byte[0];+ instructions = new short[0];}else {- instructionBytes = reader.readByteArray( reader.getPointerIndex( ), instructionSize * 2 );- instructions = reader.readNextShortArray( instructionSize );+ instructionBytes = reader.readByteArray(reader.getPointerIndex(), instructionSize * 2);+ instructions = reader.readNextShortArray(instructionSize);}- if ( hasPadding( ) ) {- padding = reader.readNextShort( );+ if (hasPadding()) {+ padding = reader.readNextShort();}- for ( int i = 0 ; i < triesSize ; ++i ) {- tries.add( new TryItem( reader ) );+ for (int i = 0; i < triesSize; ++i) {+ tries.add(new TryItem(reader));}- if ( triesSize > 0 ) {- handlers = new EncodedCatchHandlerList( reader );+ if (triesSize > 0) {+ handlers = new EncodedCatchHandlerList(reader);}- if ( debugInfoOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (debugInfoOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( debugInfoOffset );- debugInfo = new DebugInfoItem( reader );+ reader.setPointerIndex(debugInfoOffset);+ debugInfo = new DebugInfoItem(reader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}/**- * <pre>* The number of registers used by this code- * </pre>+ * @return number of registers used by this code*/- public short getRegistersSize( ) {+ public short getRegistersSize() {return registersSize;}/**- * <pre>- * The number of words of incoming arguments to the method that this code is for- * </pre>+ * The number of words of incoming arguments to the method.+ * @return number of words of incoming arguments to the method*/- public short getIncomingSize( ) {+ public short getIncomingSize() {return incomingSize;}/**- * <pre>* The number of words of outgoing argument space required by this code for method invocation- * </pre>+ * @return number of words of outgoing argument space required by this code for method invocation*/- public short getOutgoingSize( ) {+ public short getOutgoingSize() {return outgoingSize;}/**- * <pre>* The number of try_items for this instance.* If non-zero, then these appear as the tries array just* after the insns in this instance.- * </pre>+ * @return number of try_items for this instance*/- public short getTriesSize( ) {+ public short getTriesSize() {return triesSize;}/**- * <pre>* Offset from the start of the file to the debug info* (line numbers + local variable info) sequence for this code, or 0 if there* simply is no information. The offset, if non-zero, should be to a location* in the data section. The format of the data is specified by "debug_info_item" below.- * </pre>+ * @return offset from the start of the file to the debug info*/- public int getDebugInfoOffset( ) {+ public int getDebugInfoOffset() {return debugInfoOffset;}/*** Size of the instructions list, in 16-bit code units+ * @return size of the instructions list*/- public int getInstructionSize( ) {+ public int getInstructionSize() {return instructionSize;}/**- * <pre>* Actual array of bytecode.* The format of code in an insns array is specified by the companion document Dalvik bytecode.* Note that though this is defined as an array of ushort,* there are some internal structures that prefer four-byte alignment.* Also, if this happens to be in an endian-swapped file, then the swapping is* only done on individual ushorts and not on the larger internal structures.- * </pre>+ * @return array of bytecode*/- public short [] getInstructions( ) {+ public short[] getInstructions() {return instructions;}- public byte [] getInstructionBytes( ) {+ public byte[] getInstructionBytes() {return instructionBytes;}/**- * <pre>* Two bytes of padding to make tries four-byte aligned.* This element is only present if tries_size is non-zero and insns_size is odd.- * </pre>+ * @return 2-bytes of padding*/- public short getPadding( ) {+ public short getPadding() {return padding;}/**- * <pre>* Array indicating where in the code exceptions are caught and how to handle them.* Elements of the array must be non-overlapping in range and in order from low to high address.* This element is only present if tries_size is non-zero.- * </pre>+ * @return array of Try's*/- public List< TryItem > getTries( ) {- return Collections.unmodifiableList( tries );+ public List<TryItem> getTries() {+ return Collections.unmodifiableList(tries);}/**- * <pre>- * Bytes representing a list of lists of catch types and associated handler addresses.+ * Bytes representing lists of catch types and associated handler addresses.* Each try_item has a byte-wise offset into this structure.* This element is only present if tries_size is non-zero.- * </pre>+ * @return lists of catch types*/- public EncodedCatchHandlerList getHandlerList( ) {+ public EncodedCatchHandlerList getHandlerList() {return handlers;}- public DebugInfoItem getDebugInfo( ) {+ public DebugInfoItem getDebugInfo() {return debugInfo;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- String suffix = hasPadding( ) ? "_p" : "";- String name = "code_item" + "_" + ( instructionSize * 2 ) + suffix;- Structure structure = new StructureDataType( name, 0 );- structure.add( WORD, "registers_size", null );- structure.add( WORD, "ins_size", null );- structure.add( WORD, "outs_size", null );- structure.add( WORD, "tries_size", null );- structure.add( DWORD, "debug_info_off", null );- structure.add( DWORD, "insns_size", null );- structure.add( new ArrayDataType( WORD, instructionSize, WORD.getLength( ) ), "insns", null );- if ( hasPadding( ) ) {- structure.add( WORD, "padding", null );+ public DataType toDataType() throws DuplicateNameException, IOException {+ String suffix = hasPadding() ? "_p" : "";+ String name = "code_item" + "_" + (instructionSize * 2) + suffix;+ Structure structure = new StructureDataType(name, 0);+ structure.add(WORD, "registers_size", null);+ structure.add(WORD, "ins_size", null);+ structure.add(WORD, "outs_size", null);+ structure.add(WORD, "tries_size", null);+ structure.add(DWORD, "debug_info_off", null);+ structure.add(DWORD, "insns_size", null);+ structure.add(new ArrayDataType(WORD, instructionSize, WORD.getLength()), "insns", null);+ if (hasPadding()) {+ structure.add(WORD, "padding", null);}// for ( int i = 0 ; i < tries.size( ) ; ++i ) {// DataType dataType = tries.get( i ).toDataType( );@@ -220,11 +222,11 @@ public class CodeItem implements StructConverter {// structure.add( dataType, "handlers", null );// unique = dataType.getLength( );// }- structure.setCategoryPath( new CategoryPath( "/dex/code_item" ) );+ structure.setCategoryPath(new CategoryPath("/dex/code_item"));return structure;}- private boolean hasPadding( ) {- return ( instructionSize % 2 ) != 0;+ private boolean hasPadding() {+ return (instructionSize % 2) != 0;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoItem.javaindex 184f5b4913..ec6a607332 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoItem.java@@ -29,11 +29,11 @@ public class DebugInfoItem implements StructConverter {private int lineStartLength;// in bytesprivate int parametersSize;private int parametersSizeLength;// in bytes- private int [] parameterNames;- private int [] parameterNamesLengths;- private byte [] stateMachineOpcodes;+ private int[] parameterNames;+ private int[] parameterNamesLengths;+ private byte[] stateMachineOpcodes;- public DebugInfoItem( BinaryReader reader ) throws IOException {+ public DebugInfoItem(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);lineStart = leb128.asUInt32();lineStartLength = leb128.getLength();@@ -42,18 +42,18 @@ public class DebugInfoItem implements StructConverter {parametersSize = leb128.asUInt32();parametersSizeLength = leb128.getLength();- parameterNames = new int[ parametersSize ];- parameterNamesLengths = new int[ parametersSize ];+ parameterNames = new int[parametersSize];+ parameterNamesLengths = new int[parametersSize];- for ( int i = 0 ; i < parametersSize ; ++i ) {+ for (int i = 0; i < parametersSize; ++i) {leb128 = LEB128.readUnsignedValue(reader);parameterNames[i] = leb128.asUInt32() - 1;// uleb128p1parameterNamesLengths[i] = leb128.getLength();}- int count = DebugInfoStateMachineReader.computeLength( reader.clone() );- stateMachineOpcodes = reader.readNextByteArray( count );+ int count = DebugInfoStateMachineReader.computeLength(reader.clone());+ stateMachineOpcodes = reader.readNextByteArray(count);}/**@@ -62,7 +62,7 @@ public class DebugInfoItem implements StructConverter {* Does not represent an actual positions entry.* </pre>*/- public int getLineStart( ) {+ public int getLineStart() {return lineStart;}@@ -72,7 +72,7 @@ public class DebugInfoItem implements StructConverter {* There should be one per method parameter, excluding an instance method's this, if any.* </pre>*/- public int getParametersSize( ) {+ public int getParametersSize() {return parametersSize;}@@ -83,42 +83,46 @@ public class DebugInfoItem implements StructConverter {* The type descriptor and signature are implied from the method descriptor and signature.* </pre>*/- public int [] getParameterNames( ) {+ public int[] getParameterNames() {return parameterNames;}- public byte [] getStateMachineOpcodes( ) {+ public byte[] getStateMachineOpcodes() {return stateMachineOpcodes;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- StringBuilder builder = new StringBuilder( );- builder.append( "debug_info_item" + "_" );- builder.append( lineStartLength + "" );- builder.append( parametersSizeLength + "" );- builder.append( parametersSize + "" );- builder.append( stateMachineOpcodes.length + "" );-- Structure structure = new StructureDataType( builder.toString( ), 0 );-- structure.add( new ArrayDataType( BYTE, lineStartLength, BYTE.getLength( ) ), "line_start", null );- structure.add( new ArrayDataType( BYTE, parametersSizeLength, BYTE.getLength( ) ), "parameters_size", null );-- for ( int i = 0 ; i < parametersSize ; ++i ) {- ArrayDataType dataType = new ArrayDataType( BYTE, parameterNamesLengths[ i ], BYTE.getLength( ) );- structure.add( dataType, "parameter_" + i, null );- builder.append( dataType.getLength( ) + "" );+ public DataType toDataType() throws DuplicateNameException, IOException {+ StringBuilder builder = new StringBuilder();+ builder.append("debug_info_item" + "_");+ builder.append(lineStartLength + "");+ builder.append(parametersSizeLength + "");+ builder.append(parametersSize + "");+ builder.append(stateMachineOpcodes.length + "");++ Structure structure = new StructureDataType(builder.toString(), 0);++ structure.add(new ArrayDataType(BYTE, lineStartLength, BYTE.getLength()), "line_start",+ null);+ structure.add(new ArrayDataType(BYTE, parametersSizeLength, BYTE.getLength()),+ "parameters_size", null);++ for (int i = 0; i < parametersSize; ++i) {+ ArrayDataType dataType =+ new ArrayDataType(BYTE, parameterNamesLengths[i], BYTE.getLength());+ structure.add(dataType, "parameter_" + i, null);+ builder.append(dataType.getLength() + "");}- ArrayDataType stateMachineArray = new ArrayDataType( BYTE, stateMachineOpcodes.length, BYTE.getLength( ) );- structure.add( stateMachineArray, "state_machine", null );+ ArrayDataType stateMachineArray =+ new ArrayDataType(BYTE, stateMachineOpcodes.length, BYTE.getLength());+ structure.add(stateMachineArray, "state_machine", null);- structure.setCategoryPath( new CategoryPath( "/dex/debug_info_item" ) );+ structure.setCategoryPath(new CategoryPath("/dex/debug_info_item"));try {- structure.setName( builder.toString( ) );+ structure.setName(builder.toString());}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return structure;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoOpcodes.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoOpcodes.javanew file mode 100644index 0000000000..e83c840fa4--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoOpcodes.java@@ -0,0 +1,38 @@+/* ###+ * 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.android.dex.format;++/**+ * Debug info opcodes and constants+ *+ */+public final class DebugInfoOpcodes {++ public final static byte DBG_END_SEQUENCE = 0x00;+ public final static byte DBG_ADVANCE_PC = 0x01;+ public final static byte DBG_ADVANCE_LINE = 0x02;+ public final static byte DBG_START_LOCAL = 0x03;+ public final static byte DBG_START_LOCAL_EXTENDED = 0x04;+ public final static byte DBG_END_LOCAL = 0x05;+ public final static byte DBG_RESTART_LOCAL = 0x06;+ public final static byte DBG_SET_PROLOGUE_END = 0x07;+ public final static byte DBG_SET_EPILOGUE_BEGIN = 0x08;+ public final static byte DBG_SET_FILE = 0x09;+ public final static byte DBG_FIRST_SPECIAL = 0x0a;+ public final static byte DBG_LINE_BASE = -4;+ public final static byte DBG_LINE_RANGE = 15;++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoStateMachineReader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoStateMachineReader.javaindex bd8ab387c7..cc47a11eb9 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoStateMachineReader.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugInfoStateMachineReader.java@@ -23,73 +23,73 @@ import ghidra.app.util.bin.format.dwarf4.LEB128;class DebugInfoStateMachineReader {private static final int MAX_SIZE = 0x10000; // 64k- static int computeLength( BinaryReader reader ) throws IOException {+ static int computeLength(BinaryReader reader) throws IOException {long start = reader.getPointerIndex();while (reader.getPointerIndex() - start < MAX_SIZE) {- byte opcode = reader.readNextByte( );+ byte opcode = reader.readNextByte();- switch( opcode ) {- case DebugStateMachineOpCodes.DBG_END_SEQUENCE: {+ switch (opcode) {+ case DebugStateMachineOpCodes.DBG_END_SEQUENCE: {return (int) (reader.getPointerIndex() - start);//done!- }- case DebugStateMachineOpCodes.DBG_ADVANCE_PC: {+ }+ case DebugStateMachineOpCodes.DBG_ADVANCE_PC: {LEB128.readAsUInt32(reader);- break;- }- case DebugStateMachineOpCodes.DBG_ADVANCE_LINE: {+ break;+ }+ case DebugStateMachineOpCodes.DBG_ADVANCE_LINE: {LEB128.readAsUInt32(reader);- break;- }- case DebugStateMachineOpCodes.DBG_START_LOCAL: {+ break;+ }+ case DebugStateMachineOpCodes.DBG_START_LOCAL: {int register = LEB128.readAsUInt32(reader);- //TODO uleb128p1+ //TODO uleb128p1int name = LEB128.readAsUInt32(reader);- //TODO uleb128p1+ //TODO uleb128p1int type = LEB128.readAsUInt32(reader);- break;- }- case DebugStateMachineOpCodes.DBG_START_LOCAL_EXTENDED: {+ break;+ }+ case DebugStateMachineOpCodes.DBG_START_LOCAL_EXTENDED: {int register = LEB128.readAsUInt32(reader);- //TODO uleb128p1+ //TODO uleb128p1int name = LEB128.readAsUInt32(reader);- //TODO uleb128p1+ //TODO uleb128p1int type = LEB128.readAsUInt32(reader);- //TODO uleb128p1+ //TODO uleb128p1int signature = LEB128.readAsUInt32(reader);- break;- }- case DebugStateMachineOpCodes.DBG_END_LOCAL: {+ break;+ }+ case DebugStateMachineOpCodes.DBG_END_LOCAL: {int register = LEB128.readAsUInt32(reader);- break;- }- case DebugStateMachineOpCodes.DBG_RESTART_LOCAL: {+ break;+ }+ case DebugStateMachineOpCodes.DBG_RESTART_LOCAL: {int register = LEB128.readAsUInt32(reader);- break;- }- case DebugStateMachineOpCodes.DBG_SET_PROLOGUE_END: {- break;- }- case DebugStateMachineOpCodes.DBG_SET_EPILOGUE_BEGIN: {- break;- }- case DebugStateMachineOpCodes.DBG_SET_FILE: {- //TODO uleb128p1+ break;+ }+ case DebugStateMachineOpCodes.DBG_SET_PROLOGUE_END: {+ break;+ }+ case DebugStateMachineOpCodes.DBG_SET_EPILOGUE_BEGIN: {+ break;+ }+ case DebugStateMachineOpCodes.DBG_SET_FILE: {+ //TODO uleb128p1int name = LEB128.readAsUInt32(reader);- break;- }- default: {- break;- }- }+ break;+ }+ default: {+ break;+ }+ }}return 0;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugStateMachineOpCodes.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugStateMachineOpCodes.javaindex d73618b4c0..2f9ee2f0b8 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugStateMachineOpCodes.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DebugStateMachineOpCodes.java@@ -134,8 +134,8 @@ public final class DebugStateMachineOpCodes {* Special Opcodes 0x0a...0xff (none) advances the line and address registers, emits a position entry, and clears prologue_end and epilogue_begin. See below for description.* </pre>*/- public final static boolean isSpecialOpCode( byte opcode ) {- return ( opcode & 0xff ) >= 0xa && ( opcode & 0xff ) <= 0xff;+ public final static boolean isSpecialOpCode(byte opcode) {+ return (opcode & 0xff) >= 0xa && (opcode & 0xff) <= 0xff;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexConstants.javaindex b3692acde8..6a0fa2c6ae 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexConstants.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexConstants.java@@ -17,6 +17,10 @@ package ghidra.file.formats.android.dex.format;import ghidra.app.util.bin.ByteProvider;+/**+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/dex_file.h+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/standard_dex_file.cc+ */public final class DexConstants {//public final static String DEX_MAGIC = "dex\n035\0";@@ -25,38 +29,57 @@ public final class DexConstants {public final static int DEX_VERSION_LENGTH = 4;- public final static String DEX_VERSION_009 = "009";+ public final static String DEX_VERSION_009 = "009";/** Expected version string */- public final static String DEX_VERSION_035 = "035";+ public final static String DEX_VERSION_035 = "035";/*** Dex version 036 skipped because of an old dalvik bug on some versions* of android where dex files with that version number would erroneously* be accepted and run.+ */+ public final static String DEX_VERSION_036 = "036";+ /**+ * V037 was introduced in API LEVEL 24+ */+ public final static String DEX_VERSION_037 = "037";+ /**+ * Dex version 038: Android "O" and beyond.+ *+ * V038 was introduced in API LEVEL 26+ */+ public final static String DEX_VERSION_038 = "038";+ /**+ * Dex version 039: Android "P" and beyond.*- * @see https://android.googlesource.com/platform/art/+/master/libdexfile/dex/standard_dex_file.cc+ * V039 was introduced in API LEVEL 28+ */+ public final static String DEX_VERSION_039 = "039";+ /**+ * Dex version 040: beyond Android "10" (previously known as Android "Q").*/- public final static String DEX_VERSION_036 = "036";- /** V037 was introduced in API LEVEL 24 */- public final static String DEX_VERSION_037 = "037";- /** V038 was introduced in API LEVEL 26 */- public final static String DEX_VERSION_038 = "038";- /** V039 was introduced in API LEVEL 28 */- public final static String DEX_VERSION_039 = "039";+ public final static String DEX_VERSION_040 = "040";public final static String MACHINE = "1";public final static int ENDIAN_CONSTANT = 0x12345678;public final static int REVERSE_ENDIAN_CONSTANT = 0x78563412;- public final static String kClassesDex = "classes.dex";+ public final static int kDexEndianConstant = 0x12345678;++ /**+ * First Dex format version enforcing class definition ordering rules.+ */+ public final static int kClassDefinitionOrderEnforcedVersion = 37;++ public final static int kSha1DigestSize = 20;- public final static boolean isDexFile( ByteProvider provider ) {+ public final static boolean isDexFile(ByteProvider provider) {try {- byte [] bytes = provider.readBytes( 0, DEX_MAGIC_BASE.length( ) );- return DEX_MAGIC_BASE.equals( new String( bytes ) );+ byte[] bytes = provider.readBytes(0, DEX_MAGIC_BASE.length());+ return DEX_MAGIC_BASE.equals(new String(bytes));}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return false;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexHeader.javaindex 8e22ed7503..8f4925520e 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexHeader.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexHeader.java@@ -29,10 +29,13 @@ import ghidra.util.NumericUtilities;import ghidra.util.datastruct.FixedSizeHashMap;import ghidra.util.exception.DuplicateNameException;+/**+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/dex_file.h#91+ */public class DexHeader implements StructConverter {private byte[] magic;- private byte [] version;+ private byte[] version;private int checksum;private byte[] signature;private int fileSize;@@ -67,6 +70,8 @@ public class DexHeader implements StructConverter {private AddressCache methodXref = new AddressCache(); // Index to method address cacheprivate DataTypeCache typeXref = new DataTypeCache(); // Index to datatype cache+ private boolean parsed = false;+public static class AddressCache extends FixedSizeHashMap<Integer, Address> {private static final int MAX_ENTRIES = 500;@@ -84,12 +89,10 @@ public class DexHeader implements StructConverter {}public DexHeader(BinaryReader reader) throws IOException {- magic = reader.readNextByteArray( DexConstants.DEX_MAGIC_BASE.length( ) );- version = reader.readNextByteArray( DexConstants.DEX_VERSION_LENGTH );+ magic = reader.readNextByteArray(DexConstants.DEX_MAGIC_BASE.length());+ version = reader.readNextByteArray(DexConstants.DEX_VERSION_LENGTH);- if (!DexConstants.DEX_MAGIC_BASE.equals(new String(magic))) {- throw new IOException("not a dex file.");- }+ checkMagic();checksum = reader.readNextInt();signature = reader.readNextByteArray(20);@@ -113,15 +116,22 @@ public class DexHeader implements StructConverter {classDefsIdsOffset = reader.readNextInt();dataSize = reader.readNextInt();dataOffset = reader.readNextInt();+ }- reader.setPointerIndex(mapOffset);+ public void parse(BinaryReader reader) throws IOException {+ if (parsed) {+ return;+ }+ parsed = true;++ reader.setPointerIndex(DexUtil.adjustOffset(mapOffset, this));if (mapOffset > 0) {mapList = new MapList(reader);}reader.setPointerIndex(stringIdsOffset);for (int i = 0; i < stringIdsSize; ++i) {- strings.add(new StringIDItem(reader));+ strings.add(new StringIDItem(reader, this));}reader.setPointerIndex(typeIdsOffset);@@ -131,7 +141,7 @@ public class DexHeader implements StructConverter {reader.setPointerIndex(protoIdsOffset);for (int i = 0; i < protoIdsSize; ++i) {- prototypes.add(new PrototypesIDItem(reader));+ prototypes.add(new PrototypesIDItem(reader, this));}reader.setPointerIndex(fieldIdsOffset);@@ -146,10 +156,31 @@ public class DexHeader implements StructConverter {reader.setPointerIndex(classDefsIdsOffset);for (int i = 0; i < classDefsIdsSize; ++i) {- classDefs.add(new ClassDefItem(reader));+ classDefs.add(new ClassDefItem(reader, this));}}+ protected void checkMagic() throws IOException {+ if (!DexConstants.DEX_MAGIC_BASE.equals(new String(getMagic()))) {+ throw new IOException("not a dex file.");+ }+ }++ /**+ * According to dex_file.h, the map offset is relative to data offset+ * <br>+ * https://android.googlesource.com/platform/art/+/refs/heads/master/libdexfile/dex/dex_file.h+ * <br>+ * <code>+ * uint32_t map_off_ = 0; // map list offset from data_off_+ * </code>+ * but it appears to only be true when dealing with compact dex files!+ * @return true if offsets in this DEX file are relative+ */+ public boolean isDataOffsetRelative() {+ return false;+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {Structure structure = new StructureDataType("header_item", 0);@@ -185,13 +216,14 @@ public class DexHeader implements StructConverter {return magic;}- public byte [] getVersion( ) {+ public byte[] getVersion() {return version;}/*** Adler32 checksum of the rest of the file (everything but magic and this field);* used to detect file corruption+ * @return the checksum*/public int getChecksum() {return checksum;@@ -200,6 +232,7 @@ public class DexHeader implements StructConverter {/*** SHA-1 signature (hash) of the rest of the file (everything but magic, checksum, and this field);* used to uniquely identify files+ * @return the signature*/public byte[] getSignature() {return signature;@@ -207,6 +240,7 @@ public class DexHeader implements StructConverter {/*** Size of the entire file (including the header), in bytes+ * @return the file size in bytes*/public int getFileSize() {return fileSize;@@ -216,6 +250,7 @@ public class DexHeader implements StructConverter {* Size of the header (this entire section), in bytes.* This allows for at least a limited amount of* backwards/forwards compatibility without invalidating the format.+ * @return the header size in bytes*/public int getHeaderSize() {return headerSize;@@ -223,6 +258,7 @@ public class DexHeader implements StructConverter {/*** Endianness tag. Either "ENDIAN_CONSTANT or REVERSE_ENDIAN_CONSTANT".+ * @return the endianness*/public int getEndianTag() {return endianTag;@@ -316,6 +352,11 @@ public class DexHeader implements StructConverter {return linkSize;}+ /**+ * NOTE: For CDEX files, this value is relative to DataOffset in DexHeader+ * Return the MAP offset.+ * @return the MAP offset+ */public int getMapOffset() {return mapOffset;}@@ -337,8 +378,9 @@ public class DexHeader implements StructConverter {try {val = program.getMemory().getInt(addr);if (val != -1) { // If there is an address here, it is in memory location of function- addr = program.getAddressFactory().getDefaultAddressSpace().getAddress(- val & 0xffffffffL);+ addr = program.getAddressFactory()+ .getDefaultAddressSpace()+ .getAddress(Integer.toUnsignedLong(val));}// Otherwise, the method is external, and we use the lookup address as placeholder}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexHeaderQuickMethods.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexHeaderQuickMethods.javanew file mode 100644index 0000000000..d5ddc89fcd--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/DexHeaderQuickMethods.java@@ -0,0 +1,41 @@+/* ###+ * 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.android.dex.format;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;++public final class DexHeaderQuickMethods {++ public static int getDexLength(BinaryReader reader) throws IOException {+ byte[] magic = reader.readNextByteArray(DexConstants.DEX_MAGIC_BASE.length());++ if (!DexConstants.DEX_MAGIC_BASE.equals(new String(magic))) {+ throw new IOException("not a dex file.");+ }++ byte[] version = reader.readNextByteArray(DexConstants.DEX_VERSION_LENGTH);++ int checksum = reader.readNextInt();++ byte[] signature = reader.readNextByteArray(20);++ int fileSize = reader.readNextInt();+ return fileSize;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedAnnotation.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedAnnotation.javaindex aa9f4ed5cd..9c3de4fdc1 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedAnnotation.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedAnnotation.java@@ -30,9 +30,9 @@ public class EncodedAnnotation implements StructConverter {private int typeIndexLength;// in bytesprivate int size;private int sizeLength;// in bytes- private List< AnnotationElement > elements = new ArrayList< >( );+ private List<AnnotationElement> elements = new ArrayList<>();- public EncodedAnnotation( BinaryReader reader ) throws IOException {+ public EncodedAnnotation(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);typeIndex = leb128.asUInt32();typeIndexLength = leb128.getLength();@@ -41,49 +41,50 @@ public class EncodedAnnotation implements StructConverter {size = leb128.asUInt32();sizeLength = leb128.getLength();- for ( int i = 0 ; i < size ; ++i ) {- elements.add( new AnnotationElement( reader ) );+ for (int i = 0; i < size; ++i) {+ elements.add(new AnnotationElement(reader));}}- public int getTypeIndex( ) {+ public int getTypeIndex() {return typeIndex;}- public int getSize( ) {+ public int getSize() {return size;}public List<AnnotationElement> getElements() {- return Collections.unmodifiableList( elements );+ return Collections.unmodifiableList(elements);}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- StringBuilder builder = new StringBuilder( );- builder.append( "encoded_annotation" + "_" );- builder.append( typeIndexLength + "_" );- builder.append( sizeLength + "_" );- builder.append( elements.size( ) + "_" );+ public DataType toDataType() throws DuplicateNameException, IOException {+ StringBuilder builder = new StringBuilder();+ builder.append("encoded_annotation" + "_");+ builder.append(typeIndexLength + "_");+ builder.append(sizeLength + "_");+ builder.append(elements.size() + "_");- Structure structure = new StructureDataType( builder.toString( ), 0 );+ Structure structure = new StructureDataType(builder.toString(), 0);- structure.add( new ArrayDataType( BYTE, typeIndexLength, BYTE.getLength( ) ), "typeIndex", null );- structure.add( new ArrayDataType( BYTE, sizeLength, BYTE.getLength( ) ), "size", null );+ structure.add(new ArrayDataType(BYTE, typeIndexLength, BYTE.getLength()), "typeIndex",+ null);+ structure.add(new ArrayDataType(BYTE, sizeLength, BYTE.getLength()), "size", null);int index = 0;- for ( AnnotationElement element : elements ) {- DataType dataType = element.toDataType( );- structure.add( dataType, "element" + index, null );+ for (AnnotationElement element : elements) {+ DataType dataType = element.toDataType();+ structure.add(dataType, "element" + index, null);++index;- builder.append( "" + dataType.getName( ) );+ builder.append("" + dataType.getName());}- structure.setCategoryPath( new CategoryPath( "/dex/encoded_annotation" ) );+ structure.setCategoryPath(new CategoryPath("/dex/encoded_annotation"));try {- structure.setName( builder.toString( ) );+ structure.setName(builder.toString());}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return structure;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArray.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArray.javaindex fa6454f602..86e5a2f16c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArray.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArray.java@@ -30,43 +30,43 @@ public class EncodedArray implements StructConverter {private int size;private int sizeLength;// in bytes// private List< EncodedValue > values = new ArrayList< EncodedValue >( );- private byte [] values;+ private byte[] values;- public EncodedArray( BinaryReader reader ) throws IOException {+ public EncodedArray(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);size = leb128.asUInt32();sizeLength = leb128.getLength();BinaryReader evReader = reader.clone();- List< EncodedValue > valuesList = new ArrayList< >( );- for ( int i = 0 ; i < size ; ++i ) {+ List<EncodedValue> valuesList = new ArrayList<>();+ for (int i = 0; i < size; ++i) {valuesList.add(new EncodedValue(evReader));}int nBytes = (int) (evReader.getPointerIndex() - reader.getPointerIndex());values = reader.readNextByteArray(nBytes); // Re-read the encoded values as a byte array}- public int getSize( ) {+ public int getSize() {return size;}- public byte [] getValues( ) {+ public byte[] getValues() {return values;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "encoded_array_" + values.length, 0 );- structure.add( new ArrayDataType( BYTE, sizeLength, BYTE.getLength( ) ), "size", null );- if ( values.length > 0 ) {- structure.add( new ArrayDataType( BYTE, values.length, BYTE.getLength( ) ), "values", null );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("encoded_array_" + values.length, 0);+ structure.add(new ArrayDataType(BYTE, sizeLength, BYTE.getLength()), "size", null);+ if (values.length > 0) {+ structure.add(new ArrayDataType(BYTE, values.length, BYTE.getLength()), "values", null);}// int index = 0;// for ( EncodedValue value : values ) {// structure.add( value.toDataType( ), "value" + index, null );// ++index;// }- structure.setCategoryPath( new CategoryPath( "/dex/encoded_array" ) );+ structure.setCategoryPath(new CategoryPath("/dex/encoded_array"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArrayItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArrayItem.javaindex b321b9962e..217c4e2fb1 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArrayItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedArrayItem.java@@ -26,20 +26,21 @@ public class EncodedArrayItem implements StructConverter {private EncodedArray array;- public EncodedArrayItem( BinaryReader reader ) throws IOException {- array = new EncodedArray( reader );+ public EncodedArrayItem(BinaryReader reader) throws IOException {+ array = new EncodedArray(reader);}- public EncodedArray getArray( ) {+ public EncodedArray getArray() {return array;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = array.toDataType( );- Structure structure = new StructureDataType( "encoded_array_item_" + dataType.getLength( ), 0 );- structure.add( dataType, "value", null );- structure.setCategoryPath( new CategoryPath( "/dex/encoded_array_item" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = array.toDataType();+ Structure structure =+ new StructureDataType("encoded_array_item_" + dataType.getLength(), 0);+ structure.add(dataType, "value", null);+ structure.setCategoryPath(new CategoryPath("/dex/encoded_array_item"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandler.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandler.javaindex 5bcf91a62c..74c7df8c2a 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandler.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandler.java@@ -29,20 +29,20 @@ public class EncodedCatchHandler implements StructConverter {private int size;private int sizeLength;// in bytes- private List< EncodedTypeAddressPair > handlers = new ArrayList< >( );+ private List<EncodedTypeAddressPair> handlers = new ArrayList<>();private int catchAllAddress;private int catchAllAddressLength;- public EncodedCatchHandler( BinaryReader reader ) throws IOException {+ public EncodedCatchHandler(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readSignedValue(reader);size = leb128.asInt32();sizeLength = leb128.getLength();- for ( int i = 0 ; i < Math.abs( size ) ; ++i ) {- handlers.add( new EncodedTypeAddressPair( reader ) );+ for (int i = 0; i < Math.abs(size); ++i) {+ handlers.add(new EncodedTypeAddressPair(reader));}- if ( size <= 0 ) {// This element is only present if size is non-positive.+ if (size <= 0) {// This element is only present if size is non-positive.leb128 = LEB128.readUnsignedValue(reader);catchAllAddress = leb128.asUInt32();catchAllAddressLength = leb128.getLength();@@ -58,44 +58,46 @@ public class EncodedCatchHandler implements StructConverter {* And a size of -1 means that there is one typed catch along with a catch-all.* </pre>*/- public int getSize( ) {+ public int getSize() {return size;}/*** Stream of abs(size) encoded items, one for each caught type, in the order that the types should be tested.*/- public List< EncodedTypeAddressPair > getPairs( ) {+ public List<EncodedTypeAddressPair> getPairs() {return handlers;}/*** Bytecode address of the catch-all handler. This element is only present if size is non-positive.*/- public int getCatchAllAddress( ) {+ public int getCatchAllAddress() {return catchAllAddress;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- StringBuilder builder = new StringBuilder( );- builder.append("encoded_catch_handler_" + sizeLength + "_" + catchAllAddressLength + "_" + handlers.size( ) );- Structure structure = new StructureDataType( builder.toString( ), 0 );- structure.add( new ArrayDataType( BYTE, sizeLength, BYTE.getLength( ) ), "size", null );+ public DataType toDataType() throws DuplicateNameException, IOException {+ StringBuilder builder = new StringBuilder();+ builder.append("encoded_catch_handler_" + sizeLength + "_" + catchAllAddressLength + "_" ++ handlers.size());+ Structure structure = new StructureDataType(builder.toString(), 0);+ structure.add(new ArrayDataType(BYTE, sizeLength, BYTE.getLength()), "size", null);int index = 0;- for ( EncodedTypeAddressPair pair : handlers ) {- DataType dataType = pair.toDataType( );- structure.add( dataType, "handler_" + index, null );- builder.append( pair.getDataTypeIdString( ) );+ for (EncodedTypeAddressPair pair : handlers) {+ DataType dataType = pair.toDataType();+ structure.add(dataType, "handler_" + index, null);+ builder.append(pair.getDataTypeIdString());}- if ( size <= 0 ) {// This element is only present if size is non-positive.- structure.add( new ArrayDataType( BYTE, catchAllAddressLength, BYTE.getLength( ) ), "catch_all_addr", null );+ if (size <= 0) {// This element is only present if size is non-positive.+ structure.add(new ArrayDataType(BYTE, catchAllAddressLength, BYTE.getLength()),+ "catch_all_addr", null);}- structure.setCategoryPath( new CategoryPath( "/dex/encoded_catch_handler" ) );+ structure.setCategoryPath(new CategoryPath("/dex/encoded_catch_handler"));try {- structure.setName( builder.toString( ) );+ structure.setName(builder.toString());}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return structure;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandlerList.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandlerList.javaindex 5df1321781..9d9b99ce4c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandlerList.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedCatchHandlerList.java@@ -29,42 +29,42 @@ public class EncodedCatchHandlerList implements StructConverter {private int size;private int sizeLength;// in bytes- private List< EncodedCatchHandler > handlers = new ArrayList< >( );+ private List<EncodedCatchHandler> handlers = new ArrayList<>();- public EncodedCatchHandlerList( BinaryReader reader ) throws IOException {+ public EncodedCatchHandlerList(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);size = leb128.asUInt32();sizeLength = leb128.getLength();- for ( int i = 0 ; i < size ; ++i ) {- handlers.add( new EncodedCatchHandler( reader ) );+ for (int i = 0; i < size; ++i) {+ handlers.add(new EncodedCatchHandler(reader));}}/*** size of this list, in entries*/- public int getSize( ) {+ public int getSize() {return size;}- public List< EncodedCatchHandler > getHandlers( ) {+ public List<EncodedCatchHandler> getHandlers() {return handlers;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {+ public DataType toDataType() throws DuplicateNameException, IOException {// int unique = 0;String name = "encoded_catch_handler_list" + "_" + sizeLength;- Structure structure = new StructureDataType( name, 0 );- structure.add( new ArrayDataType( BYTE, sizeLength, BYTE.getLength( ) ), "size", null );+ Structure structure = new StructureDataType(name, 0);+ structure.add(new ArrayDataType(BYTE, sizeLength, BYTE.getLength()), "size", null);// int index = 0;// for ( EncodedCatchHandler handler : handlers ) {// DataType dataType = handler.toDataType( );// structure.add( dataType, "handler_" + index, null );// unique += dataType.getLength( );// }- structure.setCategoryPath( new CategoryPath( "/dex/encoded_catch_handler_list" ) );+ structure.setCategoryPath(new CategoryPath("/dex/encoded_catch_handler_list"));// try {// structure.setName( name + "_" + Integer.toHexString( unique ) );// }diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedField.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedField.javaindex 1b98b51a8a..df52e191f3 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedField.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedField.java@@ -33,7 +33,7 @@ public class EncodedField implements StructConverter {private int accessFlags;private int accessFlagsLength;// in bytes- public EncodedField( BinaryReader reader ) throws IOException {+ public EncodedField(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);_fileOffset = leb128.getOffset();@@ -45,25 +45,27 @@ public class EncodedField implements StructConverter {accessFlagsLength = leb128.getLength();}- public long getFileOffset( ) {+ public long getFileOffset() {return _fileOffset;}- public int getFieldIndexDifference( ) {+ public int getFieldIndexDifference() {return fieldIndexDifference;}- public int getAccessFlags( ) {+ public int getAccessFlags() {return accessFlags;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {+ public DataType toDataType() throws DuplicateNameException, IOException {String name = "encoded_field_" + fieldIndexDifferenceLength + "_" + accessFlagsLength;- Structure structure = new StructureDataType( name, 0 );- structure.add( new ArrayDataType( BYTE, fieldIndexDifferenceLength, BYTE.getLength( ) ), "field_idx_diff", null );- structure.add( new ArrayDataType( BYTE, accessFlagsLength, BYTE.getLength( ) ), "accessFlags", null );- structure.setCategoryPath( new CategoryPath( "/dex/encoded_field" ) );+ Structure structure = new StructureDataType(name, 0);+ structure.add(new ArrayDataType(BYTE, fieldIndexDifferenceLength, BYTE.getLength()),+ "field_idx_diff", null);+ structure.add(new ArrayDataType(BYTE, accessFlagsLength, BYTE.getLength()), "accessFlags",+ null);+ structure.setCategoryPath(new CategoryPath("/dex/encoded_field"));return structure;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedMethod.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedMethod.javaindex a07e6342fc..0df6b246f9 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedMethod.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedMethod.java@@ -20,9 +20,20 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.dwarf4.LEB128;-import ghidra.program.model.data.*;+import ghidra.file.formats.android.cdex.CDexCodeItem;+import ghidra.file.formats.android.cdex.CDexHeader;+import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.program.model.data.ArrayDataType;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.data.StructureDataType;import ghidra.util.exception.DuplicateNameException;+/**+ *+ * https://source.android.com/devices/tech/dalvik/dex-format#encoded-method+ */public class EncodedMethod implements StructConverter {private long _fileOffset;@@ -38,7 +49,7 @@ public class EncodedMethod implements StructConverter {private CodeItem codeItem;- public EncodedMethod( BinaryReader reader ) throws IOException {+ public EncodedMethod(BinaryReader reader, DexHeader dexHeader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);_fileOffset = leb128.getOffset();@@ -53,51 +64,67 @@ public class EncodedMethod implements StructConverter {codeOffset = leb128.asUInt32();codeOffsetLength = leb128.getLength();- if ( codeOffset > 0 ) {- codeItem = new CodeItem( reader.clone(codeOffset) );+ if (codeOffset > 0) {+ long oldIndex = reader.getPointerIndex();+ try {+ reader.setPointerIndex(DexUtil.adjustOffset(codeOffset, dexHeader));+ if (dexHeader instanceof CDexHeader) {+ codeItem = new CDexCodeItem(reader);+ }+ else { //must be actual DexHeader base class+ codeItem = new CodeItem(reader);+ }+ }+ finally {+ reader.setPointerIndex(oldIndex);+ }}}- public long getFileOffset( ) {+ public long getFileOffset() {return _fileOffset;}- void setMethodIndex( int methodIndex ) {+ void setMethodIndex(int methodIndex) {_methodIndex = methodIndex;}- public int getMethodIndex( ) {+ public int getMethodIndex() {return _methodIndex;}- public int getMethodIndexDifference( ) {+ public int getMethodIndexDifference() {return methodIndexDifference;}- public int getAccessFlags( ) {+ public int getAccessFlags() {return accessFlags;}- public boolean isStatic( ) {- return ( accessFlags & AccessFlags.ACC_STATIC ) != 0;+ public boolean isStatic() {+ return (accessFlags & AccessFlags.ACC_STATIC) != 0;}- public int getCodeOffset( ) {+ public int getCodeOffset() {return codeOffset;}- public CodeItem getCodeItem( ) {+ public CodeItem getCodeItem() {return codeItem;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- String name = "encoded_method_" + methodIndexDifferenceLength + "_" + accessFlagsLength + "_" + codeOffsetLength;- Structure structure = new StructureDataType( name, 0 );- structure.add( new ArrayDataType( BYTE, methodIndexDifferenceLength, BYTE.getLength( ) ), "method_idx_diff", null );- structure.add( new ArrayDataType( BYTE, accessFlagsLength, BYTE.getLength( ) ), "access_flags", null );- structure.add( new ArrayDataType( BYTE, codeOffsetLength, BYTE.getLength( ) ), "code_off", null );- structure.setCategoryPath( new CategoryPath( "/dex/encoded_method" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ String name = "encoded_method_" + methodIndexDifferenceLength + "_" + accessFlagsLength ++ "_" + codeOffsetLength;+ Structure structure = new StructureDataType(name, 0);+ structure.add(new ArrayDataType(BYTE, methodIndexDifferenceLength, BYTE.getLength()),+ "method_idx_diff", null);+ structure.add(new ArrayDataType(BYTE, accessFlagsLength, BYTE.getLength()), "access_flags",+ null);+ structure.add(new ArrayDataType(BYTE, codeOffsetLength, BYTE.getLength()), "code_off",+ null);+ structure.setCategoryPath(new CategoryPath("/dex/encoded_method"));return structure;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedTypeAddressPair.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedTypeAddressPair.javaindex e8c70f5e54..7d66a9fdad 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedTypeAddressPair.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedTypeAddressPair.java@@ -31,7 +31,7 @@ public class EncodedTypeAddressPair implements StructConverter {private int typeIndexLength;// in bytesprivate int addressLength;// in bytes- public EncodedTypeAddressPair( BinaryReader reader ) throws IOException {+ public EncodedTypeAddressPair(BinaryReader reader) throws IOException {LEB128 leb128 = LEB128.readUnsignedValue(reader);typeIndex = leb128.asUInt32();typeIndexLength = leb128.getLength();@@ -41,11 +41,11 @@ public class EncodedTypeAddressPair implements StructConverter {addressLength = leb128.getLength();}- public int getTypeIndex( ) {+ public int getTypeIndex() {return typeIndex;}- public int getAddress( ) {+ public int getAddress() {return address;}@@ -58,11 +58,12 @@ public class EncodedTypeAddressPair implements StructConverter {}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "encoded_type_addr_pair_" + typeIndexLength + "_" + addressLength, 0 );- structure.add( new ArrayDataType( BYTE, typeIndexLength, BYTE.getLength( ) ), "type_idx", null );- structure.add( new ArrayDataType( BYTE, addressLength, BYTE.getLength( ) ), "addr", null );- structure.setCategoryPath( new CategoryPath( "/dex/encoded_type_addr_pair" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType(+ "encoded_type_addr_pair_" + typeIndexLength + "_" + addressLength, 0);+ structure.add(new ArrayDataType(BYTE, typeIndexLength, BYTE.getLength()), "type_idx", null);+ structure.add(new ArrayDataType(BYTE, addressLength, BYTE.getLength()), "addr", null);+ structure.setCategoryPath(new CategoryPath("/dex/encoded_type_addr_pair"));return structure;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedValue.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedValue.javaindex 727ceab591..0e1dfe2c40 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedValue.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/EncodedValue.java@@ -29,19 +29,19 @@ public class EncodedValue implements StructConverter {private byte valueType;private byte valueArgs;- private byte [] valueBytes;+ private byte[] valueBytes;private EncodedArray array;private EncodedAnnotation annotation;- public EncodedValue( BinaryReader reader ) throws IOException {- value = reader.readNextByte( );- valueType = ( byte ) ( value & 0x1f );- valueArgs = ( byte ) ( ( value & 0xe0 ) >> 5 );+ public EncodedValue(BinaryReader reader) throws IOException {+ value = reader.readNextByte();+ valueType = (byte) (value & 0x1f);+ valueArgs = (byte) ((value & 0xe0) >> 5);// length of value[] is based on TYPE....- switch ( valueType ) {+ switch (valueType) {case ValueFormats.VALUE_BYTE:case ValueFormats.VALUE_SHORT:case ValueFormats.VALUE_CHAR:@@ -54,15 +54,15 @@ public class EncodedValue implements StructConverter {case ValueFormats.VALUE_FIELD:case ValueFormats.VALUE_METHOD:case ValueFormats.VALUE_ENUM: {- valueBytes = reader.readNextByteArray( valueArgs + 1 );+ valueBytes = reader.readNextByteArray(valueArgs + 1);break;}case ValueFormats.VALUE_ARRAY: {- array = new EncodedArray( reader );+ array = new EncodedArray(reader);break;}case ValueFormats.VALUE_ANNOTATION: {- annotation = new EncodedAnnotation( reader );+ annotation = new EncodedAnnotation(reader);break;}case ValueFormats.VALUE_NULL: {@@ -71,50 +71,51 @@ public class EncodedValue implements StructConverter {case ValueFormats.VALUE_BOOLEAN: {break;// do nothing...}- default : {- //TODO throw new RuntimeException( "unsupported encoded value: 0x" + Integer.toHexString( valueType & 0xff ) );+ default: {+ break;// do nothing...}}}- public byte getValueArgs( ) {+ public byte getValueArgs() {return valueArgs;}- public byte getValueType( ) {+ public byte getValueType() {return valueType;}- public byte [] getValueBytes( ) {+ public byte[] getValueBytes() {return valueBytes;}- public byte getValueByte( ) {- return valueBytes[ 0 ];+ public byte getValueByte() {+ return valueBytes[0];}- public EncodedArray getArray( ) {+ public EncodedArray getArray() {return array;}- public EncodedAnnotation getAnnotation( ) {+ public EncodedAnnotation getAnnotation() {return annotation;}- public boolean isValueBoolean( ) {+ public boolean isValueBoolean() {return valueArgs == 1;}- byte getValue( ) {+ byte getValue() {return value;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- StringBuilder builder = new StringBuilder( "encoded_value_0x" + Integer.toHexString( value & 0xff ) );- Structure structure = new StructureDataType( builder.toString( ), 0 );- structure.add( BYTE, "valueType", null );- switch ( valueType ) {+ public DataType toDataType() throws DuplicateNameException, IOException {+ StringBuilder builder =+ new StringBuilder("encoded_value_0x" + Integer.toHexString(value & 0xff));+ Structure structure = new StructureDataType(builder.toString(), 0);+ structure.add(BYTE, "valueType", null);+ switch (valueType) {case ValueFormats.VALUE_BYTE:case ValueFormats.VALUE_SHORT:case ValueFormats.VALUE_CHAR:@@ -127,20 +128,20 @@ public class EncodedValue implements StructConverter {case ValueFormats.VALUE_FIELD:case ValueFormats.VALUE_METHOD:case ValueFormats.VALUE_ENUM: {- int length = ( valueArgs & 0xff ) + 1;- structure.add( new ArrayDataType( BYTE, length, BYTE.getLength( ) ), "value", null );- builder.append( "_" + length );+ int length = (valueArgs & 0xff) + 1;+ structure.add(new ArrayDataType(BYTE, length, BYTE.getLength()), "value", null);+ builder.append("_" + length);break;}case ValueFormats.VALUE_ARRAY: {- builder.append( "_" + array.getValues().length );- structure.add( array.toDataType( ), "value", null );+ builder.append("_" + array.getValues().length);+ structure.add(array.toDataType(), "value", null);break;}case ValueFormats.VALUE_ANNOTATION: {- DataType dataType = annotation.toDataType( );- structure.add( dataType, "value", null );- builder.append( "_" + dataType.getName( ) );+ DataType dataType = annotation.toDataType();+ structure.add(dataType, "value", null);+ builder.append("_" + dataType.getName());break;}case ValueFormats.VALUE_NULL: {@@ -149,17 +150,17 @@ public class EncodedValue implements StructConverter {case ValueFormats.VALUE_BOOLEAN: {break;// do nothing}- default : {+ default: {//TODO throw new RuntimeException( "unsupported encoded value: 0x" + Integer.toHexString( valueType & 0xff ) );}}try {- structure.setName( builder.toString( ) );+ structure.setName(builder.toString());}- catch ( InvalidNameException e ) {+ catch (InvalidNameException e) {// ignore, should never happen}- structure.setCategoryPath( new CategoryPath( "/dex/encoded_value" ) );+ structure.setCategoryPath(new CategoryPath("/dex/encoded_value"));return structure;}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldAnnotation.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldAnnotationsItem.javasimilarity index 58%rename from Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldAnnotation.javarename to Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldAnnotationsItem.javaindex 0832429e26..c657700e28 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldAnnotation.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldAnnotationsItem.java@@ -15,13 +15,16 @@*/package ghidra.file.formats.android.dex.format;-import ghidra.app.util.bin.*;+import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.data.CategoryPath;import ghidra.program.model.data.DataType;import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;-/**** field_annotation format@@ -33,46 +36,41 @@ import java.io.IOException;* annotations_off uint offset from the start of the file to the list of annotations for the field. The offset should be to a location in the data section. The format of the data is specified by* "annotation_set_item" below.*+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/dex_file_structs.h*/-public class FieldAnnotation implements StructConverter {+public class FieldAnnotationsItem implements StructConverter {private int fieldIndex;private int annotationsOffset;private AnnotationSetItem _annotationSetItem;- public FieldAnnotation( BinaryReader reader ) throws IOException {- fieldIndex = reader.readNextInt( );- annotationsOffset = reader.readNextInt( );+ public FieldAnnotationsItem(BinaryReader reader, DexHeader dexHeader) throws IOException {+ fieldIndex = reader.readNextInt();+ annotationsOffset = reader.readNextInt();- if ( annotationsOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );- try {- reader.setPointerIndex( annotationsOffset );- _annotationSetItem = new AnnotationSetItem( reader );- }- finally {- reader.setPointerIndex( oldIndex );- }+ if (annotationsOffset > 0) {+ BinaryReader clonedReader = reader.clone(DexUtil.adjustOffset(annotationsOffset, dexHeader));+ _annotationSetItem = new AnnotationSetItem(clonedReader, dexHeader);}}- public int getFieldIndex( ) {+ public int getFieldIndex() {return fieldIndex;}- public int getAnnotationsOffset( ) {+ public int getAnnotationsOffset() {return annotationsOffset;}- public AnnotationSetItem getAnnotationSetItem( ) {+ public AnnotationSetItem getAnnotationSetItem() {return _annotationSetItem;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( FieldAnnotation.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(FieldAnnotationsItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldIDItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldIDItem.javaindex b60fae079a..5a286cb3d0 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldIDItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FieldIDItem.java@@ -28,28 +28,28 @@ public class FieldIDItem implements StructConverter {private short typeIndex;private int nameIndex;- public FieldIDItem( BinaryReader reader ) throws IOException {- classIndex = reader.readNextShort( );- typeIndex = reader.readNextShort( );- nameIndex = reader.readNextInt( );+ public FieldIDItem(BinaryReader reader) throws IOException {+ classIndex = reader.readNextShort();+ typeIndex = reader.readNextShort();+ nameIndex = reader.readNextInt();}- public short getClassIndex( ) {+ public short getClassIndex() {return classIndex;}- public short getTypeIndex( ) {+ public short getTypeIndex() {return typeIndex;}- public int getNameIndex( ) {+ public int getNameIndex() {return nameIndex;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( FieldIDItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(FieldIDItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FilledArrayDataPayload.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FilledArrayDataPayload.javaindex 2fa30db6c3..9a814d4254 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FilledArrayDataPayload.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/FilledArrayDataPayload.java@@ -29,39 +29,40 @@ public class FilledArrayDataPayload implements StructConverter {private short ident;private short elementWidth;private int size;- private byte [] data;+ private byte[] data;- public FilledArrayDataPayload( BinaryReader reader ) throws IOException {- ident = reader.readNextShort( );- elementWidth = reader.readNextShort( );- size = reader.readNextInt( );- data = reader.readNextByteArray( size * elementWidth );+ public FilledArrayDataPayload(BinaryReader reader) throws IOException {+ ident = reader.readNextShort();+ elementWidth = reader.readNextShort();+ size = reader.readNextInt();+ data = reader.readNextByteArray(size * elementWidth);}- public short getIdent( ) {+ public short getIdent() {return ident;}- public short getElementWidth( ) {+ public short getElementWidth() {return elementWidth;}- public int getSize( ) {+ public int getSize() {return size;}- public byte [] getData( ) {+ public byte[] getData() {return data;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "filled_array_data_payload_" + elementWidth + "_" + size, 0 );- structure.add( WORD, "ident", null );- structure.add( WORD, "element_width", null );- structure.add( DWORD, "size", null );- structure.add( new ArrayDataType( BYTE, size * elementWidth, BYTE.getLength( ) ), "data", null );- structure.setCategoryPath( new CategoryPath( "/dex/filled_array_data_payload" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure =+ new StructureDataType("filled_array_data_payload_" + elementWidth + "_" + size, 0);+ structure.add(WORD, "ident", null);+ structure.add(WORD, "element_width", null);+ structure.add(DWORD, "size", null);+ structure.add(new ArrayDataType(BYTE, size * elementWidth, BYTE.getLength()), "data", null);+ structure.setCategoryPath(new CategoryPath("/dex/filled_array_data_payload"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItem.javaindex 027ddc7d3d..eed074b825 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItem.java@@ -29,33 +29,33 @@ public class MapItem implements StructConverter {private int size;private int offset;- public MapItem( BinaryReader reader ) throws IOException {- type = reader.readNextShort( );- unused = reader.readNextShort( );- size = reader.readNextInt( );- offset = reader.readNextInt( );+ public MapItem(BinaryReader reader) throws IOException {+ type = reader.readNextShort();+ unused = reader.readNextShort();+ size = reader.readNextInt();+ offset = reader.readNextInt();}- public short getType( ) {+ public short getType() {return type;}- public short getUnused( ) {+ public short getUnused() {return unused;}- public int getSize( ) {+ public int getSize() {return size;}- public int getOffset( ) {+ public int getOffset() {return offset;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( MapItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(MapItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItemType.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItemType.javanew file mode 100644index 0000000000..bccae7b96e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItemType.java@@ -0,0 +1,61 @@+/* ###+ * 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.android.dex.format;++import java.lang.reflect.Field;++/**+ * Map item type codes.+ */+public final class MapItemType {++ public final static short kDexTypeHeaderItem = 0x0000;+ public final static short kDexTypeStringIdItem = 0x0001;+ public final static short kDexTypeTypeIdItem = 0x0002;+ public final static short kDexTypeProtoIdItem = 0x0003;+ public final static short kDexTypeFieldIdItem = 0x0004;+ public final static short kDexTypeMethodIdItem = 0x0005;+ public final static short kDexTypeClassDefItem = 0x0006;+ public final static short kDexTypeCallSiteIdItem = 0x0007;+ public final static short kDexTypeMethodHandleItem = 0x0008;+ public final static short kDexTypeMapList = 0x1000;+ public final static short kDexTypeTypeList = 0x1001;+ public final static short kDexTypeAnnotationSetRefList = 0x1002;+ public final static short kDexTypeAnnotationSetItem = 0x1003;+ public final static short kDexTypeClassDataItem = 0x2000;+ public final static short kDexTypeCodeItem = 0x2001;+ public final static short kDexTypeStringDataItem = 0x2002;+ public final static short kDexTypeDebugInfoItem = 0x2003;+ public final static short kDexTypeAnnotationItem = 0x2004;+ public final static short kDexTypeEncodedArrayItem = 0x2005;+ public final static short kDexTypeAnnotationsDirectoryItem = 0x2006;+ public final static short kDexTypeHiddenapiClassData = (short) 0xF000;++ public final static String toString(short type) {+ try {+ Field[] fields = MapItemType.class.getDeclaredFields();+ for (Field field : fields) {+ if (field.getShort(null) == type) {+ return field.getName();+ }+ }+ }+ catch (Exception e) {+ // ignore+ }+ return "MapItemType:" + type;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItemTypeCodes.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItemTypeCodes.javaindex 49f95a73ac..62523947c2 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItemTypeCodes.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapItemTypeCodes.java@@ -38,16 +38,16 @@ public final class MapItemTypeCodes {public final static short TYPE_ENCODED_ARRAY_ITEM = 0x2005;// implicit; must parsepublic final static short TYPE_ANNOTATIONS_DIRECTORY_ITEM = 0x2006;// implicit; must parse- public final static String toString( short type ) {+ public final static String toString(short type) {try {- Field [] fields = MapItemTypeCodes.class.getDeclaredFields( );- for ( Field field : fields ) {- if ( field.getShort( null ) == type ) {- return field.getName( );+ Field[] fields = MapItemTypeCodes.class.getDeclaredFields();+ for (Field field : fields) {+ if (field.getShort(null) == type) {+ return field.getName();}}}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return "Type:" + type;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapList.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapList.javaindex 9abc11bf6d..7f945c474c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapList.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MapList.java@@ -26,32 +26,32 @@ import java.util.*;public class MapList implements StructConverter {private int size;- private List< MapItem > items = new ArrayList< MapItem >( );+ private List<MapItem> items = new ArrayList<MapItem>();- public MapList( BinaryReader reader ) throws IOException {- size = reader.readNextInt( );- for ( int i = 0 ; i < size ; ++i ) {- items.add( new MapItem( reader ) );+ public MapList(BinaryReader reader) throws IOException {+ size = reader.readNextInt();+ for (int i = 0; i < size; ++i) {+ items.add(new MapItem(reader));}}- public int getSize( ) {+ public int getSize() {return size;}- public List< MapItem > getItems( ) {- return Collections.unmodifiableList( items );+ public List<MapItem> getItems() {+ return Collections.unmodifiableList(items);}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "MapList_" + size, 0 );- structure.add( DWORD, "size", null );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("MapList_" + size, 0);+ structure.add(DWORD, "size", null);int index = 0;- for ( MapItem item : items ) {- structure.add( item.toDataType( ), "item_" + ( index++ ), null );+ for (MapItem item : items) {+ structure.add(item.toDataType(), "item_" + (index++), null);}- structure.setCategoryPath( new CategoryPath( "/dex" ) );+ structure.setCategoryPath(new CategoryPath("/dex"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodAnnotation.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodAnnotationsItem.javasimilarity index 51%rename from Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodAnnotation.javarename to Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodAnnotationsItem.javaindex 2679e34dc2..eed9c6e882 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodAnnotation.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodAnnotationsItem.java@@ -16,50 +16,56 @@package ghidra.file.formats.android.dex.format;import ghidra.app.util.bin.*;+import ghidra.file.formats.android.dex.util.DexUtil;import ghidra.program.model.data.*;import ghidra.util.exception.DuplicateNameException;import java.io.IOException;-public class MethodAnnotation implements StructConverter {+/**+ *+ * https://android.googlesource.com/platform/art/+/master/libdexfile/dex/dex_file_structs.h+ *+ */+public class MethodAnnotationsItem implements StructConverter {private int methodIndex;private int annotationsOffset;private AnnotationSetItem _annotationSetItem;- public MethodAnnotation( BinaryReader reader ) throws IOException {- methodIndex = reader.readNextInt( );- annotationsOffset = reader.readNextInt( );+ public MethodAnnotationsItem(BinaryReader reader, DexHeader dexHeader) throws IOException {+ methodIndex = reader.readNextInt();+ annotationsOffset = reader.readNextInt();- if ( annotationsOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (annotationsOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( annotationsOffset );- _annotationSetItem = new AnnotationSetItem( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(annotationsOffset, dexHeader));+ _annotationSetItem = new AnnotationSetItem(reader, dexHeader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}- public int getMethodIndex( ) {+ public int getMethodIndex() {return methodIndex;}- public int getAnnotationsOffset( ) {+ public int getAnnotationsOffset() {return annotationsOffset;}- public AnnotationSetItem getAnnotationSetItem( ) {+ public AnnotationSetItem getAnnotationSetItem() {return _annotationSetItem;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( MethodAnnotation.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(MethodAnnotationsItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodHandleType.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodHandleType.javanew file mode 100644index 0000000000..300aff79b0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodHandleType.java@@ -0,0 +1,60 @@+/* ###+ * 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.android.dex.format;++import java.lang.reflect.Field;++public final class MethodHandleType {++ /** a setter for a given static field. */+ public final static short kStaticPut = 0x0000;+ /** a getter for a given static field. */+ public final static short kStaticGet = 0x0001;+ /** a setter for a given instance field. */+ public final static short kInstancePut = 0x0002;+ /** a getter for a given instance field. */+ public final static short kInstanceGet = 0x0003;+ /** an invoker for a given static method. */+ public final static short kInvokeStatic = 0x0004;+ /**+ * invoke_instance : an invoker for a given instance method.+ * This can be any non-static method on any class (or interface)+ * except for ?<init>?.+ */+ public final static short kInvokeInstance = 0x0005;+ /** an invoker for a given constructor. */+ public final static short kInvokeConstructor = 0x0006;+ /** an invoker for a direct (special) method. */+ public final static short kInvokeDirect = 0x0007;+ /** an invoker for an interface method. */+ public final static short kInvokeInterface = 0x0008;+ public final static short kLast = kInvokeInterface;++ public final static String toString(short type) {+ try {+ Field[] fields = MethodHandleType.class.getDeclaredFields();+ for (Field field : fields) {+ if (field.getShort(null) == type) {+ return field.getName();+ }+ }+ }+ catch (Exception e) {+ // ignore+ }+ return "MethodHandleType:" + type;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodIDItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodIDItem.javaindex 8bbe0ab214..1243faf390 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodIDItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/MethodIDItem.java@@ -30,33 +30,33 @@ public class MethodIDItem implements StructConverter {private short protoIndex;private int nameIndex;- public MethodIDItem( BinaryReader reader ) throws IOException {- _fileOffset = reader.getPointerIndex( );- classIndex = reader.readNextShort( );- protoIndex = reader.readNextShort( );- nameIndex = reader.readNextInt( );+ public MethodIDItem(BinaryReader reader) throws IOException {+ _fileOffset = reader.getPointerIndex();+ classIndex = reader.readNextShort();+ protoIndex = reader.readNextShort();+ nameIndex = reader.readNextInt();}public long getFileOffset() {return _fileOffset;}- public int getClassIndex( ) {+ public int getClassIndex() {return classIndex;}- public short getProtoIndex( ) {+ public short getProtoIndex() {return protoIndex;}- public int getNameIndex( ) {+ public int getNameIndex() {return nameIndex;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( MethodIDItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(MethodIDItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ModifiedUTF8.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ModifiedUTF8.javaindex e3b62ac92b..c3298a4519 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ModifiedUTF8.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ModifiedUTF8.java@@ -17,36 +17,44 @@ package ghidra.file.formats.android.dex.format;import java.io.*;+/**+ * https://source.android.com/devices/tech/dalvik/dex-format#mutf-8+ * <br>+ * Modified version of:+ * <br>+ * https://android.googlesource.com/platform/libcore/+/7047230/dex/src/main/java/com/android/dex/Mutf8.java+ */public final class ModifiedUTF8 {- public final static String decode( InputStream in, char [] out ) throws UTFDataFormatException, IOException {+ public final static String decode(InputStream in, char[] out)+ throws UTFDataFormatException, IOException {int s = 0;- while ( true ) {- char a = ( char ) ( in.read( ) & 0xff );- if ( a == 0 ) {- return new String( out, 0, s );+ while (true) {+ char a = (char) (in.read() & 0xff);+ if (a == 0) {+ return new String(out, 0, s);}- out[ s ] = a;- if ( a < '\u0080' ) {+ out[s] = a;+ if (a < '\u0080') {s++;}- else if ( ( a & 0xe0 ) == 0xc0 ) {- int b = in.read( ) & 0xff;- if ( ( b & 0xC0 ) != 0x80 ) {- throw new UTFDataFormatException( "bad second byte" );+ else if ((a & 0xe0) == 0xc0) {+ int b = in.read() & 0xff;+ if ((b & 0xC0) != 0x80) {+ throw new UTFDataFormatException("bad second byte");}- out[ s++ ] = ( char ) ( ( ( a & 0x1F ) << 6 ) | ( b & 0x3F ) );+ out[s++] = (char) (((a & 0x1F) << 6) | (b & 0x3F));}- else if ( ( a & 0xf0 ) == 0xe0 ) {- int b = in.read( ) & 0xff;- int c = in.read( ) & 0xff;- if ( ( ( b & 0xC0 ) != 0x80 ) || ( ( c & 0xC0 ) != 0x80 ) ) {- throw new UTFDataFormatException( "bad second or third byte" );+ else if ((a & 0xf0) == 0xe0) {+ int b = in.read() & 0xff;+ int c = in.read() & 0xff;+ if (((b & 0xC0) != 0x80) || ((c & 0xC0) != 0x80)) {+ throw new UTFDataFormatException("bad second or third byte");}- out[ s++ ] = ( char ) ( ( ( a & 0x0F ) << 12 ) | ( ( b & 0x3F ) << 6 ) | ( c & 0x3F ) );+ out[s++] = (char) (((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F));}else {- throw new UTFDataFormatException( "bad byte" );+ throw new UTFDataFormatException("bad byte");}}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/Modifiers.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/Modifiers.javanew file mode 100644index 0000000000..fd3b062ccd--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/Modifiers.java@@ -0,0 +1,25 @@+/* ###+ * 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.android.dex.format;++/**+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/libdexfile/dex/modifiers.h+ *+ */+public final class Modifiers {+//TODO+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PackedSwitchPayload.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PackedSwitchPayload.javaindex 9ead9c830c..1be36c4379 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PackedSwitchPayload.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PackedSwitchPayload.java@@ -29,39 +29,39 @@ public class PackedSwitchPayload implements StructConverter {private short ident;private short size;private int firstKey;- private int [] targets;+ private int[] targets;- public PackedSwitchPayload( BinaryReader reader ) throws IOException {- ident = reader.readNextShort( );- size = reader.readNextShort( );- firstKey = reader.readNextInt( );- targets = reader.readNextIntArray( size & 0xffff );+ public PackedSwitchPayload(BinaryReader reader) throws IOException {+ ident = reader.readNextShort();+ size = reader.readNextShort();+ firstKey = reader.readNextInt();+ targets = reader.readNextIntArray(size & 0xffff);}- public short getIdent( ) {+ public short getIdent() {return ident;}- public short getSize( ) {+ public short getSize() {return size;}- public int getFirstKey( ) {+ public int getFirstKey() {return firstKey;}- public int [] getTargets( ) {+ public int[] getTargets() {return targets;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "packed_switch_payload_" + size, 0 );- structure.add( WORD, "ident", null );- structure.add( WORD, "size", null );- structure.add( DWORD, "first_key", null );- structure.add( new ArrayDataType( DWORD, size & 0xffff, DWORD.getLength( ) ), "targets", null );- structure.setCategoryPath( new CategoryPath( "/dex/packed_switch_payload" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("packed_switch_payload_" + size, 0);+ structure.add(WORD, "ident", null);+ structure.add(WORD, "size", null);+ structure.add(DWORD, "first_key", null);+ structure.add(new ArrayDataType(DWORD, size & 0xffff, DWORD.getLength()), "targets", null);+ structure.setCategoryPath(new CategoryPath("/dex/packed_switch_payload"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ParameterAnnotation.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ParameterAnnotationsItem.javasimilarity index 63%rename from Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ParameterAnnotation.javarename to Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ParameterAnnotationsItem.javaindex 1560c7b897..41c08c1847 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ParameterAnnotation.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ParameterAnnotationsItem.java@@ -21,45 +21,45 @@ import ghidra.util.exception.DuplicateNameException;import java.io.IOException;-public class ParameterAnnotation implements StructConverter {+public class ParameterAnnotationsItem implements StructConverter {private int methodIndex;private int annotationsOffset;private AnnotationSetReferenceList _annotationSetReferenceList;- public ParameterAnnotation( BinaryReader reader ) throws IOException {- methodIndex = reader.readNextInt( );- annotationsOffset = reader.readNextInt( );+ public ParameterAnnotationsItem(BinaryReader reader) throws IOException {+ methodIndex = reader.readNextInt();+ annotationsOffset = reader.readNextInt();- if ( annotationsOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (annotationsOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( annotationsOffset );- _annotationSetReferenceList = new AnnotationSetReferenceList( reader );+ reader.setPointerIndex(annotationsOffset);+ _annotationSetReferenceList = new AnnotationSetReferenceList(reader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}- public int getMethodIndex( ) {+ public int getMethodIndex() {return methodIndex;}- public int getAnnotationsOffset( ) {+ public int getAnnotationsOffset() {return annotationsOffset;}- public AnnotationSetReferenceList getAnnotationSetReferenceList( ) {+ public AnnotationSetReferenceList getAnnotationSetReferenceList() {return _annotationSetReferenceList;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( ParameterAnnotation.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(ParameterAnnotationsItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PrototypesIDItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PrototypesIDItem.javaindex d10665ac73..51466b25c5 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PrototypesIDItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/PrototypesIDItem.java@@ -15,12 +15,16 @@*/package ghidra.file.formats.android.dex.format;-import ghidra.app.util.bin.*;-import ghidra.program.model.data.*;-import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;+public class PrototypesIDItem implements StructConverter {private int shortyIndex;@@ -28,43 +32,46 @@ public class PrototypesIDItem implements StructConverter {private int parametersOffset;private TypeList _parameters;- public PrototypesIDItem( BinaryReader reader ) throws IOException {- shortyIndex = reader.readNextInt( );- returnTypeIndex = reader.readNextInt( );- parametersOffset = reader.readNextInt( );+ public PrototypesIDItem(BinaryReader reader, DexHeader dexHeader) throws IOException {+ shortyIndex = reader.readNextInt();+ returnTypeIndex = reader.readNextInt();+ parametersOffset = reader.readNextInt();- if ( parametersOffset > 0 ) {- long oldIndex = reader.getPointerIndex( );+ if (parametersOffset > 0) {+ long oldIndex = reader.getPointerIndex();try {- reader.setPointerIndex( parametersOffset );- _parameters = new TypeList( reader );+ reader.setPointerIndex(DexUtil.adjustOffset(parametersOffset, dexHeader));+ _parameters = new TypeList(reader);}finally {- reader.setPointerIndex( oldIndex );+ reader.setPointerIndex(oldIndex);}}}- public int getShortyIndex( ) {+ public int getShortyIndex() {return shortyIndex;}- public int getReturnTypeIndex( ) {+ public int getReturnTypeIndex() {return returnTypeIndex;}- public int getParametersOffset( ) {+ /**+ * NOTE: For CDEX files, this value is relative to DataOffset in DexHeader+ */+ public int getParametersOffset() {return parametersOffset;}- public TypeList getParameters( ) {+ public TypeList getParameters() {return _parameters;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( PrototypesIDItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(PrototypesIDItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/SparseSwitchPayload.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/SparseSwitchPayload.javaindex c97fabac32..583c602fee 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/SparseSwitchPayload.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/SparseSwitchPayload.java@@ -28,40 +28,40 @@ public class SparseSwitchPayload implements StructConverter {private short ident;private short size;- private int [] keys;- private int [] targets;+ private int[] keys;+ private int[] targets;- public SparseSwitchPayload( BinaryReader reader ) throws IOException {- ident = reader.readNextShort( );- size = reader.readNextShort( );- keys = reader.readNextIntArray( size & 0xffff );- targets = reader.readNextIntArray( size & 0xffff );+ public SparseSwitchPayload(BinaryReader reader) throws IOException {+ ident = reader.readNextShort();+ size = reader.readNextShort();+ keys = reader.readNextIntArray(size & 0xffff);+ targets = reader.readNextIntArray(size & 0xffff);}- public short getIdent( ) {+ public short getIdent() {return ident;}- public short getSize( ) {+ public short getSize() {return size;}- public int [] getKeys( ) {+ public int[] getKeys() {return keys;}- public int [] getTargets( ) {+ public int[] getTargets() {return targets;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "sparse_switch_payload_" + size, 0 );- structure.add( WORD, "ident", null );- structure.add( WORD, "size", null );- structure.add( new ArrayDataType( DWORD, size & 0xffff, DWORD.getLength( ) ), "keys", null );- structure.add( new ArrayDataType( DWORD, size & 0xffff, DWORD.getLength( ) ), "targets", null );- structure.setCategoryPath( new CategoryPath( "/dex/sparse_switch_payload" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("sparse_switch_payload_" + size, 0);+ structure.add(WORD, "ident", null);+ structure.add(WORD, "size", null);+ structure.add(new ArrayDataType(DWORD, size & 0xffff, DWORD.getLength()), "keys", null);+ structure.add(new ArrayDataType(DWORD, size & 0xffff, DWORD.getLength()), "targets", null);+ structure.setCategoryPath(new CategoryPath("/dex/sparse_switch_payload"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringDataItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringDataItem.javaindex 867182230f..2307ce20f9 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringDataItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringDataItem.java@@ -21,9 +21,17 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.dwarf4.LEB128;-import ghidra.program.model.data.*;+import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.program.model.data.ArrayDataType;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.program.model.data.Structure;+import ghidra.program.model.data.StructureDataType;import ghidra.util.exception.DuplicateNameException;+/**+ * https://source.android.com/devices/tech/dalvik/dex-format#string-data-item+ */public class StringDataItem implements StructConverter {private static final int MAX_STRING_LEN = 0x200000; // 2Mb'ish@@ -32,8 +40,11 @@ public class StringDataItem implements StructConverter {private int actualLength;private String string;- public StringDataItem(StringIDItem stringItem, BinaryReader reader) throws IOException {- reader = reader.clone(stringItem.getStringDataOffset());+ public StringDataItem(StringIDItem stringItem, BinaryReader reader, DexHeader dexHeader)+ throws IOException {++ reader = reader.clone(DexUtil.adjustOffset(stringItem.getStringDataOffset(), dexHeader));+LEB128 leb128 = LEB128.readUnsignedValue(reader);stringLength = leb128.asUInt32();lebLength = leb128.getLength();@@ -49,16 +60,24 @@ public class StringDataItem implements StructConverter {string = ModifiedUTF8.decode(in, out);}+ /**+ * Only used for invalid string conditions.+ * @param string the invalid string.+ */+ StringDataItem(String string) {+ this.string = string;+ }+public String getString() {return string;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "string_data_item_" + actualLength, 0 );- structure.add( new ArrayDataType( BYTE, lebLength, BYTE.getLength( ) ), "utf16_size", null );- structure.add( UTF8, actualLength, "data", null );- structure.setCategoryPath( new CategoryPath( "/dex/string_data_item" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("string_data_item_" + actualLength, 0);+ structure.add(new ArrayDataType(BYTE, lebLength, BYTE.getLength()), "utf16_size", null);+ structure.add(UTF8, actualLength, "data", null);+ structure.setCategoryPath(new CategoryPath("/dex/string_data_item"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringIDItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringIDItem.javaindex 6a20c90f1c..500fc85cd6 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringIDItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/StringIDItem.java@@ -15,35 +15,51 @@*/package ghidra.file.formats.android.dex.format;-import ghidra.app.util.bin.*;-import ghidra.program.model.data.*;-import ghidra.util.exception.DuplicateNameException;-import java.io.IOException;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://source.android.com/devices/tech/dalvik/dex-format#string-item+ */public class StringIDItem implements StructConverter {private int stringDataOffset;private StringDataItem _stringDataItem;- public StringIDItem( BinaryReader reader ) throws IOException {- stringDataOffset = reader.readNextInt( );-- _stringDataItem = new StringDataItem( this, reader );+ public StringIDItem(BinaryReader reader, DexHeader dexHeader) throws IOException {+ stringDataOffset = reader.readNextInt();+ try {+ _stringDataItem = new StringDataItem(this, reader, dexHeader);+ }+ catch (Exception e) {+ //ignore+ _stringDataItem =+ new StringDataItem("Invalid_String_0x" + Integer.toHexString(stringDataOffset));+ }}- public int getStringDataOffset( ) {+ /**+ * NOTE: For CDEX files, this value is relative to DataOffset in DexHeader+ * @return the string data offset+ */+ public int getStringDataOffset() {return stringDataOffset;}- public StringDataItem getStringDataItem( ) {+ public StringDataItem getStringDataItem() {return _stringDataItem;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( StringIDItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(StringIDItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TryItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TryItem.javaindex 722500e305..261efc99e5 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TryItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TryItem.java@@ -32,10 +32,10 @@ public class TryItem implements StructConverter {private short instructionCount;private short handlerOffset;- TryItem( BinaryReader reader ) throws IOException {- startAddress = reader.readNextInt( );- instructionCount = reader.readNextShort( );- handlerOffset = reader.readNextShort( );+ TryItem(BinaryReader reader) throws IOException {+ startAddress = reader.readNextInt();+ instructionCount = reader.readNextShort();+ handlerOffset = reader.readNextShort();}/**@@ -44,7 +44,7 @@ public class TryItem implements StructConverter {* The address is a count of 16-bit code units to the start of the first covered instruction.* </pre>*/- public int getStartAddress( ) {+ public int getStartAddress() {return startAddress;}@@ -54,7 +54,7 @@ public class TryItem implements StructConverter {* The last code unit covered (inclusive) is start_addr + insn_count - 1.* </pre>*/- public short getInstructionCount( ) {+ public short getInstructionCount() {return instructionCount;}@@ -65,14 +65,14 @@ public class TryItem implements StructConverter {* This must be an offset to the start of an encoded_catch_handler.* </pre>*/- public short getHandlerOffset( ) {+ public short getHandlerOffset() {return handlerOffset;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( TryItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(TryItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeIDItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeIDItem.javaindex d05c71ad88..34e9a34134 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeIDItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeIDItem.java@@ -31,18 +31,18 @@ public class TypeIDItem implements StructConverter {private int descriptorIndex;- public TypeIDItem( BinaryReader reader ) throws IOException {- descriptorIndex = reader.readNextInt( );+ public TypeIDItem(BinaryReader reader) throws IOException {+ descriptorIndex = reader.readNextInt();}- public int getDescriptorIndex( ) {+ public int getDescriptorIndex() {return descriptorIndex;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( TypeIDItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(TypeIDItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeItem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeItem.javaindex 584bb384af..34f4a50eb3 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeItem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeItem.java@@ -26,18 +26,18 @@ public class TypeItem implements StructConverter {private short typeIndex;- public TypeItem( BinaryReader reader ) throws IOException {- typeIndex = reader.readNextShort( );+ public TypeItem(BinaryReader reader) throws IOException {+ typeIndex = reader.readNextShort();}- public short getType( ) {+ public short getType() {return typeIndex;}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- DataType dataType = StructConverterUtil.toDataType( TypeItem.class );- dataType.setCategoryPath( new CategoryPath( "/dex" ) );+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(TypeItem.class);+ dataType.setCategoryPath(new CategoryPath("/dex"));return dataType;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeList.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeList.javaindex b389abc82e..812febe836 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeList.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/TypeList.java@@ -26,38 +26,38 @@ import java.util.*;public class TypeList implements StructConverter {private int size;- private List< TypeItem > items = new ArrayList< TypeItem >( );+ private List<TypeItem> items = new ArrayList<TypeItem>();- public TypeList( BinaryReader reader ) throws IOException {- size = reader.readNextInt( );- for ( int i = 0 ; i < size ; ++i ) {- items.add( new TypeItem( reader ) );+ public TypeList(BinaryReader reader) throws IOException {+ size = reader.readNextInt();+ for (int i = 0; i < size; ++i) {+ items.add(new TypeItem(reader));}}/*** Size of the list, in entries*/- public int getSize( ) {+ public int getSize() {return size;}/*** Elements of the list*/- public List< TypeItem > getItems( ) {- return Collections.unmodifiableList( items );+ public List<TypeItem> getItems() {+ return Collections.unmodifiableList(items);}@Override- public DataType toDataType( ) throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "type_list" + size, 0 );- structure.add( DWORD, "size", null );+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = new StructureDataType("type_list" + size, 0);+ structure.add(DWORD, "size", null);int index = 0;- for ( TypeItem item : items ) {- structure.add( item.toDataType( ), "item_" + ( index++ ), null );+ for (TypeItem item : items) {+ structure.add(item.toDataType(), "item_" + (index++), null);}- structure.setCategoryPath( new CategoryPath( "/dex" ) );+ structure.setCategoryPath(new CategoryPath("/dex"));return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ValueFormats.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ValueFormats.javaindex cafbdf648b..43f949b4c6 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ValueFormats.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/format/ValueFormats.java@@ -43,16 +43,16 @@ public final class ValueFormats {public final static byte VALUE_NULL = 0x1e;// (none; must be 0) (none) null reference valuepublic final static byte VALUE_BOOLEAN = 0x1f;// boolean (0...1) (none) one-bit value; 0 for false and 1 for true. The bit is represented in the value_arg.- public final static String toString( byte value ) {+ public final static String toString(byte value) {try {- Field [ ] fields = ValueFormats.class.getDeclaredFields( );- for ( Field field : fields ) {- if ( field.getByte( null ) == value ) {- return field.getName( );+ Field[] fields = ValueFormats.class.getDeclaredFields();+ for (Field field : fields) {+ if (field.getByte(null) == value) {+ return field.getName();}}}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return "Value:" + value;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/util/DexUtil.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/util/DexUtil.javaindex 2b7cf56f22..cdb5ff154c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/util/DexUtil.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/dex/util/DexUtil.java@@ -27,11 +27,14 @@ import ghidra.util.exception.InvalidInputException;public final class DexUtil {- public final static long METHOD_ADDRESS = 0x50000000;+ public final static long METHOD_ADDRESS = 0x50000000L;- public final static long LOOKUP_ADDRESS = 0xE0000000;+ public final static long LOOKUP_ADDRESS = 0xE0000000L;- public final static long MAX_METHOD_LENGTH = (long) Math.pow(2, 16) * 4;+ /**+ * Max size possible 0x10000 (2^16) methods * pointer size+ */+ public final static long MAX_METHOD_LENGTH = 0x80000;public final static String CLASSDEF_NAME = "__classdef__";@@ -39,12 +42,26 @@ public final class DexUtil {public final static String HANDLE_PATH = "/handles/";+ /**+ * Converts the method index into the address where the method is stored in memory+ * @param program the program+ * @param methodIndex the method index+ * @return address where method of index is stored+ */public static Address toLookupAddress(Program program, int methodIndex) {+ int pointerSize = program.getLanguage().getDefaultSpace().getPointerSize();AddressFactory addressFactory = program.getAddressFactory();AddressSpace defaultAddressSpace = addressFactory.getDefaultAddressSpace();- return defaultAddressSpace.getAddress(DexUtil.LOOKUP_ADDRESS + (methodIndex * 4));+ return defaultAddressSpace.getAddress(DexUtil.LOOKUP_ADDRESS + (methodIndex * pointerSize));}+ /**+ * Returns the namespace with the given name.+ * If namespace does not exist, then it gets created first.+ * @param program the program containing the namespace+ * @param name the namespace name+ * @return the namespace object+ */public static Namespace getOrCreateNameSpace(Program program, String name) {SymbolTable symbolTable = program.getSymbolTable();Namespace parent = program.getGlobalNamespace();@@ -61,12 +78,27 @@ public final class DexUtil {}}+ /**+ * Converts the mangled namespace into a namespace hierarchy,+ * @param program the program containing the namespaces+ * @param className the mangled classname+ * @return the child namespace+ * @throws InvalidInputException if an invalid character exists in the className+ */public static Namespace createNameSpaceFromMangledClassName(Program program, String className)throws InvalidInputException {Namespace namespace = program.getGlobalNamespace();return createNameSpaceFromMangledClassName(program, namespace, className);}+ /**+ * Converts the mangled namespace into a namespace hierarchy,+ * @param program the program containing the namespaces+ * @param parentNamespace the parent namespace+ * @param className the mangled classname+ * @return the child namespace+ * @throws InvalidInputException if an invalid character exists in the className+ */public static Namespace createNameSpaceFromMangledClassName(Program program,Namespace parentNamespace, String className) throws InvalidInputException {SymbolTable symbolTable = program.getSymbolTable();@@ -101,10 +133,22 @@ public final class DexUtil {return parentNamespace;}+ /**+ * Converts the typeIndex into the Type String.+ * @param header the DEX/CDEX header+ * @param typeIndex the type index+ * @return the Type String+ */public static String convertTypeIndexToString(DexHeader header, short typeIndex) {return convertTypeIndexToString(header, typeIndex & 0xffff);}+ /**+ * Converts the typeIndex into the Type String.+ * @param header the DEX/CDEX header+ * @param typeIndex the type index+ * @return the Type String+ */public static String convertTypeIndexToString(DexHeader header, int typeIndex) {if (typeIndex == -1) {//java.lang.Object, no super classreturn "<none>";@@ -113,11 +157,26 @@ public final class DexUtil {return convertToString(header, typeItem.getDescriptorIndex());}+ /**+ * Converts the stringIndex into the actual String.+ * @param header the DEX/CDEX header+ * @param stringIndex the string index+ * @return the actual String+ */public static String convertToString(DexHeader header, int stringIndex) {StringIDItem stringItem = header.getStrings().get(stringIndex);+ if (stringItem == null || stringItem.getStringDataItem() == null) {+ return "INVALID STRING 0x" + Integer.toHexString(stringIndex);+ }return stringItem.getStringDataItem().getString();}+ /**+ * Converts the prototypeIndex into the Prototype object.+ * @param header the DEX/CDEX header+ * @param prototypeIndex the prototype index+ * @return the Prototype object+ */public static String convertPrototypeIndexToString(DexHeader header, short prototypeIndex) {PrototypesIDItem prototype = header.getPrototypes().get(prototypeIndex & 0xffff);StringBuilder builder = new StringBuilder();@@ -134,6 +193,12 @@ public final class DexUtil {return builder.toString();}+ /**+ * Converts the string package/class into an array+ * @param prefix the prefix+ * @param classString the class string+ * @return the array of package/class+ */public static String[] convertClassStringToPathArray(String prefix, String classString) {int len = classString.length();if (len == 0) {@@ -148,6 +213,12 @@ public final class DexUtil {return (prefix + classString.substring(1, len - 1)).split("/");}+ /**+ * Converts the data type string into a Ghidra data type+ * @param dtm the data type manager for getting data types.+ * @param dataTypeString the data type string (java encodings)+ * @return the Ghidra datatype+ */public static DataType toDataType(DataTypeManager dtm, String dataTypeString) {if (dataTypeString.length() == 0) {return null;@@ -190,4 +261,32 @@ public final class DexUtil {return null;}}++ /**+ * Adjusts the specified offset relative to the data offset.+ * Some DEX/CDEX files do not start at 0x0.+ * @param offset the offset+ * @param header the DEX/CDEX header+ * @return the offset, adjusted as needed+ */+ public static int adjustOffset(int offset, DexHeader header) {+ if (header.isDataOffsetRelative()) {+ return offset + header.getDataOffset();+ }+ return offset;+ }++ /**+ * Adjusts the specified offset relative to the data offset.+ * Some DEX/CDEX files do not start at 0x0.+ * @param offset the offset+ * @param header the DEX/CDEX header+ * @return the offset, adjusted as needed+ */+ public static long adjustOffset(long offset, DexHeader header) {+ if (header.isDataOffsetRelative()) {+ return offset + Integer.toUnsignedLong(header.getDataOffset());+ }+ return offset;+ }}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK.javanew file mode 100644index 0000000000..78da4b1b8e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK.java@@ -0,0 +1,84 @@+/* ###+ * 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.android.fbpk;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class FBPK implements StructConverter {+ private String magic;+ private int unknown1;+ private String version;+ private int partitionCount;+ private int size;+ private List<FBPK_Partition> partitions = new ArrayList<>();++ public FBPK(BinaryReader reader) throws IOException {+ magic = reader.readNextAsciiString(FBPK_Constants.FBPK.length());+ unknown1 = reader.readNextInt();+ version = reader.readNextAsciiString(FBPK_Constants.VERSION_MAX_LENGTH);+ partitionCount = reader.readNextInt();+ size = reader.readNextInt();++ for (int i = 0; i < partitionCount; ++i) {+ FBPK_Partition partition = new FBPK_Partition(reader);+ partitions.add(partition);+ reader.setPointerIndex(partition.getOffsetToNextPartitionTable());+ }+ }++ public String getMagic() {+ return magic;+ }++ public String getVersion() {+ return version;+ }++ public int getPartitionCount() {+ return partitionCount;+ }++ public int getSize() {+ return size;+ }++ public List<FBPK_Partition> getPartitions() {+ return partitions;+ }++ public int getUnknown1() {+ return unknown1;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(FBPK.class);+ Structure struct = new StructureDataType(className, 0);+ struct.add(STRING, FBPK_Constants.FBPK.length(), "magic", null);+ struct.add(DWORD, "unknown1", null);+ struct.add(STRING, FBPK_Constants.VERSION_MAX_LENGTH, "version", null);+ struct.add(DWORD, "count", null);+ struct.add(DWORD, "size", null);+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Analyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Analyzer.javanew file mode 100644index 0000000000..9fbf122770--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Analyzer.java@@ -0,0 +1,135 @@+/* ###+ * 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.android.fbpk;++import java.util.List;++import ghidra.app.services.AbstractAnalyzer;+import ghidra.app.services.AnalyzerType;+import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSetView;+import ghidra.program.model.data.DataType;+import ghidra.program.model.listing.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++public class FBPK_Analyzer extends AbstractAnalyzer {++ public FBPK_Analyzer() {+ super("Android FBPK Analyzer", "Annotates Android FBPK Files", AnalyzerType.BYTE_ANALYZER);+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return FBPK_Constants.isFBPK(program);+ }++ @Override+ public boolean canAnalyze(Program program) {+ return FBPK_Constants.isFBPK(program);+ }++ @Override+ public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws CancelledException {++ Address headerAddress = program.getMinAddress();+ ByteProvider provider = new MemoryByteProvider(program.getMemory(), headerAddress);+ BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());+ try {+ FBPK header = new FBPK(reader);+ DataType headerDataType = header.toDataType();+ Data headerData = program.getListing().createData(headerAddress, headerDataType);+ if (headerData == null) {+ log.appendMsg("Unable to apply FBPK data, stopping - " + headerAddress);+ return false;+ }++ Address address = headerAddress.add(headerDataType.getLength());++ List<FBPK_Partition> partitions = header.getPartitions();+ for (int i = 0; i < partitions.size(); ++i) {+ FBPK_Partition partition = partitions.get(i);++ DataType partitionDataType = partition.toDataType();+ Data partitionData = program.getListing().createData(address, partitionDataType);+ if (partitionData == null) {+ log.appendMsg("Unable to apply partition data, stopping - " + address);+ return false;+ }+ program.getListing()+ .setComment(address, CodeUnit.PLATE_COMMENT,+ partition.getName() + " - " + i);+ address = address.add(partitionDataType.getLength());++ if (partition.isDirectory()) {+ if (!processFBPT(program, address, partition, monitor, log)) {+ return false;+ }+ }+ else if (partition.isFile()) {+ //unused, but leave as placeholder for future+ }++ address = address.getNewAddress(partition.getOffsetToNextPartitionTable());+ }++ return true;+ }+ catch (Exception e) {+ log.appendException(e);+ }+ return false;+ }++ private boolean processFBPT(Program program, Address address, FBPK_Partition partition,+ TaskMonitor monitor, MessageLog log) throws Exception {++ FBPT fbpt = partition.getFBPT();+ DataType fbptDataType = fbpt.toDataType();+ Data fbptData = program.getListing().createData(address, fbptDataType);+ if (fbptData == null) {+ log.appendMsg("Unable to apply FBPT data, stopping - " + address);+ return false;+ }+ String comment = "FBPT" + "\n" + "Num of entries: " + fbpt.getNEntries();+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);+ address = address.add(fbptDataType.getLength());++ return processFbPtEntries(program, address, fbpt, monitor, log);+ }++ private boolean processFbPtEntries(Program program, Address address, FBPT fbpt,+ TaskMonitor monitor, MessageLog log) throws Exception {+ for (int i = 0; i < fbpt.getEntries().size(); ++i) {+ FBPT_Entry entry = fbpt.getEntries().get(i);+ monitor.checkCanceled();+ DataType entryDataType = entry.toDataType();+ Data entryData = program.getListing().createData(address, entryDataType);+ if (entryData == null) {+ log.appendMsg("Unable to apply FBPT Entry data, stopping - " + address);+ return false;+ }+ program.getListing()+ .setComment(address, CodeUnit.PLATE_COMMENT, entry.getName() + " - " + i);+ address = address.add(entryDataType.getLength());+ }+ return true;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Constants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Constants.javanew file mode 100644index 0000000000..77a90d4bc7--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Constants.java@@ -0,0 +1,46 @@+/* ###+ * 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.android.fbpk;++import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.Memory;++public final class FBPK_Constants {++ public final static String FBPK = "FBPK";+ public final static String FBPT = "FBPT";+ public final static String PARTITION_TABLE = "partition table";+ public final static String LAST_PARTITION_ENTRY = "last_parti";++ public final static int PARTITION_TYPE_DIRECTORY = 0;+ public final static int PARTITION_TYPE_FILE = 1;+ public final static int NAME_MAX_LENGTH = 36;+ public final static int VERSION_MAX_LENGTH = 68;++ public static boolean isFBPK(Program program) {+ try {+ Memory memory = program.getMemory();+ byte[] bytes = new byte[FBPK.length()];+ memory.getBytes(program.getMinAddress(), bytes);+ String magic = new String(bytes).trim();+ return FBPK.equals(magic);+ }+ catch (Exception e) {+ //ignore+ }+ return false;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_FileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_FileSystem.javanew file mode 100644index 0000000000..7b16662dab--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_FileSystem.java@@ -0,0 +1,87 @@+/* ###+ * 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.android.fbpk;++import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.CryptoException;+import ghidra.util.task.TaskMonitor;++@FileSystemInfo(type = "androidbootloaderfbpk", // ([a-z0-9]+ only)+ description = "Android Boot Loader Image (FBPK)", factory = GFileSystemBaseFactory.class)++public class FBPK_FileSystem extends GFileSystemBase {+ private List<GFileImpl> fileList = new ArrayList<>();+ private Map<GFileImpl, FBPK_Partition> map = new HashMap<>();++ public FBPK_FileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ byte[] bytes = provider.readBytes(0, FBPK_Constants.FBPK.length());+ return FBPK_Constants.FBPK.equals(new String(bytes).trim());+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {+ BinaryReader reader = new BinaryReader(provider, true /*might not always be LE*/ );+ FBPK header = new FBPK(reader);+ List<FBPK_Partition> partitions = header.getPartitions();+ for (FBPK_Partition partition : partitions) {+ if (partition.isFile()) {+ GFileImpl file = GFileImpl.fromFilename(this, root, partition.getName(), false,+ partition.getDataSize(), null);+ fileList.add(file);+ map.put(file, partition);+ }+ }+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ return new ArrayList<>(fileList);+ }++ @Override+ public String getInfo(GFile file, TaskMonitor monitor) {+ return null;+ }++ @Override+ protected InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException, CryptoException {++ FBPK_Partition partition = map.get(file);++ return provider.getInputStream(partition.getDataStartOffset());+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Partition.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Partition.javanew file mode 100644index 0000000000..1c142981f1--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Partition.java@@ -0,0 +1,105 @@+/* ###+ * 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.android.fbpk;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class FBPK_Partition implements StructConverter {+ private int type;+ private String name;+ private int dataSize;+ private int unknown1;+ private int offsetToNextPartitionTable;+ private int unknown2;+ private FBPT fbpt;+ private long dataStartOffset;++ public FBPK_Partition(BinaryReader reader) throws IOException {+ type = reader.readNextInt();+ name = reader.readNextAsciiString(FBPK_Constants.NAME_MAX_LENGTH);+ dataSize = reader.readNextInt();+ unknown1 = reader.readNextInt();+ offsetToNextPartitionTable = reader.readNextInt();+ unknown2 = reader.readNextInt();+ if (type == FBPK_Constants.PARTITION_TYPE_DIRECTORY) {+ fbpt = new FBPT(reader);+ }+ else if (type == FBPK_Constants.PARTITION_TYPE_FILE) {+ dataStartOffset = reader.getPointerIndex();+ }+ }++ public int getType() {+ return type;+ }++ public String getName() {+ return name;+ }++ /**+ * Returns the Fast Boot Partition Table+ * @return the Fast Boot Partition Table, could be null if file+ */+ public FBPT getFBPT() {+ return fbpt;+ }++ public long getDataStartOffset() {+ return dataStartOffset;+ }++ public int getDataSize() {+ return dataSize;+ }++ public int getOffsetToNextPartitionTable() {+ return offsetToNextPartitionTable;+ }++ public boolean isDirectory() {+ return getType() == FBPK_Constants.PARTITION_TYPE_DIRECTORY;+ }++ public boolean isFile() {+ return getType() == FBPK_Constants.PARTITION_TYPE_FILE;+ }++ public int getUnknown1() {+ return unknown1;+ }++ public int getUnknown2() {+ return unknown2;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(FBPK_Partition.class);+ Structure struct = new StructureDataType(className, 0);+ struct.add(DWORD, "type", null);+ struct.add(STRING, FBPK_Constants.NAME_MAX_LENGTH, "name", null);+ struct.add(DWORD, "dataSize", null);+ struct.add(DWORD, "unknown1", null);+ struct.add(DWORD, "offsetToNextPartitionTable", null);+ struct.add(DWORD, "unknown2", null);+ return struct;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT.javanew file mode 100644index 0000000000..f993d194ef--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT.java@@ -0,0 +1,173 @@+/* ###+ * 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.android.fbpk;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class FBPT implements StructConverter {+ private String magic;+ private int unknown1;+ private int unknown2;+ private int unknown3;+ private int nEntries;+ private int unknownA;+ private int unknownB;+ private int unknownC;+ private int unknownD;+ private int unknownE;+ private int unknownF;+ private int unknownG;+ private int unknownH;+ private int unknownI;+ private int unknownJ;+ private int unknownK;+ private int unknownL;+ private int unknownM;+ private List<FBPT_Entry> entries = new ArrayList<>();++ public FBPT(BinaryReader reader) throws IOException {+ magic = reader.readNextAsciiString(FBPK_Constants.FBPT.length());+ unknown1 = reader.readNextInt();+ unknown2 = reader.readNextInt();+ unknown3 = reader.readNextInt();+ nEntries = reader.readNextInt();+ unknownA = reader.readNextInt();+ unknownB = reader.readNextInt();+ unknownC = reader.readNextInt();+ unknownD = reader.readNextInt();+ unknownE = reader.readNextInt();+ unknownF = reader.readNextInt();+ unknownG = reader.readNextInt();+ unknownH = reader.readNextInt();+ unknownI = reader.readNextInt();+ unknownJ = reader.readNextInt();+ unknownK = reader.readNextInt();+ unknownL = reader.readNextInt();+ unknownM = reader.readNextInt();++ for (int i = 0; i < nEntries; ++i) {+ entries.add(new FBPT_Entry(reader, i == nEntries - 1));+ }+ }++ public String getMagic() {+ return magic;+ }++ public int getNEntries() {+ return nEntries;+ }++ public List<FBPT_Entry> getEntries() {+ return entries;+ }++ public int getUnknown1() {+ return unknown1;+ }++ public int getUnknown2() {+ return unknown2;+ }++ public int getUnknown3() {+ return unknown3;+ }++ public int getUnknownA() {+ return unknownA;+ }++ public int getUnknownB() {+ return unknownB;+ }++ public int getUnknownC() {+ return unknownC;+ }++ public int getUnknownD() {+ return unknownD;+ }++ public int getUnknownE() {+ return unknownE;+ }++ public int getUnknownF() {+ return unknownF;+ }++ public int getUnknownG() {+ return unknownG;+ }++ public int getUnknownH() {+ return unknownH;+ }++ public int getUnknownI() {+ return unknownI;+ }++ public int getUnknownJ() {+ return unknownJ;+ }++ public int getUnknownK() {+ return unknownK;+ }++ public int getUnknownL() {+ return unknownL;+ }++ public int getUnknownM() {+ return unknownM;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(FBPT.class);+ Structure struct = new StructureDataType(className, 0);+ struct.add(STRING, FBPK_Constants.FBPT.length(), "magic", null);+ struct.add(DWORD, "unknown1", null);+ struct.add(DWORD, "unknown2", null);+ struct.add(DWORD, "unknown3", null);+ struct.add(DWORD, "nEntries", null);+ struct.add(DWORD, "unknownA", null);+ struct.add(DWORD, "unknownB", null);+ struct.add(DWORD, "unknownC", null);+ struct.add(DWORD, "unknownD", null);+ struct.add(DWORD, "unknownE", null);+ struct.add(DWORD, "unknownF", null);+ struct.add(DWORD, "unknownG", null);+ struct.add(DWORD, "unknownH", null);+ struct.add(DWORD, "unknownI", null);+ struct.add(DWORD, "unknownJ", null);+ struct.add(DWORD, "unknownK", null);+ struct.add(DWORD, "unknownL", null);+ struct.add(DWORD, "unknownM", null);+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT_Entry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT_Entry.javanew file mode 100644index 0000000000..14152e2647--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT_Entry.java@@ -0,0 +1,105 @@+/* ###+ * 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.android.fbpk;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.InvalidNameException;+import ghidra.util.exception.DuplicateNameException;++public class FBPT_Entry implements StructConverter {+ private String name;+ private String guid1;+ private String guid2;+ private String padding;+ private int unknown1;+ private int unknown2;+ private int unknown3;+ private boolean isLast;++ public FBPT_Entry(BinaryReader reader, boolean isLast) throws IOException {+ this.isLast = isLast;+ name = reader.readNextAsciiString(FBPK_Constants.NAME_MAX_LENGTH);//not +1+ guid1 = reader.readNextAsciiString(FBPK_Constants.NAME_MAX_LENGTH + 1);+ guid2 = reader.readNextAsciiString(FBPK_Constants.NAME_MAX_LENGTH + 1);+ padding = reader.readNextAsciiString(2);+ if (FBPK_Constants.LAST_PARTITION_ENTRY.equals(name)) {+ return;+ }+ unknown1 = reader.readNextInt();+ if (!isLast) {+ unknown2 = reader.readNextInt();+ unknown3 = reader.readNextInt();+ }+ }++ public String getName() {+ return name;+ }++ public String getGuid1() {+ return guid1;+ }++ public String getGuid2() {+ return guid2;+ }++ public String getPadding() {+ return padding;+ }++ public int getUnknown1() {+ return unknown1;+ }++ public int getUnknown2() {+ return unknown2;+ }++ public int getUnknown3() {+ return unknown3;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(FBPT_Entry.class);+ Structure struct = new StructureDataType(className, 0);+ struct.add(STRING, FBPK_Constants.NAME_MAX_LENGTH, "name", null);+ struct.add(STRING, FBPK_Constants.NAME_MAX_LENGTH + 1, "guid1", null);+ struct.add(STRING, FBPK_Constants.NAME_MAX_LENGTH + 1, "guid2", null);+ struct.add(STRING, 2, "padding", null);+ if (FBPK_Constants.LAST_PARTITION_ENTRY.equals(name) || isLast) {+ try {+ struct.setName(className + "_last");+ }+ catch (InvalidNameException e) {+ //ignore+ }+ }+ else {+ struct.add(DWORD, "unknown1", null);+ if (!isLast) {+ struct.add(DWORD, "unknown2", null);+ struct.add(DWORD, "unknown3", null);+ }+ }+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/lz4/LZ4ArchiveFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/lz4/LZ4ArchiveFileSystem.javanew file mode 100644index 0000000000..fa2be9e52a--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/lz4/LZ4ArchiveFileSystem.java@@ -0,0 +1,140 @@+/* ###+ * 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.android.lz4;++import java.io.ByteArrayInputStream;+import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;++import org.apache.commons.compress.compressors.lz4.BlockLZ4CompressorInputStream;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ *+ * See: https://android.googlesource.com/platform/external/lz4/+/HEAD/doc/lz4_Frame_format.md+ *+ */+@FileSystemInfo(type = "lz4", description = "LZ4 Archive Format", factory = GFileSystemBaseFactory.class)+public class LZ4ArchiveFileSystem extends GFileSystemBase {++ /**+ * LZ4 Magic Number+ */+ public final static int ARCHIVE_MAGIC = 0x184C2102;+ public final static byte[] ARCHIVE_MAGIC_BYTES = { 0x02, 0x21, 0x4c, 0x18 };++ /**+ * Note: Uncompressed chunk size is used in the compressor side+ * (userspace side for compression).+ * It is hardcoded because there is not proper way to extract it+ * from the binary stream which is generated by the preliminary+ * version of LZ4 tool so far.+ */+ public final static int LZ4_DEFAULT_UNCOMPRESSED_CHUNK_SIZE = (8 << 20);++ public final static String NAME = "lz4_decompressed";++ private GFile decompressedLZ4File = null;++ public LZ4ArchiveFileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ byte[] bytes = provider.readBytes(0, ARCHIVE_MAGIC_BYTES.length);+ return Arrays.equals(bytes, ARCHIVE_MAGIC_BYTES);+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CancelledException {+ byte[] decompressedBytes = decompress(monitor);+ decompressedLZ4File =+ GFileImpl.fromFilename(this, root, NAME, false, decompressedBytes.length, null);+ }++ private byte[] decompress(TaskMonitor monitor) throws IOException {+ monitor.setShowProgressValue(true);+ monitor.setMaximum(provider.length());+ monitor.setProgress(0);+ monitor.setMessage("Decompressing LZ4 archive...");++ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ BinaryReader reader = new BinaryReader(provider, true);//always LE+ int magic = reader.readNextInt();+ if (magic != ARCHIVE_MAGIC) {+ throw new IOException("invalid magic");+ }+ try {+ while (reader.getPointerIndex() < reader.length()) {+ monitor.checkCanceled();++ int compressedChunkSize = reader.readNextInt();+ monitor.setMessage("Chunk size: 0x" + Integer.toHexString(compressedChunkSize));+ monitor.incrementProgress(compressedChunkSize);++ byte[] compressedChunk = reader.readNextByteArray(compressedChunkSize);++ try (InputStream compressedStream =+ new BlockLZ4CompressorInputStream(new ByteArrayInputStream(compressedChunk))) {+ while (true) {+ monitor.checkCanceled();+ byte[] bytes = new byte[0x10000];+ int nRead = compressedStream.read(bytes);+ if (nRead == -1) {+ break;+ }+ baos.write(bytes, 0, nRead);+ }+ }+ }+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ return baos.toByteArray();+ }++ @Override+ protected InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException {+ if (file == decompressedLZ4File || file.equals(decompressedLZ4File)) {+ byte[] decompressedBytes = decompress(monitor);+ return new ByteArrayInputStream(decompressedBytes);+ }+ return null;+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ return (directory == null || directory.equals(root)) && (decompressedLZ4File != null)+ ? Arrays.asList(decompressedLZ4File)+ : Collections.emptyList();+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/lz4/LZ4FrameFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/lz4/LZ4FrameFileSystem.javanew file mode 100644index 0000000000..e0cdfcebcd--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/lz4/LZ4FrameFileSystem.java@@ -0,0 +1,111 @@+/* ###+ * 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.android.lz4;++import java.io.ByteArrayInputStream;+import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;++import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorInputStream;++import ghidra.app.util.bin.ByteProvider;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ *+ * See: https://android.googlesource.com/platform/external/lz4/+/HEAD/doc/lz4_Frame_format.md+ *+ */+@FileSystemInfo(type = "lz4frame", description = "LZ4 Frame Format", factory = GFileSystemBaseFactory.class)+public class LZ4FrameFileSystem extends GFileSystemBase {++ /** LZ4 Magic Number */+ public final static int LZ4F_MAGIC = 0x184D2204;+ public final static byte[] LZ4F_MAGIC_BYTES = { 0x04, 0x22, 0x4d, 0x18 };++ public final static String NAME = "lz4f_decompressed";++ private GFile decompressedLZ4FFile = null;++ public LZ4FrameFileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ byte[] bytes = provider.readBytes(0, LZ4F_MAGIC_BYTES.length);+ return Arrays.equals(bytes, LZ4F_MAGIC_BYTES);+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CancelledException {+ byte[] decompressedBytes = decompress(monitor);+ decompressedLZ4FFile =+ GFileImpl.fromFilename(this, root, NAME, false, decompressedBytes.length, null);+ }++ private byte[] decompress(TaskMonitor monitor) throws IOException {+ monitor.setShowProgressValue(true);+ monitor.setMaximum(100000);+ monitor.setProgress(0);+ monitor.setMessage("Decompressing LZ4 Frame...");+ FramedLZ4CompressorInputStream lz4 =+ new FramedLZ4CompressorInputStream(provider.getInputStream(0));+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ int chunk = 0;+ while (!monitor.isCancelled()) {+ byte[] bytes = new byte[0x1000];+ int nRead = lz4.read(bytes);+ if (nRead <= 0) {+ break;+ }+ ++chunk;+ monitor.incrementProgress(1);+ monitor.setMessage(+ "Decompressing LZ4F ... " + chunk + " ... 0x" + Integer.toHexString(nRead));+ baos.write(bytes, 0, nRead);+ }+ lz4.close();+ return baos.toByteArray();+ }++ @Override+ protected InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException {+ if (file == decompressedLZ4FFile || file.equals(decompressedLZ4FFile)) {+ byte[] decompressedBytes = decompress(monitor);+ return new ByteArrayInputStream(decompressedBytes);+ }+ return null;+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ return (directory == null || directory.equals(root)) && (decompressedLZ4FFile != null)+ ? Arrays.asList(decompressedLZ4FFile)+ : Collections.emptyList();+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/IndexBssMappingEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/IndexBssMappingEntry.javanew file mode 100644index 0000000000..f3dd1af17a--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/IndexBssMappingEntry.java@@ -0,0 +1,58 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * See https://android.googlesource.com/platform/art/+/master/runtime/index_bss_mapping.h+ *+ */+public class IndexBssMappingEntry implements StructConverter {++ private int index_and_mask;+ private int bss_offset;++ IndexBssMappingEntry(BinaryReader reader) throws IOException {+ index_and_mask = reader.readNextInt();+ bss_offset = reader.readNextInt();+ }++ public int getIndexAndMask() {+ return index_and_mask;+ }++ public int getIndex(int index_bits) {+ return index_and_mask & IndexBssUtilities.indexMask(index_bits);+ }++ public int getMask(int index_bits) {+ return index_and_mask >> index_bits;+ }++ public int getBssOffset() {+ return bss_offset;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(IndexBssMappingEntry.class);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/IndexBssUtilities.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/IndexBssUtilities.javanew file mode 100644index 0000000000..a208b93229--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/IndexBssUtilities.java@@ -0,0 +1,38 @@+/* ###+ * 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.android.oat;++/**+ * https://android.googlesource.com/platform/art/+/master/runtime/index_bss_mapping.h+ *+ */+public final class IndexBssUtilities {++ public final static int indexMask(int index_bits) {+ int kAllOnes = -1;+ // Handle `index_bits == 32u` explicitly; shifting uint32_t left by 32 is undefined behavior.+ return (index_bits == 32) ? kAllOnes : ~(kAllOnes << index_bits);+ }++ public final static int intIndexBits(int number_of_indexes) {+ return minimumBitsToStore(number_of_indexes - 1);+ }++ private static int minimumBitsToStore(int value) {+ return 0;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/MethodBssMappingEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/MethodBssMappingEntry.javanew file mode 100644index 0000000000..838752f423--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/MethodBssMappingEntry.java@@ -0,0 +1,62 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * See https://android.googlesource.com/platform/art/+/oreo-m2-release/runtime/method_bss_mapping.h+ * <br>+ * MethodBssMappingEntry describes a mapping of up to 17 method indexes to their offsets+ * in the .bss. The highest index and its associated .bss offset are stored in plain form+ * as `method_index` and `bss_offset`, respectively, while the additional indexes can be+ * stored in compressed form if their associated .bss entries are consecutive and in the+ * method index order. Each of the 16 bits of the `index_mask` corresponds to one of the+ * previous 16 method indexes and indicates whether there is a .bss entry for that index.+ */+public class MethodBssMappingEntry implements StructConverter {++ private short method_index;+ private short index_mask;+ private int bss_offset;++ MethodBssMappingEntry(BinaryReader reader) throws IOException {+ method_index = reader.readNextShort();+ index_mask = reader.readNextShort();+ bss_offset = reader.readNextInt();+ }++ public short getMethodIndex() {+ return method_index;+ }++ public short getIndexMask() {+ return index_mask;+ }++ public int getBssOffset() {+ return bss_offset;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(MethodBssMappingEntry.class);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClass.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClass.javanew file mode 100644index 0000000000..93ee482513--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClass.java@@ -0,0 +1,166 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.file.formats.android.dex.format.ClassDataItem;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ * https://android.googlesource.com/platform/art/+/kitkat-release/runtime/oat_file.h#144+ *+ * https://android.googlesource.com/platform/art/+/lollipop-release/runtime/oat_file.h#205+ *+ * https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/oat_file.h#200+ *+ */+public class OatClass implements StructConverter {++ private String oatVersion;++ private short status;+ private short type;+ private int bitmapSize;+ private byte[] bitmap = new byte[0];+ private List<OatMethodOffsets> methodOffsets = new ArrayList<OatMethodOffsets>();++ OatClass(BinaryReader reader, ClassDataItem classDataItem, String oatVersion)+ throws IOException {+ this.oatVersion = oatVersion;++ status = reader.readNextShort();+ type = reader.readNextShort();++ int methodOffsetsCount = 0;++ if (type == OatClassType.kOatClassSomeCompiled.ordinal()) {+ bitmapSize = reader.readNextInt();+ bitmap = reader.readNextByteArray(bitmapSize);++ //For every set bit, there will be a corresponding entry in method_offsets.;+ for (int i = 0; i < bitmapSize; ++i) {+ methodOffsetsCount += Integer.bitCount(Byte.toUnsignedInt(bitmap[i]));+ }+ }+ else if (type == OatClassType.kOatClassAllCompiled.ordinal()) {+ methodOffsetsCount =+ classDataItem.getDirectMethodsSize() + classDataItem.getVirtualMethodsSize();+ }++ for (int i = 0; i < methodOffsetsCount; ++i) {+ methodOffsets.add(OatMethodOffsetsFactory.getOatMethodOffsets(reader, oatVersion));+ }+ }++ /**+ * State of class during compilation+ * @return the class status+ */+ public short getStatus() {+ return status;+ }++ /**+ * Returns the class type+ * @return the OAT class type+ * @see OatClassType+ */+ public short getType() {+ return type;+ }++ /**+ * Size of compiled methods bitmap (present only when type = 1)+ * @return size of methods bitmap+ */+ public int getBitmapSize() {+ return bitmapSize;+ }++ /**+ * Compiled methods bitmap (present only when type = 1)+ * @return methods bitmap+ */+ public byte[] getBitmap() {+ return bitmap;+ }++ /**+ * Returns true if this method index is declared native in the bitmap+ * @param methodIndex the method index+ * @return true if this method index is declared native in the bitmap+ */+ public boolean isMethodNative(int methodIndex) {+ int bytePos = methodIndex / 8;+ int bitPos = methodIndex % 8;+ return (((bitmap[bytePos] >> bitPos) & 0x1) == 0x1);+ }++ /**+ * methodOffsets is a list of offset that points to the generated+ * native code for each compiled method.+ * @return list of method offsets+ */+ public List<OatMethodOffsets> getMethodOffsets() {+ return methodOffsets;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatClass.class);++ if (bitmapSize > 0) {+ className += "_" + bitmapSize;+ }+ if (methodOffsets.size() > 0) {+ className += "_" + methodOffsets.size();+ }++ Structure structure = new StructureDataType(className, 0);++ //structure.add( WORD, "status", null );+ if (oatVersion.equals(OatConstants.VERSION_OREO_M2_RELEASE)) {+ structure.add(OatClassStatus_OreoM2.toDataType(), "status", null);+ }+ else {+ structure.add(OatClassStatus.toDataType(), "status", null);+ }++ structure.add(WORD, "type", null);++ if (type == OatClassType.kOatClassSomeCompiled.ordinal()) {+ structure.add(DWORD, "bitmapSize", null);+ if (bitmapSize > 0) {+ DataType bitmapDataType = new ArrayDataType(BYTE, bitmapSize, BYTE.getLength());+ structure.add(bitmapDataType, "bitmap", null);+ }+ }++ for (int i = 0; i < methodOffsets.size(); ++i) {+ structure.add(methodOffsets.get(i).toDataType(), "methodOffsets_" + i, null);+ }++ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassStatus.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassStatus.javanew file mode 100644index 0000000000..3c982d60d2--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassStatus.java@@ -0,0 +1,160 @@+/* ###+ * 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.android.oat;++import java.lang.reflect.Field;++import ghidra.program.model.data.*;++/**+ *+ * See https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/mirror/class.h+ *+ */+public final class OatClassStatus {++ /**+ * Class that's temporarily used till class linking time+ * has its (vtable) size figured out and has been cloned to one with the+ * right size which will be the one used later. The old one is retired and+ * will be gc'ed once all refs to the class point to the newly+ * cloned version.+ */+ public final static short kStatusRetired = -3;++ /**+ * Class is erroneous. We need to distinguish between classes that+ * have been resolved and classes that have not. This is important+ * because the const-class instruction needs to return a previously+ * resolved class even if its subsequent initialization failed.+ * We also need this to decide whether to wrap a previous initialization+ * failure in ClassDefNotFound error or not.+ */+ public final static short kStatusErrorResolved = -2;++ /**+ * Class is erroneous. We need to distinguish between classes that+ * have been resolved and classes that have not. This is important+ * because the const-class instruction needs to return a previously+ * resolved class even if its subsequent initialization failed.+ * We also need this to decide whether to wrap a previous initialization+ * failure in ClassDefNotFound error or not.+ */+ public final static short kStatusErrorUnresolved = -1;++ /**+ * If a Class cannot be found in the class table by FindClass,+ * it allocates an new one with AllocClass in the kStatusNotReady+ * and calls LoadClass. Note if it does find a class, it may+ * not be kStatusResolved and it will try to push it forward toward kStatusResolved.+ */+ public final static short kStatusNotReady = 0;++ /**+ * LoadClass populates with Class with information from the DexFile,+ * moving the status to kStatusIdx, indicating that the Class value+ * in super_class_ has not been populated. The new Class can+ * then be inserted into the classes table.+ */+ public final static short kStatusIdx = 1;++ /**+ * After taking a lock on Class, the ClassLinker will attempt+ * to move a kStatusIdx class forward to kStatusLoaded by using+ * ResolveClass to initialize the super_class_ and ensuring the+ * interfaces are resolved.+ */+ public final static short kStatusLoaded = 2;++ /**+ * Class is just cloned with the right size from temporary+ * class that's acting as a placeholder for linking. The old+ * class will be retired. New class is set to this status first+ * before moving on to being resolved.+ */+ public final static short kStatusResolving = 3;++ /**+ * Still holding the lock on Class, the ClassLinker+ * shows linking is complete and fields of the Class populated by making+ * it kStatusResolved. Java allows circularities of the form where a super+ * class has a field that is of the type of the sub class. We need to be able+ * to fully resolve super classes while resolving types for fields.+ */+ public final static short kStatusResolved = 4;++ /** In the process of being verified. */+ public final static short kStatusVerifying = 5;++ /**+ * The verifier sets a class to this state if it encounters a soft+ * failure at compile time. This often happens when there are unresolved+ * classes in other dex files, and this status marks a class as+ * needing to be verified again at runtime.+ */+ public final static short kStatusRetryVerificationAtRuntime = 6;++ /** Retrying verification at runtime. */+ public final static short kStatusVerifyingAtRuntime = 7;++ /** Logically part of linking; done pre-init. */+ public final static short kStatusVerified = 8;++ /** Class init in progress. */+ public final static short kStatusInitializing = 9;++ /** Ready to go. */+ public final static short kStatusInitialized = 10;++ public final static short kStatusMax = 11;++ /**+ * Returns the field name for the given value.+ * If not found, simply returns a hex string of the value.+ * @param value the field value+ * @return the field name+ */+ public static String toString(short value) {+ for (Field field : OatClassStatus.class.getDeclaredFields()) {+ try {+ Object obj = field.get(null);+ if (obj != null && obj.equals(value)) {+ return field.getName();+ }+ }+ catch (Exception e) {+ //ignore...+ }+ }+ return OatClassStatus.class.getSimpleName() + ":0x" + Integer.toHexString(value);+ }++ public static DataType toDataType() {+ EnumDataType enumDataType = new EnumDataType(OatClassStatus.class.getSimpleName(), 2);+ for (Field field : OatClassStatus.class.getDeclaredFields()) {+ try {+ Object obj = field.get(null);+ enumDataType.add(field.getName(), (short) obj);+ }+ catch (Exception e) {+ //ignore...+ }+ }+ enumDataType.setCategoryPath(new CategoryPath("/oat"));+ return enumDataType;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassStatus_OreoM2.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassStatus_OreoM2.javanew file mode 100644index 0000000000..53a81a58ad--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassStatus_OreoM2.java@@ -0,0 +1,164 @@+/* ###+ * 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.android.oat;++import java.lang.reflect.Field;++import ghidra.program.model.data.*;+import ghidra.util.UniversalIdGenerator;++/**+ *+ * See https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/mirror/class.h+ *+ */+public final class OatClassStatus_OreoM2 {++ /**+ * Class that's temporarily used till class linking time+ * has its (vtable) size figured out and has been cloned to one with the+ * right size which will be the one used later. The old one is retired and+ * will be gc'ed once all refs to the class point to the newly+ * cloned version.+ */+ public final static short kStatusRetired = -3;++ /**+ * Class is erroneous. We need to distinguish between classes that+ * have been resolved and classes that have not. This is important+ * because the const-class instruction needs to return a previously+ * resolved class even if its subsequent initialization failed.+ * We also need this to decide whether to wrap a previous initialization+ * failure in ClassDefNotFound error or not.+ */+ public final static short kStatusErrorResolved = -2;++ /**+ * Class is erroneous. We need to distinguish between classes that+ * have been resolved and classes that have not. This is important+ * because the const-class instruction needs to return a previously+ * resolved class even if its subsequent initialization failed.+ * We also need this to decide whether to wrap a previous initialization+ * failure in ClassDefNotFound error or not.+ */+ public final static short kStatusErrorUnresolved = -1;++ /**+ * If a Class cannot be found in the class table by FindClass,+ * it allocates an new one with AllocClass in the kStatusNotReady+ * and calls LoadClass. Note if it does find a class, it may+ * not be kStatusResolved and it will try to push it forward toward kStatusResolved.+ */+ public final static short kStatusNotReady = 0;++ /**+ * LoadClass populates with Class with information from the DexFile,+ * moving the status to kStatusIdx, indicating that the Class value+ * in super_class_ has not been populated. The new Class can+ * then be inserted shorto the classes table.+ */+ public final static short kStatusIdx = 1;++ /**+ * After taking a lock on Class, the ClassLinker will attempt+ * to move a kStatusIdx class forward to kStatusLoaded by using+ * ResolveClass to initialize the super_class_ and ensuring the+ * shorterfaces are resolved.+ */+ public final static short kStatusLoaded = 2;++ /**+ * Class is just cloned with the right size from temporary+ * class that's acting as a placeholder for linking. The old+ * class will be retired. New class is set to this status first+ * before moving on to being resolved.+ */+ public final static short kStatusResolving = 3;++ /**+ * Still holding the lock on Class, the ClassLinker+ * shows linking is complete and fields of the Class populated by making+ * it kStatusResolved. Java allows circularities of the form where a super+ * class has a field that is of the type of the sub class. We need to be able+ * to fully resolve super classes while resolving types for fields.+ */+ public final static short kStatusResolved = 4;++ /** In the process of being verified. */+ public final static short kStatusVerifying = 5;++ /**+ * The verifier sets a class to this state if it encounters a soft+ * failure at compile time. This often happens when there are unresolved+ * classes in other dex files, and this status marks a class as+ * needing to be verified again at runtime.+ */+ public final static short kStatusRetryVerificationAtRuntime = 6;++ /** Retrying verification at runtime. */+ public final static short kStatusVerifyingAtRuntime = 7;++ /** Logically part of linking; done pre-init. */+ public final static short kStatusVerified = 8;++ /** Superclass validation part of init done. */+ public final static short kStatusSuperclassValidated = 9;++ /** Class init in progress. */+ public final static short kStatusInitializing = 10;++ /** Ready to go. */+ public final static short kStatusInitialized = 11;++ public final static short kStatusMax = 12;++ /**+ * Returns the field name for the given value.+ * If not found, simply returns a hex string of the value.+ */+ public static String toString(short value) {+ for (Field field : OatClassStatus_OreoM2.class.getDeclaredFields()) {+ try {+ Object obj = field.get(null);+ if (obj != null && obj.equals(value)) {+ return field.getName();+ }+ }+ catch (Exception e) {+ //ignore...+ }+ }+ return OatClassStatus_OreoM2.class.getSimpleName() + ":0x" + Integer.toHexString(value);+ }++ public static DataType toDataType() {+ EnumDataType enumDataType =+ new EnumDataType(OatClassStatus_OreoM2.class.getSimpleName(), 2);+ for (Field field : OatClassStatus_OreoM2.class.getDeclaredFields()) {+ try {+ Object obj = field.get(null);+ enumDataType.add(field.getName(), (short) obj);+ }+ catch (Exception e) {+ e.printStackTrace();+ //ignore...+ }+ }+ enumDataType.setCategoryPath(new CategoryPath("/oat"));+ return enumDataType;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassType.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassType.javanew file mode 100644index 0000000000..0fb59c849b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatClassType.java@@ -0,0 +1,52 @@+/* ###+ * 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.android.oat;++/**+ * OatMethodOffsets are currently 5x32-bits=160-bits long, so if we can+ * save even one OatMethodOffsets struct, the more complicated encoding+ * using a bitmap pays for itself since few classes will have 160+ * methods.+ *+ * https://android.googlesource.com/platform/art/+/lollipop-release/runtime/oat.h#152+ *+ */+public enum OatClassType {++ /**+ * OatClass is followed by an OatMethodOffsets for each method.+ */+ kOatClassAllCompiled,//0+ /**+ * A bitmap of which OatMethodOffsets are present follows the OatClass.+ */+ kOatClassSomeCompiled,//1+ /**+ * All methods are interpreted so no OatMethodOffsets are necessary.+ */+ kOatClassNoneCompiled,//2+ /**+ * Possibly an invalid case?+ * From "oat_file.cc":+ * . . .+ * case kOatClassMax: {+ * LOG(FATAL) << "Invalid OatClassType " << type_;+ * break;+ * }+ * . . .+ */+ kOatClassMax//3+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatConstants.javanew file mode 100644index 0000000000..c9592568ff--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatConstants.java@@ -0,0 +1,184 @@+/* ###+ * 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.android.oat;++import ghidra.app.util.bin.format.elf.ElfSectionHeaderConstants;+import ghidra.app.util.opinion.ElfLoader;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.MemoryBlock;+import ghidra.program.model.symbol.Symbol;+import ghidra.program.model.symbol.SymbolTable;++/**+ * https://android.googlesource.com/platform/art/+/marshmallow-mr3-release/runtime/oat.h+ */+public final class OatConstants {+ //@formatter:off++ public final static String MAGIC = "oat\n";++ public final static String SYMBOL_OAT_BSS = "oatbss";+ public final static String SYMBOL_OAT_BSS_LASTWORD = "oatbsslastword";+ public final static String SYMBOL_OAT_BSS_METHODS = "oatbssmethods";+ public final static String SYMBOL_OAT_BSS_ROOTS = "oatbssroots";+ public final static String SYMBOL_OAT_DATA = "oatdata";+ public final static String SYMBOL_OAT_DATA_BIMGRELRO = "oatdatabimgrelro";+ public final static String SYMBOL_OAT_DATA_BIMGRELRO_LASTWORD = "oatdatabimgrelrolastword";+ public final static String SYMBOL_OAT_DEX = "oatdex";+ public final static String SYMBOL_OAT_DEX_LASTWORD = "oatdexlastword";+ public final static String SYMBOL_OAT_EXEC = "oatexec";+ public final static String SYMBOL_OAT_LASTWORD = "oatlastword";++ public final static String OAT_SECTION_NAME = ElfSectionHeaderConstants.dot_rodata;++ public final static String DOT_OAT_PATCHES_SECTION_NAME = ".oat_patches";++ // * * * * * * * * * * * * * * * * * * * * * * * *+ // NOTE: we plan to only support RELEASE versions...+ // Upper case indicates supported version.++ public final static String VERSION_KITKAT_RELEASE = "007";+ public final static String version_kitkat_dev = "008";+ public final static String VERSION_LOLLIPOP_RELEASE = "039";+ public final static String VERSION_LOLLIPOP_MR1_FI_RELEASE = "045";+ public final static String VERSION_LOLLIPOP_WEAR_RELEASE = "051";+ public final static String VERSION_MARSHMALLOW_RELEASE = "064";+ public final static String VERSION_NOUGAT_RELEASE = "079";+ public final static String version_n_iot_preview_2 = "083";+ public final static String VERSION_NOUGAT_MR1_RELEASE = "088";+ public final static String version_o_preview = "114";+ public final static String VERSION_OREO_RELEASE = "124";+ public final static String version_n_iot_preview_4 = "125";+ public final static String VERSION_OREO_DR3_RELEASE = "126";+ public final static String VERSION_OREO_M2_RELEASE = "131";+ public final static String version_o_iot_preview_5 = "132";+ public final static String version_134 = "134";+ public final static String version_o_mr1_iot_preview_6 = "135";+ public final static String VERSION_PIE_RELEASE = "138";+ public final static String version_o_mr1_iot_preview_7 = "139";+ public final static String version_o_mr1_iot_preview_8 = "140";+ public final static String version_o_mr1_iot_release_1_0_0 = "141";+ public final static String version_o_mr1_iot_release_1_0_1 = "146";+ public final static String version_n_iot_release_polk_at1 = "147";+ public final static String version_q_preview_1 = "166";+ public final static String VERSION_10_RELEASE = "170";+ public final static String VERSION_11_RELEASE = "183";++ public final static int VERSION_LENGTH = 3;//3 bytes in length++ // * * * * * * * * * * * * * * * * * * * * * * * *+++ /**+ * This array contains version that have been actively tested and verified.+ * All other version will be considered unsupported until tested on exemplar firmware.+ */+ public final static String [ ] SUPPORTED_VERSIONS = new String [ ] {+ VERSION_KITKAT_RELEASE,+ VERSION_LOLLIPOP_RELEASE,+ VERSION_LOLLIPOP_MR1_FI_RELEASE,+ VERSION_LOLLIPOP_WEAR_RELEASE,+ VERSION_MARSHMALLOW_RELEASE,+ VERSION_NOUGAT_RELEASE,+ VERSION_NOUGAT_MR1_RELEASE,+ VERSION_OREO_RELEASE,+ VERSION_OREO_DR3_RELEASE,+ VERSION_OREO_M2_RELEASE,+ VERSION_PIE_RELEASE,+ VERSION_10_RELEASE,+ VERSION_11_RELEASE,+ };++ /** Keys from the OAT header "key/value" store. */+ public final static String kImageLocationKey = "image-location";+ public final static String kDex2OatCmdLineKey = "dex2oat-cmdline";+ public final static String kDex2OatHostKey = "dex2oat-host";+ public final static String kPicKey = "pic";+ public final static String kHasPatchInfoKey = "has-patch-info";+ public final static String kDebuggableKey = "debuggable";+ public final static String kNativeDebuggableKey = "native-debuggable";+ public final static String kCompilerFilter = "compiler-filter";+ public final static String kClassPathKey = "classpath";+ public final static String kBootClassPathKey = "bootclasspath";+ public final static String kBootClassPathChecksumsKey = "bootclasspath-checksums";+ public final static String kConcurrentCopying = "concurrent-copying";+ public final static String kCompilationReasonKey = "compilation-reason";++ /** Boolean value used in the Key/Value store for TRUE. */+ public final static String kTrueValue = "true";+ /** Boolean value used in the Key/Value store for FALSE. */+ public final static String kFalseValue = "false";++ //@formatter:on++ /**+ * Returns true if the given OAT version string is supported by Ghidra.+ * @param version the OAT version+ * @return true if the given OAT version string is supported+ */+ public final static boolean isSupportedVersion(String version) {+ for (String supportedVersion : SUPPORTED_VERSIONS) {+ if (supportedVersion.equals(version)) {+ return true;+ }+ }+ return false;+ }++ /**+ * Returns true if the given program contain OAT information.+ * Checks for the program being an ELF, and containing the three magic OAT symbols.+ * @param program the program to inspect+ * @return true if the program is OAT+ */+ public final static boolean isOAT(Program program) {+ if (program != null) {+ String executableFormat = program.getExecutableFormat();+ if (ElfLoader.ELF_NAME.equals(executableFormat)) {+ MemoryBlock roDataBlock =+ program.getMemory().getBlock(ElfSectionHeaderConstants.dot_rodata);+ if (roDataBlock != null) {+ SymbolTable symbolTable = program.getSymbolTable();+ Symbol oatDataSymbol = symbolTable.getPrimarySymbol(roDataBlock.getStart());+ return oatDataSymbol != null && oatDataSymbol.getName().equals(SYMBOL_OAT_DATA);+ }+ }+ }+ return false;+ }++ /**+ * Returns the version string from the OAT program, or "unknown" if not found/valid.+ * @param program the program to inspect+ * @return the OAT version+ */+ final static String getOatVersion(Program program) {+ if (OatConstants.isOAT(program)) {+ Symbol symbol = OatUtilities.getOatDataSymbol(program);+ Address address = symbol.getAddress().add(MAGIC.length());+ byte[] versionBytes = new byte[VERSION_LENGTH];+ try {+ program.getMemory().getBytes(address, versionBytes);+ return new String(versionBytes).trim();+ }+ catch (Exception e) {+ //ignore+ }+ }+ return "unknown";+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile.javanew file mode 100644index 0000000000..9c78be8f2a--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile.java@@ -0,0 +1,70 @@+/* ###+ * 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.android.oat;++import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.program.model.listing.Program;+import ghidra.util.task.TaskMonitor;++public abstract class OatDexFile implements StructConverter {++ public static final String PREFIX = StructConverterUtil.parseName(OatDexFile.class);++ /**+ * Returns the path string (not null terminated).+ * @return the path string (not null terminated)+ */+ abstract public String getDexFileLocation();++ /**+ * Returns the checksum of the embedded dex files.+ * @return the checksum of the embedded dex files+ */+ abstract public int getDexFileChecksum();++ /**+ * Returns the offset to the dex files, relative to the OATDATA symbol.+ * @return the offset to the dex files+ */+ abstract public int getDexFileOffset();++ /**+ * Returns the embedded DEX header.+ * @return the embedded DEX header+ */+ abstract public DexHeader getDexHeader();++ /**+ * Annotates the listing with data structures related to this object.+ * @param oatHeader the OAT header to markup+ * @param program the program to create markup+ * @param monitor the task monitor+ * @param log the message log+ * @throws Exception if any error occur during markup+ */+ abstract public void markup(OatHeader oatHeader, Program program, TaskMonitor monitor,+ MessageLog log) throws Exception;++ /**+ * Is the DEX header stored in an external file (e.g. VDEX files).+ * @return true if the DEX header is stored externally+ */+ abstract public boolean isDexHeaderExternal();++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFileFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFileFactory.javanew file mode 100644index 0000000000..cc793064c6--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFileFactory.java@@ -0,0 +1,64 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.vdex.VdexHeader;++public final class OatDexFileFactory {++ public final static OatDexFile getOatDexFile(BinaryReader reader, String oatVersion,+ Object additionalData) throws IOException {++ switch (oatVersion) {+ case OatConstants.VERSION_KITKAT_RELEASE:+ return new OatDexFile_KitKat(reader);+ case OatConstants.VERSION_LOLLIPOP_RELEASE:+ case OatConstants.VERSION_LOLLIPOP_MR1_FI_RELEASE:+ case OatConstants.VERSION_LOLLIPOP_WEAR_RELEASE:+ return new OatDexFile_Lollipop(reader);+ case OatConstants.VERSION_MARSHMALLOW_RELEASE:+ return new OatDexFile_Marshmallow(reader);+ case OatConstants.VERSION_NOUGAT_RELEASE:+ case OatConstants.VERSION_NOUGAT_MR1_RELEASE:+ return new OatDexFile_Nougat(reader);+ case OatConstants.VERSION_OREO_RELEASE:+ case OatConstants.VERSION_OREO_DR3_RELEASE: {+ VdexHeader vdexHeader = (VdexHeader) additionalData;+ return new OatDexFile_Oreo(reader, vdexHeader);+ }+ case OatConstants.VERSION_OREO_M2_RELEASE: {+ VdexHeader vdexHeader = (VdexHeader) additionalData;+ return new OatDexFile_OreoM2(reader, vdexHeader);+ }+ case OatConstants.VERSION_PIE_RELEASE: {+ VdexHeader vdexHeader = (VdexHeader) additionalData;+ return new OatDexFile_Pie(reader, vdexHeader);+ }+ case OatConstants.VERSION_10_RELEASE: {+ VdexHeader vdexHeader = (VdexHeader) additionalData;+ return new OatDexFile_Android10(reader, vdexHeader);+ }+ case OatConstants.VERSION_11_RELEASE: {+ VdexHeader vdexHeader = (VdexHeader) additionalData;+ return new OatDexFile_Android11(reader, vdexHeader);+ }+ }+ throw new IOException("Unsupported OAT version: " + oatVersion);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFileUtilities.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFileUtilities.javanew file mode 100644index 0000000000..488c0aae07--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFileUtilities.java@@ -0,0 +1,247 @@+/* ###+ * 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.android.oat;++import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.dex.format.*;+import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.*;+import ghidra.program.model.scalar.Scalar;+import ghidra.program.model.symbol.*;+import ghidra.program.model.util.CodeUnitInsertionException;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.InvalidInputException;+import ghidra.util.task.TaskMonitor;++public final class OatDexFileUtilities {++ /**+ * Table size is determined by the DexHeader's "classDefsIdsSize" field.+ * @param caller the caller class+ * @param address the address to perform markup+ * @param dexHeader the dex header+ * @param oatHeader the oat header+ * @param program the program to markup+ * @param monitor the task monitor for canceling+ * @param log the message log for logging messages+ */+ static void markupLookupTableData(Class<?> caller, Address address, DexHeader dexHeader,+ OatHeader oatHeader, Program program, TaskMonitor monitor, MessageLog log) {++ if (dexHeader == null) {+ log.appendMsg(+ caller.getSimpleName() + "- markupLookupTableData() - no dex header, skipping...");+ return;+ }++ monitor.setMessage("OAT - Processing Lookup Table Data...");+ monitor.setMaximum(dexHeader.getClassDefsIdsSize());+ monitor.setProgress(0);++ Symbol oatDataSymbol = OatUtilities.getOatDataSymbol(program);+ DataType dword = new DWordDataType();+ try {+ for (int i = 0; i < dexHeader.getClassDefsIdsSize(); ++i) {+ program.getListing().createData(address, dword);+ int value = program.getMemory().getInt(address);+ Address destinationAddress = oatDataSymbol.getAddress().add(value);++ program.getReferenceManager()+ .addMemoryReference(address, destinationAddress, RefType.DATA,+ SourceType.ANALYSIS, 0);+ address = address.add(dword.getLength());++ ClassDefItem classDefItem = dexHeader.getClassDefs().get(i);+ String className =+ DexUtil.convertTypeIndexToString(dexHeader, classDefItem.getClassIndex());+ Namespace classNameSpace =+ DexUtil.createNameSpaceFromMangledClassName(program, className);++ ByteProvider oatClassHeaderProvider =+ new MemoryByteProvider(program.getMemory(), destinationAddress);+ BinaryReader oatClassHeaderReader =+ new BinaryReader(oatClassHeaderProvider, !program.getLanguage().isBigEndian());++ OatClass oatClassHeader = new OatClass(oatClassHeaderReader,+ classDefItem.getClassDataItem(), oatHeader.getVersion());++ markupMethod(oatHeader, oatClassHeader, dexHeader, classDefItem, program,+ oatDataSymbol, classNameSpace, log, monitor);++ markupClassHeaderData(program, oatDataSymbol, destinationAddress, oatHeader,+ oatClassHeader, log, monitor);++ monitor.setProgress(i);+ }+ }+ catch (Exception e) {+ log.appendException(e);+ }+ }++ static void markupMethod(OatHeader oatHeader, OatClass oatClassHeader, DexHeader dexHeader,+ ClassDefItem classDefItem, Program program, Symbol oatDataSymbol,+ Namespace classNameSpace, MessageLog log, TaskMonitor monitor)+ throws CancelledException, InvalidInputException {++ if (classDefItem.getClassDataOffset() == 0) {+ return;+ }++ SymbolTable symbolTable = program.getSymbolTable();++ List<EncodedMethod> allMethods =+ OatUtilities.getAllMethods(classDefItem.getClassDataItem());++ if (oatClassHeader.getType() == OatClassType.kOatClassAllCompiled.ordinal()) {+ for (int j = 0; j < oatClassHeader.getMethodOffsets().size(); ++j) {+ monitor.checkCanceled();++ OatMethodOffsets methodOffset = oatClassHeader.getMethodOffsets().get(j);+ if (methodOffset.getCodeOffset() == 0) {+ continue;//TODO what does 0 mean?+ }+ Address toAddr = oatDataSymbol.getAddress().add(methodOffset.getCodeOffset());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);++ EncodedMethod encodedMethod = allMethods.get(j);++ MethodIDItem methodID = dexHeader.getMethods().get(encodedMethod.getMethodIndex());++ String methodName = DexUtil.convertToString(dexHeader, methodID.getNameIndex());++ symbolTable.createLabel(toAddr, methodName, classNameSpace, SourceType.ANALYSIS);+ }+ }+ else if (oatClassHeader.getType() == OatClassType.kOatClassSomeCompiled.ordinal()) {+ int offset = 0;+ for (int j = 0; j < allMethods.size(); ++j) {+ monitor.checkCanceled();+ if (oatClassHeader.isMethodNative(j)) {+ OatMethodOffsets methodOffset = oatClassHeader.getMethodOffsets().get(offset++);+ if (methodOffset.getCodeOffset() == 0) {+ continue;//TODO what does 0 mean?+ }+ Address toAddr = oatDataSymbol.getAddress().add(methodOffset.getCodeOffset());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);++ EncodedMethod encodedMethod = allMethods.get(j);+ MethodIDItem methodID =+ dexHeader.getMethods().get(encodedMethod.getMethodIndex());++ String methodName = DexUtil.convertToString(dexHeader, methodID.getNameIndex());++ symbolTable.createLabel(toAddr, methodName, classNameSpace,+ SourceType.ANALYSIS);+ }+ }+ }+ else if (oatClassHeader.getType() == OatClassType.kOatClassNoneCompiled.ordinal()) {+ // do nothing... all methods are still dalvik+ }+ else if (oatClassHeader.getType() == OatClassType.kOatClassMax.ordinal()) {+ throw new RuntimeException("invalid state!!");+ }+ }++ static void markupClassHeaderData(Program program, Symbol oatDataSymbol, Address address,+ OatHeader oatHeader, OatClass oatClassHeader, MessageLog log, TaskMonitor monitor)+ throws Exception {++ SymbolTable symbolTable = program.getSymbolTable();+ ReferenceManager referenceManager = program.getReferenceManager();+ Listing listing = program.getListing();++ Data oatClassHeaderData = listing.createData(address, oatClassHeader.toDataType());+ for (int j = 0; j < oatClassHeaderData.getNumComponents(); ++j) {+ monitor.checkCanceled();+ Data component = oatClassHeaderData.getComponent(j);+ if (component.getFieldName().startsWith("methodOffsets_")) {+ Data methodOffsetData = component.getComponent(0);+ Scalar scalar = methodOffsetData.getScalar(0);+ if (scalar.getUnsignedValue() == 0) {+ continue;//TODO what does 0 mean?+ }+ Address toAddr = oatDataSymbol.getAddress().add(scalar.getUnsignedValue());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);+ referenceManager.addMemoryReference(component.getMinAddress(), toAddr, RefType.READ,+ SourceType.ANALYSIS, 0);+ symbolTable.addExternalEntryPoint(toAddr);++ // Lays down quick header in listing right before the method+ Address quickHeaderAddress = toAddr.subtract(OatQuickMethodHeaderFactory+ .getOatQuickMethodHeaderSize(oatHeader.getVersion()));+ if (listing.isUndefined(quickHeaderAddress, quickHeaderAddress)) {+ ByteProvider oqmhProvider =+ new MemoryByteProvider(program.getMemory(), quickHeaderAddress);+ BinaryReader oqmhReader =+ new BinaryReader(oqmhProvider, !program.getLanguage().isBigEndian());+ OatQuickMethodHeader quickHeader = OatQuickMethodHeaderFactory+ .getOatQuickMethodHeader(oqmhReader, oatHeader.getVersion());+ DataType dataType = quickHeader.toDataType();+ try {+ listing.createData(quickHeaderAddress, dataType);+ }+ catch (CodeUnitInsertionException e) {+ log.appendMsg(e.getMessage());+ }+ }+ }+ }+ }++ static int getNextPowerOfTwo(int value) {+ int highestBit = Integer.highestOneBit(value);+ value = (highestBit == value ? value : highestBit << 1);+ return Math.min(value, 0x100000);//clip at 0x100000 (this will be array size of pointers)+ }++ static void markupOatClassOffsetsPointer(Class<?> caller, Address address, DexHeader dexHeader,+ OatHeader oatHeader, Program program, TaskMonitor monitor, MessageLog log) {++ if (dexHeader == null) {+ log.appendMsg(caller.getSimpleName() ++ " - markupOatClassOffsetsPointer() - no dex header, skipping...");+ return;+ }++ monitor.setMessage("Processing Oat Class Offset Pointers...");++ int size = dexHeader.getClassDefsIdsSize();++ size *= 2;++ size = getNextPowerOfTwo(size);++ DataType dword = new DWordDataType();++ // size *= dword.getLength( );++ ArrayDataType array = new ArrayDataType(dword, size, dword.getLength());+ try {+ program.getListing().createData(address, array);+ }+ catch (Exception e) {+ log.appendException(e);+ }+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Android10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Android10.javanew file mode 100644index 0000000000..49c96c2a44--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Android10.java@@ -0,0 +1,48 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.vdex.VdexHeader;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ * https://android.googlesource.com/platform/art/+/android10-release/runtime/oat_file.h#569+ */+public class OatDexFile_Android10 extends OatDexFile_Pie {++ public OatDexFile_Android10(BinaryReader reader, VdexHeader vdexHeader) throws IOException {+ super(reader, vdexHeader);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = super.toDataType();+ try {+ String className = StructConverterUtil.parseName(OatDexFile_Android10.class);+ dataType.setName(className);+ }+ catch (Exception e) {+ //ignore+ }+ return dataType;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Android11.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Android11.javanew file mode 100644index 0000000000..6400f8393d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Android11.java@@ -0,0 +1,48 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.file.formats.android.vdex.VdexHeader;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ * https://android.googlesource.com/platform/art/+/android11-release/runtime/oat_file.h#571+ */+public class OatDexFile_Android11 extends OatDexFile_Pie {++ public OatDexFile_Android11(BinaryReader reader, VdexHeader vdexHeader) throws IOException {+ super(reader, vdexHeader);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = super.toDataType();+ try {+ String className = StructConverterUtil.parseName(OatDexFile_Android11.class);+ dataType.setName(className);+ }+ catch (Exception e) {+ //ignore+ }+ return dataType;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_KitKat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_KitKat.javanew file mode 100644index 0000000000..cf14fe7e3c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_KitKat.java@@ -0,0 +1,377 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.dex.DexHeaderFactory;+import ghidra.file.formats.android.dex.format.*;+import ghidra.file.formats.android.dex.util.DexUtil;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.*;+import ghidra.program.model.mem.Memory;+import ghidra.program.model.scalar.Scalar;+import ghidra.program.model.symbol.*;+import ghidra.program.model.util.CodeUnitInsertionException;+import ghidra.util.exception.*;+import ghidra.util.task.TaskMonitor;++/**+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/kitkat-release/runtime/oat_file.h#191+ */+class OatDexFile_KitKat extends OatDexFile {++ protected int dex_file_location_size_;+ protected String dex_file_location_;+ protected int dex_file_location_checksum_;+ protected int dex_file_pointer_;+ protected int[] oat_class_offsets_pointer_;++ private DexHeader dexHeader;++ OatDexFile_KitKat(BinaryReader reader) throws IOException {+ dex_file_location_size_ = reader.readNextInt();+ dex_file_location_ = reader.readNextAsciiString(dex_file_location_size_);+ dex_file_location_checksum_ = reader.readNextInt();+ dex_file_pointer_ = reader.readNextInt();++ ByteProvider provider = reader.getByteProvider();+ ByteProvider tmpProvider = new ByteProviderWrapper(provider, dex_file_pointer_,+ provider.length() - dex_file_pointer_);+ BinaryReader tmpReader = new BinaryReader(tmpProvider, reader.isLittleEndian());+ dexHeader = DexHeaderFactory.getDexHeader(tmpReader);++ int size = dexHeader.getClassDefs().size();//read number of classes...+ if (size == 0) {+ oat_class_offsets_pointer_ = new int[0];+ }+ else {+ oat_class_offsets_pointer_ = reader.readNextIntArray(size);+ }+ }++ @Override+ public String getDexFileLocation() {+ return dex_file_location_;+ }++ @Override+ public int getDexFileChecksum() {+ return dex_file_location_checksum_;+ }++ @Override+ public int getDexFileOffset() {+ return dex_file_pointer_;+ }++ @Override+ public DexHeader getDexHeader() {+ return dexHeader;+ }++ @Override+ public boolean isDexHeaderExternal() {+ return false;+ }++ @Override+ public void markup(OatHeader oatHeader, Program program, TaskMonitor monitor, MessageLog log)+ throws Exception {+ Symbol oatDataSymbol = OatUtilities.getOatDataSymbol(program);+ Address address = oatDataSymbol.getAddress();++ Listing listing = program.getListing();+ ReferenceManager referenceManager = program.getReferenceManager();+ SymbolTable symbolTable = program.getSymbolTable();+ Memory memory = program.getMemory();++ Data oatHeaderData = listing.getDefinedDataAt(address);+ if (oatHeaderData == null ||+ !oatHeaderData.getDataType().getName().startsWith("OatHeader")) {+ return;+ }++ List<Data> oatDexFileHeaderDataList = getOatDexFileHeaderData(oatHeaderData, monitor);+ monitor.setProgress(0);+ monitor.setMaximum(oatDexFileHeaderDataList.size());+ for (Data data : oatDexFileHeaderDataList) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);++ for (int i = 0; i < data.getNumComponents(); ++i) {+ monitor.checkCanceled();+ monitor.setMaximum(data.getNumComponents());+ monitor.setProgress(i);++ Data componentI = data.getComponent(i);++ if (componentI.getFieldName().startsWith("dex_file_pointer_")) {+ Scalar scalar = componentI.getScalar(0);+ Address toAddr = oatDataSymbol.getAddress().add(scalar.getUnsignedValue());+ referenceManager.addMemoryReference(componentI.getMinAddress(), toAddr,+ RefType.DATA, SourceType.ANALYSIS, 0);+ }+ if (componentI.getFieldName().startsWith("dexClassOffsets")) {+ Data dexClassOffsetsData = getDexClassOffsetsData(data, monitor);+ markupDexClassOffset(oatHeader, program, oatDataSymbol, dexClassOffsetsData,+ monitor, log);+ }+ }+ }++ for (int i = 0; i < oat_class_offsets_pointer_.length; ++i) {+ monitor.checkCanceled();+ monitor.setMaximum(oat_class_offsets_pointer_.length);+ monitor.setProgress(i);++ ClassDefItem classDefItem = dexHeader.getClassDefs().get(i);++ String className =+ DexUtil.convertTypeIndexToString(dexHeader, classDefItem.getClassIndex());+ Namespace classNameSpace =+ DexUtil.createNameSpaceFromMangledClassName(program, className);++ Address offsetAddress = oatDataSymbol.getAddress().add(oat_class_offsets_pointer_[i]);++ symbolTable.createLabel(offsetAddress, className, SourceType.ANALYSIS);++ ByteProvider oatClassHeaderProvider = new MemoryByteProvider(memory, offsetAddress);+ BinaryReader oatClassHeaderReader =+ new BinaryReader(oatClassHeaderProvider, !program.getLanguage().isBigEndian());++ OatClass oatClassHeader = new OatClass(oatClassHeaderReader,+ classDefItem.getClassDataItem(), oatHeader.getVersion());++ markupMethod(oatHeader, oatClassHeader, dexHeader, classDefItem, program, symbolTable,+ oatDataSymbol, classNameSpace, log, monitor);++ markupClassHeaderData(program, oatDataSymbol, offsetAddress, oatHeader, oatClassHeader,+ log, monitor);+ }+ }++ private void markupDexClassOffset(OatHeader oatHeader, Program program, Symbol oatDataSymbol,+ Data dexClassOffsetsData, TaskMonitor monitor, MessageLog log)+ throws Exception, CancelledException {++ ReferenceManager referenceManager = program.getReferenceManager();+ SymbolTable symbolTable = program.getSymbolTable();++ for (int j = 0; j < dexClassOffsetsData.getNumComponents(); ++j) {+ monitor.checkCanceled();+ Data component = dexClassOffsetsData.getComponent(j);+ if (component.getFieldName().startsWith("oat_class_offsets_pointer")) {+ Scalar scalar = component.getScalar(0);+ Address toAddr = oatDataSymbol.getAddress().add(scalar.getUnsignedValue());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);+ referenceManager.addMemoryReference(component.getMinAddress(), toAddr, RefType.DATA,+ SourceType.ANALYSIS, 0);+ symbolTable.addExternalEntryPoint(toAddr);+ }+ }+ }++ private void markupMethod(OatHeader oatHeader, OatClass oatClassHeader, DexHeader dexHeader,+ ClassDefItem classDefItem, Program program, SymbolTable symbolTable,+ Symbol oatDataSymbol, Namespace classNameSpace, MessageLog log, TaskMonitor monitor)+ throws CancelledException, InvalidInputException {++ if (classDefItem.getClassDataOffset() == 0) {+ return;+ }+ List<EncodedMethod> allMethods =+ OatUtilities.getAllMethods(classDefItem.getClassDataItem());++ if (oatClassHeader.getType() == OatClassType.kOatClassAllCompiled.ordinal()) {+ for (int j = 0; j < oatClassHeader.getMethodOffsets().size(); ++j) {+ monitor.checkCanceled();+ monitor.setMaximum(oatClassHeader.getMethodOffsets().size());+ monitor.setProgress(j);++ OatMethodOffsets methodOffset = oatClassHeader.getMethodOffsets().get(j);+ if (methodOffset.getCodeOffset() == 0) {+ continue;//TODO what does 0 mean?+ }+ Address toAddr = oatDataSymbol.getAddress().add(methodOffset.getCodeOffset());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);++ EncodedMethod encodedMethod = allMethods.get(j);++ MethodIDItem methodID = dexHeader.getMethods().get(encodedMethod.getMethodIndex());++ String methodName = DexUtil.convertToString(dexHeader, methodID.getNameIndex());++ symbolTable.createLabel(toAddr, methodName, classNameSpace, SourceType.ANALYSIS);+ }+ }+ else if (oatClassHeader.getType() == OatClassType.kOatClassSomeCompiled.ordinal()) {+ int offset = 0;+ for (int j = 0; j < allMethods.size(); ++j) {+ monitor.checkCanceled();+ monitor.setMaximum(allMethods.size());+ monitor.setProgress(j);++ if (oatClassHeader.isMethodNative(j)) {+ OatMethodOffsets methodOffset = oatClassHeader.getMethodOffsets().get(offset++);+ if (methodOffset.getCodeOffset() == 0) {+ continue;//TODO what does 0 mean?+ }+ Address toAddr = oatDataSymbol.getAddress().add(methodOffset.getCodeOffset());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);++ EncodedMethod encodedMethod = allMethods.get(j);+ MethodIDItem methodID =+ dexHeader.getMethods().get(encodedMethod.getMethodIndex());++ String methodName = DexUtil.convertToString(dexHeader, methodID.getNameIndex());++ symbolTable.createLabel(toAddr, methodName, classNameSpace,+ SourceType.ANALYSIS);+ }+ }+ }+ else if (oatClassHeader.getType() == OatClassType.kOatClassNoneCompiled.ordinal()) {+ // do nothing... all methods are still dalvik+ }+ else if (oatClassHeader.getType() == OatClassType.kOatClassMax.ordinal()) {+ throw new RuntimeException("invalid state!!");+ }+ }++ private void markupClassHeaderData(Program program, Symbol oatDataSymbol, Address address,+ OatHeader oatHeader, OatClass oatClassHeader, MessageLog log, TaskMonitor monitor)+ throws Exception {++ SymbolTable symbolTable = program.getSymbolTable();+ ReferenceManager referenceManager = program.getReferenceManager();+ Listing listing = program.getListing();++ Data oatClassHeaderData = listing.createData(address, oatClassHeader.toDataType());+ for (int j = 0; j < oatClassHeaderData.getNumComponents(); ++j) {+ monitor.checkCanceled();+ monitor.setMaximum(oatClassHeaderData.getNumComponents());+ monitor.setProgress(j);++ Data component = oatClassHeaderData.getComponent(j);+ if (component.getFieldName().startsWith("methodOffsets_")) {+ Data methodOffsetData = component.getComponent(0);+ Scalar scalar = methodOffsetData.getScalar(0);+ if (scalar.getUnsignedValue() == 0) {+ continue;//TODO what does 0 mean?+ }+ Address toAddr = oatDataSymbol.getAddress().add(scalar.getUnsignedValue());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);+ referenceManager.addMemoryReference(methodOffsetData.getMinAddress(), toAddr,+ RefType.DATA, SourceType.ANALYSIS, 0);+ symbolTable.addExternalEntryPoint(toAddr);++ Address quickHeaderAddress = toAddr.subtract(OatQuickMethodHeaderFactory+ .getOatQuickMethodHeaderSize(oatHeader.getVersion()));+ if (listing.isUndefined(quickHeaderAddress, quickHeaderAddress)) {+ ByteProvider oqmhProvider =+ new MemoryByteProvider(program.getMemory(), quickHeaderAddress);+ BinaryReader quickReader =+ new BinaryReader(oqmhProvider, !program.getLanguage().isBigEndian());+ OatQuickMethodHeader quickHeader = OatQuickMethodHeaderFactory+ .getOatQuickMethodHeader(quickReader, oatHeader.getVersion());+ DataType dataType = quickHeader.toDataType();+ try {+ listing.createData(quickHeaderAddress, dataType);+ }+ catch (CodeUnitInsertionException e) {+ log.appendMsg(e.getMessage());+ }+ }++// Address oqmhAddress = toAddr.subtract( OatQuickMethodHeader001to064.SIZE );+// if ( listing.isUndefined( oqmhAddress, oqmhAddress ) ) {+// ByteProvider oqmhProvider = new MemoryByteProvider( program.getMemory( ), oqmhAddress );+// BinaryReader oqmhReader = new BinaryReader( oqmhProvider, !program.getLanguage( ).isBigEndian( ) );+// OatQuickMethodHeader oqmh = new OatQuickMethodHeader001to064( oqmhReader );+// DataType dataType = oqmh.toDataType( );+// try {+// listing.createData( oqmhAddress, dataType );+// }+// catch ( CodeUnitInsertionException e ) {+// log.appendMsg( e.getMessage( ) );+// }+// }+ }+ }+ }++ private List<Data> getOatDexFileHeaderData(Data oatHeaderData, TaskMonitor monitor)+ throws Exception {+ List<Data> list = new ArrayList<Data>();+ for (int i = 0; i < oatHeaderData.getNumComponents(); ++i) {+ monitor.checkCanceled();+ monitor.setMaximum(oatHeaderData.getNumComponents());+ monitor.setProgress(i);++ Data componentI = oatHeaderData.getComponent(i);+ if (componentI.getFieldName().startsWith(OatDexFile.PREFIX)) {+ list.add(componentI);+ }+ }+ return list;+ }++ private Data getDexClassOffsetsData(Data oatDexFileHeaderData, TaskMonitor monitor)+ throws Exception {+ for (int i = 0; i < oatDexFileHeaderData.getNumComponents(); ++i) {+ monitor.checkCanceled();+ monitor.setMaximum(oatDexFileHeaderData.getNumComponents());+ monitor.setProgress(i);++ Data componentI = oatDexFileHeaderData.getComponent(i);+ if (componentI.getFieldName().startsWith("dexClassOffsets")) {+ return componentI;+ }+ }+ throw new RuntimeException("Can't find dexClassOffsets");+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatDexFile_KitKat.class);+ Structure structure =+ new StructureDataType(className + "_" + oat_class_offsets_pointer_.length, 0);+ structure.add(DWORD, "dex_file_location_size_", null);+ structure.add(STRING, dex_file_location_size_, "dex_file_location_", null);+ structure.add(DWORD, "dex_file_location_checksum_", null);+ structure.add(DWORD, "dex_file_pointer_", null);++ Structure dexClassOffsetsStructure =+ new StructureDataType("dexClassOffsets_" + oat_class_offsets_pointer_.length, 0);+ for (int i = 0; i < oat_class_offsets_pointer_.length; ++i) {+ dexClassOffsetsStructure.add(DWORD, "oat_class_offsets_pointer_" + i, null);+ }+ dexClassOffsetsStructure.setCategoryPath(new CategoryPath("/oat"));++ structure.add(dexClassOffsetsStructure, "dexClassOffsets", null);++ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Lollipop.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Lollipop.javanew file mode 100644index 0000000000..0bcd08195d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Lollipop.java@@ -0,0 +1,49 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * Note: actual data structure seen in firmware does not contain the "canonical_dex_file_location_" field.+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-release/runtime/oat_file.h#261+ */+class OatDexFile_Lollipop extends OatDexFile_KitKat {++ OatDexFile_Lollipop(BinaryReader reader) throws IOException {+ super(reader);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = super.toDataType();+ try {+ dataType.setName(StructConverterUtil.parseName(OatDexFile_Lollipop.class) + "_" ++ oat_class_offsets_pointer_.length);+ }+ catch (Exception e) {+ //ignore+ }+ return dataType;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Marshmallow.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Marshmallow.javanew file mode 100644index 0000000000..42d90550f5--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Marshmallow.java@@ -0,0 +1,49 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * Note: actual data structure seen in firmware does not contain the "canonical_dex_file_location_" field.+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/marshmallow-release/runtime/oat_file.h#405+ */+class OatDexFile_Marshmallow extends OatDexFile_Lollipop {++ OatDexFile_Marshmallow(BinaryReader reader) throws IOException {+ super(reader);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = super.toDataType();+ try {+ dataType.setName(StructConverterUtil.parseName(OatDexFile_Marshmallow.class) + "_" ++ oat_class_offsets_pointer_.length);+ }+ catch (Exception e) {+ //ignore+ }+ return dataType;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Nougat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Nougat.javanew file mode 100644index 0000000000..fe642209bf--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Nougat.java@@ -0,0 +1,168 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.dex.DexHeaderFactory;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.*;+import ghidra.program.model.scalar.Scalar;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * Used for OAT Header version 079 to 088.+ *+ * Versions: Nougat, Nougat MR1+ *+ * https://android.googlesource.com/platform/art/+/nougat-release/runtime/oat_file.h#383+ */+class OatDexFile_Nougat extends OatDexFile {++ protected int dex_file_location_;+ protected String canonical_dex_file_location_;+ protected int dex_file_location_checksum_;+ protected int dex_file_pointer_;+ protected int lookup_table_data_;+ protected int oat_class_offsets_pointer_;++ protected DexHeader dexHeader;++ OatDexFile_Nougat(BinaryReader reader) throws IOException {+ dex_file_location_ = reader.readNextInt();+ canonical_dex_file_location_ = reader.readNextAsciiString(dex_file_location_);+ dex_file_location_checksum_ = reader.readNextInt();+ dex_file_pointer_ = reader.readNextInt();+ lookup_table_data_ = reader.readNextInt();+ oat_class_offsets_pointer_ = reader.readNextInt();++ if (!isDexHeaderExternal()) {+ ByteProvider provider = reader.getByteProvider();+ ByteProvider tmpProvider = new ByteProviderWrapper(provider, dex_file_pointer_,+ provider.length() - dex_file_pointer_);+ BinaryReader tmpReader = new BinaryReader(tmpProvider, reader.isLittleEndian());+ dexHeader = DexHeaderFactory.getDexHeader(tmpReader);+ }+ }++ @Override+ public int getDexFileChecksum() {+ return dex_file_location_checksum_;+ }++ @Override+ public DexHeader getDexHeader() {+ return dexHeader;+ }++ @Override+ public int getDexFileOffset() {+ return dex_file_pointer_;+ }++ @Override+ public String getDexFileLocation() {+ return canonical_dex_file_location_;+ }++ public int getLookupTableData() {+ return lookup_table_data_;+ }++ public int getOatClassOffsetsPointer() {+ return oat_class_offsets_pointer_;+ }++ @Override+ public boolean isDexHeaderExternal() {+ return false;+ }++ @Override+ public void markup(OatHeader oatHeader, Program program, TaskMonitor monitor, MessageLog log)+ throws Exception {+ Symbol oatDataSymbol = OatUtilities.getOatDataSymbol(program);+ Address address = oatDataSymbol.getAddress();++ Listing listing = program.getListing();+ ReferenceManager referenceManager = program.getReferenceManager();+ SymbolTable symbolTable = program.getSymbolTable();++ Data oatHeaderData = listing.getDefinedDataAt(address);+ if (oatHeaderData == null ||+ !oatHeaderData.getDataType().getName().startsWith("OatHeader")) {+ return;+ }+ for (int i = 0; i < oatHeaderData.getNumComponents(); ++i) {+ monitor.checkCanceled();+ Data componentI = oatHeaderData.getComponent(i);+ if (componentI.getFieldName().startsWith(OatDexFile.PREFIX)) {+ for (int j = 0; j < componentI.getNumComponents(); ++j) {+ monitor.checkCanceled();+ Data componentJ = componentI.getComponent(j);+ if (componentJ.getFieldName().startsWith("canonical_dex_file_location_")) {+ if (!canonical_dex_file_location_.equals(componentJ.getValue())) {+ break;//not the correct structure...+ }+ }+ if (componentJ.getFieldName().startsWith("oat_class_offsets_pointer_") ||+ componentJ.getFieldName().startsWith("lookup_table_data_") ||+ componentJ.getFieldName().startsWith("oat_class_offsets_pointer_")) {++ Scalar scalar = componentJ.getScalar(0);+ Address destinationAddress = address.add(scalar.getUnsignedValue());+ referenceManager.addMemoryReference(componentJ.getMinAddress(),+ destinationAddress, RefType.DATA, SourceType.ANALYSIS, 0);+ symbolTable.createLabel(destinationAddress, componentJ.getFieldName(),+ SourceType.ANALYSIS);++ if (componentJ.getFieldName().startsWith("lookup_table_data_")) {+ OatDexFileUtilities.markupLookupTableData(this.getClass(),+ destinationAddress, dexHeader, oatHeader, program, monitor, log);+ }+ if (componentJ.getFieldName().startsWith("oat_class_offsets_pointer_")) {+ OatDexFileUtilities.markupOatClassOffsetsPointer(this.getClass(),+ destinationAddress, dexHeader, oatHeader, program, monitor, log);+ }+ }+ }+ }+ }+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatDexFile_Nougat.class);+ Structure structure =+ new StructureDataType(className + "_" + Integer.toHexString(dex_file_location_), 0);+ structure.add(DWORD, "dex_file_location_", null);+ structure.add(STRING, dex_file_location_, "canonical_dex_file_location_", null);+ structure.add(DWORD, "dex_file_location_checksum_", null);+ structure.add(DWORD, "dex_file_pointer_", null);+ structure.add(DWORD, "lookup_table_data_", null);+ structure.add(DWORD, "oat_class_offsets_pointer_", null);++ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Oreo.javanew file mode 100644index 0000000000..a8ecbd235c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Oreo.java@@ -0,0 +1,52 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.vdex.VdexHeader;++/**+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-release/runtime/oat_file.h#444+ */+class OatDexFile_Oreo extends OatDexFile_Nougat {++ private VdexHeader vdexHeader;++ OatDexFile_Oreo(BinaryReader reader, VdexHeader vdexHeader) throws IOException {+ super(reader);+ this.vdexHeader = vdexHeader;+ if (vdexHeader != null) {+ for (int i = 0; i < vdexHeader.getDexChecksums().length; ++i) {+ if (vdexHeader.getDexChecksums()[i] == getDexFileChecksum()) {+ dexHeader = vdexHeader.getDexHeaderList().get(i);+ }+ }+ }+ }++ public VdexHeader getVdexHeader() {+ return vdexHeader;+ }++ @Override+ public boolean isDexHeaderExternal() {+ return true;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_OreoM2.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_OreoM2.javanew file mode 100644index 0000000000..bee4077bda--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_OreoM2.java@@ -0,0 +1,167 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.file.formats.android.vdex.VdexHeader;+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.scalar.Scalar;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ *+ * https://android.googlesource.com/platform/art/+/oreo-m2-release/runtime/oat_file.h#467+ */+class OatDexFile_OreoM2 extends OatDexFile {++ private int dex_file_location_;+ private String canonical_dex_file_location_;+ private int dex_file_location_checksum_;+ private int dex_file_pointer_;+ private int lookup_table_data_;+ private int method_bss_mapping_;+ private int oat_class_offsets_pointer_;+ private int dex_cache_arrays_;++ private long _offset;+ private DexHeader dexHeader;++ OatDexFile_OreoM2(BinaryReader reader, VdexHeader vdexHeader) throws IOException {+ _offset = reader.getPointerIndex();++ dex_file_location_ = reader.readNextInt();+ canonical_dex_file_location_ = reader.readNextAsciiString(dex_file_location_);+ dex_file_location_checksum_ = reader.readNextInt();+ dex_file_pointer_ = reader.readNextInt();+ lookup_table_data_ = reader.readNextInt();+ method_bss_mapping_ = reader.readNextInt();+ oat_class_offsets_pointer_ = reader.readNextInt();+ dex_cache_arrays_ = reader.readNextInt();++ if (vdexHeader != null) {+ for (int i = 0; i < vdexHeader.getDexChecksums().length; ++i) {+ if (vdexHeader.getDexChecksums()[i] == getDexFileChecksum()) {+ dexHeader = vdexHeader.getDexHeaderList().get(i);+ }+ }+ }+ }++ @Override+ public int getDexFileChecksum() {+ return dex_file_location_checksum_;+ }++ @Override+ public DexHeader getDexHeader() {+ return dexHeader;+ }++ @Override+ public int getDexFileOffset() {+ return dex_file_pointer_;+ }++ @Override+ public String getDexFileLocation() {+ return canonical_dex_file_location_;+ }++ @Override+ public boolean isDexHeaderExternal() {+ return true;+ }++ public int getLookupTableData() {+ return lookup_table_data_;+ }++ public int getMethodBssMapping() {+ return method_bss_mapping_;+ }++ public int getOatClassOffsetsPointer() {+ return oat_class_offsets_pointer_;+ }++ public int getDexCacheArrays() {+ return dex_cache_arrays_;+ }++ @Override+ public void markup(OatHeader oatHeader, Program program, TaskMonitor monitor, MessageLog log)+ throws Exception {+ Symbol oatDataSymbol = OatUtilities.getOatDataSymbol(program);+ Address address = oatDataSymbol.getAddress();++ Address dataAddress = address.add(_offset);+ Data data = program.getListing().createData(dataAddress, toDataType());++ for (int i = 0; i < data.getNumComponents(); ++i) {+ monitor.checkCanceled();+ Data componentI = data.getComponent(i);+ if (componentI.getFieldName().startsWith("lookup_table_data_") ||+ componentI.getFieldName().startsWith("oat_class_offsets_pointer_") ||+ componentI.getFieldName().startsWith("lookup_table_data_") ||+ componentI.getFieldName().startsWith("method_bss_mapping_") ||+ componentI.getFieldName().startsWith("oat_class_offsets_pointer_") ||+ componentI.getFieldName().startsWith("dex_cache_arrays_")) {++ Scalar scalar = componentI.getScalar(0);+ Address destinationAddress = address.add(scalar.getUnsignedValue());+ program.getReferenceManager()+ .addMemoryReference(componentI.getMinAddress(), destinationAddress,+ RefType.DATA, SourceType.ANALYSIS, 0);+ program.getSymbolTable()+ .createLabel(destinationAddress, componentI.getFieldName(),+ SourceType.ANALYSIS);++ if (componentI.getFieldName().startsWith("lookup_table_data_")) {+ OatDexFileUtilities.markupLookupTableData(this.getClass(), destinationAddress,+ dexHeader, oatHeader, program, monitor, log);+ }+ }+ }+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatDexFile_OreoM2.class);+ Structure structure = new StructureDataType(className + "_" + dex_file_location_, 0);+ structure.add(DWORD, "dex_file_location_", null);+ structure.add(STRING, dex_file_location_, "canonical_dex_file_location_", null);+ structure.add(DWORD, "dex_file_location_checksum_", null);+ structure.add(DWORD, "dex_file_pointer_", null);+ structure.add(DWORD, "lookup_table_data_", null);+ structure.add(DWORD, "method_bss_mapping_", null);+ structure.add(DWORD, "oat_class_offsets_pointer_", null);+ structure.add(DWORD, "dex_cache_arrays_", null);++ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Pie.javanew file mode 100644index 0000000000..fdc3313404--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatDexFile_Pie.java@@ -0,0 +1,200 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.file.formats.android.vdex.VdexHeader;+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.scalar.Scalar;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ *+ * https://android.googlesource.com/platform/art/+/pie-release/runtime/oat_file.h#518+ */+class OatDexFile_Pie extends OatDexFile {++ private int dex_file_location_;+ private String canonical_dex_file_location_;+ private int dex_file_location_checksum_;+ private int dex_file_pointer_;+ private int lookup_table_data_;+ private int method_bss_mapping_;+ private int type_bss_mapping_;+ private int string_bss_mapping_;+ private int oat_class_offsets_pointer_;+ private int lookup_table_;+ private int dex_layout_sections_;//according to spec this field should exist, but it does not++ private long _offset;+ private DexHeader dexHeader;++ OatDexFile_Pie(BinaryReader reader, VdexHeader vdexHeader) throws IOException {+ _offset = reader.getPointerIndex();++ dex_file_location_ = reader.readNextInt();+ canonical_dex_file_location_ = reader.readNextAsciiString(dex_file_location_);+ dex_file_location_checksum_ = reader.readNextInt();+ dex_file_pointer_ = reader.readNextInt();+ lookup_table_data_ = reader.readNextInt();+ method_bss_mapping_ = reader.readNextInt();+ type_bss_mapping_ = reader.readNextInt();+ string_bss_mapping_ = reader.readNextInt();+ oat_class_offsets_pointer_ = reader.readNextInt();+ lookup_table_ = reader.readNextInt();+ //dex_layout_sections_ = reader.readNextInt( );//according to spec this field should exist, but it does not++ if (vdexHeader != null) {+ for (int i = 0; i < vdexHeader.getDexChecksums().length; ++i) {+ if (vdexHeader.getDexChecksums()[i] == getDexFileChecksum()) {+ if (vdexHeader.getDexHeaderList().size() > i) {+ dexHeader = vdexHeader.getDexHeaderList().get(i);+ break;+ }+ }+ }+ }+ }++ @Override+ public int getDexFileChecksum() {+ return dex_file_location_checksum_;+ }++ @Override+ public DexHeader getDexHeader() {+ return dexHeader;+ }++ @Override+ public int getDexFileOffset() {+ return dex_file_pointer_;+ }++ @Override+ public String getDexFileLocation() {+ return canonical_dex_file_location_;+ }++ @Override+ public boolean isDexHeaderExternal() {+ return true;+ }++ public int getLookupTable() {+ return lookup_table_;+ }++ public int getLookupTableData() {+ return lookup_table_data_;+ }++ public int getMethodBssMapping() {+ return method_bss_mapping_;+ }++ public int getTypeBssMapping() {+ return type_bss_mapping_;+ }++ public int getStringBssMapping() {+ return string_bss_mapping_;+ }++ public int getOatClassOffsetsPointer() {+ return oat_class_offsets_pointer_;+ }++ public int getDexLayoutSections() {+ return dex_layout_sections_;+ }++ @Override+ public void markup(OatHeader oatHeader, Program program, TaskMonitor monitor, MessageLog log)+ throws Exception {+ Symbol oatDataSymbol = OatUtilities.getOatDataSymbol(program);+ Address address = oatDataSymbol.getAddress();++ Address dataAddress = address.add(_offset);+ Data data = program.getListing().createData(dataAddress, toDataType());++ for (int i = 0; i < data.getNumComponents(); ++i) {+ monitor.checkCanceled();+ Data componentI = data.getComponent(i);+ if (componentI.getFieldName().startsWith("lookup_table_data_") ||+ componentI.getFieldName().startsWith("oat_class_offsets_pointer_") ||+ componentI.getFieldName().startsWith("lookup_table_data_") ||+ componentI.getFieldName().startsWith("method_bss_mapping_") ||+ componentI.getFieldName().startsWith("type_bss_mapping_") ||+ componentI.getFieldName().startsWith("string_bss_mapping_") ||+ componentI.getFieldName().startsWith("oat_class_offsets_pointer_") ||+ componentI.getFieldName().startsWith("lookup_table_") ||+ componentI.getFieldName().startsWith("dex_layout_sections_")) {++ Scalar scalar = componentI.getScalar(0);+ if (scalar.getUnsignedValue() == 0) {+ continue;+ }++ Address destinationAddress = address.add(scalar.getUnsignedValue());+ program.getReferenceManager()+ .addMemoryReference(componentI.getMinAddress(), destinationAddress,+ RefType.DATA, SourceType.ANALYSIS, 0);+ program.getSymbolTable()+ .createLabel(destinationAddress, componentI.getFieldName(),+ SourceType.ANALYSIS);++ if (componentI.getFieldName().startsWith("lookup_table_data_")) {+ OatDexFileUtilities.markupLookupTableData(this.getClass(), destinationAddress,+ dexHeader, oatHeader, program, monitor, log);+ }+ }+ }+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatDexFile_Pie.class);++ Structure structure = new StructureDataType(className + "_" + dex_file_location_, 0);++ structure.add(DWORD, "dex_file_location_", null);+ structure.add(STRING, dex_file_location_, "canonical_dex_file_location_", null);+ structure.add(DWORD, "dex_file_location_checksum_", null);+ structure.add(DWORD, "dex_file_pointer_", null);+ structure.add(DWORD, "lookup_table_data_", null);+ structure.add(DWORD, "method_bss_mapping_", null);+ structure.add(DWORD, "type_bss_mapping_", null);+ structure.add(DWORD, "string_bss_mapping_", null);+ structure.add(DWORD, "oat_class_offsets_pointer_", null);+ structure.add(DWORD, "lookup_table_", null);+ //structure.add( DWORD, "dex_layout_sections_", null );//according to spec this field should exist, but it does not++ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatExecAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatExecAnalyzer.javanew file mode 100644index 0000000000..564c55cdd5--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatExecAnalyzer.java@@ -0,0 +1,139 @@+/* ###+ * 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.android.oat;++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.Program;+import ghidra.program.model.symbol.Symbol;+import ghidra.util.task.TaskMonitor;++public class OatExecAnalyzer extends FileFormatAnalyzer {++ @Override+ public String getName() {+ return "Android OATEXEC Format";+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return true;+ }++ @Override+ public String getDescription() {+ return "Analyzes the Android OAT executable (oatexec) section of this program.";+ }++ @Override+ public boolean canAnalyze(Program program) {+ //return OatConstants.isOAT(program);+ return false;+ }++ @Override+ public boolean isPrototype() {+ return true;+ }++ @Override+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {+ OatHeader header = null;+ try {+ BinaryReader reader = OatUtilities.getBinaryReader(program);+ header = OatHeaderFactory.newOatHeader(reader);+ OatHeaderFactory.parseOatHeader(header, program, reader, monitor, log);+ }+ catch (UnsupportedOatVersionException e) {+ log.appendMsg(e.getMessage());+ return false;+ }+ monitor.setMessage("OAT Version: " + header.getVersion());++ Symbol oatExecSymbol = OatUtilities.getOatExecSymbol(program);+ if (oatExecSymbol == null) {+ log.appendMsg(+ "Unable to locate " + OatConstants.SYMBOL_OAT_EXEC + " symbol, skipping...");+ return true;+ }+ Address address = oatExecSymbol.getAddress();++ Symbol oatLastWordSymbol = OatUtilities.getOatLastWordSymbol(program);+ program.getListing()+ .clearCodeUnits(oatLastWordSymbol.getAddress(), oatLastWordSymbol.getAddress(),+ true);++ //TODO adjust start position based on OatHeader values being set, such as "interpreter_to_interpreter_bridge_offset_"++ monitor.setProgress(0);+ monitor.setMaximum(oatLastWordSymbol.getAddress().subtract(address));+ try {+ while (true) {+ monitor.checkCanceled();+ monitor.setProgress(address.subtract(oatExecSymbol.getAddress()));++ if (oatLastWordSymbol.getAddress().compareTo(address) <= 0) {+ break;+ }++ ByteProvider provider = new MemoryByteProvider(program.getMemory(), address);+ BinaryReader reader =+ new BinaryReader(provider, !program.getLanguage().isBigEndian());++ OatQuickMethodHeader quickMethodHeader = OatQuickMethodHeaderFactory+ .getOatQuickMethodHeader(reader, header.getVersion());+ DataType dataType = quickMethodHeader.toDataType();+ createData(program, address, dataType);++ address = address.add(dataType.getLength());++ //TODO disassemble, restricted to, the CODESIZE amount of bytes.+ //DisassembleCommand cmd = new DisassembleCommand( address, null, true );+ //cmd.applyTo( program );+ //createFunction( program, address );++ address = address.add(quickMethodHeader.getCodeSize());+ address = align(address);+ }+ }+ catch (Exception e) {+ log.appendMsg(e.getMessage());+ return false;+ }+ return true;+ }++ /**+ * Returns the address aligned to 0x10 bytes.+ *+ * TODO how is alignment determined??? it seems to vary across files.+ */+ private Address align(Address address) {+ int alignmentValue = 0x8;+ long offset = address.getOffset();+ if (offset % alignmentValue == 0) {+ return address;+ }+ long value = alignmentValue - (offset % alignmentValue);+ return address.getNewAddress(offset + value);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatFileSystem.javanew file mode 100644index 0000000000..c6c06d9858--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatFileSystem.java@@ -0,0 +1,200 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.List;+import java.util.StringTokenizer;++import generic.continues.RethrowContinuesFactory;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.ByteProviderWrapper;+import ghidra.app.util.bin.format.elf.ElfConstants;+import ghidra.app.util.bin.format.elf.ElfHeader;+import ghidra.app.util.bin.format.elf.ElfSectionHeader;+import ghidra.app.util.bin.format.elf.ElfSectionHeaderConstants;+import ghidra.app.util.bin.format.elf.ElfSymbol;+import ghidra.app.util.bin.format.elf.ElfSymbolTable;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.CryptoException;+import ghidra.util.task.TaskMonitor;++@FileSystemInfo(type = "androidoat", description = "Android OAT (for extracting embedded DEX files)", factory = GFileSystemBaseFactory.class)+public class OatFileSystem extends GFileSystemBase {++ private long baseOffset;+ private List<GFile> listing = new ArrayList<GFile>();+ private List<OatDexFile> dexFileList = new ArrayList<OatDexFile>();++ public OatFileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ try {+ byte e_ident_magic_num = provider.readByte(0);+ String e_ident_magic_str =+ new String(provider.readBytes(1, ElfConstants.MAGIC_STR_LEN));++ boolean magicMatch = ElfConstants.MAGIC_NUM == e_ident_magic_num &&+ ElfConstants.MAGIC_STR.equalsIgnoreCase(e_ident_magic_str);++ if (magicMatch) {+ ElfHeader elf =+ ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);+ elf.parse();++ ElfSymbolTable dynamicSymbolTable = elf.getDynamicSymbolTable();+ ElfSymbol[] symbols = dynamicSymbolTable.getSymbols();+ for (ElfSymbol symbol : symbols) {+ if (OatConstants.SYMBOL_OAT_DATA.equals(symbol.getNameAsString())) {+ return true;+ }+ }++ //TODO check for OAT symbols (must be quick lookup)++// FactoryBundledWithBinaryReader reader = new FactoryBundledWithBinaryReader( RethrowContinuesFactory.INSTANCE, provider, elf.isLittleEndian( ) );+// for ( int i = 0 ; i < elf.e_phnum( ) ; ++i ) {+// monitor.checkCanceled( );+//+// long index = elf.e_phoff( ) + ( i * elf.e_phentsize ( ) );+// reader.setPointerIndex(index);+// int headerType = reader.peekNextInt();+// if ( headerType == ElfProgramHeaderConstants.PT_DYNAMIC ) {+// ElfProgramHeader programHeader = ElfProgramHeader.createElfProgramHeader( reader, elf );+//+// }+// }+ }+ }+ catch (Exception e) {+ //ignore+ }+ return false;+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {+ try {+ monitor.setProgress(0);+ monitor.setMaximum(10);+ monitor.setMessage("Parsing ELF header...");+ monitor.incrementProgress(1);+ ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);+ elf.parse();+ monitor.incrementProgress(1);++ ElfSectionHeader roDataSection = elf.getSection(ElfSectionHeaderConstants.dot_rodata);+ if (roDataSection == null) {+ //TODO should we check?+ }+ baseOffset = roDataSection.getOffset();++ monitor.setMessage("Parsing OAT header...");+ ByteProviderWrapper wrapper =+ new ByteProviderWrapper(provider, baseOffset, roDataSection.getSize());+ BinaryReader reader = new BinaryReader(wrapper, elf.isLittleEndian());+ OatHeader oatHeader = OatHeaderFactory.newOatHeader(reader);+ //oatHeader.parse( reader, null );+ OatHeaderFactory.parseOatHeader(oatHeader, reader, monitor);+ monitor.incrementProgress(1);++ dexFileList = oatHeader.getOatDexFileList();++ monitor.setProgress(0);+ monitor.setMaximum(dexFileList.size());+ monitor.setMessage("Creating OAT filesystem...");++ for (OatDexFile oatDexFileHeader : dexFileList) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ DexHeader dexHeader = oatDexFileHeader.getDexHeader();+ if (dexHeader == null) {+ continue;+ }+ //add to file list, but remove the paths...+ StringTokenizer tokenizer =+ new StringTokenizer(oatDexFileHeader.getDexFileLocation(), "/");+ while (tokenizer.hasMoreTokens()) {+ monitor.checkCanceled();+ String token = tokenizer.nextToken();+ boolean isDirectory = tokenizer.hasMoreTokens();//last token is file name+ if (!isDirectory) {+ if (listing.isEmpty() && !token.endsWith(":classes.dex")) {+ token = token + ":classes.dex";//for some reason only the 2nd and on has this suffix+ }+ GFile file = GFileImpl.fromPathString(this, root, token, null, isDirectory,+ dexHeader.getFileSize());+ listing.add(file);+ }+ }+ }+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ @Override+ public void close() throws IOException {+ super.close();+ listing.clear();+ dexFileList = new ArrayList<OatDexFile>();//prevent UnmodifiableException+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ if (directory == null || directory.equals(root)) {+ return listing;+ }+ return null;+ }++ @Override+ public String getInfo(GFile file, TaskMonitor monitor) {+ int index = listing.indexOf(file);+ OatDexFile oatDexFileHeader = dexFileList.get(index);+ return oatDexFileHeader.getDexFileLocation();+ }++ @Override+ public InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException, CryptoException {+ int index = listing.indexOf(file);+ OatDexFile oatDexFileHeader = dexFileList.get(index);+ return provider.getInputStream(baseOffset + oatDexFileHeader.getDexFileOffset());+ }++ @Override+ public InputStream getInputStream(GFile file, TaskMonitor monitor)+ throws CancelledException, IOException {+ int index = listing.indexOf(file);+ OatDexFile oatDexFileHeader = dexFileList.get(index);+ return provider.getInputStream(baseOffset + oatDexFileHeader.getDexFileOffset());+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader.javanew file mode 100644index 0000000000..de1c69d4f2--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader.java@@ -0,0 +1,94 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;++/**+ * Base OatHeader implementations+ * <br>+ * Each sub-class is based on that version of OAT, as released,+ * and overrides/modifies behavior, as defined in the original source, from the previous version(s).+ * <br>+ * Some versions have no apparent change in class fields.+ */+public abstract class OatHeader implements StructConverter {++ protected String magic;+ protected String version;++ protected OatHeader(BinaryReader reader) throws IOException {+ magic = new String(reader.readNextByteArray(OatConstants.MAGIC.length()));+ version = reader.readNextAsciiString(4);+ }++ /**+ * Parses the OAT header beyond the MAGIC and VERSION fields.+ * The "additionalData" is used to future proof the parsers.+ * For example, its needed for handling vdex files.+ */+ abstract public void parse(BinaryReader reader, Object additionalData)+ throws IOException, UnsupportedOatVersionException;++ /**+ * Returns the MAGIC string, i.e. "oat\n".+ */+ public String getMagic() {+ return magic;+ }++ /**+ * Returns the VERSION string, e.g. "001", "009", etc.+ */+ public String getVersion() {+ return version;+ }++ /**+ * Returns the number of DEX files embedded inside this OAT file.+ */+ abstract public int getDexFileCount();++ /**+ * Returns the size (in bytes) of the Key/Value store contained inside this OAT file.+ */+ abstract public int getKeyValueStoreSize();++ /**+ * Returns a list of the OatDexFileHeader, a structure defining the embedded DEX files.+ */+ abstract public List<OatDexFile> getOatDexFileList();++ /**+ * Returns the OAT instruction set (ARM, X86, etc).+ */+ abstract public OatInstructionSet getInstructionSet();++ /**+ * Returns the offset to the executable code, relative to the "oatdata" symbol.+ * The executable code can also be located using the "oatexec" symbol.+ */+ abstract public int getExecutableOffset();++ /**+ * Returns the OAT checksum value.+ */+ abstract public int getChecksum();+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeaderAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeaderAnalyzer.javanew file mode 100644index 0000000000..f2437288f6--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeaderAnalyzer.java@@ -0,0 +1,317 @@+/* ###+ * 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.android.oat;++import ghidra.app.cmd.disassemble.DisassembleCommand;+import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.format.elf.ElfSectionHeaderConstants;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSetView;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.*;+import ghidra.program.model.mem.Memory;+import ghidra.program.model.mem.MemoryBlock;+import ghidra.program.model.scalar.Scalar;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++public class OatHeaderAnalyzer extends FileFormatAnalyzer {++ @Override+ public String getName() {+ return "Android OAT Header Format";+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return true;+ }++ @Override+ public String getDescription() {+ return "Analyzes the Android OAT sections (oatdata and oatexec) in this program.";+ }++ @Override+ public boolean canAnalyze(Program program) {+ return OatConstants.isOAT(program);+ }++ @Override+ public boolean isPrototype() {+ return true;+ }++ @Override+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {+ clearIfNeeded(program, monitor, log);++ Symbol oatDataSymbol = OatUtilities.getOatDataSymbol(program);+ Address address = oatDataSymbol.getAddress();++ BinaryReader reader = OatUtilities.getBinaryReader(program);+ if (reader == null) {+ return false;+ }++ OatHeader oatHeader = null;+ try {+ oatHeader = OatHeaderFactory.newOatHeader(reader);++ OatHeaderFactory.parseOatHeader(oatHeader, program, reader, monitor, log);+ }+ catch (UnsupportedOatVersionException e) {+ log.appendMsg(e.getMessage());+ return false;+ }++ try {+ DataType headerDataType = oatHeader.toDataType();+ Data headerData = createData(program, address, headerDataType);+ address = address.add(headerDataType.getLength());++ markupClassOffsets(program, oatDataSymbol, oatHeader, headerData, monitor, log);++ monitor.setMessage("Applying OAT DEX headers...");+ monitor.initialize(oatHeader.getOatDexFileList().size());++ for (int i = 0; i < oatHeader.getOatDexFileList().size(); ++i) {+ monitor.checkCanceled();+ monitor.setMessage("Applying OAT DEX class offsets [ Pass " + i + " of " ++ oatHeader.getOatDexFileList().size() + " ]...");+ monitor.incrementProgress(1);++ OatDexFile oatDexFileHeader = oatHeader.getOatDexFileList().get(i);++ oatDexFileHeader.markup(oatHeader, program, monitor, log);++ applyDexHeader(program, oatDexFileHeader, oatDataSymbol, i);+ }++ markupOatPatches(program, oatHeader, monitor, log);+ }+ catch (Exception e) {+ throw e;+ }+ finally {+ oatHeader = null;+ }+ return true;+ }++ /**+ * Ghidra sometimes applies undefined1[x] at "oatdata" and "oatexec".+ * This method checks for these arrays and clears if they exist.+ */+ private void clearIfNeeded(Program program, TaskMonitor monitor, MessageLog log) {+ Symbol oatDataSymbol = OatUtilities.getOatDataSymbol(program);+ Data oatDataSymbolData = program.getListing().getDefinedDataAt(oatDataSymbol.getAddress());+ if (oatDataSymbolData != null && oatDataSymbolData.isArray()) {+ Array array = (Array) oatDataSymbolData.getDataType();+ if (array.getDataType().isEquivalent(new Undefined1DataType())) {+ program.getListing()+ .clearCodeUnits(oatDataSymbolData.getMinAddress(),+ oatDataSymbolData.getMaxAddress(), false);+ }+ }+ Symbol oatExecSymbol = OatUtilities.getOatExecSymbol(program);+ if (oatExecSymbol != null) {+ Data oatExecSymbolData =+ program.getListing().getDefinedDataAt(oatExecSymbol.getAddress());+ if (oatExecSymbolData != null && oatExecSymbolData.isArray()) {+ Array array = (Array) oatExecSymbolData.getBaseDataType();+ if (array.getDataType().isEquivalent(new Undefined1DataType())) {+ program.getListing()+ .clearCodeUnits(oatExecSymbolData.getMinAddress(),+ oatExecSymbolData.getMaxAddress(), false);+ }+ }+ }+ Symbol oatLastWordSymbol = OatUtilities.getOatLastWordSymbol(program);+ if (oatLastWordSymbol != null) {+ Data oatLastWordSymbolData =+ program.getListing().getDefinedDataAt(oatLastWordSymbol.getAddress());+ if (oatLastWordSymbolData != null) {+ program.getListing()+ .clearCodeUnits(oatLastWordSymbolData.getMinAddress(),+ oatLastWordSymbolData.getMaxAddress(), false);+ }+ }+ }++ /**+ * Annotates the listing for the ".oat_patches" section(s).+ * The format of the section changes based on the OAT version.+ */+ private void markupOatPatches(Program program, OatHeader oatHeader, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ monitor.setMessage("Annotating OAT Patches...");+ Memory memory = program.getMemory();++ if (oatHeader.getVersion().equals(OatConstants.VERSION_LOLLIPOP_MR1_FI_RELEASE)) {+ MemoryBlock oatBlock = memory.getBlock(OatConstants.DOT_OAT_PATCHES_SECTION_NAME);+ MemoryBlock destinationBlock = findOatPatchesDestinationBlock(program, oatBlock);+ if (oatBlock == null || destinationBlock == null) {+ log.appendMsg("Could not locate OAT patches source / destination block.");+ return;+ }+ DataType dataType = new DWordDataType();+ monitor.setProgress(0);+ long numberOfElements = oatBlock.getSize() / dataType.getLength();+ monitor.setMaximum(numberOfElements);+ for (int i = 0; i < numberOfElements; ++i) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ try {+ Address address = oatBlock.getStart().add(i * dataType.getLength());+ Data data = createData(program, address, dataType);+ Scalar scalar = data.getScalar(0);+ Address toAddr = destinationBlock.getStart().add(scalar.getUnsignedValue());+ program.getListing().setComment(address, CodeUnit.EOL_COMMENT, "->" + toAddr);+ }+ catch (Exception e) {+ log.appendException(e);+ return;+ }+ }+ }+ else if (oatHeader.getVersion().equals(OatConstants.VERSION_MARSHMALLOW_RELEASE)) {+ //TODO+ }+ else if (oatHeader.getVersion().equals(OatConstants.VERSION_NOUGAT_MR1_RELEASE)) {+ //TODO+ }+ else if (oatHeader.getVersion().equals(OatConstants.VERSION_OREO_RELEASE)) {+ //TODO+ }+ else if (oatHeader.getVersion().equals(OatConstants.VERSION_OREO_M2_RELEASE)) {+ //TODO+ }+ }++ private MemoryBlock findOatPatchesDestinationBlock(Program program,+ MemoryBlock oatPatchesBlock) {+ int pos = oatPatchesBlock.getName().indexOf(OatConstants.DOT_OAT_PATCHES_SECTION_NAME);+ if (pos == 0) {//the block's full name is ".oat_patches"+ return program.getMemory().getBlock(ElfSectionHeaderConstants.dot_text);+ }+ //the block has a prefix, that is the destination name+ String destinationBlockName = oatPatchesBlock.getName().substring(0, pos);+ return program.getMemory().getBlock(destinationBlockName);+ }++ private void applyDexHeader(Program program, OatDexFile oatDexFileHeader, Symbol oatDataSymbol,+ int index) throws Exception {++ Address address = oatDataSymbol.getAddress().add(oatDexFileHeader.getDexFileOffset());++ DexHeader dexHeader = oatDexFileHeader.getDexHeader();++ if (dexHeader == null) {+ return;+ }++ if (oatDexFileHeader.isDexHeaderExternal()) {+ return;+ }++ DataType dexHeaderDataType = dexHeader.toDataType();+ try {+ dexHeaderDataType.setName(dexHeaderDataType.getName() + "_" + index);+ }+ catch (Exception e) {+ //ignore+ }++ createData(program, address, dexHeaderDataType);++ address = address.add(dexHeaderDataType.getLength());++ int dexRemainder = dexHeader.getFileSize() - dexHeaderDataType.getLength();+ if (dexRemainder > 0) {+ DataType paddingDataType = new ArrayDataType(StructConverter.BYTE, dexRemainder,+ StructConverter.BYTE.getLength());+ createData(program, address, paddingDataType);+ }+ }++ private void markupClassOffsets(Program program, Symbol oatDataSymbol, OatHeader oatHeader,+ Data headerData, TaskMonitor monitor, MessageLog log) throws CancelledException {++ SymbolTable symbolTable = program.getSymbolTable();+ ReferenceManager referenceManager = program.getReferenceManager();+ EquateTable equateTable = program.getEquateTable();++ for (int i = 0; i < headerData.getNumComponents(); ++i) {+ monitor.checkCanceled();+ if (!headerData.getComponent(i).getFieldName().equals("executable_offset_") &&+ headerData.getComponent(i).getFieldName().endsWith("_offset_")) {+ Scalar scalar = headerData.getComponent(i).getScalar(0);+ if (scalar.getUnsignedValue() > 0) {+ Address toAddr = oatDataSymbol.getAddress().add(scalar.getUnsignedValue());+ toAddr = OatUtilities.adjustForThumbAsNeeded(oatHeader, program, toAddr, log);++ referenceManager.addMemoryReference(headerData.getComponent(i).getMinAddress(),+ toAddr, RefType.DATA, SourceType.ANALYSIS, 0);+ try {+ symbolTable.createLabel(toAddr, headerData.getComponent(i).getFieldName(),+ SourceType.ANALYSIS);++ disassembleAsNeeded(program, toAddr);+ }+ catch (Exception e) {+ //ignore...+ }+ }+ }+ else if (headerData.getComponent(i)+ .getFieldName()+ .equals(OatInstructionSet.DISPLAY_NAME)) {+ try {+ Scalar scalar = headerData.getComponent(i).getScalar(0);+ OatInstructionSet instructionSet =+ OatInstructionSet.valueOf((int) scalar.getUnsignedValue());+ Equate equate =+ equateTable.createEquate(instructionSet.name(), scalar.getUnsignedValue());+ equate.addReference(headerData.getComponent(i).getMinAddress(), 0);+ }+ catch (Exception e) {+ //ignore...+ }+ }+ }+ }++ /**+ * Check to see if points to instructions and not undefined, if so then disassemble.+ */+ private void disassembleAsNeeded(Program program, Address toAddr) {+ if (program.getMemory().contains(toAddr) &&+ program.getMemory().getBlock(toAddr).isExecute()) {+ if (program.getListing().isUndefined(toAddr, toAddr)) {+ DisassembleCommand cmd = new DisassembleCommand(toAddr, null, false);+ cmd.applyTo(program);+ }+ }+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeaderFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeaderFactory.javanew file mode 100644index 0000000000..a2ff1c278c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeaderFactory.java@@ -0,0 +1,96 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.formats.android.vdex.VdexFactory;+import ghidra.file.formats.android.vdex.VdexHeader;+import ghidra.program.model.listing.Program;+import ghidra.util.task.TaskMonitor;++public final class OatHeaderFactory {++ /**+ * Returns an OatHeader of the correct version.+ * @param reader the binary reader for the OAT header+ * @return the new OAT header+ * @throws IOException if OAT header cannot be created from reader+ * @throws UnsupportedOatVersionException when the provided version is invalid or not yet implemented.+ */+ public final static OatHeader newOatHeader(BinaryReader reader)+ throws IOException, UnsupportedOatVersionException {+ String magic = new String(reader.readByteArray(0, OatConstants.MAGIC.length()));+ String version = reader.readAsciiString(4, 4);+ if (magic.equals(OatConstants.MAGIC)) {+ if (OatConstants.isSupportedVersion(version)) {+ switch (version) {+ case OatConstants.VERSION_KITKAT_RELEASE:+ return new OatHeader_KitKat(reader);+ case OatConstants.VERSION_LOLLIPOP_RELEASE:+ case OatConstants.VERSION_LOLLIPOP_MR1_FI_RELEASE:+ case OatConstants.VERSION_LOLLIPOP_WEAR_RELEASE:+ return new OatHeader_Lollipop(reader);+ case OatConstants.VERSION_MARSHMALLOW_RELEASE:+ return new OatHeader_Marshmallow(reader);+ case OatConstants.VERSION_NOUGAT_RELEASE:+ case OatConstants.VERSION_NOUGAT_MR1_RELEASE:+ return new OatHeader_Nougat(reader);+ case OatConstants.VERSION_OREO_RELEASE:+ case OatConstants.VERSION_OREO_DR3_RELEASE:+ return new OatHeader_Oreo(reader);//v124 and v126 are same format+ case OatConstants.VERSION_OREO_M2_RELEASE:+ return new OatHeader_Oreo_M2(reader);+ case OatConstants.VERSION_PIE_RELEASE:+ return new OatHeader_Pie(reader);+ case OatConstants.VERSION_10_RELEASE:+ return new OatHeader_10(reader);+ case OatConstants.VERSION_11_RELEASE:+ return new OatHeader_11(reader);+ }+ }+ }+ throw new UnsupportedOatVersionException(magic, version);+ }++ public final static void parseOatHeader(OatHeader oatHeader, BinaryReader reader,+ TaskMonitor monitor) throws UnsupportedOatVersionException, IOException {++ parseOatHeader(oatHeader, null, reader, monitor, new MessageLog());+ }++ public final static void parseOatHeader(OatHeader oatHeader, Program oatProgram,+ BinaryReader reader, TaskMonitor monitor, MessageLog log)+ throws UnsupportedOatVersionException, IOException {++ if (oatHeader.getVersion().equals(OatConstants.VERSION_OREO_RELEASE) ||+ oatHeader.getVersion().equals(OatConstants.VERSION_OREO_M2_RELEASE) ||+ oatHeader.getVersion().equals(OatConstants.VERSION_PIE_RELEASE) ||+ oatHeader.getVersion().equals(OatConstants.VERSION_10_RELEASE) ||+ oatHeader.getVersion().equals(OatConstants.VERSION_11_RELEASE)) {++ //TODO move instantiation into parse method (will need program?)+ VdexHeader vdexHeader = VdexFactory.loadVdexHeader(oatProgram, monitor, log);+ oatHeader.parse(reader, vdexHeader);+ }+ else {+ oatHeader.parse(reader, null);+ }+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_10.javanew file mode 100644index 0000000000..5dcf4e7e52--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_10.java@@ -0,0 +1,140 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.*;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class OatHeader_10 extends OatHeader {+ protected int oat_checksum_;+ protected int instruction_set_;+ protected int instruction_set_features_bitmap_;+ protected int dex_file_count_;+ protected int oat_dex_files_offset_;+ protected int executable_offset_;+ protected int jni_dlsym_lookup_offset_;+ protected int quick_generic_jni_trampoline_offset_;+ protected int quick_imt_conflict_trampoline_offset_;+ protected int quick_resolution_trampoline_offset_;+ protected int quick_to_interpreter_bridge_offset_;+ protected int key_value_store_size_;+ protected Map<String, String> key_value_store_ = new HashMap<String, String>();+ protected List<String> orderedKeyList = new ArrayList<String>();//ordered as defined++ protected List<OatDexFile> oatDexFileList = new ArrayList<OatDexFile>();++ OatHeader_10(BinaryReader reader) throws IOException {+ super(reader);++ oat_checksum_ = reader.readNextInt();+ instruction_set_ = reader.readNextInt();+ instruction_set_features_bitmap_ = reader.readNextInt();+ dex_file_count_ = reader.readNextInt();+ oat_dex_files_offset_ = reader.readNextInt();+ executable_offset_ = reader.readNextInt();+ jni_dlsym_lookup_offset_ = reader.readNextInt();+ quick_generic_jni_trampoline_offset_ = reader.readNextInt();+ quick_imt_conflict_trampoline_offset_ = reader.readNextInt();+ quick_resolution_trampoline_offset_ = reader.readNextInt();+ quick_to_interpreter_bridge_offset_ = reader.readNextInt();+ key_value_store_size_ = reader.readNextInt();+ }++ @Override+ public void parse(BinaryReader reader, Object additionalData)+ throws IOException, UnsupportedOatVersionException {+ int count = 0;+ while (count < key_value_store_size_) {+ String key = reader.readNextAsciiString();+ String value = reader.readNextAsciiString();+ count += key.length() + 1;+ count += value.length() + 1;+ orderedKeyList.add(key);+ key_value_store_.put(key, value);+ }++ reader.setPointerIndex(oat_dex_files_offset_);+ for (int i = 0; i < dex_file_count_; ++i) {+ oatDexFileList+ .add(OatDexFileFactory.getOatDexFile(reader, getVersion(), additionalData));+ }+ }++ @Override+ public int getDexFileCount() {+ return dex_file_count_;+ }++ @Override+ public int getKeyValueStoreSize() {+ return key_value_store_size_;+ }++ @Override+ public List<OatDexFile> getOatDexFileList() {+ return oatDexFileList;+ }++ @Override+ public OatInstructionSet getInstructionSet() {+ return OatInstructionSet.valueOf(instruction_set_);+ }++ @Override+ public int getExecutableOffset() {+ return executable_offset_;+ }++ @Override+ public int getChecksum() {+ return oat_checksum_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatHeader_10.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, OatInstructionSet.DISPLAY_NAME, null);+ structure.add(DWORD, "instruction_set_features_bitmap_", null);+ structure.add(DWORD, "dex_file_count_", null);+ structure.add(DWORD, "oat_dex_files_offset_", null);+ structure.add(DWORD, "executable_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_offset_", null);+ structure.add(DWORD, "quick_generic_jni_trampoline_offset_", null);+ structure.add(DWORD, "quick_imt_conflict_trampoline_offset_", null);+ structure.add(DWORD, "quick_resolution_trampoline_offset_", null);+ structure.add(DWORD, "quick_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "key_value_store_size_", null);++ for (int i = 0; i < orderedKeyList.size(); ++i) {+ String key = orderedKeyList.get(i);+ String value = key_value_store_.get(key);+ structure.add(STRING, key.length() + 1, "key_value_store_[" + i + "].key", null);+ structure.add(STRING, value.length() + 1, "key_value_store_[" + i + "].value", null);+ }++ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_11.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_11.javanew file mode 100644index 0000000000..3d338db51e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_11.java@@ -0,0 +1,143 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.*;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class OatHeader_11 extends OatHeader {+ protected int oat_checksum_;+ protected int instruction_set_;+ protected int instruction_set_features_bitmap_;+ protected int dex_file_count_;+ protected int oat_dex_files_offset_;+ protected int executable_offset_;+ protected int jni_dlsym_lookup_offset_;+ protected int jni_dlsym_lookup_critical_trampoline_offset_;+ protected int quick_generic_jni_trampoline_offset_;+ protected int quick_imt_conflict_trampoline_offset_;+ protected int quick_resolution_trampoline_offset_;+ protected int quick_to_interpreter_bridge_offset_;+ protected int key_value_store_size_;+ protected Map<String, String> key_value_store_ = new HashMap<String, String>();+ protected List<String> orderedKeyList = new ArrayList<String>();//ordered as defined++ protected List<OatDexFile> oatDexFileList = new ArrayList<OatDexFile>();++ OatHeader_11(BinaryReader reader) throws IOException {+ super(reader);++ oat_checksum_ = reader.readNextInt();+ instruction_set_ = reader.readNextInt();+ instruction_set_features_bitmap_ = reader.readNextInt();+ dex_file_count_ = reader.readNextInt();+ oat_dex_files_offset_ = reader.readNextInt();+ executable_offset_ = reader.readNextInt();+ jni_dlsym_lookup_offset_ = reader.readNextInt();+ jni_dlsym_lookup_critical_trampoline_offset_ = reader.readNextInt();+ quick_generic_jni_trampoline_offset_ = reader.readNextInt();+ quick_imt_conflict_trampoline_offset_ = reader.readNextInt();+ quick_resolution_trampoline_offset_ = reader.readNextInt();+ quick_to_interpreter_bridge_offset_ = reader.readNextInt();+ key_value_store_size_ = reader.readNextInt();+ }++ @Override+ public void parse(BinaryReader reader, Object additionalData)+ throws IOException, UnsupportedOatVersionException {+ int count = 0;+ while (count < key_value_store_size_) {+ String key = reader.readNextAsciiString();+ String value = reader.readNextAsciiString();+ count += key.length() + 1;+ count += value.length() + 1;+ orderedKeyList.add(key);+ key_value_store_.put(key, value);+ }++ reader.setPointerIndex(oat_dex_files_offset_);+ for (int i = 0; i < dex_file_count_; ++i) {+ oatDexFileList+ .add(OatDexFileFactory.getOatDexFile(reader, getVersion(), additionalData));+ }+ }++ @Override+ public int getDexFileCount() {+ return dex_file_count_;+ }++ @Override+ public int getKeyValueStoreSize() {+ return key_value_store_size_;+ }++ @Override+ public List<OatDexFile> getOatDexFileList() {+ return oatDexFileList;+ }++ @Override+ public OatInstructionSet getInstructionSet() {+ return OatInstructionSet.valueOf(instruction_set_);+ }++ @Override+ public int getExecutableOffset() {+ return executable_offset_;+ }++ @Override+ public int getChecksum() {+ return oat_checksum_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatHeader_11.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "oat_checksum_", null);+ structure.add(DWORD, OatInstructionSet.DISPLAY_NAME, null);+ structure.add(DWORD, "instruction_set_features_bitmap_", null);+ structure.add(DWORD, "dex_file_count_", null);+ structure.add(DWORD, "oat_dex_files_offset_", null);+ structure.add(DWORD, "executable_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_critical_trampoline_offset_", null);+ structure.add(DWORD, "quick_generic_jni_trampoline_offset_", null);+ structure.add(DWORD, "quick_imt_conflict_trampoline_offset_", null);+ structure.add(DWORD, "quick_resolution_trampoline_offset_", null);+ structure.add(DWORD, "quick_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "key_value_store_size_", null);++ for (int i = 0; i < orderedKeyList.size(); ++i) {+ String key = orderedKeyList.get(i);+ String value = key_value_store_.get(key);+ structure.add(STRING, key.length() + 1, "key_value_store_[" + i + "].key", null);+ structure.add(STRING, value.length() + 1, "key_value_store_[" + i + "].value", null);+ }++ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_KitKat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_KitKat.javanew file mode 100644index 0000000000..8814916757--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_KitKat.java@@ -0,0 +1,151 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class OatHeader_KitKat extends OatHeader {++ protected int adler32_checksum_;+ protected int instruction_set_;+ protected int dex_file_count_;+ protected int executable_offset_;+ protected int interpreter_to_interpreter_bridge_offset_;+ protected int interpreter_to_compiled_code_bridge_offset_;+ protected int jni_dlsym_lookup_offset_;+ protected int portable_resolution_trampoline_offset_;+ protected int portable_to_interpreter_bridge_offset_;+ protected int image_file_location_oat_checksum_;+ protected int image_file_location_oat_data_begin_;+ protected int image_file_location_size_;+ protected byte[] image_file_location_data_; // note variable width data at end++ OatHeader_KitKat(BinaryReader reader) throws IOException {+ super(reader);+ adler32_checksum_ = reader.readNextInt();+ instruction_set_ = reader.readNextInt();+ dex_file_count_ = reader.readNextInt();+ executable_offset_ = reader.readNextInt();+ interpreter_to_interpreter_bridge_offset_ = reader.readNextInt();+ interpreter_to_compiled_code_bridge_offset_ = reader.readNextInt();+ jni_dlsym_lookup_offset_ = reader.readNextInt();+ portable_resolution_trampoline_offset_ = reader.readNextInt();+ portable_to_interpreter_bridge_offset_ = reader.readNextInt();+ image_file_location_oat_checksum_ = reader.readNextInt();+ image_file_location_oat_data_begin_ = reader.readNextInt();+ image_file_location_size_ = reader.readNextInt();+ }++ @Override+ public void parse(BinaryReader reader, Object additionalData) throws IOException {+ //do nothing+ }++ public int getChecksum() {+ return adler32_checksum_;+ }++ @Override+ public OatInstructionSet getInstructionSet() {+ return OatInstructionSet.valueOf(instruction_set_);+ }++ @Override+ public int getDexFileCount() {+ return dex_file_count_;+ }++ @Override+ public int getExecutableOffset() {+ return executable_offset_;+ }++ public int getInterpreterToInterpreterBridgeOffset() {+ return interpreter_to_interpreter_bridge_offset_;+ }++ public int getInterpreterToCompiledCodeBridgeOffset() {+ return interpreter_to_compiled_code_bridge_offset_;+ }++ public int getJniDlsymLookupOffset() {+ return jni_dlsym_lookup_offset_;+ }++ public int getPortableResolutionTrampolineOffset() {+ return portable_resolution_trampoline_offset_;+ }++ public int getPortableToInterpreterBridgeOffset() {+ return portable_to_interpreter_bridge_offset_;+ }++ public int getImageFileLocationOatChecksum() {+ return image_file_location_oat_checksum_;+ }++ public int getImageFileLocationOatDataBegin() {+ return image_file_location_oat_data_begin_;+ }++ public int getImageFileLocationSize_() {+ return image_file_location_size_;+ }++ public byte[] getImageFileLocationData_() {+ return image_file_location_data_;+ }++ @Override+ public int getKeyValueStoreSize() {+ // TODO Auto-generated method stub+ return 0;+ }++ @Override+ public List<OatDexFile> getOatDexFileList() {+ // TODO Auto-generated method stub+ return null;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatHeader_KitKat.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "adler32_checksum_", null);+ structure.add(DWORD, OatInstructionSet.DISPLAY_NAME, null);+ structure.add(DWORD, "dex_file_count_", null);+ structure.add(DWORD, "executable_offset_", null);+ structure.add(DWORD, "interpreter_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "interpreter_to_compiled_code_bridge_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_offset_", null);+ structure.add(DWORD, "portable_resolution_trampoline_offset_", null);+ structure.add(DWORD, "portable_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "image_file_location_oat_checksum_", null);+ structure.add(DWORD, "image_file_location_oat_data_begin_", null);+ structure.add(DWORD, "image_file_location_size_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Lollipop.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Lollipop.javanew file mode 100644index 0000000000..7f219ed755--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Lollipop.java@@ -0,0 +1,165 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.*;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/oat.h+ */+public class OatHeader_Lollipop extends OatHeader {++ protected int adler32_checksum_;+ protected int instruction_set_;+ protected int instruction_set_features_;+ protected int dex_file_count_;+ protected int executable_offset_;+ protected int interpreter_to_interpreter_bridge_offset_;+ protected int interpreter_to_compiled_code_bridge_offset_;+ protected int jni_dlsym_lookup_offset_;+ protected int portable_imt_conflict_trampoline_offset_;+ protected int portable_resolution_trampoline_offset_;+ protected int portable_to_interpreter_bridge_offset_;+ protected int quick_generic_jni_trampoline_offset_;+ protected int quick_imt_conflict_trampoline_offset_;+ protected int quick_resolution_trampoline_offset_;+ protected int quick_to_interpreter_bridge_offset_;+ protected int image_patch_delta_;+ protected int image_file_location_oat_checksum_;+ protected int image_file_location_oat_data_begin_;+ protected int key_value_store_size_;++ protected List<String> orderedKeyList = new ArrayList<String>();//ordered as defined+ protected Map<String, String> key_value_store_ = new HashMap<String, String>();++ protected List<OatDexFile> oatDexFileList = new ArrayList<OatDexFile>();++ OatHeader_Lollipop(BinaryReader reader) throws IOException {+ super(reader);+ adler32_checksum_ = reader.readNextInt();+ instruction_set_ = reader.readNextInt();+ instruction_set_features_ = reader.readNextInt();+ dex_file_count_ = reader.readNextInt();+ executable_offset_ = reader.readNextInt();+ interpreter_to_interpreter_bridge_offset_ = reader.readNextInt();+ interpreter_to_compiled_code_bridge_offset_ = reader.readNextInt();+ jni_dlsym_lookup_offset_ = reader.readNextInt();+ portable_imt_conflict_trampoline_offset_ = reader.readNextInt();+ portable_resolution_trampoline_offset_ = reader.readNextInt();+ portable_to_interpreter_bridge_offset_ = reader.readNextInt();+ quick_generic_jni_trampoline_offset_ = reader.readNextInt();+ quick_imt_conflict_trampoline_offset_ = reader.readNextInt();+ quick_resolution_trampoline_offset_ = reader.readNextInt();+ quick_to_interpreter_bridge_offset_ = reader.readNextInt();+ image_patch_delta_ = reader.readNextInt();+ image_file_location_oat_checksum_ = reader.readNextInt();+ image_file_location_oat_data_begin_ = reader.readNextInt();+ key_value_store_size_ = reader.readNextInt();+ }++ @Override+ public void parse(BinaryReader reader, Object additionalData) throws IOException {+ int count = 0;+ while (count < key_value_store_size_) {+ String key = reader.readNextAsciiString();+ String value = reader.readNextAsciiString();+ count += key.length() + 1;+ count += value.length() + 1;+ key_value_store_.put(key, value);+ orderedKeyList.add(key);+ }++ for (int i = 0; i < dex_file_count_; ++i) {+ oatDexFileList+ .add(OatDexFileFactory.getOatDexFile(reader, getVersion(), additionalData));+ }+ }++ @Override+ public int getDexFileCount() {+ return dex_file_count_;+ }++ @Override+ public int getKeyValueStoreSize() {+ return key_value_store_size_;+ }++ @Override+ public List<OatDexFile> getOatDexFileList() {+ return oatDexFileList;+ }++ @Override+ public OatInstructionSet getInstructionSet() {+ return OatInstructionSet.valueOf(instruction_set_);+ }++ @Override+ public int getExecutableOffset() {+ return executable_offset_;+ }++ @Override+ public int getChecksum() {+ return adler32_checksum_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatHeader_Lollipop.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "adler32_checksum_", null);+ structure.add(DWORD, OatInstructionSet.DISPLAY_NAME, null);+ structure.add(DWORD, "instruction_set_features_", null);+ structure.add(DWORD, "dex_file_count_", null);+ structure.add(DWORD, "executable_offset_", null);+ structure.add(DWORD, "interpreter_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "interpreter_to_compiled_code_bridge_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_offset_", null);+ structure.add(DWORD, "portable_imt_conflict_trampoline_offset_", null);+ structure.add(DWORD, "portable_resolution_trampoline_offset_", null);+ structure.add(DWORD, "portable_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "quick_generic_jni_trampoline_offset_", null);+ structure.add(DWORD, "quick_imt_conflict_trampoline_offset_", null);+ structure.add(DWORD, "quick_resolution_trampoline_offset_", null);+ structure.add(DWORD, "quick_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "image_patch_delta_", null);+ structure.add(DWORD, "image_file_location_oat_checksum_", null);+ structure.add(DWORD, "image_file_location_oat_data_begin_", null);+ structure.add(DWORD, "key_value_store_size_", null);+ for (int i = 0; i < orderedKeyList.size(); ++i) {+ String key = orderedKeyList.get(i);+ String value = key_value_store_.get(key);+ structure.add(STRING, key.length() + 1, "key_value_store_[" + i + "].key", null);+ structure.add(STRING, value.length() + 1, "key_value_store_[" + i + "].value", null);+ }+ for (int i = 0; i < oatDexFileList.size(); ++i) {+ DataType dataType = oatDexFileList.get(i).toDataType();+ structure.add(dataType, dataType.getName(), null);+ }+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Marshmallow.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Marshmallow.javanew file mode 100644index 0000000000..544a481807--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Marshmallow.java@@ -0,0 +1,186 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.*;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ */+class OatHeader_Marshmallow extends OatHeader {++ protected int adler32_checksum_;+ protected int instruction_set_;+ protected int instruction_set_features_bitmap_;+ protected int dex_file_count_;+ protected int executable_offset_;+ protected int interpreter_to_interpreter_bridge_offset_;+ protected int interpreter_to_compiled_code_bridge_offset_;+ protected int jni_dlsym_lookup_offset_;+ protected int quick_generic_jni_trampoline_offset_;+ protected int quick_imt_conflict_trampoline_offset_;+ protected int quick_resolution_trampoline_offset_;+ protected int quick_to_interpreter_bridge_offset_;+ protected int image_patch_delta_;+ protected int image_file_location_oat_checksum_;+ protected int image_file_location_oat_data_begin_;+ protected int key_value_store_size_;++ protected List<String> orderedKeyList = new ArrayList<String>();//ordered as defined+ protected Map<String, String> key_value_store_ = new HashMap<String, String>();++ protected List<OatDexFile> oatDexFileList = new ArrayList<OatDexFile>();++ OatHeader_Marshmallow(BinaryReader reader) throws IOException {+ super(reader);++ adler32_checksum_ = reader.readNextInt();+ instruction_set_ = reader.readNextInt();+ instruction_set_features_bitmap_ = reader.readNextInt();+ dex_file_count_ = reader.readNextInt();+ executable_offset_ = reader.readNextInt();+ interpreter_to_interpreter_bridge_offset_ = reader.readNextInt();+ interpreter_to_compiled_code_bridge_offset_ = reader.readNextInt();+ jni_dlsym_lookup_offset_ = reader.readNextInt();+ quick_generic_jni_trampoline_offset_ = reader.readNextInt();+ quick_imt_conflict_trampoline_offset_ = reader.readNextInt();+ quick_resolution_trampoline_offset_ = reader.readNextInt();+ quick_to_interpreter_bridge_offset_ = reader.readNextInt();+ image_patch_delta_ = reader.readNextInt();+ image_file_location_oat_checksum_ = reader.readNextInt();+ image_file_location_oat_data_begin_ = reader.readNextInt();+ key_value_store_size_ = reader.readNextInt();+ }++ @Override+ public void parse(BinaryReader reader, Object additionalData)+ throws IOException, UnsupportedOatVersionException {+ int count = 0;+ while (count < key_value_store_size_) {+ String key = reader.readNextAsciiString();+ String value = reader.readNextAsciiString();+ count += key.length() + 1;+ count += value.length() + 1;+ key_value_store_.put(key, value);+ orderedKeyList.add(key);+ }++ for (int i = 0; i < dex_file_count_; ++i) {+ oatDexFileList+ .add(OatDexFileFactory.getOatDexFile(reader, getVersion(), additionalData));+ }+ }++ @Override+ public int getDexFileCount() {+ return dex_file_count_;+ }++ @Override+ public int getKeyValueStoreSize() {+ return key_value_store_size_;+ }++ @Override+ public List<OatDexFile> getOatDexFileList() {+ return Collections.unmodifiableList(oatDexFileList);+ }++ @Override+ public OatInstructionSet getInstructionSet() {+ return OatInstructionSet.valueOf(instruction_set_);+ }++ @Override+ public int getExecutableOffset() {+ return executable_offset_;+ }++ public int getInterpreterToInterpreterBridgeOffset() {+ return interpreter_to_interpreter_bridge_offset_;+ }++ public int getInstructionSetFeaturesBitmap() {+ return instruction_set_features_bitmap_;+ }++ public int getJniDlsymLookupOffset() {+ return jni_dlsym_lookup_offset_;+ }++ public int getQuickGenericJniTrampolineOffset() {+ return quick_generic_jni_trampoline_offset_;+ }++ public int getQuickImtConflictTrampolineOffset() {+ return quick_imt_conflict_trampoline_offset_;+ }++ public int getQuickResolutionTrampolineOffset() {+ return quick_resolution_trampoline_offset_;+ }++ public int getQuickToInterpreterBridgeOffset() {+ return quick_to_interpreter_bridge_offset_;+ }++ @Override+ public int getChecksum() {+ return adler32_checksum_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatHeader_Marshmallow.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "adler32_checksum_", null);+ structure.add(DWORD, OatInstructionSet.DISPLAY_NAME, null);+ structure.add(DWORD, "instruction_set_features_bitmap_", null);+ structure.add(DWORD, "dex_file_count_", null);+ structure.add(DWORD, "executable_offset_", null);+ structure.add(DWORD, "interpreter_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "interpreter_to_compiled_code_bridge_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_offset_", null);+ structure.add(DWORD, "quick_generic_jni_trampoline_offset_", null);+ structure.add(DWORD, "quick_imt_conflict_trampoline_offset_", null);+ structure.add(DWORD, "quick_resolution_trampoline_offset_", null);+ structure.add(DWORD, "quick_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "image_patch_delta_", null);+ structure.add(DWORD, "image_file_location_oat_checksum_", null);+ structure.add(DWORD, "image_file_location_oat_data_begin_", null);+ structure.add(DWORD, "key_value_store_size_", null);+ for (int i = 0; i < orderedKeyList.size(); ++i) {+ String key = orderedKeyList.get(i);+ String value = key_value_store_.get(key);+ structure.add(STRING, key.length() + 1, "key_value_store_[" + i + "].key", null);+ structure.add(STRING, value.length() + 1, "key_value_store_[" + i + "].value", null);+ }+ for (int i = 0; i < oatDexFileList.size(); ++i) {+ DataType dataType = oatDexFileList.get(i).toDataType();+ structure.add(dataType, dataType.getName(), null);+ }+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Nougat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Nougat.javanew file mode 100644index 0000000000..10db04d2ac--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Nougat.java@@ -0,0 +1,43 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++public class OatHeader_Nougat extends OatHeader_Marshmallow {++ OatHeader_Nougat(BinaryReader reader) throws IOException {+ super(reader);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = super.toDataType();+ try {+ String className = StructConverterUtil.parseName(OatHeader_Nougat.class);+ dataType.setName(className);+ }+ catch (Exception e) {+ //ignore+ }+ return dataType;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Oreo.javanew file mode 100644index 0000000000..b95b7ae809--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Oreo.java@@ -0,0 +1,43 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++public class OatHeader_Oreo extends OatHeader_Marshmallow {++ OatHeader_Oreo(BinaryReader reader) throws IOException {+ super(reader);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = super.toDataType();+ try {+ String className = StructConverterUtil.parseName(OatHeader_Oreo.class);+ dataType.setName(className);+ }+ catch (Exception e) {+ //ignore+ }+ return dataType;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Oreo_M2.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Oreo_M2.javanew file mode 100644index 0000000000..3b2f307c87--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Oreo_M2.java@@ -0,0 +1,191 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.*;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ */+class OatHeader_Oreo_M2 extends OatHeader {++ protected int adler32_checksum_;+ protected int instruction_set_;+ protected int instruction_set_features_bitmap_;+ protected int dex_file_count_;+ protected int oat_dex_files_offset_;+ protected int executable_offset_;+ protected int interpreter_to_interpreter_bridge_offset_;+ protected int interpreter_to_compiled_code_bridge_offset_;+ protected int jni_dlsym_lookup_offset_;+ protected int quick_generic_jni_trampoline_offset_;+ protected int quick_imt_conflict_trampoline_offset_;+ protected int quick_resolution_trampoline_offset_;+ protected int quick_to_interpreter_bridge_offset_;+ protected int image_patch_delta_;+ protected int image_file_location_oat_checksum_;+ protected int image_file_location_oat_data_begin_;+ protected int key_value_store_size_;++ protected List<String> orderedKeyList = new ArrayList<String>();//ordered as defined+ protected Map<String, String> key_value_store_ = new HashMap<String, String>();++ protected List<OatDexFile> oatDexFileList = new ArrayList<OatDexFile>();++ OatHeader_Oreo_M2(BinaryReader reader) throws IOException {+ super(reader);++ adler32_checksum_ = reader.readNextInt();+ instruction_set_ = reader.readNextInt();+ instruction_set_features_bitmap_ = reader.readNextInt();+ dex_file_count_ = reader.readNextInt();+ oat_dex_files_offset_ = reader.readNextInt();+ executable_offset_ = reader.readNextInt();+ interpreter_to_interpreter_bridge_offset_ = reader.readNextInt();+ interpreter_to_compiled_code_bridge_offset_ = reader.readNextInt();+ jni_dlsym_lookup_offset_ = reader.readNextInt();+ quick_generic_jni_trampoline_offset_ = reader.readNextInt();+ quick_imt_conflict_trampoline_offset_ = reader.readNextInt();+ quick_resolution_trampoline_offset_ = reader.readNextInt();+ quick_to_interpreter_bridge_offset_ = reader.readNextInt();+ image_patch_delta_ = reader.readNextInt();+ image_file_location_oat_checksum_ = reader.readNextInt();+ image_file_location_oat_data_begin_ = reader.readNextInt();+ key_value_store_size_ = reader.readNextInt();+ }++ @Override+ public void parse(BinaryReader reader, Object additionalData)+ throws IOException, UnsupportedOatVersionException {+ int count = 0;+ while (count < key_value_store_size_) {+ String key = reader.readNextAsciiString();+ String value = reader.readNextAsciiString();+ count += key.length() + 1;+ count += value.length() + 1;+ key_value_store_.put(key, value);+ orderedKeyList.add(key);+ }++ reader.setPointerIndex(oat_dex_files_offset_);++ for (int i = 0; i < dex_file_count_; ++i) {+ oatDexFileList+ .add(OatDexFileFactory.getOatDexFile(reader, getVersion(), additionalData));+ }+ }++ @Override+ public int getDexFileCount() {+ return dex_file_count_;+ }++ @Override+ public int getKeyValueStoreSize() {+ return key_value_store_size_;+ }++ @Override+ public List<OatDexFile> getOatDexFileList() {+ return Collections.unmodifiableList(oatDexFileList);+ }++ @Override+ public OatInstructionSet getInstructionSet() {+ return OatInstructionSet.valueOf(instruction_set_);+ }++ @Override+ public int getExecutableOffset() {+ return executable_offset_;+ }++ public int getInterpreterToInterpreterBridgeOffset() {+ return interpreter_to_interpreter_bridge_offset_;+ }++ public int getInstructionSetFeaturesBitmap() {+ return instruction_set_features_bitmap_;+ }++ public int getJniDlsymLookupOffset() {+ return jni_dlsym_lookup_offset_;+ }++ public int getQuickGenericJniTrampolineOffset() {+ return quick_generic_jni_trampoline_offset_;+ }++ public int getQuickImtConflictTrampolineOffset() {+ return quick_imt_conflict_trampoline_offset_;+ }++ public int getQuickResolutionTrampolineOffset() {+ return quick_resolution_trampoline_offset_;+ }++ public int getQuickToInterpreterBridgeOffset() {+ return quick_to_interpreter_bridge_offset_;+ }++ @Override+ public int getChecksum() {+ return adler32_checksum_;+ }++ public int getOatDexFilesOffset() {+ return oat_dex_files_offset_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatHeader_Oreo_M2.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "adler32_checksum_", null);+ structure.add(DWORD, OatInstructionSet.DISPLAY_NAME, null);+ structure.add(DWORD, "instruction_set_features_bitmap_", null);+ structure.add(DWORD, "dex_file_count_", null);+ structure.add(DWORD, "oat_dex_files_offset_", null);+ structure.add(DWORD, "executable_offset_", null);+ structure.add(DWORD, "interpreter_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "interpreter_to_compiled_code_bridge_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_offset_", null);+ structure.add(DWORD, "quick_generic_jni_trampoline_offset_", null);+ structure.add(DWORD, "quick_imt_conflict_trampoline_offset_", null);+ structure.add(DWORD, "quick_resolution_trampoline_offset_", null);+ structure.add(DWORD, "quick_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "image_patch_delta_", null);+ structure.add(DWORD, "image_file_location_oat_checksum_", null);+ structure.add(DWORD, "image_file_location_oat_data_begin_", null);+ structure.add(DWORD, "key_value_store_size_", null);+ for (int i = 0; i < orderedKeyList.size(); ++i) {+ String key = orderedKeyList.get(i);+ String value = key_value_store_.get(key);+ structure.add(STRING, key.length() + 1, "key_value_store_[" + i + "].key", null);+ structure.add(STRING, value.length() + 1, "key_value_store_[" + i + "].value", null);+ }+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Pie.javanew file mode 100644index 0000000000..ab42f52b91--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatHeader_Pie.java@@ -0,0 +1,161 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.*;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/oat.h+ */+class OatHeader_Pie extends OatHeader {++ protected int adler32_checksum_;+ protected int instruction_set_;+ protected int instruction_set_features_bitmap_;+ protected int dex_file_count_;+ protected int oat_dex_files_offset_;+ protected int executable_offset_;+ protected int interpreter_to_interpreter_bridge_offset_;+ protected int interpreter_to_compiled_code_bridge_offset_;+ protected int jni_dlsym_lookup_offset_;+ protected int quick_generic_jni_trampoline_offset_;+ protected int quick_imt_conflict_trampoline_offset_;+ protected int quick_resolution_trampoline_offset_;+ protected int quick_to_interpreter_bridge_offset_;+ protected int image_patch_delta_;+ protected int image_file_location_oat_checksum_;+ protected int image_file_location_oat_data_begin_;+ protected int key_value_store_size_;++ protected List<String> orderedKeyList = new ArrayList<String>();//ordered as defined+ protected Map<String, String> key_value_store_ = new HashMap<String, String>();++ protected List<OatDexFile> oatDexFileList = new ArrayList<OatDexFile>();++ OatHeader_Pie(BinaryReader reader) throws IOException {+ super(reader);+ adler32_checksum_ = reader.readNextInt();+ instruction_set_ = reader.readNextInt();+ instruction_set_features_bitmap_ = reader.readNextInt();+ dex_file_count_ = reader.readNextInt();+ oat_dex_files_offset_ = reader.readNextInt();+ executable_offset_ = reader.readNextInt();+ interpreter_to_interpreter_bridge_offset_ = reader.readNextInt();+ interpreter_to_compiled_code_bridge_offset_ = reader.readNextInt();+ jni_dlsym_lookup_offset_ = reader.readNextInt();+ quick_generic_jni_trampoline_offset_ = reader.readNextInt();+ quick_imt_conflict_trampoline_offset_ = reader.readNextInt();+ quick_resolution_trampoline_offset_ = reader.readNextInt();+ quick_to_interpreter_bridge_offset_ = reader.readNextInt();+ image_patch_delta_ = reader.readNextInt();+ image_file_location_oat_checksum_ = reader.readNextInt();+ image_file_location_oat_data_begin_ = reader.readNextInt();+ key_value_store_size_ = reader.readNextInt();+ }++ @Override+ public void parse(BinaryReader reader, Object additionalData)+ throws IOException, UnsupportedOatVersionException {+ int count = 0;+ while (count < key_value_store_size_) {+ String key = reader.readNextAsciiString();+ String value = reader.readNextAsciiString();+ count += key.length() + 1;+ count += value.length() + 1;+ key_value_store_.put(key, value);+ orderedKeyList.add(key);+ }++ reader.setPointerIndex(oat_dex_files_offset_);+ for (int i = 0; i < dex_file_count_; ++i) {+ oatDexFileList+ .add(OatDexFileFactory.getOatDexFile(reader, getVersion(), additionalData));+ }+ }++ @Override+ public int getDexFileCount() {+ return dex_file_count_;+ }++ @Override+ public int getKeyValueStoreSize() {+ return key_value_store_size_;+ }++ @Override+ public List<OatDexFile> getOatDexFileList() {+ return oatDexFileList;+ }++ @Override+ public OatInstructionSet getInstructionSet() {+ return OatInstructionSet.valueOf(instruction_set_);+ }++ @Override+ public int getExecutableOffset() {+ return executable_offset_;+ }++ @Override+ public int getChecksum() {+ return adler32_checksum_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatHeader_Pie.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "adler32_checksum_", null);+ structure.add(DWORD, OatInstructionSet.DISPLAY_NAME, null);+ structure.add(DWORD, "instruction_set_features_bitmap_", null);+ structure.add(DWORD, "dex_file_count_", null);+ structure.add(DWORD, "oat_dex_files_offset_", null);+ structure.add(DWORD, "executable_offset_", null);+ structure.add(DWORD, "interpreter_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "interpreter_to_compiled_code_bridge_offset_", null);+ structure.add(DWORD, "jni_dlsym_lookup_offset_", null);+ structure.add(DWORD, "quick_generic_jni_trampoline_offset_", null);+ structure.add(DWORD, "quick_imt_conflict_trampoline_offset_", null);+ structure.add(DWORD, "quick_resolution_trampoline_offset_", null);+ structure.add(DWORD, "quick_to_interpreter_bridge_offset_", null);+ structure.add(DWORD, "image_patch_delta_", null);+ structure.add(DWORD, "image_file_location_oat_checksum_", null);+ structure.add(DWORD, "image_file_location_oat_data_begin_", null);+ structure.add(DWORD, "key_value_store_size_", null);+ for (int i = 0; i < orderedKeyList.size(); ++i) {+ String key = orderedKeyList.get(i);+ String value = key_value_store_.get(key);+ structure.add(STRING, key.length() + 1, "key_value_store_[" + i + "].key", null);+ structure.add(STRING, value.length() + 1, "key_value_store_[" + i + "].value", null);+ }+// for ( int i = 0 ; i < oatDexFileList.size( ) ; ++i ) {+// DataType dataType = oatDexFileList.get( i ).toDataType( );+// structure.add( dataType, dataType.getName( ), null );+// }+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatInstructionSet.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatInstructionSet.javanew file mode 100644index 0000000000..a2a8b70d45--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatInstructionSet.java@@ -0,0 +1,35 @@+/* ###+ * 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.android.oat;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-release/runtime/instruction_set.h#29+ */+public enum OatInstructionSet {+ kNone, kArm, kArm64, kThumb2, kX86, kX86_64, kMips, kMips64;++ public final static String DISPLAY_NAME = "instruction_set_";++ public static OatInstructionSet valueOf(int instructionSet) {+ try {+ return OatInstructionSet.values()[instructionSet];+ }+ catch (Exception e) {+ return null;+ }+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets.javanew file mode 100644index 0000000000..d2073918c5--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets.java@@ -0,0 +1,57 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-mr1-release/runtime/oat.h#163+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-wear-release/runtime/oat.h#165+ * https://android.googlesource.com/platform/art/+/refs/heads/marshmallow-release/runtime/oat.h#162+ * https://android.googlesource.com/platform/art/+/refs/heads/nougat-release/runtime/oat.h#172+ * https://android.googlesource.com/platform/art/+/refs/heads/nougat-mr1-release/runtime/oat.h#172+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-release/runtime/oat.h#172+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-dr3-release/runtime/oat.h#172+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-m2-release/runtime/oat.h#176+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/oat.h#177+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/oat.h#150+ * https://android.googlesource.com/platform/art/+/refs/heads/android11-release/runtime/oat_file.h#75+ */+public class OatMethodOffsets implements StructConverter {++ protected int code_offset_;++ public OatMethodOffsets(BinaryReader reader) throws IOException {+ code_offset_ = reader.readNextInt();+ }++ public int getCodeOffset() {+ return code_offset_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(OatMethodOffsets.class);+ dataType.setCategoryPath(new CategoryPath("/oat"));+ return dataType;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsetsFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsetsFactory.javanew file mode 100644index 0000000000..d9d5e23c32--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsetsFactory.java@@ -0,0 +1,37 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;++public final class OatMethodOffsetsFactory {++ public final static OatMethodOffsets getOatMethodOffsets(BinaryReader reader, String oatVersion)+ throws IOException {+ if (oatVersion.equals(OatConstants.VERSION_KITKAT_RELEASE)) {+ return new OatMethodOffsets_KitKat(reader);+ }+ else if (oatVersion.equals(OatConstants.VERSION_LOLLIPOP_RELEASE)) {+ return new OatMethodOffsets_Lollipop(reader);+ }+ else {+ return new OatMethodOffsets(reader);+ }+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets_KitKat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets_KitKat.javanew file mode 100644index 0000000000..c37487d80d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets_KitKat.java@@ -0,0 +1,85 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/kitkat-release/runtime/oat.h#107+ *+ */+public class OatMethodOffsets_KitKat extends OatMethodOffsets {++ private int frame_size_in_bytes_;+ private int core_spill_mask_;+ private int fp_spill_mask_;+ private int mapping_table_offset_;+ private int vmap_table_offset_;+ private int gc_map_offset_;++ public OatMethodOffsets_KitKat(BinaryReader reader) throws IOException {+ super(reader);+ frame_size_in_bytes_ = reader.readNextInt();+ core_spill_mask_ = reader.readNextInt();+ fp_spill_mask_ = reader.readNextInt();+ mapping_table_offset_ = reader.readNextInt();+ vmap_table_offset_ = reader.readNextInt();+ gc_map_offset_ = reader.readNextInt();+ }++ public int getFrameSizeInBytes() {+ return frame_size_in_bytes_;+ }++ public int getCoreSpillMask() {+ return core_spill_mask_;+ }++ public int getFpSpillMask() {+ return fp_spill_mask_;+ }++ public int getMappingTableOffset() {+ return mapping_table_offset_;+ }++ public int getVmapTableOffset() {+ return vmap_table_offset_;+ }++ public int getGcMapOffset() {+ return gc_map_offset_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ structure.add(DWORD, "frame_size_in_bytes_", null);+ structure.add(DWORD, "core_spill_mask_", null);+ structure.add(DWORD, "fp_spill_mask_", null);+ structure.add(DWORD, "mapping_table_offset_", null);+ structure.add(DWORD, "vmap_table_offset_", null);+ structure.add(DWORD, "gc_map_offset_", null);+ structure.add(DWORD, "gc_map_offset_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets_Lollipop.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets_Lollipop.javanew file mode 100644index 0000000000..b19f44a617--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatMethodOffsets_Lollipop.java@@ -0,0 +1,49 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ *+ * https://android.googlesource.com/platform/art/+/lollipop-release/runtime/oat.h#161+ *+ */+public class OatMethodOffsets_Lollipop extends OatMethodOffsets {++ private int gc_map_offset_;++ public OatMethodOffsets_Lollipop(BinaryReader reader) throws IOException {+ super(reader);+ gc_map_offset_ = reader.readNextInt();+ }++ public int getGcMapOffset() {+ return gc_map_offset_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ Structure structure = (Structure) super.toDataType();+ structure.add(DWORD, "gc_map_offset_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader.javanew file mode 100644index 0000000000..b910e34c07--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader.java@@ -0,0 +1,24 @@+/* ###+ * 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.android.oat;++import ghidra.app.util.bin.StructConverter;++public abstract class OatQuickMethodHeader implements StructConverter {++ protected abstract int getCodeSize();++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeaderFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeaderFactory.javanew file mode 100644index 0000000000..0c0d99a70c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeaderFactory.java@@ -0,0 +1,70 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;++public final class OatQuickMethodHeaderFactory {++ public final static int getOatQuickMethodHeaderSize(String oatVersion) throws IOException {+ switch (oatVersion) {+ case OatConstants.VERSION_LOLLIPOP_RELEASE:+ return 12 + QuickMethodFrameInfo.SIZE;+ case OatConstants.VERSION_LOLLIPOP_MR1_FI_RELEASE:+ case OatConstants.VERSION_LOLLIPOP_WEAR_RELEASE:+ case OatConstants.VERSION_MARSHMALLOW_RELEASE:+ return 16 + QuickMethodFrameInfo.SIZE;+ case OatConstants.VERSION_NOUGAT_RELEASE:+ case OatConstants.VERSION_NOUGAT_MR1_RELEASE:+ return 8 + QuickMethodFrameInfo.SIZE;+ case OatConstants.VERSION_OREO_RELEASE:+ case OatConstants.VERSION_OREO_M2_RELEASE:+ case OatConstants.VERSION_OREO_DR3_RELEASE:+ case OatConstants.VERSION_PIE_RELEASE:+ return 12 + QuickMethodFrameInfo.SIZE;+ case OatConstants.VERSION_10_RELEASE:+ case OatConstants.VERSION_11_RELEASE:+ return 8;+ }+ throw new IOException("OatQuickMethodHeader unsupported OAT version: " + oatVersion);+ }++ public final static OatQuickMethodHeader getOatQuickMethodHeader(BinaryReader reader,+ String oatVersion) throws IOException {+ switch (oatVersion ) {+ case OatConstants.VERSION_LOLLIPOP_RELEASE:+ return new OatQuickMethodHeader_Lollipop(reader);+ case OatConstants.VERSION_LOLLIPOP_MR1_FI_RELEASE:+ case OatConstants.VERSION_LOLLIPOP_WEAR_RELEASE:+ case OatConstants.VERSION_MARSHMALLOW_RELEASE:+ return new OatQuickMethodHeader_LollipopMR1(reader);+ case OatConstants.VERSION_NOUGAT_RELEASE:+ case OatConstants.VERSION_NOUGAT_MR1_RELEASE:+ return new OatQuickMethodHeader_Nougat(reader);+ case OatConstants.VERSION_OREO_RELEASE:+ case OatConstants.VERSION_OREO_M2_RELEASE:+ case OatConstants.VERSION_OREO_DR3_RELEASE:+ case OatConstants.VERSION_PIE_RELEASE:+ return new OatQuickMethodHeader_Oreo(reader);+ case OatConstants.VERSION_10_RELEASE:+ case OatConstants.VERSION_11_RELEASE:+ return new OatQuickMethodHeader_Android10(reader);+ }+ throw new IOException("OatQuickMethodHeader unsupported OAT version: " + oatVersion);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Android10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Android10.javanew file mode 100644index 0000000000..c24ff0aaf3--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Android10.java@@ -0,0 +1,73 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/oat_quick_method_header.h#158+ * https://android.googlesource.com/platform/art/+/refs/heads/android11-release/runtime/oat_quick_method_header.h#175+ */+public class OatQuickMethodHeader_Android10 extends OatQuickMethodHeader {+ private int vmap_table_offset_;+ private int code_size_;+ private byte[] code_;++ OatQuickMethodHeader_Android10(BinaryReader reader) throws IOException {+ vmap_table_offset_ = reader.readNextInt();+ code_size_ = reader.readNextInt();+ code_ = reader.readNextByteArray(code_size_);+ }++ /**+ * The offset in bytes from the start of the vmap table to the end of the header.+ * @return the VMAP table offset+ */+ public int getVmapTableOffset() {+ return vmap_table_offset_;+ }++ /**+ * The code size in bytes.+ * @return the code size+ */+ public int getCodeSize() {+ return code_size_;+ }++ /**+ * The actual code.+ * @return the actual code bytes+ */+ public byte[] getCode() {+ return code_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatQuickMethodHeader_Android10.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(DWORD, "vmap_table_offset_", null);+ structure.add(DWORD, "code_size_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Lollipop.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Lollipop.javanew file mode 100644index 0000000000..52d62660fb--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Lollipop.java@@ -0,0 +1,83 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-release/runtime/oat.h#185+ */+public class OatQuickMethodHeader_Lollipop extends OatQuickMethodHeader {+ private int mapping_table_offset_;+ private int vmap_table_offset_;+ private QuickMethodFrameInfo frame_info_;+ private int code_size_;++ OatQuickMethodHeader_Lollipop(BinaryReader reader) throws IOException {+ mapping_table_offset_ = reader.readNextInt();+ vmap_table_offset_ = reader.readNextInt();+ frame_info_ = new QuickMethodFrameInfo(reader);+ code_size_ = reader.readNextInt();+ }++ /**+ * The offset in bytes from the start of the mapping table to the end of the header.+ * @return offset in bytes+ */+ public int getMappingTableOffset() {+ return mapping_table_offset_;+ }++ /**+ * The offset in bytes from the start of the vmap table to the end of the header.+ * @return the VMAP table offset+ */+ public int getVmapTableOffset() {+ return vmap_table_offset_;+ }++ /**+ * The stack frame information.+ * @return the stack frame+ */+ public QuickMethodFrameInfo getFrameInfo() {+ return frame_info_;+ }++ /**+ * The code size in bytes.+ * @return the code size in bytes+ */+ public int getCodeSize() {+ return code_size_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatQuickMethodHeader_Lollipop.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(DWORD, "mapping_table_offset_", null);+ structure.add(DWORD, "vmap_table_offset_", null);+ structure.add(frame_info_.toDataType(), "frame_info_", null);+ structure.add(DWORD, "code_size_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_LollipopMR1.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_LollipopMR1.javanew file mode 100644index 0000000000..bf9b10bf35--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_LollipopMR1.java@@ -0,0 +1,96 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-mr1-fi-release/runtime/oat.h#182+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-wear-release/runtime/oat.h#184+ * https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/oat.h#185+ */+public class OatQuickMethodHeader_LollipopMR1 extends OatQuickMethodHeader {+ private int mapping_table_offset_;+ private int vmap_table_offset_;+ private int gc_map_offset_;+ private QuickMethodFrameInfo frame_info_;+ private int code_size_;++ OatQuickMethodHeader_LollipopMR1(BinaryReader reader) throws IOException {+ mapping_table_offset_ = reader.readNextInt();+ vmap_table_offset_ = reader.readNextInt();+ gc_map_offset_ = reader.readNextInt();+ frame_info_ = new QuickMethodFrameInfo(reader);+ code_size_ = reader.readNextInt();+ }++ /**+ * The offset in bytes from the start of the mapping table to the end of the header.+ * @return offset in bytes+ */+ public int getMappingTableOffset() {+ return mapping_table_offset_;+ }++ /**+ * The offset in bytes from the start of the vmap table to the end of the header.+ * @return VMAP table offset+ */+ public int getVmapTableOffset() {+ return vmap_table_offset_;+ }++ /**+ * The offset in bytes from the start of the gc map to the end of the header.+ * @return GC Map offset+ */+ public int getGcMapOffset() {+ return gc_map_offset_;+ }++ /**+ * The stack frame information.+ * @return the stack frame+ */+ public QuickMethodFrameInfo getFrameInfo() {+ return frame_info_;+ }++ /**+ * The code size in bytes.+ * @return code size in bytes+ */+ public int getCodeSize() {+ return code_size_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatQuickMethodHeader_LollipopMR1.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(DWORD, "mapping_table_offset_", null);+ structure.add(DWORD, "vmap_table_offset_", null);+ structure.add(DWORD, "gc_map_offset_", null);+ structure.add(frame_info_.toDataType(), "frame_info_", null);+ structure.add(DWORD, "code_size_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Nougat.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Nougat.javanew file mode 100644index 0000000000..100fe42f4c--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Nougat.java@@ -0,0 +1,87 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/nougat-release/runtime/oat_quick_method_header.h#128+ * https://android.googlesource.com/platform/art/+/nougat-mr1-release/runtime/oat_quick_method_header.h#128+ */+public class OatQuickMethodHeader_Nougat extends OatQuickMethodHeader {++ final static int SIZE = 16 + QuickMethodFrameInfo.SIZE;++ private int mapping_table_offset_;+ private QuickMethodFrameInfo frame_info_;+ private int code_size_;+ private byte[] code_;++ OatQuickMethodHeader_Nougat(BinaryReader reader) throws IOException {+ mapping_table_offset_ = reader.readNextInt();+ frame_info_ = new QuickMethodFrameInfo(reader);+ code_size_ = reader.readNextInt();+ code_ = reader.readNextByteArray(code_size_);+ }++ /**+ * The offset in bytes from the start of the mapping table to the end of the header.+ * @return offset in bytes+ */+ public int getMappingTableOffset() {+ return mapping_table_offset_;+ }++ /**+ * The stack frame information.+ * @return the stack frame+ */+ public QuickMethodFrameInfo getFrameInfo() {+ return frame_info_;+ }++ /**+ * The code size in bytes.+ * @return the code size+ */+ public int getCodeSize() {+ return code_size_;+ }++ /**+ * The actual code.+ * @return the actual code bytes+ */+ public byte[] getCode() {+ return code_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatQuickMethodHeader_Nougat.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(DWORD, "mapping_table_offset_", null);+ structure.add(frame_info_.toDataType(), "frame_info_", null);+ structure.add(DWORD, "code_size_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Oreo.javanew file mode 100644index 0000000000..1e95d6daf9--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatQuickMethodHeader_Oreo.java@@ -0,0 +1,103 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-release/runtime/oat_quick_method_header.h#190+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-dr3-release/runtime/oat_quick_method_header.h#191+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-m2-release/runtime/oat_quick_method_header.h#191+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/oat_quick_method_header.h#191+ */+public class OatQuickMethodHeader_Oreo extends OatQuickMethodHeader {++ final static int SIZE = 16 + QuickMethodFrameInfo.SIZE;++ private int vmap_table_offset_;+ private int method_info_offset_;+ private QuickMethodFrameInfo frame_info_;+ private int code_size_;+ private byte[] code_;++ OatQuickMethodHeader_Oreo(BinaryReader reader) throws IOException {+ vmap_table_offset_ = reader.readNextInt();+ method_info_offset_ = reader.readNextInt();+ frame_info_ = new QuickMethodFrameInfo(reader);+ code_size_ = reader.readNextInt();+ code_ = reader.readNextByteArray(code_size_);+ }++ /**+ * The offset in bytes from the start of the vmap table to the end of the header.+ * @return the VMAP table offset+ */+ public int getVmapTableOffset() {+ return vmap_table_offset_;+ }++ /**+ * The offset in bytes from the start of the method info to the end of the header.+ * The method info offset is not in the CodeInfo since CodeInfo has good dedupe properties that+ * would be lost from doing so. The method info memory region contains method indices since they+ * are hard to dedupe.+ * @return offset in bytes+ */+ public int getMethodInfoOffset() {+ return method_info_offset_;+ }++ /**+ * The stack frame information.+ * @return the stack frame+ */+ public QuickMethodFrameInfo getFrameInfo() {+ return frame_info_;+ }++ /**+ * The code size in bytes. The highest bit is used to signify if the compiled+ * code with the method header has should_deoptimize flag.+ */+ public int getCodeSize() {+ return code_size_;+ }++ /**+ * The actual code.+ * @return the actual code bytes+ */+ public byte[] getCode() {+ return code_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(OatQuickMethodHeader_Oreo.class);+ Structure structure = new StructureDataType(className, 0);+ structure.add(DWORD, "vmap_table_offset_", null);+ structure.add(DWORD, "method_info_offset_", null);+ structure.add(frame_info_.toDataType(), "frame_info_", null);+ structure.add(DWORD, "code_size_", null);+ structure.setCategoryPath(new CategoryPath("/oat"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatUtilities.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatUtilities.javanew file mode 100644index 0000000000..f1dcca37e9--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/OatUtilities.java@@ -0,0 +1,140 @@+/* ###+ * 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.android.oat;++import java.math.BigInteger;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.app.util.bin.format.elf.ElfSectionHeaderConstants;+import ghidra.app.util.importer.MessageLog;+import ghidra.app.util.opinion.ElfLoader;+import ghidra.file.formats.android.dex.format.ClassDataItem;+import ghidra.file.formats.android.dex.format.EncodedMethod;+import ghidra.program.model.address.Address;+import ghidra.program.model.lang.Register;+import ghidra.program.model.lang.RegisterValue;+import ghidra.program.model.listing.ContextChangeException;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.MemoryBlock;+import ghidra.program.model.symbol.Symbol;+import ghidra.program.model.symbol.SymbolTable;++final class OatUtilities {++ /**+ * Returns a BinaryReader based at the "oatdata" symbol.+ * The ".rodata" section contains the OAT information.+ * Returns null when the "oatdata" symbol does not exist.+ */+ final static BinaryReader getBinaryReader(Program program) {+ if (OatConstants.isOAT(program)) {+ Symbol symbol = getOatDataSymbol(program);+ if (symbol != null && symbol.getName().equals(OatConstants.SYMBOL_OAT_DATA)) {+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), symbol.getAddress());+ return new BinaryReader(provider, !program.getLanguage().isBigEndian());+ }+ }+ return null;+ }++ final static boolean isELF(Program program) {+ return ElfLoader.ELF_NAME.equals(program.getExecutableFormat());+ }++ final static Symbol getOatDataSymbol(Program program) {+ if (isELF(program)) {+ MemoryBlock block = program.getMemory().getBlock(ElfSectionHeaderConstants.dot_rodata);+ if (block != null) {+ SymbolTable symbolTable = program.getSymbolTable();+ Symbol oatDataSymbol = symbolTable.getPrimarySymbol(block.getStart());+ if (oatDataSymbol != null &&+ oatDataSymbol.getName().equals(OatConstants.SYMBOL_OAT_DATA)) {+ return oatDataSymbol;+ }+ }+ }+ return null;+ }++ final static Symbol getOatExecSymbol(Program program) {+ if (isELF(program)) {+ MemoryBlock block = program.getMemory().getBlock(ElfSectionHeaderConstants.dot_text);+ if (block != null) {+ SymbolTable symbolTable = program.getSymbolTable();+ Symbol oatExecSymbol = symbolTable.getPrimarySymbol(block.getStart());+ if (oatExecSymbol != null &&+ oatExecSymbol.getName().equals(OatConstants.SYMBOL_OAT_EXEC)) {+ return oatExecSymbol;+ }+ }+ }+ return null;+ }++ final static Symbol getOatLastWordSymbol(Program program) {+ if (isELF(program)) {+ MemoryBlock block = program.getMemory().getBlock(ElfSectionHeaderConstants.dot_text);+ if (block != null) {+ SymbolTable symbolTable = program.getSymbolTable();+ List<Symbol> oatLastWordSymbols =+ symbolTable.getGlobalSymbols(OatConstants.SYMBOL_OAT_LASTWORD);+ if (oatLastWordSymbols.size() == 1) {+ return oatLastWordSymbols.get(0);+ }+ }+ }+ return null;+ }++// final static Symbol getSymbol( Program program, String name ) {+// SymbolTable symbolTable = program.getSymbolTable( );+// List< Symbol > symbols = symbolTable.getSymbols( name, program.getGlobalNamespace( ) );+// if ( symbols.size( ) != 1 ) {+// return null;//TODO+// }+// return symbols.get( 0 );+// }++ final static List<EncodedMethod> getAllMethods(ClassDataItem classDataItem) {+ List<EncodedMethod> list = new ArrayList<EncodedMethod>();+ list.addAll(classDataItem.getDirectMethods());+ list.addAll(classDataItem.getVirtualMethods());+ return list;+ }++ final static Address adjustForThumbAsNeeded(OatHeader oatHeader, Program program,+ Address address, MessageLog log) {+ long displacement = address.getOffset();+ if (oatHeader.getInstructionSet() == OatInstructionSet.kThumb2) {+ if ((displacement & 0x1) == 0x1) {//thumb code?+ address = address.subtract(1);++ Register register = program.getLanguage().getRegister("TMode");+ RegisterValue value = new RegisterValue(register, BigInteger.valueOf(1));+ try {+ program.getProgramContext().setRegisterValue(address, address, value);+ }+ catch (ContextChangeException e) {+ log.appendException(e);+ }+ }+ }+ return address;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/QuickMethodFrameInfo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/QuickMethodFrameInfo.javanew file mode 100644index 0000000000..e77784ba79--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/QuickMethodFrameInfo.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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-release/runtime/quick/quick_method_frame_info.h#53+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-mr1-fi-release/runtime/quick/quick_method_frame_info.h#54+ * https://android.googlesource.com/platform/art/+/refs/heads/lollipop-wear-release/runtime/quick/quick_method_frame_info.h#54+ * https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/quick/quick_method_frame_info.h#54+ * https://android.googlesource.com/platform/art/+/refs/heads/nougat-release/runtime/quick/quick_method_frame_info.h#57+ * https://android.googlesource.com/platform/art/+/nougat-mr1-release/runtime/quick/quick_method_frame_info.h#57+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-release/runtime/quick/quick_method_frame_info.h#57+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-dr3-release/runtime/quick/quick_method_frame_info.h#57+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-m2-release/runtime/quick/quick_method_frame_info.h#57+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/quick/quick_method_frame_info.h#57+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/quick/quick_method_frame_info.h#57+ * https://android.googlesource.com/platform/art/+/refs/heads/android11-release/runtime/quick/quick_method_frame_info.h#57+ */+public class QuickMethodFrameInfo implements StructConverter {++ final static int SIZE = 12;++ private int frame_size_in_bytes_;+ private int core_spill_mask_;+ private int fp_spill_mask_;++ QuickMethodFrameInfo(BinaryReader reader) throws IOException {+ frame_size_in_bytes_ = reader.readNextInt();+ core_spill_mask_ = reader.readNextInt();+ fp_spill_mask_ = reader.readNextInt();+ }++ public int getFrameSizeInBytes() {+ return frame_size_in_bytes_;+ }++ public int getCoreSpillMask() {+ return core_spill_mask_;+ }++ public int getFpSpillMask() {+ return fp_spill_mask_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(QuickMethodFrameInfo.class);+ dataType.setCategoryPath(new CategoryPath("/oat"));+ return dataType;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable.javanew file mode 100644index 0000000000..812d2fbbf9--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable.java@@ -0,0 +1,26 @@+/* ###+ * 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.android.oat;++import ghidra.app.util.bin.StructConverter;++/**+ * https://android.googlesource.com/platform/art/+/oreo-release/runtime/type_lookup_table.h#161+ * https://android.googlesource.com/platform/art/+/oreo-m2-release/runtime/type_lookup_table.h#161+ */+public abstract class TypeLookupTable implements StructConverter {++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTableEntry.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTableEntry.javanew file mode 100644index 0000000000..daab1c39f5--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTableEntry.java@@ -0,0 +1,64 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/oreo-release/runtime/type_lookup_table.h#100+ * https://android.googlesource.com/platform/art/+/oreo-m2-release/runtime/type_lookup_table.h#100+ * https://android.googlesource.com/platform/art/+/pie-release/runtime/type_lookup_table.h#102+ *+ *+ */+public class TypeLookupTableEntry implements StructConverter {++ private int str_offset;+ private short data;+ private short next_pos_delta;++ public TypeLookupTableEntry(BinaryReader reader) throws IOException {+ str_offset = reader.readNextInt();+ data = reader.readNextShort();+ next_pos_delta = reader.readNextShort();+ }++ public int getStringOffset() {+ return str_offset;+ }++ public short getData() {+ return data;+ }++ public short getNextPosDelta() {+ return next_pos_delta;+ }++ public boolean isEmpty() {+ return str_offset == 0;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(TypeLookupTableEntry.class);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTableEntry_Android10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTableEntry_Android10.javanew file mode 100644index 0000000000..056c41e15f--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTableEntry_Android10.java@@ -0,0 +1,55 @@+/* ###+ * 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.android.oat;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/libdexfile/dex/type_lookup_table.h#110+ * https://android.googlesource.com/platform/art/+/refs/heads/android11-release/libdexfile/dex/type_lookup_table.h#110+ */+public class TypeLookupTableEntry_Android10 implements StructConverter {++ private int str_offset;+ private short data;++ public TypeLookupTableEntry_Android10(BinaryReader reader) throws IOException {+ str_offset = reader.readNextInt();+ data = reader.readNextShort();+ }++ public int getStringOffset() {+ return str_offset;+ }++ public short getData() {+ return data;+ }++ public boolean isEmpty() {+ return str_offset == 0;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(TypeLookupTableEntry_Android10.class);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Android10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Android10.javanew file mode 100644index 0000000000..31b3626ee9--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Android10.java@@ -0,0 +1,76 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/oreo-release/runtime/type_lookup_table.h#161+ * https://android.googlesource.com/platform/art/+/oreo-m2-release/runtime/type_lookup_table.h#161+ */+public class TypeLookupTable_Android10 extends TypeLookupTable {++ private int dex_file_begin_;+ private int mask_bits_;+ private List<TypeLookupTableEntry> entries_ = new ArrayList<TypeLookupTableEntry>();+ // owns_entries_ specifies if the lookup table owns the entries_ array.+ private int owns_entries_;++ public TypeLookupTable_Android10(BinaryReader reader) throws IOException {+ // TODO Auto-generated constructor stub+ }++ public int getDexFileBegin() {+ return dex_file_begin_;+ }++ public List<TypeLookupTableEntry> getEntries() {+ return entries_;+ }++ public int getMaskBits() {+ return mask_bits_;+ }++ /**+ * owns_entries_ specifies if the lookup table owns the entries_ array.+ */+ public boolean isOwnsEntries() {+ return owns_entries_ == 0;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(getClass());+ Structure struct = new StructureDataType(className, 0);+ struct.add(DWORD, "dex_file_begin_", null);+ struct.add(DWORD, "raw_data_length_", null);+ struct.add(DWORD, "mask_", null);+ for (int i = 0; i < entries_.size(); ++i) {+ struct.add(entries_.get(i).toDataType(), "entry_" + i, null);+ }+ struct.add(DWORD, "owns_entries_", null);+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Oreo.javanew file mode 100644index 0000000000..a196f00cc8--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Oreo.java@@ -0,0 +1,81 @@+/* ###+ * 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.android.oat;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/oreo-release/runtime/type_lookup_table.h#161+ * https://android.googlesource.com/platform/art/+/oreo-m2-release/runtime/type_lookup_table.h#161+ */+public class TypeLookupTable_Oreo extends TypeLookupTable {++ private int dex_file_begin_;+ private int raw_data_length_;+ private int mask_;+ private List<TypeLookupTableEntry> entries_ = new ArrayList<TypeLookupTableEntry>();+ // owns_entries_ specifies if the lookup table owns the entries_ array.+ private int owns_entries_;++ public TypeLookupTable_Oreo(BinaryReader reader) throws IOException {+ // TODO Auto-generated constructor stub+ }++ public int getDexFileBegin() {+ return dex_file_begin_;+ }++ public int getRawDataLength() {+ return raw_data_length_;+ }++ public int getMask() {+ return mask_;+ }++ public List<TypeLookupTableEntry> getEntries() {+ return entries_;+ }++ /**+ * owns_entries_ specifies if the lookup table owns the entries_ array.+ */+ public boolean isOwnsEntries() {+ return owns_entries_ == 0;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(TypeLookupTable_Oreo.class);+ Structure struct = new StructureDataType(className, 0);+ struct.add(DWORD, "dex_file_begin_", null);+ struct.add(DWORD, "raw_data_length_", null);+ struct.add(DWORD, "mask_", null);+ for (int i = 0; i < entries_.size(); ++i) {+ struct.add(entries_.get(i).toDataType(), "entry_" + i, null);+ }+ struct.add(DWORD, "owns_entries_", null);+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Pie.javanew file mode 100644index 0000000000..ff3a608963--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/TypeLookupTable_Pie.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.android.oat;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/pie-release/runtime/type_lookup_table.h#102+ */+public class TypeLookupTable_Pie extends TypeLookupTable {++ private int dex_data_begin_;+ private int raw_data_length_;+ private int mask_;+ private List<TypeLookupTableEntry> entries_ = new ArrayList<TypeLookupTableEntry>();+ // owns_entries_ specifies if the lookup table owns the entries_ array.+ private int owns_entries_;++ public TypeLookupTable_Pie(BinaryReader reader) throws IOException {+ // TODO Auto-generated constructor stub+ }++ public int getDexDataBegin() {+ return dex_data_begin_;+ }++ public int getRawDataLength() {+ return raw_data_length_;+ }++ public int getMask() {+ return mask_;+ }++ public List<TypeLookupTableEntry> getEntries() {+ return entries_;+ }++ /**+ * owns_entries_ specifies if the lookup table owns the entries_ array.+ */+ public boolean isOwnsEntries() {+ return owns_entries_ == 0;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(TypeLookupTable_Pie.class);+ Structure struct = new StructureDataType(className, 0);+ struct.add(DWORD, "dex_data_begin_", null);+ struct.add(DWORD, "raw_data_length_", null);+ struct.add(DWORD, "mask_", null);+ for (int i = 0; i < entries_.size(); ++i) {+ struct.add(entries_.get(i).toDataType(), "entry_" + i, null);+ }+ struct.add(DWORD, "owns_entries_", null);+ return struct;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/UnsupportedOatVersionException.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/UnsupportedOatVersionException.javanew file mode 100644index 0000000000..f54ab17de6--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/UnsupportedOatVersionException.java@@ -0,0 +1,23 @@+/* ###+ * 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.android.oat;++public final class UnsupportedOatVersionException extends Exception {++ public UnsupportedOatVersionException(String magic, String version) {+ super("Unsupported OAT (" + magic + ") for version: " + version);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexConstants.javaindex bdb9c4628a..9922bd33f2 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexConstants.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexConstants.java@@ -17,6 +17,19 @@ package ghidra.file.formats.android.odex;import ghidra.app.util.bin.ByteProvider;+/**+ *+ * https://android.googlesource.com/platform/dalvik/+/refs/heads/kitkat-release/libdex/DexFile.h+ * https://android.googlesource.com/platform/dalvik/+/refs/heads/lollipop-release/libdex/DexFile.h+ * https://android.googlesource.com/platform/dalvik/+/refs/heads/marshmallow-release/libdex/DexFile.h+ * https://android.googlesource.com/platform/dalvik/+/refs/heads/nougat-release/libdex/DexFile.h+ * https://android.googlesource.com/platform/dalvik/+/refs/heads/oreo-release/libdex/DexFile.h+ * https://android.googlesource.com/platform/dalvik/+/refs/heads/pie-release/libdex/DexFile.h+ * https://android.googlesource.com/platform/dalvik/+/refs/heads/android10-release/libdex/DexFile.h+ *+ * Removed in Android11+ *+ */public final class OdexConstants {public final static String ODEX_MAGIC_35 = "dey\n035\0";@@ -25,13 +38,13 @@ public final class OdexConstants {public final static int ODEX_MAGIC_LENGTH = ODEX_MAGIC_36.length();- public final static boolean isOdexFile( ByteProvider provider ) {+ public final static boolean isOdexFile(ByteProvider provider) {try {- byte [] bytes = provider.readBytes( 0, ODEX_MAGIC_LENGTH );- return ODEX_MAGIC_35.equals( new String( bytes ) ) ||- ODEX_MAGIC_36.equals( new String( bytes ) );+ String magic = new String(provider.readBytes(0, ODEX_MAGIC_LENGTH));+ return ODEX_MAGIC_35.equals(new String(magic)) ||+ ODEX_MAGIC_36.equals(new String(magic));}- catch ( Exception e ) {+ catch (Exception e) {// ignore}return false;diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexFileSystem.javaindex fc9d27b99c..541ca8b1c5 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexFileSystem.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexFileSystem.java@@ -67,18 +67,18 @@ public class OdexFileSystem extends GFileSystemBase {public String getInfo(GFile file, TaskMonitor monitor) {StringBuilder builder = new StringBuilder();builder.append("Magic: " + odexHeader.getMagic()).append("\n");- builder.append("Dex Offset: " + Integer.toHexString(odexHeader.getDexOffset())).append(- "\n");- builder.append("Dex Length: " + Integer.toHexString(odexHeader.getDexLength())).append(- "\n");- builder.append("Deps Offset: " + Integer.toHexString(odexHeader.getDepsOffset())).append(- "\n");- builder.append("Deps Length: " + Integer.toHexString(odexHeader.getDepsLength())).append(- "\n");- builder.append("Aux Offset: " + Integer.toHexString(odexHeader.getAuxOffset())).append(- "\n");- builder.append("Aux Length: " + Integer.toHexString(odexHeader.getAuxLength())).append(- "\n");+ builder.append("Dex Offset: " + Integer.toHexString(odexHeader.getDexOffset()))+ .append("\n");+ builder.append("Dex Length: " + Integer.toHexString(odexHeader.getDexLength()))+ .append("\n");+ builder.append("Deps Offset: " + Integer.toHexString(odexHeader.getDepsOffset()))+ .append("\n");+ builder.append("Deps Length: " + Integer.toHexString(odexHeader.getDepsLength()))+ .append("\n");+ builder.append("Aux Offset: " + Integer.toHexString(odexHeader.getAuxOffset()))+ .append("\n");+ builder.append("Aux Length: " + Integer.toHexString(odexHeader.getAuxLength()))+ .append("\n");builder.append("Flags: " + Integer.toHexString(odexHeader.getFlags())).append("\n");return builder.toString();}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeader.javaindex 6c0f5dc6cc..0e9298369b 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeader.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeader.java@@ -26,7 +26,7 @@ import ghidra.util.exception.DuplicateNameException;public class OdexHeader implements StructConverter {- private byte [] magic;+ private byte[] magic;private int dexOffset;private int dexLength;private int depsOffset;@@ -35,9 +35,9 @@ public class OdexHeader implements StructConverter {private int auxLength;private int flags;private int padding;-- public OdexHeader( BinaryReader reader ) throws IOException {- magic = reader.readNextByteArray( OdexConstants.ODEX_MAGIC_LENGTH );++ public OdexHeader(BinaryReader reader) throws IOException {+ magic = reader.readNextByteArray(OdexConstants.ODEX_MAGIC_LENGTH);dexOffset = reader.readNextInt();dexLength = reader.readNextInt();depsOffset = reader.readNextInt();@@ -49,66 +49,74 @@ public class OdexHeader implements StructConverter {}public String getMagic() {- return new String( magic );+ return new String(magic);}+/*** Returns byte offset to the optimized DEX file.*/public int getDexOffset() {return dexOffset;}+/*** Returns byte length of the optimized DEX file.*/public int getDexLength() {return dexLength;}+/*** Return byte offset to the framework dependencies.*/public int getDepsOffset() {return depsOffset;}+/*** Return byte length of the framework dependencies.*/public int getDepsLength() {return depsLength;}+/*** Return byte offset to the auxiliary data.*/public int getAuxOffset() {return auxOffset;}+/*** Return byte length to the auxiliary data.*/public int getAuxLength() {return auxLength;}+/*** Return the ODEX flags.*/public int getFlags() {return flags;}+public int getPadding() {return padding;}@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {- Structure structure = new StructureDataType( "odex_header_item", 0 );- structure.add( UTF8, OdexConstants.ODEX_MAGIC_LENGTH, "magic", null );- structure.add( DWORD, "dex_offset", null );- structure.add( DWORD, "dex_length", null );- structure.add( DWORD, "deps_offset", null );- structure.add( DWORD, "deps_length", null );- structure.add( DWORD, "aux_offset", null );- structure.add( DWORD, "aux_length", null );- structure.add( DWORD, "flags", null );- structure.add( DWORD, "padding", null );+ Structure structure = new StructureDataType("odex_header_item", 0);+ structure.add(UTF8, OdexConstants.ODEX_MAGIC_LENGTH, "magic", null);+ structure.add(DWORD, "dex_offset", null);+ structure.add(DWORD, "dex_length", null);+ structure.add(DWORD, "deps_offset", null);+ structure.add(DWORD, "deps_length", null);+ structure.add(DWORD, "aux_offset", null);+ structure.add(DWORD, "aux_length", null);+ structure.add(DWORD, "flags", null);+ structure.add(DWORD, "padding", null);return structure;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeaderFormatAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeaderFormatAnalyzer.javaindex ab48f068c9..c45516810c 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeaderFormatAnalyzer.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/odex/OdexHeaderFormatAnalyzer.java@@ -35,28 +35,30 @@ import ghidra.util.task.TaskMonitor;public class OdexHeaderFormatAnalyzer extends FileFormatAnalyzer {@Override- public boolean analyze( Program program, AddressSetView set, TaskMonitor monitor, MessageLog log ) throws Exception {+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {- Address address = toAddr( program, 0x0 );+ Address address = toAddr(program, 0x0);- if ( getDataAt( program, address ) != null ) {- log.appendMsg( "data already exists." );+ if (getDataAt(program, address) != null) {+ log.appendMsg("data already exists.");return true;}- Memory memory = program.getMemory( );- MemoryBlock block = memory.getBlock( "ram" );- block.setRead( true );- block.setWrite( false );- block.setExecute( false );+ Memory memory = program.getMemory();+ MemoryBlock block = memory.getBlock("ram");+ block.setRead(true);+ block.setWrite(false);+ block.setExecute(false);- ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getMinAddress( ) );- BinaryReader reader = new BinaryReader( provider, true );+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), program.getMinAddress());+ BinaryReader reader = new BinaryReader(provider, true);- OdexHeader header = new OdexHeader( reader );+ OdexHeader header = new OdexHeader(reader);DataType headerDataType = header.toDataType();- createData( program, address, headerDataType);+ createData(program, address, headerDataType);createFragment(program, "header", address, address.add(headerDataType.getLength()));@@ -65,87 +67,88 @@ public class OdexHeaderFormatAnalyzer extends FileFormatAnalyzer {Address depsAddress = toAddr(program, header.getDepsOffset());createFragment(program, "deps", depsAddress, depsAddress.add(header.getDepsLength()));- processDeps( program, header, monitor, log );+ processDeps(program, header, monitor, log);Address auxAddress = toAddr(program, header.getAuxOffset());createFragment(program, "aux", auxAddress, auxAddress.add(header.getAuxLength()));- monitor.setMessage( "ODEX: cleaning up tree" );- removeEmptyFragments( program );+ monitor.setMessage("ODEX: cleaning up tree");+ removeEmptyFragments(program);return true;}@Override- public boolean canAnalyze( Program program ) {- ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getMinAddress( ) );- return OdexConstants.isOdexFile( provider );+ public boolean canAnalyze(Program program) {+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), program.getMinAddress());+ return OdexConstants.isOdexFile(provider);}@Override- public AnalyzerType getAnalysisType( ) {+ public AnalyzerType getAnalysisType() {return AnalyzerType.BYTE_ANALYZER;}@Override- public boolean getDefaultEnablement( Program program ) {+ public boolean getDefaultEnablement(Program program) {return true;}@Override- public String getDescription( ) {+ public String getDescription() {return "Android ODEX Header Format";}@Override- public String getName( ) {+ public String getName() {return "Android ODEX Header Format";}@Override- public AnalysisPriority getPriority( ) {- return new AnalysisPriority( 0 );+ public AnalysisPriority getPriority() {+ return new AnalysisPriority(0);}@Override- public boolean isPrototype( ) {+ public boolean isPrototype() {return false;}- private void processDeps(Program program, OdexHeader header,- TaskMonitor monitor, MessageLog log) throws Exception {+ private void processDeps(Program program, OdexHeader header, TaskMonitor monitor,+ MessageLog log) throws Exception {int depsOffset = header.getDepsOffset();int depsLength = header.getDepsLength();- Address depsAddress = toAddr( program, depsOffset );- Address depsEndAddress = depsAddress.add( depsLength );+ Address depsAddress = toAddr(program, depsOffset);+ Address depsEndAddress = depsAddress.add(depsLength);- createData( program, depsAddress, new DWordDataType() );- depsAddress = depsAddress.add( 4 );+ createData(program, depsAddress, new DWordDataType());+ depsAddress = depsAddress.add(4);- createData( program, depsAddress, new DWordDataType() );- depsAddress = depsAddress.add( 4 );+ createData(program, depsAddress, new DWordDataType());+ depsAddress = depsAddress.add(4);- createData( program, depsAddress, new DWordDataType() );- depsAddress = depsAddress.add( 4 );+ createData(program, depsAddress, new DWordDataType());+ depsAddress = depsAddress.add(4);- createData( program, depsAddress, new DWordDataType() );- depsAddress = depsAddress.add( 4 );+ createData(program, depsAddress, new DWordDataType());+ depsAddress = depsAddress.add(4);- while ( depsAddress.compareTo(depsEndAddress) < 0 ) {+ while (depsAddress.compareTo(depsEndAddress) < 0) {monitor.checkCanceled();- createData( program, depsAddress, new DWordDataType() );+ createData(program, depsAddress, new DWordDataType());int stringLength = program.getMemory().getInt(depsAddress);- depsAddress = depsAddress.add( 4 );+ depsAddress = depsAddress.add(4);program.getListing().createData(depsAddress, new StringDataType(), stringLength);- depsAddress = depsAddress.add( stringLength );+ depsAddress = depsAddress.add(stringLength);- for ( int i = 0; i < 5; ++i ) {- createData( program, depsAddress, new DWordDataType() );- depsAddress = depsAddress.add( 4 );+ for (int i = 0; i < 5; ++i) {+ createData(program, depsAddress, new DWordDataType());+ depsAddress = depsAddress.add(4);}}}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/ota_update/PayloadConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/ota_update/PayloadConstants.javanew file mode 100644index 0000000000..becee333fb--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/ota_update/PayloadConstants.java@@ -0,0 +1,56 @@+/* ###+ * 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.android.ota_update;++/**+ * https://android.googlesource.com/platform/system/update_engine/+/refs/heads/android10-release/payload_consumer/payload_constants.cc+ *+ * https://android.googlesource.com/platform/system/update_engine/+/refs/heads/android10-release/payload_generator/payload_file.h+ */+public final class PayloadConstants {++ public final static long kChromeOSMajorPayloadVersion = 1;++ public final static long kBrilloMajorPayloadVersion = 2;++ public final static int kMinSupportedMinorPayloadVersion = 1;+ public final static int kMaxSupportedMinorPayloadVersion = 6;++ public final static int kFullPayloadMinorVersion = 0;++ public final static int kInPlaceMinorPayloadVersion = 1;++ public final static int kSourceMinorPayloadVersion = 2;++ public final static int kOpSrcHashMinorPayloadVersion = 3;++ public final static int kBrotliBsdiffMinorPayloadVersion = 4;++ public final static int kPuffdiffMinorPayloadVersion = 5;++ public final static int kVerityMinorPayloadVersion = 6;++ public final static long kMinSupportedMajorPayloadVersion = 1;+ public final static long kMaxSupportedMajorPayloadVersion = 2;++ public final static long kMaxPayloadHeaderSize = 24;++ public final static String kPartitionNameKernel = "kernel";+ public final static String kPartitionNameRoot = "root";++ public final static String kDeltaMagic = "CrAU";++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileConstants.javanew file mode 100644index 0000000000..b89bd29906--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileConstants.java@@ -0,0 +1,76 @@+/* ###+ * 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.android.prof;++import java.util.Arrays;++import ghidra.app.util.bin.ByteProvider;++/**+ * Android Profiling (.PROF) files.+ *+ * "current profiles are stored next to the dex files under the oat folder"+ *+ * https://android.googlesource.com/platform/art/+/refs/heads/android11-release/libprofile/profile/profile_compilation_info.cc+ *+ * https://android.googlesource.com/platform/frameworks/native/+/master/cmds/installd/utils.cpp+ * https://android.googlesource.com/platform/frameworks/native/+/master/cmds/installd/dexopt.cpp+ *+ */+public final class ProfileConstants {++ public final static byte[] kProfileMagic = { 'p', 'r', 'o', '\0' };++ public final static int kProfileMagicLength = kProfileMagic.length;++ public final static byte[] kProfileVersion_008 = { '0', '0', '8', '\0' };+ public final static byte[] kProfileVersion_009 = { '0', '0', '9', '\0' };+ /**+ * Android 10+ * Android 11+ */+ public final static byte[] kProfileVersion_010 = { '0', '1', '0', '\0' };++ public final static byte[] kProfileVersionForBootImage_012 = { '0', '1', '2', '\0' };++ public final static String kDexMetadataProfileEntry = "primary.prof";++ public final static byte[] kProfileVersionWithCounters = { '5', '0', '0', '\0' };++ /**+ * Converts the byte array into String and trims it.+ */+ public final static String toString(byte[] bytes) {+ return new String(bytes).trim();+ }++ public static boolean isProfile(ByteProvider provider) {+ try {+ byte[] magicBytes = provider.readBytes(0, kProfileMagicLength);+ if (Arrays.equals(magicBytes, kProfileMagic)) {+ byte[] versionBytes =+ provider.readBytes(kProfileMagicLength, kProfileVersion_010.length);+ if (Arrays.equals(versionBytes, kProfileVersion_010)) {+ return true;+ }+ }+ }+ catch (Exception e) {+ // ignore+ }+ return false;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileFileSystem.javanew file mode 100644index 0000000000..0656407131--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileFileSystem.java@@ -0,0 +1,95 @@+/* ###+ * 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.android.prof;++import java.io.*;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.file.formats.zlib.ZLIB;+import ghidra.formats.gfilesystem.*;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.CryptoException;+import ghidra.util.task.TaskMonitor;++@FileSystemInfo(type = "prof", description = "PROF", factory = GFileSystemBaseFactory.class)+public class ProfileFileSystem extends GFileSystemBase {++ private ProfileHeader header;+ private GFileImpl dataFile;++ public ProfileFileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ protected InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException, CryptoException {++ if (file != null) {+ if (file.equals(dataFile)) {+ InputStream compressedStream =+ provider.getInputStream(header.getCompressedDataOffset());+ ZLIB zlib = new ZLIB();+ ByteArrayOutputStream decompressedBytes =+ zlib.decompress(compressedStream, header.getUncompressedSizeOfZippedData());+ return new ByteArrayInputStream(decompressedBytes.toByteArray());+ }+ }+ return null;+ }++ @Override+ public String getInfo(GFile file, TaskMonitor monitor) {+ StringBuilder builder = new StringBuilder();+ builder.append("Magic: " + header.getMagic()).append("\n");+ return builder.toString();+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ List<GFile> list = new ArrayList<>();+ if (directory == null || directory.equals(root)) {+ list.add(dataFile);+ }+ return list;+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ return ProfileConstants.isProfile(provider);+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {+ BinaryReader reader = new BinaryReader(provider, true);+ header = new ProfileHeader(reader);+ dataFile = GFileImpl.fromFilename(this, root, "uncompressed-data", false,+ header.getUncompressedSizeOfZippedData(), null);+ }++ @Override+ public void close() throws IOException {+ super.close();+ header = null;+ dataFile = null;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileHeader.javanew file mode 100644index 0000000000..9764846fd7--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/prof/ProfileHeader.java@@ -0,0 +1,81 @@+/* ###+ * 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.android.prof;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * <code>+ * profile_header:+ * magic (4)+ * version (4)+ * number_of_dex_files (1)+ * uncompressed_size_of_zipped_data (4)+ * compressed_data_size (4)+ * compressed data in 0x78 0x01 format+ * </code>+ */+public class ProfileHeader implements StructConverter {+ private byte[] magic;+ private byte[] version;+ private byte number_of_dex_files;+ private int uncompressed_size_of_zipped_data;+ private int compressed_data_size;+ private int _compressed_data_offset;++ public ProfileHeader(BinaryReader reader) throws IOException {+ magic = reader.readNextByteArray(ProfileConstants.kProfileMagic.length);+ version = reader.readNextByteArray(ProfileConstants.kProfileVersion_008.length);+ number_of_dex_files = reader.readNextByte();+ uncompressed_size_of_zipped_data = reader.readNextInt();+ compressed_data_size = reader.readNextInt();+ _compressed_data_offset = (int) reader.getPointerIndex();+ }++ public String getMagic() {+ return new String(magic).trim();+ }++ public String getVersion() {+ return new String(version).trim();+ }++ public byte getNumberOfDexFiles() {+ return number_of_dex_files;+ }++ public int getUncompressedSizeOfZippedData() {+ return uncompressed_size_of_zipped_data;+ }++ public int getCompressedDataSize() {+ return compressed_data_size;+ }++ public int getCompressedDataOffset() {+ return _compressed_data_offset;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ return StructConverterUtil.toDataType(ProfileHeader.class);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/DecompressionManager.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/DecompressionManager.javanew file mode 100644index 0000000000..f769b57bb1--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/DecompressionManager.java@@ -0,0 +1,153 @@+/* ###+ * 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.android.util;++import java.io.IOException;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.file.formats.android.art.*;+import ghidra.program.model.address.*;+import ghidra.program.model.listing.Program;+import ghidra.util.task.TaskMonitor;++public class DecompressionManager {++ /**+ * Decompress the bytes and pipe into a new binary reader.+ * Required to allow reading of the remainder of the ART header.+ * @param reader binary reader containing compressed bytes+ * @param compression type of compression+ * @param monitor task monitor for controlling the task+ * @return binary reader containing decompressed bytes+ * @throws IOException should an error occur reading the bytes+ */+ public static BinaryReader decompress(BinaryReader reader, ArtCompression compression,+ TaskMonitor monitor) throws IOException {+ if (compression.getStorageMode() == ArtStorageMode.kStorageModeUncompressed) {+ return reader;//no need to decompress...+ }+ OverlayByteProvider provider = new OverlayByteProvider(reader.getByteProvider());+ BinaryReader decompressedReader = new BinaryReader(provider, reader.isLittleEndian());+ byte[] compressedBytes = reader.readByteArray(compression.getCompressedOffset(),+ compression.getCompressedSize());+ byte[] decompressedBytes = Decompressor.decompress(compression.getStorageMode(),+ compressedBytes, compression.getDecompressedSize(), monitor);+ provider.addRange(new OverlayRange(compression.getDecompressedOffset(), decompressedBytes));+ return decompressedReader;+ }++ /**+ * Decompress the block bytes and pipe into a new binary reader.+ * Required to allow reading of the remainder of the ART header.+ * @param reader binary reader containing compressed bytes+ * @param blocks list of ART blocks that need decompressing+ * @param monitor task monitor for controlling the task+ * @return binary reader containing decompressed bytes+ * @throws IOException should an error occur reading the bytes+ */+ public static BinaryReader decompress(BinaryReader reader, List<ArtBlock> blocks,+ TaskMonitor monitor) throws IOException {+ OverlayByteProvider provider = new OverlayByteProvider(reader.getByteProvider());+ BinaryReader decompressedReader = new BinaryReader(provider, reader.isLittleEndian());+ for (ArtBlock block : blocks) {+ byte[] compressedBytes =+ reader.readByteArray(block.getDataOffset(), block.getDataSize());+ byte[] decompressedBytes = Decompressor.decompress(block.getStorageMode(),+ compressedBytes, block.getImageSize(), monitor);+ if (decompressedBytes.length != block.getImageSize()) {+ throw new RuntimeException( "decompressed length mismatch!" );+ }+ provider.addRange(new OverlayRange(block.getImageOffset(), decompressedBytes));+ }+ return decompressedReader;+ }++ /**+ * Decompress the block bytes and lay over program memory.+ * @param program the program to overwrite+ * @param blocks list of ART blocks that need decompressing+ * @param monitor task monitor for controlling the task+ * @throws Exception should an error occur reading the bytes+ */+ public static void decompressOverMemory(Program program, List<ArtBlock> blocks,+ TaskMonitor monitor) throws Exception {+ for (ArtBlock block : blocks) {+ monitor.checkCanceled();++ Address sourceAddress = program.getMinAddress().add(block.getDataOffset());+ byte[] compressedBytes = new byte[block.getDataSize()];+ program.getMemory().getBytes(sourceAddress, compressedBytes);++ byte[] decompressedBytes = Decompressor.decompress(block.getStorageMode(),+ compressedBytes, block.getImageSize(), monitor);++ Address destinationAddress = program.getMinAddress().add(block.getImageOffset());++ //make sure block exists for bytes...+ AddressSet destinationSet = new AddressSet(destinationAddress,+ destinationAddress.add(decompressedBytes.length));+ AddressSet uncreatedSet = destinationSet.subtract(program.getMemory());+ for (AddressRange range : uncreatedSet) {+ monitor.checkCanceled();+ program.getMemory()+ .createInitializedBlock(toBlockName(range), range.getMinAddress(),+ range.getLength(), (byte) 0x00, monitor, false);+ }++ program.getMemory().setBytes(destinationAddress, decompressedBytes);+ }+ }++ /**+ * Decompress the block bytes and lay over program memory.+ * @param program the program to overwrite+ * @param compression type of compression+ * @param monitor task monitor for controlling the task+ * @throws Exception should an error occur reading the bytes+ */+ public static void decompressOverMemory(Program program, ArtCompression compression,+ TaskMonitor monitor) throws Exception {+ if (compression.getStorageMode() != ArtStorageMode.kStorageModeUncompressed) {+ Address sourceAddress = program.getMinAddress().add(compression.getCompressedOffset());+ byte[] compressedBytes = new byte[compression.getCompressedSize()];+ program.getMemory().getBytes(sourceAddress, compressedBytes);++ byte[] decompressedBytes = Decompressor.decompress(compression.getStorageMode(),+ compressedBytes, compression.getDecompressedSize(), monitor);++ Address destinationAddress =+ program.getMinAddress().add(compression.getDecompressedOffset());++ //make block exists for bytes...+ AddressSet destinationSet = new AddressSet(destinationAddress,+ destinationAddress.add(decompressedBytes.length));+ AddressSet uncreatedSet = destinationSet.subtract(program.getMemory());+ for (AddressRange range : uncreatedSet) {+ monitor.checkCanceled();+ program.getMemory()+ .createInitializedBlock(toBlockName(range), range.getMinAddress(),+ range.getLength(), (byte) 0x00, monitor, false);+ }++ program.getMemory().setBytes(destinationAddress, decompressedBytes);+ }+ }++ private static String toBlockName(AddressRange range) {+ return "decomp_" + range.getMinAddress() + "_" + range.getMaxAddress();+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/Decompressor.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/Decompressor.javanew file mode 100644index 0000000000..7bd3063e00--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/Decompressor.java@@ -0,0 +1,84 @@+/* ###+ * 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.android.util;++import java.io.*;++import org.apache.commons.compress.compressors.lz4.BlockLZ4CompressorInputStream;++import ghidra.file.formats.android.art.ArtStorageMode;+import ghidra.util.task.TaskMonitor;+import utilities.util.FileUtilities;++public class Decompressor {++ /**+ * Decompresses the source bytes using the specified "mode".+ * @param mode storage mode (aka compression type)+ * @param source compressed bytes, if compressed+ * @param maxDecompressedSize maximum byte size after being decompressed+ * @return decompressed bytes+ * @param monitor task monitor for controlling the task+ * @throws IOException should an error occur reading the bytes+ */+ public static byte[] decompress(ArtStorageMode mode, byte[] source, int maxDecompressedSize,+ TaskMonitor monitor) throws IOException {+ if (mode == ArtStorageMode.kStorageModeLZ4) {+ return decompressLZ4(source, maxDecompressedSize, monitor);+ }+ if (mode == ArtStorageMode.kStorageModeLZ4HC) {+ return decompressLZ4HC(source, maxDecompressedSize, monitor);+ }+ if (mode == ArtStorageMode.kStorageModeUncompressed) {+ return source;//not compressed+ }+ throw new IOException("invalid storage mode");+ }++ /**+ * Call the LZ4 decompression library+ */+ private static byte[] decompressLZ4(byte[] source, int maxDecompressedSize, TaskMonitor monitor)+ throws IOException {+ try {+ ByteArrayOutputStream decompressedStream = new ByteArrayOutputStream();+ BlockLZ4CompressorInputStream compressedStream =+ new BlockLZ4CompressorInputStream(new ByteArrayInputStream(source));+ FileUtilities.copyStreamToStream(compressedStream, decompressedStream, monitor);+ return decompressedStream.toByteArray();+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }++ /**+ * Call the LZ4-HC decompression library+ */+ private static byte[] decompressLZ4HC(byte[] source, int maxDecompressedSize,+ TaskMonitor monitor) throws IOException {+ try {+ ByteArrayOutputStream decompressedStream = new ByteArrayOutputStream();+ BlockLZ4CompressorInputStream compressedStream =+ new BlockLZ4CompressorInputStream(new ByteArrayInputStream(source));+ FileUtilities.copyStreamToStream(compressedStream, decompressedStream, monitor);+ return decompressedStream.toByteArray();+ }+ catch (Exception e) {+ throw new IOException(e);+ }+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayByteProvider.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayByteProvider.javanew file mode 100644index 0000000000..7ce3ae3aeb--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayByteProvider.java@@ -0,0 +1,103 @@+/* ###+ * 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.android.util;++import java.io.*;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.ByteProvider;++/**+ * This byte provider is used to store decompressed chunks at specific locations.+ */+public class OverlayByteProvider implements ByteProvider {+ private ByteProvider provider;+ private List<OverlayRange> overlayList = new ArrayList<>();++ public OverlayByteProvider(ByteProvider provider) {+ this.provider = provider;+ }++ public void addRange(OverlayRange range) {+ overlayList.add(range);+ }++ @Override+ public File getFile() {+ return provider.getFile();+ }++ @Override+ public String getName() {+ return provider.getName();+ }++ @Override+ public String getAbsolutePath() {+ return provider.getAbsolutePath();+ }++ @Override+ public long length() throws IOException {+ long currentMax = 0;+ for (OverlayRange range : overlayList) {+ currentMax = Math.max(currentMax, range.getEndIndex());+ }+ return Math.max(currentMax, provider.length());+ }++ @Override+ public boolean isValidIndex(long index) {+ for (OverlayRange range : overlayList) {+ if (range.containsIndex(index)) {+ return true;+ }+ }+ return provider.isValidIndex(index);+ }++ @Override+ public void close() throws IOException {+ provider.close();+ }++ @Override+ public byte readByte(long index) throws IOException {+ for (OverlayRange range : overlayList) {+ if (range.containsIndex(index)) {+ return range.getByte(index);+ }+ }+ return provider.readByte(index);+ }++ @Override+ public byte[] readBytes(long index, long length) throws IOException {+ for (OverlayRange range : overlayList) {+ if (range.containsIndex(index)) {+ return range.getBytes(index, length);+ }+ }+ return provider.readBytes(index, length);+ }++ @Override+ public InputStream getInputStream(long index) throws IOException {+ throw new IOException("get input stream is not supported");+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayRange.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayRange.javanew file mode 100644index 0000000000..087b5e678b--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/util/OverlayRange.java@@ -0,0 +1,122 @@+/* ###+ * 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.android.util;++import java.io.IOException;++public class OverlayRange {++ private int overlayIndex;+ private byte[] overlayBytes;++ public OverlayRange(long overlayIndex, byte[] overlayBytes) {+ this((int) overlayIndex, overlayBytes);+ }++ public OverlayRange(int overlayIndex, byte[] overlayBytes) {+ this.overlayIndex = overlayIndex;+ this.overlayBytes = overlayBytes;+ }++ /**+ * Get the start index of this range.+ * @return the start index of this range+ */+ public int getStartIndex() {+ return overlayIndex;+ }++ /**+ * Get the end index of this range.+ * @return the end index of this range+ */+ public int getEndIndex() {+ return overlayIndex + overlayBytes.length;+ }++ /**+ * Returns true if this range contains the specific index.+ * @param index the specific index+ * @return true if this range contains the specific index+ */+ public boolean containsIndex(int index) {+ return index >= getStartIndex() && index <= getEndIndex();+ }++ /**+ * Returns true if this range contains the specific index.+ * @param index the specific index+ * @return true if this range contains the specific index+ */+ public boolean containsIndex(long index) {+ return containsIndex((int) index);+ }++ /**+ * Returns the byte at the specified index.+ * @param index the specific index+ * @return the byte at the specified index+ */+ public byte getByte(int index) {+ return overlayBytes[index - overlayIndex];+ }++ /**+ * Returns the byte at the specified index.+ * @param index the specific index+ * @return the byte at the specified index+ */+ public byte getByte(long index) {+ return getByte((int) index);+ }++ /**+ * Returns the byte array starting at index with specified length.+ * @param index the index into the range+ * @param length the length of the bytes from the range+ * @return the byte array starting at index with specified length+ * @throws IOException if the index or length is out of range+ */+ public byte[] getBytes(int index, int length) throws IOException {+ try {+ byte[] bytes = new byte[length];+ System.arraycopy(overlayBytes, index - overlayIndex, bytes, 0, length);+ return bytes;+ }+ catch (Exception e) {+ throw new IOException("specified index and length are out of range");+ }+ }++ /**+ * Returns the byte array starting at index with specified length.+ * @param index the index into the range+ * @param length the length of the bytes from the range+ * @return the byte array starting at index with specified length+ * @throws IOException if the index or length is out of range+ */+ public byte[] getBytes(long index, long length) throws IOException {+ return getBytes((int) index, (int) length);+ }++ /**+ * Returns all bytes contained in this range.+ * @return all bytes contained in this range+ */+ public byte[] getAllBytes() {+ return overlayBytes;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/DexSectionHeader_002.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/DexSectionHeader_002.javanew file mode 100644index 0000000000..f88734cc49--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/DexSectionHeader_002.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.android.vdex;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.CategoryPath;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/vdex_file.h#114+ */+public class DexSectionHeader_002 implements StructConverter {++ private int dex_size_;+ private int dex_shared_data_size_;+ private int quickening_info_size_;++ DexSectionHeader_002(BinaryReader reader) throws IOException {+ dex_size_ = reader.readNextInt();+ dex_shared_data_size_ = reader.readNextInt();+ quickening_info_size_ = reader.readNextInt();+ }++ public int getDexSize() {+ return dex_size_;+ }++ public int getDexSharedDataSize() {+ return dex_shared_data_size_;+ }++ public int getQuickeningInfoSize() {+ return quickening_info_size_;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = StructConverterUtil.toDataType(DexSectionHeader_002.class);+ dataType.setCategoryPath(new CategoryPath("/vdex"));+ return dataType;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/UnsupportedVdexVersionException.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/UnsupportedVdexVersionException.javanew file mode 100644index 0000000000..f57bd6584d--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/UnsupportedVdexVersionException.java@@ -0,0 +1,27 @@+/* ###+ * 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.android.vdex;++final class UnsupportedVdexVersionException extends Exception {++ UnsupportedVdexVersionException(String magic, String version) {+ super("Unsupported VDEX version: " + version);+ }++ UnsupportedVdexVersionException(String message) {+ super(message);+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexConstants.javanew file mode 100644index 0000000000..896f264bcc--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexConstants.java@@ -0,0 +1,140 @@+/* ###+ * 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.android.vdex;++import java.io.IOException;++import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.bin.MemoryByteProvider;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.MemoryBlock;++/**+ * Validated DEX+ *+ * VDEX files contain extracted DEX files. The VdexFile class maps the file to+ * memory and provides tools for accessing its individual sections.+ *+ * https://android.googlesource.com/platform/art/+/master/runtime/vdex_file.h+ */+public final class VdexConstants {++ /**+ * <pre>+ * static constexpr uint8_t kVdexMagic[] = { 'v', 'd', 'e', 'x' };+ * </pre>+ */+ public final static String MAGIC = "vdex";++ public final static String version_o_preview = "003";+ public final static String VERSION_OREO_RELEASE = "006";+ public final static String VERSION_OREO_M2_RELEASE = "010";+ public final static String version_o_iot_preview_5 = "010";+ public final static String version_o_mr1_iot_preview_6 = "011";+ public final static String VERSION_PIE_RELEASE = "019";+ public final static String VERSION_10_RELEASE = "021";+ public final static String VERSION_11_RELEASE = "021";++ public final static String version_master = "021";++ /**+ * The format version of the dex section header and the dex section,+ * containing both the dex code and the quickening data.+ * Last update: Add owned section for CompactDex.+ * Cite: https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/vdex_file.h+ */+ public final static String kDexSectionVersion = "002";++ /**+ * If the .vdex file has no dex section (hence no dex code nor quickening data),+ * we encode this magic version.+ * Cite: https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/vdex_file.h+ */+ public final static String kDexSectionVersionEmpty = "000";++ /**+ * Note: The file is called "primary" to match the naming with profiles.+ */+ public final static String kVdexNameInDmFile = "primary.vdex";++ /**+ * NOTE: only going to support RELEASE versions+ */+ public final static String[] SUPPORTED_VERSIONS = new String[] { VERSION_OREO_RELEASE,+ VERSION_OREO_M2_RELEASE, VERSION_PIE_RELEASE, VERSION_10_RELEASE, VERSION_11_RELEASE, };++ public final static boolean isSupportedVersion(String version) {+ for (String supportedVersion : SUPPORTED_VERSIONS) {+ if (supportedVersion.equals(version)) {+ return true;+ }+ }+ return false;+ }++ /**+ * Returns true if the given program contain VDEX information.+ * @param program the program to inspect for being VDEX+ * @return true if the program is VDEX+ */+ public final static boolean isVDEX(Program program) {+ if (program != null) {+ for (MemoryBlock block : program.getMemory().getBlocks()) {++ try (ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), block.getStart())) {+ String magic = new String(provider.readBytes(0, VdexConstants.MAGIC.length()));+ if (VdexConstants.MAGIC.equals(magic)) {+ return true;+ }+ }+ catch (Exception e) {+ //ignore+ }+ }+ }+ return false;+ }++ public final static Address findVDEX(Program program) {+ try {+ if (program != null) {+ for (MemoryBlock block : program.getMemory().getBlocks()) {+ ByteProvider provider =+ new MemoryByteProvider(program.getMemory(), block.getStart());+ try {+ String magic =+ new String(provider.readBytes(0, VdexConstants.MAGIC.length()));+ if (VdexConstants.MAGIC.equals(magic)) {+ return block.getStart();+ }+ }+ catch (Exception e) {+ //ignore+ }+ finally {+ provider.close();+ }+ }+ }+ }+ catch (IOException e) {+ //ignore+ }+ return null;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexFactory.javanew file mode 100644index 0000000000..03c2dd8672--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexFactory.java@@ -0,0 +1,136 @@+/* ###+ * 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.android.vdex;++import java.io.File;+import java.io.IOException;++import org.apache.commons.io.FilenameUtils;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.framework.model.DomainFile;+import ghidra.framework.model.DomainFolder;+import ghidra.program.model.listing.Program;+import ghidra.util.task.TaskMonitor;++public final class VdexFactory {++ /**+ * Returns an VDEX Header for the specified version.+ * @param reader the binary reader+ * @return the new VDEX header+ * @throws IOException if an error occurs creating new VDEX header+ * @throws UnsupportedVdexVersionException when the provided version is invalid or not yet implemented.+ */+ public static VdexHeader getVdexHeader(BinaryReader reader)+ throws IOException, UnsupportedVdexVersionException {+ String magic = reader.readAsciiString(0, VdexConstants.MAGIC.length());+ String version = reader.readAsciiString(4, 4);+ if (magic.equals(VdexConstants.MAGIC)) {+ if (VdexConstants.isSupportedVersion(version)) {+ if (version.equals(VdexConstants.VERSION_OREO_RELEASE) ||+ version.equals(VdexConstants.VERSION_OREO_M2_RELEASE)) {+ return new VdexHeader_Oreo(reader);+ }+ if (version.equals(VdexConstants.VERSION_PIE_RELEASE)) {+ return new VdexHeader_Pie(reader);+ }+ if (version.equals(VdexConstants.VERSION_10_RELEASE)) {+ return new VdexHeader_10(reader);+ }+ if (version.equals(VdexConstants.VERSION_11_RELEASE)) {+ return new VdexHeader_11(reader);+ }+ }+ }+ throw new UnsupportedVdexVersionException(magic, version);+ }++ public static VdexHeader loadVdexHeader(Program program, TaskMonitor monitor, MessageLog log) {++ if (program == null) {+ return null;+ }++ String vdexProgramName = FilenameUtils.removeExtension(program.getName());++ //first, look in current project for VDEX file....++ DomainFile domainFile = program.getDomainFile();+ DomainFolder parentFolder = domainFile.getParent();+ VdexHeader vdexHeader =+ scanProjectFolder(parentFolder, vdexProgramName, program, monitor, log);+ if (vdexHeader == null) {+ vdexHeader =+ scanProjectFolder(parentFolder.getParent(), vdexProgramName, program, monitor, log);+ }+ if (vdexHeader != null) {+ return vdexHeader;+ }++ //then, try to locate the VDEX on disk, in same folder where binary was imported....++ String oatFilePath = program.getExecutablePath();++ if (oatFilePath.endsWith(".odex") || oatFilePath.endsWith(".oat")) {+ String vdexFilePath = FilenameUtils.removeExtension(oatFilePath);+ File vdexFile = new File(vdexFilePath);+ try (ByteProvider vdexProvider = new RandomAccessByteProvider(vdexFile)) {+ BinaryReader vdexReader =+ new BinaryReader(vdexProvider, !program.getLanguage().isBigEndian());+ vdexHeader = getVdexHeader(vdexReader);+ vdexHeader.parse(vdexReader, monitor);+ return vdexHeader;+ }+ catch (Exception e) {+ log.appendMsg("Unable to locate matching VDEX.");+ }+ }++ return null;+ }++ private static VdexHeader scanProjectFolder(DomainFolder parentFolder, String vdexProgramName,+ Program program, TaskMonitor monitor, MessageLog log) {++ DomainFile child = parentFolder.getFile(vdexProgramName);+ if (child != null) {+ try {+ Object consumer = new Object();+ Program vdexProgram =+ (Program) child.getDomainObject(consumer, true, true, monitor);+ try {+ ByteProvider vdexProvider = new MemoryByteProvider(vdexProgram.getMemory(),+ vdexProgram.getMinAddress());+ BinaryReader vdexReader =+ new BinaryReader(vdexProvider, !program.getLanguage().isBigEndian());+ VdexHeader vdexHeader = getVdexHeader(vdexReader);+ vdexHeader.parse(vdexReader, monitor);+ return vdexHeader;+ }+ finally {+ vdexProgram.release(consumer);+ }+ }+ catch (Exception e) {+ log.appendMsg("Unable to locate matching VDEX.");+ }+ }+ return null;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexFileSystem.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexFileSystem.javanew file mode 100644index 0000000000..6ebf03178a--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexFileSystem.java@@ -0,0 +1,116 @@+/* ###+ * 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.android.vdex;++import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.ByteProvider;+import ghidra.file.formats.android.cdex.CDexHeader;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.formats.gfilesystem.GFile;+import ghidra.formats.gfilesystem.GFileImpl;+import ghidra.formats.gfilesystem.GFileSystemBase;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.factory.GFileSystemBaseFactory;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.CryptoException;+import ghidra.util.task.TaskMonitor;++@FileSystemInfo(type = "androidvdex", description = "Android VDEX (for extracting embedded DEX files)", factory = GFileSystemBaseFactory.class)+public class VdexFileSystem extends GFileSystemBase {++ private VdexHeader header;+ private List<GFile> listing = new ArrayList<GFile>();++ public VdexFileSystem(String fileSystemName, ByteProvider provider) {+ super(fileSystemName, provider);+ }++ @Override+ public boolean isValid(TaskMonitor monitor) throws IOException {+ try {+ byte[] magicBytes = provider.readBytes(0, VdexConstants.MAGIC.length());+ return VdexConstants.MAGIC.equals(new String(magicBytes));+ }+ catch (Exception e) {+ // ignore...+ }+ return false;+ }++ @Override+ public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {+ monitor.setMessage("Parsing VDEX header...");+ BinaryReader reader = new BinaryReader(provider, true /* TODO always LE??? */ );+ try {+ header = VdexFactory.getVdexHeader(reader);+ header.parse(reader, monitor);++ for (int i = 0; i < header.getDexHeaderList().size(); ++i) {+ monitor.checkCanceled();+ DexHeader dexHeader = header.getDexHeaderList().get(i);+ String name =+ ((dexHeader instanceof CDexHeader) ? "cdex" + "_" + i : "classes" + i + ".dex");+ GFile file = GFileImpl.fromPathString(this, root, name, null, false,+ Integer.toUnsignedLong(dexHeader.getFileSize()));+ listing.add(file);+ }+ }+ catch (UnsupportedVdexVersionException e) {+ throw new IOException(e);+ }+ }++ @Override+ public void close() throws IOException {+ super.close();+ header = null;+ listing.clear();+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ if (directory == null || directory.equals(root)) {+ return listing;+ }+ return Collections.emptyList();+ }++ @Override+ public String getInfo(GFile file, TaskMonitor monitor) {+ int index = listing.indexOf(file);++ if (index >= 0 && index < header.getDexHeaderList().size() - 1) {+ long length = Integer.toUnsignedLong(header.getDexHeaderList().get(index).getFileSize());+ return "DEX Header Size: 0x" + Long.toHexString(length);+ }+ return null;+ }++ @Override+ protected InputStream getData(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException, CryptoException {+ int index = listing.indexOf(file);+ long startIndex = header.getDexStartOffset(index);+ return provider.getInputStream(startIndex);+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader.javanew file mode 100644index 0000000000..0523aa00b2--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader.java@@ -0,0 +1,81 @@+/* ###+ * 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.android.vdex;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++public abstract class VdexHeader implements StructConverter {++ protected String magic_;+ protected String verifier_deps_version_;++ protected VdexStringTable stringTable;+ protected List<Long> dexHeaderStartsList = new ArrayList<>();+ protected List<DexHeader> dexHeaderList = new ArrayList<>();++ protected VdexHeader(BinaryReader reader) throws IOException {+ magic_ = new String(reader.readNextByteArray(VdexConstants.MAGIC.length()));+ }++ final public String getMagic() {+ return magic_;+ }++ final public String getVerifierDepsVersion() {+ return verifier_deps_version_;+ }++ abstract public void parse(BinaryReader reader, TaskMonitor monitor)+ throws IOException, CancelledException;++ final public long getDexStartOffset(int index) {+ return dexHeaderStartsList.get(index);+ }++ abstract public int getVerifierDepsSize();++ abstract public int getQuickeningInfoSize();++ abstract public int[] getDexChecksums();++ /**+ * Returns the list of DEX headers contained in this VDEX.+ * Could return empty list depending on version of VDEX.+ */+ final public List<DexHeader> getDexHeaderList() {+ return dexHeaderList;+ }++ /**+ * Returns the VDEX String Table.+ * Note: Could be NULL.+ */+ final public VdexStringTable getStringTable() {+ return stringTable;+ }++ abstract public boolean isDexHeaderEmbeddedInDataType();++ abstract public DexSectionHeader_002 getDexSectionHeader_002();+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeaderAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeaderAnalyzer.javanew file mode 100644index 0000000000..6e4d218399--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeaderAnalyzer.java@@ -0,0 +1,185 @@+/* ###+ * 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.android.vdex;++import ghidra.app.util.bin.*;+import ghidra.app.util.importer.MessageLog;+import ghidra.file.analyzers.FileFormatAnalyzer;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.file.formats.android.oat.OatConstants;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSetView;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.CodeUnit;+import ghidra.program.model.listing.Program;+import ghidra.util.task.TaskMonitor;++public class VdexHeaderAnalyzer extends FileFormatAnalyzer {++ private final static DataType BYTE = new ByteDataType();++ @Override+ public String getName() {+ return "Android VDEX Header Format";+ }++ @Override+ public boolean getDefaultEnablement(Program program) {+ return true;+ }++ @Override+ public String getDescription() {+ return "Annotates the Android VDEX data in this program.";+ }++ @Override+ public boolean canAnalyze(Program program) {+ return VdexConstants.isVDEX(program)+ //HACK:+ //Make analyzer appear after VDEX is merged with OAT program+ //Currently, analyzers will not recognize the new VDEX block being added+ || OatConstants.isOAT(program);+ }++ @Override+ public boolean isPrototype() {+ return true;+ }++ @Override+ public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)+ throws Exception {+ Address address = VdexConstants.findVDEX(program);+ if (address == null) {+ log.appendMsg(getClass().getSimpleName() + " - no vdex header found, skipping");+ return true;+ }+ ByteProvider provider = new MemoryByteProvider(program.getMemory(), address);+ BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());+ try {+ VdexHeader vdexHeader = VdexFactory.getVdexHeader(reader);+ vdexHeader.parse(reader, monitor);++ DataType vdexHeaderDataType = vdexHeader.toDataType();+ createData(program, address, vdexHeaderDataType);+ address = address.add(vdexHeaderDataType.getLength());++ if (!vdexHeader.isDexHeaderEmbeddedInDataType()) {+ for (int i = 0; i < vdexHeader.getDexHeaderList().size(); ++i) {+ monitor.checkCanceled();++ program.getListing()+ .setComment(address, CodeUnit.PLATE_COMMENT,+ "quicken info table entry");+ createData(program, address, new DWordDataType());+ address = address.add(4);++ DexHeader dexHeader = vdexHeader.getDexHeaderList().get(i);+ DataType dexHeaderDataType = dexHeader.toDataType();+ createData(program, address, dexHeaderDataType);++ int size = dexHeader.getFileSize() - dexHeaderDataType.getLength();+ DataType array = new ArrayDataType(BYTE, size, BYTE.getLength());+ createData(program, address.add(dexHeaderDataType.getLength()), array);++ address = address.add(dexHeader.getFileSize());+ }+ }++ address = createDexSharedDataSize(program, address, vdexHeader);++ address = createVerifierDepsSize(program, address, vdexHeader);++ address = createQuickeningInfoSize(program, address, vdexHeader);++ return true;+ }+ catch (UnsupportedVdexVersionException e) {+ log.appendMsg(e.getMessage());+ }+ catch (Exception e) {+ log.appendException(e);+ }+ return false;+ }++ private Address createDexSharedDataSize(Program program, Address address, VdexHeader vdexHeader)+ throws Exception {+ DexSectionHeader_002 sectionHeader = vdexHeader.getDexSectionHeader_002();+ if (sectionHeader != null) {+ int dexSharedDataSize = sectionHeader.getDexSharedDataSize();+ String comment = "dex_shared_data_size_ : 0x" + Integer.toHexString(dexSharedDataSize);+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);+ DataType array = new ArrayDataType(BYTE, dexSharedDataSize, BYTE.getLength());+ createData(program, address, array);+ address = address.add(dexSharedDataSize);+ }+ return address;+ }++ private Address createVerifierDepsSize(Program program, Address address, VdexHeader vdexHeader)+ throws Exception {+ if (vdexHeader.getVerifierDepsVersion() != VdexConstants.VERSION_10_RELEASE) {+ return address;+ }++ String comment =+ "verifier_deps_size_ : 0x" + Integer.toHexString(vdexHeader.getVerifierDepsSize());+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);++ int remainderSize = vdexHeader.getVerifierDepsSize();++ ByteProvider provider = new MemoryByteProvider(program.getMemory(), address);+ BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());+ VdexStringTable stringTable = new VdexStringTable(reader);+ if (stringTable.getStringCount() > 0) {+ createData(program, address, stringTable.toDataType());+ address = address.add(stringTable.getSize());+ remainderSize -= stringTable.getSize();+ }+ if (address.add(remainderSize).compareTo(program.getMaxAddress()) > 0) {+ remainderSize = (int) program.getMaxAddress().subtract(address);+ }+ if (remainderSize > 0) {+ DataType array = new ArrayDataType(BYTE, remainderSize, BYTE.getLength());+ createData(program, address, array);+ address = address.add(remainderSize);+ }+ return address;+ }++ private Address createQuickeningInfoSize(Program program, Address address,+ VdexHeader vdexHeader) throws Exception {+ int quickeningInfoSize = vdexHeader.getQuickeningInfoSize();++ DexSectionHeader_002 sectionHeader = vdexHeader.getDexSectionHeader_002();+ if (sectionHeader != null) {+ quickeningInfoSize = sectionHeader.getQuickeningInfoSize();+ }++ if (quickeningInfoSize == 0) {+ return address;+ }++ String comment = "quickening_info_size_ : 0x" + Integer.toHexString(quickeningInfoSize);+ program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, comment);++ address = address.add(quickeningInfoSize);++ return address;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_10.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_10.javanew file mode 100644index 0000000000..6160891f9e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_10.java@@ -0,0 +1,161 @@+/* ###+ * 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.android.vdex;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.file.formats.android.dex.DexHeaderFactory;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.program.model.data.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/android10-release/runtime/vdex_file.h+ */+public class VdexHeader_10 extends VdexHeader {++ private String dex_section_version_;+ private int number_of_dex_files_;+ private int verifier_deps_size_;+ private int bootclasspath_checksums_size_;+ private int class_loader_context_size_;+ private int[] dex_checksums_;+ private DexSectionHeader_002 sectionHeader;+ private List<Integer> quickenTableOffsetList = new ArrayList<>();++ public VdexHeader_10(BinaryReader reader) throws IOException, UnsupportedVdexVersionException {+ super(reader);+ verifier_deps_version_ = reader.readNextAsciiString(4);+ dex_section_version_ = reader.readNextAsciiString(4);+ number_of_dex_files_ = reader.readNextInt();+ verifier_deps_size_ = reader.readNextInt();+ bootclasspath_checksums_size_ = reader.readNextInt();+ class_loader_context_size_ = reader.readNextInt();++ // dex checksums appear as contiguous list++ dex_checksums_ = new int[number_of_dex_files_];+ for (int i = 0; i < number_of_dex_files_; ++i) {+ dex_checksums_[i] = reader.readNextInt();+ }++ if (VdexConstants.kDexSectionVersion.equals(dex_section_version_)) {+ sectionHeader = new DexSectionHeader_002(reader);++ for (int i = 0; i < number_of_dex_files_; ++i) {+ quickenTableOffsetList.add(reader.readNextInt());++ long index = reader.getPointerIndex();++ dexHeaderStartsList.add(index);++ ByteProviderWrapper wrapperProvider = new ByteProviderWrapper(+ reader.getByteProvider(), index, reader.getByteProvider().length() - index);+ BinaryReader wrappedReader =+ new BinaryReader(wrapperProvider, reader.isLittleEndian());++ DexHeader cdexHeader = DexHeaderFactory.getDexHeader(wrappedReader);+ dexHeaderList.add(cdexHeader);++ reader.setPointerIndex(index + cdexHeader.getFileSize());+ }+ }+ else if (VdexConstants.kDexSectionVersionEmpty.equals(dex_section_version_)) {+ stringTable = new VdexStringTable( reader );+ }+ else {+ throw new UnsupportedVdexVersionException(+ "Unknown VDEX section version: " + dex_section_version_);+ }+ }++ public void parse(BinaryReader reader, TaskMonitor monitor)+ throws IOException, CancelledException {+ //do nothing+ }++ public String getDexSectionVersion() {+ return dex_section_version_;+ }++ public int getNumberOfDexFiles() {+ return number_of_dex_files_;+ }++ @Override+ public int getVerifierDepsSize() {+ return verifier_deps_size_;+ }++ @Override+ public int getQuickeningInfoSize() {+ // unsupported...+ return 0;+ }++ @Override+ public DexSectionHeader_002 getDexSectionHeader_002() {+ return sectionHeader;+ }++ public int getBootclasspathChecksumsSize() {+ return bootclasspath_checksums_size_;+ }++ public int getClassLoaderContextSize() {+ return class_loader_context_size_;+ }++ @Override+ public int[] getDexChecksums() {+ return dex_checksums_;+ }++ @Override+ public boolean isDexHeaderEmbeddedInDataType() {+ return false;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(VdexHeader_10.class);+ Structure structure = new StructureDataType(className + "_" + number_of_dex_files_, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "verifier_deps_version_", null);+ structure.add(STRING, 4, "dex_section_version_", null);+ structure.add(DWORD, "number_of_dex_files_", null);+ structure.add(DWORD, "verifier_deps_size_", null);+ structure.add(DWORD, "bootclasspath_checksums_size_", null);+ structure.add(DWORD, "class_loader_context_size_", null);+ for (int i = 0; i < dex_checksums_.length; ++i) {+ structure.add(DWORD, "dex_checksum_" + i, null);+ }+ if (sectionHeader != null) {+ structure.add(sectionHeader.toDataType(), "dex_section_header_", null);+ }+ if (stringTable != null && stringTable.getStringCount() > 0) {+ structure.add(stringTable.toDataType(), "strings", null);+ }+ structure.setCategoryPath(new CategoryPath("/vdex"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_11.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_11.javanew file mode 100644index 0000000000..5d5301df97--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_11.java@@ -0,0 +1,43 @@+/* ###+ * 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.android.vdex;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverterUtil;+import ghidra.program.model.data.DataType;+import ghidra.util.exception.DuplicateNameException;++public class VdexHeader_11 extends VdexHeader_10 {++ public VdexHeader_11(BinaryReader reader) throws IOException, UnsupportedVdexVersionException {+ super(reader);+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ DataType dataType = super.toDataType();+ try {+ String className = StructConverterUtil.parseName(VdexHeader_11.class);+ dataType.setName(className);+ }+ catch (Exception e) {+ //ignore...+ }+ return dataType;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_Oreo.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_Oreo.javanew file mode 100644index 0000000000..3c6aaa253e--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_Oreo.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.android.vdex;++import java.io.IOException;++import ghidra.app.util.bin.*;+import ghidra.file.formats.android.dex.DexHeaderFactory;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.file.formats.android.dex.format.DexHeaderQuickMethods;+import ghidra.program.model.data.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-release/runtime/vdex_file.h+ * https://android.googlesource.com/platform/art/+/refs/heads/oreo-m2-release/runtime/vdex_file.h+ */+public class VdexHeader_Oreo extends VdexHeader {++ private String version_;+ private int number_of_dex_files_;+ private int dex_size_;+ private int verifier_deps_size_;+ private int quickening_info_size_;+ private int[] dex_checksums_;++ public VdexHeader_Oreo(BinaryReader reader) throws IOException {+ super(reader);+ version_ = reader.readNextAsciiString(4);+ number_of_dex_files_ = reader.readNextInt();+ dex_size_ = reader.readNextInt();+ verifier_deps_size_ = reader.readNextInt();+ quickening_info_size_ = reader.readNextInt();+ dex_checksums_ = reader.readNextIntArray(number_of_dex_files_);+ }++ public void parse(BinaryReader reader, TaskMonitor monitor)+ throws IOException, CancelledException {+ monitor.setMessage("Parsing DEX files inside VDEX (oreo)...");+ monitor.setProgress(0);+ monitor.setMaximum(number_of_dex_files_ * 2);+ for (int i = 0; i < number_of_dex_files_; ++i) {+ monitor.checkCanceled();+ monitor.incrementProgress(1);+ long index = reader.getPointerIndex();+ ByteProvider provider = reader.getByteProvider();+ ByteProvider tmpProvider =+ new ByteProviderWrapper(provider, index, provider.length() - index);+ BinaryReader tmpReader = new BinaryReader(tmpProvider, reader.isLittleEndian());+ tmpReader.setPointerIndex(0);+ dexHeaderList.add(DexHeaderFactory.getDexHeader(tmpReader));+ tmpReader.setPointerIndex(0);+ int length = DexHeaderQuickMethods.getDexLength(tmpReader);+ dexHeaderStartsList.add(index);+ reader.setPointerIndex(index + length);+ }+ //stringTable = new VdexStringTable( reader );+ }++ public String getVersion() {+ return version_;+ }++ public int getNumberOfDexFiles() {+ return number_of_dex_files_;+ }++ public int getDexSize() {+ return dex_size_;+ }++ @Override+ public int getVerifierDepsSize() {+ return verifier_deps_size_;+ }++ @Override+ public int getQuickeningInfoSize() {+ return quickening_info_size_;+ }++ @Override+ public int[] getDexChecksums() {+ return dex_checksums_;+ }++ @Override+ public boolean isDexHeaderEmbeddedInDataType() {+ return true;+ }++ @Override+ public DexSectionHeader_002 getDexSectionHeader_002() {+ return null;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(VdexHeader_Oreo.class);+ Structure structure = new StructureDataType(className + "_" + number_of_dex_files_, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "version_", null);+ structure.add(DWORD, "number_of_dex_files_", null);+ structure.add(DWORD, "dex_size_", null);+ structure.add(DWORD, "verifier_deps_size_", null);+ structure.add(DWORD, "quickening_info_size_", null);+ for (int i = 0; i < dex_checksums_.length; ++i) {+ structure.add(DWORD, "dex_checksums_" + i, null);+ }+ for (int i = 0; i < dexHeaderList.size(); ++i) {+ DexHeader dexHeader = dexHeaderList.get(i);+ DataType dexHeaderDataType = dexHeader.toDataType();+ try {+ dexHeaderDataType.setName(dexHeaderDataType.getName() + "_" + i);+ }+ catch (Exception e) {+ //ignore...+ }+ structure.add(dexHeaderDataType, "dex_header_" + i, null);+ ArrayDataType array = new ArrayDataType(BYTE,+ dexHeader.getFileSize() - dexHeaderDataType.getLength(), BYTE.getLength());+ structure.add(array, "dex_header_bytes_" + i, null);+ }+ if (stringTable != null) {+ structure.add(stringTable.toDataType(), "strings", null);+ }+ structure.setCategoryPath(new CategoryPath("/vdex"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_Pie.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_Pie.javanew file mode 100644index 0000000000..d53eb155f0--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeader_Pie.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.android.vdex;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.file.formats.android.dex.DexHeaderFactory;+import ghidra.file.formats.android.dex.format.DexHeader;+import ghidra.program.model.data.*;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * https://android.googlesource.com/platform/art/+/refs/heads/pie-release/runtime/vdex_file.h+ */+public class VdexHeader_Pie extends VdexHeader {++ private String dex_section_version_;+ private int number_of_dex_files_;+ private int verifier_deps_size_;+ private int[] dex_checksums_;+ private DexSectionHeader_002 sectionHeader;+ private List<Integer> quickenTableOffsetList = new ArrayList<>();++ public VdexHeader_Pie(BinaryReader reader) throws IOException, UnsupportedVdexVersionException {+ super(reader);++ verifier_deps_version_ = reader.readNextAsciiString(4);+ dex_section_version_ = reader.readNextAsciiString(4);+ number_of_dex_files_ = reader.readNextInt();+ verifier_deps_size_ = reader.readNextInt();++ dex_checksums_ = new int[number_of_dex_files_];+ for (int i = 0; i < number_of_dex_files_; ++i) {+ dex_checksums_[i] = reader.readNextInt();+ }++ if (VdexConstants.kDexSectionVersion.equals(dex_section_version_)) {+ sectionHeader = new DexSectionHeader_002(reader);++ for (int i = 0; i < number_of_dex_files_; ++i) {+ quickenTableOffsetList.add(reader.readNextInt());++ long index = reader.getPointerIndex();++ dexHeaderStartsList.add(index);++ ByteProviderWrapper wrapperProvider = new ByteProviderWrapper(+ reader.getByteProvider(), index, reader.getByteProvider().length() - index);+ BinaryReader wrappedReader =+ new BinaryReader(wrapperProvider, reader.isLittleEndian());++ DexHeader cdexHeader = DexHeaderFactory.getDexHeader(wrappedReader);+ dexHeaderList.add(cdexHeader);++ reader.setPointerIndex(index + cdexHeader.getFileSize());+ }+ }+ else if (VdexConstants.kDexSectionVersionEmpty.equals(dex_section_version_)) {+ stringTable = new VdexStringTable(reader);+ }+ else {+ throw new UnsupportedVdexVersionException(+ "Unknown VDEX section version: " + dex_section_version_);+ }+ }++ public void parse(BinaryReader reader, TaskMonitor monitor)+ throws IOException, CancelledException {+ //do nothing+ }++ public String getDexSectionVersion() {+ return dex_section_version_;+ }++ public int getNumberOfDexFiles() {+ return number_of_dex_files_;+ }++ @Override+ public int getVerifierDepsSize() {+ return verifier_deps_size_;+ }++ @Override+ public int getQuickeningInfoSize() {+ // unsupported...+ return 0;+ }++ @Override+ public DexSectionHeader_002 getDexSectionHeader_002() {+ return sectionHeader;+ }++ @Override+ public int[] getDexChecksums() {+ return dex_checksums_;+ }++ @Override+ public boolean isDexHeaderEmbeddedInDataType() {+ return false;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(VdexHeader_Pie.class);+ Structure structure = new StructureDataType(className + "_" + number_of_dex_files_, 0);+ structure.add(STRING, 4, "magic_", null);+ structure.add(STRING, 4, "verifier_deps_version_", null);+ structure.add(STRING, 4, "dex_section_version_", null);+ structure.add(DWORD, "number_of_dex_files_", null);+ structure.add(DWORD, "verifier_deps_size_", null);+ for (int i = 0; i < dex_checksums_.length; ++i) {+ structure.add(DWORD, "dex_checksum_" + i, null);+ }+ if (sectionHeader != null) {+ structure.add(sectionHeader.toDataType(), "dex_section_header_", null);+ }+ if (stringTable != null) {+ structure.add(stringTable.toDataType(), "strings", null);+ }+ structure.setCategoryPath(new CategoryPath("/vdex"));+ return structure;+ }++}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexStringTable.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexStringTable.javanew file mode 100644index 0000000000..6207717363--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexStringTable.java@@ -0,0 +1,67 @@+/* ###+ * 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.android.vdex;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.*;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++public class VdexStringTable implements StructConverter {++ private int stringCount;//note only 1 byte in size+ private List<String> strings = new ArrayList<>();++ VdexStringTable(BinaryReader reader) throws IOException {+ stringCount = Byte.toUnsignedInt(reader.readNextByte());+ for (int i = 0; i < stringCount; ++i) {+ strings.add(reader.readNextAsciiString());+ }+ }++ public int getStringCount() {+ return stringCount;+ }++ public List<String> getStrings() {+ return strings;+ }++ public int getSize() {+ int size = 1;+ for (int i = 0; i < stringCount; ++i) {+ String string = strings.get(i);+ size += string.length() + 1;+ }+ return size;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ String className = StructConverterUtil.parseName(VdexStringTable.class);+ Structure structure = new StructureDataType(className + "_" + stringCount, 0);+ structure.add(BYTE, "stringCount", null);+ for (int i = 0; i < stringCount; ++i) {+ String string = strings.get(i);+ structure.add(STRING, string.length() + 1, "string_" + i, null);+ }+ structure.setCategoryPath(new CategoryPath("/vdex"));+ return structure;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/FailureKind.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/FailureKind.javanew file mode 100644index 0000000000..9155263670--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/FailureKind.java@@ -0,0 +1,23 @@+/* ###+ * 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.android.verifier;++/**+ * https://android.googlesource.com/platform/art/+/master/runtime/verifier/verifier_enums.h+ */+public enum FailureKind {+ kNoFailure, kSoftFailure, kHardFailure;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/HardFailLogMode.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/HardFailLogMode.javanew file mode 100644index 0000000000..debcc6785f--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/HardFailLogMode.java@@ -0,0 +1,26 @@+/* ###+ * 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.android.verifier;++/**+ * https://android.googlesource.com/platform/art/+/master/runtime/verifier/verifier_enums.h+ */+public enum HardFailLogMode {+ kLogNone,+ kLogVerbose,+ kLogWarning,+ kLogInternalFatal;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/MethodType.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/MethodType.javanew file mode 100644index 0000000000..35211915b3--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/MethodType.java@@ -0,0 +1,29 @@+/* ###+ * 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.android.verifier;++/**+ * https://android.googlesource.com/platform/art/+/master/runtime/verifier/verifier_enums.h+ */+public enum MethodType {+ METHOD_UNKNOWN,+ METHOD_DIRECT,+ METHOD_STATIC,+ METHOD_VIRTUAL,+ METHOD_SUPER,+ METHOD_INTERFACE,+ METHOD_POLYMORPHIC;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/VerifyError.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/VerifyError.javanew file mode 100644index 0000000000..a7b869aec2--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/VerifyError.java@@ -0,0 +1,48 @@+/* ###+ * 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.android.verifier;++/**+ * https://android.googlesource.com/platform/art/+/master/runtime/verifier/verifier_enums.h+ */+public final class VerifyError {++ public final static int VERIFY_ERROR_BAD_CLASS_HARD = 1 << 0;++ public final static int VERIFY_ERROR_BAD_CLASS_SOFT = 1 << 1;++ public final static int VERIFY_ERROR_NO_CLASS = 1 << 2;++ public final static int VERIFY_ERROR_NO_FIELD = 1 << 3;++ public final static int VERIFY_ERROR_NO_METHOD = 1 << 4;++ public final static int VERIFY_ERROR_ACCESS_CLASS = 1 << 5;++ public final static int VERIFY_ERROR_ACCESS_FIELD = 1 << 6;++ public final static int VERIFY_ERROR_ACCESS_METHOD = 1 << 7;++ public final static int VERIFY_ERROR_CLASS_CHANGE = 1 << 8;++ public final static int VERIFY_ERROR_INSTANTIATION = 1 << 9;++ public final static int VERIFY_ERROR_FORCE_INTERPRETER = 1 << 10;++ public final static int VERIFY_ERROR_LOCKING = 1 << 11;++ public final static int VERIFY_ERROR_SKIP_COMPILER = 1 << 31;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/VerifyMode.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/VerifyMode.javanew file mode 100644index 0000000000..0928ed7dbb--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/verifier/VerifyMode.java@@ -0,0 +1,25 @@+/* ###+ * 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.android.verifier;++/**+ * https://android.googlesource.com/platform/art/+/master/runtime/verifier/verifier_enums.h+ */+public enum VerifyMode {+ kNone,+ kEnable,+ kSoftFail;+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/wdex/WdexConstants.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/wdex/WdexConstants.javanew file mode 100644index 0000000000..8bc4eb47de--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/wdex/WdexConstants.java@@ -0,0 +1,52 @@+/* ###+ * 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.android.wdex;++import ghidra.program.model.listing.Program;++/**+ * Android .WDEX files.+ *+ * https://android.googlesource.com/platform/art/+/master/runtime/vdex_file.h+ */+public final class WdexConstants {++ /**+ * <pre>+ * static constexpr uint8_t kVdexInvalidMagic[] = { 'w', 'd', 'e', 'x' };+ * </pre>+ */+ public final static String MAGIC = "wdex";++ public final static String kVdexInvalidMagic = MAGIC;++ /**+ * Returns true if the given program contain WDEX information.+ */+ public final static boolean isWDEX(Program program) {+ if (program != null) {+ try {+ byte[] bytes = new byte[MAGIC.length()];+ program.getMemory().getBytes(program.getMinAddress(), bytes);+ return MAGIC.equals(new String(bytes));+ }+ catch (Exception e) {+ //ignore+ }+ }+ return false;+ }+}diff --git a/Ghidra/Processors/Dalvik/certification.manifest b/Ghidra/Processors/Dalvik/certification.manifestindex 27441d891a..7c45e60c34 100644--- a/Ghidra/Processors/Dalvik/certification.manifest+++ b/Ghidra/Processors/Dalvik/certification.manifest@@ -1,7 +1,41 @@##VERSION: 2.0Module.manifest||GHIDRA||||END|-data/languages/Dalvik.cspec||GHIDRA||||END|-data/languages/Dalvik.ldefs||GHIDRA||||END|-data/languages/Dalvik.opinion||GHIDRA||||END|-data/languages/Dalvik.pspec||GHIDRA||||END|-data/languages/Dalvik.slaspec||GHIDRA||||END|+data/languages/Dalvik_Base.cspec||GHIDRA||||END|+data/languages/Dalvik_Base.ldefs||GHIDRA||||END|+data/languages/Dalvik_Base.opinion||GHIDRA||||END|+data/languages/Dalvik_Base.pspec||GHIDRA||||END|+data/languages/Dalvik_Base.sinc||GHIDRA||||END|+data/languages/Dalvik_Base.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_Android10.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_Android11.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_KitKat.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_Lollipop.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_Marshmallow.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_Nougat.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_Oreo.slaspec||GHIDRA||||END|+data/languages/Dalvik_DEX_Pie.slaspec||GHIDRA||||END|+data/languages/Dalvik_ODEX_KitKat.slaspec||GHIDRA||||END|+data/languages/Dalvik_OpCode_3E_43_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_73_return_void_barrier.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_73_return_void_no_barrier.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_73_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_79_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_7A_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_E3_EA_dex.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_EB_F2_iput_iget.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_EB_F2_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_F3_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_F4_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_F5_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_F6_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_F7_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_F8_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_F9_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FA_FD_dex.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FA_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FB_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FC_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FD_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FE_FF_dex.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FE_unused.sinc||GHIDRA||||END|+data/languages/Dalvik_OpCode_FF_unused.sinc||GHIDRA||||END|diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik.ldefs b/Ghidra/Processors/Dalvik/data/languages/Dalvik.ldefsdeleted file mode 100644index 5773aa9fdc..0000000000--- a/Ghidra/Processors/Dalvik/data/languages/Dalvik.ldefs+++ /dev/null@@ -1,15 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>--<language_definitions>- <language processor="Dalvik"- endian="little"- size="32"- variant="default"- version="1.0"- slafile="Dalvik.sla"- processorspec="Dalvik.pspec"- id="Dalvik:LE:32:default">- <description>Dalvik</description>- <compiler name="default" spec="Dalvik.cspec" id="default"/>- </language>-</language_definitions>diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik.cspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.cspecsimilarity index 100%rename from Ghidra/Processors/Dalvik/data/languages/Dalvik.cspecrename to Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.cspecdiff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.ldefs b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.ldefsnew file mode 100644index 0000000000..0216dbae06--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.ldefs@@ -0,0 +1,125 @@+<?xml version="1.0" encoding="UTF-8"?>++<language_definitions>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX-Base"+ version="1.0"+ slafile="Dalvik_Base.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_Base">+ <description>Dalvik Base</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX KitKat"+ version="1.0"+ slafile="Dalvik_DEX_KitKat.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_KitKat">+ <description>Dalvik DEX KitKat</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="ODEX KitKat"+ version="1.0"+ slafile="Dalvik_ODEX_KitKat.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:ODEX_KitKat">+ <description>Dalvik ODEX KitKat</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX Lollipop"+ version="1.0"+ slafile="Dalvik_DEX_Lollipop.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_Lollipop">+ <description>Dalvik DEX Lollipop</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX Marshmallow"+ version="1.0"+ slafile="Dalvik_DEX_Marshmallow.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:Marshmallow">+ <description>Dalvik DEX Marshmallow</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX Nougat"+ version="1.0"+ slafile="Dalvik_DEX_Nougat.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_Nougat">+ <description>Dalvik DEX Nougat</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX Oreo"+ version="1.0"+ slafile="Dalvik_DEX_Oreo.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_Oreo">+ <description>Dalvik DEX Oreo</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++<language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX Pie"+ version="1.0"+ slafile="Dalvik_DEX_Pie.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_Pie">+ <description>Dalvik DEX Pie</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX Android10"+ version="1.0"+ slafile="Dalvik_DEX_Android10.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_Android10">+ <description>Dalvik DEX Android10</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++ <language processor="Dalvik"+ endian="little"+ size="32"+ variant="DEX Android11"+ version="1.0"+ slafile="Dalvik_DEX_Android11.sla"+ processorspec="Dalvik_Base.pspec"+ id="Dalvik:LE:32:DEX_Android11">+ <description>Dalvik DEX Android11</description>+ <compiler name="default" spec="Dalvik_Base.cspec" id="default"/>+ </language>++</language_definitions>diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik.opinion b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.opinionsimilarity index 51%rename from Ghidra/Processors/Dalvik/data/languages/Dalvik.opinionrename to Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.opinionindex e395f8bb94..43a4def045 100644--- a/Ghidra/Processors/Dalvik/data/languages/Dalvik.opinion+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.opinion@@ -2,4 +2,7 @@<constraint loader="Dalvik Executable (DEX)" compilerSpecID="default"><constraint primary="1" processor="Dalvik" endian="little" size="32" /></constraint>+ <constraint loader="Compact Dalvik Executable (CDEX)" compilerSpecID="default">+ <constraint primary="1" processor="Dalvik" endian="little" size="32" />+ </constraint></opinions>diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik.pspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.pspecsimilarity index 79%rename from Ghidra/Processors/Dalvik/data/languages/Dalvik.pspecrename to Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.pspecindex 3585846d91..92e96494f6 100644--- a/Ghidra/Processors/Dalvik/data/languages/Dalvik.pspec+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.pspec@@ -3,12 +3,12 @@<processor_spec><properties><property key="DisableAllAnalyzers" value="value ignored, just turns them off"/>- <property key="Analyzers.Android DEX Condense Filler Bytes" value="true"/>- <property key="Analyzers.Android DEX Data Markup" value="true"/>- <property key="Analyzers.Android DEX Exception Handlers" value="true"/>- <property key="Analyzers.Android DEX Header Format" value="true"/>- <property key="Analyzers.Android DEX Instruction Markup" value="true"/>- <property key="Analyzers.Android DEX Switch Table Markup" value="true"/>+ <property key="Analyzers.Android DEX/CDEX Condense Filler Bytes" value="true"/>+ <property key="Analyzers.Android DEX/CDEX Data Markup" value="true"/>+ <property key="Analyzers.Android DEX/CDEX Exception Handlers" value="true"/>+ <property key="Analyzers.Android DEX/CDEX Header Format" value="true"/>+ <property key="Analyzers.Android DEX/CDEX Instruction Markup" value="true"/>+ <property key="Analyzers.Android DEX/CDEX Switch Table Markup" value="true"/><property key="Analyzers.Android ODEX Header Format" value="true"/><property key="pcodeInjectLibraryClass" value="ghidra.dalvik.dex.inject.PcodeInjectLibraryDex"/></properties>diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.sincsimilarity index 81%rename from Ghidra/Processors/Dalvik/data/languages/Dalvik.slaspecrename to Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.sincindex 77759e80a1..63a7e01266 100644--- a/Ghidra/Processors/Dalvik/data/languages/Dalvik.slaspec+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.sinc@@ -2,6 +2,10 @@# Sleigh specification file for DALVIK VM#------------------------------------------------------------------------------------+# Source:+# https://android.googlesource.com/platform/art/+/[...]/runtime/dex_instruction_list.h+# where [...] is the actual Android version name (ie "oreo-release")+define endian=little;define alignment=1;@@ -277,6 +281,10 @@ define pcodeop invokeVirtualQuickRange;define pcodeop switchAssist;+define pcodeop breakpoint;++#SOURCE: https://android.googlesource.com/platform/art/+/kitkat-dev/runtime/dex_instruction_list.h+#------------------------------------------------------------------------------------#------------------------------------------------------------------------------------@@ -806,8 +814,7 @@ define pcodeop switchAssist;:packed_switch registerA8,B_BITS_0_31_S is inst0=0x2b ; registerA8 ; B_BITS_0_31_S{distance:4 = B_BITS_0_31_S * 2;- # ident:2 = *[ram] ( inst_start + distance );- # if (ident != 0x0100) goto inst_next;+ ident:4 = *[ram] ( inst_start + distance );size2:2 = *[ram] ( inst_start + distance + 2 );sze:4 = zext( size2 );first_key:4 = *[ram] ( inst_start + distance + 2 + 2 );@@ -968,16 +975,6 @@ define pcodeop switchAssist;#------------------------------------------------------------------------------------#-------------------------------------------------------------------------------------# 0x3e unused-# 0x3f unused-# 0x40 unused-# 0x41 unused-# 0x42 unused-# 0x43 unused--#-------------------------------------------------------------------------------------#-------------------------------------------------------------------------------------# Perform the identified array operation at the identified index# of the given array, loading or storing into the value register.#@@ -1494,11 +1491,6 @@ define pcodeop switchAssist;#------------------------------------------------------------------------------------#-------------------------------------------------------------------------------------# 0x73 unused--#-------------------------------------------------------------------------------------#-------------------------------------------------------------------------------------# Call the indicated method.# See first invoke-kind description above for details, caveats, and suggestions.#@@ -1541,12 +1533,6 @@ define pcodeop switchAssist;#------------------------------------------------------------------------------------#-------------------------------------------------------------------------------------# 0x79 unused-# 0x7a unused--#-------------------------------------------------------------------------------------#-------------------------------------------------------------------------------------# Perform the identified unary operation on the source register,# storing the result in the destination register.#@@ -2037,356 +2023,3 @@ define pcodeop switchAssist;#------------------------------------------------------------------------------------#-------------------------------------------------------------------------------------:iget_volatile registerA4,[registerB4:C_BITS_0_15] is inst0=0xe3 ; registerA4 & registerB4 ; C_BITS_0_15-{- registerA4 = getInstanceFieldVolatile( registerB4, C_BITS_0_15:16 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iput_volatile registerA4,[registerB4:C_BITS_0_15] is inst0=0xe4 ; registerA4 & registerB4 ; C_BITS_0_15-{- setInstanceFieldVolatile( registerB4, C_BITS_0_15:16, registerA4 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:sget_volatile registerA8,B_BITS_0_15 is inst0=0xe5 ; registerA8 ; B_BITS_0_15-{- registerA8 = getStaticFieldVolatile( B_BITS_0_15:16 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:sput_volatile registerA8,B_BITS_0_15 is inst0=0xe6 ; registerA8 ; B_BITS_0_15-{- setStaticFieldVolatile( B_BITS_0_15:16, registerA8 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iget_object_volatile registerA4,[registerB4:C_BITS_0_15] is inst0=0xe7 ; registerA4 & registerB4 ; C_BITS_0_15-{- registerA4 = getInstanceFieldVolatile( registerB4, C_BITS_0_15:16 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iget_wide_volatile registerA4w,[registerB4:C_BITS_0_15] is inst0=0xe8 ; registerA4w & registerB4 ; C_BITS_0_15-{- registerA4w = getInstanceFieldVolatile( registerB4, C_BITS_0_15:16 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iput_wide_volatile registerA4w,[registerB4:C_BITS_0_15] is inst0=0xe9 ; registerA4w & registerB4 ; C_BITS_0_15-{- setInstanceFieldVolatile( registerB4, C_BITS_0_15:16, registerA4w );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:sget_wide_volatile registerA8w,B_BITS_0_15 is inst0=0xea ; registerA8w ; B_BITS_0_15-{- registerA8w = getStaticFieldVolatile( B_BITS_0_15:16 );-}---#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:sput_wide_volatile registerA8w,B_BITS_0_15 is inst0=0xeb ; registerA8w ; B_BITS_0_15-{- setStaticFieldVolatile( B_BITS_0_15:16, registerA8w );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iput_byte_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xec ; registerA4 & registerB4 ; C_BITS_0_15-{- setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:throw_verification_error registerA8,registerB16 is inst0=0xed ; registerA8 ; registerB16-{- registerA8 = registerB16;-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:execute_inline INLINE,{} is inst0=0xee ; N_PARAMS=0 & INLINE-{- destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );- call [ destination ];-}-:execute_inline INLINE,{regParamC} is inst0=0xee ; N_PARAMS=1 & INLINE & regParamC-{- destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );- call [ destination ];-}-:execute_inline INLINE,{regParamC,regParamD} is inst0=0xee ; N_PARAMS=2 & INLINE & regParamC & regParamD-{- destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );- call [ destination ];-}-:execute_inline INLINE,{regParamC,regParamD,regParamE} is inst0=0xee ; N_PARAMS=3 & INLINE & regParamC & regParamD & regParamE-{- destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );- call [ destination ];-}-:execute_inline INLINE,{regParamC,regParamD,regParamE,regParamF} is inst0=0xee ; N_PARAMS=4 & INLINE & regParamC & regParamD & regParamE & regParamF-{- destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );- call [ destination ];-}-:execute_inline INLINE,{regParamC,regParamD,regParamE,regParamF,regParamG} is inst0=0xee ; N_PARAMS=5 & INLINE & regParamC & regParamD & regParamE & regParamF & regParamG-{- destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );- call [ destination ];-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:execute_inline_range "inline@"^B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xef ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16-{- destination:4 = *[ram] ( ( 4 * B_BITS_0_15:4 ) + 0xe0000000 );- call [ destination ];-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------# THIS ODEX INSTRUCTION WAS VALID UNTIL API version 13 (OS Version 3.2.x)--# :invoke_direct_empty METHOD_INDEX is inst0=0xf0 ; N_PARAMS=0 & METHOD_INDEX-# {-# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );-# call [ destination ];-# }-# :invoke_direct_empty METHOD_INDEX,regParamC is inst0=0xf0 ; N_PARAMS=1 & METHOD_INDEX & regParamC-# {-# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );-# call [ destination ];-# }-# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD is inst0=0xf0 ; N_PARAMS=2 & METHOD_INDEX & regParamC & regParamD-# {-# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );-# call [ destination ];-# }-# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD,regParamE is inst0=0xf0 ; N_PARAMS=3 & METHOD_INDEX & regParamC & regParamD & regParamE-# {-# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );-# call [ destination ];-# }-# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD,regParamE,regParamF is inst0=0xf0 ; N_PARAMS=4 & METHOD_INDEX & regParamC & regParamD & regParamE & regParamF-# {-# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );-# call [ destination ];-# }-# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD,regParamE,regParamF,regParamG is inst0=0xf0 ; N_PARAMS=5 & METHOD_INDEX & regParamC & regParamD & regParamE & regParamF & regParamG-# {-# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );-# call [ destination ];-# }---# THIS ODEX INSTRUCTION WAS ADDED IN API version 14 (OS VERSIOn 4.0.x ICS)--:invoke_object_init_range B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xf0 ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16-{- destination:4 = *[ram] ( ( 4 * B_BITS_0_15:4 ) + 0xe0000000 );- call [ destination ];-}--# 0xf0 iget-byte-quick TODO All ART Versions--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:return_void_barrier is inst1=0xf1 & inst1_padding-{- return [sp];#TODO-}--# 0xf1 iget-char-quick TODO---#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iget_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf2 ; registerA4 & registerB4 ; C_BITS_0_15-{- registerA4 = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );-}--# 0xf2 iget-short-quick TODO--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iget_wide_quick "field@"^C_BITS_0_15,registerA4w,registerB4 is inst0=0xf3 ; registerA4w & registerB4 ; C_BITS_0_15-{- registerA4w = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );-}--# 0xf3 invoke-lambda TODO--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iget_object_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf4 ; registerA4 & registerB4 ; C_BITS_0_15-{- registerA4 = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iput_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf5 ; registerA4 & registerB4 ; C_BITS_0_15-{- setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );-}--# 0xf5 capture-variable TODO--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iput_wide_quick "field@"^C_BITS_0_15,registerA4w,registerB4 is inst0=0xf6 ; registerA4w & registerB4 ; C_BITS_0_15-{- setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4w );-}--# 0xf6 create-lambda TODO--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iput_object_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf7 ; registerA4 & registerB4 ; C_BITS_0_15-{- setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );-}--# 0xf7 liberate-variable TODO--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:invoke_virtual_quick "vtable@"^VTABLE_OFFSET is inst0=0xf8 ; N_PARAMS=0 & VTABLE_OFFSET-{- invokeVirtualQuick( VTABLE_OFFSET:4 );-}-:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC is inst0=0xf8 ; N_PARAMS=1 & VTABLE_OFFSET & regParamC-{- invokeVirtualQuick( VTABLE_OFFSET:4, regParamC );-}-:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD is inst0=0xf8 ; N_PARAMS=2 & VTABLE_OFFSET & regParamC & regParamD-{- invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD );-}-:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE is inst0=0xf8 ; N_PARAMS=3 & VTABLE_OFFSET & regParamC & regParamD & regParamE-{- invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE );-}-:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF is inst0=0xf8 ; N_PARAMS=4 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF-{- invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF );-}-:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF,regParamG is inst0=0xf8 ; N_PARAMS=5 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF & regParamG-{- invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF, regParamG );--}--# 0xf8 box-lambda TODO--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:invoke_virtual_quick_range "vtable@"^B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xf9 ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16-{- invokeVirtualQuickRange( B_BITS_0_15:4, A_BITS_0_7:4, registerC16 );-}--# 0xf9 unbox-lambda TODO--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:invoke_super_quick "vtable@"^VTABLE_OFFSET is inst0=0xfa ; N_PARAMS=0 & VTABLE_OFFSET-{- invokeSuperQuick( VTABLE_OFFSET:4 );-}-:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC is inst0=0xfa ; N_PARAMS=1 & VTABLE_OFFSET & regParamC-{- invokeSuperQuick( VTABLE_OFFSET:4, regParamC );-}-:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD is inst0=0xfa ; N_PARAMS=2 & VTABLE_OFFSET & regParamC & regParamD-{- invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD );-}-:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE is inst0=0xfa ; N_PARAMS=3 & VTABLE_OFFSET & regParamC & regParamD & regParamE-{- invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE );-}-:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF is inst0=0xfa ; N_PARAMS=4 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF-{- invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF );-}-:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF,regParamG is inst0=0xfa ; N_PARAMS=5 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF & regParamG-{- invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF, regParamG );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:invoke_super_quick_range "vtable@"^B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xfb ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16-{- invokeSuperQuickRange( B_BITS_0_15:4, A_BITS_0_7:4, registerC16 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:iput_object_volatile registerA4,registerB4,C_BITS_0_15 is inst0=0xfc ; registerA4 & registerB4 ; C_BITS_0_15-{- setInstanceFieldVolatile( registerB4, C_BITS_0_15:16, registerA4 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:sget_object_volatile registerA8,B_BITS_0_15 is inst0=0xfd ; registerA8 ; B_BITS_0_15-{- registerA8 = getStaticFieldVolatile( B_BITS_0_15:16 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------:sput_object_volatile registerA8,B_BITS_0_15 is inst0=0xfe ; registerA8 ; B_BITS_0_15-{- setStaticFieldVolatile( B_BITS_0_15:16, registerA8 );-}--#-------------------------------------------------------------------------------------#--------------------------------------------------------------------------------------# 0xff ?--#-------------------------------------------------------------------------------------#------------------------------------------------------------------------------------diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.slaspecnew file mode 100644index 0000000000..d2a9654381--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_Base.slaspec@@ -0,0 +1,5 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM (base set of instructions)+#------------------------------------------------------------------------------------++@include "Dalvik_Base.sinc"\ No newline at end of filediff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Android10.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Android10.slaspecnew file mode 100644index 0000000000..c303f120f5--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Android10.slaspec@@ -0,0 +1,30 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/refs/heads/android10-release/libdexfile/dex/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_no_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_iput_iget.sinc"++@include "Dalvik_OpCode_F3_unused.sinc"+@include "Dalvik_OpCode_F4_unused.sinc"+@include "Dalvik_OpCode_F5_unused.sinc"+@include "Dalvik_OpCode_F6_unused.sinc"+@include "Dalvik_OpCode_F7_unused.sinc"+@include "Dalvik_OpCode_F8_unused.sinc"+@include "Dalvik_OpCode_F9_unused.sinc"++@include "Dalvik_OpCode_FA_FD_dex.sinc"+@include "Dalvik_OpCode_FE_FF_dex.sinc"diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Android11.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Android11.slaspecnew file mode 100644index 0000000000..9829695c60--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Android11.slaspec@@ -0,0 +1,30 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/refs/heads/android11-release/libdexfile/dex/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_no_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_iput_iget.sinc"++@include "Dalvik_OpCode_F3_unused.sinc"+@include "Dalvik_OpCode_F4_unused.sinc"+@include "Dalvik_OpCode_F5_unused.sinc"+@include "Dalvik_OpCode_F6_unused.sinc"+@include "Dalvik_OpCode_F7_unused.sinc"+@include "Dalvik_OpCode_F8_unused.sinc"+@include "Dalvik_OpCode_F9_unused.sinc"++@include "Dalvik_OpCode_FA_FD_dex.sinc"+@include "Dalvik_OpCode_FE_FF_dex.sinc"\ No newline at end of filediff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_KitKat.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_KitKat.slaspecnew file mode 100644index 0000000000..d04373f467--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_KitKat.slaspec@@ -0,0 +1,33 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/refs/heads/kitkat-release/runtime/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_unused.sinc"++@include "Dalvik_OpCode_F3_unused.sinc"+@include "Dalvik_OpCode_F4_unused.sinc"+@include "Dalvik_OpCode_F5_unused.sinc"+@include "Dalvik_OpCode_F6_unused.sinc"+@include "Dalvik_OpCode_F7_unused.sinc"+@include "Dalvik_OpCode_F8_unused.sinc"+@include "Dalvik_OpCode_F9_unused.sinc"+@include "Dalvik_OpCode_FA_unused.sinc"+@include "Dalvik_OpCode_FB_unused.sinc"+@include "Dalvik_OpCode_FC_unused.sinc"+@include "Dalvik_OpCode_FD_unused.sinc"+@include "Dalvik_OpCode_FE_unused.sinc"+@include "Dalvik_OpCode_FF_unused.sinc"diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Lollipop.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Lollipop.slaspecnew file mode 100644index 0000000000..18bdd19adb--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Lollipop.slaspec@@ -0,0 +1,33 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/refs/heads/lollipop-release/runtime/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_unused.sinc"++@include "Dalvik_OpCode_F3_unused.sinc"+@include "Dalvik_OpCode_F4_unused.sinc"+@include "Dalvik_OpCode_F5_unused.sinc"+@include "Dalvik_OpCode_F6_unused.sinc"+@include "Dalvik_OpCode_F7_unused.sinc"+@include "Dalvik_OpCode_F8_unused.sinc"+@include "Dalvik_OpCode_F9_unused.sinc"+@include "Dalvik_OpCode_FA_unused.sinc"+@include "Dalvik_OpCode_FB_unused.sinc"+@include "Dalvik_OpCode_FC_unused.sinc"+@include "Dalvik_OpCode_FD_unused.sinc"+@include "Dalvik_OpCode_FE_unused.sinc"+@include "Dalvik_OpCode_FF_unused.sinc"diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Marshmallow.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Marshmallow.slaspecnew file mode 100644index 0000000000..88a620bff4--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Marshmallow.slaspec@@ -0,0 +1,33 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/refs/heads/marshmallow-release/runtime/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_no_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_iput_iget.sinc"++@include "Dalvik_OpCode_F3_unused.sinc"+@include "Dalvik_OpCode_F4_unused.sinc"+@include "Dalvik_OpCode_F5_unused.sinc"+@include "Dalvik_OpCode_F6_unused.sinc"+@include "Dalvik_OpCode_F7_unused.sinc"+@include "Dalvik_OpCode_F8_unused.sinc"+@include "Dalvik_OpCode_F9_unused.sinc"+@include "Dalvik_OpCode_FA_unused.sinc"+@include "Dalvik_OpCode_FB_unused.sinc"+@include "Dalvik_OpCode_FC_unused.sinc"+@include "Dalvik_OpCode_FD_unused.sinc"+@include "Dalvik_OpCode_FE_unused.sinc"+@include "Dalvik_OpCode_FF_unused.sinc"diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Nougat.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Nougat.slaspecnew file mode 100644index 0000000000..9ef27d1111--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Nougat.slaspec@@ -0,0 +1,129 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/refs/heads/nougat-release/runtime/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_no_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_iput_iget.sinc"++@include "Dalvik_OpCode_F4_unused.sinc"++@include "Dalvik_OpCode_FA_unused.sinc"+@include "Dalvik_OpCode_FB_unused.sinc"+@include "Dalvik_OpCode_FC_unused.sinc"+@include "Dalvik_OpCode_FD_unused.sinc"+@include "Dalvik_OpCode_FE_unused.sinc"+@include "Dalvik_OpCode_FF_unused.sinc"++define pcodeop invokeLamda;++define token invokeLamda_operands ( 24 )+ LAMBDA_vB = ( 4 , 7 )+ LAMBDA_vG = ( 0 , 3 )+ LAMBDA_vD = ( 12 , 15 )+ LAMBDA_vC = ( 8 , 11 )+ LAMBDA_vF = ( 20 , 23 )+ LAMBDA_vE = ( 16 , 19 )+;++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF3, INVOKE_LAMBDA, "invoke-lambda", k25x, false, kIndexNone, kContinue | kThrow | kInvoke | kExperimental, kVerifyRegC /*TODO: | kVerifyVarArg*/) \+# k25x, // op vC, {vD, vE, vF, vG} (B: count)+#+# See https://android.googlesource.com/platform/art/+/nougat-release/runtime/dex_instruction-inl.h+#+# * uint16 ||| uint16+# * 7-0 15-8 7-0 15-8+# * |------|-----|||-----|-----|+# * |opcode|vB|vG|||vD|vC|vF|vE|+# * |------|-----|||-----|-----|+#+# e.g. invoke-lambda vClosure, {vD, vE, vF, vG} -- up to 4 parameters + the closure.++:invoke_lambda LAMBDA_vC,{} is inst0=0xf3 ; LAMBDA_vB=0 ;LAMBDA_vG ; LAMBDA_vD ; LAMBDA_vC ; LAMBDA_vF; LAMBDA_vE+{+ #TODO pCode+}+:invoke_lambda LAMBDA_vC,{LAMBDA_vD} is inst0=0xf3 ; LAMBDA_vB=1 ;LAMBDA_vG ; LAMBDA_vD ; LAMBDA_vC ; LAMBDA_vF; LAMBDA_vE+{+ #TODO pCode+}+:invoke_lambda LAMBDA_vC,{LAMBDA_vD,LAMBDA_vE} is inst0=0xf3 ; LAMBDA_vB=2 ;LAMBDA_vG ; LAMBDA_vD ; LAMBDA_vC ; LAMBDA_vF; LAMBDA_vE+{+ #TODO pCode+}+:invoke_lambda LAMBDA_vC,{LAMBDA_vD,LAMBDA_vE,LAMBDA_vF} is inst0=0xf3 ; LAMBDA_vB=3 ;LAMBDA_vG ; LAMBDA_vD ; LAMBDA_vC ; LAMBDA_vF; LAMBDA_vE+{+ #TODO pCode+}+:invoke_lambda LAMBDA_vC,{LAMBDA_vD,LAMBDA_vE,LAMBDA_vF,LAMBDA_vG} is inst0=0xf3 ; LAMBDA_vB=4 ;LAMBDA_vG ; LAMBDA_vD ; LAMBDA_vC ; LAMBDA_vF; LAMBDA_vE+{+ #TODO pCode+}+++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF5, CAPTURE_VARIABLE, "capture-variable", k21c, false, kIndexStringRef, kExperimental, kVerifyRegA | kVerifyRegBString) \+#+# e.g. capture-variable v1, "foobar"++:capture_variable registerA8,B_BITS_0_15 is inst0=0xf5 ; registerA8 ; B_BITS_0_15+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF6, CREATE_LAMBDA, "create-lambda", k21c, false_UNUSED, kIndexMethodRef, kContinue | kThrow | kExperimental, kVerifyRegA | kVerifyRegBMethod) \+#+# e.g. create-lambda v1, "java/io/PrintStream/print(Ljava/lang/Stream;)V"++:create_lambda registerA8,B_BITS_0_15 is inst0=0xf6 ; registerA8 ; B_BITS_0_15+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF7, LIBERATE_VARIABLE, "liberate-variable", k22c, false, kIndexStringRef, kExperimental, kVerifyRegA | kVerifyRegB | kVerifyRegCString) \+#+# e.g. liberate-variable v0, v1, "baz"++:liberate_variable registerA4,registerB4,C_BITS_0_15 is inst0=0xf7 ; registerA4 & registerB4 ; C_BITS_0_15+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF8, BOX_LAMBDA, "box-lambda", k22x, true, kIndexNone, kContinue | kExperimental, kVerifyRegA | kVerifyRegB) \++:box_lambda registerA8,registerB16 is inst0=0xf8 ; registerA8 ; registerB16+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF9, UNBOX_LAMBDA, "unbox-lambda", k22c, true, kIndexTypeRef, kContinue | kThrow | kExperimental, kVerifyRegA | kVerifyRegB | kVerifyRegCType) \++:unbox_lambda registerA4,registerB4,C_BITS_0_15 is inst0=0xf9 ; registerA4 & registerB4 ; C_BITS_0_15+{+ #TODO pCode+}++diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Oreo.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Oreo.slaspecnew file mode 100644index 0000000000..b82f6d5dfe--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Oreo.slaspec@@ -0,0 +1,35 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/oreo-release/runtime/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_no_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_iput_iget.sinc"++@include "Dalvik_OpCode_F3_unused.sinc"+@include "Dalvik_OpCode_F4_unused.sinc"+@include "Dalvik_OpCode_F5_unused.sinc"+@include "Dalvik_OpCode_F6_unused.sinc"+@include "Dalvik_OpCode_F7_unused.sinc"+@include "Dalvik_OpCode_F8_unused.sinc"+@include "Dalvik_OpCode_F9_unused.sinc"++@include "Dalvik_OpCode_FA_FD_dex.sinc"++@include "Dalvik_OpCode_FE_unused.sinc"+@include "Dalvik_OpCode_FF_unused.sinc"+++diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Pie.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Pie.slaspecnew file mode 100644index 0000000000..c04c6ccbd5--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_DEX_Pie.slaspec@@ -0,0 +1,30 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------++# Source:+# https://android.googlesource.com/platform/art/+/refs/heads/pie-release/libdexfile/dex/dex_instruction_list.h++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_return_void_no_barrier.sinc"++@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_E3_EA_dex.sinc"++@include "Dalvik_OpCode_EB_F2_iput_iget.sinc"++@include "Dalvik_OpCode_F3_unused.sinc"+@include "Dalvik_OpCode_F4_unused.sinc"+@include "Dalvik_OpCode_F5_unused.sinc"+@include "Dalvik_OpCode_F6_unused.sinc"+@include "Dalvik_OpCode_F7_unused.sinc"+@include "Dalvik_OpCode_F8_unused.sinc"+@include "Dalvik_OpCode_F9_unused.sinc"++@include "Dalvik_OpCode_FA_FD_dex.sinc"+@include "Dalvik_OpCode_FE_FF_dex.sinc"diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_ODEX_KitKat.slaspec b/Ghidra/Processors/Dalvik/data/languages/Dalvik_ODEX_KitKat.slaspecnew file mode 100644index 0000000000..4b29e97c6e--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_ODEX_KitKat.slaspec@@ -0,0 +1,359 @@+#------------------------------------------------------------------------------------+# Sleigh specification file for DALVIK VM+#------------------------------------------------------------------------------------+#+# Source:+# https://android.googlesource.com/platform/dalvik/+/refs/heads/kitkat-release/libdex/DexFile.h+# https://android.googlesource.com/platform/dalvik/+/refs/heads/kitkat-release/libdex/DexOpcodes.h+#++@include "Dalvik_Base.sinc"++@include "Dalvik_OpCode_3E_43_unused.sinc"++@include "Dalvik_OpCode_73_unused.sinc"+@include "Dalvik_OpCode_79_unused.sinc"+@include "Dalvik_OpCode_7A_unused.sinc"++@include "Dalvik_OpCode_FF_unused.sinc"+++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iget_volatile registerA4,[registerB4:C_BITS_0_15] is inst0=0xe3 ; registerA4 & registerB4 ; C_BITS_0_15+{+ registerA4 = getInstanceFieldVolatile( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iput_volatile registerA4,[registerB4:C_BITS_0_15] is inst0=0xe4 ; registerA4 & registerB4 ; C_BITS_0_15+{+ setInstanceFieldVolatile( registerB4, C_BITS_0_15:16, registerA4 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:sget_volatile registerA8,B_BITS_0_15 is inst0=0xe5 ; registerA8 ; B_BITS_0_15+{+ registerA8 = getStaticFieldVolatile( B_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:sput_volatile registerA8,B_BITS_0_15 is inst0=0xe6 ; registerA8 ; B_BITS_0_15+{+ setStaticFieldVolatile( B_BITS_0_15:16, registerA8 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iget_object_volatile registerA4,[registerB4:C_BITS_0_15] is inst0=0xe7 ; registerA4 & registerB4 ; C_BITS_0_15+{+ registerA4 = getInstanceFieldVolatile( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iget_wide_volatile registerA4w,[registerB4:C_BITS_0_15] is inst0=0xe8 ; registerA4w & registerB4 ; C_BITS_0_15+{+ registerA4w = getInstanceFieldVolatile( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iput_wide_volatile registerA4w,[registerB4:C_BITS_0_15] is inst0=0xe9 ; registerA4w & registerB4 ; C_BITS_0_15+{+ setInstanceFieldVolatile( registerB4, C_BITS_0_15:16, registerA4w );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:sget_wide_volatile registerA8w,B_BITS_0_15 is inst0=0xea ; registerA8w ; B_BITS_0_15+{+ registerA8w = getStaticFieldVolatile( B_BITS_0_15:16 );+}+++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:sput_wide_volatile registerA8w,B_BITS_0_15 is inst0=0xeb ; registerA8w ; B_BITS_0_15+{+ setStaticFieldVolatile( B_BITS_0_15:16, registerA8w );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++#:iput_byte_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xec ; registerA4 & registerB4 ; C_BITS_0_15+#{+# setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );+#}++:breakpoint is inst0=0xec+{+ #TODO+ breakpoint( );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:throw_verification_error registerA8,registerB16 is inst0=0xed ; registerA8 ; registerB16+{+ registerA8 = registerB16;+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:execute_inline INLINE,{} is inst0=0xee ; N_PARAMS=0 & INLINE+{+ destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );+ call [ destination ];+}+:execute_inline INLINE,{regParamC} is inst0=0xee ; N_PARAMS=1 & INLINE & regParamC+{+ destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );+ call [ destination ];+}+:execute_inline INLINE,{regParamC,regParamD} is inst0=0xee ; N_PARAMS=2 & INLINE & regParamC & regParamD+{+ destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );+ call [ destination ];+}+:execute_inline INLINE,{regParamC,regParamD,regParamE} is inst0=0xee ; N_PARAMS=3 & INLINE & regParamC & regParamD & regParamE+{+ destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );+ call [ destination ];+}+:execute_inline INLINE,{regParamC,regParamD,regParamE,regParamF} is inst0=0xee ; N_PARAMS=4 & INLINE & regParamC & regParamD & regParamE & regParamF+{+ destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );+ call [ destination ];+}+:execute_inline INLINE,{regParamC,regParamD,regParamE,regParamF,regParamG} is inst0=0xee ; N_PARAMS=5 & INLINE & regParamC & regParamD & regParamE & regParamF & regParamG+{+ destination:4 = *[ram] ( ( 4 * INLINE:4 ) + 0xe0000000 );+ call [ destination ];+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:execute_inline_range "inline@"^B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xef ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16+{+ destination:4 = *[ram] ( ( 4 * B_BITS_0_15:4 ) + 0xe0000000 );+ call [ destination ];+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++# THIS ODEX INSTRUCTION WAS VALID UNTIL API version 13 (OS Version 3.2.x)++# :invoke_direct_empty METHOD_INDEX is inst0=0xf0 ; N_PARAMS=0 & METHOD_INDEX+# {+# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );+# call [ destination ];+# }+# :invoke_direct_empty METHOD_INDEX,regParamC is inst0=0xf0 ; N_PARAMS=1 & METHOD_INDEX & regParamC+# {+# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );+# call [ destination ];+# }+# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD is inst0=0xf0 ; N_PARAMS=2 & METHOD_INDEX & regParamC & regParamD+# {+# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );+# call [ destination ];+# }+# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD,regParamE is inst0=0xf0 ; N_PARAMS=3 & METHOD_INDEX & regParamC & regParamD & regParamE+# {+# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );+# call [ destination ];+# }+# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD,regParamE,regParamF is inst0=0xf0 ; N_PARAMS=4 & METHOD_INDEX & regParamC & regParamD & regParamE & regParamF+# {+# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );+# call [ destination ];+# }+# :invoke_direct_empty METHOD_INDEX,regParamC,regParamD,regParamE,regParamF,regParamG is inst0=0xf0 ; N_PARAMS=5 & METHOD_INDEX & regParamC & regParamD & regParamE & regParamF & regParamG+# {+# destination:4 = *[ram] ( ( 4 * METHOD_INDEX:4 ) + 0xe0000000 );+# call [ destination ];+# }++:invoke_object_init_range B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xf0 ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16+{+ destination:4 = *[ram] ( ( 4 * B_BITS_0_15:4 ) + 0xe0000000 );+ call [ destination ];+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:return_void_barrier is inst1=0xf1 & inst1_padding+{+ return [sp];#TODO+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iget_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf2 ; registerA4 & registerB4 ; C_BITS_0_15+{+ registerA4 = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iget_wide_quick "field@"^C_BITS_0_15,registerA4w,registerB4 is inst0=0xf3 ; registerA4w & registerB4 ; C_BITS_0_15+{+ registerA4w = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iget_object_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf4 ; registerA4 & registerB4 ; C_BITS_0_15+{+ registerA4 = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iput_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf5 ; registerA4 & registerB4 ; C_BITS_0_15+{+ setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iput_wide_quick "field@"^C_BITS_0_15,registerA4w,registerB4 is inst0=0xf6 ; registerA4w & registerB4 ; C_BITS_0_15+{+ setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4w );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iput_object_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xf7 ; registerA4 & registerB4 ; C_BITS_0_15+{+ setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:invoke_virtual_quick "vtable@"^VTABLE_OFFSET is inst0=0xf8 ; N_PARAMS=0 & VTABLE_OFFSET+{+ invokeVirtualQuick( VTABLE_OFFSET:4 );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC is inst0=0xf8 ; N_PARAMS=1 & VTABLE_OFFSET & regParamC+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD is inst0=0xf8 ; N_PARAMS=2 & VTABLE_OFFSET & regParamC & regParamD+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE is inst0=0xf8 ; N_PARAMS=3 & VTABLE_OFFSET & regParamC & regParamD & regParamE+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF is inst0=0xf8 ; N_PARAMS=4 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF,regParamG is inst0=0xf8 ; N_PARAMS=5 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF & regParamG+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF, regParamG );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:invoke_virtual_quick_range "vtable@"^B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xf9 ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16+{+ invokeVirtualQuickRange( B_BITS_0_15:4, A_BITS_0_7:4, registerC16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:invoke_super_quick "vtable@"^VTABLE_OFFSET is inst0=0xfa ; N_PARAMS=0 & VTABLE_OFFSET+{+ invokeSuperQuick( VTABLE_OFFSET:4 );+}+:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC is inst0=0xfa ; N_PARAMS=1 & VTABLE_OFFSET & regParamC+{+ invokeSuperQuick( VTABLE_OFFSET:4, regParamC );+}+:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD is inst0=0xfa ; N_PARAMS=2 & VTABLE_OFFSET & regParamC & regParamD+{+ invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD );+}+:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE is inst0=0xfa ; N_PARAMS=3 & VTABLE_OFFSET & regParamC & regParamD & regParamE+{+ invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE );+}+:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF is inst0=0xfa ; N_PARAMS=4 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF+{+ invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF );+}+:invoke_super_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF,regParamG is inst0=0xfa ; N_PARAMS=5 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF & regParamG+{+ invokeSuperQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF, regParamG );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:invoke_super_quick_range "vtable@"^B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xfb ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16+{+ invokeSuperQuickRange( B_BITS_0_15:4, A_BITS_0_7:4, registerC16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:iput_object_volatile registerA4,registerB4,C_BITS_0_15 is inst0=0xfc ; registerA4 & registerB4 ; C_BITS_0_15+{+ setInstanceFieldVolatile( registerB4, C_BITS_0_15:16, registerA4 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:sget_object_volatile registerA8,B_BITS_0_15 is inst0=0xfd ; registerA8 ; B_BITS_0_15+{+ registerA8 = getStaticFieldVolatile( B_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:sput_object_volatile registerA8,B_BITS_0_15 is inst0=0xfe ; registerA8 ; B_BITS_0_15+{+ setStaticFieldVolatile( B_BITS_0_15:16, registerA8 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++# 0xff ?++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_3E_43_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_3E_43_unused.sincnew file mode 100644index 0000000000..aecfcfefa8--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_3E_43_unused.sinc@@ -0,0 +1,54 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x3E, UNUSED_3E, "unused-3e", k10x, false, kUnknown, 0, kVerifyError) \++:unused_3e is inst0=0x3e+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x3F, UNUSED_3F, "unused-3f", k10x, false, kUnknown, 0, kVerifyError) \++:unused_3f is inst0=0x3f+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x40, UNUSED_40, "unused-40", k10x, false, kUnknown, 0, kVerifyError) \++:unused_40 is inst0=0x40+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x41, UNUSED_41, "unused-41", k10x, false, kUnknown, 0, kVerifyError) \++:unused_41 is inst0=0x41+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x42, UNUSED_42, "unused-42", k10x, false, kUnknown, 0, kVerifyError) \++:unused_42 is inst0=0x42+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x43, UNUSED_43, "unused-43", k10x, false, kUnknown, 0, kVerifyError) \++:unused_43 is inst0=0x43+{+ #no pCode+}+diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_return_void_barrier.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_return_void_barrier.sincnew file mode 100644index 0000000000..327889469e--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_return_void_barrier.sinc@@ -0,0 +1,7 @@+#------------------------------------------------------------------------------------+# V(0x73, RETURN_VOID_BARRIER, "return-void-barrier", k10x, false, kNone, kReturn, kVerifyNone) \++:return_void_barrier is inst1=0x73 & inst1_padding+{+ return [sp];+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_return_void_no_barrier.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_return_void_no_barrier.sincnew file mode 100644index 0000000000..f3786d5c46--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_return_void_no_barrier.sinc@@ -0,0 +1,7 @@+#------------------------------------------------------------------------------------+# V(0x73, RETURN_VOID_NO_BARRIER, "return-void-no-barrier", k10x, false, kNone, kReturn, kVerifyNone) \++:return_void_no_barrier is inst1=0x73 & inst1_padding+{+ return [sp];+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_unused.sincnew file mode 100644index 0000000000..eb2aaccee0--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_73_unused.sinc@@ -0,0 +1,7 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------++:unused_73 is inst0=0x73+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_79_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_79_unused.sincnew file mode 100644index 0000000000..3cf6230760--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_79_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x79, UNUSED_79, "unused-79", k10x, false, kUnknown, 0, kVerifyError) \++:unused_79 is inst0=0x79+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_7A_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_7A_unused.sincnew file mode 100644index 0000000000..7409b47cef--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_7A_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0x7A, UNUSED_7A, "unused-7a", k10x, false, kUnknown, 0, kVerifyError) \++:unused_7a is inst0=0x7a+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_E3_EA_dex.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_E3_EA_dex.sincnew file mode 100644index 0000000000..e7c5f913d1--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_E3_EA_dex.sinc@@ -0,0 +1,94 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xE3, IGET_QUICK, "iget-quick", k22c, true, kFieldRef, kContinue | kThrow, kVerifyRegA | kVerifyRegB) \++:iget_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xe3 ; registerA4 & registerB4 ; C_BITS_0_15+{+ registerA4 = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xE4, IGET_WIDE_QUICK, "iget-wide-quick", k22c, true, kFieldRef, kContinue | kThrow, kVerifyRegAWide | kVerifyRegB) \++:iget_wide_quick "field@"^C_BITS_0_15,registerA4w,registerB4 is inst0=0xe4 ; registerA4w & registerB4 ; C_BITS_0_15+{+ registerA4w = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xE5, IGET_OBJECT_QUICK, "iget-object-quick", k22c, true, kFieldRef, kContinue | kThrow, kVerifyRegA | kVerifyRegB) \++:iget_object_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xe5 ; registerA4 & registerB4 ; C_BITS_0_15+{+ registerA4 = getInstanceFieldQuick( registerB4, C_BITS_0_15:16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xE6, IPUT_QUICK, "iput-quick", k22c, false, kFieldRef, kContinue | kThrow, kVerifyRegA | kVerifyRegB) \++:iput_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xe6 ; registerA4 & registerB4 ; C_BITS_0_15+{+ setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xE7, IPUT_WIDE_QUICK, "iput-wide-quick", k22c, false, kFieldRef, kContinue | kThrow, kVerifyRegAWide | kVerifyRegB) \++:iput_wide_quick "field@"^C_BITS_0_15,registerA4w,registerB4 is inst0=0xe7 ; registerA4w & registerB4 ; C_BITS_0_15+{+ setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4w );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xE8, IPUT_OBJECT_QUICK, "iput-object-quick", k22c, false, kFieldRef, kContinue | kThrow, kVerifyRegA | kVerifyRegB) \++:iput_object_quick "field@"^C_BITS_0_15,registerA4,registerB4 is inst0=0xe8 ; registerA4 & registerB4 ; C_BITS_0_15+{+ setInstanceFieldQuick( registerB4, C_BITS_0_15:16, registerA4 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xE9, INVOKE_VIRTUAL_QUICK, "invoke-virtual-quick", k35c, false, kMethodRef, kContinue | kThrow | kInvoke, kVerifyVarArg) \++:invoke_virtual_quick "vtable@"^VTABLE_OFFSET is inst0=0xe9 ; N_PARAMS=0 & VTABLE_OFFSET+{+ invokeVirtualQuick( VTABLE_OFFSET:4 );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC is inst0=0xe9 ; N_PARAMS=1 & VTABLE_OFFSET & regParamC+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD is inst0=0xe9 ; N_PARAMS=2 & VTABLE_OFFSET & regParamC & regParamD+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE is inst0=0xe9 ; N_PARAMS=3 & VTABLE_OFFSET & regParamC & regParamD & regParamE+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF is inst0=0xe9 ; N_PARAMS=4 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF );+}+:invoke_virtual_quick "vtable@"^VTABLE_OFFSET,regParamC,regParamD,regParamE,regParamF,regParamG is inst0=0xe9 ; N_PARAMS=5 & VTABLE_OFFSET & regParamC & regParamD & regParamE & regParamF & regParamG+{+ invokeVirtualQuick( VTABLE_OFFSET:4, regParamC, regParamD, regParamE, regParamF, regParamG );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xEA, INVOKE_VIRTUAL_RANGE_QUICK, "invoke-virtual/range-quick", k3rc, false, kMethodRef, kContinue | kThrow | kInvoke, kVerifyVarArgRange) \++:invoke_virtual_quick_range "vtable@"^B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xea ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16+{+ invokeVirtualQuickRange( B_BITS_0_15:4, A_BITS_0_7:4, registerC16 );+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_EB_F2_iput_iget.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_EB_F2_iput_iget.sincnew file mode 100644index 0000000000..2a9b4b1b74--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_EB_F2_iput_iget.sinc@@ -0,0 +1,71 @@+#------------------------------------------------------------------------------------+# V(0xEB, IPUT_BOOLEAN_QUICK, "iput-boolean-quick", k22c, false, kFieldRef, kContinue | kThrow | kStore | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iput_boolean_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xeb ; registerA4 & registerB4 ; C_BITS_0_15+{+ ptr:4 = cpool(registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ *ptr = registerA4 : 1;+}++#------------------------------------------------------------------------------------+# V(0xEC, IPUT_BYTE_QUICK, "iput-byte-quick", k22c, false, kFieldRef, kContinue | kThrow | kStore | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iput_byte_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xec ; registerA4 & registerB4 ; C_BITS_0_15+ {+ ptr:4 = cpool(registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ *ptr = registerA4 : 1;+}++#------------------------------------------------------------------------------------+# V(0xED, IPUT_CHAR_QUICK, "iput-char-quick", k22c, false, kFieldRef, kContinue | kThrow | kStore | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iput_char_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xed ; registerA4 & registerB4 ; C_BITS_0_15+{+ ptr:4 = cpool(registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ *ptr = registerA4 : 2;+}++#------------------------------------------------------------------------------------+# V(0xEE, IPUT_SHORT_QUICK, "iput-short-quick", k22c, false, kFieldRef, kContinue | kThrow | kStore | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iput_short_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xee ; registerA4 & registerB4 ; C_BITS_0_15+{+ ptr:4 = cpool(registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ *ptr = registerA4 : 2;+}++#------------------------------------------------------------------------------------+# V(0xEF, IGET_BOOLEAN_QUICK, "iget-boolean-quick", k22c, true, kFieldRef, kContinue | kThrow | kLoad | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iget_boolean_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xef ; registerA4 & registerB4 ; C_BITS_0_15+{+ ptr:4 = cpool( registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ registerA4 = zext( *:1 ptr );+}++#------------------------------------------------------------------------------------+# V(0xF0, IGET_BYTE_QUICK, "iget-byte-quick", k22c, true, kFieldRef, kContinue | kThrow | kLoad | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iget_byte_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xf0 ; registerA4 & registerB4 ; C_BITS_0_15+{+ ptr:4 = cpool( registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ registerA4 = sext( *:1 ptr );+}++#------------------------------------------------------------------------------------+# V(0xF1, IGET_CHAR_QUICK, "iget-char-quick", k22c, true, kFieldRef, kContinue | kThrow | kLoad | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iget_char_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xf1 ; registerA4 & registerB4 ; C_BITS_0_15+ {+ ptr:4 = cpool( registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ registerA4 = zext( *:2 ptr );+}++#------------------------------------------------------------------------------------+# V(0xF2, IGET_SHORT_QUICK, "iget-short-quick", k22c, true, kFieldRef, kContinue | kThrow | kLoad | kRegCFieldOrConstant, kVerifyRegA | kVerifyRegB | kVerifyRuntimeOnly) \++:iget_short_quick registerA4,[registerB4:C_BITS_0_15] is inst0=0xf2 ; registerA4 & registerB4 ; C_BITS_0_15+{+ ptr:4 = cpool( registerB4, C_BITS_0_15:4, $(CPOOL_FIELD));+ registerA4 = sext( *:2 ptr );+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_EB_F2_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_EB_F2_unused.sincnew file mode 100644index 0000000000..09a3aa86f1--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_EB_F2_unused.sinc@@ -0,0 +1,71 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xEB, UNUSED_EB, "unused-eb", k10x, false, kUnknown, 0, kVerifyError) \++:unused_eb is inst0=0xeb+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xEC, UNUSED_EC, "unused-ec", k10x, false, kUnknown, 0, kVerifyError) \++:unused_ec is inst0=0xec+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xED, UNUSED_ED, "unused-ed", k10x, false, kUnknown, 0, kVerifyError) \++:unused_ed is inst0=0xed+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xEE, UNUSED_EE, "unused-ee", k10x, false, kUnknown, 0, kVerifyError) \++:unused_ee is inst0=0xee+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xEF, UNUSED_EF, "unused-ef", k10x, false, kUnknown, 0, kVerifyError) \++:unused_ef is inst0=0xef+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF0, UNUSED_F0, "unused-f0", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f0 is inst0=0xf0+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF1, UNUSED_F1, "unused-f1", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f1 is inst0=0xf1+{+ #no pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF2, UNUSED_F2, "unused-f2", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f2 is inst0=0xf2+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F3_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F3_unused.sincnew file mode 100644index 0000000000..0e2cc34343--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F3_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF3, UNUSED_F3, "unused-f3", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f3 is inst0=0xf3+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F4_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F4_unused.sincnew file mode 100644index 0000000000..1e76ac5b93--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F4_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF4, UNUSED_F4, "unused-f4", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f4 is inst0=0xf4+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F5_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F5_unused.sincnew file mode 100644index 0000000000..9e06181848--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F5_unused.sinc@@ -0,0 +1,9 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF5, UNUSED_F5, "unused-f5", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f5 is inst0=0xf5+{+ #no pCode+}+diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F6_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F6_unused.sincnew file mode 100644index 0000000000..0283f74d89--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F6_unused.sinc@@ -0,0 +1,9 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF6, UNUSED_F6, "unused-f6", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f6 is inst0=0xf6+{+ #no pCode+}+diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F7_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F7_unused.sincnew file mode 100644index 0000000000..ec082591fe--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F7_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF7, UNUSED_F7, "unused-f7", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f7 is inst0=0xf7+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F8_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F8_unused.sincnew file mode 100644index 0000000000..2ea3d0d90d--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F8_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF8, UNUSED_F8, "unused-f8", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f8 is inst0=0xf8+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F9_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F9_unused.sincnew file mode 100644index 0000000000..d36d1a92f0--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_F9_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xF9, UNUSED_F9, "unused-f9", k10x, false, kUnknown, 0, kVerifyError) \++:unused_f9 is inst0=0xf9+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FA_FD_dex.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FA_FD_dex.sincnew file mode 100644index 0000000000..5709a7bce5--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FA_FD_dex.sinc@@ -0,0 +1,178 @@+define token invoke_poly_operands_2 ( 8 )+ POLY_ARG_COUNT = ( 4 , 7 )+ POLY_PARAM_G = ( 0 , 3 )+;++define token invoke_poly_operands_1 ( 48 )+ POLY_METHOD_INDEX = ( 0 , 15 )+ POLY_PARAM_D = ( 16 , 19 )+ POLY_PARAM_C = ( 20 , 23 )+ POLY_PARAM_F = ( 24 , 27 )+ POLY_PARAM_E = ( 28 , 31 )+ POLY_PROTO_INDEX = ( 32 , 47 )+;++#define token invoke_poly_operands_1 ( 64 )+# POLY_METHOD_INDEX = ( 0 , 15 )+# POLY_METHOD_HANDLE = ( 16 , 31 )+# POLY_PARAM_D = ( 32 , 35 )+# POLY_PARAM_C = ( 36 , 39 )+# POLY_PARAM_F = ( 40 , 43 )+# POLY_PARAM_E = ( 44 , 47 )+# POLY_PROTO_INDEX = ( 48 , 63 )+#;++regPolyC: reg is POLY_PARAM_C [ reg = (POLY_PARAM_C * 4) + 0x1000; ] { export *[register]:4 reg; }+regPolyD: reg is POLY_PARAM_D [ reg = (POLY_PARAM_D * 4) + 0x1000; ] { export *[register]:4 reg; }+regPolyE: reg is POLY_PARAM_E [ reg = (POLY_PARAM_E * 4) + 0x1000; ] { export *[register]:4 reg; }+regPolyF: reg is POLY_PARAM_F [ reg = (POLY_PARAM_F * 4) + 0x1000; ] { export *[register]:4 reg; }+regPolyG: reg is POLY_PARAM_G [ reg = (POLY_PARAM_G * 4) + 0x1000; ] { export *[register]:4 reg; }++define token invoke_poly_range_operands ( 40 )+ POLY_RANGE_ARG_COUNT = ( 0 , 7 )+ POLY_RANGE_METHOD_INDEX = ( 8 , 23 )+ POLY_RANGE_PROTO_INDEX = ( 24 , 39 )+;++#------------------------------------------------------------------------------------+# V(0xFA, INVOKE_POLYMORPHIC, "invoke-polymorphic", k45cc, kIndexMethodAndProtoRef, kContinue | kThrow | kInvoke, kVerifyRegBMethod | kVerifyVarArgNonZero | kVerifyRegHPrototype) \+#+# invoke-polymorphic {vC, vD, vE, vF, vG}, meth@BBBB, proto@HHHH+#+# A: argument word count (4 bits)+# B: method reference index (16 bits)+# C: method handle reference to invoke (16 bits)+# D..G: argument registers (4 bits each)+# H: prototype reference index (16 bits)+#+# case Instruction::k45cc: { // op {vC, vD, vE, vF, vG}, method@BBBB, proto@HHHH+#+# Invoke the indicated method handle.+# The result (if any) may be stored with an appropriate move-result* variant as the immediately subsequent instruction.+# The method reference must be to java.lang.invoke.MethodHandle.invoke or java.lang.invoke.MethodHandle.invokeExact.+# The prototype reference describes the argument types provided and the expected return type.+#+# Present in Dex files from version 038 onwards.++:invoke_polymorphic "meth@"^POLY_METHOD_INDEX,"proto@"^POLY_PROTO_INDEX,{} is inst0=0xfa ; POLY_ARG_COUNT=0 ; POLY_METHOD_INDEX & POLY_PROTO_INDEX+{+ #TODO pCode+}+:invoke_polymorphic "meth@"^POLY_METHOD_INDEX,"proto@"^POLY_PROTO_INDEX,{regPolyC} is inst0=0xfa ; POLY_ARG_COUNT=1 ; POLY_METHOD_INDEX & POLY_PROTO_INDEX & regPolyC+{+ #TODO pCode+}+:invoke_polymorphic "meth@"^POLY_METHOD_INDEX,"proto@"^POLY_PROTO_INDEX,{regPolyC,regPolyD} is inst0=0xfa ; POLY_ARG_COUNT=2 ; POLY_METHOD_INDEX & POLY_PROTO_INDEX & regPolyC & regPolyD+{+ #TODO pCode+}+:invoke_polymorphic "meth@"^POLY_METHOD_INDEX,"proto@"^POLY_PROTO_INDEX,{regPolyC,regPolyD,regPolyE} is inst0=0xfa ; POLY_ARG_COUNT=3 ; POLY_METHOD_INDEX & POLY_PROTO_INDEX & regPolyC & regPolyD & regPolyE+{+ #TODO pCode+}+:invoke_polymorphic "meth@"^POLY_METHOD_INDEX,"proto@"^POLY_PROTO_INDEX,{regPolyC,regPolyD,regPolyE,regPolyF} is inst0=0xfa ; POLY_ARG_COUNT=4 ; POLY_METHOD_INDEX & POLY_PROTO_INDEX & regPolyC & regPolyD & regPolyE & regPolyF+{+ #TODO pCode+}+:invoke_polymorphic "meth@"^POLY_METHOD_INDEX,"proto@"^POLY_PROTO_INDEX,{regPolyC,regPolyD,regPolyE,regPolyF,regPolyG} is inst0=0xfa ; POLY_ARG_COUNT=5 ; POLY_METHOD_INDEX & POLY_PROTO_INDEX & regPolyC & regPolyD & regPolyE & regPolyF ; regPolyG+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+# V(0xFB, INVOKE_POLYMORPHIC_RANGE, "invoke-polymorphic/range", k4rcc, kIndexMethodAndProtoRef, kContinue | kThrow | kInvoke, kVerifyRegBMethod | kVerifyVarArgRangeNonZero | kVerifyRegHPrototype) \+#+# invoke-polymorphic/range {vCCCC .. vNNNN}, meth@BBBB, proto@HHHH+#+# A: argument word count (8 bits)+# B: method reference index (16 bits)+# C: method handle reference to invoke (16 bits)+# H: prototype reference index (16 bits)+# N = A + C - 1+#+# case Instruction::k4rcc: { // op {vCCCC .. v(CCCC+AA-1)}, method@BBBB, proto@HHHH+#+# Invoke the indicated method handle. See the invoke-polymorphic description above for details.+#+# Present in Dex files from version 038 onwards.++:invoke_polymorphic_range "meth@"^POLY_RANGE_METHOD_INDEX,"cnt@"^POLY_RANGE_ARG_COUNT,"proto@"^POLY_RANGE_PROTO_INDEX is inst0=0xfb ; POLY_RANGE_ARG_COUNT & POLY_RANGE_METHOD_INDEX & POLY_RANGE_PROTO_INDEX+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+# V(0xFC, INVOKE_CUSTOM, "invoke-custom", k35c, kIndexCallSiteRef, kContinue | kThrow, kVerifyRegBCallSite | kVerifyVarArg) \+#+# invoke-custom {vC, vD, vE, vF, vG}, call_site@BBBB+#+# A: argument word count (4 bits)+# B: call site reference index (16 bits)+# C..G: argument registers (4 bits each)+#+# Resolves and invokes the indicated call site.+# The result from the invocation (if any) may be stored with an+# appropriate move-result* variant as the immediately subsequent instruction.+#+# This instruction executes in two phases: call site resolution and call site invocation.+#+# Call site resolution checks whether the indicated call site has an associated+# java.lang.invoke.CallSite instance. If not, the bootstrap linker method for the+# indicated call site is invoked using arguments present in the DEX file (see call_site_item).+# The bootstrap linker method returns a java.lang.invoke.CallSite instance that will then+# be associated with the indicated call site if no association exists. Another thread may+# have already made the association first, and if so execution of the instruction continues+# with the first associated java.lang.invoke.CallSite instance.+#+# Call site invocation is made on the java.lang.invoke.MethodHandle target of the resolved+# java.lang.invoke.CallSite instance. The target is invoked as if executing invoke-polymorphic+# (described above) using the method handle and arguments to the invoke-custom instruction as+# the arguments to an exact method handle invocation.+#+# Present in Dex files from version 038 onwards.++:invoke_custom METHOD_INDEX,{} is inst0=0xfc ; N_PARAMS=0 & METHOD_INDEX+{+ #TODO pCode -- see invoke_direct+}+:invoke_custom METHOD_INDEX,{regParamC} is inst0=0xfc ; N_PARAMS=1 & METHOD_INDEX & regParamC+{+ #TODO pCode+}+:invoke_custom ^METHOD_INDEX,{regParamC,regParamD} is inst0=0xfc ; N_PARAMS=2 & METHOD_INDEX & regParamC & regParamD+{+ #TODO pCode+}+:invoke_custom METHOD_INDEX,{regParamC,regParamD,regParamE} is inst0=0xfc ; N_PARAMS=3 & METHOD_INDEX & regParamC & regParamD & regParamE+{+ #TODO pCode+}+:invoke_custom METHOD_INDEX,{regParamC,regParamD,regParamE,regParamF} is inst0=0xfc ; N_PARAMS=4 & METHOD_INDEX & regParamC & regParamD & regParamE & regParamF+{+ #TODO pCode+}+:invoke_custom METHOD_INDEX,{regParamC,regParamD,regParamE,regParamF,regParamG} is inst0=0xfc ; N_PARAMS=5 & METHOD_INDEX & regParamC & regParamD & regParamE & regParamF & regParamG+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+# V(0xFD, INVOKE_CUSTOM_RANGE, "invoke-custom/range", k3rc, kIndexCallSiteRef, kContinue | kThrow, kVerifyRegBCallSite | kVerifyVarArgRange) \+#+# invoke-custom/range {vCCCC .. vNNNN}, call_site@BBBB+#+# A: argument word count (8 bits)+# B: call site reference index (16 bits)+# C: first argument register (16-bits)+# N = A + C - 1+#+# Resolve and invoke a call site. See the invoke-custom description above for details.+#+# Present in Dex files from version 038 onwards.++:invoke_custom_range B_BITS_0_15,A_BITS_0_7,registerC16 is inst0=0xfd ; A_BITS_0_7 ; B_BITS_0_15 ; registerC16+{+ #TODO pCode -- see invoke_direct_range+}++#------------------------------------------------------------------------------------diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FA_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FA_unused.sincnew file mode 100644index 0000000000..08961316f3--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FA_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFA, UNUSED_FA, "unused-fa", k10x, false, kUnknown, 0, kVerifyError) \++:unused_fa is inst0=0xfa+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FB_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FB_unused.sincnew file mode 100644index 0000000000..a51cfd8043--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FB_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFB, UNUSED_FB, "unused-fb", k10x, false, kUnknown, 0, kVerifyError) \++:unused_fb is inst0=0xfb+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FC_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FC_unused.sincnew file mode 100644index 0000000000..9ad6eba49a--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FC_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFC, UNUSED_FC, "unused-fc", k10x, false, kUnknown, 0, kVerifyError) \++:unused_fc is inst0=0xfc+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FD_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FD_unused.sincnew file mode 100644index 0000000000..864b3d3bf0--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FD_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFD, UNUSED_FD, "unused-fd", k10x, false, kUnknown, 0, kVerifyError) \++:unused_fd is inst0=0xfd+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FE_FF_dex.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FE_FF_dex.sincnew file mode 100644index 0000000000..859e65d03f--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FE_FF_dex.sinc@@ -0,0 +1,20 @@++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFE, CONST_METHOD_HANDLE, "const-method-handle", k21c, kIndexMethodHandleRef, kContinue | kThrow, 0, kVerifyRegA | kVerifyRegBMethodHandle) \++:const_method_handle registerA8,B_BITS_0_15 is inst0=0xfe ; registerA8 ; B_BITS_0_15+{+ #TODO pCode+}++#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFF, CONST_METHOD_TYPE, "const-method-type", k21c, kIndexProtoRef, kContinue | kThrow, 0, kVerifyRegA | kVerifyRegBPrototype)++:const_method_type registerA8,B_BITS_0_15 is inst0=0xff ; registerA8 ; B_BITS_0_15+{+ #TODO pCode+}++#------------------------------------------------------------------------------------diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FE_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FE_unused.sincnew file mode 100644index 0000000000..4f30f21780--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FE_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFE, UNUSED_FE, "unused-fe", k10x, false, kUnknown, 0, kVerifyError) \++:unused_fe is inst0=0xfe+{+ #no pCode+}diff --git a/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FF_unused.sinc b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FF_unused.sincnew file mode 100644index 0000000000..f937e758d6--- /dev/null+++ b/Ghidra/Processors/Dalvik/data/languages/Dalvik_OpCode_FF_unused.sinc@@ -0,0 +1,8 @@+#------------------------------------------------------------------------------------+#------------------------------------------------------------------------------------+# V(0xFF, UNUSED_FF, "unused-ff", k10x, false, kUnknown, 0, kVerifyError)++:unused_ff is inst0=0xff+{+ #no pCode+}