Ghidra is a software reverse engineering (SRE) framework
GP-4643: Add a JIT-accelerated p-code emulator (API/scripting only)
Dana8fae1fe5bef
diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/modules/DebuggerStaticMappingUtils.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/modules/DebuggerStaticMappingUtils.javaindex c4d4739199..3d1ba7b7dd 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/modules/DebuggerStaticMappingUtils.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/service/modules/DebuggerStaticMappingUtils.java@@ -34,7 +34,7 @@ import ghidra.program.util.ProgramLocation;import ghidra.trace.model.*;import ghidra.trace.model.modules.*;import ghidra.trace.model.program.TraceProgramView;-import ghidra.util.ComparatorMath;+import ghidra.util.MathUtilities;import ghidra.util.Msg;public enum DebuggerStaticMappingUtils {@@ -163,8 +163,8 @@ public enum DebuggerStaticMappingUtils {private Address max = null;public void consider(Address min, Address max) {- this.min = this.min == null ? min : ComparatorMath.cmin(this.min, min);- this.max = this.max == null ? max : ComparatorMath.cmax(this.max, max);+ this.min = this.min == null ? min : MathUtilities.cmin(this.min, min);+ this.max = this.max == null ? max : MathUtilities.cmax(this.max, max);}public void consider(AddressRange range) {diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/SymPcodeArithmetic.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/SymPcodeArithmetic.javaindex 5687e82e94..ef29bbef32 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/SymPcodeArithmetic.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/SymPcodeArithmetic.java@@ -19,6 +19,7 @@ import ghidra.app.plugin.core.debug.stack.Sym.ConstSym;import ghidra.pcode.exec.ConcretionError;import ghidra.pcode.exec.PcodeArithmetic;import ghidra.pcode.utils.Utils;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.*;import ghidra.program.model.pcode.PcodeOp;@@ -70,14 +71,14 @@ class SymPcodeArithmetic implements PcodeArithmetic<Sym> {}@Override- public Sym modBeforeStore(int sizeout, int sizeinAddress, Sym inAddress,- int sizeinValue, Sym inValue) {+ public Sym modBeforeStore(int sizeinOffset, AddressSpace space, Sym inOffset, int sizeinValue,+ Sym inValue) {return inValue;}@Override- public Sym modAfterLoad(int sizeout, int sizeinAddress, Sym inAddress,- int sizeinValue, Sym inValue) {+ public Sym modAfterLoad(int sizeinOffset, AddressSpace space, Sym inOffset, int sizeinValue,+ Sym inValue) {return inValue;}diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/pcode/exec/DebuggerPcodeUtils.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/pcode/exec/DebuggerPcodeUtils.javaindex df4a3beb00..1fd25ce6a1 100644--- a/Ghidra/Debug/Debugger/src/main/java/ghidra/pcode/exec/DebuggerPcodeUtils.java+++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/pcode/exec/DebuggerPcodeUtils.java@@ -505,33 +505,33 @@ public enum DebuggerPcodeUtils {}@Override- public WatchValue modBeforeStore(int sizeout, int sizeinAddress, WatchValue inAddress,+ public WatchValue modBeforeStore(int sizeinOffset, AddressSpace space, WatchValue inOffset,int sizeinValue, WatchValue inValue) {return new WatchValue(new PrettyBytes(inValue.bytes.bigEndian,- bytes.modBeforeStore(sizeout, sizeinAddress, inAddress.bytes.bytes,- sizeinValue, inValue.bytes.bytes)),- STATE.modBeforeStore(sizeout, sizeinAddress, inAddress.state,- sizeinValue, inValue.state),- location.modBeforeStore(sizeout, sizeinAddress, inAddress.location,- sizeinValue, inValue.location),- READS.modBeforeStore(sizeout, sizeinAddress, inAddress.reads,- sizeinValue, inValue.reads));+ bytes.modBeforeStore(sizeinOffset, space, inOffset.bytes.bytes, sizeinValue,+ inValue.bytes.bytes)),+ STATE.modBeforeStore(sizeinOffset, space, inOffset.state, sizeinValue,+ inValue.state),+ location.modBeforeStore(sizeinOffset, space, inOffset.location, sizeinValue,+ inValue.location),+ READS.modBeforeStore(sizeinOffset, space, inOffset.reads, sizeinValue,+ inValue.reads));}@Override- public WatchValue modAfterLoad(int sizeout, int sizeinAddress, WatchValue inAddress,+ public WatchValue modAfterLoad(int sizeinOffset, AddressSpace space, WatchValue inOffset,int sizeinValue, WatchValue inValue) {return new WatchValue(new PrettyBytes(getEndian().isBigEndian(),- bytes.modAfterLoad(sizeout, sizeinAddress, inAddress.bytes.bytes,- sizeinValue, inValue.bytes.bytes)),- STATE.modAfterLoad(sizeout, sizeinAddress, inAddress.state,- sizeinValue, inValue.state),- location.modAfterLoad(sizeout, sizeinAddress, inAddress.location,- sizeinValue, inValue.location),- READS.modAfterLoad(sizeout, sizeinAddress, inAddress.reads,- sizeinValue, inValue.reads));+ bytes.modAfterLoad(sizeinOffset, space, inOffset.bytes.bytes, sizeinValue,+ inValue.bytes.bytes)),+ STATE.modAfterLoad(sizeinOffset, space, inOffset.state, sizeinValue,+ inValue.state),+ location.modAfterLoad(sizeinOffset, space, inOffset.location, sizeinValue,+ inValue.location),+ READS.modAfterLoad(sizeinOffset, space, inOffset.reads, sizeinValue,+ inValue.reads));}@Overridediff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/pcode/exec/trace/TraceMemoryStatePcodeArithmetic.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/pcode/exec/trace/TraceMemoryStatePcodeArithmetic.javaindex 37a231064d..2293d8107d 100644--- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/pcode/exec/trace/TraceMemoryStatePcodeArithmetic.java+++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/pcode/exec/trace/TraceMemoryStatePcodeArithmetic.java@@ -19,6 +19,7 @@ import java.math.BigInteger;import ghidra.pcode.exec.ConcretionError;import ghidra.pcode.exec.PcodeArithmetic;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.Endian;import ghidra.trace.model.memory.TraceMemoryState;@@ -58,15 +59,15 @@ public enum TraceMemoryStatePcodeArithmetic implements PcodeArithmetic<TraceMemo}@Override- public TraceMemoryState modBeforeStore(int sizeout, int sizeinAddress,- TraceMemoryState inAddress, int sizeinValue, TraceMemoryState inValue) {+ public TraceMemoryState modBeforeStore(int sizeinOffset, AddressSpace space,+ TraceMemoryState inOffset, int sizeinValue, TraceMemoryState inValue) {return inValue; // Shouldn't see STORE during Sleigh eval, anyway}@Override- public TraceMemoryState modAfterLoad(int sizeout, int sizeinAddress, TraceMemoryState inAddress,- int sizeinValue, TraceMemoryState inValue) {- if (inAddress == TraceMemoryState.KNOWN && inValue == TraceMemoryState.KNOWN) {+ public TraceMemoryState modAfterLoad(int sizeinOffset, AddressSpace space,+ TraceMemoryState inOffset, int sizeinValue, TraceMemoryState inValue) {+ if (inOffset == TraceMemoryState.KNOWN && inValue == TraceMemoryState.KNOWN) {return TraceMemoryState.KNOWN;}return TraceMemoryState.UNKNOWN;diff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramViewRootModule.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramViewRootModule.javaindex ffd6d1122e..e77b345bca 100644--- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramViewRootModule.java+++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramViewRootModule.java@@ -24,8 +24,8 @@ import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressSetView;import ghidra.program.model.listing.*;import ghidra.trace.model.memory.TraceMemoryRegion;-import ghidra.util.ComparatorMath;import ghidra.util.LockHold;+import ghidra.util.MathUtilities;import ghidra.util.exception.*;public class DBTraceProgramViewRootModule implements ProgramModule {@@ -195,7 +195,7 @@ public class DBTraceProgramViewRootModule implements ProgramModule {.getMinAddress();}// TODO: There has got to be a better way- return reduceRegions(TraceMemoryRegion::getMinAddress, ComparatorMath::cmin);+ return reduceRegions(TraceMemoryRegion::getMinAddress, MathUtilities::cmin);}@Override@@ -206,7 +206,7 @@ public class DBTraceProgramViewRootModule implements ProgramModule {.getMaxAddress();}// TODO: There has got to be a better way- return reduceRegions(TraceMemoryRegion::getMaxAddress, ComparatorMath::cmax);+ return reduceRegions(TraceMemoryRegion::getMaxAddress, MathUtilities::cmax);}@Overridediff --git a/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/pcode/exec/trace/BytesTracePcodeEmulatorTest.java b/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/pcode/exec/trace/BytesTracePcodeEmulatorTest.javaindex 994ccf6963..50d03ba72d 100644--- a/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/pcode/exec/trace/BytesTracePcodeEmulatorTest.java+++ b/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/pcode/exec/trace/BytesTracePcodeEmulatorTest.java@@ -983,6 +983,7 @@ public class BytesTracePcodeEmulatorTest extends AbstractTracePcodeEmulatorTestTraceSleighUtils.evaluate("r1", tb.trace, 1, thread, 0));}}+@Testpublic void testITE_ContextFlow() throws Throwable {try (ToyDBTraceBuilder tb = new ToyDBTraceBuilder("Test", "ARM:LE:32:v8T")) {diff --git a/Ghidra/Debug/ProposedUtils/build.gradle b/Ghidra/Debug/ProposedUtils/build.gradleindex e6920c4033..3a9482f04f 100644--- a/Ghidra/Debug/ProposedUtils/build.gradle+++ b/Ghidra/Debug/ProposedUtils/build.gradle@@ -4,9 +4,9 @@* 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.@@ -30,7 +30,7 @@ dependencies {api project(':Utility')api project(':Base') // Boo!: (Where to put DefaultEnumeratedColumnProgramTableModel?)-+// TODO: Evaluate these dependencies// api("com.google.auto.service:auto-service-annotations:$autoServiceVersion")// annotationProcessor("com.google.auto.service:auto-service:$autoServiceVersion")diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/app/util/opinion/JitLogLoader.java b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/app/util/opinion/JitLogLoader.javanew file mode 100644index 0000000000..b304314d96--- /dev/null+++ b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/app/util/opinion/JitLogLoader.java@@ -0,0 +1,232 @@+/* ###+ * 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.app.util.opinion;++import java.io.*;+import java.util.*;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++import generic.ULongSpan;+import ghidra.app.util.Option;+import ghidra.app.util.bin.ByteProvider;+import ghidra.app.util.importer.MessageLog;+import ghidra.framework.model.Project;+import ghidra.framework.store.LockException;+import ghidra.generic.util.datastruct.SemisparseByteArray;+import ghidra.program.database.function.OverlappingFunctionException;+import ghidra.program.model.address.*;+import ghidra.program.model.lang.*;+import ghidra.program.model.listing.CodeUnit;+import ghidra.program.model.listing.Program;+import ghidra.program.model.mem.MemoryAccessException;+import ghidra.program.model.mem.MemoryConflictException;+import ghidra.program.model.symbol.SourceType;+import ghidra.program.model.symbol.SymbolUtilities;+import ghidra.util.NumericUtilities;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.InvalidInputException;+import ghidra.util.task.TaskMonitor;++public class JitLogLoader extends AbstractProgramLoader {+ public final static String JIT_LOG_NAME = "OpenJDK 17 JIT compilation log";++ @Override+ public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {+ return getLanguageService().getLanguageCompilerSpecPairs(+ new LanguageCompilerSpecQuery(null, null, null, null, null))+ .stream()+ .map(lcs -> new LoadSpec(this, 0, lcs, false))+ .toList();+ }++ @Override+ public String getName() {+ return JIT_LOG_NAME;+ }++ @Override+ public LoaderTier getTier() {+ return LoaderTier.UNTARGETED_LOADER;+ }++ @Override+ public int getTierPriority() {+ return 100;+ }++ @Override+ protected List<Loaded<Program>> loadProgram(ByteProvider provider, String loadedName,+ Project project, String projectFolderPath, LoadSpec loadSpec, List<Option> options,+ MessageLog log, Object consumer, TaskMonitor monitor)+ throws IOException, LoadException, CancelledException {+ LanguageCompilerSpecPair pair = loadSpec.getLanguageCompilerSpec();+ CompilerSpec cSpec = pair.getCompilerSpec();+ Language language = cSpec.getLanguage();+ Program program =+ createProgram(provider, loadedName, null, getName(), language, cSpec, consumer);+ boolean success = false;+ try {+ loadInto(provider, loadSpec, options, log, program, monitor);+ success = true;+ createDefaultMemoryBlocks(program, language, log);+ }+ finally {+ if (!success) {+ program.release(consumer);+ program = null;+ }+ }+ List<Loaded<Program>> results = new ArrayList<>();+ if (program != null) {+ results.add(new Loaded<>(program, loadedName, projectFolderPath));+ }+ return results;+ }++ static class JitMethod {+ final String name;++ SemisparseByteArray bytes = new SemisparseByteArray();+ Map<Address, String> comments = new HashMap<>();++ public JitMethod(String name) {+ this.name = name;+ }++ void appendComment(Address address, String line) {+ comments.compute(address, (a, c) -> c == null ? line : c + "\n" + line);+ }+ }++ List<JitMethod> methods = new ArrayList<>();+ AddressSet fullSet = new AddressSet();++ static final Pattern PAT_METHOD =+ Pattern.compile("\\s*#\\s*\\{method\\}\\s*\\{0x[0-9A-Fa-f]+\\}(?<name>.*)");+ static final Pattern PAT_COMMENT =+ Pattern.compile("\\s*0x(?<addrHex>[0-9A-Fa-f]+):\\s*;(?<comment>.*)");+ static final Pattern PAT_BYTES =+ Pattern.compile("\\s*0x(?<addrHex>[0-9A-Fa-f]+):\\s*(?<bytes>[\\s\\|0-9A-Fa-f]+)");++ @Override+ protected void loadProgramInto(ByteProvider provider, LoadSpec loadSpec,+ List<Option> options, MessageLog log, Program program, TaskMonitor monitor)+ throws IOException, CancelledException {+ monitor.setMessage("Reading lines");+ JitMethod curMethod = null;+ String line;+ try (BufferedReader in =+ new BufferedReader(new InputStreamReader(provider.getInputStream(0)))) {+ while (null != (line = in.readLine())) {+ Matcher matcher;+ monitor.checkCanceled();++ matcher = PAT_METHOD.matcher(line);+ if (matcher.matches()) {+ putMethod(curMethod, program);+ curMethod = new JitMethod(matcher.group("name")+ .replace("'", "'")+ .replace("<", "<")+ .replace(">", ">"));+ continue;+ }+ if (curMethod == null) {+ continue;+ }+ matcher = PAT_COMMENT.matcher(line);+ if (matcher.matches()) {+ Address address =+ program.getAddressFactory().getAddress(matcher.group("addrHex"));+ curMethod.appendComment(address, matcher.group("comment"));+ }+ matcher = PAT_BYTES.matcher(line);+ if (matcher.matches()) {+ Address address =+ program.getAddressFactory().getAddress(matcher.group("addrHex"));+ curMethod.bytes.putData(address.getOffset(),+ NumericUtilities.convertStringToBytes(+ matcher.group("bytes").replace(" ", "").replace("|", "")));+ }+ }+ }+ putMethod(curMethod, program);++ monitor.setMaximum(fullSet.getNumAddresses() + methods.size());++ monitor.setMessage("Creating blocks");+ for (AddressRange range : fullSet) {+ monitor.checkCanceled();+ try {+ program.getMemory()+ .createInitializedBlock("block" + range.getMinAddress(),+ range.getMinAddress(), range.getLength(), (byte) 0, monitor, false);+ }+ catch (AddressOverflowException | LockException | IllegalArgumentException+ | MemoryConflictException e) {+ log.appendMsg("Could not create block " + range + ": " + e);+ }+ monitor.incrementProgress(1);+ }++ monitor.setMessage("Creating methods");++ AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();+ for (JitMethod method : methods) {+ monitor.checkCanceled();+ AddressSet body = new AddressSet();+ for (ULongSpan span : method.bytes.getInitialized(0, -1).spans()) {+ body.add(space.getAddress(span.min()), space.getAddress(span.max()));+ if (span.length() > Integer.MAX_VALUE) {+ log.appendMsg("Method too large: " + method.name);+ continue;+ }+ byte[] data = new byte[(int) span.length()];+ method.bytes.getData(span.min(), data);+ try {+ program.getMemory().setBytes(space.getAddress(span.min()), data);+ }+ catch (MemoryAccessException | AddressOutOfBoundsException e) {+ log.appendMsg("Could not write bytes " + span + ": " + e);+ }+ }+ for (Map.Entry<Address, String> ent : method.comments.entrySet()) {+ program.getListing().setComment(ent.getKey(), CodeUnit.PRE_COMMENT, ent.getValue());+ }+ try {+ program.getFunctionManager()+ .createFunction(SymbolUtilities.replaceInvalidChars(method.name, true),+ body.getMinAddress(), body,+ SourceType.IMPORTED);+ }+ catch (InvalidInputException | OverlappingFunctionException e) {+ log.appendMsg("Couldn't create function: " + method.name + ": " + e);+ }+ monitor.incrementProgress(1);+ }+ }++ void putMethod(JitMethod method, Program program) {+ if (method == null) {+ return;+ }+ AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();+ methods.add(method);+ for (ULongSpan span : method.bytes.getInitialized(0, -1).spans()) {+ fullSet.add(space.getAddress(span.min()), space.getAddress(span.max()));+ }+ }+}diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/pcode/eval/ArithmeticVarnodeEvaluator.java b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/pcode/eval/ArithmeticVarnodeEvaluator.javaindex 0cd482e33f..20af1039d6 100644--- a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/pcode/eval/ArithmeticVarnodeEvaluator.java+++ b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/pcode/eval/ArithmeticVarnodeEvaluator.java@@ -43,7 +43,7 @@ public abstract class ArithmeticVarnodeEvaluator<T> extends AbstractVarnodeEvalu* SLEIGH: {@code shift} the left piece then {@code or} it with the right piece.** @param <T> the type of values- * @param arithmetic the p-code arithmetic for values of type {@link T}+ * @param arithmetic the p-code arithmetic for values of type {@code T}* @param sizeTotal the expected output size in bytes* @param upper the value of the left (more significant) piece* @param lower the value of the right (less significant) piece@@ -143,8 +143,6 @@ public abstract class ArithmeticVarnodeEvaluator<T> extends AbstractVarnodeEvaluT offset = evaluateVarnode(program, inOffset, already);Varnode outVar = op.getOutput(); // Only for measuring sizeT out = evaluateAbstract(program, space, offset, outVar.getSize(), already);- return arithmetic.modAfterLoad(outVar.getSize(),- inOffset.getSize(), offset,- outVar.getSize(), out);+ return arithmetic.modAfterLoad(op, space, offset, out);}}diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/program/model/address/CachedAddressSetView.java b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/program/model/address/CachedAddressSetView.javaindex 7bf11f34fc..5b77d9da6d 100644--- a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/program/model/address/CachedAddressSetView.java+++ b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/program/model/address/CachedAddressSetView.java@@ -15,8 +15,8 @@*/package ghidra.program.model.address;-import static ghidra.util.ComparatorMath.cmax;-import static ghidra.util.ComparatorMath.cmin;+import static ghidra.util.MathUtilities.cmax;+import static ghidra.util.MathUtilities.cmin;import java.util.Iterator;diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/IntersectionAddressSetView.java b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/IntersectionAddressSetView.javaindex 0458d6e80c..696d2a51b2 100644--- a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/IntersectionAddressSetView.java+++ b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/IntersectionAddressSetView.java@@ -15,8 +15,8 @@*/package ghidra.util;-import static ghidra.util.ComparatorMath.cmax;-import static ghidra.util.ComparatorMath.cmin;+import static ghidra.util.MathUtilities.cmax;+import static ghidra.util.MathUtilities.cmin;import ghidra.program.model.address.*;diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/TwoWayBreakdownAddressRangeIterator.java b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/TwoWayBreakdownAddressRangeIterator.javaindex 9a2dab44c0..b6c740dca1 100644--- a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/TwoWayBreakdownAddressRangeIterator.java+++ b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/TwoWayBreakdownAddressRangeIterator.java@@ -15,8 +15,8 @@*/package ghidra.util;-import static ghidra.util.ComparatorMath.cmax;-import static ghidra.util.ComparatorMath.cmin;+import static ghidra.util.MathUtilities.cmax;+import static ghidra.util.MathUtilities.cmin;import java.util.Iterator;import java.util.Map.Entry;diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressRangeIterator.java b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressRangeIterator.javaindex bc6b9fb004..d5024751a8 100644--- a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressRangeIterator.java+++ b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressRangeIterator.java@@ -15,8 +15,8 @@*/package ghidra.util;-import static ghidra.util.ComparatorMath.cmax;-import static ghidra.util.ComparatorMath.cmin;+import static ghidra.util.MathUtilities.cmax;+import static ghidra.util.MathUtilities.cmin;import java.util.Collection;import java.util.Iterator;diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressSetView.java b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressSetView.javaindex c093ccc545..51246b8bcd 100644--- a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressSetView.java+++ b/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/UnionAddressSetView.java@@ -15,8 +15,8 @@*/package ghidra.util;-import static ghidra.util.ComparatorMath.cmax;-import static ghidra.util.ComparatorMath.cmin;+import static ghidra.util.MathUtilities.cmax;+import static ghidra.util.MathUtilities.cmin;import java.util.Arrays;import java.util.Collection;diff --git a/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/TaintPcodeArithmetic.java b/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/TaintPcodeArithmetic.javaindex 25e2ce35b2..1eb3dd987f 100644--- a/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/TaintPcodeArithmetic.java+++ b/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/TaintPcodeArithmetic.java@@ -19,6 +19,7 @@ import java.util.Objects;import ghidra.pcode.exec.ConcretionError;import ghidra.pcode.exec.PcodeArithmetic;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.Endian;import ghidra.program.model.lang.Language;import ghidra.program.model.pcode.PcodeOp;@@ -83,7 +84,7 @@ public enum TaintPcodeArithmetic implements PcodeArithmetic<TaintVec> {* <p>* We can't just naively return {@code in1}, because each unary op may mix the bytes of the* operand a little differently. For {@link PcodeOp#COPY}, we can, since no mixing happens at- * all. This is also the case of both {@link NEGATE} operations ("negate" is a bit of a+ * all. This is also the case of both {@code NEGATE} operations ("negate" is a bit of a* misnomer, as they merely inverts the bits.) For {@link PcodeOp#INT_ZEXT}, we append empties* to the correct end of the vector. Similarly, we replicate the most-significant element and* append for {@link PcodeOp#INT_SEXT}. For {@link PcodeOp#INT_2COMP} (which negates an integer@@ -183,9 +184,9 @@ public enum TaintPcodeArithmetic implements PcodeArithmetic<TaintVec> {* Here we handle indirect taint for indirect writes*/@Override- public TaintVec modBeforeStore(int sizeout, int sizeinAddress, TaintVec inAddress,+ public TaintVec modBeforeStore(int sizeinOffset, AddressSpace space, TaintVec inOffset,int sizeinValue, TaintVec inValue) {- return inValue.tagIndirectWrite(inAddress);+ return inValue.tagIndirectWrite(inOffset);}/**@@ -195,9 +196,9 @@ public enum TaintPcodeArithmetic implements PcodeArithmetic<TaintVec> {* Here we handle indirect taint for indirect reads*/@Override- public TaintVec modAfterLoad(int sizeout, int sizeinAddress, TaintVec inAddress,+ public TaintVec modAfterLoad(int sizeinOffset, AddressSpace space, TaintVec inOffset,int sizeinValue, TaintVec inValue) {- return inValue.tagIndirectRead(inAddress);+ return inValue.tagIndirectRead(inOffset);}/**diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/PCodeDfgGraphTask.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/PCodeDfgGraphTask.javaindex 27720c29cf..b882ff295a 100644--- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/PCodeDfgGraphTask.java+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/decompile/actions/PCodeDfgGraphTask.java@@ -39,7 +39,7 @@ public class PCodeDfgGraphTask extends Task {private GraphDisplayBroker graphService;protected HighFunction hfunction;- private AttributedGraph graph;+ protected AttributedGraph graph;private PluginTool tool;public PCodeDfgGraphTask(PluginTool tool, GraphDisplayBroker graphService,diff --git a/Ghidra/Features/FileFormats/Module.manifest b/Ghidra/Features/FileFormats/Module.manifestindex 3ca3eccd3e..d3b4445614 100644--- a/Ghidra/Features/FileFormats/Module.manifest+++ b/Ghidra/Features/FileFormats/Module.manifest@@ -2,11 +2,6 @@ MODULE FILE LICENSE: lib/dex-ir-2.4.24.jar Apache License 2.0MODULE FILE LICENSE: lib/dex-reader-2.4.24.jar Apache License 2.0MODULE FILE LICENSE: lib/dex-reader-api-2.4.24.jar Apache License 2.0MODULE FILE LICENSE: lib/dex-translator-2.4.24.jar Apache License 2.0-MODULE FILE LICENSE: lib/asm-9.7.1.jar INRIA License-MODULE FILE LICENSE: lib/asm-analysis-9.7.1.jar INRIA License-MODULE FILE LICENSE: lib/asm-commons-9.7.1.jar INRIA License-MODULE FILE LICENSE: lib/asm-tree-9.7.1.jar INRIA License-MODULE FILE LICENSE: lib/asm-util-9.7.1.jar INRIA LicenseMODULE FILE LICENSE: lib/baksmali-2.5.2.jar BSD-3-GRUVERMODULE FILE LICENSE: lib/dexlib2-2.5.2.jar BSD-3-GRUVERMODULE FILE LICENSE: lib/util-2.5.2.jar BSD-3-GRUVERdiff --git a/Ghidra/Features/FileFormats/build.gradle b/Ghidra/Features/FileFormats/build.gradleindex 7b56694df6..2c77ea6cbf 100644--- a/Ghidra/Features/FileFormats/build.gradle+++ b/Ghidra/Features/FileFormats/build.gradle@@ -29,17 +29,13 @@ dependencies {api project(':Base')api project(':Recognizers')api project(':PDB')-+// Used by "Android DEX to JAR" file system+ // dex2jar depends on asm-9.7.1, which is declared in Framework/Emulationapi 'de.femtopedia.dex2jar:dex-ir:2.4.24'api 'de.femtopedia.dex2jar:dex-reader:2.4.24'api 'de.femtopedia.dex2jar:dex-reader-api:2.4.24'api 'de.femtopedia.dex2jar:dex-translator:2.4.24'- api 'org.ow2.asm:asm:9.7.1'- api 'org.ow2.asm:asm-analysis:9.7.1'- api 'org.ow2.asm:asm-commons:9.7.1'- api 'org.ow2.asm:asm-tree:9.7.1'- api 'org.ow2.asm:asm-util:9.7.1'// Used by "Android DEX to SMALI" file systemapi 'org.smali:baksmali:2.5.2' // requires guava-27.1-android or laterdiff --git a/Ghidra/Features/FileFormats/certification.manifest b/Ghidra/Features/FileFormats/certification.manifestindex 0944b3210d..4baaeaf6f2 100644--- a/Ghidra/Features/FileFormats/certification.manifest+++ b/Ghidra/Features/FileFormats/certification.manifest@@ -5,7 +5,6 @@##MODULE IP: BSD-3-GRUVER##MODULE IP: Copyright Distribution Permitted##MODULE IP: Creative Commons Attribution 2.5-##MODULE IP: INRIA License##MODULE IP: Jython License##MODULE IP: LGPL 2.1##MODULE IP: Public Domaindiff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuSyscallLibrary.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuSyscallLibrary.javaindex d2ae18e8a1..396f641a18 100644--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuSyscallLibrary.java+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuSyscallLibrary.java@@ -4,9 +4,9 @@* 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.@@ -16,6 +16,7 @@package ghidra.pcode.emu.sys;import java.io.*;+import java.lang.reflect.Method;import java.util.*;import java.util.Map.Entry;import java.util.stream.Collectors;@@ -132,8 +133,8 @@ public interface EmuSyscallLibrary<T> extends PcodeUseropLibrary<T> {* Derive a syscall number to calling convention map by scraping functions in the program's* "syscall" space.*- * @param program- * @return+ * @param program the program whose "syscall" space to scrape+ * @return the map of syscall number to calling convention*/public static Map<Long, PrototypeModel> loadSyscallConventionMap(Program program) {return loadSyscallFunctionMap(program).entrySet()@@ -169,6 +170,37 @@ public interface EmuSyscallLibrary<T> extends PcodeUseropLibrary<T> {Varnode outVar, List<Varnode> inVars) {syslib.syscall(executor, library);}++ @Override+ public boolean isFunctional() {+ return false;+ }++ @Override+ public boolean hasSideEffects() {+ return true;+ }++ @Override+ public boolean canInlinePcode() {+ return false;+ }++ @Override+ public PcodeUseropLibrary<?> getDefiningLibrary() {+ return syslib;+ }++ @Override+ public Method getJavaMethod() {+ try {+ return syslib.getClass()+ .getMethod("syscall", PcodeExecutor.class, PcodeUseropLibrary.class);+ }+ catch (NoSuchMethodException | SecurityException e) {+ throw new AssertionError(e);+ }+ }}/**@@ -199,7 +231,7 @@ public interface EmuSyscallLibrary<T> extends PcodeUseropLibrary<T> {*/default PcodeUseropDefinition<T> getSyscallUserop() {return new SyscallPcodeUseropDefinition<>(this);- };+ }/*** Retrieve the desired system call number according to the emulated system's conventionsdiff --git a/Ghidra/Framework/Emulation/Module.manifest b/Ghidra/Framework/Emulation/Module.manifestindex e69de29bb2..cf2811d395 100644--- a/Ghidra/Framework/Emulation/Module.manifest+++ b/Ghidra/Framework/Emulation/Module.manifest@@ -0,0 +1,5 @@+MODULE FILE LICENSE: lib/asm-9.7.1.jar INRIA License+MODULE FILE LICENSE: lib/asm-analysis-9.7.1.jar INRIA License+MODULE FILE LICENSE: lib/asm-commons-9.7.1.jar INRIA License+MODULE FILE LICENSE: lib/asm-tree-9.7.1.jar INRIA License+MODULE FILE LICENSE: lib/asm-util-9.7.1.jar INRIA Licensediff --git a/Ghidra/Framework/Emulation/build.gradle b/Ghidra/Framework/Emulation/build.gradleindex d32f0677bc..e023ffa8e1 100644--- a/Ghidra/Framework/Emulation/build.gradle+++ b/Ghidra/Framework/Emulation/build.gradle@@ -4,9 +4,9 @@* 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.@@ -26,4 +26,10 @@ dependencies {api project(':SoftwareModeling')api project(':Generic')api project(':Utility')++ api 'org.ow2.asm:asm:9.7.1'+ api 'org.ow2.asm:asm-analysis:9.7.1'+ api 'org.ow2.asm:asm-commons:9.7.1'+ api 'org.ow2.asm:asm-tree:9.7.1'+ api 'org.ow2.asm:asm-util:9.7.1'}diff --git a/Ghidra/Framework/Emulation/certification.manifest b/Ghidra/Framework/Emulation/certification.manifestindex 622afd9044..a71cbedad6 100644--- a/Ghidra/Framework/Emulation/certification.manifest+++ b/Ghidra/Framework/Emulation/certification.manifest@@ -1,4 +1,5 @@##VERSION: 2.0+##MODULE IP: INRIA LicenseModule.manifest||GHIDRA||||END|README.md||GHIDRA||||END|src/test/resources/mock.cspec||GHIDRA||||END|diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/app/emulator/AdaptedEmulator.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/app/emulator/AdaptedEmulator.javaindex e7d6e6cbf3..1fba558ff1 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/app/emulator/AdaptedEmulator.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/app/emulator/AdaptedEmulator.java@@ -4,9 +4,9 @@* 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.@@ -20,6 +20,7 @@ import generic.ULongSpan.ULongSpanSet;import ghidra.app.emulator.memory.MemoryLoadImage;import ghidra.app.emulator.state.RegisterState;import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.app.util.PseudoInstruction;import ghidra.lifecycle.Transitional;import ghidra.pcode.emu.*;import ghidra.pcode.emu.PcodeMachine.SwiMode;@@ -35,7 +36,6 @@ import ghidra.pcode.utils.Utils;import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.*;-import ghidra.program.model.listing.Instruction;import ghidra.program.model.pcode.PcodeOp;import ghidra.util.Msg;import ghidra.util.exception.CancelledException;@@ -134,7 +134,7 @@ public class AdaptedEmulator implements Emulator {PcodeExecutorState<byte[]> sharedState) {return new SleighInstructionDecoder(language, sharedState) {@Override- public Instruction decodeInstruction(Address address, RegisterValue context) {+ public PseudoInstruction decodeInstruction(Address address, RegisterValue context) {try {isDecoding = true;return super.decodeInstruction(address, context);@@ -147,8 +147,7 @@ public class AdaptedEmulator implements Emulator {}}- record StateBacking(MemoryFaultHandler faultHandler, MemoryLoadImage loadImage) {- }+ record StateBacking(MemoryFaultHandler faultHandler, MemoryLoadImage loadImage) {}class AdaptedBytesPcodeExecutorState extends BytesPcodeExecutorState {public AdaptedBytesPcodeExecutorState(Language language, StateBacking backing) {diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/generic/util/datastruct/SemisparseByteArray.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/generic/util/datastruct/SemisparseByteArray.javaindex 459727858a..f008e937b2 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/generic/util/datastruct/SemisparseByteArray.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/generic/util/datastruct/SemisparseByteArray.java@@ -114,6 +114,15 @@ public class SemisparseByteArray {getData(loc, data, 0, data.length);}+ public synchronized byte[] getDirect(final long loc) {+ long blockNum = Long.divideUnsigned(loc, BLOCK_SIZE);+ int blockOffset = (int) Long.remainderUnsigned(loc, BLOCK_SIZE);+ if (blockOffset != 0) {+ throw new IllegalArgumentException("Offset must be at block boundary");+ }+ return blocks.computeIfAbsent(blockNum, n -> new byte[BLOCK_SIZE]);+ }+/*** Copy a range of data from the semisparse array into a portion of the given byte array*diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/AbstractPcodeMachine.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/AbstractPcodeMachine.javaindex 72e2a08498..5d991ef90b 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/AbstractPcodeMachine.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/AbstractPcodeMachine.java@@ -4,9 +4,9 @@* 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.@@ -273,13 +273,8 @@ public abstract class AbstractPcodeMachine<T> implements PcodeMachine<T> {return suspended;}- /**- * Check for a p-code injection (override) at the given address- *- * @param address the address, usually the program counter- * @return the injected program, most likely {@code null}- */- protected PcodeProgram getInject(Address address) {+ @Override+ public PcodeProgram getInject(Address address) {return injects.get(address);}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/DefaultPcodeThread.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/DefaultPcodeThread.javaindex c453910dfa..11eda8abf2 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/DefaultPcodeThread.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/DefaultPcodeThread.java@@ -47,6 +47,8 @@ import ghidra.util.Msg;* This class implements the control-flow logic of the target machine, cooperating with the p-code* program flow implemented by the {@link PcodeExecutor}. This implementation exists primarily in* {@link #beginInstructionOrInject()} and {@link #advanceAfterFinished()}.+ *+ * @param <T> the type of variables in the emulator*/public class DefaultPcodeThread<T> implements PcodeThread<T> {@@ -122,7 +124,7 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {** @see PcodeMachine#addBreakpoint(Address, String)*/- @PcodeUserop+ @PcodeUserop(functional = true)public void emu_swi() {thread.swi();}@@ -136,7 +138,7 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {* calls to this p-code op. Then, only if and when an erroneous inject is encountered will* the client be notified.*/- @PcodeUserop+ @PcodeUserop(functional = true)public void emu_injection_err() {throw new InjectionErrorPcodeExecutionException(null, null);}@@ -148,6 +150,8 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {* <p>* This executor checks for thread suspension and updates the program counter register upon* execution of (external) branches.+ *+ * @param <T> the type of variables in the emulator*/public static class PcodeThreadExecutor<T> extends PcodeExecutor<T> {volatile boolean suspended = false;@@ -192,7 +196,7 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {}@Override- protected void branchToAddress(Address target) {+ protected void branchToAddress(PcodeOp op, Address target) {thread.branchToAddress(target);}@@ -249,7 +253,7 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {this.arithmetic = machine.arithmetic;PcodeExecutorState<T> sharedState = machine.getSharedState();PcodeExecutorState<T> localState = machine.createLocalState(this);- this.state = new ThreadPcodeExecutorState<>(sharedState, localState);+ this.state = createThreadState(sharedState, localState);this.decoder = createInstructionDecoder(sharedState);this.library = createUseropLibrary();@@ -269,6 +273,18 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {this.reInitialize();}+ /**+ * A factory method for the thread's (multiplexed) state+ *+ * @param sharedState the shared part of the state+ * @param localState the thread-local part of the state+ * @return the complete state+ */+ protected ThreadPcodeExecutorState<T> createThreadState(PcodeExecutorState<T> sharedState,+ PcodeExecutorState<T> localState) {+ return new ThreadPcodeExecutorState<>(sharedState, localState);+ }+/*** A factory method for the instruction decoder*@@ -465,8 +481,9 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {}}- protected RegisterValue getContextAfterCommits() {+ public static RegisterValue getContextAfterCommits(Instruction instruction, long counter) {PseudoInstruction pins = (PseudoInstruction) instruction;+ Language language = instruction.getPrototype().getLanguage();try {SleighParserContext parserCtx = (SleighParserContext) pins.getParserContext();var procCtx = new DisassemblerContextAdapter() {@@ -477,7 +494,8 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {if (!value.getRegister().isProcessorContext()) {return;}- if (!address.equals(counter)) {+ if (address.getOffset() != counter &&+ !Objects.equals(pins.getAddress(), address)) {Msg.warn(this, "Context applied somewhere other than the counter.");return;}@@ -492,6 +510,10 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {}}+ protected RegisterValue getContextAfterCommits() {+ return getContextAfterCommits(instruction, counter.getOffset());+ }+/*** Resolve a finished instruction, advancing the program counter if necessary*/diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/InstructionDecoder.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/InstructionDecoder.javaindex 7f62d8f2b1..376e0293bf 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/InstructionDecoder.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/InstructionDecoder.java@@ -4,9 +4,9 @@* 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.@@ -15,7 +15,9 @@*/package ghidra.pcode.emu;+import ghidra.app.util.PseudoInstruction;import ghidra.program.model.address.Address;+import ghidra.program.model.lang.Language;import ghidra.program.model.lang.RegisterValue;import ghidra.program.model.listing.Instruction;@@ -23,6 +25,13 @@ import ghidra.program.model.listing.Instruction;* A means of decoding machine instructions from the bytes contained in the machine state*/public interface InstructionDecoder {+ /**+ * Get the language for this decoder+ *+ * @return the language+ */+ Language getLanguage();+/*** Decode the instruction starting at the given address using the given context*@@ -33,7 +42,7 @@ public interface InstructionDecoder {* @param context the disassembler/decode context* @return the instruction*/- Instruction decodeInstruction(Address address, RegisterValue context);+ PseudoInstruction decodeInstruction(Address address, RegisterValue context);/*** Inform the decoder that the emulator thread just brancheddiff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ModifiedPcodeThread.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ModifiedPcodeThread.javaindex ef808c7d87..d706d13489 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ModifiedPcodeThread.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ModifiedPcodeThread.java@@ -4,9 +4,9 @@* 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.@@ -46,6 +46,8 @@ import ghidra.util.Msg;* TODO: "State modifiers" are a feature of the older {@link Emulator}. They are crudely* incorporated into threads extended from this abstract class, so that they do not yet need to be* ported to this emulator.+ *+ * @param <T> the type of variables in the emulator*/public class ModifiedPcodeThread<T> extends DefaultPcodeThread<T> {diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/PcodeMachine.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/PcodeMachine.javaindex d5dc7d5595..c73096cc44 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/PcodeMachine.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/PcodeMachine.java@@ -4,9 +4,9 @@* 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.@@ -234,7 +234,7 @@ public interface PcodeMachine<T> {* <p>* This will attempt to compile the given source against this machine's userop library and then* inject it at the given address. The resulting p-code <em>replaces</em> that which would be- * executed by decoding the instruction at the given address. The means the machine will not+ * executed by decoding the instruction at the given address. That means the machine will not* decode, nor advance its counter, unless the Sleigh causes it. In most cases, the Sleigh will* call {@link PcodeEmulationLibrary#emu_exec_decoded()} to cause the machine to decode and* execute the overridden instruction.@@ -254,6 +254,14 @@ public interface PcodeMachine<T> {*/void inject(Address address, String source);+ /**+ * Check for a p-code injection (override) at the given address+ *+ * @param address the address, usually the program counter+ * @return the injected program, most likely {@code null}+ */+ PcodeProgram getInject(Address address);+/*** Remove the inject, if present, at the given address*diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/SleighInstructionDecoder.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/SleighInstructionDecoder.javaindex 621092668a..51a487e7e2 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/SleighInstructionDecoder.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/SleighInstructionDecoder.java@@ -15,8 +15,6 @@*/package ghidra.pcode.emu;-import java.util.Objects;-import ghidra.app.util.PseudoInstruction;import ghidra.pcode.emulate.InstructionDecodeException;import ghidra.pcode.exec.DecodePcodeExecutionException;@@ -58,6 +56,7 @@ public class SleighInstructionDecoder implements InstructionDecoder {/*** Construct a Sleigh instruction decoder*+ * @see DefaultPcodeThread#createInstructionDecoder(PcodeExecutorState)* @param language the language to decoder* @param state the state containing the target program, probably the shared state of the p-code* machine. It must be possible to obtain concrete buffers on this state.@@ -75,6 +74,11 @@ public class SleighInstructionDecoder implements InstructionDecoder {Disassembler.getDisassembler(language, addrFactory, TaskMonitor.DUMMY, listener);}+ @Override+ public Language getLanguage() {+ return language;+ }+protected boolean useCachedInstruction(Address address, RegisterValue context) {if (block == null) {return false;@@ -100,7 +104,7 @@ public class SleighInstructionDecoder implements InstructionDecoder {}@Override- public Instruction decodeInstruction(Address address, RegisterValue context) {+ public PseudoInstruction decodeInstruction(Address address, RegisterValue context) {lastMsg = DEFAULT_ERROR;if (!useCachedInstruction(address, context)) {parseNewBlock(address, context);@@ -116,7 +120,7 @@ public class SleighInstructionDecoder implements InstructionDecoder {* However, if the cached instruction's context does not match the desired one, assume we're* starting a new block. That check will have to wait for the decode call, though.*/- if (block.getInstructionAt(address) == null) {+ if (block == null || block.getInstructionAt(address) == null) {block = null;}}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ThreadPcodeExecutorState.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ThreadPcodeExecutorState.javaindex de88b6acfb..3d22ca833b 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ThreadPcodeExecutorState.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ThreadPcodeExecutorState.java@@ -149,8 +149,8 @@ public class ThreadPcodeExecutorState<T> implements PcodeExecutorState<T> {** <p>* This will only clear the thread's local state, lest we invoke clear on the shared state for- * every thread. Instead, if necessary, the machine should clear its local state then clear each- * thread's local state.+ * every thread. Instead, if necessary, the machine should clear its shared state then clear+ * each thread's local state.*/@Overridepublic void clear() {diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitBytesPcodeExecutorState.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitBytesPcodeExecutorState.javanew file mode 100644index 0000000000..ed1cd2a13f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitBytesPcodeExecutorState.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.pcode.emu.jit;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.pcode.exec.PcodeExecutorState;+import ghidra.program.model.address.AddressSpace;++/**+ * The run-time executor state for the JIT-accelerated p-code emulator+ *+ * @see JitDefaultBytesPcodeExecutorState+ * @see JitBytesPcodeExecutorStatePiece+ * @see JitBytesPcodeExecutorStateSpace+ */+public interface JitBytesPcodeExecutorState extends PcodeExecutorState<byte[]> {+ /**+ * For generated code to side-step the space lookup+ *+ * @param space the address space+ * @return the state space+ */+ JitBytesPcodeExecutorStateSpace getForSpace(AddressSpace space);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitBytesPcodeExecutorStatePiece.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitBytesPcodeExecutorStatePiece.javanew file mode 100644index 0000000000..5ba5ebadaf--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitBytesPcodeExecutorStatePiece.java@@ -0,0 +1,131 @@+/* ###+ * 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.pcode.emu.jit;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.pcode.exec.AbstractBytesPcodeExecutorStatePiece;+import ghidra.pcode.exec.BytesPcodeExecutorStateSpace;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Language;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The state piece for {@link JitDefaultBytesPcodeExecutorState}+ *+ * <p>+ * This provides access to the internals so that translated passages can pre-fetch certain objects+ * to optimize state accesses.+ */+public class JitBytesPcodeExecutorStatePiece+ extends AbstractBytesPcodeExecutorStatePiece<JitBytesPcodeExecutorStateSpace> {++ /**+ * An object to manage state for a specific {@link AddressSpace}+ */+ public class JitBytesPcodeExecutorStateSpace extends BytesPcodeExecutorStateSpace<Void> {++ /**+ * Construct a state space+ *+ * @param language the emulation target language+ * @param space the address space+ * @param backing any extra read-through backing (not used)+ */+ public JitBytesPcodeExecutorStateSpace(Language language, AddressSpace space,+ Void backing) {+ super(language, space, backing);+ }++ /**+ * Pre-fetch the byte array for the block (page) containing the given offset+ *+ * <p>+ * A translated passage is likely to call this several times in its constructor to pre-fetch+ * the byte arrays for variables (ram, register, and unique) that it accesses directly,+ * i.e., with a fixed offset. The generated code will then access the byte array directly to+ * read and write the variable values in the emulator's state.+ *+ * @param offset the {@link Address#getOffset() offset} within this address space.+ * @return the byte array for the containing block+ */+ public byte[] getDirect(long offset) {+ return bytes.getDirect(offset);+ }++ /**+ * Read a variable from this (pre-fetched) state space+ *+ * <p>+ * A translated passage is likely to call+ * {@link JitBytesPcodeExecutorStatePiece#getForSpace(AddressSpace, boolean)} once or twice+ * in its constructor to pre-fetch the per-space backing of any indirect memory variables+ * that it accesses, i.e., variables with a dynamic offset. These are usually required for+ * {@link PcodeOp#LOAD} and {@link PcodeOp#STORE} ops. The generated code will then invoke+ * this method (and {@link #write(long, byte[], int, int) write}) passing in the offset to+ * access variables in the emulator's state at runtime.+ *+ * @param offset the offset (known at runtime)+ * @param size the size of the variable+ * @return the value of the variable as a byte array+ */+ public byte[] read(long offset, int size) {+ return read(offset, size, Reason.EXECUTE_READ);+ }+ }++ /**+ * A state space map that creates a {@link JitBytesPcodeExecutorStateSpace} for each needed+ * {@link AddressSpace}+ */+ class JitBytesSpaceMap extends SimpleSpaceMap<JitBytesPcodeExecutorStateSpace> {+ @Override+ protected JitBytesPcodeExecutorStateSpace newSpace(AddressSpace space) {+ return new JitBytesPcodeExecutorStateSpace(language, space, null);+ }+ }++ /**+ * Construct a state piece+ *+ * @param language the emulation target language+ */+ public JitBytesPcodeExecutorStatePiece(Language language) {+ super(language);+ }++ @Override+ protected AbstractSpaceMap<JitBytesPcodeExecutorStateSpace> newSpaceMap() {+ return new JitBytesSpaceMap();+ }++ @Override+ public void clear() {+ throw new UnsupportedOperationException();+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Overridden to grant public access. The JIT-generated constructors will need to invoke this+ * method.+ */+ @Override+ public JitBytesPcodeExecutorStateSpace getForSpace(AddressSpace space, boolean toWrite) {+ return super.getForSpace(space, toWrite);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitCompiler.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitCompiler.javanew file mode 100644index 0000000000..185fd8bd58--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitCompiler.java@@ -0,0 +1,276 @@+/* ###+ * 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.pcode.emu.jit;++import java.lang.invoke.MethodHandles;+import java.lang.invoke.MethodHandles.Lookup;+import java.util.EnumSet;++import org.objectweb.asm.ClassWriter;++import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.decode.JitPassageDecoder;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassageClass;+import ghidra.pcode.exec.PcodeExecutorState;++/**+ * The Just-in-Time (JIT) translation engine that powers the {@link JitPcodeEmulator}.+ *+ * <p>+ * This is the translation engine from "any" machine language into JVM bytecode. The same caveats+ * that apply to interpretation-based p-code emulation apply to JIT-accelerated emulation: Ghidra+ * must have a Sleigh specification for the emulation target language, there must be userop+ * libraries (built-in or user-provided) defining any userops encountered during the course of+ * execution, all dependent code must be loaded or stubbed out, etc.+ *+ * <p>+ * A passage is decoded at a desired entry point using the {@link JitPassageDecoder}. This compiler+ * then translates the passage into bytecode. It will produce a classfile which is then loaded and+ * returned to the emulator (or other client). The provided class will have three principal methods,+ * not counting getters: 1) The class initializer, which initializes static fields; 2) The+ * constructor, which takes a thread and initializes instance fields, and 3) The+ * {@link JitCompiledPassage#run(int) run} method, which comprises the actual translation. A static+ * field {@code ENTRIES} describes each entry point generated by the compiler. To execute the+ * passage starting at a given entry point, the emulation thread must retrieve the index of the+ * appropriate entry (i.e., address and contextreg value), instantiate the class, and then invoke+ * the run method, passing it the entry index. The translated passage will read variables from the+ * thread's {@link JitBytesPcodeExecutorState state} as needed, perform the equivalent operations as+ * expressed in the source p-code, and then write the resulting variables back into the state.+ * Memory variables are treated similarly, but without scope-based optimizations. In this manner,+ * execution of the translated passage produces exactly the same effect on the emulation state as+ * interpretation of the same p-code passage. The run method returns the next entry point to execute+ * or {@code null} when the emulator must look up the next entry point.+ *+ * <p>+ * Translation of a passage takes place in distinct phases. See each respective class for details of+ * its design and implementation:+ *+ * <ol>+ * <li>Control Flow Analysis: {@link JitControlFlowModel}</li>+ * <li>Data Flow Analysis: {@link JitDataFlowModel}</li>+ * <li>Variable Scope Analysis: {@link JitVarScopeModel}</li>+ * <li>Type Assignment: {@link JitTypeModel}</li>+ * <li>Variable Allocation: {@link JitAllocationModel}</li>+ * <li>Operation Elimination: {@link JitOpUseModel}</li>+ * <li>Code Generation: {@link JitCodeGenerator}</li>+ * </ol>+ *+ * <h2>Control Flow Analysis</h2>+ * <p>+ * Some rudimentary control flow analysis is performed during decode, but the output of decode is a+ * passage, i.e., collection of <em>strides</em>, not basic blocks. The control flow analysis breaks+ * each stride down into basic blocks at the p-code level. Note that a single instruction's pcode+ * (as well as any user instrumentation on that instruction's address) may have complex control+ * flow. Additionally, branches that leave an instruction preclude execution of its remaining+ * p-code. Thus, p-code basic blocks do not coincide precisely with instruction-level basic blocks.+ * See {@link JitControlFlowModel}.+ *+ * <h2>Data Flow Analysis</h2>+ * <p>+ * Most every following step consumes the control flow analysis. Data flow analysis interprets each+ * basic block independently using an abstraction that produces a use-def graph. A varnode that is+ * read before it is written produces a "missing" variable. Those missing variables are converted to+ * <em>phi</em> nodes and later resolved during inter-block analysis. The graph is also able to+ * consider aliasing, partial accesses, overlapping accesses, etc., by synthesizing operations to+ * model those effects. See {@link JitDataFlowModel}.+ *+ * <h2>Variable Scope Analysis</h2>+ * <p>+ * Because accessing {@link PcodeExecutorState} is expensive (relative to accessing a JVM local+ * variable), the translation seeks to minimize such accesses. This is generally not recommended for+ * memory accesses, as there is no telling in multi-threaded applications whether a given memory+ * variable is shared/volatile or not. However, for registers and uniques, we can allocate the+ * variables as JVM locals. Then we only "birth" them (read them in) when they come into scope and+ * "retire" them (write them out) when they leave scope. This analyzer determines which variables+ * are in scope (alive) in which basic blocks. See {@link JitVarScopeModel}.+ *+ * <h2>Type Assignment</h2>+ * <p>+ * For those variables we allocate as JVM locals, we have to choose a type, because the JVM requires+ * it. We have essentially 4 to choose from. (Though we could also choose a <em>reference</em> type,+ * depending on the strategy we eventually choose for multi-precision arithmetic.) Those four are+ * the JVM primitives: int, float, long, and double. For those more familiar with Java but not the+ * JVM, the smaller integral primitives are all represented by JVM ints. The JVM does not permit+ * type confusion, e.g., the application of float addition {@code FADD} to int variables. However,+ * the emulation target may permit type confusion. (Those familiar with the constant 0x5f759df may+ * appreciate intentional type confusion.) When this happens, we must explicitly convert by calling,+ * e.g., {@link Float#floatToRawIntBits(float)}, which is essentially just a bit cast. Nevertheless,+ * we seek to reduce the number of such calls we encode into the translation. See+ * {@link JitTypeModel}.+ *+ * <h2>Variable Allocation</h2>+ * <p>+ * Once we've decided the type of each use-def variable node, we allocate JVM locals and assign+ * their types accordingly. To keep things simple and fast, we just allocate variables by varnode.+ * Partial/overlapping accesses are coalesced to the containing varnode and cause the type to be a+ * JVM int (to facilitate shifting and masking). Otherwise, types are assigned according to the most+ * common use of the varnode, i.e., by taking a vote among the use-def variable nodes sharing that+ * varnode. See {@link JitAllocationModel}.+ *+ * <h2>Operation Elimination</h2>+ * <p>+ * Each instruction typically produces several p-code ops, the outputs of which may not actually be+ * used by any subsequent op. This analysis seeks to identify such p-code ops and remove them. Since+ * many ISAs employ "flags," which are set by nearly every arithmetic instruction, such ops are+ * incredibly common. Worse yet, their computation is very expensive, because the JVM does not have+ * comparable flag registers, nor does it provide opcodes for producing comparable values. We have+ * to emit the bit banging operations ourselves. Thus, performing this elimination stands to improve+ * execution speed significantly. However, eliminating these operations may lead to confusing+ * results if execution is interrupted and the state inspected by a user. The effects of the+ * eliminated operations will be missing. Even though they do not (or should not) matter, the user+ * may expect to see them. Thus, this step can be toggled by+ * {@link JitConfiguration#removeUnusedOperations()}. See {@link JitOpUseModel}.+ *+ * <h2>Code Generation</h2>+ * <p>+ * For simplicity, we seek to generate JVM bytecode in the same order as the source p-code ops.+ * There are several details given the optimizations informed by all the preceding analysis. For+ * example, the transfer of control to the requested entry point, the placement of variable birth+ * and retirement on control flow edges (including fall-through).... We take an object-oriented+ * approach to the translation of each p-code op, the handling of each variable's allocation and+ * access, the conversion of types, etc. This phase outputs the final classfile bytes, which are+ * then loaded as a hidden class. See {@link JitCodeGenerator}.+ *+ * @implNote There are static fields in this class for configuring diagnostics. They are meant to be+ * modified only temporarily by developers seeking to debug issues in the translation+ * engine.+ */+public class JitCompiler {+ /**+ * Diagnostic toggles+ */+ public enum Diag {+ /** Print each passage (instructions and p-code ops) before translation */+ PRINT_PASSAGE,+ /** Print the contents (p-code) of each basic block and flows/branches among them */+ PRINT_CFM,+ /** Print the ops of each basic block in SSA (sort of) form */+ PRINT_DFM,+ /** Print the list of live variables for each basic block */+ PRINT_VSM,+ /** Print each synthetic operation, e.g., catenation, subpiece, phi */+ PRINT_SYNTH,+ /** Print each eliminated op */+ PRINT_OUM,+ /** Enable ASM's trace for each generated classfile */+ TRACE_CLASS,+ /** Save the generated {@code .class} file to disk for offline examination */+ DUMP_CLASS;+ }++ /**+ * The set of enabled diagnostic toggles.+ *+ * <p>+ * In production, this should be empty.+ */+ public static final EnumSet<Diag> ENABLE_DIAGNOSTICS = EnumSet.noneOf(Diag.class);+ /**+ * Exclude a given address offset from ASM's {@link ClassWriter#COMPUTE_MAXS} and+ * {@link ClassWriter#COMPUTE_FRAMES}.+ *+ * <p>+ * Unfortunately, when automatic computation of frames and maxes fails, the ASM library offers+ * little in terms of diagnostics. It usually crashes with an NPE or an AIOOBE. Worse, when this+ * happens, it fails to output any of the classfile trace. To help with this, a developer may+ * identify the address of the passage seed that causes such a failure and set this variable to+ * its offset. This will prevent ASM from attempting this computation so that it at least prints+ * the trace and dumps out the classfile to disk (if those {@link Diag}nostics are enabled).+ *+ * <p>+ * Once the trace/classfile is obtained, set this back to -1 and then apply debug prints in the+ * crashing method. Since it's probably in the ASM library, you'll need to use your IDE /+ * debugger to inject those prints. The way to do this in Eclipse is to set a "conditional+ * breakpoint" then have the condition print the value and return false, so that execution+ * continues. Sadly, this will still slow execution down considerably, so you'll want to set+ * some other conditional breakpoint to catch when the troublesome passage is being translated.+ * Probably the most helpful thing to print is the bytecode offset of each basic block ASM is+ * processing as it computes the frames. Once it crashes, look at the last couple of bytecode+ * offsets in the dumped classfile.+ */+ public static final long EXCLUDE_MAXS = -1L;++ /**+ * The JIT emulator's configuration+ */+ private final JitConfiguration config;++ /**+ * Construct a p-code to bytecode translator.+ *+ * <p>+ * In general, this should only be used by the JIT emulator and its test suite.+ *+ * @param config the configuration+ */+ public JitCompiler(JitConfiguration config) {+ this.config = config;+ }++ /**+ * Translate a passage using the given lookup+ *+ * @param lookup a lookup that can access everything the passage may need, e.g., userop+ * libraries. Likely, this should come from the emulator, which may be in a script.+ * If you are unsure what to use here, use {@link MethodHandles#lookup()}. If you see+ * errors about accessing stuff during the compilation, ensure everything the+ * emulator needs is accessible from the method calling+ * {@link MethodHandles#lookup()}.+ * @param passage the decoded passage to compile+ * @return the compiled class, not instantiated for any particular thread+ */+ public JitCompiledPassageClass compilePassage(Lookup lookup, JitPassage passage) {+ if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_PASSAGE)) {+ System.err.println(passage);+ }+ JitAnalysisContext context = new JitAnalysisContext(config, passage);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_CFM)) {+ cfm.dumpResult();+ }+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_DFM)) {+ dfm.dumpResult();+ }+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm);+ if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_VSM)) {+ vsm.dumpResult();+ }+ JitTypeModel tm = new JitTypeModel(dfm);+ JitAllocationModel am = new JitAllocationModel(context, dfm, vsm, tm);+ JitOpUseModel oum = new JitOpUseModel(context, cfm, dfm, vsm);+ if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_SYNTH)) {+ dfm.dumpSynth();+ }+ if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_OUM)) {+ oum.dumpResult();+ }++ JitCodeGenerator gen = new JitCodeGenerator(lookup, context, cfm, dfm, vsm, tm, am, oum);+ return gen.load();+ }++ /**+ * Get this compiler's configuration+ *+ * @return the configuration+ */+ public JitConfiguration getConfiguration() {+ return config;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitConfiguration.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitConfiguration.javanew file mode 100644index 0000000000..02fca050b5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitConfiguration.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.pcode.emu.jit;++/**+ * The configuration for a JIT-accelerated emulator.+ *+ * @param maxPassageInstructions The (soft) maximum number of instructions to decode per translated+ * passage. A passage can consist of several control-flow connected basic blocks. The+ * decoder will decode contiguous streams of instructions with fall-through (called+ * <em>strides</em>), adding seeds where it encounters branches. It will not stop+ * mid-stride, but checks the instruction count before proceeding to another seed. If it+ * exceeds the max, it stops.+ * @param maxPassageOps The (soft) maximum number of p-code ops. This is similar to+ * {@link #maxPassageInstructions}, but limits the number of p-code ops generated.+ * <b>NOTE:</b> The JVM limits each method to 65,535 total bytes of bytecode. If this+ * limit is exceeded, the ASM library throws an exception. When this happens, the+ * compiler will retry the whole process, but with this configuration parameter halved.+ * @param maxPassageStrides The maximum number of strides to include.+ * @param removeUnusedOperations Some p-code ops produce outputs that are never used later. One+ * common case is flags computed from arithmetic operations. If this option is enabled,+ * the JIT compiler will remove those p-code ops.+ * @param emitCounters Causes the translator to emit a call to+ * {@link JitPcodeThread#count(int, int)} at the start of each basic block.+ */+public record JitConfiguration(+ int maxPassageInstructions,+ int maxPassageOps,+ int maxPassageStrides,+ boolean removeUnusedOperations,+ boolean emitCounters) {++ /**+ * Construct a default configuration+ */+ public JitConfiguration() {+ this(1000, 5000, 10, true, true);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitDefaultBytesPcodeExecutorState.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitDefaultBytesPcodeExecutorState.javanew file mode 100644index 0000000000..f791ff73bb--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitDefaultBytesPcodeExecutorState.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.pcode.emu.jit;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.pcode.emu.jit.analysis.JitDataFlowState;+import ghidra.pcode.exec.BytesPcodeArithmetic;+import ghidra.pcode.exec.DefaultPcodeExecutorState;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Language;++/**+ * The default implementation of {@link JitBytesPcodeExecutorState}.+ *+ * <p>+ * <b>NOTE</b>: This is distinct from {@link JitDataFlowState}, which is used during the+ * interpretation and analysis of the passage to translate. This state, in contrast, is the concrete+ * state of the emulation target, but accessible in special ways to the translation output. In+ * particular, the constructor of each translation is permitted direct access to some of this+ * state's internals, so that it can pre-fetch, e.g., backing arrays for direct memory access+ * operations.+ *+ * <p>+ * This is just an extension of {@link DefaultPcodeExecutorState} that wraps the corresponding+ * {@link JitBytesPcodeExecutorStatePiece}.+ */+public class JitDefaultBytesPcodeExecutorState extends DefaultPcodeExecutorState<byte[]>+ implements JitBytesPcodeExecutorState {++ /**+ * Construct a new state for the given language+ *+ * @param language the emulation target language+ */+ public JitDefaultBytesPcodeExecutorState(Language language) {+ super(new JitBytesPcodeExecutorStatePiece(language),+ BytesPcodeArithmetic.forLanguage(language));+ }++ /**+ * Get the piece cast to the type we know it is+ *+ * @return the piece+ */+ protected JitBytesPcodeExecutorStatePiece getPiece() {+ return (JitBytesPcodeExecutorStatePiece) this.piece;+ }++ @Override+ public JitBytesPcodeExecutorStateSpace getForSpace(AddressSpace space) {+ return getPiece().getForSpace(space, true);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitJvmTypeUtils.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitJvmTypeUtils.javanew file mode 100644index 0000000000..29e1a02825--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitJvmTypeUtils.java@@ -0,0 +1,119 @@+/* ###+ * 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.pcode.emu.jit;++import java.lang.reflect.*;+import java.util.stream.Collectors;+import java.util.stream.Stream;++import org.apache.commons.lang3.reflect.TypeLiteral;+import org.objectweb.asm.ClassVisitor;++/**+ * Some utilities for generating type signatures, suitable for use with+ * {@link ClassVisitor#visitField(int, String, String, String, Object)}.+ *+ * <p>+ * <b>WARNING:</b> It seems to me, the internal representation of signatures as accepted by the ASM+ * API is not fixed from version to version. In the future, these utilities may need to be updated+ * to work with multiple versions, if the representation changes in a newer classfile format.+ * Hopefully, the upcoming classfile API will obviate the need for any of this.+ */+public enum JitJvmTypeUtils {+ ;++ /**+ * Get the internal name of a class as in {@link org.objectweb.asm.Type#getInternalName(Class)}.+ *+ * @param cls the class+ * @return the internal name+ */+ public static String classToInternalName(Class<?> cls) {+ return org.objectweb.asm.Type.getInternalName(cls);+ }++ /**+ * Presume the given type is a {@link Class} and get its internal name+ *+ * @param type the type+ * @return the internal name+ */+ public static String rawToInternalName(Type type) {+ return classToInternalName((Class<?>) type);+ }++ /**+ * Get the signature of the given wildcard type+ *+ * <ul>+ * <li>{@code sig(?) = *}</li>+ * <li>{@code sig(? super MyType) = -sig(MyType)}</li>+ * <li>{@code sig(? extends MyType) = +sig(MyType)}</li>+ * </ul>+ *+ * @param wt the type+ * @return the signature+ */+ public static String wildToSignature(WildcardType wt) {+ Type lower = wt.getLowerBounds().length == 0 ? null : wt.getLowerBounds()[0];+ Type upper = wt.getUpperBounds()[0];+ if (lower == null && upper == Object.class) {+ return "*";+ }+ if (lower == null) {+ return "+" + typeToSignature(upper);+ }+ if (upper == Object.class) {+ return "-" + typeToSignature(lower);+ }+ throw new UnsupportedOperationException();+ }++ /**+ * Get the signature of the given type+ *+ * <p>+ * For the use case this supports, probably the best way to obtain a {@link Type} is via+ * {@link TypeLiteral}.+ *+ * <p>+ * As of the JVM 21, internal type signatures are derived as:+ *+ * <ul>+ * <li>{@code sig(my.MyType) = Lmy/MyType.class;}</li>+ * <li>{@code sig(my.MyType[]) = [sig(my.MyType)}</li>+ * <li>{@code sig(my.MyType<Yet, Another, ...>) = Lmy/MyType<sig(Yet), sig(Another), ...>;}</li>+ * <li>Wildcard types as in {@link #wildToSignature(WildcardType)}</li>+ * <li>Type variables are not supported by these utilities</li>+ * </ul>+ *+ * @param type the type+ * @return the signature+ */+ public static String typeToSignature(Type type) {+ return switch (type) {+ case Class<?> cls -> "L" + classToInternalName(cls) + ";";+ case GenericArrayType arr -> "[" + typeToSignature(arr.getGenericComponentType());+ case ParameterizedType pt -> "L" + rawToInternalName(pt.getRawType()) + "<" ++ Stream.of(pt.getActualTypeArguments())+ .map(a -> typeToSignature(a))+ .collect(Collectors.joining(",")) ++ ">;";+ case WildcardType wt -> wildToSignature(wt);+ default -> throw new UnsupportedOperationException();+ };+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPassage.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPassage.javanew file mode 100644index 0000000000..502359c701--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPassage.java@@ -0,0 +1,849 @@+/* ###+ * 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.pcode.emu.jit;++import java.math.BigInteger;+import java.util.*;+import java.util.stream.Collectors;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.app.util.PseudoInstruction;+import ghidra.pcode.emu.PcodeMachine;+import ghidra.pcode.emu.PcodeThread;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockSplitter;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitDataFlowModel;+import ghidra.pcode.emu.jit.decode.JitPassageDecoder;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.op.OpGen;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.exec.*;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressOverflowException;+import ghidra.program.model.lang.*;+import ghidra.program.model.listing.ContextChangeException;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.mem.ByteMemBufferImpl;+import ghidra.program.model.pcode.*;+import ghidra.program.util.ProgramContextImpl;++/**+ * A selection of instructions decoded from an emulation target, the generated p-code ops, and+ * associated metadata.+ *+ * <p>+ * Note that the generated p-code ops include those injected by the emulator's client using+ * {@link PcodeMachine#inject(Address, String)} and {@link PcodeThread#inject(Address, String)},+ * which also includes breakpoints, i.e, {@link PcodeMachine#addBreakpoint(Address, String)}.+ *+ * @see JitPassageDecoder Passage decoding+ */+public class JitPassage extends PcodeProgram {++ /**+ * Check if a given p-code op could fall through+ *+ * <p>+ * Conditional branches and non-branching ops are the only ones that can fall through. Note that+ * for JIT purposes, a {@link PcodeOp#CALL CALL} op <em>does not</em> fall through! For+ * decompilation, it hints that it's branching to a subroutine that <em>usually</em> returns+ * back to the caller, but the JIT compiler does not take that hint. 1) There's no guarantee it+ * will actually return. 2) Even if it did, it would be via a {@link PcodeOp#RETURN}, which is+ * an <em>indirect</em> branch. An indirect branch is not sufficient to join two strides in the+ * same passage. Thus, we have little to gain by falling through a call, and the more likely+ * outcome is the JIT and/or ASM library will eliminate the code following the call.+ *+ * @param op the op to consider+ * @return true if the op does or could fall through+ */+ public static boolean hasFallthrough(PcodeOp op) {+ if (op instanceof NopPcodeOp) {+ return true;+ }+ return switch (op.getOpcode()) {+ case PcodeOp.BRANCH, PcodeOp.BRANCHIND -> false;+ case PcodeOp.CALL, PcodeOp.CALLIND, PcodeOp.RETURN -> false;+ case PcodeOp.UNIMPLEMENTED -> false;+ case PcodeOp.CBRANCH -> true;+ default -> true;+ };+ }++ /**+ * An address-context pair+ *+ * <p>+ * Because decode is sensitive to the contextreg value, we have to consider that visiting the+ * same address with a different context could produce a completely different stride. Thus, we+ * subsume the context value in a sense as part of the address when seeding the passage decoder,+ * when referring to the "location" of p-code ops, when exiting a translated passage, etc.+ */+ public static final class AddrCtx implements Comparable<AddrCtx> {+ /**+ * An address-context pair for synthetic p-code ops+ *+ * <p>+ * This is currently used in probing an instruction (possibly instrumented) for fall+ * through, and in testing.+ */+ public static final AddrCtx NOWHERE = new AddrCtx(null, Address.NO_ADDRESS);++ /**+ * Derive the address-context pair from an instruction's context+ *+ * @param insCtx the context+ * @return the address and input decode context of the instruction whose context was given+ */+ public static AddrCtx fromInstructionContext(InstructionContext insCtx) {+ return new AddrCtx(getInCtx(insCtx), insCtx.getAddress());+ }++ /**+ * Derive the address-context pair from an instruction+ *+ * @param instruction the instruction+ * @return the instruction's address and input decode context+ */+ public static AddrCtx fromInstruction(Instruction instruction) {+ return fromInstructionContext(instruction.getInstructionContext());+ }++ /**+ * The contextreg value as a big integer+ *+ * <p>+ * This is 0 when the language does not have a context register+ */+ public final BigInteger biCtx;+ /**+ * The contextreg as a register value+ *+ * <p>+ * This is {@code null} when the language does not have a context register+ */+ public final RegisterValue rvCtx;+ /**+ * The address+ */+ public final Address address;++ /**+ * Construct an address-context pair+ *+ * @param ctx the contextreg value+ * @param address the address+ */+ public AddrCtx(RegisterValue ctx, Address address) {+ this.biCtx = ctx == null ? BigInteger.ZERO : ctx.getUnsignedValue();+ this.rvCtx = ctx;+ this.address = Objects.requireNonNull(address);+ }++ @Override+ public String toString() {+ return "AddrCtx[ctx=%s,addr=%s]".formatted(rvCtx, address);+ }++ @Override+ public int hashCode() {+ return Objects.hash(biCtx, address);+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (!(obj instanceof AddrCtx that)) {+ return false;+ }+ return this.biCtx.equals(that.biCtx) &&+ this.address.equals(that.address);+ }++ @Override+ public int compareTo(AddrCtx that) {+ int c;+ c = this.biCtx.compareTo(that.biCtx);+ if (c != 0) {+ return c;+ }+ c = this.address.compareTo(that.address);+ if (c != 0) {+ return c;+ }+ return 0;+ }+ }++ /**+ * Derive the decode context value from the given instruction context+ *+ * @param insCtx the context+ * @return the input decode context from the instruction whose context was given+ */+ protected static RegisterValue getInCtx(InstructionContext insCtx) {+ ProcessorContextView procCtx = insCtx.getProcessorContext();+ Register contextreg = procCtx.getBaseContextRegister();+ if (contextreg == Register.NO_CONTEXT) {+ return null;+ }+ return procCtx.getRegisterValue(contextreg);+ }++ /**+ * Derive the decode context value from the given instruction+ *+ * @param instruction the instruction+ * @return the input decode context from the instruction+ */+ protected static RegisterValue getInCtx(Instruction instruction) {+ return getInCtx(instruction.getInstructionContext());+ }++ /**+ * A branch in the p-code+ */+ public interface Branch {+ /**+ * The op performing the branch+ *+ * @return the "from" op+ */+ PcodeOp from();++ /**+ * Indicates whether this branch represents a fall-through case.+ *+ * <p>+ * Note that the {@link #from()} may not be an actual branching p-code op when+ * {@code isFall} is true. A "fall-through" branch happens in two cases. First, and most+ * obvious, is to describe the fall-through case of a {@link PcodeOp#CBRANCH conditional+ * branch}. Second is when for a p-code op the immediately precedes the target of some other+ * branch. That branch causes a split in basic blocks, and so to encode the fall through+ * from that op into the basic block immediately after, a fall-through branch is added.+ *+ * @return true if this branch is the fall-through case.+ */+ default boolean isFall() {+ return false;+ }++ /**+ * Get a string description of the branch target+ *+ * @return the description+ */+ default String describeTo() {+ return toString();+ }+ }++ /**+ * A branch to another p-code op in the same passage+ *+ * <p>+ * The {@link JitCodeGenerator} translates internal branches into JVM bytecodes for the+ * equivalent branch to the translation of the target p-code op. Thus, we remain executing+ * inside the {@link JitCompiledPassage#run(int) run} method. This branch type incurs the least+ * run-time cost.+ *+ * @param from see {@link #from()}+ * @param to the target p-code op+ * @param isFall see {@link #isFall()}+ */+ public record IntBranch(PcodeOp from, PcodeOp to, boolean isFall) implements Branch {}++ /**+ * A branch to an address (and context value) not in the same passage+ *+ * <p>+ * When execution encounters this branch, the {@link JitCompiledPassage#run(int) run} method+ * sets the emulator's program counter and context to the {@link #to() branch target} and+ * returns the appropriate entry point for further execution.+ *+ * Note that this branch type is used by the decoder to track queued decode seeds as well.+ * External branches that get decoded are changed into internal branches.+ *+ * @param from see {@link #from()}+ * @param to the target address-context pair+ */+ public record ExtBranch(PcodeOp from, AddrCtx to) implements Branch {}++ /**+ * A branch to a dynamic address+ *+ * <p>+ * When execution encounters this branch, the {@link JitCompiledPassage#run(int) run} method+ * will set the emulator's program counter to the computed address and its context to+ * {@link #flowCtx()}, then return the appropriate entry point for further execution.+ *+ * <p>+ * TODO: Some analysis may be possible to narrow the possible addresses to a known few and then+ * treat this as several {@link IntBranch}es; however, I worry this is too expensive for what it+ * gets us. This will be necessary if we are to JIT, e.g., a switch table.+ *+ * @param from see {@link #from()}+ * @param flowCtx the decode context after the branch is taken+ */+ public record IndBranch(PcodeOp from, RegisterValue flowCtx) implements Branch {}++ /**+ * A "branch" representing an error+ *+ * <p>+ * When execution encounters this branch, the {@link JitCompiledPassage#run(int) run} method+ * throws an exception. This branch is used to encode error conditions that may not actually be+ * encountered at run time. Some cases are:+ *+ * <ul>+ * <li>An instruction decode error — synthesized as a {@link DecodeErrorPcodeOp}</li>+ * <li>An {@link PcodeOp#UNIMPLEMENTED unimplemented} instruction</li>+ * <li>A {@link PcodeOp#CALLOTHER call} to an undefined userop</li>+ * </ul>+ *+ * <p>+ * The decoder and translator may encounter such an error, but unless execution actually reaches+ * the error, the emulator need not crash. Thus, we note the error and generate code that will+ * actually throw it in the translation, only if it's actually encountered.+ *+ * <p>+ * Note that the {@link OpGen} for the specific p-code op generating the error will decide what+ * exception type to throw.+ *+ * @param from see {@link #from()}+ * @param message the error message for the exception+ */+ public record ErrBranch(PcodeOp from, String message) implements Branch {}++ /**+ * An extension of {@link PcodeOp} that carries along with it the address and decode context+ * where it occurred.+ *+ * <p>+ * There is a difference between {@link #at}'s {@link AddrCtx#address address} vs.+ * {@link #getSeqnum() seqnum}'s {@link SequenceNumber#getTarget() target}. The former is+ * determined by the {@link JitPassageDecoder} and applied to all p-code ops generated at that+ * address (and context value), including those from injected Sleigh. The latter is determined+ * by the {@link Instruction} (or injected {@link PcodeProgram}), which have less information+ * about their origins. There are also {@link DecodeErrorPcodeOp} and {@link NopPcodeOp}, which+ * are synthesized by the {@link JitPassageDecoder} without an instruction or inject. This+ * information is required for bookkeeping, esp., when updating the emulator's program counter+ * and decode context when a p-code op produces an unexpected run-time error.+ */+ public static class DecodedPcodeOp extends PcodeOp {+ private final AddrCtx at;++ /**+ * Construct a new p-code op, decoded by the {@link JitPassageDecoder}+ *+ * @param at the address and context value where the op was produced+ * @param seqnum the p-code op sequence number+ * @param opcode the p-code opcode+ * @param inputs the input varnodes+ * @param output the output varnode, or {@link null} if none or not applicable+ */+ DecodedPcodeOp(AddrCtx at, SequenceNumber seqnum, int opcode, Varnode[] inputs,+ Varnode output) {+ super(seqnum, opcode, inputs, output);+ this.at = at;+ }++ /**+ * Re-write a p-code op including its address and context value+ *+ * <p>+ * Aside from {@link #at}, everything is copied from the given original p-code op.+ *+ * @param at the address and context value where the op was produced+ * @param original the original p-code op+ */+ public DecodedPcodeOp(AddrCtx at, PcodeOp original) {+ this(at, original.getSeqnum(), original.getOpcode(), original.getInputs(),+ original.getOutput());+ }++ /**+ * Get the address and context value where this op was produced+ *+ * @return the address-context pair+ */+ public AddrCtx getAt() {+ return at;+ }++ /**+ * Get the address where this op was produced+ *+ * @return the address+ */+ public Address getCounter() {+ return at.address;+ }++ /**+ * Get the decode context where this op was produced+ *+ * @return the decode context+ */+ public RegisterValue getContext() {+ return at.rvCtx;+ }++ /**+ * Check if this op represents the start of an instruction+ *+ * <p>+ * If this p-code op was produced by an inject, this will return false! It only returns true+ * for an op that is genuinely the first op in the result of {@link Instruction#getPcode()}.+ * <b>WARNING:</b> This should <em>not</em> be used for branching purposes, because branches+ * to a given address are meant to target any injections there, too. Currently, this is used+ * only to count the number of instructions actually executed.+ *+ * @see JitBlock#instructionCount()+ * @see JitCompiledPassage#count(int, int)+ * @see JitPcodeThread#count(int, int)+ * @return true if this op is the first of an instruction+ */+ public boolean isInstructionStart() {+ SequenceNumber seq = getSeqnum();+ return seq.getTime() == 0 && seq.getTarget().equals(at.address);+ }+ }++ /**+ * A synthetic p-code op that represents a return from the {@link JitCompiledPassage#run(int)}+ * method.+ *+ * <p>+ * When execution encounters this op (and the corresponding {@link ExtBranch}), the emulator's+ * program counter and context values are set to the {@link ExtBranch#to() branch target}, and+ * the appropriate entry point is returned.+ *+ * <p>+ * This is used in a few ways: The simplest, though perhaps not obvious, way is when the decoder+ * encounters an existing entry point. We avoid re-translating the same instructions by forcing+ * the stride to end. However, the last instruction in that stride would have fall through,+ * causing dangling control flow. To mitigate that, we append a synthetic exit op to return the+ * existing entry point. The emulator can then resume execution accordingly.+ *+ * <p>+ * The next is even less obvious. When the emulation client (or user) injects Sleigh, a common+ * mistake is to forget control flow. The decoder detects this when "falling through" does not+ * actually advance the program counter. In this case, we append this synthetic op to exit the+ * translated passage. While it still results in an endless loop (just like the+ * interpretation-based emulator), it's easier to interrupt and diagnose when we exit the+ * translation between each "iteration."+ *+ * <p>+ * The last is a small hack: The decoder needs to know whether each instruction (possibly+ * instrumented by an inject) falls through. To do this, it appends an exit op to the very end+ * of the instruction's (and inject's) ops and performs rudimentary control flow analysis (see+ * {@link BlockSplitter}). It then seeks a path from start to exit. If one is found, it has fall+ * through. This "probe" op is <em>not</em> included in the decoded stride.+ *+ */+ public static class ExitPcodeOp extends PcodeOp {+ /**+ * Construct a synthetic exit op+ *+ * @param at the address and context value to set on the emulator when exiting the+ * {@link JitCompiledPassage#run(int)} method+ */+ public ExitPcodeOp(AddrCtx at) {+ super(new SequenceNumber(at.address, 0), PcodeOp.BRANCH, new Varnode[] {+ new Varnode(at.address, 0) }, null);+ }+ }++ /**+ * A synthetic op representing the initial seed of a decoded passage.+ *+ * <p>+ * Because we use a queue of {@link ExtBranch}es as the seed queue, and the initial seed has no+ * real {@link Branch#from()}, we synthesize a {@link PcodeOp#BRANCH branch op} from the entry+ * address to itself. This synthetic op is <em>not</em> included in the decoded stride.+ */+ public static class EntryPcodeOp extends PcodeOp {+ /**+ * Construct the passage entry p-code op.+ *+ * @param entry the target address and decode context of the passage seed+ */+ public EntryPcodeOp(AddrCtx entry) {+ super(Address.NO_ADDRESS, 0, PcodeOp.BRANCH, new Varnode[] {+ new Varnode(entry.address, 0) });+ }+ }++ /**+ * A synthetic p-code op meant to encode "no operation"+ *+ * <p>+ * P-code does not have a NOP opcode, because there's usually no reason to produce such. A NOP+ * machine instruction just produces an empty list of p-code ops, denoting "no operation."+ * However, for bookkeeping purposes in our JIT translator, we occasionally need some op to hold+ * an important place, but that op needs to do nothing. We use this in two situations:+ *+ * <ul>+ * <li>An instruction (possibly because of an inject) that does nothing. Yes, essentially a NOP+ * machine instruction. Because another op may target this instruction, and {@link Branch}es+ * need to target a p-code op, we synthesize a p-code "nop" to hold that position. The+ * alternative is to figure out what op immediately follows the branch target, but such an op+ * may not have been decoded, yet. It's easier just to synthesize the nop.</li>+ * <li>A p-code branch to the end of an instruction. Most often a slaspec author that means to+ * skip the remainder of an instruction will use {@code goto inst_next}; however, because of+ * sub-table structuring and/or personal preferences, sometimes we see {@code goto <end>;} where+ * {@code <end>} is at the end of the instruction, and thus, no p-code op actually follows it.+ * We essentially have the same situation and the NOP machine instruction where we can either+ * synthesize a placeholder nop, or else we have to figure out what op does (or will) actually+ * follow the label.</li>+ * </ul>+ */+ public static class NopPcodeOp extends DecodedPcodeOp {+ /**+ * Construct a synthetic p-code "nop"+ *+ * @param at the address-context pair where the op was generated+ * @param seq the sequence where the nop is inserted. For machine-code NOP, this should be+ * 0. For a branch to the end of an instruction, this should be the next sequence+ * number (so that the branch targets this nop)+ */+ public NopPcodeOp(AddrCtx at, int seq) {+ super(at, new SequenceNumber(at.address, seq), PcodeOp.UNIMPLEMENTED, new Varnode[] {},+ null);+ }+ }++ /**+ * A synthetic p-code op denoting a decode error+ *+ * <p>+ * The decoder may encounter several decode errors as it selects and decodes the passage. An+ * instruction is selected because the JIT believes it <em>may</em> be executed by the emulator.+ * (Predicting this and making good selections is a matter of further research.) Encounting a+ * decode error along a possible path is not cause to throw an exception. However; if the+ * emulator does in fact attempt to execute the bytes which it can't decode, then we do throw+ * the exception. This p-code op is synthesized where such decode errors occur, and the+ * translator will generate code that actually throw the exception. Note that the error message+ * is placed in the corresponding {@link ErrBranch}.+ */+ public static class DecodeErrorPcodeOp extends DecodedPcodeOp {+ /**+ * Construct a p-code op representing an instruction decode error.+ *+ * @param at the address and decode context where the error occurred+ */+ public DecodeErrorPcodeOp(AddrCtx at) {+ super(at, new SequenceNumber(at.address, 0), PcodeOp.UNIMPLEMENTED, new Varnode[] {},+ null);+ }+ }++ /**+ * An instruction denoting a decode error+ *+ * <p>+ * The Sleigh disassembler normally denotes this with a {@link PseudoInstruction} having an+ * {@link InvalidPrototype}. We essentially do the same here, but with custom types that are+ * simpler to identify. Additionally, the types contain additional information, e.g., the error+ * message. We also need the prototype to produce a single {@link DecodeErrorPcodeOp}.+ */+ public static class DecodeErrorInstruction extends PseudoInstruction {++ /**+ * The prototype for the decode error instruction+ */+ static class DecodeErrorPrototype extends InvalidPrototype {+ public DecodeErrorPrototype(Language language) {+ super(language);+ }++ @Override+ public PcodeOp[] getPcode(InstructionContext context, PcodeOverride override) {+ return new PcodeOp[] {+ new DecodeErrorPcodeOp(AddrCtx.fromInstructionContext(context)) };+ }+ }++ /**+ * An implementation of {@link ProcessorContext} to satisfy the requirements of the+ * {@link PseudoInstruction}.+ *+ * <p>+ * This need do little more than provide the decode context register value.+ */+ static class DecodeErrorProcessorContext implements ProcessorContext {+ private final Language language;+ private final RegisterValue ctx;++ public DecodeErrorProcessorContext(Language language, RegisterValue ctx) {+ this.language = language;+ this.ctx = ctx;+ }++ @Override+ public Register getBaseContextRegister() {+ return language.getContextBaseRegister();+ }++ @Override+ public List<Register> getRegisters() {+ return language.getRegisters();+ }++ @Override+ public Register getRegister(String name) {+ return language.getRegister(name);+ }++ @Override+ public BigInteger getValue(Register register, boolean signed) {+ if (register == language.getContextBaseRegister()) {+ return signed ? ctx.getSignedValue() : ctx.getUnsignedValue();+ }+ return null;+ }++ @Override+ public RegisterValue getRegisterValue(Register register) {+ if (register == language.getContextBaseRegister()) {+ return ctx;+ }+ return null;+ }++ @Override+ public boolean hasValue(Register register) {+ return register == language.getContextBaseRegister();+ }++ @Override+ public void setValue(Register register, BigInteger value)+ throws ContextChangeException {+ }++ @Override+ public void setRegisterValue(RegisterValue value)+ throws ContextChangeException {+ }++ @Override+ public void clearRegister(Register register) throws ContextChangeException {+ }+ }++ private final String message;++ /**+ * Construct an instruction to indicate a decode error+ *+ * @param language the emulation target langauge+ * @param address the address where decode was attempted+ * @param ctx the input decode context+ * @param message a message for the {@link DecodePcodeExecutionException} if the emulator+ * attempts to execute this instruction+ * @throws AddressOverflowException never+ */+ public DecodeErrorInstruction(Language language, Address address, RegisterValue ctx,+ String message) throws AddressOverflowException {+ super(address, new DecodeErrorPrototype(language),+ new ByteMemBufferImpl(address, new byte[] { 0 }, language.isBigEndian()),+ new DecodeErrorProcessorContext(language, ctx));+ this.message = message;+ }++ /**+ * Get the message for the exception, should this instruction be "executed"+ *+ * @return the error message+ */+ public String getMessage() {+ return message;+ }+ }++ /**+ * Create an instruction to indicate a decode error+ *+ * <p>+ * The resulting instruction will produce a single {@link DecodeErrorPcodeOp}. The translator+ * will generate code that throws a {@link DecodePcodeExecutionException} should execution reach+ * it.+ *+ * @param language the emulation target language+ * @param address the address where decode was attempted+ * @param ctx the input decode context+ * @param message a message for the {@link DecodePcodeExecutionException}+ * @return the new "instruction"+ */+ public static DecodeErrorInstruction decodeError(Language language, Address address,+ RegisterValue ctx, String message) {+ try {+ return new DecodeErrorInstruction(language, address, ctx, message);+ }+ catch (AddressOverflowException e) {+ throw new AssertionError(e);+ }+ }++ private final List<Instruction> instructions;+ private final AddrCtx entry;+ private final PcodeUseropLibrary<Object> decodeLibrary;+ private final Map<PcodeOp, Branch> branches;+ private final Map<PcodeOp, AddrCtx> entries;+ private final Register contextreg;+ private final ProgramContextImpl defaultContext;++ /**+ * Construct a new passage+ *+ * @param language the translation source language, i.e., the emulation target language. See+ * {@link #getLanguage()}+ * @param entry see {@link #getEntry()}+ * @param code the p-code ops, grouped by stride. Within each stride, they are ordered as+ * decoded and produced by their instructions. The strides are sorted by seed, with+ * precedence to the decode context value. See {@link #getInstructions()}. See+ * {@link #getCode()}.+ * @param decodeLibrary see {@link #getDecodeLibrary()}+ * @param instructions see {@link #getInstructions()}+ * @param branches see {@link #getBranches()}+ * @param entries see {@link #getOpEntry(PcodeOp)}+ */+ public JitPassage(SleighLanguage language, AddrCtx entry, List<PcodeOp> code,+ PcodeUseropLibrary<Object> decodeLibrary, List<Instruction> instructions,+ Map<PcodeOp, Branch> branches, Map<PcodeOp, AddrCtx> entries) {+ super(language, code, decodeLibrary.getSymbols(language));+ this.entry = entry;+ this.decodeLibrary = decodeLibrary;+ this.instructions = instructions;+ this.branches = branches;+ this.entries = entries;++ this.contextreg = language.getContextBaseRegister();++ if (contextreg != Register.NO_CONTEXT) {+ defaultContext = new ProgramContextImpl(language);+ language.applyContextSettings(defaultContext);+ }+ else {+ defaultContext = null;+ }+ }++ /**+ * Get all of the instructions in the passage.+ *+ * <p>+ * These are grouped by stride. Within each stride, the instructions are listed in decode order.+ * The strides are ordered by seed address-context pair, with context value taking precedence.+ *+ * @return the list of instructions+ */+ public List<Instruction> getInstructions() {+ return instructions;+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Conventionally, the first instruction of the program is the entry. Note this might+ * <em>not</em> be the initial seed. If the decoded passage contains a branch to an address+ * preceding the seed, and a stride results from it, then that stride's p-code will occur+ * earlier in the list. This is not a problem. The code generator will export many entry points,+ * and the seed must be among them. "Entering" at that seed is achieved using a switch table at+ * the start of the generated bytecode.+ */+ @Override+ public List<PcodeOp> getCode() {+ return super.getCode();+ }++ /**+ * Get the initial seed of this passage.+ *+ * <p>+ * This is informational only. It should be used in naming things and/or in diagnostics.+ *+ * @return the address-context pair+ */+ public AddrCtx getEntry() {+ return entry;+ }++ /**+ * Get the userop library that was used during decode of the passage+ *+ * <p>+ * This often wraps the emulator's userop library. Downstream components, namely the+ * {@link JitDataFlowModel}, will need this when translating {@link PcodeOp#CALLOTHER calls} to+ * userops.+ *+ * @return the library+ */+ public PcodeUseropLibrary<Object> getDecodeLibrary() {+ return decodeLibrary;+ }++ /**+ * Get all of the (non-fall-through) branches in the passage+ *+ * @return the branches, keyed by {@link Branch#from()}.+ */+ public Map<PcodeOp, Branch> getBranches() {+ return branches;+ }++ @Override+ public String toString() {+ return "<" + getClass().getSimpleName() + ":\n " + instructions.stream().map(i -> {+ return "(" + getInCtx(i) + ") " + i.getAddressString(false, true) + " " + i.toString();+ }).collect(Collectors.joining("\n ")) + "\n>\n" + format(true);+ }++ /**+ * Check if a given p-code op is the first of an instruction.+ *+ * <p>+ * <b>NOTE</b>: If an instruction is at an address with an inject, then the first op produced by+ * the inject is considered the "entry" to the instruction. This is to ensure that any control+ * flow to the injected address executes the injected code, not just the instruction's code.+ *+ * @param op the op to check.+ * @return the address-context pair that generated the op, if it is the first there, or+ * {@code null}+ */+ public AddrCtx getOpEntry(PcodeOp op) {+ return entries.get(op);+ }++ /**+ * If the given p-code op is known to cause an error, e.g., an unimplemented instruction, get+ * the error message.+ *+ * @param op the p-code op causing the error+ * @return the message for the error caused+ */+ public String getErrorMessage(PcodeOp op) {+ Branch branch = branches.get(op);+ return switch (branch) {+ case null -> throw new AssertionError("No branch record for op: " + op);+ case ErrBranch err -> err.message;+ default -> throw new AssertionError("Wrong branch type " + branch + " for op: " + op);+ };+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPcodeEmulator.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPcodeEmulator.javanew file mode 100644index 0000000000..a82c84bf86--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPcodeEmulator.java@@ -0,0 +1,413 @@+/* ###+ * 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.pcode.emu.jit;++import java.lang.invoke.MethodHandles.Lookup;+import java.util.HashMap;+import java.util.Map;+import java.util.Map.Entry;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.ExecutionException;++import org.apache.commons.lang3.exception.ExceptionUtils;+import org.objectweb.asm.MethodTooLargeException;++import ghidra.pcode.emu.PcodeEmulator;+import ghidra.pcode.emu.PcodeThread;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.analysis.JitDataFlowModel;+import ghidra.pcode.emu.jit.analysis.JitDataFlowUseropLibrary;+import ghidra.pcode.emu.jit.decode.JitPassageDecoder;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPointPrototype;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassageClass;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.*;+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;+import ghidra.program.model.address.AddressRange;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Language;+import ghidra.program.model.pcode.Varnode;+import ghidra.util.Msg;++/**+ * An extension of {@link PcodeEmulator} that applies Just-in-Time (JIT) translation to accelerate+ * execution.+ *+ * <p>+ * This is meant as a near drop-in replacement for the class it extends. Aside from some additional+ * configuration, and some annotations you might add to a {@link PcodeUseropLibrary}, if applicable,+ * you can simply replace {@code new PcodeEmulator()} with {@code new JitPcodeEmulator(...)}.+ *+ * <h1>A JIT-Accelerated P-code Emulator for the Java Virtual Machine</h1>+ *+ * <p>+ * There are two major tasks to achieving JIT-accelerated p-code emulation: 1) The translation of+ * p-code to a suitable target's machine language, and 2) The selection, decoding, and cache+ * management of passages of machine code translations. For our purposes, the target language is JVM+ * bytecode, which introduces some restrictions which make the translation process substantially+ * different than targeting native machine language.+ *+ * <h2>Terminology</h2>+ *+ * <p>+ * Because of the potential for confusion of terms with similar meanings from similar disciplines,+ * and to distinguish our particular use of the terms, we establish some definitions up front:+ *+ * <ul>+ *+ * <li><b>Basic block</b>: A block of <em>p-code</em> ops for which there are no branches into or+ * from, except at its top and bottom. Note that this definition pertains only to p-code ops in the+ * same passage. Branches into a block from ops generated elsewhere in the translation source need+ * not be considered. Note also that p-code basic blocks might not coincide with machine-code basic+ * blocks.</li>+ *+ * <li><b>Bytecode</b>: Shorthand for "JVM bytecode." Others sometimes use this to mean any machine+ * code, but for us "bytecode" only refers to the JVM's machine code.</li>+ *+ * <li><b>Decode context</b>: The input contextreg value for decoding an instruction. This is often+ * paired with an address to seed passages, identify an instruction's "location," and identify an+ * entry point.</li>+ *+ * <li><b>Emulation host</b>: The machine or environment on which the emulation target is being+ * hosted. This is usually also the <b>translation target</b>. For our purposes, this is the JVM,+ * often the same JVM executing Ghidra.</li>+ *+ * <li><b>Emulation target</b>: The machine being emulated. As opposed to the <b>translation+ * target</b> or <b>emulation host</b>. While this can include many aspects of a target platform, we+ * often just mean the Instruction Set Architecture (ISA, or <b>language</b>) of the machine.</li>+ *+ * <li><b>Entry point</b>: An address (and contextreg value) by which execution may enter a passage.+ * In addition to the decode seed, the translator may expose many entries into a given passage,+ * usually at branch targets or the start of each basic block coinciding with an instruction.</li>+ *+ * <li><b>Instruction</b>: A single machine-code instruction.</li>+ *+ * <li><b>Machine code</b>: The sequence of bytes and/or decoded instructions executed by a+ * machine.</li>+ *+ * <li><b>Passage</b>: A collection of strides connected by branches. Often each stride begins at+ * the target of some branch in another stride.</li>+ *+ * <li><b>P-code</b>: An intermediate representation used by Ghidra in much of its analysis and+ * execution modeling. For our purposes, we mean "low p-code," which is the common language into+ * which the source machine code is translated before final translation to bytecode.</li>+ *+ * <li><b>P-code op</b>: A single p-code operation. A single instruction usually generates several+ * p-code ops.</li>+ *+ * <li><b>Stride</b>: A contiguous sequence of instructions (and their emitted p-code) connected by+ * fall-through. Note that conditional branches may appear in the middle of the stride. So long as+ * fall-through is possible, the stride may continue.</li>+ *+ * <li><b>Translation source</b>: The machine code of the <b>emulation target</b> that is being+ * translated and subsequently executed by the <b>emulation host</b>.</li>+ *+ * <li><b>Translation target</b>: The target of the JIT translation, usually the <b>emulation+ * host</b>. For our purposes, this is always JVM bytecode.</li>+ *+ * <li><b>Varnode</b>: The triple (space,offset,size) giving the address and size of a variable in+ * the emulation target's machine state. This is distinct from a variable node (see {@link JitVal})+ * in the {@link JitDataFlowModel use-def} graph. The name "{@link Varnode}" is an unfortunate+ * inheritance from the Ghidra API, where they <em>can</em> represent genuine variable nodes in the+ * "high p-code" returned by the decompiler. However, the emulator consumes the "low p-code" where+ * varnodes are mere triples, which is how we use the term.</li>+ *+ * </ul>+ *+ * <h2>Just-in-Time Translation</h2>+ * <p>+ * For details of the translation process, see {@link JitCompiler}.+ *+ * <h2>Translation Cache</h2>+ * <p>+ * This class, aside from overriding and replacing the state and thread objects with respective+ * extensions, manages a part of the translation cache. For reasons discussed in the translation+ * section, there are two levels of caching. Once a passage is translated into a classfile, it must+ * be loaded as a class and then instantiated for the thread executing it. Thus, at the machine (or+ * emulator) level, each translated passage's class is cached. Then, each thread caches its instance+ * of that class. When a thread encounters an address (and contextreg value) that it has not yet+ * translated, it requests that the emulator perform that translation. The details of this check are+ * described in {@link #getEntryPrototype(AddrCtx, JitPassageDecoder)} and+ * {@link JitPcodeThread#getEntry(AddrCtx)}.+ */+public class JitPcodeEmulator extends PcodeEmulator {++ /**+ * The compiler which translates passages into JVM classes+ */+ protected final JitCompiler compiler;+ /**+ * A lookup to access non-public things+ */+ private final Lookup lookup;++ /**+ * This emulator's cache of passage translations, incl. all entry points.+ *+ * <p>+ * TODO: Invalidation of entries. One possible complication is any thread may still have an+ * instance of one, and could possibly be executing it. Perhaps this could be a weak hash map,+ * and they'll stay alive by virtue of the instances pointing to their classes? Still, we might+ * like to impose a total size max, which would have to be implemented among the threads. Other+ * reasons we may need to invalidate include:+ *+ * <ol>+ * <li>Self-modifying code (we'll probably want to provide a configuration toggle given how+ * expensive that may become).</li>+ * <li>Changes to the memory map. At the moment, however, the p-code emulator does not provide a+ * memory management unit (MMU).</li>+ * <li>Addition of a new inject by the user or script. This one's actually pretty likely. For+ * now, we might just document that injects should not be changes once execution starts.</li>+ * </ol>+ */+ protected final Map<AddrCtx, CompletableFuture<EntryPointPrototype>> codeCache =+ new HashMap<>();++ /**+ * Create a JIT-accelerated p-code emulator+ *+ * @param language the emulation target langauge+ * @param config configuration options for this emulator+ * @param lookup a lookup in case the emulator (or its target) needs access to non-public+ * elements, e.g., to access a nested {@link PcodeUseropLibrary}.+ */+ public JitPcodeEmulator(Language language, JitConfiguration config, Lookup lookup) {+ super(language);+ this.compiler = new JitCompiler(config);+ this.lookup = lookup;+ }++ @Override+ protected PcodeExecutorState<byte[]> createSharedState() {+ return new JitDefaultBytesPcodeExecutorState(language);+ }++ @Override+ protected PcodeExecutorState<byte[]> createLocalState(PcodeThread<byte[]> thread) {+ return new JitDefaultBytesPcodeExecutorState(language);+ }++ @Override+ protected JitPcodeThread createThread(String name) {+ return new JitPcodeThread(name, this);+ }++ @Override+ public JitPcodeThread newThread() {+ return (JitPcodeThread) super.newThread();+ }++ @Override+ public JitPcodeThread newThread(String name) {+ return (JitPcodeThread) super.newThread(name);+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Userops can be optimized by the JIT translator under certain circumstances. To read more, see+ * {@link JitDataFlowUseropLibrary}. DO NOT extend that library. The internals use it to wrap+ * the library you provide here, but its documentation describes when and how the JIT translator+ * optimizes invocations to your userops.+ *+ * <p>+ * <b>WARNING</b>: Userops that accept floating point types via direct invocation should be+ * careful that the sizes match exactly. That is, if you pass a {@code float} argument to a+ * {@code double} parameter, you may have problems. This <em>does not</em> imply a conversion of+ * floating point type. Instead, it will simply zero-fill the upper bits (as if zero-exending an+ * integer) and reinterpret the resulting bits as a double. This is almost certainly+ * <em>not</em> what you want. Until/unless we resolve this, the userop implementor must accept+ * the proper types. It's possible multiple versions of the userop must be provided (overloading+ * is not supported) to accept types of various sizes.+ */+ @Override+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {+ return super.createUseropLibrary();+ }++ /**+ * Check if the emulator already has translated a given entry point.+ *+ * <p>+ * This is used by the decoder to detect if it should end a stride before reaching its natural+ * end (i.e., a non-fall-through instruction.) This was a design decision to reduce+ * re-translation of the same machine code. Terminating the stride will cause execution to exit+ * the translated passage, but it will then immediately enter the existing translated passage.+ *+ * @param pcCtx the program counter and contextreg value to check+ * @return true if the emulator has a translation which can be entered at the given pcCtx.+ */+ public boolean hasEntryPrototype(AddrCtx pcCtx) {+ /**+ * TODO: Investigate ignoring synchronization and instead catching the CME. This would be to+ * avoid locking on every instruction decode. If we thing there's no an entry, and there+ * turns out we just won a race, it's little loss.+ *+ * I don't think in the grand scheme of things, this is the most expensive operation of the+ * translation. Nevertheless, it'll be hit a lot, so worth investigating.+ */+ synchronized (codeCache) {+ CompletableFuture<EntryPointPrototype> proto = codeCache.get(pcCtx);+ return proto != null && proto.isDone();+ }+ }++ /**+ * Translate a new passage starting at the given seed.+ *+ * <p>+ * Note the compiler must provide an entry to the resulting passage at the requested seed. It+ * and any additional entry points are placed into the code cache. Each thread executing the+ * passage must still create (and ought to cache) an instance of the translation.+ *+ * @param pcCtx the seed address and contextreg value for decoding and selecting a passage+ * @param decoder the passage decoder, provided by the thread+ * @return the class that is the translation of the passage, and information about its entry+ * points.+ */+ protected JitCompiledPassageClass compileWithMaxOpsBackoff(AddrCtx pcCtx,+ JitPassageDecoder decoder) {+ int maxOps = getConfiguration().maxPassageOps();+ while (maxOps > 0) {+ JitPassage decoded = decoder.decodePassage(pcCtx, maxOps);+ try {+ return compiler.compilePassage(lookup, decoded);+ }+ catch (MethodTooLargeException e) {+ Msg.warn(this, "Method too large for " + pcCtx + " with maxOps=" + maxOps ++ ". Retrying with half.");+ maxOps >>= 1;+ }+ }+ /**+ * This would be caused by an exceptionally large stride, perhaps with a good bit of+ * instrumentation.+ *+ * TODO: If this happens, we'll need to be willing to stop decoding mid-stride. I think it's+ * easily doable, as we already do this when we hit an address with an existing entry point.+ *+ * NOTE: We still need to treat each instruction, along with any instrumentation on it, as+ * an atomic unit. I can't imagine a single instruction maxing out the Java method size,+ * though.+ */+ throw new AssertionError();+ }++ /**+ * Get the entry prototype for a given address and contextreg value.+ *+ * <p>+ * An <b>entry prototype</b> is a class representing a translated passage and an index+ * identifying the point at which to enter the passage. The compiler numbers each entry point it+ * generates and provides those indices via a static field in the output class. Those entry+ * point indices are entered into the code cache for each translated passage. If no entry point+ * exists for the requested address and contextreg value, the emulator will decode and translate+ * a new passage at the requested seed.+ *+ * <p>+ * It's a bit odd to take the thread's decoder for a machine-level thing; however, all thread+ * decoders ought to have the same behavior. The particular thread's decoder will have better+ * cached instruction block state for decoding in the vicinity of its past execution, though.+ *+ * @param pcCtx the counter and decoder context+ * @param decoder the thread's decoder needing this entry point prototype+ * @return the entry point prototype+ * @see JitPcodeThread#getEntry(AddrCtx)+ */+ public EntryPointPrototype getEntryPrototype(AddrCtx pcCtx, JitPassageDecoder decoder) {+ /**+ * NOTE: It is possible for a race condition, still, if (very likely) the passage provides+ * multiple entry points. It's not ideal, but still correct, I think, if this happens.+ */+ CompletableFuture<EntryPointPrototype> proto;+ boolean wasAbsent;+ synchronized (codeCache) {+ proto = codeCache.get(pcCtx);+ wasAbsent = proto == null;+ if (wasAbsent) {+ proto = new CompletableFuture<>();+ codeCache.put(pcCtx, proto);+ // Won't know to put other entry points, yet+ }+ }+ /**+ * TODO: I'm not sure it makes sense to do this computation without the lock.+ *+ * On the one hand, it allows threads to avoid stalling on every translation, and instead+ * only on translations for the same entry point. However, if we do keep the lock, then we+ * can avoid the race condition on alternative entry points.+ */++ if (wasAbsent) {+ /**+ * Go ahead and use this thread instead of spawning another, because this one can't+ * proceed until compilation is completed, anyway.+ */+ try {+ JitCompiledPassageClass compiled = compileWithMaxOpsBackoff(pcCtx, decoder);+ synchronized (codeCache) {+ for (Entry<AddrCtx, EntryPointPrototype> ent : compiled.getBlockEntries()+ .entrySet()) {+ if (ent.getKey().equals(pcCtx)) {+ proto.complete(ent.getValue());+ }+ else {+ codeCache.put(ent.getKey(),+ CompletableFuture.completedFuture(ent.getValue()));+ }+ }+ }+ }+ catch (Throwable t) {+ proto.completeExceptionally(t);+ }+ }+ try {+ return proto.get();+ }+ catch (InterruptedException e) {+ throw new AssertionError(e);+ }+ catch (ExecutionException e) {+ return ExceptionUtils.rethrow(e);+ }+ }++ /**+ * Get the configuration for this emulator.+ *+ * @return the configuration+ */+ public JitConfiguration getConfiguration() {+ return compiler.getConfiguration();+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * <b>TODO</b>: The JIT-accelerated emulator does not currently implement access breakpoints.+ * Furthermore, because JIT generated code is granted direct access to the emulator's state+ * internals, it is not sufficient to override+ * {@link PcodeExecutorStatePiece#getVar(AddressSpace, Object, int, boolean, Reason) getVar} and+ * related.+ */+ @Override+ public void addAccessBreakpoint(AddressRange range, AccessKind kind) {+ throw new UnsupportedOperationException();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPcodeThread.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPcodeThread.javanew file mode 100644index 0000000000..5bad5458bf--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitPcodeThread.java@@ -0,0 +1,278 @@+/* ###+ * 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.pcode.emu.jit;++import java.util.HashMap;+import java.util.Map;++import ghidra.lifecycle.Internal;+import ghidra.pcode.emu.*;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.decode.JitPassageDecoder;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPointPrototype;+import ghidra.pcode.exec.*;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.ProgramContext;++/**+ * A JIT-accelerated thread of p-code emulation+ *+ * <p>+ * This class implements the actual JIT-accelerated execution loop. In contrast to the normal+ * per-instruction Fetch-Execute-Store loop inherited from {@link DefaultPcodeThread}, this thread's+ * {@link #run()} method implements a per-<em>passage</em> Fetch-Decode-Translate-Execute loop.+ *+ *+ * <h2>Fetch</h2>+ * <p>+ * The Fetch step involves checking the code cache for an existing translation at the thread's+ * current counter and decode context. Cache entries are keyed by <em>passage entry point</em>, that+ * is an address (and context reg value, if applicable) within a passage where execution is+ * permitted to enter. This typically consists of the passage's seed as well as each branch target+ * in the same passage. If one is found, we skip the Decode and Translate steps, and proceed+ * directly to Execute.+ *+ * <h2>Decode</h2>+ * <p>+ * The Decode step involves decoding and selecting several instructions into a <em>passage</em>. A+ * passage may comprise of several instructions connected by control flow. Often it is a few long+ * strides of instructions connected by a few branches. The decoder will avoid selecting+ * instructions that are already included in an existing translated passage. The reason for this+ * complexity is that JVM bytecode cannot be rewritten or patched once loaded. For more details, see+ * {@link JitPassageDecoder}.+ *+ * <h2>Translate</h2>+ * <p>+ * The Translate step involves translating the selected passage of instructions. The result of this+ * translation implements {@link JitCompiledPassage}. For details of this translation process, see+ * {@link JitCompiler}. The compiled passage provides a list of its entry points. Each is added to+ * the emulator's code cache. Among those should be the seed required by this iteration of the+ * execution loop, and so that entry point is chosen.+ *+ * <h2>Execute</h2>+ * <p>+ * The chosen entry point is then executed. This step is as simple as invoking the+ * {@link EntryPoint#run()} method. This, in turn, invokes {@link JitCompiledPassage#run(int)},+ * providing the entry point's index as an argument. The index identifies to the translated passage+ * the desired address of entry, and so it jumps directly to the corresponding translation. That+ * translation performs all the equivalent operations of the selected instructions, adhering to any+ * control flow within. When control flow exits the passage, the method returns, and the loop+ * repeats.+ */+public class JitPcodeThread extends BytesPcodeThread {+ /**+ * This thread's passage decoder, which is based on its {@link #getDecoder() instruction+ * decoder}.+ */+ protected final JitPassageDecoder passageDecoder;++ /**+ * This thread's cache of translations instantiated for this thread.+ *+ * <p>+ * As an optimization, the translator generates classes which pre-fetch portions of the thread's+ * state. Thus, the class must be instantiated for each particular thread needing to execute it.+ *+ * <p>+ * TODO: Invalidation of entries. There are several reasons an entry may need to be invalidated:+ * Expiration, eviction, or perhaps because the {@link EntryPointPrototype} (from the emulator)+ * was invalidated.+ */+ protected final Map<AddrCtx, EntryPoint> codeCache = new HashMap<>();++ /**+ * Create a thread+ *+ * <p>+ * This should only be called by the emulator and its test suites.+ *+ * @param name the name of the thread+ * @param machine the machine creating the thread+ */+ public JitPcodeThread(String name, JitPcodeEmulator machine) {+ super(name, machine);+ this.passageDecoder = createPassageDecoder();+ }++ @Override+ protected ThreadPcodeExecutorState<byte[]> createThreadState(+ PcodeExecutorState<byte[]> sharedState, PcodeExecutorState<byte[]> localState) {+ return new JitThreadBytesPcodeExecutorState((JitDefaultBytesPcodeExecutorState) sharedState,+ (JitDefaultBytesPcodeExecutorState) localState);+ }++ /**+ * Create the passage decoder+ *+ * <p>+ * This is an extension point in case the decoder needs to be replaced with a further extension.+ *+ * @return the new passage decoder+ */+ protected JitPassageDecoder createPassageDecoder() {+ return new JitPassageDecoder(this);+ }++ @Override+ public JitPcodeEmulator getMachine() {+ return (JitPcodeEmulator) super.getMachine();+ }++ @Override+ public JitThreadBytesPcodeExecutorState getState() {+ return (JitThreadBytesPcodeExecutorState) super.getState();+ }++ @Internal+ @Override+ public PcodeProgram getInject(Address address) {+ return super.getInject(address);+ }++ /**+ * An accessor so the passage decoder can retrieve its thread's instruction decoder.+ *+ * @return the decoder+ */+ @Internal+ public InstructionDecoder getDecoder() {+ return decoder;+ }++ /**+ * An accessor so the passage decoder can query the language's default program context.+ *+ * @return the context+ */+ @Internal+ public ProgramContext getDefaultContext() {+ return defaultContext;+ }++ @Override+ public void inject(Address address, String source) {+ /**+ * TODO: Flush code cache? Alternatively, establish some convention where injects cannot be+ * changed in the life cycle? I don't like that solution. It is workable, I think, though,+ * but the user would have to add state to a library in order to configure/toggle each+ * injection.+ *+ * Is it enough to identify which passages contain the address and just remove those? I+ * think, so. The only nuance I can think of is that the inject may change the block+ * structure, i.e., new entries are possible, but I don't think that matters terribly. The+ * caching algorithm should work that out.+ */+ super.inject(address, source);+ }++ /**+ * Check if the <em>emulator</em> has an entry prototype for the given address and contextreg+ * value.+ *+ * <p>+ * This simply passes through to the emulator. It does not matter whether or not this thread has+ * instantiated the prototype or not. If any thread has caused the emulator to translate the+ * given entry, this will return true.+ *+ * @see JitPcodeEmulator#hasEntryPrototype(AddrCtx)+ * @param pcCtx the address and contextreg to check+ * @return true if the emulator has a translation which can be entered at the given pcCtx.+ */+ public boolean hasEntry(AddrCtx pcCtx) {+ return getMachine().hasEntryPrototype(pcCtx);+ }++ /**+ * Get the translated and instantiated entry point for the given address and contextreg value.+ *+ * <p>+ * An <b>entry point</b> is an instance of a class representing a translated passage and an+ * index identifying the point at which to enter the passage. In essence, it is an instance of+ * an <b>entry prototype</b> for this thread.+ *+ * <p>+ * This will first check the cache for an existing instance. Then, it will delegate to the+ * emulator. The emulator will check its cache for an existing translation. If one is found, we+ * simply take it and instantiate it for this thread. Otherwise, the emulator translates a new+ * passage at the given seed, and we instantiate it for this thread.+ *+ * @see JitPcodeEmulator#getEntryPrototype(AddrCtx, JitPassageDecoder)+ * @param pcCtx the counter and decoder context+ * @return the entry point+ */+ public EntryPoint getEntry(AddrCtx pcCtx) {+ /**+ * NOTE: Placeholders are not needed at the thread level, but at the machine level.+ */+ return codeCache.computeIfAbsent(pcCtx,+ k -> getMachine().getEntryPrototype(k, passageDecoder).createInstance(this));+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * We override only this method to accelerate execution using JIT translation. Implementing+ * single stepping via JIT doesn't make much sense from an efficiency standpoint. However, this+ * thread still supports stepping via interpretation (as inherited). Our implementation permits+ * mixing the two execution paradigms; however, using JIT after a few single steps will incur+ * some waste as the JIT translates an otherwise uncommon entry point. Depending on+ * circumstances and the order of operations, the effect of this on overall efficiency may vary+ * because of caching.+ */+ @Override+ public void run() {+ setSuspended(false);+ if (frame != null) {+ finishInstruction();+ }+ EntryPoint next = null;+ while (!isSuspended()) {+ if (next == null) {+ next = getEntry(new AddrCtx(getContext(), getCounter()));+ }+ try {+ next = next.run();+ }+ catch (SuspendedPcodeExecutionException e) {+ // Cool.+ }+ }+ }++ /**+ * This is called before each basic block is executed.+ *+ * <p>+ * This gives the thread an opportunity to track and control execution, if desired. It provides+ * the number of instructions and additional p-code ops about to be completed. If the counts+ * exceed a desired schedule, or if the thread is suspended, this method may throw an exception+ * to interrupt execution. This can be toggled in the emulator's configuration.+ *+ * @see JitConfiguration#emitCounters()+ * @param instructions the number of instruction about to be completed+ * @param trailingOps the number of ops of a final partial instruction about to be completed. If+ * the block does not complete any instruction, this is the number of ops continuing+ * in the current (partial) instruction.+ */+ public void count(int instructions, int trailingOps) {+ if (isSuspended()) {+ throw new SuspendedPcodeExecutionException(null, null);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitThreadBytesPcodeExecutorState.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitThreadBytesPcodeExecutorState.javanew file mode 100644index 0000000000..603cc057f5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/JitThreadBytesPcodeExecutorState.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.pcode.emu.jit;++import ghidra.pcode.emu.ThreadPcodeExecutorState;+import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.program.model.address.AddressSpace;++/**+ * The equivalent to {@link ThreadPcodeExecutorState} that multiplexes shared and local state for+ * the JIT-accelerated p-code emulator+ */+public class JitThreadBytesPcodeExecutorState extends ThreadPcodeExecutorState<byte[]>+ implements JitBytesPcodeExecutorState {++ /**+ * Construct a new thread state+ *+ * @param sharedState the shared portion (e.g., ram space)+ * @param localState the local portion (i.e., register, unique spaces)+ */+ public JitThreadBytesPcodeExecutorState(JitDefaultBytesPcodeExecutorState sharedState,+ JitDefaultBytesPcodeExecutorState localState) {+ super(sharedState, localState);+ }++ @Override+ public JitDefaultBytesPcodeExecutorState getSharedState() {+ return (JitDefaultBytesPcodeExecutorState) super.getSharedState();+ }++ @Override+ public JitDefaultBytesPcodeExecutorState getLocalState() {+ return (JitDefaultBytesPcodeExecutorState) super.getLocalState();+ }++ @Override+ public JitBytesPcodeExecutorStateSpace getForSpace(AddressSpace space) {+ if (isThreadLocalSpace(space)) {+ return getLocalState().getForSpace(space);+ }+ return getSharedState().getForSpace(space);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitAllocationModel.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitAllocationModel.javanew file mode 100644index 0000000000..68540bd57e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitAllocationModel.java@@ -0,0 +1,944 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import static ghidra.pcode.emu.jit.analysis.JitVarScopeModel.maxAddr;+import static ghidra.pcode.emu.jit.analysis.JitVarScopeModel.overlapsLeft;+import static org.objectweb.asm.Opcodes.*;++import java.math.BigInteger;+import java.util.*;+import java.util.Map.Entry;++import org.apache.commons.collections4.iterators.ReverseListIterator;+import org.objectweb.asm.*;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.JitCompiler;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.gen.var.VarGen;+import ghidra.pcode.emu.jit.var.*;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressFactory;+import ghidra.program.model.lang.Endian;+import ghidra.program.model.pcode.Varnode;++/**+ * Type variable allocation phase for JIT-accelerated emulation.+ *+ * <p>+ * The implements the Variable Allocation phase of the {@link JitCompiler} using a very simple+ * placement and another "voting" algorithm to decide the allocated JVM variable types. We place/map+ * variables by their storage varnodes, coalescing them as needed. Coalescing is performed for+ * overlapping, but not abutting varnodes. This allocation is anticipated by the+ * {@link JitVarScopeModel}, which performs the actual coalescing. Because multiple SSA variables+ * will almost certainly occupy the same varnode, we employ another voting system. For example, the+ * register {@code RAX} may be re-used many times within a passage. In some cases, it might be used+ * to return a floating-point value. In others (and <em>probably</em> more commonly) it will be used+ * to return an integral value. The more common case in the passage determines the JVM type of the+ * local variable allocated for {@code RAX}. Note that variables which occupy only part of a+ * coalesced varnode always vote for a JVM {@code int}, because of the shifting and masking required+ * to extract that part.+ *+ * <p>+ * The allocation process is very simple, presuming successful type assignment:+ *+ * <ol>+ * <li>Vote Tabulation</li>+ * <li>Index Reservation</li>+ * <li>Handler Creation</li>+ * </ol>+ *+ * <h2>Vote Tabulation</h2>+ * <p>+ * Every SSA variable (excluding constants and memory variables) contributes a vote for the type of+ * its allocated local. If the varnode matches exactly, the vote is for the JVM type of the+ * variable's assigned p-code type. The type mapping is simple: For integral types, we allocate+ * using the smaller JVM type that fits the p-code type. For floating-point types, we allocate using+ * the JVM type that exactly matches the p-code type. If the varnode is larger, i.e., because it's+ * the result of coalescing, then the vote is for the smaller JVM integer type that fits the full+ * varnode. Consider the following p-code:+ *+ * <pre>+ * 1. RAX = FLOAT_ADD RCX, RDX+ * 2. EAX = FLOAT_ADD EBX, 0x3f800000:4 # 1.0f+ * </pre>+ *+ * <p>+ * Several values and variables are at play here. We tabulate the type assignments and resulting+ * votes:+ *+ * <p>+ * <table border="1">+ * <tr>+ * <th>SSA Var</th>+ * <th>Type</th>+ * <th>Varnode</th>+ * <th>Vote</th>+ * </tr>+ * <tr>+ * <td>{@code RCX}<sub>in</sub></td>+ * <td>{@link DoubleJitType#F8 float8}</td>+ * <td>{@code RCX}</td>+ * <td>{@code double}</td>+ * </tr>+ * <tr>+ * <td>{@code RDX}<sub>in</sub></td>+ * <td>{@link DoubleJitType#F8 float8}</td>+ * <td>{@code RDX}</td>+ * <td>{@code double}</td>+ * </tr>+ * <tr>+ * <td>{@code RAX}<sub>1</sub></td>+ * <td>{@link DoubleJitType#F8 float8}</td>+ * <td>{@code RAX}</td>+ * <td>{@code double}</td>+ * </tr>+ * <tr>+ * <td>{@code EBX}<sub>in</sub></td>+ * <td>{@link FloatJitType#F4 float4}</td>+ * <td>{@code EBX}</td>+ * <td>{@code float}</td>+ * </tr>+ * <tr>+ * <td>{@code 0x3f800000:4}</td>+ * <td>{@link FloatJitType#F4 float4}</td>+ * </tr>+ * <tr>+ * <td>{@code EAX}<sub>2</sub></td>+ * <td>{@link FloatJitType#F4 float4}</td>+ * <td>{@code RAX}</td>+ * <td>{@code long}</td>+ * </tr>+ * </table>+ *+ * <p>+ * The registers {@code RCX}, {@code RDX}, and {@code EBX} are trivially allocated as locals of JVM+ * types {@code double}, {@code double}, and {@code float}, respectively. It is also worth noting+ * that {@code 0x3f800000} is allocated as a {@code float} constant in the classfile's constant+ * pool. Now, we consider {@code RAX}. The varnodes for {@code RAX}<sub>1</sub> and+ * {@code EAX}<sub>2</sub> are coalesced to {@code RAX}. {@code RAX}<sub>1</sub> casts its vote for+ * {@code double}; whereas, {@code EAX}<sub>2</sub> casts its vote for {@code long}. This is because+ * placing {@code EAX}<sub>2</sub>'s value into the larger varnode requires bitwise operators, which+ * on the JVM, require integer operands. Thus the votes result in a tie, and favoring integral+ * types, we allocate {@code RAX} in a JVM {@code long}.+ *+ * <h2>Index Reservation</h2>+ * <p>+ * After all the votes have been tabulated, we go through the results in address order, reserving+ * JVM local indices and assigning types. Note that we must reserve two indices for every variable+ * of type {@code long} or {@code double}, as specific by the JVM. Each of these reservations is+ * tracked in a {@link JvmLocal}. Note that index 0 is already reserved by the JVM for the+ * {@code this} ref, so we start our counting at 1. Also, some portions of the code generator may+ * need to allocate additional temporary locals, so we must allow access to the next free index+ * after all reservations are complete.+ *+ * <h2>Handler Creation</h2>+ * <p>+ * This actually extends a little beyond allocation, but this is a suitable place for it: All SSA+ * values are assigned a handler, including constants and memory variables. Variables which access+ * the same varnode get the same handler. For varnodes that are allocated in a JVM local, we create+ * a handler that generates loads and stores to that local, e.g., {@link Opcodes#ILOAD iload}. For+ * constant varnodes, we create a handler that generates {@link Opcodes#LDC ldc} instructions. For+ * memory varnodes, we create a handler that generates a sequence of method invocations on the+ * {@link JitBytesPcodeExecutorState state}. The code generator will delegate to these handlers in+ * order to generate reads and writes of the corresponding variables, as well as to prepare any+ * resources to facilitate access, e.g., pre-fetching items from the+ * {@link JitBytesPcodeExecutorState state} in the generated constructor.+ *+ * @implNote There are many artifacts below that anticipate supporting p-code types greater than 8+ * bytes in size. One method to support that is to allocate multiple JVM locals per p-code+ * varnode. Consider a 16-byte (128-bit) integer. We could allocate 4 JVM {@code int}+ * locals and then emit bytecode that performs the gradeschool-style arithmetic. I suspect+ * this would perform better than just using refs to {@link BigInteger}, because it avoids+ * heap pollution, and also may avoid some unnecessary arithmetic, esp., for the more+ * significant portions that get dropped.+ * @implNote <b>TODO</b>: It would be nice to detect varnode re-use under a different type and+ * generate the appropriate declarations and handlers. This doesn't seem terribly complex,+ * and it stands to spare us some casts. What's not clear is whether this offers any real+ * run-time benefit.+ */+public class JitAllocationModel {++ /**+ * An allocated JVM local+ *+ * @param index the index reserved for this local+ * @param name the human-readable name for this local+ * @param type a type for this local+ * @param vn the varnode whose value this local holds+ */+ public record JvmLocal(int index, String name, SimpleJitType type, Varnode vn) {++ /**+ * Emit bytecode into the class constructor.+ *+ * @param gen the code generator+ * @param iv the visitor for the class constructor+ */+ public void generateInitCode(JitCodeGenerator gen, MethodVisitor iv) {+ VarGen.generateValInitCode(gen, vn);+ }++ /**+ * Emit bytecode at the top of the {@link JitCompiledPassage#run(int) run} method.+ *+ * <p>+ * This will declare all of the allocated locals for the entirety of the method.+ *+ * @param gen the code generator+ * @param start a label at the top of the method+ * @param end a label at the end of the method+ * @param rv the visitor for the run method+ */+ public void generateDeclCode(JitCodeGenerator gen, Label start, Label end,+ MethodVisitor rv) {+ rv.visitLocalVariable(name, Type.getDescriptor(type.javaType()), null, start, end,+ index);+ }++ /**+ * Emit bytecode to load the varnode's value onto the JVM stack.+ *+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generateLoadCode(MethodVisitor rv) {+ rv.visitVarInsn(type.opcodeLoad(), index);+ }++ /**+ * Emit bytecode to store the value on the JVM stack into the varnode.+ *+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generateStoreCode(MethodVisitor rv) {+ rv.visitVarInsn(type.opcodeStore(), index);+ }++ /**+ * Emit bytecode to bring this varnode into scope.+ *+ * <p>+ * This will copy the value from the {@link JitBytesPcodeExecutorState state} into the local+ * variable.+ *+ * @param gen the code generator+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generateBirthCode(JitCodeGenerator gen, MethodVisitor rv) {+ VarGen.generateValReadCodeDirect(gen, type, vn, rv);+ generateStoreCode(rv);+ }++ /**+ * Emit bytecode to take this varnode out of scope.+ *+ * <p>+ * This will copy the value from the local variable into the+ * {@link JitBytesPcodeExecutorState state}.+ *+ * @param gen the code generator+ * @param rv the visitor for the {@link JitCompiledPassage#run(int)} method+ */+ public void generateRetireCode(JitCodeGenerator gen, MethodVisitor rv) {+ generateLoadCode(rv);+ VarGen.generateValWriteCodeDirect(gen, type, vn, rv);+ }+ }++ /**+ * A handler that knows how to load and store variable values onto and from the JVM stack.+ */+ public interface VarHandler {+ /**+ * Get the p-code type of the variable this handler handles.+ *+ * @return the type+ */+ JitType type();++ /**+ * Emit bytecode into the class constructor.+ *+ * @param gen the code generator+ * @param iv the visitor for the class constructor+ */+ void generateInitCode(JitCodeGenerator gen, MethodVisitor iv);++ /**+ * If needed, emit bytecode at the top of the {@link JitCompiledPassage#run(int) run}+ * method.+ *+ * @param gen the code generator+ * @param start a label at the top of the method+ * @param end a label at the end of the method+ * @param rv the visitor for the run method+ */+ void generateDeclCode(JitCodeGenerator gen, Label start, Label end, MethodVisitor rv);++ /**+ * Emit bytecode to load the varnode's value onto the JVM stack.+ *+ * @param gen the code generator+ * @param type the p-code type of the value expected on the JVM stack by the proceeding+ * bytecode+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ void generateLoadCode(JitCodeGenerator gen, JitType type, MethodVisitor rv);++ /**+ * Emit bytecode to load the varnode's value onto the JVM stack.+ *+ * @param gen the code generator+ * @param type the p-code type of the value produced on the JVM stack by the preceding+ * bytecode+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ void generateStoreCode(JitCodeGenerator gen, JitType type, MethodVisitor rv);+ }++ /**+ * A handler for p-code variables composed of a single JVM local variable.+ */+ public interface OneLocalVarHandler extends VarHandler {+ /**+ * Get the local variable into which this p-code variable is allocated+ *+ * @return the local+ */+ JvmLocal local();++ @Override+ default void generateInitCode(JitCodeGenerator gen, MethodVisitor iv) {+ // Generator inits decls directly+ }++ @Override+ default void generateDeclCode(JitCodeGenerator gen, Label start, Label end,+ MethodVisitor rv) {+ // Generator calls decls directly+ }++ @Override+ default void generateLoadCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ local().generateLoadCode(rv);+ TypeConversions.generate(gen, this.type(), type, rv);+ }++ @Override+ default void generateStoreCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ TypeConversions.generate(gen, type, this.type(), rv);+ local().generateStoreCode(rv);+ }+ }++ /**+ * The handler for a p-code variable allocated in one JVM {@code int}.+ *+ * @param local the JVM local+ * @param type the p-code type+ */+ public record IntVarAlloc(JvmLocal local, IntJitType type) implements OneLocalVarHandler {}++ /**+ * The handler for a p-code variable allocated in one JVM {@code long}.+ *+ * @param local the JVM local+ * @param type the p-code type+ */+ public record LongVarAlloc(JvmLocal local, LongJitType type) implements OneLocalVarHandler {}++ /**+ * The handler for a p-code variable allocated in one JVM {@code float}.+ *+ * @param local the JVM local+ * @param type the p-code type+ */+ public record FloatVarAlloc(JvmLocal local, FloatJitType type) implements OneLocalVarHandler {}++ /**+ * The handler for a p-code variable allocated in one JVM {@code double}.+ *+ * @param local the JVM local+ * @param type the p-code type+ */+ public record DoubleVarAlloc(JvmLocal local, DoubleJitType type)+ implements OneLocalVarHandler {}++ /**+ * A portion of a multi-local variable handler.+ *+ * <p>+ * This portion is allocated in a JVM local. When loading with a positive shift, the value is+ * shifted to the right to place it into position.+ *+ * @param local the local variable allocated to this part+ * @param shift the number of bytes and direction to shift+ */+ public record MultiLocalPart(JvmLocal local, int shift) {+ private JitType chooseLargerType(JitType t1, JitType t2) {+ return t1.size() > t2.size() ? t1 : t2;+ }++ /**+ * Emit bytecode to load the value from this local and position it in a value on the JVM+ * stack.+ *+ * <p>+ * If multiple parts are to be combined, the caller should emit a bitwise or after all loads+ * but the first.+ *+ * @param gen the code generator+ * @param type the p-code type of the value expected on the stack by the proceeding+ * bytecode, which may be to load additional parts+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ *+ * @implNote We must keep temporary values in a variable of the larger of the local's or the+ * expected type, otherwise bits may get dropped while positioning the value.+ */+ public void generateLoadCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ local.generateLoadCode(rv);+ JitType tempType = chooseLargerType(local.type, type);+ TypeConversions.generate(gen, local.type, tempType, rv);+ if (shift > 0) {+ switch (tempType) {+ case IntJitType t -> {+ rv.visitLdcInsn(shift * Byte.SIZE);+ rv.visitInsn(IUSHR);+ }+ case LongJitType t -> {+ rv.visitLdcInsn(shift * Byte.SIZE);+ rv.visitInsn(LUSHR);+ }+ default -> throw new AssertionError();+ }+ }+ else if (shift < 0) {+ switch (tempType) {+ case IntJitType t -> {+ rv.visitLdcInsn(-shift * Byte.SIZE);+ rv.visitInsn(ISHL);+ }+ case LongJitType t -> {+ rv.visitLdcInsn(-shift * Byte.SIZE);+ rv.visitInsn(LSHL);+ }+ default -> throw new AssertionError();+ }+ }+ TypeConversions.generate(gen, tempType, type, rv);+ }++ /**+ * Emit bytecode to extract this part from the value on the JVM stack and store it in the+ * local variable.+ *+ * <p>+ * If multiple parts are to be stored, the caller should emit a {@link Opcodes#DUP dup} or+ * {@link Opcodes#DUP2 dup2} before all stores but the last.+ *+ * @param gen the code generator+ * @param type the p-code type of the value expected on the stack by the proceeding+ * bytecode, which may be to load additional parts+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ *+ * @implNote We must keep temporary values in a variable of the larger of the local's or the+ * expected type, otherwise bits may get dropped while positioning the value.+ */+ public void generateStoreCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ JitType tempType = chooseLargerType(local.type, type);+ TypeConversions.generate(gen, type, tempType, rv);+ switch (tempType) {+ case IntJitType t -> {+ if (shift > 0) {+ rv.visitLdcInsn(shift * Byte.SIZE);+ rv.visitInsn(ISHL);+ }+ else if (shift < 0) {+ rv.visitLdcInsn(-shift * Byte.SIZE);+ rv.visitInsn(IUSHR);+ }+ }+ case LongJitType t -> {+ if (shift > 0) {+ rv.visitLdcInsn(shift * Byte.SIZE);+ rv.visitInsn(LSHL);+ }+ else if (shift < 0) {+ rv.visitLdcInsn(-shift * Byte.SIZE);+ rv.visitInsn(LUSHR);+ }+ }+ default -> throw new AssertionError();+ }+ TypeConversions.generate(gen, tempType, local.type, rv);+ switch (local.type) {+ case IntJitType t -> {+ int mask = -1 >>> (Integer.SIZE - Byte.SIZE * type.size());+ if (shift > 0) {+ mask <<= shift * Byte.SIZE;+ }+ else {+ mask >>>= -shift * Byte.SIZE;+ }+ rv.visitLdcInsn(mask);+ rv.visitInsn(IAND);+ local.generateLoadCode(rv);+ rv.visitLdcInsn(~mask);+ rv.visitInsn(IAND);+ rv.visitInsn(IOR);+ local.generateStoreCode(rv);+ }+ case LongJitType t -> {+ long mask = -1L >>> (Long.SIZE - Byte.SIZE * type.size());+ if (shift > 0) {+ mask <<= shift * Byte.SIZE;+ }+ else {+ mask >>>= -shift * Byte.SIZE;+ }+ rv.visitLdcInsn(mask);+ rv.visitInsn(LAND);+ local.generateLoadCode(rv);+ rv.visitLdcInsn(~mask);+ rv.visitInsn(LAND);+ rv.visitInsn(LOR);+ local.generateStoreCode(rv);+ }+ default -> throw new AssertionError();+ }+ }+ }++ /**+ * The handler for a variable allocated in a composition of locals+ *+ * <p>+ * This can also handle a varnode that is a subpiece of a local variable allocated for a larger+ * varnode. For example, this may handle {@code EAX}, when we have allocated a {@code long} to+ * hold all of {@code RAX}.+ *+ * @param parts the parts describing how the locals are composed+ * @param type the p-code type of the (whole) variable+ */+ public record MultiLocalVarHandler(List<MultiLocalPart> parts, JitType type)+ implements VarHandler {+ @Override+ public void generateInitCode(JitCodeGenerator gen, MethodVisitor iv) {+ // Generator calls local inits directly+ }++ @Override+ public void generateDeclCode(JitCodeGenerator gen, Label start, Label end,+ MethodVisitor rv) {+ // Generator calls local decls directly+ }++ @Override+ public void generateLoadCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ parts.get(0).generateLoadCode(gen, this.type, rv);+ for (MultiLocalPart part : parts.subList(1, parts.size())) {+ part.generateLoadCode(gen, this.type, rv);+ switch (this.type) {+ case IntJitType t -> rv.visitInsn(IOR);+ case LongJitType t -> rv.visitInsn(LOR);+ default -> throw new AssertionError();+ }+ }+ TypeConversions.generate(gen, this.type, type, rv);+ }++ @Override+ public void generateStoreCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ TypeConversions.generate(gen, type, this.type, rv);+ for (MultiLocalPart part : parts.subList(1, parts.size()).reversed()) {+ switch (this.type) {+ case IntJitType t -> rv.visitInsn(DUP);+ case LongJitType t -> rv.visitInsn(DUP2);+ default -> throw new AssertionError();+ }+ part.generateStoreCode(gen, this.type, rv);+ }+ parts.get(0).generateStoreCode(gen, this.type, rv);+ }+ }++ /**+ * A dummy handler for values/variables that are not allocated in JVM locals+ */+ public enum NoHandler implements VarHandler {+ /** Singleton */+ INSTANCE;++ @Override+ public JitType type() {+ return null;+ }++ @Override+ public void generateInitCode(JitCodeGenerator gen, MethodVisitor iv) {+ }++ @Override+ public void generateDeclCode(JitCodeGenerator gen, Label start, Label end,+ MethodVisitor rv) {+ }++ @Override+ public void generateLoadCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ throw new AssertionError();+ }++ @Override+ public void generateStoreCode(JitCodeGenerator gen, JitType type, MethodVisitor rv) {+ throw new AssertionError();+ }+ }++ /**+ * The descriptor of a p-code variable+ *+ * <p>+ * This is just a logical grouping of a varnode and its assigned p-code type.+ */+ private record VarDesc(int spaceId, long offset, int size, JitType type) {+ /**+ * Create a descriptor from the given varnode and type+ *+ * @param vn the varnode+ * @param type the p-code type+ * @return the descriptor+ */+ static VarDesc fromVarnode(Varnode vn, JitType type) {+ return new VarDesc(vn.getSpace(), vn.getOffset(), vn.getSize(), type);+ }++ /**+ * Derive a name for this variable, to use in the name of allocated local(s)+ *+ * @return the name+ */+ public String name() {+ return "s%d_%x_%d_%s".formatted(spaceId, offset, size, type.nm());+ }++ /**+ * Convert this descriptor back to a varnode+ *+ * @param factory the address factory for the emulation target language+ * @return the varnode+ */+ public Varnode toVarnode(AddressFactory factory) {+ return new Varnode(factory.getAddressSpace(spaceId).getAddress(offset), size);+ }+ }++ private final JitDataFlowModel dfm;+ private final JitVarScopeModel vsm;+ private final JitTypeModel tm;++ private final SleighLanguage language;+ private final Endian endian;++ private int nextLocal = 2; // 0:this, 1:blockId in run(int blockId)+ private final Map<JitVal, VarHandler> handlers = new HashMap<>();+ private final Map<Varnode, VarHandler> handlersPerVarnode = new HashMap<>();+ private final NavigableMap<Address, JvmLocal> locals = new TreeMap<>();++ /**+ * Construct the allocation model.+ *+ * @param context the analysis context+ * @param dfm the data flow moel+ * @param vsm the variable scope model+ * @param tm the type model+ */+ public JitAllocationModel(JitAnalysisContext context, JitDataFlowModel dfm,+ JitVarScopeModel vsm, JitTypeModel tm) {+ this.dfm = dfm;+ this.vsm = vsm;+ this.tm = tm;++ this.endian = context.getEndian();+ this.language = context.getLanguage();++ allocate();+ }++ /**+ * Reserve (allocate) one local for the given p-code variable+ *+ * @param name the name of the JVM local+ * @param type the p-code type represented by the local+ * @param desc the variable's descriptor+ * @return the allocated JVM local+ */+ private JvmLocal genFreeLocal(String name, SimpleJitType type, VarDesc desc) {+ int i = nextLocal;+ if (type.javaType() == long.class || type.javaType() == double.class) {+ nextLocal += 2;+ }+ else {+ nextLocal += 1;+ }+ return new JvmLocal(i, name, type, desc.toVarnode(language.getAddressFactory()));+ }++ /**+ * Get the next free local index without reserving it+ *+ * <p>+ * This should be used by operator code generators <em>after</em> all the+ * {@link JitBytesPcodeExecutorState state} bypassing local variables have been allocated. The+ * variables should be scoped to that operator only, so that the ids used are freed for the next+ * operator.+ *+ * @return the next id+ */+ public int nextFreeLocal() {+ return nextLocal;+ }++ /**+ * Reserve (allocate) several locals for the given p-code variable+ *+ * @param name a prefix to name each JVM local+ * @param types a p-code type that describes what each local stores+ * @param desc the (whole) variable's descriptor+ * @return the allocated JVM locals from most to least significant+ */+ private List<JvmLocal> genFreeLocals(String name, List<SimpleJitType> types,+ VarDesc desc) {+ JvmLocal[] result = new JvmLocal[types.size()];+ Iterable<SimpleJitType> it = language.isBigEndian()+ ? types+ : () -> new ReverseListIterator<SimpleJitType>(types);+ long offset = desc.offset;+ int i = 0;+ for (SimpleJitType t : it) {+ VarDesc d = new VarDesc(desc.spaceId, offset, t.size(), t);+ result[i] = genFreeLocal(name + "_" + i, t, d);+ offset += t.size();+ i++;+ }+ return List.of(result);+ }++ /**+ * A content for assigning a type to a varnode+ *+ * <p>+ * Because several SSA variables can share one varnode, we let each cast a vote to determine the+ * JVM type of the local(s) allocated to it.+ *+ * @implNote <b>TODO</b>: This type contest could receive more detailed information from the+ * type model, but perhaps that's more work than it's worth. I would have to+ * communicate all votes, not just the winner....+ */+ record TypeContest(Map<JitType, Integer> map) {+ /**+ * Start a new contest+ */+ public TypeContest() {+ this(new HashMap<>());+ }++ /**+ * Cast a vote for the given type+ *+ * @param type the type+ */+ public void vote(JitType type) {+ map.compute(type.ext(), (t, v) -> v == null ? 1 : v + 1);+ }++ /**+ * Choose the winner, favoring integral types+ *+ * @return the winning type+ */+ public JitType winner() {+ int max = map.values().stream().max(Integer::compare).get();+ return map.entrySet()+ .stream()+ .filter(e -> e.getValue() == max)+ .map(Map.Entry::getKey)+ .sorted(Comparator.comparing(JitType::pref))+ .findFirst()+ .get();+ }+ }++ private final Map<Varnode, TypeContest> typeContests = new HashMap<>();++ /**+ * Create a handler for the variable stored by the one given local+ *+ * @param local the local+ * @return the handler+ */+ private OneLocalVarHandler createOneLocalHandler(JvmLocal local) {+ return switch (local.type) {+ case IntJitType t -> new IntVarAlloc(local, t);+ case LongJitType t -> new LongVarAlloc(local, t);+ case FloatJitType t -> new FloatVarAlloc(local, t);+ case DoubleJitType t -> new DoubleVarAlloc(local, t);+ default -> throw new AssertionError();+ };+ }++ /**+ * Create a handler for a multi-part or subpiece varnode+ *+ * @param vn the varnode+ * @return a handler to access the value of the given varnode, as allocated in one or more+ * locals.+ */+ private VarHandler createComplicatedHandler(Varnode vn) {+ Entry<Address, JvmLocal> leftEntry = locals.floorEntry(vn.getAddress());+ assert overlapsLeft(leftEntry.getValue().vn, vn);+ Address min = leftEntry.getKey();+ NavigableMap<Address, JvmLocal> sub = locals.subMap(min, true, maxAddr(vn), true);++ List<MultiLocalPart> parts = new ArrayList<>();+ for (JvmLocal local : sub.values()) {+ int offset = (int) switch (endian) {+ case BIG -> maxAddr(leftEntry.getValue().vn).subtract(maxAddr(vn));+ case LITTLE -> vn.getAddress().subtract(leftEntry.getKey());+ };+ parts.add(new MultiLocalPart(local, offset));+ }+ return new MultiLocalVarHandler(parts, JitTypeBehavior.INTEGER.type(vn.getSize()));+ }++ /**+ * Get (creating if necessary) the handler for the given variable's varnode.+ *+ * @param vv the variable+ * @return the handler+ */+ private VarHandler getOrCreateHandlerForVarnodeVar(JitVarnodeVar vv) {+ return handlersPerVarnode.computeIfAbsent(vv.varnode(), vn -> {+ JvmLocal oneLocal = locals.get(vn.getAddress());+ if (oneLocal != null && oneLocal.vn.equals(vn)) {+ return createOneLocalHandler(oneLocal);+ }+ return createComplicatedHandler(vn);+ });+ }++ /**+ * Get (creating if necessary) the handler for the given value+ *+ * @param v the value+ * @return a handler for the value's varnode, if it is a register or unique; otherwise, the+ * dummy handler+ */+ private VarHandler createHandler(JitVal v) {+ if (v instanceof JitConstVal) {+ return NoHandler.INSTANCE;+ }+ if (v instanceof JitMemoryVar) {+ return NoHandler.INSTANCE;+ }+ if (v instanceof JitVarnodeVar vv) {+ return getOrCreateHandlerForVarnodeVar(vv);+ }+ throw new AssertionError();+ }++ /**+ * Perform the actual allocations+ */+ private void allocate() {+ for (JitVal v : dfm.allValues()) {+ if (v instanceof JitVarnodeVar vv && !(v instanceof JitMemoryVar)) {+ Varnode vn = vv.varnode();+ Varnode coalesced = vsm.getCoalesced(vn);+ TypeContest tc = typeContests.computeIfAbsent(coalesced, __ -> new TypeContest());+ if (vn.equals(coalesced)) {+ tc.vote(tm.typeOf(v));+ }+ else {+ tc.vote(JitTypeBehavior.INTEGER.type(coalesced.getSize()));+ }+ }+ }++ for (Map.Entry<Varnode, TypeContest> entry : typeContests.entrySet()+ .stream()+ .sorted(Comparator.comparing(e -> e.getKey().getAddress()))+ .toList()) {+ VarDesc desc = VarDesc.fromVarnode(entry.getKey(), entry.getValue().winner());+ switch (desc.type()) {+ case SimpleJitType t -> {+ locals.put(entry.getKey().getAddress(), genFreeLocal(desc.name(), t, desc));+ }+ case MpIntJitType t -> {+ for (JvmLocal leg : genFreeLocals(desc.name(), t.legTypes(), desc)) {+ locals.put(leg.vn.getAddress(), leg);+ }+ }+ default -> throw new AssertionError();+ }+ }++ for (JitVal v : dfm.allValuesSorted()) {+ handlers.put(v, createHandler(v));+ }+ }++ /**+ * Get the handler for the given value (constant or variable in the use-def graph)+ *+ * @param v the value+ * @return the handler+ */+ public VarHandler getHandler(JitVal v) {+ return handlers.get(v);+ }++ /**+ * Get all of the locals allocated+ *+ * @return the locals+ */+ public Collection<JvmLocal> allLocals() {+ return locals.values();+ }++ /**+ * Get all of the locals allocated for the given varnode+ *+ *+ * @implNote This is used by the code generator to birth and retire the local variables, given+ * that scope is analyzed in terms of varnodes.+ * @param vn the varnode+ * @return the locals+ */+ public Collection<JvmLocal> localsForVn(Varnode vn) {+ Address min = vn.getAddress();+ Address floor = locals.floorKey(min);+ if (floor != null) {+ min = floor;+ }+ return locals.subMap(min, true, maxAddr(vn), true).values();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitAnalysisContext.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitAnalysisContext.javanew file mode 100644index 0000000000..1c398ac89d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitAnalysisContext.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.pcode.emu.jit.analysis;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.pcode.emu.jit.*;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.program.model.lang.Endian;+import ghidra.program.model.pcode.PcodeOp;++/**+ * A collection of state that is shared among several phases of the translation process.+ *+ * @see JitCompiler+ */+public class JitAnalysisContext {+ private final JitConfiguration config;+ private final JitPassage passage;+ private final SleighLanguage language;+ private final Endian endian;++ /**+ * Construct a new context, starting with the given configuration and source passage+ *+ * @param config the JIT compiler's configuration+ * @param passage the passage selected for translation+ */+ public JitAnalysisContext(JitConfiguration config, JitPassage passage) {+ this.config = config;+ this.passage = passage;+ this.language = passage.getLanguage();+ this.endian = language.isBigEndian() ? Endian.BIG : Endian.LITTLE;+ }++ /**+ * Get the JIT compiler configuration+ *+ * @return the configuration+ */+ public JitConfiguration getConfiguration() {+ return config;+ }++ /**+ * Get the source passage+ *+ * @return the passage+ */+ public JitPassage getPassage() {+ return passage;+ }++ /**+ * Get the translation source (i.e., emulation target) language+ *+ * @return the language+ */+ public SleighLanguage getLanguage() {+ return language;+ }++ /**+ * Get the endianness of the translation source, i.e., emulation target.+ *+ * @return the endianness+ */+ public Endian getEndian() {+ return endian;+ }++ /**+ * Check if the given p-code op is the first of an instruction.+ *+ * @param op the op to check+ * @return the address-context pair+ * @see JitPassage#getOpEntry(PcodeOp)+ */+ public AddrCtx getOpEntry(PcodeOp op) {+ return passage.getOpEntry(op);+ }++ /**+ * Get the error message for a given p-code op+ *+ * @param op the p-code op generating the error+ * @return the message+ * @see JitPassage#getErrorMessage(PcodeOp)+ */+ public String getErrorMessage(PcodeOp op) {+ return passage.getErrorMessage(op);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitControlFlowModel.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitControlFlowModel.javanew file mode 100644index 0000000000..fd7d7b738b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitControlFlowModel.java@@ -0,0 +1,586 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.util.*;++import ghidra.pcode.emu.jit.*;+import ghidra.pcode.emu.jit.JitCompiler.Diag;+import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.emu.jit.decode.DecoderForOneStride;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.exec.PcodeProgram;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.SequenceNumber;++/**+ * The control flow analysis for JIT-accelerated emulation.+ *+ * <p>+ * This implements the Control Flow Analysis phase of the {@link JitCompiler}. Some rudimentary+ * analysis is performed during passage decoding — note the {@link BlockSplitter} is exported+ * for use in {@link DecoderForOneStride}. This is necessary to evaluate whether an instruction+ * (especially an inject-instrumented instruction) has fall-through. Without that information, the+ * decoder cannot know whether it has reached the end of its stride. Note that the decoder records+ * all the branches it encounters and includes them as metadata in the passage. Because branches+ * need to record the source and target p-code op, the decoder is well suited. Additionally, it has+ * to compute these anyway, and we'd rather avoid duplicative work by this analyzer.+ *+ * <p>+ * The decoded passage contains a good deal of information, but the primary inputs at this point are+ * the ordered list of p-code ops and the branches. This model's primary responsibility is to break+ * the passage down into basic blocks at the p-code level. Even though the p-code ops have all been+ * concatenated together when constructing the passage, we know, by definition, that each stride+ * will end with an unconditional branch (or else a synthesized {@link ExitPcodeOp}. Note also that+ * {@link JitPassage#getBranches()} only includes the non-fall-through branches, because these are+ * all that are recorded by the decoder. Thus, it is also this model's responsibility to create the+ * fall-through branches. These will occur to represent the "false" case of any conditional+ * branches, and to represent "unconditional fall through."+ *+ * <p>+ * The algorithm for this is fairly straightforward and has been implemented primarily in+ * {@link BlockSplitter}. Most everything else in this class is data management and the types+ * representing the model.+ *+ * <p>+ * <b>NOTE:</b> It is technically possible for a userop to branch, but this analysis does not+ * consider that. Instead, the emulator will decide how to handle those. Conventionally, I'd rather+ * a userop <em>never</em> perform control flow. Instead, I'd rather see things like+ * <code>pc = my_control_op(); goto [pc];</code>.+ */+public class JitControlFlowModel {++ /**+ * An exception thrown when control flow might run off the edge of the passage.+ *+ * <p>+ * By definition a passage is a collection of strides, and each stride is terminated by some op+ * without fall through (or else a synthesized {@link ExitPcodeOp}. In particular, the last+ * stride cannot end in fall through. If it did, there would be no op for it to fall through to.+ * While this should never happen, it is easy in the course of development to allow it by+ * accident. The control flow analysis can detect this as it finished splitting the passage into+ * blocks. If the final block has fall through, the passage is said to have "unterminated flow,"+ * and this exception is thrown. We do not wait until execution of the passage to throw this. It+ * is thrown during translation, as it represents an assertion failure in the translation+ * process. That is, the decoder produced an unsound passage.+ */+ public static class UnterminatedFlowException extends IllegalArgumentException {+ /**+ * Construct the exception+ */+ public UnterminatedFlowException() {+ super("Final block cannot fall through");+ }+ }++ /**+ * A flow from one block to another+ *+ * <p>+ * This is just a wrapper around an {@link IntBranch} that allows us to quickly identify what+ * two blocks it connects. Note that to connect two blocks in the passage, the branch must by+ * definition be an {@link IntBranch}.+ *+ * <p>+ * If this flow represents entry into the passage, then {@link #from()} and {@link #branch()}+ * may be null+ *+ * @param from the block from which execution flows. In the case of a non-fall-through branch,+ * the block should end with the branching p-code op. For conditional fall-through,+ * it should end with the {@link PcodeOp#CBRANCH} op. For unconditional fall-through,+ * it could end with any op having fall through.+ * @param to the block to which execution flows. The block must start with the+ * {@link IntBranch#to() target op} of the branch.+ * @param branch the branch effecting the flow of execution+ */+ public record BlockFlow(JitBlock from, JitBlock to, IntBranch branch) {+ /**+ * Create an entry flow to the given block+ *+ * @param to the block to which execution flows+ * @return the flow+ */+ public static BlockFlow entry(JitBlock to) {+ return new BlockFlow(null, to, null);+ }+ }++ /**+ * A basic block of p-code+ *+ * <p>+ * This follows the formal definition of a basic block, but at the p-code level. All flows into+ * the block enter at its first op, and all flows out of the block exit at its last op. The+ * block also contains information about these flows as well as branches out of the passage via+ * this block.+ */+ public static class JitBlock extends PcodeProgram {+ private Map<IntBranch, BlockFlow> flowsFrom = new HashMap<>();+ private Map<IntBranch, BlockFlow> flowsTo = new HashMap<>();+ private List<IntBranch> branchesFrom = new ArrayList<>();+ private List<IntBranch> branchesTo = new ArrayList<>();+ private List<Branch> branchesOut = new ArrayList<>();++ private final int instructions;+ private final int trailingOps;++ /**+ * Construct a new block+ *+ * @param program the program (i.e., passage) from which this block is derived+ * @param code the subset of ops, in execution order, comprising this block+ */+ public JitBlock(PcodeProgram program, List<PcodeOp> code) {+ super(program, List.copyOf(code));++ int instructions = 0;+ int trailingOps = 0;+ for (PcodeOp op : code) {+ if (op instanceof DecodedPcodeOp dec && dec.isInstructionStart()) {+ instructions++;+ trailingOps = 0;+ }+ else if (op instanceof DecodedPcodeOp) {+ trailingOps++;+ }+ }+ this.instructions = instructions;+ this.trailingOps = trailingOps;+ }++ @Override+ protected String getHead() {+ return super.getHead() + "[start=" + start() + "]";+ }++ @Override+ public String toString() {+ return getHead();+ }++ /**+ * Get the first p-code op in this block+ *+ * @return the first p-code op+ */+ public PcodeOp first() {+ return code.getFirst();+ }++ /**+ * Get the sequence number of the first op+ *+ * <p>+ * This is used for display and testing purposes only.+ *+ * @return the sequence number+ */+ public SequenceNumber start() {+ return code.getFirst().getSeqnum();+ }++ /**+ * Get the sequence number of the last op+ *+ * <p>+ * This is used for display and testing purposes only.+ *+ * @return the sequence number+ */+ public SequenceNumber end() {+ return code.getLast().getSeqnum();+ }++ /**+ * Convert our collections to immutable ones+ */+ private void cook() {+ flowsFrom = Collections.unmodifiableMap(flowsFrom);+ flowsTo = Collections.unmodifiableMap(flowsTo);+ branchesFrom = Collections.unmodifiableList(branchesFrom);+ branchesTo = Collections.unmodifiableList(branchesTo);+ branchesOut = Collections.unmodifiableList(branchesOut);+ }++ /**+ * Get (internal) flows leaving this block+ *+ * @return the flows, keyed by branch+ */+ public Map<IntBranch, BlockFlow> flowsFrom() {+ return flowsFrom;+ }++ /**+ * Get (internal) flows entering this block+ *+ * @return the flows, keyed by branch+ */+ public Map<IntBranch, BlockFlow> flowsTo() {+ return flowsTo;+ }++ /**+ * Get internal branches leaving this block+ *+ * @return the list of branches+ */+ public List<IntBranch> branchesFrom() {+ return branchesFrom;+ }++ /**+ * Get internal branches entering this block+ *+ * @return the list of branches+ */+ public List<IntBranch> branchesTo() {+ return branchesTo;+ }++ /**+ * Get branches leaving the passage from this block+ *+ * @return the list of branches+ */+ public List<Branch> branchesOut() {+ return branchesOut;+ }++ /**+ * If this block has fall through, find the block into which it falls+ *+ * @return the block, or {@code null}+ */+ public JitBlock getFallFrom() {+ return flowsFrom.values()+ .stream()+ .filter(f -> f.branch.isFall())+ .findAny()+ .map(f -> f.to)+ .orElse(null);+ }++ /**+ * Check if there is an internal non-fall-through branch to this block+ *+ * <p>+ * This is used by the {@link JitCodeGenerator} to determine whether or not a block's+ * bytecode needs to be labeled.+ *+ * @return true if this block is targeted by a branch+ */+ public boolean hasJumpTo() {+ return flowsTo.values().stream().anyMatch(f -> !f.branch.isFall());+ }++ /**+ * Get the target block for the given internal branch, assuming it's from this block+ *+ * @param branch the branch+ * @return the target block or null+ */+ public JitBlock getTargetBlock(IntBranch branch) {+ return flowsFrom.get(branch).to;+ }++ /**+ * Get the number of instructions represented in this block+ *+ * <p>+ * This may get dicey as blocks are not necessarily split on instruction boundaries.+ * Nevertheless, we seek to count the number of instructions executed at runtime, so that we+ * can replay an execution, step in reverse, etc. What we actually do here is count the+ * number of ops which are the first op produced by a decoded instruction.+ *+ * @see JitCompiledPassage#count(int, int)+ * @see JitPcodeThread#count(int, int)+ * @return the instruction count+ */+ public int instructionCount() {+ return instructions;+ }++ /**+ * Get the number of trailing ops in this block+ *+ * <p>+ * It is possible a block represents only partial execution of an instruction. Though+ * {@link #instructionCount()} will count this partial instruction, we can tell how far we+ * got into it by examining this value. With this, we should be able to replay an execution+ * to exactly the same p-code op step.+ *+ * @return the trailing op count+ */+ public int trailingOpCount() {+ return trailingOps;+ }+ }++ /**+ * A class that splits a sequence of ops and associated branches into basic blocks.+ *+ * <p>+ * This is the kernel of control flow analysis. It first indexes the branches by source and+ * target op. Note that only non-fall-through branches are known at this point. Then, it+ * traverses the list of ops. A split occurs following an op that is a branch source and/or+ * preceding an op that is a branch target. A block is constructed when such a split point is+ * encountered. In the case of a branch source, the branch is added to the newly constructed+ * block. As traversal proceeds to the next op, it checks if the immediately-preceding block+ * should have fall through (conditional or unconditional) by examining its last op. It adds a+ * new fall-through branch if so. The end of the p-code op list is presumed a split point. If+ * that final block "should have" fall through, an {@link UnterminatedFlowException} is thrown.+ *+ * <p>+ * Once all the splitting is done, we have the blocks and all the branches (internal or+ * external) that leave each block. We then compute all the branches (internal) that enter each+ * block and the associated flows in both directions.+ */+ public static class BlockSplitter {+ private final PcodeProgram program;++ private final Map<PcodeOp, Branch> branches = new HashMap<>();+ private final Map<PcodeOp, IntBranch> branchesByTarget = new HashMap<>();+ private final SequencedMap<PcodeOp, JitBlock> blocks = new LinkedHashMap<>();++ private List<PcodeOp> partialBlock = new ArrayList<>();+ private JitBlock lastBlock = null;++ /**+ * Construct a new block splitter to process the given program+ *+ * <p>+ * No analysis is performed in the constructor. The client must call+ * {@link #addBranches(Collection)} and then {@link #splitBlocks()}.+ *+ * @param program the program, i.e., list of p-code ops+ */+ public BlockSplitter(PcodeProgram program) {+ this.program = program;+ }++ /**+ * Notify the splitter of the given branches before analysis+ *+ * <p>+ * The splitter immediately indexes the given branches by source and target op.+ *+ * @param branches the branches+ */+ public void addBranches(Collection<? extends Branch> branches) {+ for (Branch b : branches) {+ this.branches.put(b.from(), b);+ if (b instanceof IntBranch ib) {+ this.branchesByTarget.put(ib.to(), ib);+ }+ }+ }++ private JitBlock makeBlock() {+ if (!partialBlock.isEmpty()) {+ lastBlock = new JitBlock(program, partialBlock);+ partialBlock = new ArrayList<>();+ blocks.put(lastBlock.first(), lastBlock);+ return lastBlock;+ }+ return null;+ }++ private boolean needsFallthrough(JitBlock block) {+ if (block.branchesFrom.isEmpty() && block.branchesOut.isEmpty()) {+ return true;+ }+ if (block.branchesFrom.size() == 1) {+ return JitPassage.hasFallthrough(block.branchesFrom.getFirst().from());+ }+ if (block.branchesOut.size() == 1) {+ return JitPassage.hasFallthrough(block.branchesOut.getFirst().from());+ }+ throw new AssertionError();+ }++ private void checkForFallthrough(PcodeOp op) {+ if (lastBlock == null) {+ return;+ }+ if (needsFallthrough(lastBlock)) {+ lastBlock.branchesFrom.add(new IntBranch(lastBlock.getCode().getLast(), op, true));+ }+ lastBlock = null;+ }++ private void fillFlows() {+ for (JitBlock from : blocks.values()) {+ for (Branch branch : from.branchesFrom) {+ if (branch instanceof IntBranch ib) {+ JitBlock to = Objects.requireNonNull(blocks.get(ib.to()));+ to.branchesTo.add(ib);+ BlockFlow flow = new BlockFlow(from, to, ib);+ from.flowsFrom.put(ib, flow);+ to.flowsTo.put(ib, flow);+ }+ }+ }+ }++ private void cook() {+ for (JitBlock block : blocks.values()) {+ block.cook();+ }+ }++ private IntBranch getBranchTo(PcodeOp to) {+ return branchesByTarget.get(to);+ }++ private Branch getBranchFrom(PcodeOp from) {+ return branches.get(from);+ }++ private void doWork() {+ if (program.getCode().isEmpty()) {+ throw new IllegalArgumentException("No code to analyze");+ }++ for (PcodeOp op : program.getCode()) {+ // This op would be after the block from the last iteration+ checkForFallthrough(op);+ IntBranch branchTo = getBranchTo(op);+ if (branchTo != null) {+ makeBlock();+ // This op would be after the block we just made+ checkForFallthrough(op);+ }+ partialBlock.add(op);+ Branch branchFrom = getBranchFrom(op);+ if (branchFrom != null) {+ makeBlock();+ // NB. lastBlock cannot be null, we just added the op+ if (branchFrom instanceof IntBranch ib) {+ lastBlock.branchesFrom.add(ib);+ }+ else {+ lastBlock.branchesOut.add(branchFrom);+ }+ /**+ * Do not checkForFallthrough, because the current op is already in the block+ */+ }+ }++ makeBlock();+ if (needsFallthrough(lastBlock)) {+ /**+ * I'm making it the decoder's responsibility to provide a sane program. We can+ * catch missing control flow at the very end, but we cannot do so at the end of+ * other blocks. If they have fall-through, they'll (perhaps erroneously) fall+ * through to the next block that happens to be there. Thus, it is up to the+ * decoder, if it decodes any incomplete strides, that is must synthesize the+ * appropriate control-flow ops.+ */+ throw new UnterminatedFlowException();+ }++ fillFlows();+ cook();+ }++ private SequencedMap<PcodeOp, JitBlock> getBlocks() {+ return blocks;+ }++ /**+ * Perform the actual analysis+ *+ * @return the resulting split blocks, keyed by {@link JitBlock#start()}+ */+ public SequencedMap<PcodeOp, JitBlock> splitBlocks() {+ doWork();+ return getBlocks();+ }+ }++ private final JitPassage passage;+ private final SequencedMap<PcodeOp, JitBlock> blocks;++ /**+ * Construct the control flow model.+ *+ * <p>+ * Analysis is performed as part of constructing the model.+ *+ * @param context the analysis context+ */+ public JitControlFlowModel(JitAnalysisContext context) {+ this.passage = context.getPassage();+ this.blocks = analyze();+ }++ /**+ * Perform the analysis.+ *+ * @return the resulting blocks, keyed by {@link JitBlock#first()}+ */+ protected SequencedMap<PcodeOp, JitBlock> analyze() {+ BlockSplitter splitter = new BlockSplitter(passage);+ splitter.addBranches(passage.getBranches().values());+ return splitter.splitBlocks();+ }++ /**+ * Get the basic blocks+ *+ * @return the collection of blocks+ */+ public Collection<JitBlock> getBlocks() {+ return blocks.values();+ }++ /**+ * For diagnostics: Dump the results to stderr+ *+ * @see Diag#PRINT_CFM+ */+ public void dumpResult() {+ System.err.println("STAGE: ControlFlow");+ for (JitBlock block : blocks.values()) {+ System.err.println("");+ System.err.println("Block: " + block);+ System.err.println("Branches to:");+ for (IntBranch branch : block.branchesTo) {+ System.err.println(" " + branch);+ }+ System.err.println("Flows to:");+ for (BlockFlow flow : block.flowsTo.values()) {+ System.err.println(" " + flow);+ }+ System.err.println(block.format(true));+ System.err.println("Branches from:");+ for (IntBranch branch : block.branchesFrom) {+ System.err.println(" " + branch);+ }+ System.err.println("Flows from:");+ for (BlockFlow flow : block.flowsFrom.values()) {+ System.err.println(" " + flow);+ }+ System.err.println("Branches out:");+ for (Branch branch : block.branchesOut) {+ System.err.println(" " + branch);+ }+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowArithmetic.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowArithmetic.javanew file mode 100644index 0000000000..ccdcbe9f44--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowArithmetic.java@@ -0,0 +1,398 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.math.BigInteger;+import java.util.ArrayList;+import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitDataFlowState.MiniDFState;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.*;+import ghidra.pcode.exec.ConcretionError;+import ghidra.pcode.exec.PcodeArithmetic;+import ghidra.pcode.opbehavior.OpBehaviorFactory;+import ghidra.pcode.opbehavior.OpBehaviorSubpiece;+import ghidra.pcode.utils.Utils;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Endian;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++/**+ * A p-code arithmetic for interpreting p-code and constructing a use-def graph+ *+ * <p>+ * This is used for intra-block data flow analysis. We leverage the same API as is used for concrete+ * p-code interpretation, but we use it for an abstraction. The type of the interpretation is+ * {@code T:=}{@link JitVal}, which can consist of constants and variables in the use-def graph. The+ * arithmetic must be provided to the {@link JitDataFlowExecutor}. The intra-block portions of the+ * use-def graph are populated as each block is interpreted by the executor.+ *+ * <p>+ * The general strategy for each of the arithmetic operations is to 1) generate the output SSA+ * variable for the op, 2) generate the op node for the generated output and given inputs, 3) enter+ * the op into the use-def graph as the definition of its output, 4) record the inputs and used by+ * the new op, and finally 5) return the generated output.+ *+ * <p>+ * There should only need to be one of these per data flow model, not per block.+ */+public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {+ private static final OpBehaviorSubpiece OB_SUBPIECE =+ (OpBehaviorSubpiece) OpBehaviorFactory.getOpBehavior(PcodeOp.SUBPIECE);++ private final JitDataFlowModel dfm;+ private final Endian endian;++ /**+ * Construct the arithmetic+ *+ * @param context the analysis context+ * @param dfm the owning data flow model+ */+ public JitDataFlowArithmetic(JitAnalysisContext context, JitDataFlowModel dfm) {+ this.dfm = dfm;+ this.endian = context.getEndian();+ }++ @Override+ public Endian getEndian() {+ return endian;+ }++ /**+ * Remove {@code amt} bytes from the right of the <em>varnode</em>.+ *+ * <p>+ * "Right" is considered with respect to the machine endianness. If it is little endian, then+ * the byte are shaved from the <em>left</em> of the value. This should be used when getting+ * values from the state to remove pieces from off-cut values. It should be applied before the+ * pieces are ordered according to machine endianness.+ *+ * @param in1Vn the varnode representing the input+ * @param amt the number of bytes to remove+ * @param in1 the input (really a value read from the state)+ * @return the resulting value+ */+ public JitVal truncFromRight(Varnode in1Vn, int amt, JitVal in1) {+ Varnode outVn = new Varnode(in1Vn.getAddress(), in1Vn.getSize() - amt);+ return subpiece(outVn, endian.isBigEndian() ? amt : 0, in1);+ }++ /**+ * Remove {@code amt} bytes from the left of the <em>varnode</em>.+ *+ * <p>+ * "Left" is considered with respect to the machine endianness. If it is little endian, then the+ * byte are shaved from the <em>right</em> of the value. This should be used when getting values+ * from the state to remove pieces from off-cut values. It should be applied before the pieces+ * are ordered according to machine endianness.+ *+ * @param in1Vn the varnode representing the input+ * @param amt the number of bytes to remove+ * @param in1 the input (really a value read from the state)+ * @return the resulting value+ */+ public JitVal truncFromLeft(Varnode in1Vn, int amt, JitVal in1) {+ Varnode outVn = new Varnode(in1Vn.getAddress().add(amt), in1Vn.getSize() - amt);+ return subpiece(outVn, endian.isBigEndian() ? 0 : amt, in1);+ }++ private void removeOffsetFromRight(List<JitVal> parts, int offset) {+ JitVal p;+ do {+ p = parts.remove(parts.size() - 1);+ offset -= p.size();+ }+ while (offset > 0);+ if (offset < 0) {+ JitVal np = shaveFromRight(-offset, p);+ parts.add(np);+ offset += np.size();+ assert offset == 0;+ }+ }++ private void removeFromLeftToSize(List<JitVal> parts, int size) {+ int actualSize = 0;+ JitVal p;+ int i = parts.size();+ do {+ p = parts.get(--i);+ actualSize += p.size();+ }+ while (actualSize < size);+ if (actualSize > size) {+ JitVal np = shaveFromLeft(-size, p);+ parts.set(i + 1, np);+ actualSize -= p.size();+ actualSize += np.size();+ assert actualSize == size;+ }+ while (i > 0) {+ parts.remove(--i);+ }+ }++ /**+ * Try to produce a simplified {@link JitSynthSubPieceOp} or {@link JitCatenateOp}+ *+ * <p>+ * This takes an input, subpiece offset, and output variable. If the input variable is the+ * result of another subpiece, the result can be a single simplified subpiece. Similarly, if the+ * input is the result of a catenation, then the result can be a simplified catenation, or+ * possibly subpiece.+ *+ * If either of these situations applies, and simplification is possible, this returns a+ * non-null result, and that result is added to the use-def graph specifying the given output+ * variable as the simplified output. Otherwise, the result is null and the caller should create+ * a new subpiece op.+ *+ * @param out the output variable+ * @param offset the subpiece offset (number of bytes shifted right)+ * @param v the input value+ * @return the output variable, as the result of the simplified sub-graph.+ */+ private JitVal trySimplifiedSubPiece(JitOutVar out, int offset, JitVal v) {+ if (!(v instanceof JitOutVar vOut)) {+ return null;+ }+ if (vOut.definition() instanceof JitSynthSubPieceOp subsub) {+ subsub.unlink();+ return dfm+ .notifyOp(new JitSynthSubPieceOp(out, offset + subsub.offset(), subsub.v()))+ .out();+ }+ if (vOut.definition() instanceof JitCatenateOp cat) {+ cat.unlink();+ List<JitVal> newParts = new ArrayList<>(cat.parts());+ removeOffsetFromRight(newParts, offset);+ removeFromLeftToSize(newParts, out.size());+ assert !newParts.isEmpty();+ if (newParts.size() == 1) {+ // Context should already be notified+ return newParts.get(0);+ }+ return dfm.notifyOp(new JitCatenateOp(out, newParts)).out();+ }+ return null;+ }++ /**+ * Construct the result of taking the subpiece+ *+ * <p>+ * If the input is another subpiece or a catenation, the result may be simplified. In+ * particular, the subpiece of a catenation may be a smaller catenation. No matter the case, the+ * given output variable is made the output of the subpiece result, and the use-def graph is+ * updated accordingly.+ *+ * @param outVn the output variable+ * @param offset the subpiece offset (number of bytes shifted right)+ * @param v the input value+ * @return the output variable, as the result of the simplified sub-graph+ */+ private JitVal subpiece(Varnode outVn, int offset, JitVal v) {+ JitOutVar out = dfm.generateOutVar(outVn);+ JitVal simplified = trySimplifiedSubPiece(out, offset, v);+ if (simplified != null) {+ return simplified;+ }+ return dfm.notifyOp(new JitSynthSubPieceOp(out, offset, v)).out();+ }++ private Varnode subPieceVn(int size, int offset, Varnode whole) {+ if (endian.isBigEndian()) {+ return new Varnode(whole.getAddress().add(whole.getSize() - offset - size), size);+ }+ return new Varnode(whole.getAddress().add(offset), size);+ }++ /**+ * Remove {@code amt} bytes from the right of the value.+ *+ * <p>+ * The value is unaffected by the machine endianness, except to designate the output varnode.+ *+ * @param amt the number of bytes to remove+ * @param in1 the input+ * @return the output+ */+ public JitVal shaveFromRight(int amt, JitVal in1) {+ return subpiece(in1.size() - amt, amt, in1);+ }++ /**+ * Remove {@code amt} bytes from the left of the value.+ *+ * <p>+ * The value is unaffected by the machine endianness, except to designate the output varnode.+ *+ * @param amt the number of bytes to remove+ * @param in1 the input+ * @return the output+ */+ public JitVal shaveFromLeft(int amt, JitVal in1) {+ return subpiece(in1.size() - amt, 0, in1);+ }++ /**+ * Compute the subpiece of a value.+ *+ * <p>+ * The result is added to the use-def graph. The output varnode is computed from the input+ * varnode and the subpiece parameters. This is used to handle variable retrieval when an access+ * only include parts of a value previously written. Consider the x86 assembly:+ *+ * <pre>+ * MOV RAX, qword ptr [...]+ * MOV dword ptr [...], EAX+ * </pre>+ *+ * <p>+ * The second line reads {@code EAX}, which consists of only the lower part of {@code RAX}.+ * Thus, we synthesize a subpiece op. These are distinct from an actual {@link PcodeOp#SUBPIECE}+ * op, since we sometimes needs to filter out synthetic ops.+ *+ * @param size the size of the output variable in bytes+ * @param offset the subpiece offset (number of bytes shifted right)+ * @param v the input value+ * @return the output value+ */+ public JitVal subpiece(int size, int offset, JitVal v) {+ if (v instanceof JitConstVal c) {+ return new JitConstVal(size,+ OB_SUBPIECE.evaluateBinary(size, v.size(), c.value(), BigInteger.valueOf(offset)));+ }+ if (v instanceof JitVarnodeVar vv) {+ Varnode inVn = vv.varnode();+ Varnode outVn = subPieceVn(size, offset, inVn);+ return subpiece(outVn, offset, v);+ }+ throw new UnsupportedOperationException("unsupported subpiece of " + v);+ }++ /**+ * Construct the catenation of the given values to form the given output varnode.+ *+ * <p>+ * The result is added to the use-def graph. This is used to handle variable retrieval when the+ * pattern of accesses indicates catenation. Consider the x86 assembly:+ *+ * <pre>+ * MOV AH, byte ptr [...]+ * MOV AL, byte ptr [...]+ * MOV word ptr [...], AX+ * </pre>+ *+ * <p>+ * On the third line, the value in {@code AX} is the catenation of whatever values were written+ * into {@code AH} and {@code AL}. Thus, we synthesize a catenation op node in the use-def+ * graph.+ *+ * @param outVn the output varnode+ * @param parts the list of values to catenate, ordered by machine endianness+ * @return the output value+ * @see MiniDFState#getDefinitions(AddressSpace, long, int)+ */+ public JitVal catenate(Varnode outVn, List<JitVal> parts) {+ return dfm.notifyOp(new JitCatenateOp(dfm.generateOutVar(outVn), parts)).out();+ }++ @Override+ public JitVal unaryOp(PcodeOp op, JitVal in1) {+ return dfm.notifyOp(JitOp.unOp(op, dfm.generateOutVar(op.getOutput()), in1)).out();+ }++ @Override+ public JitVal unaryOp(int opcode, int sizeout, int sizein1, JitVal in1) {+ throw new AssertionError();+ }++ @Override+ public JitVal binaryOp(PcodeOp op, JitVal in1, JitVal in2) {+ return dfm.notifyOp(JitOp.binOp(op, dfm.generateOutVar(op.getOutput()), in1, in2)).out();+ }++ @Override+ public JitVal binaryOp(int opcode, int sizeout, int sizein1, JitVal in1, int sizein2,+ JitVal in2) {+ throw new AssertionError();+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * We override this to record the {@link JitStoreOp store} op into the use-def graph. As+ * "output" we just return {@code inValue}. The executor will call+ * {@link JitDataFlowState#setVar(AddressSpace, JitVal, int, boolean, JitVal) setVal}, but the+ * state will just ignore it, because it will be an indirect memory write.+ */+ @Override+ public JitVal modBeforeStore(PcodeOp op, AddressSpace space, JitVal inOffset, JitVal inValue) {+ return dfm.notifyOp(new JitStoreOp(op, space, inOffset, inValue)).value();+ }++ @Override+ public JitVal modBeforeStore(int sizeinOffset, AddressSpace space, JitVal inOffset,+ int sizeinValue, JitVal inValue) {+ throw new AssertionError();+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * We override this to record the {@lnk JitLoadOp load} op into the use-def graph. For our+ * {@code inValue}, the {@link JitDataFlowState state} will have just returned the+ * {@link JitIndirectMemoryVar#INSTANCE dummy indirect} variable definition. We must not "use"+ * this. Instead, we must take our other parameters to construct the load op and return its+ * output.+ */+ @Override+ public JitVal modAfterLoad(PcodeOp op, AddressSpace space, JitVal inOffset, JitVal inValue) {+ return dfm.notifyOp(new JitLoadOp(+ op, dfm.generateOutVar(op.getOutput()), space, inOffset)).out();+ }++ @Override+ public JitVal modAfterLoad(int sizeinOffset, AddressSpace space, JitVal inOffset,+ int sizeinValue, JitVal inValue) {+ throw new AssertionError();+ }++ @Override+ public JitVal fromConst(byte[] value) {+ BigInteger bigVal =+ Utils.bytesToBigInteger(value, value.length, endian.isBigEndian(), false);+ return JitVal.constant(value.length, bigVal);+ }++ @Override+ public byte[] toConcrete(JitVal value, Purpose purpose) {+ if (value instanceof JitConstVal c) {+ return Utils.bigIntegerToBytes(c.value(), c.size(), endian.isBigEndian());+ }+ throw new ConcretionError("Cannot concretize " + value, purpose);+ }++ @Override+ public long sizeOf(JitVal value) {+ return value.size();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowBlockAnalyzer.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowBlockAnalyzer.javanew file mode 100644index 0000000000..7165f713ca--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowBlockAnalyzer.java@@ -0,0 +1,219 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.util.*;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.op.JitPhiOp;+import ghidra.pcode.emu.jit.var.JitMissingVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.PcodeExecutor;+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Register;+import ghidra.program.model.pcode.Varnode;++/**+ * An encapsulation of the per-block data flow analysis done by {@link JitDataFlowModel}+ *+ * <p>+ * One of these is created for each basic block in the passage. This does both the intra-block+ * analysis and encapsulates parts of the inter-block analysis. The class also contains and provides+ * access to some of the analytic results.+ *+ * @see JitDataFlowModel#getAnalyzer(JitBlock)+ */+public class JitDataFlowBlockAnalyzer {+ private final JitAnalysisContext context;+ private final JitDataFlowModel dfm;+ private final JitBlock block;++ private final JitDataFlowArithmetic arithmetic;+ private final JitDataFlowUseropLibrary library;++ private final JitDataFlowState state;+ private final boolean isEntry;++ JitDataFlowBlockAnalyzer(JitAnalysisContext context, JitDataFlowModel dfm, JitBlock block) {+ this.context = context;+ this.dfm = dfm;+ this.block = block;++ this.arithmetic = dfm.getArithmetic();+ this.library = dfm.getLibrary();++ this.state = new JitDataFlowState(context, dfm, block);+ this.isEntry = context.getOpEntry(block.first()) != null;+ }++ /**+ * Perform the intra-block analysis for this block+ *+ * <p>+ * This just runs the block p-code through the analytic interpreter. See+ * {@link JitDataFlowModel}'s section on intra-block analysis.+ */+ void doIntrablock() {+ PcodeExecutor<JitVal> exec = new JitDataFlowExecutor(context, dfm, state);+ exec.execute(block, library);+ }++ /**+ * The initial entry into the recursive phi option seeking algorithm+ *+ * <p>+ * See {@link JitDataFlowModel}'s section on inter-block analysis. This will modify the given+ * phi op in place, adding to it each found option. There is also more details than discussed in+ * the data flow model documentation. Keep in mind a varnode may be partially defined, e.g.,+ * when reading {@link RAX}, perhaps only {@link EAX} has been defined. In such cases, we must+ * catenate in the same manner we would when reading the varnode during intra-block analysis.+ * The portions missing a definition will generate corresponding phi nodes, which are treated+ * recursively.+ *+ * @param phi the phi op for which we seek options+ */+ void fillPhiFromDeps(JitPhiOp phi) {+ fillPhiFromDeps(phi, new HashSet<>());+ }++ /**+ * Fill options in for the given phi op+ *+ * <p>+ * If our block is an entry, add that as a possible option. <em>Additionally</em>, consider each+ * upstream block (dependency) as an option, recursively. Recursion will naturally terminate if+ * there are no inward flows.+ *+ * @param phi the phi op for which we seek options+ * @param visited the blocks which have already been visited during recursion+ */+ private void fillPhiFromDeps(JitPhiOp phi, Set<JitBlock> visited) {+ if (isEntry) {+ phi.addInputOption();+ }+ for (BlockFlow flow : block.flowsTo().values()) {+ JitDataFlowBlockAnalyzer analyzerFrom = dfm.getOrCreateAnalyzer(flow.from());+ analyzerFrom.fillPhiFromBlock(phi, flow, visited);+ }+ }++ /**+ * Consider the given flow as an option for the given phi op, and fill it+ *+ * <p>+ * If we've already visited the given block, we return immediately, without further recursion.+ * Otherwise, we examine the varnode output state of this block for suitable definitions. If+ * needed, we fill any gaps (possibly the entire varnode sought) with new phi nodes and recurse.+ *+ * @param phi the phi op for which we seek an option+ * @param flow the flow from the block to consider+ * @param visited the blocks which have already been visited during recursion+ */+ private void fillPhiFromBlock(JitPhiOp phi, BlockFlow flow, Set<JitBlock> visited) {+ if (!visited.add(block)) {+ /**+ * NOTE: We do not need to remove the block before we return. If we didn't find it by+ * this path, we certainly not going to find it from here by another path.+ */+ return;+ }++ Varnode phiVn = phi.out().varnode();+ List<JitVal> defs = state.getDefinitions(phiVn);+ if (defs.size() != 1) {+ defs = state.generatePhis(defs, dfm.phiQueue);+ JitVal catOpt = arithmetic.catenate(phiVn, defs);+ phi.addOption(flow, catOpt);+ /**+ * New phi nodes will be picked up in next round of filling. Since parts are smaller+ * than the whole, the size of such nodes should shrink until a singular definition is+ * found.+ */+ return;+ }++ JitVal val = defs.get(0);+ if (val instanceof JitMissingVar missing) {+ // Require the chain to have a node in this block+ JitPhiOp phi2 = missing.generatePhi(dfm, block);+ dfm.phiQueue.add(phi2);+ state.setVar(missing.varnode(), phi2.out());+ phi.addOption(flow, phi2.out());+ // Will get filled on subsequent round+ //fillPhiFromDeps(phi2, visited);+ return;+ }++ phi.addOption(flow, val);+ }++ /**+ * Get a complete catalog of all varnodes read, including overlapping, subregs, etc.+ *+ * @return the set of varnodes+ */+ public Set<Varnode> getVarnodesRead() {+ return state.getVarnodesRead();+ }++ /**+ * Get a complete catalog of all varnodes written, including overlapping, subregs, etc.+ *+ * @return the set of varnodes+ */+ public Set<Varnode> getVarnodesWritten() {+ return state.getVarnodesWritten();+ }++ /**+ * Get an ordered list of all values involved in the latest definition of the given varnode.+ *+ * @see JitDataFlowState#getDefinitions(Varnode)+ * @param varnode the varnode whose definition(s) to retrieve+ * @return the list of values+ */+ public List<JitVal> getOutput(Varnode varnode) {+ return state.getDefinitions(varnode);+ }++ /**+ * Get an ordered list of all values involved in the latest definition of the given register.+ *+ * @see JitDataFlowState#getDefinitions(Register)+ * @param register the register whose definition(s) to retrieve+ * @return the list of values+ */+ public List<JitVal> getOutput(Register register) {+ return state.getDefinitions(register);+ }++ /**+ * Get the latest definition of the given varnode, synthesizing ops is required.+ *+ * <p>+ * NOTE: May produce phi nodes that need additional inter-block analysis+ *+ * @see JitDataFlowModel#analyzeInterblock(Collection)+ * @see JitDataFlowState#getVar(AddressSpace, JitVal, int, boolean, Reason)+ * @param vn the varnode+ * @return the latest definition for the block analyzed+ */+ public JitVal getVar(Varnode vn) {+ return state.getVar(vn, Reason.EXECUTE_READ);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowExecutor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowExecutor.javanew file mode 100644index 0000000000..df7c8c1f6a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowExecutor.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.pcode.emu.jit.analysis;++import java.util.Map;+import java.util.Objects;++import ghidra.pcode.emu.jit.JitPassage.Branch;+import ghidra.pcode.emu.jit.JitPassage.IndBranch;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.*;+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++/**+ * A modification to {@link PcodeExecutor} that is specialized for the per-block data flow analysis.+ *+ * <p>+ * Normally, the p-code executor follows all of the control-flow branching, as you would expect in+ * the interpretation-based p-code emulator. For analysis, we do not intend to actually follow+ * branches. These should only ever occur at the end of a basic block, anyway.+ *+ * <p>+ * We do record the branch ops into the graph as {@link JitOp op nodes}. A conditional branch+ * naturally participates in the data flow, as it uses the definition of its predicate varnode.+ * Similarly, indirect branches use the definitions of their target varnodes. Direct branch+ * operations are also added to the use-def graph, even though they do not use any variable+ * definition. Architecturally, the code generator emits JVM bytecode from the op nodes in the+ * use-def graph. For that to work, every p-code op must be entered into it. For bookkeeping, and+ * because the code generator will need them, we look up the {@link Branch} records created by the+ * passage decoder and store them in their respective branch op nodes.+ *+ * <p>+ * This is all accomplished by overriding {@link #executeBranch(PcodeOp, PcodeFrame)} and similar+ * branch execution methods. Additionally, we override {@link #badOp(PcodeOp)} and+ * {@link #onMissingUseropDef(PcodeOp, PcodeFrame, String, PcodeUseropLibrary)}, because the+ * inherited implementations will throw exceptions. We need not throw an exception until/unless we+ * reach such bad code a run time. So, we enter them into the use-def graph as op nodes from which+ * we later generate the code to throw the exception.+ */+class JitDataFlowExecutor extends PcodeExecutor<JitVal> {+ private final JitDataFlowModel dfm;+ private final Map<PcodeOp, Branch> branches;++ /**+ * Construct an executor from the given context+ *+ * @param context the analysis context, namely to get the branches recorded by the passage+ * decoder+ * @param dfm the data-flow model whose use-def graph to populate+ * @param state the executor state, which tracks varnode definitions during execution+ */+ protected JitDataFlowExecutor(JitAnalysisContext context, JitDataFlowModel dfm,+ PcodeExecutorState<JitVal> state) {+ super(context.getLanguage(), dfm.getArithmetic(), state, Reason.EXECUTE_READ);+ this.dfm = dfm;+ this.branches = context.getPassage().getBranches();+ }++ /**+ * Record a branch or call op into the use-def graph+ *+ * <p>+ * We do not need to compute the branch target, because that op was already computed by the+ * passage decoder. Past attempts to perform that computation here failed when dealing with+ * injects and inlined p-code userops. It is much easier to let the decoder do it, because it+ * has a copy of the original p-code. That op is recorded in the {@link Branch} for this op, so+ * just look it up.+ *+ * @param op the op+ */+ protected void recordBranch(PcodeOp op) {+ Branch branch = Objects.requireNonNull(branches.get(op));+ dfm.notifyOp(new JitBranchOp(op, branch));+ }++ /**+ * Record a conditional branch op into the use-def graph+ *+ * <p>+ * While we can lookup the {@link Branch} target as in+ * {@link #executeBranch(PcodeOp, PcodeFrame)}, we must still obtain the predicate's definition+ * and use it.+ *+ * @param op the op+ */+ protected void recordConditionalBranch(PcodeOp op) {+ Branch branch = Objects.requireNonNull(branches.get(op));+ Varnode condVar = getConditionalBranchPredicate(op);+ JitVal cond = state.getVar(condVar, reason);+ dfm.notifyOp(new JitCBranchOp(op, branch, cond));+ }++ /**+ * Record an indirect branch op into the use-def graph+ *+ * <p>+ * The {@link IndBranch} will have the target decode context, but the address is dynamic. We+ * have to obtain the target varnode's definition and use it.+ *+ * @param op the op+ */+ protected void recordIndirectBranch(PcodeOp op) {+ Varnode offVar = getIndirectBranchTarget(op);+ JitVal offset = state.getVar(offVar, reason);+ IndBranch branch = (IndBranch) Objects.requireNonNull(branches.get(op));+ dfm.notifyOp(new JitBranchIndOp(op, offset, branch));+ }++ @Override+ public void executeBranch(PcodeOp op, PcodeFrame frame) {+ recordBranch(op);+ }++ @Override+ public void executeConditionalBranch(PcodeOp op, PcodeFrame frame) {+ recordConditionalBranch(op);+ }++ @Override+ public void executeIndirectBranch(PcodeOp op, PcodeFrame frame) {+ recordIndirectBranch(op);+ }++ @Override+ public void executeCall(PcodeOp op, PcodeFrame frame, PcodeUseropLibrary<JitVal> library) {+ recordBranch(op);+ }++ @Override+ public void executeIndirectCall(PcodeOp op, PcodeFrame frame) {+ recordIndirectBranch(op);+ }++ @Override+ public void executeReturn(PcodeOp op, PcodeFrame frame) {+ recordIndirectBranch(op);+ }++ @Override+ protected void badOp(PcodeOp op) {+ dfm.notifyOp(JitOp.stubOp(op));+ }++ @Override+ protected void onMissingUseropDef(PcodeOp op, PcodeFrame frame, String opName,+ PcodeUseropLibrary<JitVal> library) {+ dfm.notifyOp(new JitCallOtherMissingOp(op, opName));+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowModel.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowModel.javanew file mode 100644index 0000000000..4c9dab1b9f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowModel.java@@ -0,0 +1,647 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.io.*;+import java.util.*;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.lifecycle.Internal;+import ghidra.pcode.emu.jit.JitCompiler;+import ghidra.pcode.emu.jit.JitCompiler.Diag;+import ghidra.pcode.emu.jit.JitPassage;+import ghidra.pcode.emu.jit.JitPassage.DecodedPcodeOp;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.*;+import ghidra.pcode.emu.jit.var.JitVal.ValUse;+import ghidra.pcode.exec.PcodeExecutorState;+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;+import ghidra.pcode.exec.PcodeProgram;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Register;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++/**+ * The data flow analysis for JIT-accelerated emulation.+ *+ * <p>+ * This implements the Data Flow Analysis phase of the {@link JitCompiler}. The result is a use-def+ * graph. The graph follows Static Single Assignment (SSA) form, in that each definition of a+ * variable, even if it's at the same address as a previous definition, is given a unique+ * identifier. The graph is bipartite with {@link JitOp ops} on one side and {@link JitVal values}+ * on the other. Please node the distinction between a <em>varnode</em> and a <em>variable</em> in+ * this context. A <em>varnode</em> refers to the address and size in the machine's state. For+ * better or for worse, this is often referred to as a "variable" in other contexts. A+ * <em>variable</em> in the SSA sense is a unique "instance" of a varnode with precisely one+ * <em>definition</em>. Consider the following x86 assembly:+ *+ * <pre>+ * MOV RAX, qword ptr [...]+ * ADD RAX, RDX+ * MOV qword ptr [...], RAX+ * </pre>+ *+ * <p>+ * Ignoring RAM, there are two varnodes at play, named for the registers they represent: {@code RAX}+ * and {@code RDX}. However, there are three variables. The first is an instance of {@code RAX},+ * defined by the first {@code MOV} instruction. The second is an instance of {@code RDX}, which is+ * implicitly defined as an input to the passage. The third is another instance of of {@code RAX},+ * defined by the {@code ADD} instruction. These could be given unique names+ * {@code RAX}<sub>1</sub>, {@code RDX}<sub>in</sub>, and {@code RAX}<sub>2</sub>, respectively.+ * Thus, the {@code ADD} instruction uses {@code RAX}<sub>1</sub> and {@code RDX}<sub>in</sub>, to+ * define {@code RAX}<sub>2</sub>. The last {@code MOV} instruction uses {@code RAX}<sub>2</sub>. If+ * we plot each instruction and variable in a graph, drawing edges for each use and definition, we+ * get a use-def graph.+ *+ * <p>+ * Our analysis produces a use-def graph for the passage's p-code (not instructions) in two steps:+ * First, we analyze each basic block independently. There are a lot of nuts and bolts in the+ * implementation, but the analysis is achieved by straightforward interpretation of each block's+ * p-code ops. Second, we connect the blocks' use-def graphs together using phi nodes where+ * appropriate, according to the control flow.+ *+ * <h2>Intra-block analysis</h2>+ * <p>+ * For each block, we create a p-code interpreter consisting of a {@link JitDataFlowState} and+ * {@link JitDataFlowExecutor}. Both are given this model's {@link JitDataFlowArithmetic}, which+ * populates the use-def graph. We then feed the block's p-code into the executor. The block gets a+ * fresh {@link JitDataFlowState}, so that its result has no dependency on the interpretation of any+ * other block, except in the numbering of variable identifiers; those must be unique across the+ * model.+ *+ * <p>+ * During interpretation, varnode accesses generate value nodes. When a constant varnode is+ * accessed, it simply creates a {@link JitConstVal}. When an op produces an output, it generates a+ * {@link JitOutVar} and places it into the interpreter's {@link JitDataFlowState state} for its+ * varnode. When a varnode is read, the interpreter examines its state for the last definition. If+ * one is found, the variable is returned, its use noted, and nothing new is generated. Otherwise, a+ * {@link JitMissingVar} is generated. Note that the interpreter does not track memory variables in+ * its state, because the JIT translator does not seek to optimize these. At run time, such accesses+ * will affect the emulator's state immediately. Registers and Sleigh uniques, on the other hand,+ * are allocated as JVM locals, so we must know how they are used and defined. Direct memory+ * accesses generate {@link JitDirectMemoryVar} and {@link JitMemoryOutVar}. Indirect memory+ * accesses are denoted by the {@link JitLoadOp load} and {@link JitStoreOp store} op nodes, not as+ * variables. There is a dummy {@link JitIndirectMemoryVar} singleton, so that the state can return+ * something when the memory address is not fixed.+ *+ * <h2>Inter-block analysis</h2>+ * <p>+ * Up to this point, each block's use-def sub-graph is disconnected from the others'. We define each+ * {@link JitMissingVar missing} variable generated during block interpretation as a {@link JitPhiOp+ * phi} op. A phi op is said to belong to the block that generated the missing variable. We seek+ * options for the phi op by examining the block's inward flows. For each source block, we check the+ * most recent definition of the sought varnode. If one is present, the option is added to the phi+ * op. Otherwise, we create an option by generating another phi op and taking its output. The new+ * phi op belongs to the source block, and we recurse to seek its options. If a cycle is+ * encountered, or we encounter a block with no inward flows, we do not recurse. An+ * {@link JitInputVar input} variable is generated whenever we encounter a passage entry, indicating+ * the variable could be defined outside the passage.+ *+ * <p>+ * Note that the resulting phi ops may not adhere precisely to the formal definition of <em>phi+ * node</em>. A phi op may have only one option. The recursive part of the option seeking algorithm+ * generates chains of phi ops such that an option must come from an immediately upstream block,+ * even if that block does not offer a direct definition. This may produce long chains when a+ * varnode use is several block flows removed from a possible definition. We had considered+ * simplifying/removing single-option phi ops afterward, but we found it too onerous, and the output+ * bytecode is not improved. We do not generate bytecode for phi ops; they are synthetic and only+ * used for analysis.+ */+public class JitDataFlowModel {++ /**+ * Create a list of {@link JitTypeBehavior#ANY ANY}s having the same size as the list of values.+ *+ * @param inVals the values, e.g., of each parameter to a userop+ * @return the list+ */+ static List<JitTypeBehavior> allAny(List<JitVal> inVals) {+ return inVals.stream().map(v -> JitTypeBehavior.ANY).toList();+ }++ private final JitAnalysisContext context;+ private final JitControlFlowModel cfm;++ private final JitPassage passage;+ private final SleighLanguage language;++ private final JitDataFlowArithmetic arithmetic;+ private final JitDataFlowUseropLibrary library;++ private int nextVarId = 1;+ private final List<JitPhiOp> phiNodes = new ArrayList<>();+ private final List<JitSyntheticOp> synthNodes = new ArrayList<>();+ private final Map<PcodeOp, JitOp> ops = new HashMap<>();++ private final Map<JitBlock, JitDataFlowBlockAnalyzer> analyzers = new HashMap<>();+ final SequencedSet<JitPhiOp> phiQueue = new LinkedHashSet<>();++ /**+ * Construct the data flow model.+ *+ * <p>+ * Analysis is performed as part of constructing the model.+ *+ * @param context the analysis context+ * @param cfm the control flow model+ */+ public JitDataFlowModel(JitAnalysisContext context, JitControlFlowModel cfm) {+ this.context = context;+ this.cfm = cfm;++ this.passage = context.getPassage();+ this.language = context.getLanguage();++ this.arithmetic = new JitDataFlowArithmetic(context, this);+ this.library = new JitDataFlowUseropLibrary(context, this);++ analyze();+ }++ /**+ * Get the model's arithmetic that places p-code ops into the use-def graph+ *+ * @return the arithmetic+ */+ public JitDataFlowArithmetic getArithmetic() {+ return arithmetic;+ }++ /**+ * Get a wrapper library that places userop calls into the use-def graph+ *+ * @return the library+ */+ public JitDataFlowUseropLibrary getLibrary() {+ return library;+ }++ /**+ * Get all the phi nodes in the use-def graph.+ *+ * @return the list of phi nodes+ */+ public List<JitPhiOp> phiNodes() {+ return phiNodes;+ }++ /**+ * Get all the synthetic op nodes in the use-def graph.+ *+ * @return the list of synthetic op nodes+ */+ public List<JitSyntheticOp> synthNodes() {+ return synthNodes;+ }++ /**+ * Generate a unique variable identifier+ *+ * @return the generated identifier+ */+ private int nextVarId() {+ return nextVarId++;+ }++ /**+ * Generate a new op output variable for eventual placement in the use-def graph+ *+ * @param out the varnode describing the corresponding {@link PcodeOp}'s+ * {@link PcodeOp#getOutput() output}.+ * @return the generated variable+ * @see JitDataFlowModel+ */+ public JitOutVar generateOutVar(Varnode out) {+ if (out.isRegister() || out.isUnique()) {+ return new JitLocalOutVar(nextVarId(), out);+ }+ return new JitMemoryOutVar(nextVarId(), out);+ }++ /**+ * Generate a variable representing a direct memory access+ *+ * @param vn the varnode, which ought to be neither register nor unique+ * @return the variable+ */+ public JitDirectMemoryVar generateDirectMemoryVar(Varnode vn) {+ return new JitDirectMemoryVar(nextVarId(), vn);+ }++ /**+ * Generate a variable representing an indirect memory access+ *+ * @param space the address space containing the variable, which out to be neither register nor+ * unique+ * @param offset another variable describing the (dynamic) offset of the variable in the given+ * space+ * @param size the number of bytes in the variable+ * @param quantize true if the offset should be quantized (as in+ * {@link PcodeExecutorState#getVar(AddressSpace, Object, int, boolean, Reason)+ * getVar}).+ * @return the variable+ * @see JitIndirectMemoryVar+ * @see JitLoadOp+ * @see JitStoreOp+ * @implNote because the load and store ops already encode these details (except maybe+ * {@code quantize}), this just returns a dummy instance.+ */+ public JitIndirectMemoryVar generateIndirectMemoryVar(AddressSpace space, JitVal offset,+ int size, boolean quantize) {+ return JitIndirectMemoryVar.INSTANCE;+ }++ /**+ * Add the given {@link JitOp} to the use-def graph+ *+ * @param <T> the type of the node+ * @param op the op+ * @return the same op+ * @see JitDataFlowModel+ */+ public <T extends JitOp> T notifyOp(T op) {+ op.link();+ if (op instanceof JitPhiOp phi) {+ phiNodes.add(phi);+ synthNodes.add(phi);+ }+ else if (op instanceof JitSyntheticOp synth) {+ // Prevent call of .op()+ synthNodes.add(synth);+ }+ else {+ ops.put(Objects.requireNonNull(op.op()), op);+ }+ return op;+ }++ /**+ * Get the use-def op node for the given p-code op+ *+ * <p>+ * NOTE: When used in testing, if the passage is manufactured from a {@link PcodeProgram}, the+ * decoder will re-write the p-code ops as {@link DecodedPcodeOp}s. Be sure to pass an op to+ * this method that comes from the resulting {@link JitPassage}, not the original program, or+ * else this method will certainly return {@code null}.+ *+ * @param op the p-code op from the source passage+ * @return the node from the use-def graph, if present, or {@code null}+ */+ public JitOp getJitOp(PcodeOp op) {+ return ops.get(op);+ }++ /**+ * Get all the op nodes, whether from a p-code op or synthesized.+ *+ * @return the ops.+ * @see JitDataFlowModel+ */+ Collection<JitOp> allOps() {+ Set<JitOp> all = new LinkedHashSet<>();+ all.addAll(ops.values());+ all.addAll(synthNodes);+ return all;+ }++ /**+ * An upward graph traversal for collecting all values in the use-def graph.+ *+ * @see JitAnalysisContext#allValues()+ * @see JitAnalysisContext#allValuesSorted()+ */+ protected class ValCollector extends HashSet<JitVal> implements JitOpUpwardVisitor {+ public ValCollector() {+ for (PcodeOp op : passage.getCode()) {+ JitOp jitOp = getJitOp(op);+ visitOp(jitOp);+ if (jitOp instanceof JitDefOp defOp) {+ visitVal(defOp.out());+ }+ }+ }++ @Override+ public void visitVal(JitVal v) {+ if (!add(v)) {+ return;+ }+ JitOpUpwardVisitor.super.visitVal(v);+ }+ }++ /**+ * Get all values (and variables) in the use-def graph+ *+ * @return the set of values+ */+ public Set<JitVal> allValues() {+ return new ValCollector();+ }++ /**+ * Get the sort key of a given value. Variables get their ID, constants get -2.+ *+ * @param v the value+ * @return the sort key+ */+ int idOfVal(JitVal v) {+ return v instanceof JitVar vv ? vv.id() : -2;+ }++ /**+ * Same as {@link #allValues()}, but sorted by ID with constants at the top+ *+ * @return the list of values+ */+ public List<JitVal> allValuesSorted() {+ return allValues().stream().sorted(Comparator.comparing(this::idOfVal)).toList();+ }++ protected JitDataFlowBlockAnalyzer getOrCreateAnalyzer(JitBlock block) {+ return analyzers.computeIfAbsent(block,+ b -> new JitDataFlowBlockAnalyzer(context, this, b));+ }++ /**+ * Get the per-block data flow analyzer for the given basic block+ *+ * @param block the block+ * @return the analyzer+ */+ public JitDataFlowBlockAnalyzer getAnalyzer(JitBlock block) {+ return analyzers.get(block);+ }++ /**+ * Construct the use-def graph+ */+ protected void analyze() {+ /**+ * Just visit the blocks in any order. Use input placeholders and glue them together+ * afterward.+ *+ * I considered unrolling each loop at least once to avoid certain multi-equals stuff. I+ * don't think that'll be necessary. If we pre-load the registers into local variables, then+ * we'll always be reading and writing to those locals, so no worries about multi-equals.+ */+ for (JitBlock block : cfm.getBlocks()) {+ getOrCreateAnalyzer(block).doIntrablock();+ }++ /**+ * Now, work out the inter-block flows.+ */+ analyzeInterblock(phiNodes);+ }++ /**+ * Perform the inter-block analysis.+ *+ * <p>+ * This is called by {@link #analyze()} after intra-block analysis.+ *+ * @implNote This may be called a second time by the {@link JitOpUseModel}, since a variable's+ * definition may be several block flows removed from its retirement, which counts as+ * a use.+ *+ * @see JitVarScopeModel+ * @see JitOpUseModel+ */+ void analyzeInterblock(Collection<JitPhiOp> phis) {+ phiQueue.addAll(phis);+ while (!phiQueue.isEmpty()) {+ JitPhiOp phi = phiQueue.removeFirst();+ JitDataFlowBlockAnalyzer analyzer = getOrCreateAnalyzer(phi.block());+ analyzer.fillPhiFromDeps(phi);+ }+ }++ /**+ * For testing: Get the value(s) in (or intersecting) the given register defined by the given+ * block+ *+ * @param block the block whose p-code to consider+ * @param register the register to examine+ * @return the list of values (usually variables)+ */+ @Internal+ List<JitVal> getOutput(JitBlock block, Register register) {+ return getAnalyzer(block).getOutput(register);+ }++ /**+ * For diagnostics: Dump the analysis result to stderr+ *+ * @see Diag#PRINT_DFM+ */+ public void dumpResult() {+ System.err.println("STAGE: DataFlow");+ for (JitBlock block : cfm.getBlocks()) {+ System.err.println(" Block: " + block);+ for (PcodeOp op : block.getCode()) {+ System.err.println(" %s: %s".formatted(op.getSeqnum(), getJitOp(op)));+ }+ }+ }++ /**+ * For diagnostics: Dump the synthetic ops to stderr+ *+ * @see Diag#PRINT_SYNTH+ */+ public void dumpSynth() {+ System.err.println("SYNTHETIC OPS");+ for (JitSyntheticOp synthOp : synthNodes) {+ System.err.println(" " + synthOp);+ }+ }++ /**+ * A diagnostic tool for visualizing the use-def graph.+ *+ * <p>+ * NOTE: This is only as complete as it needed to be for me to diagnose whatever issue I was+ * having at the time.+ *+ * @see JitAnalysisContext#exportGraphviz(File)+ */+ protected class GraphvizExporter implements JitOpUpwardVisitor {+ final PrintWriter out;+ final Set<JitVar> vars = new HashSet<>();+ final Set<JitOp> ops = new HashSet<>();++ public GraphvizExporter(File outFile) {+ try (FileOutputStream outStream = new FileOutputStream(outFile);+ PrintWriter out = new PrintWriter(outStream)) {+ this.out = out;+ out.println("digraph DataFlow {");+ for (PcodeOp op : passage.getCode()) {+ JitOp jitOp = getJitOp(op);+ if (jitOp instanceof JitDefOp defOp) {+ // Because of direction of visit+ visitVal(defOp.out());+ }+ else {+ visitOp(jitOp);+ }+ }+ out.println("}");+ }+ catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ String opLabel(JitOp op) {+ return switch (op) {+ case null -> "null";+ //case JitSyntheticOp synth -> synth.getClass().getSimpleName();+ //default -> op.op().toString();+ default -> "%s\n%x".formatted(op.getClass().getSimpleName(),+ System.identityHashCode(op));+ };+ }++ @Override+ public void visitOp(JitOp op) {+ if (!ops.add(op)) {+ return;+ }+ out.println("""+ "op%x" [+ label = "%s"+ shape = "ellipse"+ ];+ """.formatted(+ System.identityHashCode(op),+ opLabel(op)));++ if (op == null) {+ return;+ }++ int i = 0;+ for (JitVal input : op.inputs()) {+ i++;+ if (input instanceof JitVar iv) {+ out.println("""+ "var%d" -> "op%x" [+ headlabel = "[%d]"+ ];+ """.formatted(+ iv.id(),+ System.identityHashCode(op),+ i));+ }+ else {+ out.println("""+ "val%x" -> "op%x" [+ headlabel = "[%d]"+ ];+ """.formatted(+ System.identityHashCode(input),+ System.identityHashCode(op),+ i));+ }+ }++ if (op instanceof JitDefOp defOp) {+ out.println("""+ "op%x" -> "var%d" [+ taillabel = "out"+ ];+ """.formatted(+ System.identityHashCode(op),+ defOp.out().id()));+ }++ JitOpUpwardVisitor.super.visitOp(op);+ }++ String varLabel(JitVar v) {+ return switch (v) {+ case JitVarnodeVar vv -> "%s\n%d".formatted(vv.varnode().toString(language),+ v.id());+ default -> throw new AssertionError();+ };+ }++ @Override+ public void visitVal(JitVal v) {+ final String name;+ final String label;+ if (v instanceof JitVar vv) {+ if (!vars.add(vv)) {+ return;+ }+ name = "var%d".formatted(vv.id());+ label = varLabel(vv);+ }+ else if (v instanceof JitConstVal cv) {+ name = "val%x".formatted(System.identityHashCode(cv));+ label = cv.value().toString();+ }+ else {+ throw new AssertionError();+ }++ out.println("""+ "%s" [+ label = "%s"+ shape = "box"+ ];+ """.formatted(name, label));+ for (ValUse use : v.uses()) {+ out.println("""+ "%s" -> "op%x" [+ dir = "back"+ arrowhead = "none"+ arrowtail = "crow"+ taillabel = "use"+ ];+ """.formatted(name, System.identityHashCode(use.op())));+ }+ if (v instanceof JitOutVar ov) {+ out.println("""+ "op%x" -> "%s" [+ dir = "back"+ arrowhead = "none"+ arrowtail = "crow"+ taillabel = "def"+ ];+ """.formatted(System.identityHashCode(ov.definition()), name));+ }++ JitOpUpwardVisitor.super.visitVal(v);+ }+ }++ /**+ * Generate a graphviz .dot file to visualize the use-def graph.+ *+ * <p>+ * <b>WARNING:</b> This is an internal diagnostic that is only as complete as it needed to be.+ *+ * @param file the output file+ */+ @Internal // for diagnostics+ public void exportGraphviz(File file) {+ new GraphvizExporter(file);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowState.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowState.javanew file mode 100644index 0000000000..df3ebe2a44--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowState.java@@ -0,0 +1,572 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.util.*;+import java.util.Map.Entry;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.*;+import ghidra.pcode.exec.PcodeArithmetic.Purpose;+import ghidra.pcode.exec.PcodeExecutorState;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Language;+import ghidra.program.model.lang.Register;+import ghidra.program.model.mem.MemBuffer;+import ghidra.program.model.pcode.Varnode;+import ghidra.util.Msg;++/**+ * An implementation of {@link PcodeExecutorState} for per-block data flow interpretation+ *+ * <p>+ * In p-code interpretation, this interface's purpose is to store the current value of varnodes in+ * the emulation/interpretation state. Here we implement it using {@code T:=}{@link JitVal}, and+ * track the latest variable definition of vanodes in the data flow interpretation. The adaptation+ * is fairly straightforward, except when varnode accesses do not match their latest definitions+ * exactly, e.g., an access of {@code EAX} when the latest definition is for {@code RAX}. Thus, this+ * state object may synthesize {@link JitSynthSubPieceOp subpiece} and {@link JitCatenateOp+ * catenate} ops to model the "off-cut" use of one or more such definitions. Additionally, in+ * preparation for inter-block data flow analysis, when no definition is present for a varnode (or+ * part of a varnode) access, this state will synthesize {@link JitPhiOp phi} ops. See+ * {@link #setVar(AddressSpace, JitVal, int, boolean, JitVal) setVar} and+ * {@link #getVar(AddressSpace, JitVal, int, boolean, Reason) getVar} for details.+ *+ * <p>+ * This state only serves to analyze data flow through register and unique variables. Because we+ * know these are only accessible to the thread, we stand to save much execution time by bypassing+ * the {@link JitBytesPcodeExecutorState} at run time. We can accomplish this by mapping these+ * variables to suitable JVM local variables. Thus, we have one map of entries for register space+ * and another for unique space. Accesses to other spaces do not mutate or read from either of those+ * maps, but this class may generate a suitable {@link JitVal} for the use-def graph.+ */+public class JitDataFlowState implements PcodeExecutorState<JitVal> {++ /**+ * A minimal data flow machine state that can be captured by a {@link JitCallOtherOpIf}.+ */+ public class MiniDFState {+ private final NavigableMap<Long, JitVal> uniqMap;+ private final NavigableMap<Long, JitVal> regMap;++ MiniDFState() {+ this(new TreeMap<>(), new TreeMap<>());+ }++ MiniDFState(NavigableMap<Long, JitVal> uniqMap, NavigableMap<Long, JitVal> regMap) {+ this.uniqMap = uniqMap;+ this.regMap = regMap;+ }++ NavigableMap<Long, JitVal> mapFor(AddressSpace space) {+ if (space.isUniqueSpace()) {+ return uniqMap;+ }+ if (space.isRegisterSpace()) {+ return regMap;+ }+ return null;+ }++ /**+ * Compute the upper (exclusive) offset of a given definition entry+ *+ * @param entry the entry+ * @return the upper offset, exclusive+ */+ protected static long endOf(Entry<Long, JitVal> entry) {+ return entry.getKey() + entry.getValue().size();+ }++ /**+ * Clear all definition entries in the given per-space map for the given varnode+ *+ * <p>+ * Any entries completely covered by the given varnode (including an exact match) are+ * removed from the map. Those partially covered will be replaced by subpieces of their+ * former selves such that no part within the cleared varnode remains defined.+ *+ * @param map the map to modify+ * @param varnode the varnode whose definitions to remove+ */+ protected void doClear(NavigableMap<Long, JitVal> map, Varnode varnode) {+ AddressSpace space = varnode.getAddress().getAddressSpace();+ long offset = varnode.getOffset();+ int size = varnode.getSize();++ Entry<Long, JitVal> truncLeftEntry = map.lowerEntry(offset);+ if (truncLeftEntry != null && endOf(truncLeftEntry) <= offset) {+ truncLeftEntry = null;+ }+ /**+ * Collect entry at both ends before removal, in case the clear is cutting a hole in the+ * middle of one entry. I.e., could be the same entry at both ends.+ */+ long end = offset + size;+ Entry<Long, JitVal> truncRightEntry = map.lowerEntry(end);+ if (truncRightEntry != null && endOf(truncRightEntry) <= end) {+ truncRightEntry = null;+ }++ /**+ * Replace the right entry first. If it's the same entry as the left, and we remove by+ * key, then we might remove the replacement on the left, if it were done first.+ */+ if (truncRightEntry != null) {+ long entStart = truncRightEntry.getKey();+ map.remove(entStart);+ int shave = (int) (endOf(truncRightEntry) - end);+ JitVal entVal = truncRightEntry.getValue();+ Varnode truncVn = new Varnode(space.getAddress(entStart), entVal.size());+ JitVal truncVal = arithmetic.truncFromLeft(truncVn, shave, entVal);+ map.put(end, truncVal);+ }++ if (truncLeftEntry != null) {+ long entStart = truncLeftEntry.getKey();+ map.remove(entStart);+ int shave = (int) (endOf(truncLeftEntry) - offset);+ JitVal entVal = truncLeftEntry.getValue();+ Varnode truncVn = new Varnode(space.getAddress(entStart), entVal.size());+ JitVal truncVal = arithmetic.truncFromRight(truncVn, shave, entVal);+ map.put(truncLeftEntry.getKey(), truncVal);+ }++ /**+ * At this point, no part of the ends should be in the key range [start,end), so clear+ * that submap+ */+ map.subMap(offset, end).clear();+ }++ /**+ * The implementation of {@link #set(Varnode, JitVal)} for a given address space+ *+ * @param map the map to modify for the given space+ * @param varnode the varnode whose value to define+ * @param val the varnode's new definition+ */+ protected void doSet(NavigableMap<Long, JitVal> map, Varnode varnode, JitVal val) {+ doClear(map, varnode);++ if (val instanceof JitOutVar out) {+ if (out.definition() instanceof JitCatenateOp cat) {+ int cursor = 0;+ for (JitVal part : cat.iterParts(language.isBigEndian())) {+ /**+ * NOTE: Do not filter phi nodes here. Perhaps if we're certain its for the+ * same varnode we could, but not sure there's any benefit to doing so.+ * TODO: Determine whether there's any benefit. NOTE: While the phi nodes+ * are linked after the fact, they are generated (but empty) during p-code+ * interpretation.+ */+ map.put(varnode.getOffset() + cursor, part);+ cursor += part.size();+ }+ /**+ * Can't necessarily unlink cat here. Something else may use it. May need to+ * prune afterward.+ */+ return;+ }+ }++ map.put(varnode.getOffset(), val);+ }++ /**+ * Set one or more definition entries in the given map for the given varnode to the given+ * value+ *+ * <p>+ * Ordinary, this just sets the one varnode to the given value; however, if the given value+ * is the output of a {@link JitCatenateOp catenation}, then each input part is entered into+ * the map separately, and the synthetic catenation dropped. The behavior avoids nested+ * catenations.+ *+ * @param varnode the varnode+ * @param val the value+ */+ public void set(Varnode varnode, JitVal val) {+ var map = mapFor(varnode.getAddress().getAddressSpace());+ if (map == null) {+ return;+ }+ doSet(map, varnode, val);+ }++ /**+ * The implementation of {@link #getDefinitions(AddressSpace, long, int)} for a given+ * address space+ *+ * @param map the map of values for the given space+ * @param space the address space+ * @param offset the offset within the space+ * @param size the size of the varnode+ * @return the list of values+ */+ protected List<JitVal> doGetDefinitions(NavigableMap<Long, JitVal> map, AddressSpace space,+ long offset, int size) {+ List<JitVal> result = new ArrayList<>();+ Entry<Long, JitVal> preEntry = map.lowerEntry(offset);+ long cursor = offset;+ if (preEntry != null) {+ if (endOf(preEntry) > offset) {+ JitVal preVal = preEntry.getValue();+ Varnode preVn = new Varnode(space.getAddress(preEntry.getKey()), preVal.size());+ int shave = (int) (offset - preEntry.getKey());+ JitVal truncVal = arithmetic.truncFromLeft(preVn, shave, preVal);+ cursor = endOf(preEntry);+ result.add(truncVal);+ }+ }+ long end = offset + size;+ for (Entry<Long, JitVal> entry : map.subMap(offset, end).entrySet()) {+ if (entry.getKey() > cursor) {+ result.add(new JitMissingVar(+ new Varnode(space.getAddress(cursor), (int) (entry.getKey() - cursor))));+ }+ if (endOf(entry) > end) {+ JitVal postVal = entry.getValue();+ Varnode postVn = new Varnode(space.getAddress(entry.getKey()), postVal.size());+ int shave = (int) (endOf(entry) - end);+ JitVal truncVal = arithmetic.truncFromRight(postVn, shave, postVal);+ cursor = end;+ result.add(truncVal);+ break;+ }+ result.add(entry.getValue());+ cursor = endOf(entry);+ }+ if (end > cursor) {+ result.add(+ new JitMissingVar(new Varnode(space.getAddress(cursor), (int) (end - cursor))));+ }+ assert !result.isEmpty();+ return result;+ }++ /**+ * Get an ordered list of all values involved in the latest definition of the given varnode.+ *+ * <p>+ * In the simplest case, the list consists of exactly one SSA variable whose varnode exactly+ * matches that requested. In other cases, e.g., when only a subregister is defined, the+ * list may have several entries, some of which may be {@link JitMissingVar missing}.+ *+ * <p>+ * The list is ordered according to machine endianness. That is for little endian, the+ * values are ordered from least to most significant parts of the varnode defined. This is+ * congruent with how {@link JitDataFlowArithmetic#catenate(Varnode, List)} expects parts to+ * be listed.+ *+ * @param space the address space of the varnode+ * @param offset the offset of the varnode+ * @param size the size in bytes of the varnode+ * @return the list of values+ */+ public List<JitVal> getDefinitions(AddressSpace space, long offset, int size) {+ var map = mapFor(space);+ if (map == null) {+ throw new AssertionError("What is this space?: " + space);+ }+ return doGetDefinitions(map, space, offset, size);+ }++ /**+ * Get an ordered list of all values involved in the latest definition of the given varnode.+ *+ * @see #getDefinitions(AddressSpace, long, int)+ * @param varnode the varnode whose definitions to retrieve+ * @return the list of values+ */+ public List<JitVal> getDefinitions(Varnode varnode) {+ AddressSpace space = varnode.getAddress().getAddressSpace();+ return getDefinitions(space, varnode.getOffset(), varnode.getSize());+ }++ /**+ * Get an ordered list of all values involved in the latest definition of the given varnode.+ *+ * @see #getDefinitions(AddressSpace, long, int)+ * @param register the register whose definitions to retrieve+ * @return the list of values+ */+ public List<JitVal> getDefinitions(Register register) {+ return getDefinitions(register.getAddressSpace(), register.getOffset(),+ register.getNumBytes());+ }++ /**+ * Replace missing variables with phi nodes, mutating the given list in place+ *+ * @param defs the definitions+ * @return the same list, modified+ */+ protected List<JitVal> generatePhis(List<JitVal> defs, Collection<JitPhiOp> phiQueue) {+ int n = defs.size();+ for (int i = 0; i < n; i++) {+ JitVal v = defs.get(i);+ if (v instanceof JitMissingVar missing) {+ JitPhiOp phi = missing.generatePhi(dfm, block);+ if (phiQueue != null) {+ phiQueue.add(phi);+ }+ defs.set(i, phi.out());+ set(missing.varnode(), phi.out());+ }+ }+ return defs;+ }++ /**+ * Get the value of the given varnode+ *+ * <p>+ * This is the implementation of+ * {@link JitDataFlowState#getVar(AddressSpace, JitVal, int, boolean, Reason)}, but only for+ * uniques and registers.+ *+ * @param varnode the varnode+ * @return the value+ */+ public JitVal getVar(Varnode varnode) {+ List<JitVal> defs = generatePhis(getDefinitions(varnode), null);+ if (defs.size() == 1) {+ return defs.get(0);+ }+ return arithmetic.catenate(varnode, defs);+ }++ /**+ * Copy this mini state+ *+ * @return the copy+ */+ public MiniDFState copy() {+ return new MiniDFState(new TreeMap<>(uniqMap), new TreeMap<>(regMap));+ }+ }++ private final JitDataFlowModel dfm;+ private final JitBlock block;+ private final Language language;+ private final JitDataFlowArithmetic arithmetic;++ private final MiniDFState mini = new MiniDFState();++ private final Set<Varnode> varnodesRead = new HashSet<>();+ private final Set<Varnode> varnodesWritten = new HashSet<>();++ /**+ * Construct a state+ *+ * @param context the analysis context+ * @param dfm the data flow model whose use-def graph to populate+ * @param block the block being analyzed (to which generated phi ops belong)+ */+ JitDataFlowState(JitAnalysisContext context, JitDataFlowModel dfm, JitBlock block) {+ this.dfm = dfm;+ this.block = block;++ this.language = context.getLanguage();+ this.arithmetic = dfm.getArithmetic();+ }++ @Override+ public Language getLanguage() {+ return language;+ }++ @Override+ public JitDataFlowArithmetic getArithmetic() {+ return arithmetic;+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This and {@link #getVar(AddressSpace, JitVal, int, boolean, Reason)} are where we connect the+ * interpretation to the maps of definitions we keep in this state. We examine the varnode's+ * type first. We can't write to a constant, and that shouldn't be allowed anyway, so we warn if+ * we observe that. We'll ignore any indirect writes, because those are denoted by+ * {@link JitStoreOp store} ops. We also don't do much here with direct writes. The writes to+ * such variables are handled by {@link JitMemoryOutVar}. Such output variables are actually+ * passed in as {@code val} here, but need only be stored in a map if they are register or+ * unique variables.+ */+ @Override+ public void setVar(AddressSpace space, JitVal offset, int size, boolean quantize,+ JitVal val) {+ /**+ * We use this only to log possible storage bypasses. All uniques will be bypassed.+ * Registers must be written, but it is safe to bypass subsequent loads. Actually, perhaps+ * with a pre-load of register values and a try-finally to write them, we can optimize+ * register access, too. Might also make sense to do that for uniques, just for debugging+ * purposes.+ *+ * Memory must be written. Unless we can determine for sure the memory is non-volatile, we+ * must presume volatile, so no bypassing is allowed. TODO: We might consider assuming+ * stack-based accesses are non-volatile, but I'm not sure that is appropriate either.+ * Technically one thread may launch another, providing a ref to a stack variable it knows+ * will live for the entire thread's life.+ */+ if (space.isConstantSpace()) {+ Msg.warn(this, "Witnessed write to constant space! Ignoring.");+ return;+ }+ if (!(offset instanceof JitConstVal c)) {+ // Don't attempt bypass for any indirect memory access+ return;+ }++ // NB. There should never be need to quantize in regs or uniqs.+ Varnode varnode = new Varnode(space.getAddress(c.value().longValue()), size);+ varnodesWritten.add(varnode);++ mini.set(varnode, val);+ }++ /**+ * Get an ordered list of all values involved in the latest definition of the given varnode.+ *+ * @see MiniDFState#getDefinitions(AddressSpace, long, int)+ * @param varnode the varnode whose definitions to retrieve+ * @return the list of values+ */+ public List<JitVal> getDefinitions(Varnode varnode) {+ return mini.getDefinitions(varnode);+ }++ /**+ * Get an ordered list of all values involved in the latest definition of the given varnode.+ *+ * @see MiniDFState#getDefinitions(AddressSpace, long, int)+ * @param register the register whose definitions to retrieve+ * @return the list of values+ */+ public List<JitVal> getDefinitions(Register register) {+ return mini.getDefinitions(register);+ }++ /**+ * Replace missing variables with phi nodes, mutating the given list in place+ *+ * @param defs the definitions+ * @return the same list, modified+ */+ List<JitVal> generatePhis(List<JitVal> defs, SequencedSet<JitPhiOp> phiQueue) {+ return mini.generatePhis(defs, phiQueue);+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This and {@link #setVar(AddressSpace, JitVal, int, boolean, JitVal)} are where we connect the+ * interpretation to the maps of definitions we keep in this state. We examine the varnode's+ * type first. If it's a constant or memory variable, it just returns the appropriate+ * {@link JitConstVal}, {@link JitDirectMemoryVar}, or {@link JitIndirectMemoryVar}. If it's a+ * register or unique, then we retrieve the latest definition(s) as in+ * {@link MiniDFState#getDefinitions(AddressSpace, long, int)}. In the simple case of an exact+ * definition, we return it. Otherwise, this synthesizes the appropriate op(s), enters them into+ * the use-def graph, and returns the final output.+ */+ @Override+ public JitVal getVar(AddressSpace space, JitVal offset, int size, boolean quantize,+ Reason reason) {+ if (space.isConstantSpace()) {+ if (!(offset instanceof JitConstVal c)) {+ throw new AssertionError("Non-constant constant?");+ }+ if (c.size() == size) {+ return offset;+ }+ return new JitConstVal(size, c.value());+ }+ if (space.isMemorySpace()) {+ if (offset instanceof JitConstVal c) {+ Varnode vn = new Varnode(space.getAddress(c.value().longValue()), size);+ return dfm.generateDirectMemoryVar(vn);+ }+ return dfm.generateIndirectMemoryVar(space, offset, size, quantize);+ }+ if (!(offset instanceof JitConstVal c)) {+ throw new AssertionError("Indirect non-memory access?");+ }++ Varnode varnode = new Varnode(space.getAddress(c.value().longValue()), size);+ varnodesRead.add(varnode);++ return mini.getVar(varnode);+ }++ @Override+ public Map<Register, JitVal> getRegisterValues() {+ throw new UnsupportedOperationException();+ }++ @Override+ public MemBuffer getConcreteBuffer(Address address, Purpose purpose) {+ throw new UnsupportedOperationException();+ }++ @Override+ public void clear() {+ throw new UnsupportedOperationException();+ }++ @Override+ public PcodeExecutorState<JitVal> fork() {+ throw new UnsupportedOperationException();+ }++ /**+ * Get a complete catalog of all varnodes read, including overlapping, subregs, etc.+ *+ * @return the set of varnodes+ */+ public Set<Varnode> getVarnodesRead() {+ return varnodesRead;+ }++ /**+ * Get a complete catalog of all varnodes written, including overlapping, subregs, etc.+ *+ * @return the set of varnodes+ */+ public Set<Varnode> getVarnodesWritten() {+ return varnodesWritten;+ }++ /**+ * Capture the current state of intra-block analysis.+ *+ * <p>+ * This may be required for follow-up op-use analysis by a {@link JitCallOtherOpIf} invoked+ * using the standard strategy. All live varnodes <em>at the time of the call</em> must be+ * considered used.+ *+ * @return the captured state+ */+ public MiniDFState captureState() {+ return mini.copy();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowUseropLibrary.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowUseropLibrary.javanew file mode 100644index 0000000000..91d6bdd4ff--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitDataFlowUseropLibrary.java@@ -0,0 +1,275 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.lang.reflect.Method;+import java.lang.reflect.Parameter;+import java.util.*;+import java.util.stream.Collectors;+import java.util.stream.Stream;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.decode.DecoderUseropLibrary;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.*;+import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.PcodeUserop;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++/**+ * A wrapper around a userop library that places {@link PcodeOp#CALLOTHER callother} ops into the+ * use-def graph+ *+ * <p>+ * This is the library provided to+ * {@link JitDataFlowExecutor#execute(PcodeProgram, PcodeUseropLibrary)} to cooperate with in the+ * population of the use-def graph. The Sleigh compiler is very permissive when it comes to userop+ * invocations. Notably, there's no way to declare the "prototype" or "signature" of the userop.+ * Invocations can have any number of input operands and an optional output operand. Because the+ * use-def graph takes careful notice of variables and their definiting ops, there are two possible+ * op nodes: {@link JitCallOtherOp} when no output operand is given and {@link JitCallOtherDefOp}+ * when an output operand is given.+ *+ * <p>+ * We employ several different strategies to handle a p-code userop:+ *+ * <ul>+ * <li><b>Standard</b>: Invocation of the userop in the same fashion as the interpreted p-code+ * emulator. Any live variables have to be written into the {@link JitBytesPcodeExecutorState state}+ * before the invocation and the read back out afterward. If the userop accesses the state directly,+ * we must use this strategy. Most userops whose implementations precede the introduction of JIT+ * acceleration can be supported with this strategy, so long as they don't manipulate the+ * emulator/executor directly is some unsupported way.</li>+ * <li><b>Inlining</b>: The inclusion of the userop's p-code directly at its call site, replacing+ * the {@link PcodeOp#CALLOTHER} op. This is implemented in the decoder by+ * {@link DecoderUseropLibrary}. This strategy is only applicable to userops defined using Sleigh+ * and/or p-code.</li>+ * <li><b>Direct</b>: The direct invocation of the userop's defining Java method in the generated+ * JVM bytecode. This is applicable when the method's parameters and return type are primitives that+ * each map to a {@link JitTypeBehavior}. The input values can be passed directly in, which works+ * well when the inputs are registers or uniques allocated in JVM locals. The return value can be+ * handled similarly.</li>+ * </ul>+ *+ * <p>+ * The default strategy for all userops is Standard. Implementors should set the attributes of+ * {@link PcodeUserop} and adjust the parameters of the userop's method accordingly. To allow+ * inlining, set {@link PcodeUserop#canInline() canInline}. To allow direct invocation, set+ * {@link PcodeUserop#functional()} and ensure all the parameter types and return type are+ * supported. Supported types include primitives other than {@code char}. The return type may be+ * {@code void}. No matter the strategy, userops may be subject to removal by the+ * {@link JitOpUseModel}. To permit removal, clear {@link PcodeUserop#hasSideEffects()}. The default+ * prevents removal. For the inline strategy, each op from the inlined userop is analyzed+ * separately, so the userop could be partially culled. An inlined userop cannot have side effects,+ * and so the attribute is ignored.+ */+public class JitDataFlowUseropLibrary implements PcodeUseropLibrary<JitVal> {++ /**+ * The wrapper of a specific userop definition+ */+ protected class WrappedUseropDefinition implements PcodeUseropDefinition<JitVal> {+ private final PcodeUseropDefinition<Object> decOp;++ public WrappedUseropDefinition(PcodeUseropDefinition<Object> decOp) {+ this.decOp = decOp;+ }++ @Override+ public String getName() {+ return decOp.getName();+ }++ @Override+ public int getInputCount() {+ return decOp.getInputCount();+ }++ @Override+ public void execute(PcodeExecutor<JitVal> executor, PcodeUseropLibrary<JitVal> library,+ Varnode outVar, List<Varnode> inVars) {+ throw new AssertionError();+ }++ /**+ * If the number of arguments matches the userop's Java method, map each argument value to+ * the type behavior for its corresponding parameter.+ *+ * <p>+ * This is used by the {@link JitTypeModel} to assign types to JVM locals in order to reduce+ * the number of type casts. In the case of direct invocation, this enters type information+ * from the userop's Java definition into the analysis.+ *+ * <p>+ * If the parameter count doesn't match, we just map the arguments to+ * {@link JitTypeBehavior#ANY} and let the error surface at run time. We need not throw the+ * exception until/unless the invocation is actually executed. Similarly, if any parameter's+ * type is not supported, or the userop cannot be invoked directly, we just map all+ * arguments to {@link JitTypeBehavior#ANY}, because the generator will apply standard+ * invocation, which does not benefit from type analysis.+ *+ * @param inVals the input arguments+ * @return the map from argument value (SSA variable) to parameter type behavior+ */+ private List<JitTypeBehavior> getInputTypes(List<JitVal> inVals) {+ int inputCount = getInputCount();+ if (inputCount != inVals.size()) { // includes inputCount == -1 (variadic)+ return JitDataFlowModel.allAny(inVals);+ }+ Method method = decOp.getJavaMethod();+ if (method == null) {+ return JitDataFlowModel.allAny(inVals);+ }+ List<JitTypeBehavior> result = new ArrayList<>();+ Parameter[] parameters = method.getParameters();+ for (int i = 0; i < inVals.size(); i++) {+ Parameter p = parameters[i];+ JitTypeBehavior type = JitTypeBehavior.forJavaType(p.getType());+ if (type == null) {+ return JitDataFlowModel.allAny(inVals);+ }+ result.add(type);+ }+ return Collections.unmodifiableList(result);+ }++ /**+ * Get the type behavior from the userop's Java method+ *+ * <p>+ * If the userop is not backed by a Java method, or its return type is not supported, this+ * return {@link JitTypeBehavior#ANY}.+ *+ * @return the type behavior+ */+ private JitTypeBehavior getReturnType() {+ Method method = decOp.getJavaMethod();+ if (method == null) {+ return JitTypeBehavior.ANY;+ }+ return JitTypeBehavior.forJavaType(method.getReturnType());+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This "execution" is part of the intra-block analysis. This is the analytic interpretation+ * of the invocation, not the actual run time invocation. This derives type information+ * about the userop from the Java method and selects the approparite {@link JitCallOtherOpIf+ * callother} op to enter into the use-def graph. If an output operand is given, then this+ * generates an output notes defined by a {@lnk JitCallOtherDefOp}. Otherwise, it generates+ * a (sink) {@link JitCallOtherOp}.+ *+ * @implNote When inlining a userop, the decoder leaves the original callother op in place.+ * This is for branch bookkeeping. Thus, we ask the decoder-wrapped version of the+ * userop if it was inlined. If so, we enter a {@link JitNopOp nop} node into the+ * use-def graph. The node will still contain the original callother op, but the+ * generator will not emit any code.+ * @implNote <b>TODO</b>: Maybe float types shouldn't be size cast as ints and then bitcast+ * to the requested type. Either that, or we need to develop an overloading system+ * for userops, or to require the user to be very careful about which to invoke+ * for what (float) operand sizes. <b>TODO</b>: I don't know what the actual+ * behavior is here. We should add test cases for this.+ * @implNote <b>TODO</b>: I think userop libraries may need to be able to hook this point.+ * Not sure to what extent we should allow them control of code generation. But+ * consider a syscall library. It might like to try to concretize, e.g., RAX, and+ * just hard code the invoked userop in the generated code.+ */+ @Override+ public void execute(PcodeExecutor<JitVal> executor, PcodeUseropLibrary<JitVal> library,+ PcodeOp op) {+ if (decOp.canInlinePcode()) {+ dfm.notifyOp(new JitNopOp(op));+ return;+ }+ JitDataFlowState state = (JitDataFlowState) executor.getState();+ List<JitVal> inVals = Stream.of(op.getInputs())+ .skip(1)+ .map(inVn -> state.getVar(inVn, executor.getReason()))+ .toList();+ List<JitTypeBehavior> inTypes = getInputTypes(inVals);+ Varnode outVn = op.getOutput();+ if (outVn == null) {+ dfm.notifyOp(new JitCallOtherOp(op, decOp, inVals, inTypes, state.captureState()));+ }+ else {+ JitOutVar out = dfm.generateOutVar(outVn);+ dfm.notifyOp(new JitCallOtherDefOp(op, out, getReturnType(), decOp, inVals, inTypes,+ state.captureState()));+ state.setVar(outVn, out);+ }+ }++ @Override+ public boolean isFunctional() {+ return decOp.isFunctional();+ }++ @Override+ public boolean hasSideEffects() {+ return decOp.hasSideEffects();+ }++ @Override+ public boolean canInlinePcode() {+ return decOp.canInlinePcode();+ }++ @Override+ public Method getJavaMethod() {+ return decOp.getJavaMethod();+ }++ @Override+ public PcodeUseropLibrary<?> getDefiningLibrary() {+ return decOp.getDefiningLibrary();+ }+ }++ private final JitDataFlowModel dfm;++ private final Map<String, PcodeUseropDefinition<JitVal>> userops;++ /**+ * Construct a wrapper library+ *+ * @param context the context from which the decoder's userop wrapper library is retrieved+ * @param dfm the data flow model whose use-def graph to populate.+ * @implNote Each time this is constructed, it has to traverse the wrapped userop library and+ * create a wrapper for each individual userop. For a large library, this could get+ * expensive, and it currently must happen for every passage compiled. Part of the+ * cause for this requirement is the reference to the data flow mode used by each+ * userop wrapper.+ */+ public JitDataFlowUseropLibrary(JitAnalysisContext context, JitDataFlowModel dfm) {+ this.dfm = dfm;+ this.userops = context.getPassage()+ .getDecodeLibrary()+ .getUserops()+ .values()+ .stream()+ .map(WrappedUseropDefinition::new)+ .collect(Collectors.toUnmodifiableMap(d -> d.getName(), d -> d));+ }++ @Override+ public Map<String, PcodeUseropDefinition<JitVal>> getUserops() {+ return userops;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpUpwardVisitor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpUpwardVisitor.javanew file mode 100644index 0000000000..61b5231ba8--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpUpwardVisitor.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.pcode.emu.jit.analysis;++import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;++/**+ * A visitor that traverses the use-def graph upward, that is from uses toward definitions+ */+public interface JitOpUpwardVisitor extends JitOpVisitor {+ @Override+ default void visitUnOp(JitUnOp op) {+ visitVal(op.u());+ }++ @Override+ default void visitBinOp(JitBinOp op) {+ visitVal(op.l());+ visitVal(op.r());+ }++ @Override+ default void visitStoreOp(JitStoreOp op) {+ visitVal(op.offset());+ visitVal(op.value());+ }++ @Override+ default void visitLoadOp(JitLoadOp op) {+ visitVal(op.offset());+ }++ @Override+ default void visitCallOtherOp(JitCallOtherOp otherOp) {+ for (JitVal v : otherOp.args()) {+ visitVal(v);+ }+ }++ @Override+ default void visitCallOtherDefOp(JitCallOtherDefOp otherOp) {+ for (JitVal v : otherOp.args()) {+ visitVal(v);+ }+ }++ @Override+ default void visitCatenateOp(JitCatenateOp op) {+ for (JitVal p : op.parts()) {+ visitVal(p);+ }+ }++ @Override+ default void visitPhiOp(JitPhiOp op) {+ for (JitVal opt : op.options().values()) {+ visitVal(opt);+ }+ }++ @Override+ default void visitSubPieceOp(JitSynthSubPieceOp op) {+ visitVal(op.v());+ }++ @Override+ default void visitCBranchOp(JitCBranchOp op) {+ visitVal(op.cond());+ }++ @Override+ default void visitBranchIndOp(JitBranchIndOp op) {+ visitVal(op.target());+ }++ @Override+ default void visitOutVar(JitOutVar v) {+ visitOp(v.definition());+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpUseModel.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpUseModel.javanew file mode 100644index 0000000000..f11abe025d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpUseModel.java@@ -0,0 +1,333 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.util.*;++import ghidra.pcode.emu.jit.JitCompiler;+import ghidra.pcode.emu.jit.JitCompiler.Diag;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitDataFlowState.MiniDFState;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.JitMissingVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.PcodeUserop;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++/**+ * The operator output use analysis for JIT-accelerated emulation.+ *+ * <p>+ * This implements the Operation Elimination phase of the {@link JitCompiler} using a simple graph+ * traversal. The result is the set of {@link JitOp ops} whose outputs are (or could be) used by a+ * downstream op. This includes all "sink" ops and all ops on which they depend.+ *+ * <p>+ * Some of the sink ops are easy to identify. These are ops that have direct effects on memory,+ * control flow, or other aspects of the emulated machine:+ *+ * <ul>+ * <li><b>Memory outputs</b> - any p-code op whose output operand is a memory varnode.</li>+ * <li><b>Store ops</b> - a {@link JitStoreOp store} op.</li>+ * <li><b>Branch ops</b> - one of {@link JitBranchOp branch}, {@link JitCBranchOp cbranch}, or+ * {@link JitBranchIndOp branchind}.</li>+ * <li><b>User ops with side effects</b> - a {@link JitCallOtherOpIf callother} to a method where+ * {@link PcodeUserop#hasSideEffects() hasSideEffects}{@code =true}.</li>+ * <li><b>Errors</b> - e.g., {@link JitUnimplementedOp unimplemented}, {@link JitCallOtherMissingOp+ * missing userop}.</li>+ * </ul>+ *+ * <p>+ * We identify these ops by invoking {@link JitOp#canBeRemoved()}. Ops that return {@code false} are+ * "sink" ops.+ *+ * <p>+ * There is another class of ops to consider as "sinks," though: The definitions of SSA variables+ * that could be retired. This could be from exiting the passage, flowing to a block with fewer live+ * variables, or invoking a userop with the Standard strategy (see+ * {@link JitDataFlowUseropLibrary}). Luckily, we have already performed {@link JitVarScopeModel+ * scope} analysis, so we already know what varnodes are retired. However, to determine what SSA+ * variables are retired, we have to consider where the retirement happens. For block transitions,+ * it is always at the end of the block. Thus, we can use+ * {@link JitDataFlowBlockAnalyzer#getVar(Varnode)}. For userops, we capture the intra-block+ * analysis state into {@link JitCallOtherOpIf#dfState()} <em>at the time of invocation</em>. We can+ * then use {@link MiniDFState#getVar(Varnode)}. The defining op for each retired SSA variable is+ * considered used.+ *+ * <p>+ * Retirement due to block flow requires a little more attention. Consider an op that defines a+ * variable, where that op exists in a block that ends with a conditional branch. The analyzer does+ * not know which flow the code will take, so we have to consider that it could take either. If for+ * either branch, the variable goes out of scope and is retired, we have to consider the defining op+ * as used.+ *+ * <p>+ * The remainder of the algorithm is simply an upward traversal of the use-def graph to collect all+ * of the sink ops' dependencies. All the dependencies are considered used.+ *+ * @implNote The {@link JitOpUpwardVisitor} permits seeding of values (constants and variables) and+ * ops. Thus, we seed using the non-{@link JitOp#canBeRemoved() removable} ops, and the+ * retireable SSA variables. We do not have to get the variables' defining ops, since the+ * visitor will do that for us.+ */+public class JitOpUseModel {+ private final JitAnalysisContext context;+ private final JitControlFlowModel cfm;+ private final JitDataFlowModel dfm;+ private final JitVarScopeModel vsm;++ private final Set<JitOp> used = new HashSet<>();++ /**+ * Construct the operator use model+ *+ * @param context the analysis context+ * @param cfm the control flow model+ * @param dfm the data flow model+ * @param vsm the variable scope model+ */+ public JitOpUseModel(JitAnalysisContext context, JitControlFlowModel cfm,+ JitDataFlowModel dfm, JitVarScopeModel vsm) {+ this.context = context;+ this.cfm = cfm;+ this.dfm = dfm;+ this.vsm = vsm;++ if (context.getConfiguration().removeUnusedOperations()) {+ analyze();+ }+ }++ /**+ * The implementation of the graph traversal+ *+ * <p>+ * This implements the use-def upward visitor to collect the dependencies of ops and variables+ * identified elsewhere in the code. By calling {@link #visitOp(JitOp)},+ * {@link #visitVal(JitVal)}, etc., all used ops are collected into {@link JitOpUseModel#used}.+ */+ class OpUseCollector implements JitOpUpwardVisitor {+ final JitBlock block;+ final JitDataFlowBlockAnalyzer analyzer;++ /**+ * Construct a collector for the given block+ *+ * @param block the block whose ops are being examined+ */+ public OpUseCollector(JitBlock block) {+ this.block = block;+ this.analyzer = dfm.getAnalyzer(block);+ }++ @Override+ public void visitOp(JitOp op) {+ if (!used.add(op)) {+ return;+ }+ JitOpUpwardVisitor.super.visitOp(op);+ }++ @Override+ public void visitMissingVar(JitMissingVar missingVar) {+ throw new AssertionError("missing: " + missingVar);+ }++ /**+ * Visit a varnode that could be retired upon exiting a block+ *+ * <p>+ * This applies whether exiting the passage altogether or just flowing to another block. It+ * will find all definitions (including just-generated phi nodes) and visit them.+ *+ * @param vn the retireable varnode+ */+ void visitRetireable(Varnode vn) {+ for (JitVal val : analyzer.getOutput(vn)) {+ visitVal(val);+ }+ }++ /**+ * Visit a varnode that will be retired before calling a userop+ *+ * <p>+ * This applies only when the userop is invoked using the Standard strategy.+ *+ * @see JitDataFlowUseropLibrary+ * @param vn the retired varnode+ * @param callother the callother op+ */+ void visitCallOtherRetireable(Varnode vn, JitCallOtherOpIf callother) {+ for (JitVal val : callother.dfState().getDefinitions(vn)) {+ visitVal(val);+ }+ }+ }++ /**+ * Get the varnodes that will be retired before the given callother+ *+ * @param block the block containing the callother+ * @param op the callother op+ * @return the block's live varnodes, or empty, depending on the callother invocation strategy.+ */+ private Set<Varnode> getCallOtherRetireVarnodes(JitBlock block, JitCallOtherOpIf op) {+ // Should not see inline-replaced ops here+ if (op.userop().isFunctional()) {+ return Set.of();+ }+ return vsm.getLiveVars(block);+ }++ /**+ * Get the varnodes that could be retired upon leaving this block+ *+ * <p>+ * If the block has an {@link JitBlock#branchesOut() exit} branch, then all live varnodes could+ * be retired. The result is the union of retired varnodes among each flow+ * {@link JitBlock#flowsFrom() from} the block. Note that every block must have a means of+ * leaving, i.e., {@link JitBlock#branchesOut()} and {@link JitBlock#flowsFrom()} cannot both be+ * empty.+ *+ * @implNote Because retired varnodes are the difference in live varnodes, we can optimize the+ * set computation by taking the intersection of live varnodes among all flow+ * destinations and subtracting it from the live varnodes of this block.+ *+ * @param block the block to examine+ * @return the set of varnodes that could be retired+ */+ private Set<Varnode> getCouldRetireVarnodes(JitBlock block) {+ if (!block.branchesOut().isEmpty()) {+ return vsm.getLiveVars(block);+ }+ if (block.flowsFrom().isEmpty()) {+ throw new AssertionError();+ // or just return Set.of()?+ }+ Set<Varnode> aliveAfterAnyFlow =+ new HashSet<>(vsm.getLiveVars(block.flowsFrom().values().iterator().next().to()));+ for (BlockFlow flow : block.flowsFrom().values()) {+ aliveAfterAnyFlow.retainAll(vsm.getLiveVars(flow.to()));+ }+ Set<Varnode> result = new HashSet<>(vsm.getLiveVars(block));+ result.removeAll(aliveAfterAnyFlow);+ return result;+ }++ /**+ * Perform the analysis+ *+ * <p>+ * This first backfills any missing phi nodes that might not have been considered during data+ * flow analysis. Then, it collects all the sinks and invokes the traversal on them. Note that+ * we can end traversal any time we encounter an op that we have already marked as used, because+ * we will already have marked its dependencies, too. The visit order does not matter, so we+ * just iterate over the blocks and ops, marking things as we encounter them.+ */+ private void analyze() {+ /**+ * I want every value that could get written back out to the state, either because it's+ * retired, or because the output operand is memory. I also need inputs to branches or to+ * callother's, since those may have side effects depending on those inputs.+ */++ Set<JitPhiOp> phisBefore = Set.copyOf(dfm.phiNodes());+ for (JitBlock block : cfm.getBlocks()) {++ for (PcodeOp op : block.getCode()) {+ if (dfm.getJitOp(op) instanceof JitCallOtherOpIf callother) {+ for (Varnode vn : getCallOtherRetireVarnodes(block, callother)) {+ // We only want the side effect: Adds needed phi.+ callother.dfState().getVar(vn); // Visit is later+ }+ }+ }++ for (Varnode vn : getCouldRetireVarnodes(block)) {+ JitDataFlowBlockAnalyzer analyzer = dfm.getAnalyzer(block);+ analyzer.getVar(vn); // Visit is later+ }+ }+ Set<JitPhiOp> extraPhis = new LinkedHashSet<>(dfm.phiNodes());+ extraPhis.removeAll(phisBefore);+ dfm.analyzeInterblock(extraPhis);++ for (JitBlock block : cfm.getBlocks()) {+ OpUseCollector collector = new OpUseCollector(block);++ // Locate memory outputs, stores, branches, callothers+ for (PcodeOp op : block.getCode()) {+ JitOp jitOp = dfm.getJitOp(op);+ if (jitOp instanceof JitCallOtherOpIf callotherOp) {+ for (Varnode vn : getCallOtherRetireVarnodes(block, callotherOp)) {+ collector.visitCallOtherRetireable(vn, callotherOp);+ }+ }+ if (!jitOp.canBeRemoved()) {+ collector.visitOp(jitOp);+ }+ }++ // Compute retire-able variables+ for (Varnode vn : getCouldRetireVarnodes(block)) {+ collector.visitRetireable(vn);+ }+ }+ }++ /**+ * Check whether the given op node is used.+ *+ * <p>+ * If the op is used, then it cannot be eliminated.+ *+ * @param op the op to check+ * @return true if used, i.e., non-removable+ */+ public boolean isUsed(JitOp op) {+ if (context.getConfiguration().removeUnusedOperations()) {+ return used.contains(op);+ }+ return true;+ }++ /**+ * For diagnostics: Dump the analysis result to stderr+ *+ * @see Diag#PRINT_OUM+ */+ public void dumpResult() {+ System.err.println("STAGE: OpUse");+ for (JitBlock block : cfm.getBlocks()) {+ JitDataFlowBlockAnalyzer analyzer = dfm.getAnalyzer(block);+ System.err.println(" Block: " + block);+ for (Varnode vn : getCouldRetireVarnodes(block)) {+ for (JitVal val : analyzer.getOutput(vn)) {+ System.err.println(" Could retire: " + val);+ }+ }+ for (PcodeOp op : block.getCode()) {+ JitOp jitOp = dfm.getJitOp(op);+ if (!isUsed(jitOp)) {+ System.err.println(" Removed: %s: %s".formatted(op.getSeqnum(), jitOp));+ }+ }+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpVisitor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpVisitor.javanew file mode 100644index 0000000000..3633dc54e3--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitOpVisitor.java@@ -0,0 +1,270 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.*;++/**+ * A visitor for traversing the use-def graph+ *+ * <p>+ * The default implementations here do nothing other than discern the type of an op and variable and+ * dispatch the invocations appropriately. To traverse the graph upward, consider+ * {@link JitOpUpwardVisitor}. Note no "downward" visitor is currently provided, because it was not+ * needed.+ */+public interface JitOpVisitor {++ /**+ * Visit an op node+ *+ * <p>+ * The default implementation dispatches this to the type-specific {@code visit} method.+ *+ * @param op the op visited+ */+ default void visitOp(JitOp op) {+ switch (op) {+ case null -> throw new NullPointerException("null op");+ case JitUnOp unOp -> visitUnOp(unOp);+ case JitBinOp binOp -> visitBinOp(binOp);+ case JitStoreOp storeOp -> visitStoreOp(storeOp);+ case JitLoadOp loadOp -> visitLoadOp(loadOp);+ case JitCallOtherOp otherOp -> visitCallOtherOp(otherOp);+ case JitCallOtherDefOp otherOp -> visitCallOtherDefOp(otherOp);+ case JitCallOtherMissingOp otherOp -> visitCallOtherMissingOp(otherOp);+ case JitCatenateOp catOp -> visitCatenateOp(catOp);+ case JitPhiOp phiOp -> visitPhiOp(phiOp);+ case JitSynthSubPieceOp pieceOp -> visitSubPieceOp(pieceOp);+ case JitBranchOp branchOp -> visitBranchOp(branchOp);+ case JitCBranchOp cBranchOp -> visitCBranchOp(cBranchOp);+ case JitBranchIndOp branchIndOp -> visitBranchIndOp(branchIndOp);+ case JitUnimplementedOp unimplOp -> visitUnimplementedOp(unimplOp);+ case JitNopOp nopOp -> visitNopOp(nopOp);+ default -> throw new AssertionError("Unrecognized op: " + op);+ }+ }++ /**+ * Visit a {@link JitUnOp}+ *+ * @param unOp the op visited+ */+ default void visitUnOp(JitUnOp unOp) {+ }++ /**+ * Visit a {@link JitBinOp}+ *+ * @param binOp the op visited+ */+ default void visitBinOp(JitBinOp binOp) {+ }++ /**+ * Visit a {@link JitStoreOp}+ *+ * @param storeOp the op visited+ */+ default void visitStoreOp(JitStoreOp storeOp) {+ }++ /**+ * Visit a {@link JitLoadOp}+ *+ * @param loadOp the op visited+ */+ default void visitLoadOp(JitLoadOp loadOp) {+ }++ /**+ * Visit a {@link JitCallOtherOp}+ *+ * @param otherOp the op visited+ */+ default void visitCallOtherOp(JitCallOtherOp otherOp) {+ }++ /**+ * Visit a {@link JitCallOtherDefOp}+ *+ * @param otherOp the op visited+ */+ default void visitCallOtherDefOp(JitCallOtherDefOp otherOp) {+ }++ /**+ * Visit a {@link JitCallOtherMissingOp}+ *+ * @param otherOp the op visited+ */+ default void visitCallOtherMissingOp(JitCallOtherMissingOp otherOp) {+ }++ /**+ * Visit a {@link JitCatenateOp}+ *+ * @param catOp the op visited+ */+ default void visitCatenateOp(JitCatenateOp catOp) {+ }++ /**+ * Visit a {@link JitPhiOp}+ *+ * @param phiOp the op visited+ */+ default void visitPhiOp(JitPhiOp phiOp) {+ }++ /**+ * Visit a {@link JitSynthSubPieceOp}+ *+ * @param pieceOp the op visited+ */+ default void visitSubPieceOp(JitSynthSubPieceOp pieceOp) {+ }++ /**+ * Visit a {@link JitBranchOp}+ *+ * @param branchOp the op visited+ */+ default void visitBranchOp(JitBranchOp branchOp) {+ }++ /**+ * Visit a {@link JitCBranchOp}+ *+ * @param cBranchOp the op visited+ */+ default void visitCBranchOp(JitCBranchOp cBranchOp) {+ }++ /**+ * Visit a {@link JitBranchIndOp}+ *+ * @param branchIndOp the op visited+ */+ default void visitBranchIndOp(JitBranchIndOp branchIndOp) {+ }++ /**+ * Visit a {@link JitUnimplementedOp}+ *+ * @param unimplOp the op visited+ */+ default void visitUnimplementedOp(JitUnimplementedOp unimplOp) {+ }++ /**+ * Visit a {@link JitNopOp}+ *+ * @param nopOp the op visited+ */+ default void visitNopOp(JitNopOp nopOp) {+ }++ /**+ * Visit a {@link JitVal}+ *+ * <p>+ * The default implementation dispatches this to the type-specific {@code visit} method.+ *+ * @param v the value visited+ */+ default void visitVal(JitVal v) {+ switch (v) {+ case JitConstVal constVal -> visitConstVal(constVal);+ case JitVar jVar -> visitVar(jVar);+ default -> throw new AssertionError();+ }+ }++ /**+ * Visit a {@link JitVar}+ *+ * <p>+ * The default implementation dispatches this to the type-specific {@code visit} method.+ *+ * @param v the variable visited+ */+ default void visitVar(JitVar v) {+ switch (v) {+ case JitInputVar inputVar -> visitInputVar(inputVar);+ case JitMissingVar missingVar -> visitMissingVar(missingVar);+ case JitOutVar outVar -> visitOutVar(outVar);+ case JitDirectMemoryVar dirMemVar -> visitDirectMemoryVar(dirMemVar);+ case JitIndirectMemoryVar indMemVar -> visitIndirectMemoryVar(indMemVar);+ default -> throw new AssertionError();+ }+ }++ /**+ * Visit a {@link JitConstVal}+ *+ * @param constVal the variable visited+ */+ default void visitConstVal(JitConstVal constVal) {+ }++ /**+ * Visit a {@link JitDirectMemoryVar}+ *+ * @param dirMemVar the variable visited+ */+ default void visitDirectMemoryVar(JitDirectMemoryVar dirMemVar) {+ }++ /**+ * Visit a {@link JitIndirectMemoryVar}+ *+ * <p>+ * NOTE: These should not ordinarily appear in the use-def graph. There is only the one+ * {@link JitIndirectMemoryVar#INSTANCE}, and it's used as a temporary dummy. Indirect memory+ * access is instead modeled by the {@link JitLoadOp}.+ *+ * @param indMemVar the variable visited+ */+ default void visitIndirectMemoryVar(JitIndirectMemoryVar indMemVar) {+ throw new AssertionError();+ }++ /**+ * Visit a {@link JitInputVar}+ *+ * @param inputVar the variable visited+ */+ default void visitInputVar(JitInputVar inputVar) {+ }++ /**+ * Visit a {@link JitMissingVar}+ *+ * @param missingVar the variable visited+ */+ default void visitMissingVar(JitMissingVar missingVar) {+ }++ /**+ * Visit a {@link JitOutVar}+ *+ * @param outVar the variable visited+ */+ default void visitOutVar(JitOutVar outVar) {+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitType.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitType.javanew file mode 100644index 0000000000..c435f48b4e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitType.java@@ -0,0 +1,529 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import static org.objectweb.asm.Opcodes.*;++import java.util.*;++import org.objectweb.asm.Opcodes;++/**+ * The p-code type of an operand.+ *+ * <p>+ * A type is an integer of floating-point value of a specific size in bytes. All values and+ * variables in p-code are just bit vectors. The operators interpret those vectors according to a+ * {@link JitTypeBehavior}. While types only technically belong to the operands, we also talk about+ * values, variables, and varnodes being assigned types, so that we can allocate suitable JVM+ * locals.+ */+public interface JitType {++ /**+ * Compare two types by preference. The type with the more preferred behavior then smaller size+ * is preferred.+ *+ * @param t1 the first type+ * @param t2 the second type+ * @return as in {@link Comparator#compare(Object, Object)}+ */+ static int compare(JitType t1, JitType t2) {+ int c;+ c = Integer.compare(t1.pref(), t2.pref());+ if (c != 0) {+ return c;+ }+ c = Integer.compare(t1.size(), t2.size());+ if (c != 0) {+ return c;+ }+ return 0;+ }++ /**+ * Identify the p-code type that is exactly represented by the given JVM type.+ *+ * <p>+ * This is used during Direct userop invocation to convert the arguments and return value.+ *+ * @param cls the primitive class (not boxed)+ * @return the p-code type+ * @see JitDataFlowUseropLibrary+ */+ public static JitType forJavaType(Class<?> cls) {+ if (cls == boolean.class) {+ return IntJitType.I4;+ }+ if (cls == byte.class) {+ return IntJitType.I1;+ }+ if (cls == short.class) {+ return IntJitType.I2;+ }+ if (cls == int.class) {+ return IntJitType.I4;+ }+ if (cls == long.class) {+ return LongJitType.I8;+ }+ if (cls == float.class) {+ return FloatJitType.F4;+ }+ if (cls == double.class) {+ return DoubleJitType.F8;+ }+ throw new IllegalArgumentException();+ }++ /**+ * A p-code type that can be represented in a single JVM variable.+ */+ public interface SimpleJitType extends JitType {+ /**+ * The JVM type of the variable that can represent a p-code variable of this type+ *+ * @return the primitive class (not boxed)+ */+ Class<?> javaType();++ /**+ * The JVM opcode to load a local variable of this type onto the stack+ *+ * @return the opcode+ */+ int opcodeLoad();++ /**+ * The JVM opcode to store a local variable of this type from the stack+ *+ * @return the opcode+ */+ int opcodeStore();++ /**+ * Re-apply the {@link JitTypeBehavior#INTEGER integer} behavior to this type+ *+ * <p>+ * This may be slightly faster than {@code JitTypeBehavior.INTEGER.resolve(this)}, because+ * each type can pick its int type directly, and integer types can just return {@code this}.+ *+ * @return this type as an int+ */+ SimpleJitType asInt();+ }++ /**+ * The p-code types for integers of size 1 through 4, i.e., that fit in a JVM int.+ *+ * @param size the size in bytes+ */+ public record IntJitType(int size) implements SimpleJitType {+ /** {@code int1}: a 1-byte integer */+ public static final IntJitType I1 = new IntJitType(1);+ /** {@code int2}: a 2-byte integer */+ public static final IntJitType I2 = new IntJitType(2);+ /** {@code int3}: a 3-byte integer */+ public static final IntJitType I3 = new IntJitType(3);+ /** {@code int4}: a 4-byte integer */+ public static final IntJitType I4 = new IntJitType(4);++ /**+ * Get the type for an integer of the given size 1 through 4+ *+ * @param size the size in bytes+ * @return the type+ * @throws IllegalArgumentException for any size <em>not</em> 1 through 4+ */+ public static IntJitType forSize(int size) {+ return switch (size) {+ case 1 -> I1;+ case 2 -> I2;+ case 3 -> I3;+ case 4 -> I4;+ default -> throw new IllegalArgumentException("size:" + size);+ };+ }++ /**+ * Compact constructor to check the size+ *+ * @param size the size in bytes+ */+ public IntJitType {+ assert 0 < size && size <= Integer.BYTES;+ }++ @Override+ public int pref() {+ return 0;+ }++ @Override+ public String nm() {+ return "i";+ }++ @Override+ public Class<?> javaType() {+ return int.class;+ }++ @Override+ public int opcodeLoad() {+ return ILOAD;+ }++ @Override+ public int opcodeStore() {+ return ISTORE;+ }++ @Override+ public IntJitType ext() {+ return I4;+ }++ @Override+ public IntJitType asInt() {+ return this;+ }+ }++ /**+ * The p-code types for integers of size 5 through 8, i.e., that fit in a JVM long.+ *+ * @param size the size in bytes+ */+ public record LongJitType(int size) implements SimpleJitType {+ /** {@code int5}: a 5-byte integer */+ public static final LongJitType I5 = new LongJitType(5);+ /** {@code int6}: a 6-byte integer */+ public static final LongJitType I6 = new LongJitType(6);+ /** {@code int7}: a 7-byte integer */+ public static final LongJitType I7 = new LongJitType(7);+ /** {@code int8}: a 8-byte integer */+ public static final LongJitType I8 = new LongJitType(8);++ /**+ * Get the type for an integer of the given size 5 through 8+ *+ * @param size the size in bytes+ * @return the type+ * @throws IllegalArgumentException for any size <em>not</em> 5 through 8+ */+ public static LongJitType forSize(int size) {+ return switch (size) {+ case 5 -> I5;+ case 6 -> I6;+ case 7 -> I7;+ case 8 -> I8;+ default -> throw new IllegalArgumentException("size:" + size);+ };+ }++ /**+ * Compact constructor to check the size+ *+ * @param size the size in bytes+ */+ public LongJitType {+ assert 0 < size && size <= Long.BYTES;+ }++ @Override+ public int pref() {+ return 1;+ }++ @Override+ public String nm() {+ return "l";+ }++ @Override+ public Class<?> javaType() {+ return long.class;+ }++ @Override+ public int opcodeLoad() {+ return LLOAD;+ }++ @Override+ public int opcodeStore() {+ return LSTORE;+ }++ @Override+ public LongJitType ext() {+ return I8;+ }++ @Override+ public LongJitType asInt() {+ return this;+ }+ }++ /**+ * The p-code type for floating-point of size 4, i.e., that fits in a JVM float.+ */+ public enum FloatJitType implements SimpleJitType {+ /** {@code float4}: a 4-byte float */+ F4;++ @Override+ public int pref() {+ return 2;+ }++ @Override+ public String nm() {+ return "f";+ }++ @Override+ public int size() {+ return Float.BYTES;+ }++ @Override+ public Class<?> javaType() {+ return float.class;+ }++ @Override+ public int opcodeLoad() {+ return FLOAD;+ }++ @Override+ public int opcodeStore() {+ return FSTORE;+ }++ @Override+ public FloatJitType ext() {+ return this;+ }++ @Override+ public IntJitType asInt() {+ return IntJitType.I4;+ }+ }++ /**+ * The p-code type for floating-point of size 8, i.e., that fits in a JVM double.+ */+ public enum DoubleJitType implements SimpleJitType {+ /** {@code float8}: a 8-byte float */+ F8;++ @Override+ public int pref() {+ return 3;+ }++ @Override+ public String nm() {+ return "d";+ }++ @Override+ public int size() {+ return Double.BYTES;+ }++ @Override+ public Class<?> javaType() {+ return double.class;+ }++ @Override+ public int opcodeLoad() {+ return DLOAD;+ }++ @Override+ public int opcodeStore() {+ return DSTORE;+ }++ @Override+ public DoubleJitType ext() {+ return this;+ }++ @Override+ public LongJitType asInt() {+ return LongJitType.I8;+ }+ }++ /**+ * <b>WIP</b>: The p-code types for integers of size 9 and greater.+ *+ * @param size the size in bytes+ */+ public record MpIntJitType(int size) implements JitType {+ private static final Map<Integer, MpIntJitType> FOR_SIZES = new HashMap<>();++ /**+ * Get the type for an integer of the given size 9 or greater+ *+ * @param size the size in bytes+ * @return the type+ * @throws IllegalArgumentException for any size 8 or less+ */+ public static MpIntJitType forSize(int size) {+ return FOR_SIZES.computeIfAbsent(size, MpIntJitType::new);+ }++ @Override+ public int pref() {+ return 4;+ }++ @Override+ public String nm() {+ return "I";+ }++ /**+ * The total number of JVM int variables ("legs") required to store the int+ *+ * @return the total number of legs+ */+ public int legsAlloc() {+ return (size + Integer.BYTES - 1) / Integer.BYTES;+ }++ /**+ * The number of legs that are filled+ *+ * @return the number of whole legs+ */+ public int legsWhole() {+ return size / Integer.BYTES;+ }++ /**+ * The number of bytes filled in the last leg, if partial+ *+ * @return the number of bytes in the partial leg, or 0 if all legs are whole+ */+ public int partialSize() {+ return size % Integer.BYTES;+ }++ /**+ * Get the p-code type that describes the part of the variable in each leg+ *+ * <p>+ * Each whole leg will have the type {@link IntJitType#I4}, and the partial leg, if+ * applicable, will have its appropriate smaller integer type.+ *+ * @return the list of types, each fitting in a JVM int.+ */+ public List<SimpleJitType> legTypes() {+ IntJitType[] types = new IntJitType[legsAlloc()];+ int i = 0;+ if (partialSize() != 0) {+ types[i++] = IntJitType.forSize(partialSize());+ }+ for (; i < legsWhole(); i++) {+ types[i] = IntJitType.I4;+ }+ return Arrays.asList(types);+ }++ @Override+ public MpIntJitType ext() {+ return MpIntJitType.forSize(legsAlloc() * Integer.BYTES);+ }+ }++ /**+ * <b>WIP</b>: The p-code types for floats of size other than 4 and 8+ *+ * @param size the size in bytes+ */+ public record MpFloatJitType(int size) implements JitType {+ private static final Map<Integer, MpFloatJitType> FOR_SIZES = new HashMap<>();++ /**+ * Get the type for a float of the given size other than 4 and 8+ *+ * @param size the size in bytes+ * @return the type+ * @throws IllegalArgumentException for size 4 or 8+ */+ public static MpFloatJitType forSize(int size) {+ return FOR_SIZES.computeIfAbsent(size, MpFloatJitType::new);+ }++ @Override+ public int pref() {+ return 5;+ }++ @Override+ public String nm() {+ return "F";+ }++ @Override+ public MpFloatJitType ext() {+ return this;+ }+ }++ /**+ * The preference for this type. Smaller is more preferred.+ *+ * @return the preference+ */+ public int pref();++ /**+ * Part of the name of a JVM local variable allocated for this type+ *+ * @return the "type" part of a JVM local's name+ */+ public String nm();++ /**+ * The size of this type+ *+ * @return the size in bytes+ */+ public int size();++ /**+ * Extend this p-code type to the p-code type that fills its entire host JVM type.+ *+ * <p>+ * This is useful, e.g., when multiplying two {@link IntJitType#I3 int3} values using+ * {@link Opcodes#IMUL imul} that the result might be an {@link IntJitType#I4 int4} and so may+ * need additional conversion.+ *+ * @return the extended type+ */+ JitType ext();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitTypeBehavior.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitTypeBehavior.javanew file mode 100644index 0000000000..64a152ee2a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitTypeBehavior.java@@ -0,0 +1,182 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.util.Comparator;+import java.util.Objects;++import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.op.JitCopyOp;+import ghidra.pcode.emu.jit.op.JitPhiOp;++/**+ * The behavior/requirement for an operand's type.+ *+ * @see JitTypeModel+ */+public enum JitTypeBehavior {+ /**+ * No type requirement or interpretation.+ */+ ANY {+ /**+ * {@inheritDoc}+ *+ * <p>+ * If no type is specified, we default to ints.+ */+ @Override+ public JitType type(int size) {+ return INTEGER.type(size);+ }++ @Override+ public JitType resolve(JitType varType) {+ return varType;+ }+ },+ /**+ * The bits are interpreted as an integer.+ */+ INTEGER {+ @Override+ public JitType type(int size) {+ assert size > 0;+ return switch (size) {+ case 1, 2, 3, 4 -> IntJitType.forSize(size);+ case 5, 6, 7, 8 -> LongJitType.forSize(size);+ default -> MpIntJitType.forSize(size);+ };+ }++ @Override+ public JitType resolve(JitType varType) {+ return type(varType.size());+ }+ },+ /**+ * The bits are interpreted as a floating-point value.+ */+ FLOAT {+ @Override+ public JitType type(int size) {+ return switch (size) {+ case Float.BYTES -> FloatJitType.F4;+ case Double.BYTES -> DoubleJitType.F8;+ default -> MpFloatJitType.forSize(size);+ };+ }++ @Override+ public JitType resolve(JitType varType) {+ return type(varType.size());+ }+ },+ /**+ * For {@link JitCopyOp} and {@link JitPhiOp}: No type requirement or interpretation, but there+ * is an implication that the output has the same interpretation as the inputs.+ */+ COPY {+ @Override+ public JitType type(int size) {+ throw new AssertionError();+ }++ @Override+ public JitType resolve(JitType varType) {+ return ANY.resolve(varType);+ }+ },+ ;++ /**+ * Compare two behaviors by preference. The behavior with the smaller ordinal is preferred.+ *+ * @param b1 the first behavior+ * @param b2 the second behavior+ * @return as in {@link Comparator#compare(Object, Object)}+ */+ public static int compare(JitTypeBehavior b1, JitTypeBehavior b2) {+ return Objects.compare(b1, b2, JitTypeBehavior::compareTo);+ }++ /**+ * Apply this behavior to a value of the given size to determine its type+ *+ * @param size the size of the value in bytes+ * @return the resulting type+ * @throws AssertionError if the type is not applicable, and such an invocation was not expected+ */+ public abstract JitType type(int size);++ /**+ * Re-apply this behavior to an existing type+ *+ * <p>+ * For {@link #ANY} and {@link #COPY} the result is the given type.+ *+ * @param varType the type+ * @return the resulting type+ */+ public abstract JitType resolve(JitType varType);++ /**+ * Derive the type behavior from a Java language type.+ *+ * <p>+ * This is used on userops declared with Java primitives for parameters. To work with the+ * {@link JitTypeModel}, we need to specify the type behavior of each operand. We aim to select+ * behaviors such that the model allocates JVM locals whose JVM types match the userop method's+ * parameters. This optimizes type conversions during Direct invocation.+ *+ * @param cls the primitive class (not boxed)+ * @return the p-code type behavior+ * @see JitDataFlowUseropLibrary+ */+ public static JitTypeBehavior forJavaType(Class<?> cls) {+ if (cls == byte.class) {+ return INTEGER;+ }+ if (cls == short.class) {+ return INTEGER;+ }+ if (cls == int.class) {+ return INTEGER;+ }+ if (cls == long.class) {+ return INTEGER;+ }+ if (cls == float.class) {+ return FLOAT;+ }+ if (cls == double.class) {+ return FLOAT;+ }+ if (cls == boolean.class) {+ return INTEGER;+ }+ if (cls == char.class) {+ return null;+ }+ if (cls == void.class) {+ return null;+ }+ if (cls.isPrimitive()) {+ throw new AssertionError();+ }+ return null;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitTypeModel.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitTypeModel.javanew file mode 100644index 0000000000..5bcd20b258--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitTypeModel.java@@ -0,0 +1,401 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.util.*;+import java.util.Map.Entry;++import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.JitCompiler;+import ghidra.pcode.emu.jit.analysis.JitType.FloatJitType;+import ghidra.pcode.emu.jit.analysis.JitType.IntJitType;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.emu.jit.var.JitVal.ValUse;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The type analysis for JIT-accelerated emulation.+ *+ * <p>+ * This implements the Type Assignment phase of the {@link JitCompiler} using a very basic "voting"+ * algorithm. The result is an assignment of type to each {@link JitVal}. To be clear, at this+ * phase, we're assigning types to variables (and constants) in the use-def graph, not varnodes.+ * Later we do another bit of "voting" to determine the type of each JVM local allocated to a+ * varnode. Perhaps we could be more direct, but in anticipation of future optimizations, we keep+ * this analysis at the per-variable level. This is partly an artifact of exploration before+ * deciding to allocate by varnode instead of by variable.+ *+ * <h2>Types in P-code and the JVM</h2>+ * <p>+ * P-code (and Sleigh) is a relatively type free language. Aside from size, variables have no type;+ * they are just bit vectors. The operators are typed and cast the bits as required. This aligns+ * well with most machine architectures. Registers are just bit vectors, and the instructions+ * interpret them according to some type. In contrast, JVM variables have a type: {@code int},+ * {@code long}, {@code float}, {@code double}, or a reference. Conversions between JVM types must+ * be explicit, so we must attend to certain aspects of p-code types when consuming operands+ * allocated in JVM locals. There are three aspects to consider when translating p-code types to the+ * JVM: behavior, size, and signedness.+ *+ * <h3>Behavior: Integer vs. Float</h3>+ * <p>+ * The JVM has two integral types {@code int} and {@code long} of 4 and 8 bytes respectively. P-code+ * has one integral type of no specified size. Or rather, it has as many integral types: 1-byte int,+ * 2-byte int, 3-byte int, and so on. We thus describe p-code operands as having a type+ * {@link JitTypeBehavior behavior}: <em>integral</em> or <em>floating-point</em>. Note there are+ * two ancillary behaviors <em>any</em> and <em>copy</em> to describe the operands of truly typeless+ * operators, like {@link JitCopyOp}.+ *+ * <h3>Size</h3>+ * <p>+ * When paired with a varnode's size, we have enough information to start mapping p-code types to+ * JVM types. For float types, p-code only supports specific sizes defined by IEEE 754: 2-byte+ * half-precision, 4-byte single-precision, 8-byte double-precision, 10-byte extended-precision,+ * 16-byte quadruple-precision, and 32-byte octuple-precision. Some p-code types map precisely to+ * JVM counterparts: The 4- and 8-byte integer types map precisely to the JVM's {@code int} and+ * {@code long} types. Similarly, the 4- and 8-byte float types map precisely to {@code float} and+ * {@code double}. <b>TODO</b>: The JIT translator does not currently support integral types greater+ * than 8 bytes (64 bits) in size nor floating-point types other than 4 and 8 bytes (single and+ * double precision) in size.+ *+ * <h3>Signedness</h3>+ * <p>+ * All floating-point types are signed, whether in p-code or in the JVM, so there's little to+ * consider in terms of mapping. Some p-code operators have signed operands, some have unsigned+ * operands, and others have no signedness at all. In contrast, no JVM bytecodes are strictly+ * unsigned. They are either signed or have no signedness. It was a choice of the Java language+ * designers that all variables would be signed, and this is consequence of that choice. In time,+ * "unsigned" operations were introduced in the form of static methods, e.g.,+ * {@link Integer#compareUnsigned(int, int)} and {@link Long#divideUnsigned(long, long)}. Note that+ * at the bit level, unsigned multiplication is the same as signed, and so no "unsigned multiply"+ * method was provided. This actually aligns well with p-code in that, for this aspect of+ * signedness, the variables are all the same. Instead the operations apply the type interpretation.+ * Thus, we need not consider signedness when allocating JVM locals.+ *+ * <h2>Conversions and Casts</h2>+ * <p>+ * Conversions between JVM primitive types must be explicit in the emitted bytecode, even if the+ * intent is just to re-cast the bits. This is not the case for p-code. Conversions in p-code need+ * only be explicit when they mutate the actual bits. Consider the following p-code:+ *+ * <pre>+ * $U00:4 = FLOAT_ADD r0, r1+ * r2 = INT_2COMP $U00:4+ * </pre>+ *+ * <p>+ * The native translation to bytecode:+ *+ * <pre>+ * FLOAD 1 # r0+ * FLOAD 2 # r1+ * FADD+ * FSTORE 3 # $U00:4+ * LDC 0+ * ILOAD 3 # $U00:4+ * ISUB+ * ISTORE 4 # r2+ * </pre>+ *+ * <p>+ * Will cause an error when loading the class. This is because the local variable 3 must be one of+ * {@code int} or {@code float}, and the bytecode must declare which, so either the {@code FSTORE 3}+ * or the {@code ILOAD 3} will fail the JVM's type checker. To resolve this, we could assign the+ * type {@code float} to local variable 3, and change the erroneous {@code ILOAD 3} to:+ *+ * <pre>+ * FLOAD 3+ * INVOKESTATIC {@link Float#floatToRawIntBits(float)}+ * </pre>+ *+ * <p>+ * At this point, the bit-vector contents of {@code $U00:4} are on the stack, but for all the JVM+ * cares, they are now an {@code int}. We must assigned a JVM type to each local we allocate and+ * place bitwise type casts wherever the generated bytecodes would cause type disagreement. We would+ * like to assign JVM types in a way that reduces the number of {@code INVOKESTATIC} bytecodes+ * emitted. One could argue that we should instead seek to reduce the number of {@code INVOKESTATIC}+ * bytecodes actually executed, but I pray the JVM's JIT compiler can recognize calls to+ * {@link Float#floatToRawIntBits(float)} and similar and emit no native code for them, i.e., they+ * ought to have zero run-time cost.+ *+ * <p>+ * Size conversions cause a similar need for explicit conversions, for two reasons: 1) Any+ * conversion between JVM {@code int} and {@code long} still requires specific bytecodes. Neither+ * platform supports implicit conversion between {@code float} and {@code double}. 2) We allocate+ * the smaller JVM integral type to accommodate each p-code integral type, so we must apply masks in+ * some cases to assure values to do not exceed their p-code varnode size. Luckily, p-code also+ * requires explicit conversions between sizes, e.g., using {@link PcodeOp#INT_ZEXT zext}. However,+ * we often have to perform temporary conversions in order to meet the type/size requirements of JVM+ * bytecodes.+ *+ * <p>+ * Consider {@code r2 = INT_MULT r0, r1} where the registers are all 5 bytes. Thus, the registers+ * are allocated as JVM locals of type {@code long}. We load {@code r0} and {@code r1} onto the+ * stack, and then we emit an {@link Opcodes#LMUL}. Technically, the result is another JVM+ * {@code long}, which maps to an 8-byte p-code integer. Thus, we must apply a mask to "convert" the+ * result to a 5-byte p-code integer before storing the result in {@code r2}'s JVM local.+ *+ * <h2>Type Assignment</h2>+ * <p>+ * Given that only behavior and size require any explicit conversions, we omit signedness from the+ * formal definition of p-code {@link JitType type}. It is just the behavior applied to a size,+ * e.g., {@link IntJitType#I3 int3}.+ *+ * <p>+ * We use a fairly straightforward voting algorithm that examines how each variable definition is+ * used. The type of an operand is trivially determined by examining the behavior of each operand,+ * as specified by the p-code opcode; and the size of the input varnode, specified by the specific+ * p-code op instance. For example, the p-code op {@code $U00:4 = FLOAT_ADD r0, r1} has an output+ * operand of {@link FloatJitType#F4 float4}. Thus, it casts a vote that {@code $U00:4} should be+ * that type. However, the subsequent op {@code r2 = INT_2COMP $U00} casts a vote for+ * {@link IntJitType#I4 int4}. We prefer an {@code int} when tied, so we assign {@code $U00:4} the+ * type {@code int4}.+ *+ * <p>+ * This become complicated in the face of typeless ops, namely {@link JitCopyOp copy} and+ * {@link JitPhiOp phi}. Again, we'd like to reduce the number of casts we have to emit in the+ * bytecode. Consider the op {@code r1 = COPY r0}. This should emit a load followed immediately by a+ * store, but The JVM will require both the source and destination locals to have the same type.+ * Otherwise, a cast is necessary. The votes regarding {@code r0} will thus need to incorporate the+ * votes regarding {@code r1} and vice versa.+ *+ * <p>+ * Our algorithm is a straightforward queued traversal of the use-def graph until convergence.+ * First, we initialize a queue with all values (variables and constants) in the graph and+ * initialize all type assignments to {@link JitTypeBehavior#ANY any}. We then process each value in+ * the queue until it is empty. A value receives votes from its uses as required by each operand.+ * {@link JitTypeBehavior#INTEGER integer} and {@link JitTypeBehavior float} behaviors count as 1+ * vote for that behavior. The {@link JitTypeBehavior#ANY any} behavior contributes 0 votes. If the+ * behavior is {@link JitTypeBehavior#COPY copy}, then we know the use is either a {@link JitCopyOp+ * copy} or {@link JitPhiOp phi} op, so we fetch its output value. The op casts its vote for the+ * tentative type of that output value. Similar is done for the value's defining op, if applicable.+ * If it's a copy or phi, we start a sub contest where each input/option casts a vote for its+ * tentative type. The defining op's vote is cast according to the winner of the sub contest. Ties+ * favor {@link JitTypeBehavior#INTEGER integer}. The final winner is computed and the tentative+ * type assignment is updated. If there are no votes, the tentative assignment is+ * {@link JitTypeBehavior#ANY}.+ *+ * <p>+ * When an update changes the tentative type assignment of a value, then all its neighbors are added+ * back to the queue. Neighbors are those values connected to this one via a copy or phi. When the+ * queue is empty, the tentative type assignments are made final. Any assignment that remains+ * {@link JitTypeBehavior#ANY any} is treated as if {@link JitTypeBehavior#INTEGER int}.+ * <b>TODO</b>: Prove that this algorithm always terminates.+ *+ * @implNote We do all the bookkeeping in terms of {@link JitTypeBehavior} and wait to resolve the+ * actual type until the final assignment.+ */+public class JitTypeModel {++ /**+ * A contest to determine a type assignment+ *+ * @param counts the initial count for each candidate (should just be empty)+ */+ protected record Contest(Map<JitTypeBehavior, Integer> counts) {+ /**+ * Start a new contest+ */+ public Contest() {+ this(new HashMap<>());+ }++ /**+ * Cast a vote for the given candidate+ *+ * @param candidate the candidate type+ * @param c the number of votes cast+ */+ private void vote(JitTypeBehavior candidate, int c) {+ if (candidate == JitTypeBehavior.ANY || candidate == JitTypeBehavior.COPY) {+ return;+ }+ counts.compute(candidate, (k, v) -> v == null ? c : v + c);+ }++ /**+ * Cast a vote for the given candidate+ *+ * @param candidate the candidate type+ */+ public void vote(JitTypeBehavior candidate) {+ vote(candidate, 1);+ }++ /**+ * Compare the votes between two candidates, and select the winner+ *+ * <p>+ * The {@link #winner()} method seeks the "max" candidate, so the vote counts are compared+ * in the usual fashion. We need to invert the comparison of the types, though.+ * {@link JitTypeBehavior#INTEGER} has a lower ordinal than {@link JitTypeBehavior#FLOAT},+ * but we want to ensure int is preferred, so we reverse that comparison.+ *+ * @param ent1 the first candidate-vote entry+ * @param ent2 the second candidate-vote entry+ * @return -1 if the <em>second</em> wins, 1 if the <em>first</em> wins. 0 should never+ * result, unless we're comparing a candidate with itself.+ */+ public static int compareCandidateEntries(Entry<JitTypeBehavior, Integer> ent1,+ Entry<JitTypeBehavior, Integer> ent2) {+ int c;+ c = Integer.compare(ent1.getValue(), ent2.getValue());+ if (c != 0) {+ return c;+ }+ c = JitTypeBehavior.compare(ent1.getKey(), ent2.getKey());+ if (c != 0) {+ return -c; // INT is preferred to FLOAT+ }+ return 0;+ }++ /**+ * Compute the winner of the contest+ *+ * @return the winner, or {@link JitTypeBehavior#ANY} if there are no entries+ */+ public JitTypeBehavior winner() {+ return counts.entrySet()+ .stream()+ .max(Contest::compareCandidateEntries)+ .map(Entry::getKey)+ .orElse(JitTypeBehavior.ANY);+ }+ }++ private final JitDataFlowModel dfm;++ private final SequencedSet<JitVal> queue = new LinkedHashSet<>();+ private final Map<JitVal, JitTypeBehavior> assignments = new HashMap<>();++ /**+ * Construct the type model+ *+ * @param dfm the data flow model whose use-def graph to process+ */+ public JitTypeModel(JitDataFlowModel dfm) {+ this.dfm = dfm;++ analyze();+ }++ /**+ * Compute the new tentative assignment for the given value+ *+ * <p>+ * As discussed in the "voting" section of {@link JitTypeModel}, this tallies up the votes among+ * the values's uses and defining op then selects the winner.+ *+ * @param v the value+ * @return the new assignment+ */+ protected JitTypeBehavior computeNewAssignment(JitVal v) {+ Contest contest = new Contest();+ // Downstream votes+ for (ValUse use : v.uses()) {+ JitTypeBehavior type = use.type();+ if (type == JitTypeBehavior.COPY && use.op() instanceof JitDefOp def) {+ JitVal downstream = def.out();+ type = assignments.get(downstream);+ }+ contest.vote(type);+ }++ // Upstream votes+ if (v instanceof JitOutVar out) {+ JitTypeBehavior defType = JitTypeBehavior.ANY;+ JitDefOp def = out.definition();+ defType = def.type();+ if (defType == JitTypeBehavior.COPY) {+ Contest subContest = new Contest();+ for (JitVal upstream : def.inputs()) {+ subContest.vote(assignments.get(upstream));+ }+ defType = subContest.winner();+ }+ contest.vote(defType);+ }++ return contest.winner();+ }++ /**+ * Re-add the given value's neighbors to the processing queue.+ *+ * <p>+ * Neighbors are any values connected to the given one via {@link JitCopyOp} or {@link JitPhiOp}+ * — or any op with an operand requiring {@link JitTypeBehavior#COPY} if additional ones+ * should appear in the future. This is necessary because those ops may change their vote now+ * that this value's tentative type has changed. Note if the value is already in the queue, it+ * need not be added again. Thus, the queue is a {@link SequencedSet}.+ *+ * @param v the value whose neighbors to re-process+ */+ protected void queueNeighbors(JitVal v) {+ for (ValUse use : v.uses()) {+ JitTypeBehavior type = use.type();+ if (type == JitTypeBehavior.COPY && use.op() instanceof JitDefOp def) {+ queue.add(def.out());+ }+ }++ if (v instanceof JitOutVar out) {+ JitDefOp def = out.definition();+ if (def.type() == JitTypeBehavior.COPY) {+ queue.addAll(def.inputs());+ }+ }+ }++ /**+ * Perform the analysis+ *+ * <p>+ * This queues every value up to be processed at least once and then runs the algorithm to+ * termination. Each value in the queue is removed and a voting contest run to update its type+ * assignment. If the new assignment differs from its old assignment, its neighbors (if any) are+ * re-added to the queue.+ */+ protected void analyze() {+ Set<JitVal> vals = dfm.allValues();+ queue.addAll(vals);+ for (JitVal v : vals) {+ assignments.put(v, JitTypeBehavior.ANY);+ }++ while (!queue.isEmpty()) {+ JitVal v = queue.removeFirst();+ JitTypeBehavior type = computeNewAssignment(v);+ JitTypeBehavior old = assignments.put(v, type);+ if (old != type) {+ queueNeighbors(v);+ }+ }+ }++ /**+ * Get the final type assignment for the given value+ *+ * @param v the value+ * @return the value's assigned type+ */+ public JitType typeOf(JitVal v) {+ return assignments.get(v).type(v.size());+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitVarScopeModel.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitVarScopeModel.javanew file mode 100644index 0000000000..e5431f7b76--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitVarScopeModel.java@@ -0,0 +1,531 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import java.util.*;+import java.util.Map.Entry;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.JitCompiler;+import ghidra.pcode.emu.jit.JitCompiler.Diag;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.program.model.address.Address;+import ghidra.program.model.lang.Register;+import ghidra.program.model.pcode.Varnode;+import ghidra.util.MathUtilities;++/**+ * The variable scope analysis of JIT-accelerated emulation.+ *+ * <p>+ * This implements the Variable Scope Analysis phase of the {@link JitCompiler}. The result provides+ * the set of in-scope (alive) varnodes for each basic block. The design of this analysis, and the+ * shortcuts we take, are informed by the design of downstream phases. In particular, we do not+ * intend to allocate each SSA variable. There are often many, many such variables, and attempting+ * to allocate them to as few target resources, e.g., JVM locals, as possible is <em>probably</em> a+ * complicated and expensive algorithm. I don't think we'd gain much from it either. Instead, we'll+ * just allocate by varnode. To do that, though, we still have to consider that some varnodes+ * overlap and otherwise alias others. If we are able to handle all that aliasing in place, then we+ * need not generate code for the synthetic ops. One might ask, well then why do any of the Data+ * Flow Analysis in the first place? 1) We still need data flow to inform the selection of JVM local+ * types. We have not measured the run-time cost of the bitwise casts, but we do know the bytecode+ * for each cast occupies space, counted against the 65,535-byte max. 2) We also need data flow to+ * inform operation elimination, which removes many wasted flag computations.+ *+ * <p>+ * To handle the aliasing, we coalesce overlapping varnodes. For example, {@code EAX} will get+ * coalesced with {@code RAX}, but {@code BH} <em>will not</em> get coalesced with {@code BL},+ * assuming no other part of {@code RBX} is accessed. The {@link JitDataFlowModel} records all+ * varnodes accessed in the course of its intra-block analysis. Only those actually accessed are+ * considered. We then compute scope in terms of these coalesced varnodes. For example, if both+ * {@code RAX} and {@code EAX} are used by a passage, then an access of {@code EAX} causes+ * {@code RAX} to remain in scope.+ *+ * <p>+ * The decision to compute scope on a block-by-block basis instead of op-by-op is for simplicity. We+ * intend to birth and retire variables along block transitions by considering what variables are+ * coming into or leaving scope on the flow edge. <em>Birthing</em> is just reading a variable's+ * value from the run-time {@link JitBytesPcodeExecutorState state} into its allocated JVM local.+ * Conversely, <em>retiring</em> is writing the value back out to the state. There's little to be+ * gained by retiring a variable midway through a block as opposed to the end of the block. Perhaps+ * if one giant block handles a series of variables in sequence, we could have used a single JVM+ * local to allocate each, but we're already committed to allocating a JVM local per (coalesced)+ * varnode. So, while that may ensure only one variable is alive at a time, the number of JVM locals+ * required remains the same. Furthermore, the amount of bytecode emitted remains the same, but at+ * different locations in the block. The case where this might be worth considering is a userop+ * invocation, because all live variables must be forcefully retired.+ *+ * <p>+ * We then consider what common cases we want to ensure are optimized, when we're limited to a+ * block-by-block analysis. One that comes to mind is a function with an early bail. Consider the+ * following C source:+ *+ * <pre>+ * int func(my_struct* ptr) {+ * if (ptr == NULL) {+ * return ERR;+ * }+ * // Do some serious work+ * return ptr->v;+ * }+ * </pre>+ *+ * <p>+ * Often, the C compiler will group all the returns into one final basic block, so we might get the+ * following p-code:+ *+ * <pre>+ * 1 RSP = INT_SUB RSP, 0x20:8+ * 2 $U00:1 = INT_EQUAL RDI, 0:8 # RDI is ptr+ * 3 CBRANCH <err>, $U0:1+ *+ * 4 # Do some serious work+ * 5 $U10:8 = INT_ADD RDI, 0xc:8 # Offset to field v+ * 6 EAX = LOAD [ram] $U10:8+ * 7 BRANCH <exit>+ * <err>+ * 8 EAX = COPY 0xffffffff:4+ * <exit>+ * 9 RSP = INT_ADD RSP, 0x20:8+ * 10 RIP = LOAD [ram] RSP+ * 11 RSP = INT_ADD RSP, 8:8+ * 12 RETURN RIP+ * </pre>+ *+ * <p>+ * Note that I've elided the actual x86 machine code and all of the noise generated by C compilation+ * and p-code lifting, and I've presumed the decoded passage contains exactly the example function.+ * The result is your typical if-else diamond. We'll place the error case on the left:+ *+ * <pre>+ * +---------++ * | 1--3 |+ * | CBRANCH |+ * +-T-----F-++ * / \+ * / \+ * +--------+ +--------++ * | 8 | | 4--7 |+ * | (fall) | | BRANCH |+ * +--------+ +--------++ * \ /+ * \ /+ * +---------++ * | 9--12 |+ * | RETURN |+ * +---------++ * </pre>+ *+ * <p>+ * Suppose the "serious work" on line 4 accesses several varnodes: RBX, RCX, RDX, and RSI. If+ * execution follows the error path, we'd rather not birth any of those variables. Thus, we might+ * like the result of the scope analysis to be:+ *+ * <p>+ * <table border="1">+ * <tr>+ * <th>Block</th>+ * <th>Live Vars</th>+ * </tr>+ * <tr>+ * <td>1–3</td>+ * <td>RDI, RSP, $U00:1</td>+ * </tr>+ * <tr>+ * <td>4–7</td>+ * <td>EAX, RBX, RCX, RDI, RDX, RSI, RSP, $U10:8</td>+ * </tr>+ * <tr>+ * <td>8</td>+ * <td>EAX, RSP</td>+ * </tr>+ * <tr>+ * <td>9–12</td>+ * <td>RIP, RSP</td>+ * </tr>+ * </table>+ *+ * <p>+ * This can be achieved rather simply: Define two sets for each block, the upward view and the+ * downward view. The first corresponds to all varnodes that could be accessed before entering this+ * block or while in it. The second corresponds to all varnodes that could be access while in this+ * block or after leaving it. The upward view is computed by initializing each set to the varnodes+ * accessed by its block. Then we "push" each set upward by adding its elements into the set for+ * each block with flows into this one, until the sets converge. The downward sets are similarly+ * computed, independently of the upward sets. The result is the intersection of these sets, per+ * block. The algorithm is somewhat intuitive in that we accrue live variables as we move toward the+ * "body" of the control flow graph, and they begin to drop off as we approach an exit. The accrual+ * is captured by the downward set, and the drop off is captured by intersection with the upward+ * set. This will also prevent retirement and rebirth of variables. Essentially, if we are between+ * two accesses of a varnode, then that varnode is alive. Consider {@code RSP} from the example+ * above. The algorithm considers it alive in blocks 4–7 and 8, despite the fact neither+ * actually accesses it. Nevertheless, we'd rather generate one birth upon entering block 1–3,+ * keep it alive in the body, and then generate one retirement upon leaving block 9–12.+ *+ * <p>+ * One notable effect of this algorithm is that all blocks in a loop will have the same variables in+ * scope.... I think this is okay. We'll birth the relevant variables upon entering the loop, keep+ * them all alive during loop execution, and then retire them (unless they're accessed downstream)+ * upon leaving.+ *+ * @implNote <b>TODO</b>: There's some nonsense to figure out with types. It would be nice if we+ * could allow variables of different types to occupy the same location at different+ * times. This can be the case, e.g., if a register is used as a temporary location for+ * copying values around. If there are times when it's treated as an int and other times+ * when it's treated as a float, we could avoid unnecessary Java type conversions.+ * However, this would require us to track liveness with types, and at that granularity,+ * it could get unwieldy. My inclination is to just consider location liveness and then+ * have the allocator decide what type to assign the local variable for that location+ * based on some voting system. This is not the best, because some access sites are+ * executed more often than others, but it'll suffice.+ */+public class JitVarScopeModel {++ /**+ * Encapsulates set movement when computing the upward and downward views.+ */+ enum Which {+ /**+ * Set movement for the upward view+ */+ UP {+ @Override+ Collection<JitBlock> getFlows(ScopeInfo info) {+ return info.block.flowsTo().values().stream().map(BlockFlow::from).toList();+ }++ @Override+ Set<Varnode> getLive(ScopeInfo info) {+ return info.liveUp;+ }++ @Override+ Set<Varnode> getQueued(ScopeInfo info) {+ return info.queuedUp;+ }+ },+ /**+ * Set movement for the downward view+ */+ DOWN {+ @Override+ Collection<JitBlock> getFlows(ScopeInfo info) {+ return info.block.flowsFrom().values().stream().map(BlockFlow::to).toList();+ }++ @Override+ Set<Varnode> getLive(ScopeInfo info) {+ return info.liveDn;+ }++ @Override+ Set<Varnode> getQueued(ScopeInfo info) {+ return info.queuedDn;+ }+ };++ /**+ * Get the flow toward which we will push the given block's set+ *+ * @param info the intermediate analytic result for the block whose set to push+ * @return the blocks into which our set will be unioned+ */+ abstract Collection<JitBlock> getFlows(ScopeInfo info);++ /**+ * Get the current set for the given block+ *+ * @param info the intermediate analytic result for the block whose set to get+ * @return the set of live varnodes+ */+ abstract Set<Varnode> getLive(ScopeInfo info);++ /**+ * Get the varnodes which are queued for addition into the given block's set+ *+ * @param info the intermediate analytic result for the given block+ * @return the set of queued live varnodes+ */+ abstract Set<Varnode> getQueued(ScopeInfo info);+ }++ /**+ * Encapsulates the (intermediate) analytic result for each block+ */+ private class ScopeInfo {+ private final JitBlock block;+ private final Set<Varnode> liveUp = new HashSet<>();+ private final Set<Varnode> liveDn = new HashSet<>();++ private final Set<Varnode> queuedUp = new HashSet<>();+ private final Set<Varnode> queuedDn = new HashSet<>();++ private final Set<Varnode> liveVars = new LinkedHashSet<>();+ private final Set<Varnode> liveVarsImm = Collections.unmodifiableSet(liveVars);++ /**+ * Construct the result for the given block+ *+ * @param block the block+ */+ public ScopeInfo(JitBlock block) {+ this.block = block;++ JitDataFlowBlockAnalyzer dfa = dfm.getAnalyzer(block);+ for (Varnode vn : dfa.getVarnodesRead()) {+ if (!vn.isAddress()) {+ queuedUp.add(getCoalesced(vn));+ queuedDn.add(getCoalesced(vn));+ }+ }+ for (Varnode vn : dfa.getVarnodesWritten()) {+ if (!vn.isAddress()) {+ queuedUp.add(getCoalesced(vn));+ queuedDn.add(getCoalesced(vn));+ }+ }+ }++ /**+ * Push this block's queue for the given view+ *+ * <p>+ * Any block whose set was affected by this push is added to the queue of blocks to be+ * processed again.+ *+ * @param which which view (direction)+ */+ private void push(Which which) {+ Set<Varnode> queued = which.getQueued(this);+ if (queued.isEmpty()) {+ return;+ }+ for (JitBlock block : which.getFlows(this)) {+ ScopeInfo that = infos.get(block);+ Set<Varnode> toQueueThat = new HashSet<>(queued);+ toQueueThat.removeAll(which.getLive(that));+ if (which.getQueued(that).addAll(toQueueThat)) {+ blockQueue.add(that);+ }+ }+ which.getLive(this).addAll(queued);+ queued.clear();+ }++ /**+ * Finish the analytic computation for this block+ *+ * <p>+ * If a block contains an access to a variable, that variable is alive in that block. If a+ * block is between (in terms of possible control-flow paths) two others that access a+ * variable, that variable is alive in the block.+ */+ private void finish() {+ List<Varnode> sortedLiveUp = new ArrayList<>(this.liveUp);+ Collections.sort(sortedLiveUp, Comparator.comparing(Varnode::getAddress));+ liveVars.addAll(sortedLiveUp);+ liveVars.retainAll(liveDn);+ }+ }++ private final JitControlFlowModel cfm;+ private final JitDataFlowModel dfm;++ private final NavigableMap<Address, Varnode> coalesced = new TreeMap<>();++ private final Map<JitBlock, ScopeInfo> infos = new HashMap<>();+ private final SequencedSet<ScopeInfo> blockQueue = new LinkedHashSet<>();++ /**+ * Construct the model+ *+ * @param cfm the control flow model+ * @param dfm the data flow model+ */+ public JitVarScopeModel(JitControlFlowModel cfm, JitDataFlowModel dfm) {+ this.cfm = cfm;+ this.dfm = dfm;++ analyze();+ }++ /**+ * Get the maximum address (inclusive) in the varnode+ *+ * @param varnode the node+ * @return the max address+ */+ static Address maxAddr(Varnode varnode) {+ return varnode.getAddress().add(varnode.getSize() - 1);+ }++ /**+ * Check for overlap when one varnode is known to be to the left of the other.+ *+ * @param left the left varnode (having lower address)+ * @param right the right varnode (having higher address)+ * @return true if they overlap (not counting abutting), false otherwise.+ */+ static boolean overlapsLeft(Varnode left, Varnode right) {+ // max is inclusive, so use >=, not just >+ return maxAddr(left).compareTo(right.getAddress()) >= 0;+ }++ private void coalesceVarnode(Varnode varnode) {+ Address min = varnode.getAddress();+ Address max = maxAddr(varnode);+ Entry<Address, Varnode> leftEntry = coalesced.floorEntry(min);+ if (leftEntry != null && overlapsLeft(leftEntry.getValue(), varnode)) {+ min = leftEntry.getKey();+ }+ Entry<Address, Varnode> rightEntry = coalesced.floorEntry(max);+ if (rightEntry != null) {+ max = MathUtilities.cmax(max, maxAddr(rightEntry.getValue()));+ }+ Varnode exists = leftEntry == null ? null : leftEntry.getValue();+ Varnode existsRight = rightEntry == null ? null : rightEntry.getValue();+ if (exists == existsRight && exists != null && exists.getAddress().equals(min) &&+ maxAddr(exists).equals(max)) {+ return; // no change+ }+ coalesced.subMap(min, true, maxAddr(varnode), true).clear();+ coalesced.put(min, new Varnode(min, (int) max.subtract(min) + 1));+ }++ private void coalesceVarnodes() {+ Set<Varnode> allVarnodes = new HashSet<>();+ for (JitBlock block : cfm.getBlocks()) {+ allVarnodes.addAll(dfm.getAnalyzer(block).getVarnodesRead());+ allVarnodes.addAll(dfm.getAnalyzer(block).getVarnodesWritten());+ }+ for (Varnode varnode : allVarnodes) {+ if (!varnode.isAddress()) {+ coalesceVarnode(varnode);+ }+ }+ }++ /**+ * Get the varnode into which the given varnode was coalesced+ *+ * <p>+ * In many cases, the result is the same varnode.+ *+ * @param part the varnode+ * @return the coalesced varnode+ */+ public Varnode getCoalesced(Varnode part) {+ if (part.isAddress()) {+ return part;+ }+ Entry<Address, Varnode> floorEntry = coalesced.floorEntry(part.getAddress());+ assert overlapsLeft(floorEntry.getValue(), part);+ return floorEntry.getValue();+ }++ /**+ * Perform a push for the given direction for the next block in the queue.+ *+ * <p>+ * Any block whose varnode queue was affected is added back into the block queue.+ *+ * @param which which view is being computed (direction)+ * @return true if there remains at least one block in the queue+ */+ private boolean pushNext(Which which) {+ if (blockQueue.isEmpty()) {+ return false;+ }+ ScopeInfo info = blockQueue.removeFirst();+ info.push(which);+ return !blockQueue.isEmpty();+ }++ /**+ * Perform the analysis.+ *+ * <p>+ * This starts with the upward set, which is computed by pushing queued block's varnodes upward+ * until the queue is empty. All blockes are queued initially. When a block's set is affected,+ * it's re-added to the queue, so we know we've converged when the queue is empty. The downward+ * set is then computed in the same fashion.+ */+ private void analyze() {+ coalesceVarnodes();+ for (JitBlock block : cfm.getBlocks()) {+ ScopeInfo info = new ScopeInfo(block);+ infos.put(block, info);+ blockQueue.add(info);+ }+ while (pushNext(Which.UP)) {+ }++ blockQueue.addAll(infos.values());+ while (pushNext(Which.DOWN)) {+ }++ for (ScopeInfo info : infos.values()) {+ info.finish();+ }+ }++ /**+ * Get the collection of all coalesced varnodes+ *+ * @return the varnodes+ */+ public Iterable<Varnode> coalescedVarnodes() {+ return coalesced.values();+ }++ /**+ * Get the set of live varnodes for the given block+ *+ * @param block the block+ * @return the live varnodes+ */+ public Set<Varnode> getLiveVars(JitBlock block) {+ return infos.get(block).liveVarsImm;+ }++ /**+ * For diagnostics: Dump the analysis result to stderr+ *+ * @see Diag#PRINT_VSM+ */+ public void dumpResult() {+ System.err.println("STAGE: VarLiveness");+ for (JitBlock block : cfm.getBlocks()) {+ System.err.println(" Block: " + block);+ Set<String> liveNames = new TreeSet<>();+ for (Varnode vn : infos.get(block).liveVarsImm) {+ Register register = block.getLanguage().getRegister(vn.getAddress(), vn.getSize());+ if (register != null) {+ liveNames.add(register.getName());+ }+ else if (vn.isUnique()) {+ liveNames.add("$U%x:%d".formatted(vn.getOffset(), vn.getSize()));+ }+ else {+ liveNames.add("%s:%x:4".formatted(vn.getAddress().getAddressSpace().getName(),+ vn.getOffset(), vn.getSize()));+ }+ }+ System.err.println(" Live: " + liveNames);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecodedStride.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecodedStride.javanew file mode 100644index 0000000000..d1d069eb24--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecodedStride.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.pcode.emu.jit.decode;++import java.util.List;++import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.pcode.PcodeOp;++/**+ * A list of contiguous instructions connected by fall through, along with their emitted p-code ops+ *+ * @param start the address and contextreg value that seeded this stride+ * @param instructions the instructions in the order decoded+ * @param ops the ops in the order decoded and emitted+ * @see JitPassageDecoder+ */+record DecodedStride(AddrCtx start, List<Instruction> instructions, List<PcodeOp> ops) {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderExecutor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderExecutor.javanew file mode 100644index 0000000000..a48660ae4d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderExecutor.java@@ -0,0 +1,563 @@+/* ###+ * 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.pcode.emu.jit.decode;++import java.math.BigInteger;+import java.util.*;++import ghidra.app.plugin.processors.sleigh.SleighParserContext;+import ghidra.app.util.PseudoInstruction;+import ghidra.pcode.emu.PcodeMachine;+import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.*;+import ghidra.pcode.emu.jit.analysis.JitDataFlowState;+import ghidra.pcode.emu.jit.op.JitNopOp;+import ghidra.pcode.exec.*;+import ghidra.program.disassemble.Disassembler;+import ghidra.program.model.address.Address;+import ghidra.program.model.lang.*;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.listing.ProgramContext;+import ghidra.program.model.mem.MemoryAccessException;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.util.Msg;++/**+ * The p-code interpreter used during passage decode+ *+ * <p>+ * Aside from branches, this interpreter simply logs each op, so that they get collected into the+ * greater stride and passage. It does "rewrite" the ops, so that we can easily recover the input+ * context, especially when the op is emitted from a user inject. For branches, this interpreter+ * creates the appropriate {@link Branch} records and notifies the passage decoder of new seeds.+ *+ * <p>+ * This executor also implements the {@link DisassemblerContext} to track context changes, namely+ * uses of {@code globalset}. This is kept in {@link #futCtx}. <b>TODO</b>: Should {@link #futCtx}+ * be moved into the passage decoder to ensure it persists for more than a single instruction? I'm+ * not sure whether or not that is already taken care of by the {@link Disassembler}.+ *+ * @implNote I had considered using a {@link JitDataFlowState} here, but that's Not a Good Idea,+ * because a stride is not generally a <em>basic block</em>. A "stride" is just a+ * contiguous run of instructions with fall-through. If there is a jump into the middle of+ * it, any value analysis (e.g., constant folding) would be meaningless. Were we to put+ * this in there, the temptation may be to have userop libraries attempt constant+ * resolution, esp., for syscall numbers. While that may work, if only because syscall+ * numbers are conventionally set in the same basic block as the invocation, there's no+ * guarantee that's the case. And there may be other use cases where this is totally+ * wrong. Instead, we should use as barren an executor here as possible. We do incorporate+ * injects here, because they may affect control flow, which the decoder must consider.+ *+ * @implNote <b>WARNING</b>: This executor has no {@link PcodeExecutorState state} object. Care must+ * be taken to ensure we override any method that assumes we have one, and that we don't+ * invoke any method from the superclass that assumes we have one.+ *+ */+class DecoderExecutor extends PcodeExecutor<Object>+ implements DisassemblerContextAdapter {+ private final DecoderForOneStride stride;+ final AddrCtx at;++ private PseudoInstruction instruction;+ private NopPcodeOp termNop;++ private RegisterValue flow;+ private final Map<Address, RegisterValue> futCtx = new HashMap<>();++ final List<PcodeOp> opsForThisStep = new ArrayList<>();+ private final List<Branch> branchesForThisStep = new ArrayList<>();++ private final Map<PcodeOp, DecodedPcodeOp> rewrites = new HashMap<>();++ /**+ * Construct the interpreter+ *+ * @param stride the stride being decoded+ * @param at the address and contextreg value of the instruction+ * @param instruction the instruction, or {@code null}+ */+ DecoderExecutor(DecoderForOneStride stride, AddrCtx at, PseudoInstruction instruction) {+ super(stride.decoder.thread.getLanguage(), null, null, null);+ this.stride = stride;+ this.at = at;+ setInstruction(instruction);+ }++ /**+ * Construct the interpreter without an instruction+ *+ * <p>+ * This initializes the interpreter without an instruction. The decoder must set the instruction+ * via {@link #setInstruction(PseudoInstruction)} as soon as it becomes available, either 1)+ * because the step resulted in a simple instruction, or 2) because a user inject caused the+ * instruction to be decoded.+ *+ * @param stride the stride being decoded+ * @param at the address and contextreg value of the instruction+ */+ DecoderExecutor(DecoderForOneStride stride, AddrCtx at) {+ this(stride, at, null);+ }++ /**+ * Re-write the given op as a {@link DecodedPcodeOp} with the given address/contextreg value+ *+ * <p>+ * If the given op is already a {@link DecodedPcodeOp}, i.e., a {@link DecodeErrorPcodeOp} or+ * {@link NopPcodeOp}, just return the same op without re-writing.+ *+ * @param at the address and decode context+ * @param op the original p-code op+ * @return the equivalent op, re-written+ */+ static DecodedPcodeOp rewriteOp(AddrCtx at, PcodeOp op) {+ if (op instanceof DecodedPcodeOp dec) {+ assert dec.getAt().equals(at);+ return dec;+ }+ return new DecodedPcodeOp(at, op);+ }++ /**+ * Re-write the given op+ *+ * <p>+ * Because we create an interpreter for each instruction step, we already know the target+ * address and decode context. We re-write the op to capture that target. If we've already+ * re-written the op, return the existing one to ensure we retain identity in the re-written+ * realm.+ *+ * @param op the op to re-write+ * @return the equivalent op, re-written+ */+ DecodedPcodeOp rewrite(PcodeOp op) {+ return rewrites.computeIfAbsent(op, o -> rewriteOp(at, o));+ }++ /**+ * Set the current instruction.+ *+ * <p>+ * This also pre-computes the resulting "flow" context from the given instruction. That is, the+ * input context for the next decode instruction, not accounting for {@code globalset}. It is+ * computed by taking the given instruction's input context and resetting non-flowing bits to+ * the language's defaults. When a branch is encountered or fall through is considered, we+ * account for {@code globalset} and derive the target context for the target address.+ *+ * @param instruction the instruction+ */+ void setInstruction(PseudoInstruction instruction) {+ this.instruction = instruction;+ if (at.rvCtx == null || instruction == null ||+ instruction instanceof DecodeErrorInstruction) {+ this.flow = at.rvCtx;+ }+ else {+ Register contextreg = stride.decoder.contextreg;+ ProgramContext defaultContext = stride.decoder.defaultContext;+ this.flow = new RegisterValue(contextreg, BigInteger.ZERO)+ .combineValues(defaultContext.getDefaultValue(contextreg, at.address))+ .combineValues(defaultContext.getFlowValue(at.rvCtx));+ processContextChanges();+ }+ }++ /**+ * Decode the instruction this executor is meant to interpret+ *+ * <p>+ * This can be delayed if there is a user inject at the target address. In that case, this may+ * be invoked by {@link DecoderUseropLibrary#emu_exec_decoded(PcodeExecutor)} or+ * {@link DecoderUseropLibrary#emu_skip_decoded(PcodeExecutor)}.+ *+ * @return the decoded instruction, which may be a {@link DecodeErrorInstruction}+ */+ PseudoInstruction decodeInstruction() {+ PseudoInstruction instruction = stride.decoder.decodeInstruction(at.address, at.rvCtx);+ setInstruction(instruction);+ return instruction;+ }++ private void processContextChanges() {+ try {+ SleighParserContext parserCtx =+ (SleighParserContext) instruction.getParserContext();+ parserCtx.applyCommits(this);+ }+ catch (MemoryAccessException e) {+ throw new AssertionError(e);+ }+ }++ /**+ * Interpret the given program with the passage decoder's userop library+ *+ * @param program the p-code to interpret+ */+ public void execute(PcodeProgram program) {+ execute(program, stride.passage.library());+ }++ /**+ * {@inheritDoc}+ *+ * @implNote We check here if a "terminal nop" was necessary. Any jump to (should never be past)+ * the end of the program will require one. Instead of trying to figure out what the+ * op following this instruction is, so the jumps can target it, we add a special nop,+ * and the jump is made to target it. Once we reach the end of the p-code program+ * proper, we have to add that nop.+ */+ @Override+ public void finish(PcodeFrame frame, PcodeUseropLibrary<Object> library) {+ super.finish(frame, library);+ if (termNop != null) {+ opsForThisStep.add(termNop);+ }+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * We only really need to interpret branching ops here. We also interpret+ * {@link PcodeOp#CALLOTHER callother}, in case wer're able to inline a p-code userop. Note that+ * if we inline the userop, we still retain the {@code callother} op, because internal jumps may+ * target it. It is easier to leave it in the books and {@link JitNopOp nop} it out later than+ * to try to substitute the first inlined op. Worse, if the inlined userop emits no p-code,+ * substitution would get especially difficult.+ *+ * <p>+ * We also interpret {@link PcodeOp#UNIMPLEMENTED unimplemented}, because that will require us+ * to create an {@link ErrBranch} record. All other ops must still be added to the decoded+ * passage, but not (yet) interpreted.+ */+ @Override+ public void stepOp(PcodeOp op, PcodeFrame frame, PcodeUseropLibrary<Object> library) {+ /**+ * NOTE: Must log every op, including inlined CALLOTHER's, because an internal jump may+ * refer to that CALLOTHER. It's easier, I think, to snuff the op later than it is to try to+ * substitute the refs.+ */+ op = rewrite(op);+ switch (op.getOpcode()) {+ case PcodeOp.BRANCH, //+ PcodeOp.CBRANCH, //+ PcodeOp.CALL, //+ PcodeOp.BRANCHIND, //+ PcodeOp.CALLIND, //+ PcodeOp.RETURN, //+ PcodeOp.CALLOTHER, //+ PcodeOp.UNIMPLEMENTED -> {+ opsForThisStep.add(op);+ super.stepOp(op, frame, library);+ }+ default -> {+ opsForThisStep.add(op);+ }+ }+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * We interpret this the same as an unconditional branch, because at this point, we need only+ * collect branch targets to seed additional strides.+ */+ @Override+ public void executeConditionalBranch(PcodeOp op, PcodeFrame frame) {+ doExecuteBranch(op, frame);+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * We override this to prevent an attempt to write PC to the {@link #getState() state}, which is+ * {@code null}.+ */+ @Override+ protected void branchToOffset(PcodeOp op, long offset, PcodeFrame frame) {+ }++ @Override+ protected void branchToOffset(PcodeOp op, Object offset, PcodeFrame frame) {+ throw new AssertionError();+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This creates an {@link ExtBranch} record and collects it for this instruction step. The+ * record will first be used to check for fall through. Then, the passage decoder is notified,+ * which either adds it to the seed queue or converts it to an {@link IntBranch} record.+ *+ * @see #checkFallthroughAndAccumulate(PcodeProgram)+ */+ @Override+ protected void branchToAddress(PcodeOp op, Address target) {+ branchesForThisStep.add(new ExtBranch(op, takeTargetContext(target)));+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This create an {@link IntBranch} record and collects it for this instruction step. The record+ * will first be used to check for fall through. Then, the passage decoder is notified, which+ * collects the records to later passage-wide control flow analysis.+ *+ * @see #checkFallthroughAndAccumulate(PcodeProgram)+ */+ @Override+ protected void branchInternal(PcodeOp op, PcodeFrame frame, int relative) {+ int tgtSeq = op.getSeqnum().getTime() + relative;+ if (tgtSeq == frame.getCode().size()) {+ if (termNop == null) {+ termNop = new NopPcodeOp(at, tgtSeq);+ }+ branchesForThisStep.add(new IntBranch(op, termNop, false));+ }+ else {+ PcodeOp to = frame.getCode().get(op.getSeqnum().getTime() + relative);+ branchesForThisStep.add(new IntBranch(op, rewrite(to), false));+ }+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This create an {@link IndBranch} record and collects it for this instruction step. The record+ * will first be used to check for fall through. Then, the passage decoder is notified, which+ * collects the records to later passage-wide control flow analysis.+ *+ * @see #checkFallthroughAndAccumulate(PcodeProgram)+ */+ @Override+ protected void doExecuteIndirectBranch(PcodeOp op, PcodeFrame frame) {+ branchesForThisStep.add(new IndBranch(op, flow));+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This create an {@link ErrBranch} record and collects it for this instruction step. The record+ * will first be used to check for fall through. Then, the passage decoder is notified, which+ * collects the records to later passage-wide control flow analysis. In most (all?) cases, this+ * is the only op emitted by the instruction (decode error, unimplemented instruction), and so+ * there is certainly no fall through.+ *+ * @see #checkFallthroughAndAccumulate(PcodeProgram)+ */+ @Override+ protected void badOp(PcodeOp op) {+ String message;+ if (instruction instanceof DecodeErrorInstruction err) {+ message = err.getMessage();+ }+ else {+ message =+ "Encountered an unimplemented instruction at " + at + " (" + instruction + ")";+ }+ branchesForThisStep.add(new ErrBranch(op, message));+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This create an {@link ErrBranch} record and collects it for this instruction step. The record+ * will first be used to check for fall through. Then, the passage decoder is notified, which+ * collects the records to later passage-wide control flow analysis. In contrast to+ * {@link #badOp(PcodeOp)}, an instruction that calls a missing userop may still have fall+ * through.+ */+ @Override+ protected void onMissingUseropDef(PcodeOp op, PcodeFrame frame, String opName,+ PcodeUseropLibrary<Object> library) {+ branchesForThisStep.add(+ new ErrBranch(op, "Sleigh userop '%s' is not in the library".formatted(opName)));+ }++ @Override+ public void setFutureRegisterValue(Address address, RegisterValue value) {+ if (!value.getRegister().isProcessorContext()) {+ return;+ }+ futCtx.compute(address, (a, v) -> v == null ? value : v.combineValues(value));+ }++ /**+ * Derive the contextreg value at the given target address (branch or fall through).+ *+ * <p>+ * An instruction's constructors may use {@code globalset} to place context changes at specific+ * addresses. Those changes are collected by+ * {@link #setFutureRegisterValue(Address, RegisterValue)} through some chain of method+ * invocations started by {@link #setInstruction(PseudoInstruction)}. When the interpreter+ * encounters a branch op, that op will specify the target address. We must also derive the+ * context for that branch. This is the pre-computed "flow" context, but now accounting for+ * {@code globalset} at the target address.+ *+ * @param target the target address+ * @return the target address and contextreg value+ */+ public AddrCtx takeTargetContext(Address target) {+ if (!futCtx.containsKey(target)) {+ return new AddrCtx(flow, target);+ }+ /** Do not remove, in case there are multiple branches to the same target address */+ return new AddrCtx(flow.combineValues(futCtx.get(target)), target);+ }++ /**+ * After p-code interpretation, check if the instruction has fall through, notify the stride+ * decoder of the instruction's ops, and notify the passage of the instruction's branches.+ *+ * <p>+ * To determine whether there's fall through, this performs a miniature control flow analysis on+ * just this step's p-code ops. This is required because a user inject can be very complex, and+ * need not obey all of the usual control flow checks imposed by the Sleigh semantic compiler.+ * In particular {@link Instruction#hasFallthrough()} is not sufficient, for at least two+ * reasons: 1) The aforementioned user inject possibilities, 2) We do not consider a+ * {@link PcodeOp#CALL call} or {@link PcodeOp#CALLIND callind} as having fall through.+ *+ * <p>+ * To use control flow analysis as a means of checking for fall through, we append a special+ * "probe" {@link ExitPcodeOp} along with an {@link ExtBranch} record to {@link AddrCtx#NOWHERE+ * nowhere}. The probe thus serves the secondary purpose of preventing any complaints from the+ * analyzer about unterminated control flow. We then perform the analysis, borrowing+ * {@link BlockSplitter} from {@link JitControlFlowModel}. In practice, this seems fast enough.+ * Because the splitter keeps the blocks in the original order, the first op will certainly be+ * in the first block, and the probe op will certainly be in the last block. We perform a simple+ * reachability test between the two. The step has fall through if and only if a path is found.+ *+ * @param from the instruction's or inject's p-code+ * @return true if the step falls through.+ */+ public boolean checkFallthroughAndAccumulate(PcodeProgram from) {+ if (instruction instanceof DecodeErrorInstruction) {+ stride.opsForStride.addAll(opsForThisStep);+ for (Branch branch : branchesForThisStep) {+ switch (branch) {+ case ErrBranch eb -> stride.passage.otherBranches.put(eb.from(), eb);+ default -> throw new AssertionError();+ }+ }+ return false;+ }+ if (opsForThisStep.isEmpty()) {+ return true;+ }++ ExitPcodeOp probeOp = new ExitPcodeOp(AddrCtx.NOWHERE);+ opsForThisStep.add(probeOp);+ ExtBranch probeBranch = new ExtBranch(probeOp, AddrCtx.NOWHERE);+ branchesForThisStep.add(probeBranch);++ PcodeProgram program = new PcodeProgram(from, opsForThisStep);+ BlockSplitter splitter = new BlockSplitter(program);+ splitter.addBranches(branchesForThisStep);+ SequencedMap<PcodeOp, JitBlock> blocks = splitter.splitBlocks();+ JitBlock entry = blocks.firstEntry().getValue();+ JitBlock exit = blocks.lastEntry().getValue();++ Set<JitBlock> reachable = new HashSet<>();+ collectReachable(reachable, entry);++ for (JitBlock block : blocks.values()) {+ for (PcodeOp op : block.getCode()) {+ if (op != probeOp) {+ stride.opsForStride.add(op);+ }+ }+ for (IntBranch branch : block.branchesFrom()) {+ if (!branch.isFall()) {+ stride.passage.internalBranches.put(branch.from(), branch);+ }+ }+ for (Branch branch : block.branchesOut()) {+ if (branch != probeBranch) {+ switch (branch) {+ case ExtBranch eb -> stride.passage.flowTo(eb);+ default -> stride.passage.otherBranches.put(branch.from(), branch);+ }+ }+ }+ }++ return reachable.contains(exit);+ }++ /**+ * The reachability test mentioned in {@link #checkFallthroughAndAccumulate(PcodeProgram)}+ *+ * <p>+ * Collects the set of blocks reachable from {@code cur} into the given mutable set.+ *+ * @param into a mutable set for collecting reachable blocks+ * @param cur the source block, or an intermediate during recursion+ */+ private void collectReachable(Set<JitBlock> into, JitBlock cur) {+ if (!into.add(cur)) {+ return;+ }+ for (BlockFlow flow : cur.flowsFrom().values()) {+ collectReachable(into, flow.to());+ }+ }++ /**+ * Compute the fall-through address+ *+ * <p>+ * This computes the "next" address whether or not the instruction actually has fall through.+ * The caller should check for fall through first.+ *+ * @return the next address+ * @implNote If no instruction was actually decoded during this step, and the decoder is asking+ * about fall through, then the user very likely made an error in specifying an+ * inject's control flow, in which case the counter will not advance. To get this same+ * effect, we just return the current address. The decoder and/or translator ought to+ * recognize this and ensure the resulting infinite loop can be interrupted.+ * @see PcodeMachine#inject(Address, String)+ */+ Address getAdvancedAddress() {+ if (instruction != null) {+ return instruction.getMaxAddress().next();+ }+ Msg.warn(this, "An inject may have forgotten control flow.");+ return at.address;+ }++ /**+ * Notify the stride of an instruction+ *+ * <p>+ * For addresses without injects, every decoded instruction ought to be included in the stride.+ * For an address with an inject, a decoded instruction should only be included if it is+ * actually interpreted, i.e., its ops are included.+ *+ * @param instruction the decoded instruction+ */+ void addInstruction(PseudoInstruction instruction) {+ stride.instructions.add(instruction);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderForOnePassage.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderForOnePassage.javanew file mode 100644index 0000000000..21a4fda003--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderForOnePassage.java@@ -0,0 +1,169 @@+/* ###+ * 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.pcode.emu.jit.decode;++import java.util.*;+import java.util.Map.Entry;++import org.apache.commons.collections4.MapUtils;++import ghidra.pcode.emu.jit.JitConfiguration;+import ghidra.pcode.emu.jit.JitPassage;+import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.exec.PcodeUseropLibrary;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The decoder for a single passage+ *+ * <p>+ * This is a sort of "mutable" passage or passage "builder" that is used while the passage is being+ * decoded. Once complete, this provides an immutable (or at least it's supposed to be) decoded+ * {@link Passage}.+ */+class DecoderForOnePassage {+ private final JitPassageDecoder decoder;+ private final AddrCtx seed;+ private final int maxOps;+ private final int maxInstrs;+ private final int maxStrides;++ final Map<PcodeOp, IntBranch> internalBranches = new HashMap<>();+ final SequencedMap<PcodeOp, ExtBranch> externalBranches = new LinkedHashMap<>();+ final Map<PcodeOp, Branch> otherBranches = new HashMap<>();+ final Map<AddrCtx, PcodeOp> firstOps = new HashMap<>();+ final List<DecodedStride> strides = new ArrayList<>();++ private int opCount = 0;+ private int instructionCount = 0;++ /**+ * Construct the decoder+ *+ * @param decoder the thread's passage decoder+ * @param seed the seed for this passage+ * @param maxOps the maximum-ish number of p-code ops to emit+ */+ DecoderForOnePassage(JitPassageDecoder decoder, AddrCtx seed, int maxOps) {+ this.decoder = decoder;+ this.seed = seed;+ this.maxOps = maxOps;+ JitConfiguration config = decoder.thread.getMachine().getConfiguration();+ this.maxInstrs = config.maxPassageInstructions();+ this.maxStrides = config.maxPassageStrides();+ EntryPcodeOp entryOp = new EntryPcodeOp(seed);+ externalBranches.put(entryOp, new ExtBranch(entryOp, seed));+ }++ /**+ * Implements the actual decode loop+ */+ void decodePassage() {+ while (opCount < maxOps && instructionCount < maxInstrs &&+ strides.size() < maxStrides) {+ Entry<PcodeOp, ExtBranch> nextEnt = externalBranches.pollFirstEntry();+ if (nextEnt == null) {+ break;+ }+ ExtBranch next = nextEnt.getValue();+ AddrCtx start = next.to();++ if (decoder.thread.hasEntry(start)) {+ otherBranches.put(next.from(), next);+ }+ else {+ decodeStride(start);+ PcodeOp to = Objects.requireNonNull(firstOps.get(start));+ internalBranches.put(next.from(), new IntBranch(next.from(), to, false));+ }+ }+ }++ /**+ * Record that a direct branch was encountered.+ *+ * <p>+ * If we've already decoded the target, we create an {@link IntBranch} record, and we're done.+ * Otherwise, we queue up an {@link ExtBranch} record. If multiple direct branches target the+ * same address, we still create separate entries. First, we note their {@link Branch#from()+ * from} fields will be different. Also, we ensure once we've terminated (probably because of a+ * quota), we must examine records still in the queue, but whose targets may have since been+ * decoded, and convert them to {@link IntBranch} records.+ *+ * @param from the op representing or causing the control flow+ * @param to the target of the branch+ */+ void flowTo(ExtBranch eb) {+ if (firstOps.containsKey(eb.to())) {+ IntBranch ib = new IntBranch(eb.from(), firstOps.get(eb.to()), false);+ internalBranches.put(ib.from(), ib);+ return;+ }+ externalBranches.put(eb.from(), eb);+ }++ /**+ * Decode a stride starting at the given address.+ *+ * @param start the starting address and context+ */+ private void decodeStride(AddrCtx start) {+ DecodedStride stride = new DecoderForOneStride(decoder, this, start).decode();+ opCount += stride.ops().size();+ instructionCount += stride.instructions().size();+ strides.add(stride);+ }++ /**+ * Sort out the result and create the decoded passage+ *+ * <p>+ * The strides are sorted by their seeds (contextreg value then address), and their code+ * concatenated together. The various types of branches are also all combined. (They can still+ * be distinguished by type.) {@link ExtBranch} records are converted to {@link IntBranch}+ * records where possible.+ *+ * @return the passage+ */+ JitPassage finish() {+ strides.sort(Comparator.comparing(DecodedStride::start));+ List<PcodeOp> code = strides.stream().flatMap(b -> b.ops().stream()).toList();+ List<Instruction> instructions =+ strides.stream().flatMap(b -> b.instructions().stream()).toList();+ Map<PcodeOp, Branch> branches = otherBranches;+ branches.putAll(internalBranches);+ for (ExtBranch eb : externalBranches.values()) {+ if (firstOps.containsKey(eb.to())) {+ branches.put(eb.from(), new IntBranch(eb.from(), firstOps.get(eb.to()), false));+ }+ else {+ branches.put(eb.from(), eb);+ }+ }+ return new JitPassage(decoder.thread.getLanguage(), seed, code, decoder.library,+ instructions, branches, MapUtils.invertMap(firstOps));+ }++ /**+ * Get the decoder-wrapped userop library+ *+ * @return the library+ */+ PcodeUseropLibrary<Object> library() {+ return decoder.library;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderForOneStride.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderForOneStride.javanew file mode 100644index 0000000000..4ef0dd049b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderForOneStride.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.pcode.emu.jit.decode;++import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.PseudoInstruction;+import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.exec.PcodeProgram;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The decoder for a single stride.+ *+ * <p>+ * This starts at a given seed and proceeds linearly until it hits an instruction without fall+ * through. It may also stop if it encounters an existing entry point or an erroneous user inject.+ *+ * @see JitPassageDecoder+ */+public class DecoderForOneStride {++ /**+ * The result of decoding an instruction+ *+ * <p>+ * This may also represent an error encountered while trying to decode an instruction.+ *+ * @param executor the p-code interpreter, which retains some state+ * @param program the resulting p-code+ */+ record StepResult(DecoderExecutor executor, PcodeProgram program) {++ /**+ * Check whether the result falls through, accumulate its instructions and ops, and apply+ * any control-flow effects.+ *+ * @return true if the result falls through.+ * @see DecoderExecutor#checkFallthroughAndAccumulate(PcodeProgram)+ */+ boolean checkFallthroughAndAccumulate() {+ return executor.checkFallthroughAndAccumulate(program);+ }++ /**+ * Compute the fall-through target+ *+ * <p>+ * <b>NOTE</b>: This should only be called after checking if the result actually has fall+ * through; otherwise, this will blindly compute the address and context immediately after+ * the instruction.+ *+ * @return the next address to decode+ */+ AddrCtx next() {+ return executor.takeTargetContext(executor.getAdvancedAddress());+ }+ }++ final JitPassageDecoder decoder;+ final DecoderForOnePassage passage;+ private final AddrCtx start;++ final List<Instruction> instructions = new ArrayList<>();+ final List<PcodeOp> opsForStride = new ArrayList<>();;++ /**+ * Construct a stride decoder+ *+ * @param decoder the thread's passage decoder+ * @param passage the decoder for this specific passage+ * @param start the seed to start this stride+ */+ public DecoderForOneStride(JitPassageDecoder decoder, DecoderForOnePassage passage,+ AddrCtx start) {+ this.decoder = decoder;+ this.passage = passage;+ this.start = start;+ }++ /**+ * Finish decoding and create the stride+ *+ * @return the stride+ */+ DecodedStride toStride() {+ return new DecodedStride(start, instructions, opsForStride);+ }++ /**+ * "Step" the decoder an instruction+ *+ * <p>+ * This will attempt to decode the instruction at the given address (and contextreg value). If+ * the given address is already a known entry point (for the entire emulator), then this returns+ * {@code null} and the stride should be terminated. Otherwise, this checks for a user inject or+ * then decodes an instruction. The resulting p-code (which may represent a decode error) is+ * interpreted, and the first op is saved, in case it is targeted by a direct branch. As a+ * special case, if the inject and/or instruction emits no p-code, we synthesize a+ * {@link NopPcodeOp nop}, so that we can enter something into our books.+ *+ * @param at the address of the instruction to decode+ * @return the result+ */+ private StepResult stepAddrCtx(AddrCtx at) {+ /**+ * Avoid duplicate translation when we encounter an existing entry point. Just encode an+ * exit branch.+ */+ if (decoder.thread.hasEntry(at)) {+ ExitPcodeOp exitOp = new ExitPcodeOp(at);+ opsForStride.add(exitOp);+ passage.otherBranches.put(exitOp, new ExtBranch(exitOp, at));+ return null;+ }++ DecoderExecutor executor = new DecoderExecutor(this, at);+ PcodeProgram program = decoder.thread.getInject(at.address);+ if (program == null) {+ PseudoInstruction instruction = executor.decodeInstruction();+ instructions.add(instruction);+ program = PcodeProgram.fromInstruction(instruction, false);+ }++ executor.execute(program);+ if (executor.opsForThisStep.isEmpty()) {+ NopPcodeOp nop = new NopPcodeOp(at, 0);+ passage.firstOps.put(at, nop);+ opsForStride.add(nop);+ }+ else {+ passage.firstOps.put(at, executor.opsForThisStep.getFirst());+ }+ return new StepResult(executor, program);+ }++ /**+ * Decode the stride.+ *+ * @return the decoded stride+ */+ public DecodedStride decode() {+ AddrCtx at = start;+ while (true) {+ if (passage.firstOps.containsKey(at)) {+ return toStride();+ }++ StepResult result = stepAddrCtx(at);++ if (result == null || !result.checkFallthroughAndAccumulate()) {+ return toStride();+ }++ AddrCtx next = result.next();+ if (at.equals(next)) {+ // Would happen because of inject without control flow+ ExitPcodeOp exitOp = new ExitPcodeOp(at);+ opsForStride.add(exitOp);+ passage.otherBranches.put(exitOp, new ExtBranch(exitOp, at));+ return toStride();+ }+ at = next;+ }++ /**+ * NOTE: If we impose a max instruction count within the stride, be sure to add the+ * "external branch" that falls-through to the next instruction outside the passage.+ */+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderUseropLibrary.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderUseropLibrary.javanew file mode 100644index 0000000000..a66ed0e4fe--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/DecoderUseropLibrary.java@@ -0,0 +1,202 @@+/* ###+ * 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.pcode.emu.jit.decode;++import java.lang.reflect.Method;+import java.util.List;++import ghidra.app.util.PseudoInstruction;+import ghidra.pcode.emu.DefaultPcodeThread.PcodeEmulationLibrary;+import ghidra.pcode.emu.jit.op.JitNopOp;+import ghidra.pcode.exec.*;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++/**+ * The decoder's wrapper around the emulator's userop library+ *+ * <p>+ * This library serves two purposes: 1) to override {@link PcodeEmulationLibrary#emu_exec_decoded()}+ * and {@link PcodeEmulationLibrary#emu_skip_decoded()}, and 2) to check and inline p-code userops+ * that {@link ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition#canInlinePcode() allow}+ * it.+ *+ * <p>+ * We accomplish the first purpose simply by adding the two userops using the usual annotations. The+ * two built-in userops regarding the decoded instruction are easily inlinable, so we will mark them+ * as such. Note, however, that they are separate from the wrappers we mention for the second+ * purpose (inlining), and so we must implement that inlining in the actual userop. We still mark+ * them for informational purposes and because the translator needs to know.+ *+ * <p>+ * We accomplish the second purpose of inlining by accepting the emulator's userop library and+ * individually wrapping each of its userops, excluding the two we override. We allow each userop's+ * attributes to pass through, but when executed, we check if the userop allows inlining. If so,+ * then we feed the userop's p-code into the decoder's interpreter. This effectively inlines the op,+ * control flow ops and all, into the passage. Note we do not actually replace the+ * {@link PcodeOp#CALLOTHER callother} op, for bookkeeping purposes. Instead we will map it to a+ * {@link JitNopOp nop} during translation.+ */+public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<Object> {++ /**+ * The wrapper around one of the emulator's userops+ */+ protected class WrappedUseropDefinition implements PcodeUseropDefinition<Object> {+ private final PcodeUseropDefinition<byte[]> rtOp;++ /**+ * Wrap the given userop+ *+ * @param rtOp the actual userop, as defined by the user or emulator+ */+ public WrappedUseropDefinition(PcodeUseropDefinition<byte[]> rtOp) {+ this.rtOp = rtOp;+ }++ @Override+ public String getName() {+ return rtOp.getName();+ }++ @Override+ public int getInputCount() {+ return rtOp.getInputCount();+ }++ @Override+ public void execute(PcodeExecutor<Object> executor, PcodeUseropLibrary<Object> library,+ Varnode outVar, List<Varnode> inVars) {+ throw new AssertionError();+ }++ /**+ * {@inheritDoc}+ *+ * @implNote If the userop can be inlined, we assume the delegate's {@code execute} method+ * simply produces p-code and feeds it to the executor. If that is true, then the+ * target type {@code <T>} does not matter, so we cast everything to raw types.+ * Thus, the user is responsible to apply the {@link #canInlinePcode()} attribute+ * correctly.+ */+ @Override+ @SuppressWarnings("unchecked")+ public void execute(PcodeExecutor<Object> executor, PcodeUseropLibrary<Object> library,+ PcodeOp op) {+ if (rtOp.canInlinePcode()) {+ @SuppressWarnings("rawtypes")+ PcodeExecutor rawExec = executor;+ @SuppressWarnings("rawtypes")+ PcodeUseropLibrary rawLib = library;+ rtOp.execute(rawExec, rawLib, op);+ }+ else {+ // Nothing to do. CALLOTHER is logged and will be compiled later.+ }+ }++ @Override+ public boolean isFunctional() {+ return rtOp.isFunctional();+ }++ @Override+ public boolean hasSideEffects() {+ return rtOp.hasSideEffects();+ }++ @Override+ public boolean canInlinePcode() {+ return rtOp.canInlinePcode();+ }++ @Override+ public Method getJavaMethod() {+ return rtOp.getJavaMethod();+ }++ @Override+ public PcodeUseropLibrary<?> getDefiningLibrary() {+ return rtOp.getDefiningLibrary();+ }+ }++ /**+ * Wrap the given userop library+ *+ * @param rtLib the actual library provided by the user or emulator+ */+ public DecoderUseropLibrary(PcodeUseropLibrary<byte[]> rtLib) {+ for (PcodeUseropDefinition<byte[]> opDef : rtLib.getUserops().values()) {+ if (ops.containsKey(opDef.getName())) {+ // Allow our annotations to override stuff in rtLib+ continue;+ }+ ops.put(opDef.getName(), new WrappedUseropDefinition(opDef));+ }+ }++ /**+ * The replacement for {@link PcodeEmulationLibrary#emu_exec_decoded()}.+ *+ * <p>+ * The one built into the emulator would have the thread interpret the decoded instruction+ * directly. While this might "work," it totally missed the purpose of JIT translation. We+ * instead inline the userop's p-code into the rest of the passage. We accomplish this by having+ * the decoder interpret the p-code instead. We also need to ensure the decoded instruction is+ * added into the passage.+ *+ * <p>+ * Note that the {@link PcodeOp#CALLOTHER callother} op will be mapped to a {@link JitNopOp nop}+ * during translation because we have set {@code canInline}.+ *+ * @param executor the decoder's executor+ */+ @PcodeUserop(canInline = true)+ public void emu_exec_decoded(@OpExecutor PcodeExecutor<Object> executor) {+ DecoderExecutor de = (DecoderExecutor) executor;+ PseudoInstruction instruction = de.decodeInstruction();+ de.addInstruction(instruction);+ PcodeProgram program = PcodeProgram.fromInstruction(instruction, false);+ de.execute(program);+ }++ /**+ * The replacement for {@link PcodeEmulationLibrary#emu_skip_decoded()}.+ *+ * <p>+ * The one built into the emulator would have the thread drop and skip the decoded instruction+ * directly. This would not have the intended effect, because the decoder is the thing that+ * needs to skip and advance to the next address. We instead "inline" nothing, but we must still+ * decode the instruction. Because the executor provides the decode routine, it can internally+ * work out fall through. We will <em>not</em> add the instruction to the passage, though,+ * because we will not have the executor interpret any of the instructon's p-code. As for fall+ * through, the {@link DecoderExecutor#checkFallthroughAndAccumulate(PcodeProgram)} routine just+ * does its usual. If the inject falls through, {@link DecoderExecutor#getAdvancedAddress()}+ * considers the decoded instruction, even though it was never interpreted.+ *+ * <p>+ * Note that the {@link PcodeOp#CALLOTHER callother} op will still be mapped to a+ * {@link JitNopOp nop} during translation because we have set {@code canInline}.+ *+ * @param executor the decoder's executor+ */+ @PcodeUserop(canInline = true)+ public void emu_skip_decoded(@OpExecutor PcodeExecutor<Object> executor) {+ DecoderExecutor de = (DecoderExecutor) executor;+ de.decodeInstruction();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/JitPassageDecoder.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/JitPassageDecoder.javanew file mode 100644index 0000000000..5ea92286bf--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/JitPassageDecoder.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.pcode.emu.jit.decode;++import ghidra.app.util.PseudoInstruction;+import ghidra.pcode.emu.InstructionDecoder;+import ghidra.pcode.emu.jit.*;+import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockSplitter;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.exec.DecodePcodeExecutionException;+import ghidra.program.model.address.Address;+import ghidra.program.model.lang.Register;+import ghidra.program.model.lang.RegisterValue;+import ghidra.program.model.listing.ProgramContext;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The decoder of a {@link JitPassage} to support JIT-accelerated p-code emulation.+ *+ * <p>+ * When the emulator encounters an address (and contextreg value) that it has not previously+ * translated, it must decode a passage seeded at that required entry point. It must then translate+ * the passage and collects all the resulting entry points, and finally invoke the passage's+ * {@link JitCompiledPassage#run(int) run} method for the required entry point.+ *+ * <h2>Decoding a Passage</h2>+ * <p>+ * Decode starts with a single seed, which is the entry point required by the emulator. As such,+ * that seed <em>must</em> be among the entry points exported by the translator. Decode occurs one+ * stride at a time. Starting with the seed, we decode a stride by disassembling linearly until: 1)+ * We encounter an instruction without fall through, 2) there's already an entry point to a+ * translated passage at an encountered address, or 3) a user injection fails to specify control+ * flow. Case 1 is the normal expected case. For example, when the decoder encounters an+ * unconditional branch, the stride is terminated. Case 2 is meant to reduce duplicative+ * translations, but it does come at some cost during decode time. Suppose execution branches into+ * the middle of a previously translated basic block. (Note that basic blocks are only broken apart+ * using branches <em>in the same passage</em>, so it is possible some branch encountered later+ * would jump into another passage's basic block.) That previously translated passage will not have+ * exposed an entry point at that branch target, so the emulator will begin decoding using the+ * branch target as the seed. Ideally, the resulting passage will consist of a single stride that+ * terminates at an existing entry point. The emulator will translate and execute the passage, which+ * should exit at that entry point, where the emulator can then continue execution. Case 3 is just+ * to ensure execution does not get caught in a translated infinite loop. There will still be an+ * infinite loop, but it can be interrupted while execution is in the emulator's logic rather than+ * the translated logic.+ *+ * <p>+ * As the stride decoder processes each instruction, it interprets its p-code, along with any+ * generated by user injects, to collect branch targets. For direct branches ({@link PcodeOp#BRANCH+ * branch}, {@link PcodeOp#CBRANCH cbranch}, and {@link PcodeOp#CALL call}), the target address (and+ * appropriate contextreg value) is added to the queue of seeds, unless that target is already+ * decoded in this passage. A bit of control flow analysis is required to determine whether each+ * instruction (with user injects) has fall through. We borrow the {@link BlockSplitter} from the+ * {@link JitControlFlowModel} to accomplish this. We append a "probe" p-code op at the very end,+ * and then once we have the (miniature) control flow graph, we check if there's a path from+ * instruction start to the probe op. If there is, then we can fall through, so decode proceeds to+ * the next instruction. If not, the stride is terminated, so the decoder starts a new stride at the+ * next seed, unless we've met the p-code op, instruction, or stride {@link JitConfiguration quota}.+ *+ * <p>+ * The seed queue is a list of {@link ExtBranch} records. Each stride is decoded by removing a seed+ * from that queue, decoding instructions, emitting ops, and then creating an {@link IntBranch}+ * record targeting the first op of the newly-decoded instruction. The {@link Branch#from() from}+ * field is taken from the seed {@link ExtBranch} record. Decode will likely terminate before this+ * queue is emptied, in which case, those remaining external branches will become part of the+ * passage's {@link JitPassage#getBranches() branches}. Direct branches to instructions already+ * included in the passage, p-code relative branches, and queued external branches to instructions+ * which have since been decoded all become {@link IntBranch} records, too. For indirect branches+ * ({@link PcodeOp#BRANCHIND branchind}, {@link PcodeOp#CALLIND callind}, and {@link PcodeOp#RETURN+ * return}), we create {@link IndBranch} records. For error cases (e.g.,+ * {@link PcodeOp#UNIMPLEMENTED unimplemented}), we create {@link ErrBranch} records.+ *+ * @implNote The process described above is actually implemented in {@link DecoderForOnePassage}.+ * This class just keeps the configuration and some other trappings, and instantiates an+ * actual decoder upon requesting a seed.+ */+public class JitPassageDecoder {+ final JitPcodeThread thread;++ final InstructionDecoder decoder;+ final ProgramContext defaultContext;+ final Register contextreg;+ final DecoderUseropLibrary library;++ /**+ * Construct a passage decoder+ *+ * @param thread the thread whose instruction decoder, context, and userop library to use.+ */+ public JitPassageDecoder(JitPcodeThread thread) {+ this.thread = thread;++ this.decoder = thread.getDecoder();+ this.defaultContext = thread.getDefaultContext();+ this.contextreg =+ defaultContext == null ? Register.NO_CONTEXT : defaultContext.getBaseContextRegister();+ this.library = new DecoderUseropLibrary(thread.getUseropLibrary());+ }++ /**+ * Decode a passage starting at the given seed+ *+ * @param seed the seed address+ * @param ctxIn the seed contextreg value+ * @param maxOps the maximum-ish number of p-code ops to emit+ * @see #decodePassage(AddrCtx, int)+ * @return the decoded passage+ */+ public JitPassage decodePassage(Address seed, RegisterValue ctxIn, int maxOps) {+ return decodePassage(new AddrCtx(ctxIn, seed), maxOps);+ }++ /**+ * Decode a passage starting at the given seed+ *+ * <p>+ * We provide a {@code maxOps} parameter so that the configured+ * {@link JitConfiguration#maxPassageOps() option} can be overridden. In particular, the+ * bytecode emitter may exceed the maximum size of a Java method, in which case we must abort,+ * re-decode with fewer ops, and retry. Whether this back off should persist in the+ * configuration is yet to be determined. Output size can vary wildly depending on the number of+ * basic blocks, scope transitions, nature of the ops, etc. We ought to be able to provide a+ * reasonable default value that mostly avoids retries, because each retry essentially wastes an+ * entire JIT translation. On the other hand, if we choose too small a value, we lose some of+ * the benefits of translating the control flow and keeping variables in JVM locals.+ *+ * @param seed the required entry point, where decode will start+ * @param maxOps the maximum-ish number of p-codes to emit+ * @return the decoded passage+ */+ public JitPassage decodePassage(AddrCtx seed, int maxOps) {+ DecoderForOnePassage forOne = new DecoderForOnePassage(this, seed, maxOps);+ forOne.decodePassage();+ return forOne.finish();+ }++ /**+ * Decode a single instruction+ *+ * @param address the address of the instruction+ * @param ctx the input decode context+ * @return the decoded instruction, or a {@link DecodeErrorInstruction}.+ */+ PseudoInstruction decodeInstruction(Address address, RegisterValue ctx) {+ try {+ return decoder.decodeInstruction(address, ctx);+ }+ catch (DecodePcodeExecutionException e) {+ return JitPassage.decodeError(decoder.getLanguage(), address, ctx, e.getMessage());+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/ExceptionHandler.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/ExceptionHandler.javanew file mode 100644index 0000000000..a46fcf0d44--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/ExceptionHandler.java@@ -0,0 +1,74 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.pcode.emu.jit.gen;++import static org.objectweb.asm.Opcodes.ATHROW;++import org.objectweb.asm.Label;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitPassage.DecodedPcodeOp;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.program.model.pcode.PcodeOp;++/**+ * A requested exception handler+ *+ * <p>+ * When an exception occurs, we must retire all of the variables before we pop the+ * {@link JitCompiledPassage#run(int) run} method's frame. We also write out the program counter and+ * disassembly context so that the emulator can resume appropriately. After that, we re-throw the+ * exception.+ *+ * <p>+ * When the code generator knows the code it's emitting can cause a user exception, e.g., the Direct+ * invocation of a userop, and there are live variables in scope, then it should request a handler+ * (via {@link JitCodeGenerator#requestExceptionHandler(DecodedPcodeOp, JitBlock)}) and surround the+ * code in a {@code try-catch} on {@link Throwable} directing it to this handler.+ *+ * @param op the op which may cause an exception+ * @param block the block containing the op+ * @param label the label at the start of the handler+ */+public record ExceptionHandler(PcodeOp op, JitBlock block, Label label) {+ /**+ * Construct a handler, generating a new label+ *+ * @param op the op which may cause an exception+ * @param block the block containing the op+ */+ public ExceptionHandler(PcodeOp op, JitBlock block) {+ this(op, block, new Label());+ }++ /**+ * Emit the handler's code into the {@link JitCompiledPassage#run(int) run} method.+ *+ * @param gen the code generator+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generateRunCode(JitCodeGenerator gen, MethodVisitor rv) {+ rv.visitLabel(label);+ // [exc]+ gen.generatePassageExit(block, () -> {+ rv.visitLdcInsn(gen.getAddressForOp(op).getOffset());+ }, gen.getExitContext(op), rv);+ // [exc]+ rv.visitInsn(ATHROW);+ // []+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForArrDirect.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForArrDirect.javanew file mode 100644index 0000000000..40a9c12c8f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForArrDirect.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.pcode.emu.jit.gen;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.program.model.address.Address;++/**+ * A field request for a pre-fetched page from the {@link JitBytesPcodeExecutorStateSpace}.+ *+ * <p>+ * The field is used for direct memory accesses. For those, the address space and fixed address is+ * given in the p-code, so we are able to pre-fetch the page and access it directly at run time.+ *+ * @param address the address contained by the page to pre-fetch+ */+public record FieldForArrDirect(Address address) implements InstanceFieldReq {+ @Override+ public String name() {+ return "arrDir_%s_%x".formatted(address.getAddressSpace().getName(),+ address.getOffset());+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Consider the address {@code ram:00600000}. The declaration is equivalent to:+ *+ * <pre>+ * private final byte[] arrDir_ram_600000;+ * </pre>+ *+ * <p>+ * And the initialization is equivalent to:+ *+ * <pre>+ * arrDir_ram_600000 =+ * state.getForSpace(ADDRESS_FACTORY.getAddressSpace(ramId)).getDirect(0x600000);+ * </pre>+ */+ @Override+ public void generateInitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor iv) {+ cv.visitField(ACC_PRIVATE | ACC_FINAL, name(), TDESC_BYTE_ARR, null, null);++ // [...]+ iv.visitVarInsn(ALOAD, 0);+ // [...,this]+ gen.generateLoadJitStateSpace(address.getAddressSpace(), iv);+ // [...,jitspace]+ iv.visitLdcInsn(address.getOffset());+ // [...,arr]+ iv.visitMethodInsn(INVOKEVIRTUAL, NAME_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE,+ "getDirect", MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE__GET_DIRECT, false);+ iv.visitFieldInsn(PUTFIELD, gen.nameThis, name(), TDESC_BYTE_ARR);+ // [...]+ }++ @Override+ public void generateLoadCode(JitCodeGenerator gen, MethodVisitor rv) {+ // [...]+ rv.visitVarInsn(ALOAD, 0);+ // [...,this]+ rv.visitFieldInsn(GETFIELD, gen.nameThis, name(),+ TDESC_BYTE_ARR);+ // [...,arr]+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForContext.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForContext.javanew file mode 100644index 0000000000..a606bfc755--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForContext.java@@ -0,0 +1,77 @@+/* ###+ * 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.pcode.emu.jit.gen;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.program.model.lang.Language;+import ghidra.program.model.lang.RegisterValue;++/**+ * A field request for pre-constructed contextreg value+ */+record FieldForContext(RegisterValue ctx) implements StaticFieldReq {+ @Override+ public String name() {+ return "CTX_%s".formatted(ctx.getUnsignedValue().toString(16));+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Consider the context value 0x80000000. The code is equivalent to:+ *+ * <pre>+ * private static final {@link RegisterValue} CTX_80000000 = {@link JitCompiledPassage#createContext(Language, String) createContext}(LANGUAGE, "80000000");+ * </pre>+ */+ @Override+ public void generateClinitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor sv) {+ if (ctx == null) {+ return;+ }+ cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, name(), TDESC_REGISTER_VALUE, null,+ null);++ // []+ sv.visitFieldInsn(GETSTATIC, gen.nameThis, "LANGUAGE", TDESC_LANGUAGE);+ // [language]+ sv.visitLdcInsn(ctx.getUnsignedValue().toString(16));+ // [language,ctx:STR]+ sv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "createContext",+ MDESC_JIT_COMPILED_PASSAGE__CREATE_CONTEXT, true);+ // [ctx:RV]+ sv.visitFieldInsn(PUTSTATIC, gen.nameThis, name(), TDESC_REGISTER_VALUE);+ }++ @Override+ public void generateLoadCode(JitCodeGenerator gen, MethodVisitor rv) {+ // [...]+ if (ctx == null) {+ rv.visitInsn(ACONST_NULL);+ }+ else {+ rv.visitFieldInsn(GETSTATIC, gen.nameThis, name(), TDESC_REGISTER_VALUE);+ }+ // [...,ctx]+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForExitSlot.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForExitSlot.javanew file mode 100644index 0000000000..20136db252--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForExitSlot.java@@ -0,0 +1,101 @@+/* ###+ * 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.pcode.emu.jit.gen;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.JitPassage.ExtBranch;+import ghidra.pcode.emu.jit.JitPcodeThread;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.ExitSlot;+import ghidra.program.model.lang.RegisterValue;++/**+ * A field request for an {@link ExitSlot}.+ *+ * <p>+ * One of these is allocated per {@link ExtBranch#to()}. At run time, the first time a branch is+ * encountered from this passage to the given target, the slot calls+ * {@link JitPcodeThread#getEntry(AddrCtx) getEntry}{@code (target)} and keeps the reference. Each+ * subsequent encounter uses the kept reference. This reference is what gets returned by+ * {@link JitCompiledPassage#run(int)}, so now the thread already has in hand the next+ * {@link EntryPoint} to execute.+ *+ * @param target the target address-contextreg pair of the branch exiting via this slot+ */+public record FieldForExitSlot(AddrCtx target) implements InstanceFieldReq {+ @Override+ public String name() {+ return "exit_%x_%s".formatted(target.address.getOffset(), target.biCtx.toString(16));+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Consider the target {@code (ram:00401234,ctx=80000000)}. The declaration is equivalent to:+ *+ * <pre>+ * private final {@link ExitSlot} exit_401234_80000000;+ * </pre>+ *+ * <p>+ * And the initialization is equivalent to:+ *+ * <pre>+ * exit_401234_80000000 = {@link JitCompiledPassage#createExitSlot(long, RegisterValue) createExitSlot}(0x401234, CTX_80000000);+ * </pre>+ *+ * <p>+ * Note that this method will ensure the {@code CTX_...} field is allocated and loads its value+ * as needed.+ */+ @Override+ public void generateInitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor iv) {+ FieldForContext ctxField = gen.requestStaticFieldForContext(target.rvCtx);+ cv.visitField(ACC_PRIVATE | ACC_FINAL, name(), TDESC_EXIT_SLOT, null, null);++ // []+ iv.visitVarInsn(ALOAD, 0);+ // [this]+ iv.visitInsn(DUP);+ // [this,this]+ iv.visitLdcInsn(target.address.getOffset());+ // [this,this,target:LONG]+ ctxField.generateLoadCode(gen, iv);+ // [this,this,target:LONG,ctx:RV]+ iv.visitMethodInsn(INVOKEINTERFACE, NAME_JIT_COMPILED_PASSAGE, "createExitSlot",+ MDESC_JIT_COMPILED_PASSAGE__CREATE_EXIT_SLOT, true);+ // [this,slot]+ iv.visitFieldInsn(PUTFIELD, gen.nameThis, name(), TDESC_EXIT_SLOT);+ // []+ }++ @Override+ public void generateLoadCode(JitCodeGenerator gen, MethodVisitor rv) {+ // []+ rv.visitVarInsn(ALOAD, 0);+ // [this]+ rv.visitFieldInsn(GETFIELD, gen.nameThis, name(), TDESC_EXIT_SLOT);+ // [slot]+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForSpaceIndirect.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForSpaceIndirect.javanew file mode 100644index 0000000000..d9067d46be--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForSpaceIndirect.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.pcode.emu.jit.gen;++import static ghidra.pcode.emu.jit.gen.GenConsts.TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.program.model.address.AddressSpace;++/**+ * A field request for a pre-fetched {@link JitBytesPcodeExecutorStateSpace}+ *+ * <p>+ * The field is used for indirect memory accesses. For those, the address space is given in the+ * p-code, but the offset must be computed at run time. Thus, we can pre-fetch the state space, but+ * not any particular page.+ *+ * @param space the address space of the state space to pre-fetch+ */+public record FieldForSpaceIndirect(AddressSpace space) implements InstanceFieldReq {+ @Override+ public String name() {+ return "spaceInd_" + space.getName();+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Consider the "ram" space. The declaration is equivalent to:+ *+ * <pre>+ * private final {@link JitBytesPcodeExecutorStateSpace} spaceInd_ram;+ * </pre>+ *+ * <p>+ * And the initialization is equivalent to:+ *+ * <pre>+ * spaceInd_ram = state.getForSpace(ADDRESS_FACTORY.getAddressSpace(ramId));+ * </pre>+ */+ @Override+ public void generateInitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor iv) {+ cv.visitField(ACC_PRIVATE | ACC_FINAL, name(),+ TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE, null, null);++ // [...]+ iv.visitVarInsn(ALOAD, 0);+ // [...,this]+ gen.generateLoadJitStateSpace(space, iv);+ // [...,this,jitspace]+ iv.visitFieldInsn(PUTFIELD, gen.nameThis, name(),+ TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE);+ // [...]+ }++ @Override+ public void generateLoadCode(JitCodeGenerator gen, MethodVisitor rv) {+ // [...]+ rv.visitVarInsn(ALOAD, 0);+ // [...,this]+ rv.visitFieldInsn(GETFIELD, gen.nameThis, name(),+ TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE);+ // [...,jitspace]+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForUserop.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForUserop.javanew file mode 100644index 0000000000..be4e34ac1b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForUserop.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.pcode.emu.jit.gen;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitDataFlowUseropLibrary;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;++/**+ * A field request for a pre-fetched userop definition+ *+ * <p>+ * These are used to invoke userops using the Standard or Direct strategies.+ *+ * @param userop the definition to pre-fetch+ * @see JitDataFlowUseropLibrary+ */+public record FieldForUserop(PcodeUseropDefinition<?> userop) implements InstanceFieldReq {+ @Override+ public String name() {+ return "userop_" + userop.getName();+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Consider the userop {@code syscall()}. The declaration is equivalent to:+ *+ * <pre>+ * private final {@link PcodeUseropDefinition} userop_syscall;+ * </pre>+ *+ * <p>+ * And the initialization is equivalent to:+ *+ * <pre>+ * userop_syscall = {@link JitCompiledPassage#getUseropDefinition(String) getUseropdDefinition}("syscall");+ * </pre>+ */+ @Override+ public void generateInitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor iv) {+ cv.visitField(ACC_PRIVATE | ACC_FINAL, name(), TDESC_PCODE_USEROP_DEFINITION, null,+ null);++ // []+ iv.visitVarInsn(ALOAD, 0);+ // [this]+ iv.visitInsn(DUP);+ // [this,this]+ iv.visitLdcInsn(userop.getName());+ // [this,this,name]+ iv.visitMethodInsn(INVOKEINTERFACE, NAME_JIT_COMPILED_PASSAGE, "getUseropDefinition",+ MDESC_JIT_COMPILED_PASSAGE__GET_USEROP_DEFINITION, true);+ // [this,userop]+ iv.visitFieldInsn(PUTFIELD, gen.nameThis, name(), TDESC_PCODE_USEROP_DEFINITION);+ // []+ }++ @Override+ public void generateLoadCode(JitCodeGenerator gen, MethodVisitor rv) {+ // []+ rv.visitVarInsn(ALOAD, 0);+ // [this]+ rv.visitFieldInsn(GETFIELD, gen.nameThis, name(), TDESC_PCODE_USEROP_DEFINITION);+ // [userop]+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForVarnode.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForVarnode.javanew file mode 100644index 0000000000..c8795beed4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldForVarnode.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.pcode.emu.jit.gen;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitDataFlowUseropLibrary;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.var.VarGen;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressFactory;+import ghidra.program.model.pcode.Varnode;++/**+ * A field request for a pre-constructed varnode+ *+ * <p>+ * These are used to invoke userops using the Standard strategy.+ *+ * @param vn the varnode to pre-construct+ * @see JitDataFlowUseropLibrary+ */+public record FieldForVarnode(Varnode vn) implements StaticFieldReq {+ @Override+ public String name() {+ Address addr = vn.getAddress();+ return "VARNODE_%s_%s_%s".formatted(addr.getAddressSpace().getName().toUpperCase(),+ Long.toUnsignedString(addr.getOffset(), 16), vn.getSize());+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * Consider the varnode (ram:00400000,4). The code is equivalent to:+ *+ * <pre>+ * private static final {@link Varnode} VARNODE_ram_400000_4 = {@link JitCompiledPassage#createVarnode(AddressFactory, String, long, int) createVarnode}(ADDRESS_FACTORY, "ram", 0x400000, 4);+ * </pre>+ */+ @Override+ public void generateClinitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor sv) {+ cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, name(), TDESC_VARNODE, null, null);++ sv.visitFieldInsn(GETSTATIC, gen.nameThis, "ADDRESS_FACTORY", TDESC_ADDRESS_FACTORY);+ sv.visitLdcInsn(vn.getAddress().getAddressSpace().getName());+ sv.visitLdcInsn(vn.getAddress().getOffset());+ sv.visitLdcInsn(vn.getSize());+ sv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "createVarnode",+ MDESC_JIT_COMPILED_PASSAGE__CREATE_VARNODE, true);+ sv.visitFieldInsn(PUTSTATIC, gen.nameThis, name(), TDESC_VARNODE);+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * To clarify, this <em>does not</em> load a varnode's current value onto the JVM stack. That is+ * done by {@link VarGen}. This loads a ref to the {@link Varnode} instance. Also, it's not+ * precisely the same instance as given, but a re-construction of it as a plain {@link Varnode},+ * i.e., just the (space,offset,size) triple.+ *+ */+ @Override+ public void generateLoadCode(JitCodeGenerator gen, MethodVisitor rv) {+ rv.visitFieldInsn(GETSTATIC, gen.nameThis, name(), TDESC_VARNODE);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldReq.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldReq.javanew file mode 100644index 0000000000..8cfb65b978--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/FieldReq.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.pcode.emu.jit.gen;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;++/**+ * A field request for a pre-fetched or pre-constructed element+ */+interface FieldReq {+ /**+ * Derive a suitable name for the field+ *+ * @return the name+ */+ String name();++ /**+ * Emit code to load the field onto the JVM stack+ *+ * @param gen the code generator+ * @param rv the visitor often for the {@link JitCompiledPassage#run(int) run} method, but could+ * be the static initializer or constructor+ */+ void generateLoadCode(JitCodeGenerator gen, MethodVisitor rv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/GenConsts.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/GenConsts.javanew file mode 100644index 0000000000..4c722a138c--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/GenConsts.java@@ -0,0 +1,223 @@+/* ###+ * 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.pcode.emu.jit.gen;++import java.util.ArrayList;+import java.util.List;++import org.apache.commons.lang3.reflect.TypeLiteral;+import org.objectweb.asm.Type;++import ghidra.generic.util.datastruct.SemisparseByteArray;+import ghidra.pcode.emu.jit.*;+import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.ExitSlot;+import ghidra.pcode.error.LowlevelError;+import ghidra.pcode.exec.*;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.program.model.address.*;+import ghidra.program.model.lang.Language;+import ghidra.program.model.lang.RegisterValue;+import ghidra.program.model.pcode.Varnode;++/**+ * Various constants (namely class names, type descriptions, method descriptions, etc. used during+ * bytecode generation.+ */+@SuppressWarnings("javadoc")+public interface GenConsts {+ public static final int BLOCK_SIZE = SemisparseByteArray.BLOCK_SIZE;++ public static final String TDESC_ADDRESS = Type.getDescriptor(Address.class);+ public static final String TDESC_ADDRESS_FACTORY = Type.getDescriptor(AddressFactory.class);+ public static final String TDESC_ADDRESS_SPACE = Type.getDescriptor(AddressSpace.class);+ public static final String TDESC_BYTE_ARR = Type.getDescriptor(byte[].class);+ public static final String TDESC_EXIT_SLOT = Type.getDescriptor(ExitSlot.class);+ public static final String TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE =+ Type.getDescriptor(JitBytesPcodeExecutorState.class);+ public static final String TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE =+ Type.getDescriptor(JitBytesPcodeExecutorStateSpace.class);+ public static final String TDESC_JIT_PCODE_THREAD = Type.getDescriptor(JitPcodeThread.class);+ public static final String TDESC_LANGUAGE = Type.getDescriptor(Language.class);+ public static final String TDESC_LIST = Type.getDescriptor(List.class);+ public static final String TDESC_PCODE_USEROP_DEFINITION =+ Type.getDescriptor(PcodeUseropDefinition.class);+ public static final String TDESC_REGISTER_VALUE = Type.getDescriptor(RegisterValue.class);+ public static final String TDESC_STRING = Type.getDescriptor(String.class);+ public static final String TDESC_VARNODE = Type.getDescriptor(Varnode.class);++ public static final String TSIG_LIST_ADDRCTX =+ JitJvmTypeUtils.typeToSignature(new TypeLiteral<List<AddrCtx>>() {}.value);++ public static final String MDESC_ADDR_CTX__$INIT = Type.getMethodDescriptor(Type.VOID_TYPE,+ Type.getType(RegisterValue.class), Type.getType(Address.class));+ public static final String MDESC_ADDRESS_FACTORY__GET_ADDRESS_SPACE =+ Type.getMethodDescriptor(Type.getType(AddressSpace.class), Type.INT_TYPE);+ public static final String MDESC_ADDRESS_SPACE__GET_ADDRESS =+ Type.getMethodDescriptor(Type.getType(Address.class), Type.LONG_TYPE);+ public static final String MDESC_ARRAY_LIST__$INIT = Type.getMethodDescriptor(Type.VOID_TYPE);+ // NOTE: The void (String) form is private....+ public static final String MDESC_ASSERTION_ERROR__$INIT =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class));+ public static final String MDESC_DOUBLE__DOUBLE_TO_RAW_LONG_BITS =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.DOUBLE_TYPE);+ public static final String MDESC_DOUBLE__IS_NAN =+ Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.DOUBLE_TYPE);+ public static final String MDESC_DOUBLE__LONG_BITS_TO_DOUBLE =+ Type.getMethodDescriptor(Type.DOUBLE_TYPE, Type.LONG_TYPE);+ public static final String MDESC_FLOAT__FLOAT_TO_RAW_INT_BITS =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.FLOAT_TYPE);+ public static final String MDESC_FLOAT__INT_BITS_TO_FLOAT =+ Type.getMethodDescriptor(Type.FLOAT_TYPE, Type.INT_TYPE);+ public static final String MDESC_FLOAT__IS_NAN =+ Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.FLOAT_TYPE);+ public static final String MDESC_ILLEGAL_ARGUMENT_EXCEPTION__$INIT =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class));+ public static final String MDESC_INTEGER__BIT_COUNT =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_INTEGER__COMPARE_UNSIGNED =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_INTEGER__NUMBER_OF_LEADING_ZEROS =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_INTEGER__TO_UNSIGNED_LONG =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.INT_TYPE);+ public static final String MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE__GET_LANGUAGE =+ Type.getMethodDescriptor(Type.getType(Language.class));+ public static final String MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE__GET_SPACE_FOR =+ Type.getMethodDescriptor(Type.getType(JitBytesPcodeExecutorStateSpace.class),+ Type.getType(AddressSpace.class));+ public static final String MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE__GET_DIRECT =+ Type.getMethodDescriptor(Type.getType(byte[].class), Type.LONG_TYPE);+ public static final String MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE__READ =+ Type.getMethodDescriptor(Type.getType(byte[].class), Type.LONG_TYPE, Type.INT_TYPE);+ public static final String MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE__WRITE =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.LONG_TYPE, Type.getType(byte[].class),+ Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__CONV_OFFSET2_TO_LONG =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__COUNT =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__CREATE_CONTEXT =+ Type.getMethodDescriptor(Type.getType(RegisterValue.class), Type.getType(Language.class),+ Type.getType(String.class));+ public static final String MDESC_JIT_COMPILED_PASSAGE__CREATE_DECODE_ERROR =+ Type.getMethodDescriptor(Type.getType(DecodePcodeExecutionException.class),+ Type.getType(String.class), Type.LONG_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__CREATE_EXIT_SLOT =+ Type.getMethodDescriptor(Type.getType(ExitSlot.class), Type.LONG_TYPE,+ Type.getType(RegisterValue.class));+ public static final String MDESC_JIT_COMPILED_PASSAGE__CREATE_VARNODE =+ Type.getMethodDescriptor(Type.getType(Varnode.class), Type.getType(AddressFactory.class),+ Type.getType(String.class), Type.LONG_TYPE, Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__GET_CHAINED =+ Type.getMethodDescriptor(Type.getType(EntryPoint.class), Type.getType(ExitSlot.class));+ public static final String MDESC_JIT_COMPILED_PASSAGE__GET_LANGUAGE =+ Type.getMethodDescriptor(Type.getType(Language.class), Type.getType(String.class));+ public static final String MDESC_JIT_COMPILED_PASSAGE__GET_USEROP_DEFINITION =+ Type.getMethodDescriptor(Type.getType(PcodeUseropDefinition.class),+ Type.getType(String.class));+ public static final String MDESC_JIT_COMPILED_PASSAGE__INVOKE_USEROP =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PcodeUseropDefinition.class),+ Type.getType(Varnode.class), Type.getType(Varnode[].class));+ public static final String MDESC_JIT_COMPILED_PASSAGE__READ_INTX =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.getType(byte[].class), Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__READ_LONGX =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.getType(byte[].class), Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__RETIRE_COUNTER_AND_CONTEXT =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.LONG_TYPE, Type.getType(RegisterValue.class));+ public static final String MDESC_JIT_COMPILED_PASSAGE__S_CARRY_INT_RAW =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__S_CARRY_LONG_RAW =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.LONG_TYPE, Type.LONG_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.getType(byte[].class),+ Type.INT_TYPE);+ public static final String MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.LONG_TYPE, Type.getType(byte[].class),+ Type.INT_TYPE);+ public static final String MDESC_JIT_PCODE_THREAD__GET_STATE =+ Type.getMethodDescriptor(Type.getType(JitThreadBytesPcodeExecutorState.class));+ public static final String MDESC_LANGUAGE__GET_ADDRESS_FACTORY =+ Type.getMethodDescriptor(Type.getType(AddressFactory.class));+ public static final String MDESC_LANGUAGE__GET_DEFAULT_SPACE =+ Type.getMethodDescriptor(Type.getType(AddressSpace.class));+ public static final String MDESC_LIST__ADD =+ Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class));+ public static final String MDESC_LONG__BIT_COUNT =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.LONG_TYPE);+ public static final String MDESC_LONG__COMPARE_UNSIGNED =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.LONG_TYPE, Type.LONG_TYPE);+ public static final String MDESC_LONG__NUMBER_OF_LEADING_ZEROS =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.LONG_TYPE);+ public static final String MDESC_LOW_LEVEL_ERROR__$INIT =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class));+ public static final String MDESC_PCODE_USEROP_DEFINITION__GET_DEFINING_LIBRARY =+ Type.getMethodDescriptor(Type.getType(PcodeUseropLibrary.class));+ public static final String MDESC_SLEIGH_LINK_EXCEPTION__$INIT =+ Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class));++ public static final String MDESC_$DOUBLE_UNOP =+ Type.getMethodDescriptor(Type.DOUBLE_TYPE, Type.DOUBLE_TYPE);+ public static final String MDESC_$FLOAT_UNOP =+ Type.getMethodDescriptor(Type.FLOAT_TYPE, Type.FLOAT_TYPE);+ public static final String MDESC_$INT_BINOP =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.INT_TYPE, Type.INT_TYPE);+ public static final String MDESC_$LONG_BINOP =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.LONG_TYPE, Type.LONG_TYPE);+ public static final String MDESC_$SHIFT_JJ =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.LONG_TYPE, Type.LONG_TYPE);+ public static final String MDESC_$SHIFT_JI =+ Type.getMethodDescriptor(Type.LONG_TYPE, Type.LONG_TYPE, Type.INT_TYPE);+ public static final String MDESC_$SHIFT_IJ =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.INT_TYPE, Type.LONG_TYPE);+ public static final String MDESC_$SHIFT_II =+ Type.getMethodDescriptor(Type.INT_TYPE, Type.INT_TYPE, Type.INT_TYPE);++ public static final String NAME_ADDR_CTX = Type.getInternalName(AddrCtx.class);+ public static final String NAME_ADDRESS = Type.getInternalName(Address.class);+ public static final String NAME_ADDRESS_FACTORY = Type.getInternalName(AddressFactory.class);+ public static final String NAME_ADDRESS_SPACE = Type.getInternalName(AddressSpace.class);+ public static final String NAME_ARRAY_LIST = Type.getInternalName(ArrayList.class);+ public static final String NAME_ASSERTION_ERROR = Type.getInternalName(AssertionError.class);+ public static final String NAME_DOUBLE = Type.getInternalName(Double.class);+ public static final String NAME_EXIT_SLOT = Type.getInternalName(ExitSlot.class);+ public static final String NAME_FLOAT = Type.getInternalName(Float.class);+ public static final String NAME_ILLEGAL_ARGUMENT_EXCEPTION =+ Type.getInternalName(IllegalArgumentException.class);+ public static final String NAME_INTEGER = Type.getInternalName(Integer.class);+ public static final String NAME_JIT_BYTES_PCODE_EXECUTOR_STATE =+ Type.getInternalName(JitBytesPcodeExecutorState.class);+ public static final String NAME_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE =+ Type.getInternalName(JitBytesPcodeExecutorStateSpace.class);+ public static final String NAME_JIT_COMPILED_PASSAGE =+ Type.getInternalName(JitCompiledPassage.class);+ public static final String NAME_JIT_PCODE_THREAD = Type.getInternalName(JitPcodeThread.class);+ public static final String NAME_LANGUAGE = Type.getInternalName(Language.class);+ public static final String NAME_LIST = Type.getInternalName(List.class);+ public static final String NAME_LONG = Type.getInternalName(Long.class);+ public static final String NAME_LOW_LEVEL_ERROR = Type.getInternalName(LowlevelError.class);+ public static final String NAME_MATH = Type.getInternalName(Math.class);+ public static final String NAME_OBJECT = Type.getInternalName(Object.class);+ public static final String NAME_PCODE_USEROP_DEFINITION =+ Type.getInternalName(PcodeUseropDefinition.class);+ public static final String NAME_SLEIGH_LINK_EXCEPTION =+ Type.getInternalName(SleighLinkException.class);+ public static final String NAME_THROWABLE = Type.getInternalName(Throwable.class);+ public static final String NAME_VARNODE = Type.getInternalName(Varnode.class);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/InstanceFieldReq.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/InstanceFieldReq.javanew file mode 100644index 0000000000..ce8a01649f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/InstanceFieldReq.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.pcode.emu.jit.gen;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++/**+ * An instance field request initialized in the class constructor+ */+interface InstanceFieldReq extends FieldReq {+ /**+ * Emit the field declaration and its initialization bytecode+ *+ * <p>+ * The declaration is emitted into the class definition, and the initialization code is emitted+ * into the class constructor.+ *+ * @param gen the code generator+ * @param cv the visitor for the class definition+ * @param iv the visitor for the class constructor+ */+ void generateInitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor iv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/JitCodeGenerator.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/JitCodeGenerator.javanew file mode 100644index 0000000000..7fee8c10af--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/JitCodeGenerator.java@@ -0,0 +1,1156 @@+/* ###+ * 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.pcode.emu.jit.gen;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import java.io.*;+import java.lang.invoke.MethodHandles.Lookup;+import java.util.*;++import org.objectweb.asm.*;+import org.objectweb.asm.util.TraceClassVisitor;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.pcode.emu.jit.*;+import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.pcode.emu.jit.JitCompiler.Diag;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.JitPassage.DecodedPcodeOp;+import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.analysis.JitAllocationModel.JvmLocal;+import ghidra.pcode.emu.jit.analysis.JitAllocationModel.VarHandler;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.op.OpGen;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.ExitSlot;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassageClass;+import ghidra.pcode.emu.jit.gen.var.ValGen;+import ghidra.pcode.emu.jit.gen.var.VarGen;+import ghidra.pcode.emu.jit.gen.var.VarGen.BlockTransition;+import ghidra.pcode.emu.jit.op.JitOp;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.emu.jit.var.JitVar;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.pcode.exec.SleighPcodeUseropDefinition;+import ghidra.program.model.address.*;+import ghidra.program.model.lang.*;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;+import ghidra.util.Msg;++/**+ * The bytecode generator for JIT-accelerated emulation.+ *+ * <p>+ * This implements the Code Generation phase of the {@link JitCompiler}. With all the prior+ * analysis, code generation is just a careful process of visiting all of the ops, variables, and+ * analytic results to ensure everything is incorporated and accounted for.+ *+ * <h2>The Target Classfile</h2>+ * <p>+ * The target is a classfile that implements {@link JitCompiledPassage}. As such, it must implement+ * all of the specified methods in that interface as well as a constructor having a specific+ * {@link JitCompiledPassageClass#CONSTRUCTOR_TYPE signature}. That signature takes a+ * {@link JitPcodeThread} and, being a constructor, returns {@code void}. We will also need to+ * generate a static initializer to populate some metadata and pre-fetch any static things, e.g.,+ * the {@link SleighLanguage} for the emulation target. The fields are:+ *+ * <ul>+ * <li><b>{@code static }{@link String}{@code LANGUAGE_ID}</b> - The language ID (as in+ * {@link LanguageID} of the emulation target</li>+ * <li><b>{@code static }{@link Language}{@code LANGUAGE}</b> - The language (ISA) of the emulation+ * target</li>+ * <li><b>{@code static }{@link AddressFactory}{@code ADDRESS_FACTORY}</b> - The address factory of+ * the language</li>+ * <li><b>{@code static }{@link List}{@code <}{@link AddrCtx}{@code > ENTRIES}</b> - The lsit of+ * entry points</li>+ * <li><b>{@link JitPcodeThread}{@code thread}</b> - The bound thread for this instance of the+ * compiled passage</li>+ * <li><b>{@link JitBytesPcodeExecutorState}{@code state}</b> - The run-time machine state for this+ * thread of emulation</li>+ * </ul>+ *+ * <h3>Static Initializer</h3>+ * <p>+ * In the Java language, statements in a class's {@code static} block, as well as the initial values+ * of static fields are implemented by the classfile's {@code <clinit>} method. We use it to+ * pre-construct {@code contextreg} values and {@link Varnode varnode} refs for use in birthing and+ * retirement. They are kept in static fields. We also initialize the static {@code ENTRIES} field,+ * which is public (via reflection) and describes each entry point generated. It has the type+ * {@code List<}{@link AddrCtx}{@code >}. A call to {@link JitCompiledPassage#run(int)} should pass+ * in the position of the desired entry point in the {@code ENTRIES} list.+ *+ * <h3>Constructor</h3>+ * <p>+ * In the Java language, statements in a class's constructor, as well as the initial values of+ * instance fields are implemented by the classfile's {@code <init>} methods. We provide a single+ * constructor that accepts a {@link JitPcodeThread}. Upon construction, the generated+ * {@link JitCompiledPassage} is "bound" to the given thread. The constructor pre-fetches parts of+ * the thread's {@link JitBytesPcodeExecutorState state} and {@link SleighPcodeUseropDefinition+ * userop definitions}, and it allocates {@link ExitSlot}s. Each of these are kept in instance+ * fields.+ *+ * <h3>{@code thread()} Method</h3>+ * <p>+ * This method implements {@link JitCompiledPassage#thread()}, a simple getter for the+ * {@code thread} field.+ *+ * <h3>{@code run()} Method</h3>+ * <p>+ * This method implements {@link JitCompiledPassage#run(int)}, the actual semantics of the+ * translated machine instructions selected for the passage. It accepts a single parameter, which is+ * the position in the {@code ENTRIES} list of the desired entry point {@code blockId}. The+ * structure is as follows:+ *+ * <ol>+ * <li>Parameter declarations - {@code this} and {@code blockId}</li>+ * <li>Allocated local declarations - declares all locals allocated by+ * {@link JitAllocationModel}</li>+ * <li>Entry point dispatch - a large {@code switch} statement on the entry {@code blockId}</li>+ * <li>P-code translation - the block-by-block op-by-op translation of the p-code to bytecode</li>+ * <li>Exception handlers - exception handlers as requested by various elements of the p-code+ * translation</li>+ * </ol>+ *+ * <h4>Entry Point Dispatch</h4>+ * <p>+ * This part of the run method dispatches execution to the correct entry point within the translated+ * passage. It consists of these sub-parts:+ *+ * <ol>+ * <li>Switch table - a {@link Opcodes#TABLESWITCH tableswitch} to jump to the code for the scope+ * transition into the entry block given by {@code blockId}</li>+ * <li>Scope transitions - for each block, birth its live varnodes then jump to the block's+ * translation</li>+ * <li>Default case - throws an {@link IllegalArgumentException} for an invalid {@code blockId}</li>+ * </ol>+ *+ * <p>+ * This first ensure that a valid entry point was given in {@code blockId}. If not, we jump to the+ * default case which throws an exception. Otherwise, we jump to the appropriate entry transition.+ * Every block flow edge is subject to a scope transition wherein varnodes that leave scope must be+ * retired and varnodes that enter scope must be birthed. We generate an entry transition for each+ * possible entry block. That transition births all the varnodes that are in scope for that entry+ * block then jumps to the entry block's p-code translation.+ *+ * <h4>P-code Translation</h4>+ * <p>+ * Here, most of the generation is performed via delegation to an object model, based on the use-def+ * graph. We first iterate over the blocks, in the same order as they appear in the decoded passage.+ * This will ensure that fall-through control transitions in the p-code map to fall-through+ * transitions in the emitted bytecode. If the block is the target of a bytecode jump, i.e., it's an+ * entry block or the target of a p-code branch, then we emit a label at the start of the block. We+ * then iterate over each p-code op in the block delegating each to the appropriate generator. We+ * emit "line number" information for each op to help debug crashes. A generator may register an+ * exception handler to be emitted later in the "exception handlers" part of the {@code run} method.+ * If the block has fall through, we emit the appropriate scope transition before proceeding to the+ * next block. Note that scope transitions for branch ops are emitted by the generators for those+ * ops.+ *+ * <p>+ * For details about individual p-code op translations, see {@link OpGen}. For details about+ * individual SSA value (constant and variable) translations, see {@link VarGen}. For details about+ * emitting scope transitions, see {@link BlockTransition}.+ *+ * @implNote Throughout most of the code that emits bytecode, there are (human-generated) comments+ * to track the contents of the JVM stack. Items pushed onto the stack appear at the+ * right. If type is important, then those are denoted using :TYPE after the relevant+ * variable. TODO: It'd be nice to have a bytecode API that enforces stack structure using+ * the compiler (somehow), but that's probably overkill. Also, I have yet to see what the+ * official classfile API will bring.+ */+public class JitCodeGenerator {+ /**+ * The key for a varnode, to ensure we control the definition of {@link Object#equals(Object)+ * equality}.+ */+ record VarnodeKey(int space, long offset, int size) {+ /**+ * Extract/construct the key for a given varnode+ *+ * @param vn the varnode+ */+ public VarnodeKey(Varnode vn) {+ this(vn.getSpace(), vn.getOffset(), vn.getSize());+ }+ }++ private final Lookup lookup;+ final JitAnalysisContext context;+ final JitControlFlowModel cfm;+ final JitDataFlowModel dfm;+ final JitVarScopeModel vsm;+ final JitTypeModel tm;+ final JitAllocationModel am;+ final JitOpUseModel oum;++ private final Map<JitBlock, Label> blockLabels = new HashMap<>();+ private final Map<PcodeOp, ExceptionHandler> excHandlers = new LinkedHashMap<>();+ private final Map<AddressSpace, FieldForSpaceIndirect> fieldsForSpaceIndirect = new HashMap<>();+ private final Map<Address, FieldForArrDirect> fieldsForArrDirect = new HashMap<>();+ private final Map<RegisterValue, FieldForContext> fieldsForContext = new HashMap<>();+ private final Map<VarnodeKey, FieldForVarnode> fieldsForVarnode = new HashMap<>();+ private final Map<String, FieldForUserop> fieldsForUserop = new HashMap<>();+ private final Map<AddrCtx, FieldForExitSlot> fieldsForExitSlot = new HashMap<>();++ final String nameThis;++ private final ClassWriter cw;+ private final ClassVisitor cv;+ private final MethodVisitor clinitMv;+ private final MethodVisitor initMv;+ private final MethodVisitor runMv;++ private final Label startLocals = new Label();+ private final Label endLocals = new Label();++ /**+ * Construct a code generator for the given passage's target classfile+ *+ * <p>+ * This constructor chooses the name for the target classfile based on the passage's entry seed.+ * It has the form: <code> Passage$at_<em>address</em>_<em>context</em></code>. The address is+ * as rendered by {@link Address#toString()} but with characters replaced to make it a valid JVM+ * classfile name. The decode context is rendered in hexadecimal. This constructor also declares+ * the fields and methods, and emits the definition for {@link JitCompiledPassage#thread()}.+ *+ * @param lookup a means of accessing user-defined components, namely userops+ * @param context the analysis context for the passage+ * @param cfm the control flow model+ * @param dfm the data flow model+ * @param vsm the variable scope model+ * @param tm the type model+ * @param am the allocation model+ * @param oum the op use model+ */+ public JitCodeGenerator(Lookup lookup, JitAnalysisContext context, JitControlFlowModel cfm,+ JitDataFlowModel dfm, JitVarScopeModel vsm, JitTypeModel tm, JitAllocationModel am,+ JitOpUseModel oum) {+ this.lookup = lookup;+ this.context = context;+ this.cfm = cfm;+ this.dfm = dfm;+ this.vsm = vsm;+ this.tm = tm;+ this.am = am;+ this.oum = oum;++ // TODO: Should I incorporate more of the address set into the name?+ AddrCtx entry = context.getPassage().getEntry();+ String pkgThis = lookup.lookupClass().getPackageName().replace(".", "/");+ if (!pkgThis.isEmpty()) {+ // Scripts are in the default package :/+ pkgThis = pkgThis + "/";+ }+ this.nameThis = (pkgThis + "Passage$at_" + entry.address + "_" + entry.biCtx.toString(16))+ .replace(":", "_")+ .replace(" ", "_");++ int flags = entry.address.getOffset() == JitCompiler.EXCLUDE_MAXS ? 0+ : ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;+ cw = new ClassWriter(flags);+ if (JitCompiler.ENABLE_DIAGNOSTICS.contains(Diag.TRACE_CLASS)) {+ cv = new TraceClassVisitor(cw, new PrintWriter(System.err));+ }+ else {+ this.cv = cw;+ }++ cv.visit(V17, ACC_PUBLIC, nameThis, null, Type.getInternalName(Object.class), new String[] {+ Type.getInternalName(JitCompiledPassage.class),+ });++ cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "LANGUAGE_ID", TDESC_STRING, null,+ context.getLanguage().getLanguageID().toString());+ cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "LANGUAGE", TDESC_LANGUAGE, null, null);+ cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "ADDRESS_FACTORY",+ TDESC_ADDRESS_FACTORY, null, null);+ cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "ENTRIES", TDESC_LIST,+ TSIG_LIST_ADDRCTX, null);++ cv.visitField(ACC_PRIVATE | ACC_FINAL, "thread", TDESC_JIT_PCODE_THREAD, null, null);+ cv.visitField(ACC_PRIVATE | ACC_FINAL, "state", TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE, null,+ null);++ clinitMv = cv.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>",+ Type.getMethodDescriptor(Type.VOID_TYPE), null, null);++ initMv = cv.visitMethod(ACC_PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE,+ Type.getType(JitPcodeThread.class)), null, null);+ runMv = cv.visitMethod(ACC_PUBLIC, "run",+ Type.getMethodDescriptor(Type.getType(EntryPoint.class), Type.INT_TYPE), null, null);++ startStaticInitializer();+ startConstructor();++ MethodVisitor gtMv = cw.visitMethod(ACC_PUBLIC, "thread",+ Type.getMethodDescriptor(Type.getType(JitPcodeThread.class)), null, null);+ gtMv.visitCode();+ // []+ gtMv.visitVarInsn(ALOAD, 0);+ // [this]+ gtMv.visitFieldInsn(GETFIELD, nameThis, "thread", TDESC_JIT_PCODE_THREAD);+ // [thread]+ gtMv.visitInsn(ARETURN);+ // []+ gtMv.visitMaxs(20, 20);+ gtMv.visitEnd();+ }++ /**+ * Get the analysis context+ *+ * @return the context+ */+ public JitAnalysisContext getAnalysisContext() {+ return context;+ }++ /**+ * Get the variable scope model+ *+ * @return the model+ */+ public JitVarScopeModel getVariableScopeModel() {+ return vsm;+ }++ /**+ * Get the type model+ *+ * @return the model+ */+ public JitTypeModel getTypeModel() {+ return tm;+ }++ /**+ * Get the allocation model+ *+ * @return the model+ */+ public JitAllocationModel getAllocationModel() {+ return am;+ }++ /**+ * Emit the first bytecodes for the static initializer+ *+ * <p>+ * This generates code equivalent to:+ *+ * <pre>+ * static {+ * LANGUAGE = {@link JitCompiledPassage#getLanguage(String) getLanguage}(LANGUAGE_ID);+ * ADDRESS_FACTORY = LANGUAGE.getAddressFactory();+ * }+ * </pre>+ *+ * <p>+ * Note that {@code LANGUAGE_ID} is initialized to a constant {@link String} in its declaration.+ * Additional {@link StaticFieldReq static fields} may be requested as the p-code translation is+ * emitted.+ */+ protected void startStaticInitializer() {+ clinitMv.visitCode();++ // []+ clinitMv.visitFieldInsn(GETSTATIC, nameThis, "LANGUAGE_ID", TDESC_STRING);+ // [langID:STR]+ clinitMv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "getLanguage",+ MDESC_JIT_COMPILED_PASSAGE__GET_LANGUAGE, true);+ // [language]+ clinitMv.visitInsn(DUP);+ // [language,language]+ clinitMv.visitFieldInsn(PUTSTATIC, nameThis, "LANGUAGE", TDESC_LANGUAGE);+ // [language]+ clinitMv.visitMethodInsn(INVOKEINTERFACE, NAME_LANGUAGE, "getAddressFactory",+ MDESC_LANGUAGE__GET_ADDRESS_FACTORY, true);+ clinitMv.visitFieldInsn(PUTSTATIC, nameThis, "ADDRESS_FACTORY", TDESC_ADDRESS_FACTORY);+ // []+ }++ /**+ * Emit the first bytecodes for the class constructor+ *+ * <p>+ * This generates code equivalent to:+ *+ * <pre>+ * public Passage$at_00400000_0(JitPcodeThread thread) {+ * super(); // Implicit in Java, but we must emit i+ * this.thread = thread;+ * this.state = thread.GetState();+ * }+ * </pre>+ *+ * <p>+ * Additional {@link InstanceFieldReq instance fields} may be requested as the p-code+ * translation is emitted.+ */+ protected void startConstructor() {+ initMv.visitCode();+ // Object.super()+ // []+ initMv.visitVarInsn(ALOAD, 0);+ // [this]+ initMv.visitMethodInsn(INVOKESPECIAL, NAME_OBJECT, "<init>",+ Type.getMethodDescriptor(Type.VOID_TYPE), false);+ // []++ // this.thread = thread+ // []+ initMv.visitVarInsn(ALOAD, 0);+ // [this]+ initMv.visitVarInsn(ALOAD, 1);+ // [this,state]+ initMv.visitFieldInsn(PUTFIELD, nameThis, "thread", TDESC_JIT_PCODE_THREAD);+ // []++ // this.state = thread.getState()+ // []+ initMv.visitVarInsn(ALOAD, 0);+ // [this]+ initMv.visitVarInsn(ALOAD, 1);+ // [this,thread]+ initMv.visitMethodInsn(INVOKEVIRTUAL, NAME_JIT_PCODE_THREAD, "getState",+ MDESC_JIT_PCODE_THREAD__GET_STATE, false);+ // [this,state]+ initMv.visitFieldInsn(PUTFIELD, nameThis, "state", TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE);+ // []+ }++ /**+ * Emit bytecode to load the given {@link JitBytesPcodeExecutorStateSpace} onto the JVM stack+ *+ * <p>+ * This is equivalent to the Java expression+ * {@code state.getForSpace(AddressFactory.getAddressSpace(spaceId))}. The id of the given+ * {@code space} is encoded as an immediate or in the constant pool and is represented as+ * {@code spaceId}.+ *+ * @param space the space to load at run time+ * @param iv the visitor for the class constructor+ */+ protected void generateLoadJitStateSpace(AddressSpace space, MethodVisitor iv) {+ /**+ * this.spaceInd_`space` =+ * this.state.getForSpace(ADDRESS_FACTORY.getAddressSpace(`space.getSpaceID()`);+ */++ iv.visitVarInsn(ALOAD, 0);+ // [...,this]+ iv.visitFieldInsn(GETFIELD, nameThis, "state",+ TDESC_JIT_BYTES_PCODE_EXECUTOR_STATE);+ // [...,state]+ iv.visitFieldInsn(GETSTATIC, nameThis, "ADDRESS_FACTORY", TDESC_ADDRESS_FACTORY);+ // [...,state,factory]+ iv.visitLdcInsn(space.getSpaceID());+ // [...,state,factory,spaceid]+ iv.visitMethodInsn(INVOKEINTERFACE, NAME_ADDRESS_FACTORY, "getAddressSpace",+ MDESC_ADDRESS_FACTORY__GET_ADDRESS_SPACE, true);+ // [...,state,space]+ iv.visitMethodInsn(INVOKEINTERFACE, NAME_JIT_BYTES_PCODE_EXECUTOR_STATE, "getForSpace",+ MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE__GET_SPACE_FOR, true);+ // [...,jitspace]+ }++ /**+ * Request a field for a {@link JitBytesPcodeExecutorStateSpace} for the given address space+ *+ * @param space the address space+ * @return the field request+ */+ public FieldForSpaceIndirect requestFieldForSpaceIndirect(AddressSpace space) {+ return fieldsForSpaceIndirect.computeIfAbsent(space, s -> {+ FieldForSpaceIndirect f = new FieldForSpaceIndirect(s);+ f.generateInitCode(this, cv, initMv);+ return f;+ });+ }++ /**+ * Request a field for the bytes backing the page at the given address+ *+ * @param address the address contained by the desired page+ * @return the field request+ */+ public FieldForArrDirect requestFieldForArrDirect(Address address) {+ return fieldsForArrDirect.computeIfAbsent(address, a -> {+ FieldForArrDirect f = new FieldForArrDirect(a);+ f.generateInitCode(this, cv, initMv);+ return f;+ });+ }++ /**+ * Request a field for the given contextreg value+ *+ * @param ctx the contextreg value+ * @return the field request+ */+ protected FieldForContext requestStaticFieldForContext(RegisterValue ctx) {+ return fieldsForContext.computeIfAbsent(ctx, c -> {+ FieldForContext f = new FieldForContext(ctx);+ f.generateClinitCode(this, cv, clinitMv);+ return f;+ });+ }++ /**+ * Request a field for the given varnode+ *+ * @param vn the varnode+ * @return the field request+ */+ public FieldForVarnode requestStaticFieldForVarnode(Varnode vn) {+ return fieldsForVarnode.computeIfAbsent(new VarnodeKey(vn), vk -> {+ FieldForVarnode f = new FieldForVarnode(vn);+ f.generateClinitCode(this, cv, clinitMv);+ return f;+ });+ }++ /**+ * Request a field for the given userop+ *+ * @param userop the userop+ * @return the field request+ */+ public FieldForUserop requestFieldForUserop(PcodeUseropDefinition<?> userop) {+ return fieldsForUserop.computeIfAbsent(userop.getName(), n -> {+ FieldForUserop f = new FieldForUserop(userop);+ f.generateInitCode(this, cv, initMv);+ return f;+ });+ }++ /**+ * Request a field for the {@link ExitSlot} for the given target+ *+ * @param target the target address and decode context+ * @return the field request+ */+ public FieldForExitSlot requestFieldForExitSlot(AddrCtx target) {+ return fieldsForExitSlot.computeIfAbsent(target, t -> {+ FieldForExitSlot f = new FieldForExitSlot(t);+ f.generateInitCode(this, cv, initMv);+ return f;+ });+ }++ /**+ * Get the label at the start of a block's translation+ *+ * @param block the block+ * @return the label+ */+ public Label labelForBlock(JitBlock block) {+ return blockLabels.computeIfAbsent(block, b -> new Label());+ }++ /**+ * Request an exception handler that can retire state for a given op+ *+ * @param op the op that might throw an exception+ * @param block the block containing the op+ * @return the exception handler request+ */+ public ExceptionHandler requestExceptionHandler(DecodedPcodeOp op, JitBlock block) {+ return excHandlers.computeIfAbsent(op, o -> new ExceptionHandler(o, block));+ }++ /**+ * Emit into the constructor any bytecode necessary to support the given value.+ *+ * @param v the value from the use-def graph+ */+ protected void generateValInitCode(JitVal v) {+ ValGen.lookup(v).generateValInitCode(this, v, initMv);+ }++ /**+ * Emit into the {@link JitCompiledPassage#run(int) run} method the bytecode to read the given+ * value onto the JVM stack.+ *+ * <p>+ * Although the value may be assigned a type by the {@link JitTypeModel}, the type needed by a+ * given op might be different. This method accepts the {@link JitTypeBehavior} for the operand+ * and will ensure the value pushed onto the JVM stack is compatible with that type.+ *+ * @param v the value to read+ * @param typeReq the required type of the value+ * @return the actual type of the value on the stack+ */+ public JitType generateValReadCode(JitVal v, JitTypeBehavior typeReq) {+ return ValGen.lookup(v).generateValReadCode(this, v, typeReq, runMv);+ }++ /**+ * Emit into the {@link JitCompiledPassage#run(int) run} method the bytecode to write the value+ * on the JVM stack into the given variable.+ *+ * <p>+ * Although the destination variable may be assigned a type by the {@link JitTypeModel}, the+ * type of the value on the stack may not match. This method needs to know that type so that, if+ * necessary, it can convert it to the appropriate JVM type for local variable that holds it.+ *+ * @param v the variable to write+ * @param type the actual type of the value on the stack+ */+ public void generateVarWriteCode(JitVar v, JitType type) {+ VarGen.lookup(v).generateVarWriteCode(this, v, type, runMv);+ }++ /**+ * Emit all the bytecode for the constructor+ *+ * <p>+ * Note that some elements of the p-code translation may request additional bytecodes to be+ * emitted, even after this method is finished. That code will be emitted at the time requested.+ *+ * <p>+ * To ensure a reasonable order, for debugging's sake, we request fields (and their+ * initializations) for all the variables and values before iterating over the ops. This+ * ensures, e.g., locals are declared in order of address for the varnodes they hold. Similarly,+ * the pre-fetched byte arrays, whether for uniques, registers, or memory are initialized in+ * order of address. Were these requests not made, they'd still get requested by the op+ * generators, but the order would be less helpful.+ */+ protected void generateInitCode() {+ for (JvmLocal local : am.allLocals()) {+ local.generateInitCode(this, initMv);+ }+ for (JitVal v : dfm.allValuesSorted()) {+ generateValInitCode(v);+ }+ for (PcodeOp op : context.getPassage().getCode()) {+ JitOp jitOp = dfm.getJitOp(op);+ if (!oum.isUsed(jitOp)) {+ continue;+ }+ OpGen.lookup(jitOp).generateInitCode(this, jitOp, initMv);+ }+ }++ /**+ * Emit the bytecode translation for a given p-code op+ *+ * <p>+ * This first finds the use-def node for the op and then verifies that it has not been+ * eliminated. If not, then it find the appropriate generator, emits line number information,+ * and then emits the actual translation.+ *+ * <p>+ * Line number information in the JVM is a map of strictly-positive line numbers to bytecode+ * offsets. The ASM library allows this to be populated by placing labels and then emitting a+ * line-number-to-label entry (via {@link MethodVisitor#visitLineNumber(int, Label)}. It seems+ * the JVM presumes the entire class is defined in a single source file, so we are unable to+ * (ab)use a filename field to encode debug information. We can encode the op index into the+ * (integer) line number, although we have to add 1 to make it strictly positive.+ *+ * @param op the op+ * @param block the block containing the op+ * @param opIdx the index of the op within the whole passage+ */+ protected void generateCodeForOp(PcodeOp op, JitBlock block, int opIdx) {+ JitOp jitOp = dfm.getJitOp(op);+ if (!oum.isUsed(jitOp)) {+ return;+ }+ Label lblLine = new Label();+ runMv.visitLabel(lblLine);+ runMv.visitLineNumber(opIdx, lblLine);+ OpGen.lookup(jitOp).generateRunCode(this, jitOp, block, runMv);+ }++ /**+ * Emit the bytecode translation for the ops in the given p-code block+ *+ * <p>+ * This simply invoked {@link #generateCodeForOp(PcodeOp, JitBlock, int)} on each op in the+ * block and counts up the indices. Other per-block instrumentation is not included.+ *+ * @param block the block+ * @param opIdx the index, within the whole passage, of the first op in the block+ * @return the index, within the whole passage, of the op immediately after the block+ * @see #generateCodeForBlock(JitBlock, int)+ */+ protected int generateCodeForBlockOps(JitBlock block, int opIdx) {+ for (PcodeOp op : block.getCode()) {+ generateCodeForOp(op, block, opIdx);+ opIdx++;+ }+ return opIdx;+ }++ /**+ * Emit the bytecode translation for the given p-code block+ *+ * <p>+ * This checks if the block needs a label, i.e., it is an entry or the target of a branch, and+ * then optionally emits an invocation of {@link JitCompiledPassage#count(int, int)}. Finally,+ * it emits the actual ops' translations via {@link #generateCodeForBlockOps(JitBlock, int)}.+ *+ * @param block the block+ * @param opIdx the index, within the whole passage, of the first op in the block+ * @return the index, within the whole passage, of the op immediately after the block+ */+ protected int generateCodeForBlock(JitBlock block, int opIdx) {+ if (block.hasJumpTo() || getOpEntry(block.first()) != null) {+ Label start = labelForBlock(block);+ runMv.visitLabel(start);+ }++ if (block.first() instanceof DecodedPcodeOp first &&+ context.getConfiguration().emitCounters()) {+ final Label tryStart = new Label();+ final Label tryEnd = new Label();+ runMv.visitTryCatchBlock(tryStart, tryEnd,+ requestExceptionHandler(first, block).label(), NAME_THROWABLE);++ runMv.visitLabel(tryStart);+ runMv.visitVarInsn(ALOAD, 0);+ runMv.visitLdcInsn(block.instructionCount());+ runMv.visitLdcInsn(block.trailingOpCount());+ runMv.visitMethodInsn(INVOKEINTERFACE, NAME_JIT_COMPILED_PASSAGE, "count",+ MDESC_JIT_COMPILED_PASSAGE__COUNT, true);+ runMv.visitLabel(tryEnd);+ }++ return generateCodeForBlockOps(block, opIdx);+ }++ /**+ * Emit code to load an {@link Address} onto the JVM stack+ *+ * <p>+ * Note this does not load the identical address, but reconstructs it at run time.+ *+ * @param address the address to load+ * @param mv the visitor for the method being generated+ */+ protected void generateAddress(Address address, MethodVisitor mv) {+ if (address == Address.NO_ADDRESS) {+ mv.visitFieldInsn(GETSTATIC, NAME_ADDRESS, "NO_ADDRESS", TDESC_ADDRESS);+ return;+ }++ // []+ mv.visitFieldInsn(GETSTATIC, nameThis, "ADDRESS_FACTORY", TDESC_ADDRESS_FACTORY);+ // [factory]+ mv.visitLdcInsn(address.getAddressSpace().getSpaceID());+ // [factory,spaceid]+ mv.visitMethodInsn(INVOKEINTERFACE, NAME_ADDRESS_FACTORY, "getAddressSpace",+ MDESC_ADDRESS_FACTORY__GET_ADDRESS_SPACE, true);+ // [space]+ mv.visitLdcInsn(address.getOffset());+ // [space,offset]+ mv.visitMethodInsn(INVOKEINTERFACE, NAME_ADDRESS_SPACE, "getAddress",+ MDESC_ADDRESS_SPACE__GET_ADDRESS, true);+ // [addr]+ }++ /**+ * Emit bytecode into the class initializer that adds the given entry point into+ * {@code ENTRIES}.+ *+ * <p>+ * Consider the entry {@code (ram:00400000,ctx=80000000)}. The code would be equivalent to:+ *+ * <pre>+ * static {+ * ENTRIES.add(new AddrCtx(+ * ADDRESS_FACTORY.getAddressSpace(ramId).getAddress(0x400000), CTX_80000000));+ * }+ * </pre>+ *+ * <p>+ * Note this method will request the appropriate {@code CTX_...} field.+ *+ * @param entry the entry point to add+ */+ protected void generateStaticEntry(AddrCtx entry) {+ FieldForContext ctxField = requestStaticFieldForContext(entry.rvCtx);++ // []+ clinitMv.visitFieldInsn(GETSTATIC, nameThis, "ENTRIES", TDESC_LIST);+ // [entries]+ clinitMv.visitTypeInsn(NEW, NAME_ADDR_CTX);+ // [entries,addrCtx:NEW]+ clinitMv.visitInsn(DUP);+ // [entries,addrCtx:NEW,addrCtx:NEW]+ ctxField.generateLoadCode(this, clinitMv);+ // [entries,addrCtx:NEW,addrCtx:NEW,ctx]+ generateAddress(entry.address, clinitMv);+ // [entries,addrCtx:NEW,addrCtx:NEW,ctx,addr]+ clinitMv.visitMethodInsn(INVOKESPECIAL, NAME_ADDR_CTX, "<init>", MDESC_ADDR_CTX__$INIT,+ false);+ // [entries,addrCtx:NEW]+ clinitMv.visitMethodInsn(INVOKEINTERFACE, NAME_LIST, "add", MDESC_LIST__ADD, true);+ // [result:BOOL]+ clinitMv.visitInsn(POP);+ // []+ }++ /**+ * Emit code into the static initializer to initialize the {@code ENTRIES} field.+ *+ * <p>+ * This first constructs a new {@link ArrayList} and assigns it to the field. Then, for each+ * block representing a possible entry, it adds an element giving the address and contextreg+ * value for the first op of that block.+ */+ protected void generateStaticEntries() {+ // []+ clinitMv.visitTypeInsn(NEW, NAME_ARRAY_LIST);+ // [entries:NEW]+ clinitMv.visitInsn(DUP);+ // [entries:NEW,entries:NEW]+ clinitMv.visitMethodInsn(INVOKESPECIAL, NAME_ARRAY_LIST, "<init>", MDESC_ARRAY_LIST__$INIT,+ false);+ // [entries:NEW]+ clinitMv.visitFieldInsn(PUTSTATIC, nameThis, "ENTRIES", TDESC_LIST);+ // []++ for (JitBlock block : cfm.getBlocks()) {+ AddrCtx entry = getOpEntry(block.first());+ if (entry != null) {+ generateStaticEntry(entry);+ }+ }+ }++ /**+ * Emit all the bytecode for the {@link JitCompiledPassage#run(int) run} method.+ *+ * <p>+ * The structure of this method is described by this class's documentation. It first declares+ * all the locals allocated by the {@link JitAllocationModel}. It then collects the list of+ * entries points and assigns a label to each. These are used when emitting the entry dispatch+ * code. Several of those labels may also be re-used when translating branch ops. We must+ * iterate over the blocks in the same order as {@link #generateStaticEntries()}, so that our+ * indices and its match. Thus, we emit a {@link Opcodes#TABLESWITCH tableswitch} where each+ * value maps to the blocks label identified in the same position of the {@code ENTRIES} field.+ * We also provide a default case that just throws an {@link IllegalArgumentException}. We do+ * not jump directly to the block's translation. Instead we emit a prologue for each block,+ * wherein we birth the variables that block expects to be live, and then jump to the+ * translation. Then, we emit the translation for each block using+ * {@link #generateCodeForBlock(JitBlock, int)}, placing transitions between those connected by+ * fall through using+ * {@link VarGen#computeBlockTransition(JitCodeGenerator, JitBlock, JitBlock)}. Finally, we emit+ * each requested exception handler using+ * {@link ExceptionHandler#generateRunCode(JitCodeGenerator, MethodVisitor)}.+ */+ protected void generateRunCode() {+ runMv.visitCode();+ runMv.visitLabel(startLocals);++ runMv.visitLocalVariable("this", "L" + nameThis + ";", null, startLocals, endLocals, 0);+ runMv.visitLocalVariable("blockId", Type.getDescriptor(int.class), null, startLocals,+ endLocals, 1);++ for (JvmLocal local : am.allLocals()) {+ local.generateDeclCode(this, startLocals, endLocals, runMv);+ }+ // TODO: This for loop doesn't actually do anything....+ for (JitVal v : dfm.allValuesSorted()) {+ VarHandler handler = am.getHandler(v);+ handler.generateDeclCode(this, startLocals, endLocals, runMv);+ }+ /**+ * NB. opIdx starts at 1, because JVM will ignore "Line number 0"+ */+ int opIdx = 1;++ List<Label> entries = new ArrayList<>();+ for (JitBlock block : cfm.getBlocks()) {+ AddrCtx entry = getOpEntry(block.first());+ if (entry != null) {+ Label lblEntry = new Label();+ entries.add(lblEntry);+ }+ }++ // []+ runMv.visitVarInsn(ILOAD, 1);+ // [blockId]+ Label lblBadEntry = new Label();+ runMv.visitTableSwitchInsn(0, entries.size() - 1, lblBadEntry,+ entries.toArray(Label[]::new));+ // []++ Iterator<Label> eit = entries.iterator();+ for (JitBlock block : cfm.getBlocks()) {+ AddrCtx entry = getOpEntry(block.first());+ if (entry != null) {+ Label lblEntry = eit.next();+ runMv.visitLabel(lblEntry);+ VarGen.computeBlockTransition(this, null, block).generate(runMv);+ runMv.visitJumpInsn(GOTO, labelForBlock(block));+ }+ }+ runMv.visitLabel(lblBadEntry);+ // []+ runMv.visitTypeInsn(NEW, NAME_ILLEGAL_ARGUMENT_EXCEPTION);+ // [err:NEW]+ runMv.visitInsn(DUP);+ // [err:NEW,err:NEW]+ runMv.visitLdcInsn("Bad entry blockId");+ // [err:NEW,err:NEW,message]+ runMv.visitMethodInsn(INVOKESPECIAL, NAME_ILLEGAL_ARGUMENT_EXCEPTION, "<init>",+ MDESC_ILLEGAL_ARGUMENT_EXCEPTION__$INIT, false);+ // [err]+ runMv.visitInsn(ATHROW);+ // []++ for (JitBlock block : cfm.getBlocks()) {+ opIdx = generateCodeForBlock(block, opIdx);+ JitBlock fall = block.getFallFrom();+ if (fall != null) {+ VarGen.computeBlockTransition(this, block, fall).generate(runMv);+ }+ }++ for (ExceptionHandler handler : excHandlers.values()) {+ handler.generateRunCode(this, runMv);+ }+ }++ /**+ * Generate the classfile for this passage and load it into this JVM.+ *+ * @return the translation, wrapped in utilities that knows how to process and instantiate it+ */+ public JitCompiledPassageClass load() {+ byte[] bytes = generate();+ return JitCompiledPassageClass.load(lookup, bytes);+ }++ /**+ * For diagnostics: Dump the generated classfile to an actual file on disk+ *+ * @param bytes the classfile bytes+ * @return the same classfile bytes+ * @see Diag#DUMP_CLASS+ */+ protected byte[] dumpBytecode(byte[] bytes) {+ File dest = new File("build/gen/" + nameThis + ".class");+ dest.getParentFile().mkdirs();+ try (OutputStream os = new FileOutputStream(dest)) {+ os.write(bytes);+ }+ catch (IOException e) {+ Msg.warn(this, "Could not dump class file: " + nameThis + " (" + e + ")");+ }+ return bytes;+ }++ /**+ * Generate the classfile and get the raw bytes+ *+ * <p>+ * This emits all the bytecode for all the required methods, static initializer, and+ * constructor. Once complete, this closes out the methods by letting the ASM library compute+ * the JVM stack frames as well as the maximum stack size and local variable count. Finally, it+ * closes out the class a retrieves the resulting bytes.+ *+ * @return the classfile bytes+ * @implNote The frame and maximums computation does not always succeed, and unfortunately, the+ * ASM library is not terribly keen to explain why. If {@link Diag#DUMP_CLASS} is+ * enabled, we will catch whatever hairy exception gets thrown and close out the+ * method anyway. The resulting class will not likely load into any JVM, but at least+ * you might be able to examine it.+ */+ protected byte[] generate() {+ generateStaticEntries();+ generateInitCode();+ generateRunCode();++ clinitMv.visitInsn(RETURN);+ clinitMv.visitMaxs(20, 20);+ clinitMv.visitEnd();++ initMv.visitInsn(RETURN);+ initMv.visitMaxs(20, 20);+ initMv.visitEnd();++ runMv.visitLabel(endLocals);+ try {+ runMv.visitMaxs(20, 20);+ }+ catch (Exception e) {+ if (JitCompiler.ENABLE_DIAGNOSTICS.contains(Diag.DUMP_CLASS)) {+ // At least try to get bytecode out for diagnostics+ runMv.visitEnd();+ cv.visitEnd();+ dumpBytecode(cw.toByteArray());+ }+ throw e;+ }+ runMv.visitEnd();++ cv.visitEnd();+ if (JitCompiler.ENABLE_DIAGNOSTICS.contains(Diag.DUMP_CLASS)) {+ return dumpBytecode(cw.toByteArray());+ }+ return cw.toByteArray();+ }++ /**+ * Check if the given p-code op is the first of an instruction.+ *+ * @param op the op to check+ * @return the address-context pair+ * @see JitPassage#getOpEntry(PcodeOp)+ */+ public AddrCtx getOpEntry(PcodeOp op) {+ return context.getOpEntry(op);+ }++ /**+ * Get the context of the instruction that generated the given p-code op.+ *+ * <p>+ * This is necessary when exiting the passage, whether due to an exception or "normal" exit. The+ * emulator's context must be updated so that it can resume execution appropriately.+ *+ * @param op the p-code op causing the exit+ * @return the contextreg value+ */+ public RegisterValue getExitContext(PcodeOp op) {+ if (op instanceof DecodedPcodeOp dec) {+ return dec.getContext();+ }+ throw new AssertionError("Couldn't figure exit context for " + op);+ }++ /**+ * Emit bytecode to set the emulator's counter and contextreg.+ *+ * <p>+ * Within a translated passage, there's no need to keep constant track of the program counter+ * (nor decode context), since all the decoding has already been done. However, whenever we exit+ * the passage and return control back to the emulator (whether by {@code return} or+ * {@code throw}) we must "retire" the program counter and decode context, as if the emulator+ * had interpreted all the instructions just executed. This ensures that the emulator has the+ * correct seed when seeking its next entry point, which may require decoding a new passage.+ *+ * @param pcGen a means to emit bytecode to load the counter (as a long) onto the JVM stack. For+ * errors, this is the address of the op causing the error. For branches, this is the+ * branch target, which may be loaded from a varnode for an indirect branch.+ * @param ctx the contextreg value. For errors, this is the decode context of the op causing the+ * error. For branches, this is the decode context at the target.+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generateRetirePcCtx(Runnable pcGen, RegisterValue ctx,+ MethodVisitor rv) {+ // []+ rv.visitVarInsn(ALOAD, 0);+ // [this]+ pcGen.run();+ // [this,pc:LONG]+ if (ctx == null) { // TODO: Or if it's same as entry?+ rv.visitInsn(ACONST_NULL);+ }+ else {+ requestStaticFieldForContext(ctx).generateLoadCode(this, rv);+ }+ // [this,pc:LONG,ctx:RV]+ rv.visitMethodInsn(INVOKEINTERFACE, NAME_JIT_COMPILED_PASSAGE, "retireCounterAndContext",+ MDESC_JIT_COMPILED_PASSAGE__RETIRE_COUNTER_AND_CONTEXT, true);+ }++ /**+ * Emit code to exit the passage+ *+ * <p>+ * This retires all the variables of the current block as well as the program counter and decode+ * coontext. It does not generate the actual {@link Opcodes#ARETURN areturn} or+ * {@link Opcodes#ATHROW athrow}, but everything required up to that point.+ *+ * @param block the block containing the op at which we are exiting+ * @param pcGen as in {@link #generateRetirePcCtx(Runnable, RegisterValue, MethodVisitor)}+ * @param ctx as in {@link #generateRetirePcCtx(Runnable, RegisterValue, MethodVisitor)}+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generatePassageExit(JitBlock block, Runnable pcGen, RegisterValue ctx,+ MethodVisitor rv) {+ VarGen.computeBlockTransition(this, block, null).generate(rv);+ generateRetirePcCtx(pcGen, ctx, rv);+ }++ /**+ * Get the error message for a given p-code op.+ *+ * @param op the p-code op generating the error+ * @return the message+ * @see JitPassage#getErrorMessage(PcodeOp)+ */+ public String getErrorMessage(PcodeOp op) {+ return context.getErrorMessage(op);+ }++ /**+ * Get the address that generated the given p-code op.+ *+ * <p>+ * NOTE: The decoder rewrites ops to ensure they have the decode address, even if they were+ * injected or from an inlined userop.+ *+ * @param op the op+ * @return the address, i.e., the program counter at the time the op is executed+ */+ public Address getAddressForOp(PcodeOp op) {+ if (op instanceof DecodedPcodeOp dec) {+ return dec.getCounter();+ }+ return op.getSeqnum().getTarget();+ }++ /**+ * For testing and debugging: A means to inject granular line number information+ *+ * <p>+ * Typically, this is used to assign every bytecode offset (emitted by a certain generator) a+ * line number, so that tools expecting/requiring line numbers will display something useful.+ */+ public static class LineNumberer {+ final MethodVisitor mv;+ int nextLine = 1;++ /**+ * Prepare to number lines on the given method visitor+ *+ * @param mv the method visitor+ */+ public LineNumberer(MethodVisitor mv) {+ this.mv = mv;+ }++ /**+ * Increment the line number and add info on the next bytecode index+ */+ public void nextLine() {+ Label label = new Label();+ mv.visitLabel(label);+ mv.visitLineNumber(nextLine++, label);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/StaticFieldReq.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/StaticFieldReq.javanew file mode 100644index 0000000000..907bb41944--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/StaticFieldReq.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.pcode.emu.jit.gen;++import org.objectweb.asm.ClassVisitor;+import org.objectweb.asm.MethodVisitor;++/**+ * A static field request initialized in the class initializer+ */+interface StaticFieldReq extends FieldReq {+ /**+ * Emit the field declaration and its initialization bytecode+ *+ * <p>+ * The declaration is emitted into the class definition, and the initialization code is+ * emitted into the class initializer.+ *+ * @param gen the code generator+ * @param cv the visitor for the class definition+ * @param sv the visitor for the class (static) initializer+ */+ void generateClinitCode(JitCodeGenerator gen, ClassVisitor cv, MethodVisitor sv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BinOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BinOpGen.javanew file mode 100644index 0000000000..054bcc10ab--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BinOpGen.java@@ -0,0 +1,90 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitBinOp;++/**+ * An extension that provides conveniences and common implementations for binary p-code operators+ *+ * @param <T> the class of p-code op node in the use-def graph+ */+public interface BinOpGen<T extends JitBinOp> extends OpGen<T> {++ /**+ * Emit code between reading the left and right operands+ *+ * <p>+ * This is invoked immediately after emitting code to push the left operand onto the stack,+ * giving the implementation an opportunity to perform any manipulations of that operand+ * necessary to set up the operation, before code to push the right operand is emitted.+ *+ * @param gen the code generator+ * @param op the operator+ * @param lType the actual type of the left operand+ * @param rType the actual type of the right operand+ * @param rv the method visitor+ * @return the new actual type of the left operand+ */+ default JitType afterLeft(JitCodeGenerator gen, T op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return lType;+ }++ /**+ * Emit code for the binary operator+ *+ * <p>+ * At this point both operands are on the stack. After this returns, code to write the result+ * from the stack into the destination operand will be emitted.+ *+ * @param gen the code generator+ * @param op the operator+ * @param block the block containing the operator+ * @param lType the actual type of the left operand+ * @param rType the actual type of the right operand+ * @param rv the method visitor+ * @return the actual type of the result+ */+ JitType generateBinOpRunCode(JitCodeGenerator gen, T op, JitBlock block, JitType lType,+ JitType rType, MethodVisitor rv);++ /**+ * {@inheritDoc}+ *+ * <p>+ * This default implementation emits code to load the left operand, invokes the+ * {@link #afterLeft(JitCodeGenerator, JitBinOp, JitType, JitType, MethodVisitor) after-left}+ * hook point, emits code to load the right operand, invokes+ * {@link #generateBinOpRunCode(JitCodeGenerator, JitBinOp, JitBlock, JitType, JitType, MethodVisitor)+ * generate-binop}, and finally emits code to write the destination operand.+ */+ @Override+ default void generateRunCode(JitCodeGenerator gen, T op, JitBlock block, MethodVisitor rv) {+ JitType lType = gen.generateValReadCode(op.l(), op.lType());+ JitType rType = op.rType().resolve(gen.getTypeModel().typeOf(op.r()));+ lType = afterLeft(gen, op, lType, rType, rv);+ JitType checkRType = gen.generateValReadCode(op.r(), op.rType());+ assert checkRType == rType;+ JitType outType = generateBinOpRunCode(gen, op, block, lType, rType, rv);+ gen.generateVarWriteCode(op.out(), outType);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BitwiseBinOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BitwiseBinOpGen.javanew file mode 100644index 0000000000..7d73f93f55--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BitwiseBinOpGen.java@@ -0,0 +1,125 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.ILOAD;+import static org.objectweb.asm.Opcodes.ISTORE;++import org.objectweb.asm.*;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitBinOp;++/**+ * An extension for bitwise binary operators+ *+ * @param <T> the class of p-code op node in the use-def graph+ */+public interface BitwiseBinOpGen<T extends JitBinOp> extends BinOpGen<T> {++ /**+ * The JVM opcode to implement this operator with int operands on the stack.+ *+ * @return the opcode+ */+ int intOpcode();++ /**+ * The JVM opcode to implement this operator with long operands on the stack.+ *+ * @return the opcode+ */+ int longOpcode();++ /**+ * <b>WIP</b>: The implementation for multi-precision ints.+ *+ * @param gen the code generator+ * @param type the type of each operand, including the reuslt+ * @param mv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ default void generateMpIntBinOp(JitCodeGenerator gen, MpIntJitType type,+ MethodVisitor mv) {+ /**+ * We need temp locals to get things in order. Read in right operand, do the op as we pop+ * each left op. Then push it all back.+ *+ * No masking of the result is required, since both operands should already be masked, and+ * the bitwise op cannot generate bits of more significance.+ */+ // [lleg1,...,llegN,rleg1,rlegN] (N is least-significant leg)+ int legCount = type.legsAlloc();+ int firstIndex = gen.getAllocationModel().nextFreeLocal();+ Label start = new Label();+ Label end = new Label();+ mv.visitLabel(start);+ for (int i = 0; i < legCount; i++) {+ mv.visitLocalVariable("result" + i, Type.getDescriptor(int.class), null, start, end,+ firstIndex + i);+ mv.visitVarInsn(ISTORE, firstIndex + i);+ // NOTE: More significant legs have higher indices (reverse of stack)+ }+ for (int i = 0; i < legCount; i++) {+ // [lleg1,...,llegN:INT]+ mv.visitVarInsn(ILOAD, firstIndex + i);+ // [lleg1,...,llegN:INT,rlegN:INT]+ mv.visitInsn(intOpcode());+ // [lleg1,...,olegN:INT]+ mv.visitVarInsn(ISTORE, firstIndex + i);+ // [lleg1,...]+ }++ // Push it all back, in reverse order+ for (int i = 0; i < legCount; i++) {+ mv.visitVarInsn(ILOAD, firstIndex + legCount - i - 1);+ }+ mv.visitLabel(end);+ }++ @Override+ default JitType afterLeft(JitCodeGenerator gen, T op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformZExt(lType, rType, rv);+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This implementation reduces the need to just the JVM opcode. We simply ensure both operands+ * have the same size and JVM type, select and emit the correct opcode, and return the type of+ * the result.+ */+ @Override+ default JitType generateBinOpRunCode(JitCodeGenerator gen, T op, JitBlock block, JitType lType,+ JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitInsn(intOpcode());+ case LongJitType t -> rv.visitInsn(longOpcode());+ case MpIntJitType t when t.size() == lType.size() -> generateMpIntBinOp(gen, t, rv);+ case MpIntJitType t -> TODO("MpInt of differing sizes");+ default -> throw new AssertionError();+ }+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolAndOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolAndOpGen.javanew file mode 100644index 0000000000..14fb9fed6b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolAndOpGen.java@@ -0,0 +1,44 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IAND;+import static org.objectweb.asm.Opcodes.LAND;++import ghidra.pcode.emu.jit.op.JitBoolAndOp;+import ghidra.pcode.opbehavior.OpBehaviorBoolAnd;++/**+ * The generator for a {@link JitBoolAndOp bool_and}.+ *+ * @implNote It is the responsibility of the slaspec author to ensure boolean values are 0 or 1.+ * This allows us to use bitwise logic instead of having to check for any non-zero value,+ * just like {@link OpBehaviorBoolAnd}. Thus, this is identical to {@link IntAndOpGen}.+ */+public enum BoolAndOpGen implements BitwiseBinOpGen<JitBoolAndOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int intOpcode() {+ return IAND;+ }++ @Override+ public int longOpcode() {+ return LAND;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolNegateOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolNegateOpGen.javanew file mode 100644index 0000000000..60a85a2f7f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolNegateOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IXOR;+import static org.objectweb.asm.Opcodes.LXOR;++import org.objectweb.asm.MethodVisitor;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitBoolNegateOp;+import ghidra.pcode.opbehavior.OpBehaviorBoolNegate;++/**+ * The generator for a {@link JitBoolNegateOp bool_negate}.+ *+ * @implNote It is the responsibility of the slaspec author to ensure boolean values are 0 or 1.+ * This allows us to use bitwise logic instead of having to check for any non-zero value,+ * just like {@link OpBehaviorBoolNegate}.+ */+public enum BoolNegateOpGen implements UnOpGen<JitBoolNegateOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitBoolNegateOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case IntJitType t -> {+ rv.visitLdcInsn(1);+ rv.visitInsn(IXOR);+ }+ case LongJitType t -> {+ rv.visitLdcInsn(1L);+ rv.visitInsn(LXOR);+ }+ case MpIntJitType t -> Unfinished.TODO("MpInt");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolOrOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolOrOpGen.javanew file mode 100644index 0000000000..867fd72948--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolOrOpGen.java@@ -0,0 +1,44 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IOR;+import static org.objectweb.asm.Opcodes.LOR;++import ghidra.pcode.emu.jit.op.JitBoolOrOp;+import ghidra.pcode.opbehavior.OpBehaviorBoolOr;++/**+ * The generator for a {@link JitBoolOrOp bool_or}.+ *+ * @implNote It is the responsibility of the slaspec author to ensure boolean values are 0 or 1.+ * This allows us to use bitwise logic instead of having to check for any non-zero value,+ * just like {@link OpBehaviorBoolOr}. Thus, this is identical to {@link IntOrOpGen}.+ */+public enum BoolOrOpGen implements BitwiseBinOpGen<JitBoolOrOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int intOpcode() {+ return IOR;+ }++ @Override+ public int longOpcode() {+ return LOR;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolXorOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolXorOpGen.javanew file mode 100644index 0000000000..6d9d4867ba--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BoolXorOpGen.java@@ -0,0 +1,44 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IXOR;+import static org.objectweb.asm.Opcodes.LXOR;++import ghidra.pcode.emu.jit.op.JitBoolXorOp;+import ghidra.pcode.opbehavior.OpBehaviorBoolXor;++/**+ * The generator for a {@link JitBoolXorOp bool_xor}.+ *+ * @implNote It is the responsibility of the slaspec author to ensure boolean values are 0 or 1.+ * This allows us to use bitwise logic instead of having to check for any non-zero value,+ * just like {@link OpBehaviorBoolXor}. Thus, this is identical to {@link IntXorOpGen}.+ */+public enum BoolXorOpGen implements BitwiseBinOpGen<JitBoolXorOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int intOpcode() {+ return IXOR;+ }++ @Override+ public int longOpcode() {+ return LXOR;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BranchIndOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BranchIndOpGen.javanew file mode 100644index 0000000000..4119c8b8ed--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BranchIndOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.ACONST_NULL;+import static org.objectweb.asm.Opcodes.ARETURN;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitPcodeThread;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.LongJitType;+import ghidra.pcode.emu.jit.gen.*;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitBranchIndOp;++/**+ * The generator for a {@link JitBranchIndOp branchind}.+ *+ * <p>+ * This emits code to load the target from the operand and then retire it to the program counter,+ * along with the current flow context and live variables. It then emits code to return null so that+ * the {@link JitPcodeThread thread} knows to loop to the <b>Fetch</b> step for the new counter.+ */+public enum BranchIndOpGen implements OpGen<JitBranchIndOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitBranchIndOp op, JitBlock block,+ MethodVisitor rv) {+ gen.generatePassageExit(block, () -> {+ // [...]+ JitType targetType = gen.generateValReadCode(op.target(), op.targetType());+ // [...,target:?]+ TypeConversions.generateToLong(targetType, LongJitType.I8, rv);+ // [...,target:LONG]+ }, op.branch().flowCtx(), rv);++ rv.visitInsn(ACONST_NULL);+ rv.visitInsn(ARETURN);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BranchOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BranchOpGen.javanew file mode 100644index 0000000000..fddd2c7b53--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/BranchOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.MDESC_JIT_COMPILED_PASSAGE__GET_CHAINED;+import static ghidra.pcode.emu.jit.gen.GenConsts.NAME_JIT_COMPILED_PASSAGE;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.Label;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.emu.jit.JitPcodeThread;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.*;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.var.VarGen;+import ghidra.pcode.emu.jit.op.JitBranchOp;++/**+ * The generator for a {@link JitBranchOp branch}.+ *+ * <p>+ * With an {@link IntBranch} record, this simply looks up the label for the target block and emits a+ * block transition followed by a {@link #GOTO goto}.+ *+ * <p>+ * With an {@link ExtBranch} record, this emits code to retire the target to the program counter,+ * along with the target context and live variables. It then emits code to request the chained entry+ * point from the target's exit slot and return it. The {@link JitPcodeThread thread} can then+ * immediately execute the chained passage entry.+ */+public enum BranchOpGen implements OpGen<JitBranchOp> {+ /** The generator singleton */+ GEN;++ /**+ * Emit code that exits via a direct branch+ *+ * <p>+ * This emits the {@link ExtBranch} record case.+ *+ * @param gen the code generator+ * @param exit the target causing us to exit+ * @param block the block containing the op+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ static void generateExtBranchCode(JitCodeGenerator gen, AddrCtx exit, JitBlock block,+ MethodVisitor rv) {+ FieldForExitSlot slotField = gen.requestFieldForExitSlot(exit);++ gen.generatePassageExit(block, () -> {+ // [...]+ rv.visitLdcInsn(exit.address.getOffset());+ // [...,target:LONG]+ }, exit.rvCtx, rv);++ // []+ slotField.generateLoadCode(gen, rv);+ // [slot]+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "getChained",+ MDESC_JIT_COMPILED_PASSAGE__GET_CHAINED, true);+ // [chained:ENTRY]+ rv.visitInsn(ARETURN);+ }++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitBranchOp op, JitBlock block,+ MethodVisitor rv) {++ switch (op.branch()) {+ case IntBranch ib -> {+ JitBlock target = block.getTargetBlock(ib);+ Label label = gen.labelForBlock(target);+ VarGen.computeBlockTransition(gen, block, target).generate(rv);+ rv.visitJumpInsn(GOTO, label);+ }+ case ExtBranch eb -> {+ generateExtBranchCode(gen, eb.to(), block, rv);+ }+ default -> throw new AssertionError("Branch type confusion");+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CBranchOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CBranchOpGen.javanew file mode 100644index 0000000000..7fcb84ad54--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CBranchOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.Label;+import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitPassage.ExtBranch;+import ghidra.pcode.emu.jit.JitPassage.IntBranch;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.gen.*;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.gen.var.VarGen;+import ghidra.pcode.emu.jit.gen.var.VarGen.BlockTransition;+import ghidra.pcode.emu.jit.op.JitCBranchOp;++/**+ * The generator for a {@link JitCBranchOp cbranch}.+ *+ * <p>+ * First, emits code to load the condition onto the JVM stack.+ *+ * <p>+ * With an {@link IntBranch} record, this looks up the label for the target block and checks if a+ * transition is necessary. If one is necessary, it emits an {@link #IFEQ ifeq} with the transition+ * and {@link #GOTO goto} it guards. The {@code ifeq} skips to the fall-through case. If a+ * transition is not necessary, it simply emits an {@link #IFNE ifne} to the target label.+ *+ * <p>+ * With an {@link ExtBranch} record, this does the same as {@link BranchOpGen} but guarded by an+ * {@link #IFEQ ifeq} that skips to the fall-through case.+ */+public enum CBranchOpGen implements OpGen<JitCBranchOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitCBranchOp op, JitBlock block,+ MethodVisitor rv) {++ JitType cType = gen.generateValReadCode(op.cond(), op.condType());+ TypeConversions.generateIntToBool(cType, rv);++ switch (op.branch()) {+ case IntBranch ib -> {+ JitBlock target = block.getTargetBlock(ib);+ Label label = gen.labelForBlock(target);+ BlockTransition transition = VarGen.computeBlockTransition(gen, block, target);+ if (transition.needed()) {+ Label fall = new Label();+ rv.visitJumpInsn(IFEQ, fall);+ transition.generate(rv);+ rv.visitJumpInsn(GOTO, label);+ rv.visitLabel(fall);+ }+ else {+ rv.visitJumpInsn(IFNE, label);+ }+ }+ case ExtBranch eb -> {+ Label fall = new Label();+ rv.visitJumpInsn(IFEQ, fall);+ BranchOpGen.generateExtBranchCode(gen, eb.to(), block, rv);+ rv.visitLabel(fall);+ }+ default -> throw new AssertionError("Branch type confusion");+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CallOtherMissingOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CallOtherMissingOpGen.javanew file mode 100644index 0000000000..ebe1ddcde9--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CallOtherMissingOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.MDESC_SLEIGH_LINK_EXCEPTION__$INIT;+import static ghidra.pcode.emu.jit.gen.GenConsts.NAME_SLEIGH_LINK_EXCEPTION;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitCallOtherMissingOp;+import ghidra.pcode.exec.SleighLinkException;++/**+ * The generator for a {@link JitCallOtherMissingOp callother-missing}.+ *+ * <p>+ * This emits code to retire the program counter, context, and live variables, then throw a+ * {@link SleighLinkException}.+ */+public enum CallOtherMissingOpGen implements OpGen<JitCallOtherMissingOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitCallOtherMissingOp op, JitBlock block,+ MethodVisitor rv) {+ gen.generatePassageExit(block, () -> {+ rv.visitLdcInsn(gen.getAddressForOp(op.op()).getOffset());+ }, gen.getExitContext(op.op()), rv);++ String message = gen.getErrorMessage(op.op());+ // [...]+ rv.visitTypeInsn(NEW, NAME_SLEIGH_LINK_EXCEPTION);+ // [...,error:NEW]+ rv.visitInsn(DUP);+ // [...,error:NEW,error:NEW]+ rv.visitLdcInsn(message);+ // [...,error:NEW,error:NEW,message]+ rv.visitMethodInsn(INVOKESPECIAL, NAME_SLEIGH_LINK_EXCEPTION, "<init>",+ MDESC_SLEIGH_LINK_EXCEPTION__$INIT, false);+ // [...,error]+ rv.visitInsn(ATHROW);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CallOtherOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CallOtherOpGen.javanew file mode 100644index 0000000000..ffaca2c070--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CallOtherOpGen.java@@ -0,0 +1,249 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import java.lang.reflect.Method;+import java.lang.reflect.Parameter;++import org.objectweb.asm.*;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.JitPassage.DecodedPcodeOp;+import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.*;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.gen.var.VarGen;+import ghidra.pcode.emu.jit.gen.var.VarGen.BlockTransition;+import ghidra.pcode.emu.jit.op.JitCallOtherDefOp;+import ghidra.pcode.emu.jit.op.JitCallOtherOpIf;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for a {@link JitCallOtherOpIf callother}.+ *+ * <p>+ * The checks if Direct invocation is possible. If so, it emits code using+ * {@link #generateRunCodeUsingDirectStrategy(JitCodeGenerator, JitCallOtherOpIf, JitBlock, MethodVisitor)}.+ * If not, it emits code using+ * {@link #generateRunCodeUsingRetirementStrategy(JitCodeGenerator, PcodeOp, JitBlock, PcodeUseropDefinition, MethodVisitor)}.+ * Direct invocation is possible when the userop is {@link PcodeUseropDefinition#isFunctional()+ * functional} and all of its parameters and return type have a supported primitive type.+ * ({@code char} is not supported.) Regarding the invocation strategies, see+ * {@link JitDataFlowUseropLibrary} and note that the Inline strategy is already handled by this+ * point.+ *+ * <p>+ * For the Standard strategy, we emit code to retire the program counter, decode context, and all+ * live variables. We then request a field to hold the userop and emit code to load it. We then emit+ * code to prepare its arguments and place them on the stack, namely the output varnode and an array+ * for the input varnodes. We request a field for each varnode and emit code to load them as needed.+ * For the array, we emit code to construct and fill it. We then emit code to invoke+ * {@link JitCompiledPassage#invokeUserop(PcodeUseropDefinition, Varnode, Varnode[])}. The userop+ * definition handles retrieving all of its inputs and writing the output, directly to the+ * {@link JitBytesPcodeExecutorState state}. Thus, we now need only to emit code to re-birth all the+ * live variables. If any errors occur, execution is interrupted as usual, and our state is+ * consistent.+ *+ * <p>+ * For the Direct strategy, we wish to avoid retirement and re-birth, so we request an+ * {@link ExceptionHandler}. We request a field for the userop, just as in the Standard strategy,+ * but we emit code to invoke {@link PcodeUseropDefinition#getDefiningLibrary()} instead. We can use+ * {@link PcodeUseropDefinition#getJavaMethod()} <em>at generation time</em> to reflect its Java+ * definition. We then emit code to cast the library and load each of the operands onto the JVM+ * stack. We then emit the invocation of the Java method, guarded by the exception handler. We then+ * have to consider whether the userop has an output operand and whether its definition returns a+ * value. If both are true, we emit code to write the result. If neither is true, we're done. If a+ * result is returned, but no output operand is provided, we <em>must</em> still emit a {@link #POP+ * pop}.+ */+public enum CallOtherOpGen implements OpGen<JitCallOtherOpIf> {+ /** The generator singleton */+ GEN;++ /**+ * Emit code to implement the Standard strategy (see the class documentation)+ *+ * @param gen the code generator+ * @param op the p-code op+ * @param block the block containing the op+ * @param userop the userop definition, wrapped by the {@link JitDataFlowUseropLibrary}+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public static void generateRunCodeUsingRetirementStrategy(JitCodeGenerator gen, PcodeOp op,+ JitBlock block, PcodeUseropDefinition<?> userop, MethodVisitor rv) {+ /**+ * This is about the simplest (laziest) approach we could take for the moment, but it should+ * suffice, depending on the frequency of CALLOTHER executions. We immediately retire all+ * variables, then invoke the userop as it would be by the p-code interpreter. It can access+ * its variables in the usual fashion. Although not ideal, it can also feed the executor+ * (interpreter) ops to execute --- they won't be jitted here. Then, we liven the variables+ * back.+ *+ * NOTE: The output variable should be "alive", so we need not store it into a local. It'll+ * be made alive in the return block transition.+ *+ * TODO: Implement direct invocation for functional userops. NOTE: Cannot avoid block+ * retirement and re-birth unless I also do direct invocation. Otherwise, the parameters are+ * read from the state instead of from the local variables.+ */+ BlockTransition transition = VarGen.computeBlockTransition(gen, block, null);+ transition.generate(rv);++ gen.generateRetirePcCtx(() -> {+ rv.visitLdcInsn(gen.getAddressForOp(op).getOffset());+ }, gen.getExitContext(op), rv);++ // []+ rv.visitVarInsn(ALOAD, 0);+ // [this]+ gen.requestFieldForUserop(userop).generateLoadCode(gen, rv);+ // [this,userop]++ if (op.getOutput() == null) {+ rv.visitInsn(ACONST_NULL);+ }+ else {+ gen.requestStaticFieldForVarnode(op.getOutput()).generateLoadCode(gen, rv);+ }+ // [this,userop,outVn]++ rv.visitLdcInsn(op.getNumInputs() - 1);+ rv.visitTypeInsn(ANEWARRAY, NAME_VARNODE);+ // [this,userop,outVn,inVns:ARR]+ for (int i = 1; i < op.getNumInputs(); i++) {+ // [this,userop,outVn,inVns:ARR]+ rv.visitInsn(DUP);+ // [this,userop,outVn,inVns:ARR,inVns:ARR]+ rv.visitLdcInsn(i - 1);+ // [this,userop,outVn,inVns:ARR,inVns:ARR,index]+ // Yes, including constants :/+ Varnode input = op.getInput(i);+ gen.requestStaticFieldForVarnode(input).generateLoadCode(gen, rv);+ // [this,userop,outVn,inVns:ARR,inVns:ARR,index,inVn]+ rv.visitInsn(AASTORE);+ // [this,userop,outVn,inVns:ARR]+ }+ // [this,userop,outVn,inVns:ARR]++ rv.visitMethodInsn(INVOKEINTERFACE, NAME_JIT_COMPILED_PASSAGE, "invokeUserop",+ MDESC_JIT_COMPILED_PASSAGE__INVOKE_USEROP, true);++ transition.generateInv(rv);+ }++ /**+ * Emit code to implement the Direct strategy (see the class documentation)+ *+ * @param gen the code generator+ * @param op the p-code op use-def node+ * @param block the block containing the op+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public static void generateRunCodeUsingDirectStrategy(JitCodeGenerator gen,+ JitCallOtherOpIf op, JitBlock block, MethodVisitor rv) {+ FieldForUserop useropField = gen.requestFieldForUserop(op.userop());++ // Set<Varnode> live = gen.vsm.getLiveVars(block);+ /**+ * NOTE: It doesn't matter if there are live variables. We still have to "retire" the+ * program counter and contextreg if the userop throws an exception.+ */+ final Label tryStart = new Label();+ final Label tryEnd = new Label();+ rv.visitTryCatchBlock(tryStart, tryEnd,+ gen.requestExceptionHandler((DecodedPcodeOp) op.op(), block).label(), NAME_THROWABLE);++ // []+ useropField.generateLoadCode(gen, rv);+ // [userop]+ rv.visitMethodInsn(INVOKEINTERFACE, NAME_PCODE_USEROP_DEFINITION, "getDefiningLibrary",+ MDESC_PCODE_USEROP_DEFINITION__GET_DEFINING_LIBRARY, true);+ // [library:PcodeUseropLibrary]+ Method method = op.userop().getJavaMethod();+ String owningLibName = Type.getInternalName(method.getDeclaringClass());+ rv.visitTypeInsn(CHECKCAST, owningLibName);+ // [library:OWNING_TYPE]+ Parameter[] parameters = method.getParameters();+ for (int i = 0; i < op.args().size(); i++) {+ JitVal arg = op.args().get(i);+ Parameter p = parameters[i];++ JitType type = gen.generateValReadCode(arg, JitTypeBehavior.ANY);+ if (p.getType() == boolean.class) {+ TypeConversions.generateIntToBool(type, rv);+ }+ else {+ TypeConversions.generate(gen, type, JitType.forJavaType(p.getType()), rv);+ }+ }+ // [library,params...]+ rv.visitLabel(tryStart);+ rv.visitMethodInsn(INVOKEVIRTUAL, owningLibName, method.getName(),+ Type.getMethodDescriptor(method), false);+ // [return?]+ rv.visitLabel(tryEnd);+ if (op instanceof JitCallOtherDefOp defOp) {+ gen.generateVarWriteCode(defOp.out(), JitType.forJavaType(method.getReturnType()));+ }+ else if (method.getReturnType() != void.class) {+ TypeConversions.generatePop(JitType.forJavaType(method.getReturnType()), rv);+ }+ }++ /**+ * Check if the Direct invocation strategy is applicable (see class documentation)+ *+ * @param op the p-code op use-def node+ * @return true if applicable+ */+ public static boolean canDoDirectInvocation(JitCallOtherOpIf op) {+ if (!op.userop().isFunctional()) {+ return false;+ }++ for (JitTypeBehavior type : op.inputTypes()) {+ if (type == JitTypeBehavior.ANY) {+ return false;+ }+ }+ if (op instanceof JitCallOtherDefOp defOp) {+ if (defOp.type() == JitTypeBehavior.ANY) {+ return false;+ }+ }++ return true;+ }++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitCallOtherOpIf op, JitBlock block,+ MethodVisitor rv) {+ if (canDoDirectInvocation(op)) {+ generateRunCodeUsingDirectStrategy(gen, op, block, rv);+ }+ else {+ generateRunCodeUsingRetirementStrategy(gen, op.op(), block, op.userop(), rv);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CatenateOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CatenateOpGen.javanew file mode 100644index 0000000000..3acab73803--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CatenateOpGen.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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitVarScopeModel;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitCatenateOp;++/**+ * The generator for a {@link JitCatenateOp catenate}.+ *+ * <p>+ * We emit nothing. This generator ought never to be invoked, anyway, but things may change. The+ * argument here is similar to that of {@link PhiOpGen}.+ *+ * @see JitVarScopeModel+ */+public enum CatenateOpGen implements OpGen<JitCatenateOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitCatenateOp op, JitBlock block,+ MethodVisitor rv) {+ throw new AssertionError("Cannnot generate synthetic op");+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CompareFloatOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CompareFloatOpGen.javanew file mode 100644index 0000000000..d60c455856--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CompareFloatOpGen.java@@ -0,0 +1,104 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.GOTO;++import org.objectweb.asm.Label;+import org.objectweb.asm.MethodVisitor;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitFloatTestOp;++/**+ * An extension for float comparison operators+ *+ * @param <T> the class of p-code op node in the use-def graph+ */+public interface CompareFloatOpGen<T extends JitFloatTestOp> extends BinOpGen<T> {++ /**+ * The JVM opcode to perform the comparison with float operands on the stack.+ *+ * @return the opcode+ */+ int fcmpOpcode();++ /**+ * The JVM opcode to perform the comparison with double operands on the stack.+ *+ * @return the opcode+ */+ int dcmpOpcode();++ /**+ * The JVM opcode to perform the conditional jump.+ *+ * <p>+ * The condition should correspond to the true case of the p-code operator.+ *+ * @return the opcode+ */+ int condOpcode();++ /**+ * {@inheritDoc}+ *+ * <p>+ * This implementation reduces the need to just a few opcodes: 1) the opcode for comparing in+ * case of JVM {@code float}, 2) the opcode for comparing in the case of JVM {@code double}, and+ * 3) the conditional jump on the result of that comparison. First, the comparison opcode is+ * emitted. It should result in and int <0, ==0, or >0 on the stack, depending on whether+ * L<R, L==R, or L>R, respectively. Then the conditional jump is emitted. We place labels+ * in an if-else pattern to place either a 1 (true) or 0 (false) value of the appropriate p-code+ * type on the stack.+ *+ * @implNote This template is consistently generated by the Java compiler (Adoptium OpenJDK 21),+ * despite there being possible branchless implementations. That could indicate one of+ * a few things: 1) the HotSpot JIT knows how to optimize this pattern, perhaps using+ * branchless native instructions, 2) branchless optimizations don't yield the speedup+ * here we might expect, or 3) they didn't care to optimize. <b>TODO</b>: Investigate+ * in case it's thing 3. We might like to see if branchless JVM bytecodes can improve+ * performance.+ */+ @Override+ default JitType generateBinOpRunCode(JitCodeGenerator gen, T op, JitBlock block, JitType lType,+ JitType rType, MethodVisitor rv) {+ assert rType == lType;+ JitType outType = op.type().resolve(gen.getTypeModel().typeOf(op.out()));+ Label lblTrue = new Label();+ Label lblDone = new Label();+ switch (rType) {+ case FloatJitType t -> rv.visitInsn(fcmpOpcode());+ case DoubleJitType t -> rv.visitInsn(dcmpOpcode());+ case MpFloatJitType t -> Unfinished.TODO("MpFloat");+ default -> throw new AssertionError();+ }+ rv.visitJumpInsn(condOpcode(), lblTrue);+ TypeConversions.generateLdcFalse(outType, rv);+ rv.visitJumpInsn(GOTO, lblDone);+ rv.visitLabel(lblTrue);+ TypeConversions.generateLdcTrue(outType, rv);+ rv.visitLabel(lblDone);++ return outType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CompareIntBinOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CompareIntBinOpGen.javanew file mode 100644index 0000000000..af5eb603d4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CompareIntBinOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.Label;+import org.objectweb.asm.MethodVisitor;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntTestOp;++/**+ * An extension for integer comparison operators+ *+ * @param <T> the class of p-code op node in the use-def graph+ */+public interface CompareIntBinOpGen<T extends JitIntTestOp> extends BinOpGen<T> {++ /**+ * Whether the comparison of p-code integers is signed+ *+ * <p>+ * If the comparison is unsigned, we will emit invocations of+ * {@link Integer#compareUnsigned(int, int)} or {@link Long#compareUnsigned(long, long)},+ * followed by a conditional jump corresponding to this p-code comparison op. If the comparison+ * is signed, and the type fits in a JVM int, we emit the conditional jump of ints directly+ * implementing this p-code comparison op. If the type requires a JVM long, we first emit an+ * {@link #LCMP lcmp}, followed by the same opcode that would be used in the unsigned case.+ *+ * @return true if signed, false if not+ */+ boolean isSigned();++ /**+ * The JVM opcode to perform the conditional jump for signed integers.+ *+ * @return the opcode+ */+ int icmpOpcode();++ /**+ * Emits bytecode for the JVM int case+ *+ * @param lblTrue the target bytecode label for the true case+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ default void generateIntJump(Label lblTrue, MethodVisitor rv) {+ if (isSigned()) {+ rv.visitJumpInsn(icmpOpcode(), lblTrue);+ }+ else {+ rv.visitMethodInsn(INVOKESTATIC, NAME_INTEGER, "compareUnsigned",+ MDESC_INTEGER__COMPARE_UNSIGNED, false);+ rv.visitJumpInsn(ifOpcode(), lblTrue);+ }+ }++ /**+ * Emits bytecode for the JVM long case+ *+ * @param lblTrue the target bytecode label for the true case+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ default void generateLongJump(Label lblTrue, MethodVisitor rv) {+ if (isSigned()) {+ rv.visitInsn(LCMP);+ }+ else {+ rv.visitMethodInsn(INVOKESTATIC, NAME_LONG, "compareUnsigned",+ MDESC_LONG__COMPARE_UNSIGNED, false);+ }+ rv.visitJumpInsn(ifOpcode(), lblTrue);+ }++ /**+ * The JVM opcode to perform the conditional jump for unsigned or long integers.+ *+ * This is emitted <em>after</em> the application of {@link #LCMP} or the comparator method.+ *+ * @return the opcode+ */+ int ifOpcode();++ @Override+ default JitType afterLeft(JitCodeGenerator gen, T op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformZExt(lType, rType, rv);+ }++ /**+ * {@inheritDoc}+ *+ * <p>+ * This reduces the implementation to a flag for signedness, the opcode for the conditional jump+ * on integer operands, and the opcode for a conditional jump after the comparison of longs. The+ * JVM, does not provide conditional jumps on long operands, so we must first compare the longs,+ * pushing an int onto the stack, and then conditionally jumping on that. This pattern is+ * similar for unsigned comparison of integers.+ */+ @Override+ default JitType generateBinOpRunCode(JitCodeGenerator gen, T op, JitBlock block, JitType lType,+ JitType rType, MethodVisitor rv) {+ Label lblTrue = new Label();+ Label lblDone = new Label();++ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> generateIntJump(lblTrue, rv);+ case LongJitType t -> generateLongJump(lblTrue, rv);+ case MpIntJitType t -> Unfinished.TODO("MpInt");+ default -> throw new AssertionError();+ }+ JitType outType = op.type().resolve(gen.getTypeModel().typeOf(op.out()));+ TypeConversions.generateLdcFalse(outType, rv);+ rv.visitJumpInsn(GOTO, lblDone);+ rv.visitLabel(lblTrue);+ TypeConversions.generateLdcTrue(outType, rv);+ rv.visitLabel(lblDone);++ return outType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CopyOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CopyOpGen.javanew file mode 100644index 0000000000..8419b27fb4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/CopyOpGen.java@@ -0,0 +1,42 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.op.JitCopyOp;++/**+ * The generator for a {@link JitCopyOp copy}.+ *+ * <p>+ * This uses the unary operator generator and emits nothing extra. The unary generator template will+ * emit code to load the input operand, this emits nothing, and then the template emits code to+ * write the output operand, effecting a simple copy.+ */+public enum CopyOpGen implements UnOpGen<JitCopyOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitCopyOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatAbsOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatAbsOpGen.javanew file mode 100644index 0000000000..7334ba8f32--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatAbsOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.INVOKESTATIC;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatAbsOp;++/**+ * The generator for a {@link JitFloatAbsOp float_abs}.+ *+ * <p>+ * This uses the unary operator generator and emits an invocation of {@link Math#abs(float)} or+ * {@link Math#abs(double)}, depending on the type.+ */+public enum FloatAbsOpGen implements UnOpGen<JitFloatAbsOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatAbsOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case FloatJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "abs",+ MDESC_$FLOAT_UNOP, false);+ case DoubleJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "abs",+ MDESC_$DOUBLE_UNOP, false);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatAddOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatAddOpGen.javanew file mode 100644index 0000000000..647f98d466--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatAddOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.DADD;+import static org.objectweb.asm.Opcodes.FADD;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatAddOp;++/**+ * The generator for a {@link JitFloatAddOp float_add}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #FADD} or {@link #DADD} depending+ * on the type.+ */+public enum FloatAddOpGen implements BinOpGen<JitFloatAddOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitFloatAddOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ assert rType == lType;+ switch (lType) {+ case FloatJitType t -> rv.visitInsn(FADD);+ case DoubleJitType t -> rv.visitInsn(DADD);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatCeilOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatCeilOpGen.javanew file mode 100644index 0000000000..cb844a89d4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatCeilOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.MDESC_$DOUBLE_UNOP;+import static ghidra.pcode.emu.jit.gen.GenConsts.NAME_MATH;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatCeilOp;++/**+ * The generator for a {@link JitFloatCeilOp float_ceil}.+ *+ * <p>+ * This uses the unary operator generator and emits an invocation of {@link Math#ceil(double)},+ * possibly surrounding it with conversions from and to float.+ */+public enum FloatCeilOpGen implements UnOpGen<JitFloatCeilOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatCeilOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case FloatJitType t -> {+ // There apparently is no Math.ceil(float)???+ rv.visitInsn(F2D);+ rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "ceil", MDESC_$DOUBLE_UNOP, false);+ rv.visitInsn(D2F);+ }+ case DoubleJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "ceil",+ MDESC_$DOUBLE_UNOP, false);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatDivOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatDivOpGen.javanew file mode 100644index 0000000000..42e8daa996--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatDivOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.DDIV;+import static org.objectweb.asm.Opcodes.FDIV;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatDivOp;++/**+ * The generator for a {@link JitFloatDivOp float_div}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #FDIV} or {@link #DDIV} depending+ * on the type.+ */+public enum FloatDivOpGen implements BinOpGen<JitFloatDivOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitFloatDivOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ assert rType == lType;+ switch (lType) {+ case FloatJitType t -> rv.visitInsn(FDIV);+ case DoubleJitType t -> rv.visitInsn(DDIV);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatEqualOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatEqualOpGen.javanew file mode 100644index 0000000000..175dfc8621--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatEqualOpGen.java@@ -0,0 +1,47 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import ghidra.pcode.emu.jit.op.JitFloatEqualOp;++/**+ * The generator for a {@link JitFloatEqualOp float_equal}.+ *+ * <p>+ * This uses the float comparison operator generator and simply emits {@link #FCMPL} or+ * {@link #DCMPL} depending on the type and then {@link #IFEQ}.+ */+public enum FloatEqualOpGen implements CompareFloatOpGen<JitFloatEqualOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int fcmpOpcode() {+ return FCMPL;+ }++ @Override+ public int dcmpOpcode() {+ return DCMPL;+ }++ @Override+ public int condOpcode() {+ return IFEQ;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatFloat2FloatOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatFloat2FloatOpGen.javanew file mode 100644index 0000000000..2b14d09ae9--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatFloat2FloatOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.D2F;+import static org.objectweb.asm.Opcodes.F2D;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatFloat2FloatOp;++/**+ * The generator for a {@link JitFloatFloat2FloatOp float_float2float}.+ *+ * <p>+ * This uses the unary operator generator and emits {@link #F2D} or {@link #D2F}.+ */+public enum FloatFloat2FloatOpGen implements UnOpGen<JitFloatFloat2FloatOp> {+ /** The generator singleton */+ GEN;++ private JitType gen(MethodVisitor rv, int opcode, JitType type) {+ rv.visitInsn(opcode);+ return type;+ }++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatFloat2FloatOp op,+ JitBlock block, JitType uType, MethodVisitor rv) {+ JitType outType = op.type().resolve(gen.getTypeModel().typeOf(op.out()));+ return switch (uType) {+ case FloatJitType ut -> switch (outType) {+ case FloatJitType ot -> ot;+ case DoubleJitType ot -> gen(rv, F2D, ot);+ case MpFloatJitType ot -> TODO("MpFloat");+ default -> throw new AssertionError();+ };+ case DoubleJitType ut -> switch (outType) {+ case FloatJitType ot -> gen(rv, D2F, ot);+ case DoubleJitType ot -> ot;+ case MpFloatJitType ot -> TODO("MpFloat");+ default -> throw new AssertionError();+ };+ case MpFloatJitType ot -> TODO("MpFloat");+ default -> throw new AssertionError();+ };+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatFloorOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatFloorOpGen.javanew file mode 100644index 0000000000..fefcad8828--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatFloorOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.MDESC_$DOUBLE_UNOP;+import static ghidra.pcode.emu.jit.gen.GenConsts.NAME_MATH;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatFloorOp;++/**+ * The generator for a {@link JitFloatFloorOp float_floor}.+ *+ * <p>+ * This uses the unary operator generator and emits an invocation of {@link Math#floor(double)},+ * possibly surrounding it with conversions from and to float.+ */+public enum FloatFloorOpGen implements UnOpGen<JitFloatFloorOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatFloorOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case FloatJitType t -> {+ // There apparently is no Math.floor(float)???+ rv.visitInsn(F2D);+ rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "floor", MDESC_$DOUBLE_UNOP, false);+ rv.visitInsn(D2F);+ }+ case DoubleJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "floor",+ MDESC_$DOUBLE_UNOP, false);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatInt2FloatOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatInt2FloatOpGen.javanew file mode 100644index 0000000000..430b252c2a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatInt2FloatOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatInt2FloatOp;++/**+ * The generator for a {@link JitFloatInt2FloatOp float_int2float}.+ *+ * <p>+ * This uses the unary operator generator and emits {@link #I2F}, {@link #I2D}, {@link #L2F}, or+ * {@link #L2D}.+ */+public enum FloatInt2FloatOpGen implements UnOpGen<JitFloatInt2FloatOp> {+ /** The generator singleton */+ GEN;++ private JitType gen(MethodVisitor rv, int opcode, JitType type) {+ rv.visitInsn(opcode);+ return type;+ }++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatInt2FloatOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ JitType outType = op.type().resolve(gen.getTypeModel().typeOf(op.out()));+ return switch (uType) {+ case IntJitType ut -> switch (outType) {+ case FloatJitType ot -> gen(rv, I2F, ot);+ case DoubleJitType ot -> gen(rv, I2D, ot);+ case MpFloatJitType ot -> TODO("MpInt/Float");+ default -> throw new AssertionError();+ };+ case LongJitType ut -> switch (outType) {+ case FloatJitType ot -> gen(rv, L2F, ot);+ case DoubleJitType ot -> gen(rv, L2D, ot);+ case MpFloatJitType ot -> TODO("MpInt/Float");+ default -> throw new AssertionError();+ };+ case MpIntJitType ut -> TODO("MpInt/Float");+ default -> throw new AssertionError();+ };+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatLessEqualOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatLessEqualOpGen.javanew file mode 100644index 0000000000..98bc9f8500--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatLessEqualOpGen.java@@ -0,0 +1,47 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import ghidra.pcode.emu.jit.op.JitFloatLessEqualOp;++/**+ * The generator for a {@link JitFloatLessEqualOp float_lessequal}.+ *+ * <p>+ * This uses the float comparison operator generator and simply emits {@link #FCMPG} or+ * {@link #DCMPG} depending on the type and then {@link #IFLE}.+ */+public enum FloatLessEqualOpGen implements CompareFloatOpGen<JitFloatLessEqualOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int fcmpOpcode() {+ return FCMPG;+ }++ @Override+ public int dcmpOpcode() {+ return DCMPG;+ }++ @Override+ public int condOpcode() {+ return IFLE;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatLessOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatLessOpGen.javanew file mode 100644index 0000000000..1da203130d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatLessOpGen.java@@ -0,0 +1,47 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import ghidra.pcode.emu.jit.op.JitFloatLessOp;++/**+ * The generator for a {@link JitFloatLessOp float_less}.+ *+ * <p>+ * This uses the float comparison operator generator and simply emits {@link #FCMPG} or+ * {@link #DCMPG} depending on the type and then {@link #IFLT}.+ */+public enum FloatLessOpGen implements CompareFloatOpGen<JitFloatLessOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int fcmpOpcode() {+ return FCMPG;+ }++ @Override+ public int dcmpOpcode() {+ return DCMPG;+ }++ @Override+ public int condOpcode() {+ return IFLT;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatMultOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatMultOpGen.javanew file mode 100644index 0000000000..c17fb951ff--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatMultOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.DMUL;+import static org.objectweb.asm.Opcodes.FMUL;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatMultOp;++/**+ * The generator for a {@link JitFloatMultOp float_mult}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #FMUL} or {@link #DMUL} depending+ * on the type.+ */+public enum FloatMultOpGen implements BinOpGen<JitFloatMultOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitFloatMultOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ assert rType == lType;+ switch (lType) {+ case FloatJitType t -> rv.visitInsn(FMUL);+ case DoubleJitType t -> rv.visitInsn(DMUL);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNaNOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNaNOpGen.javanew file mode 100644index 0000000000..38339dba61--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNaNOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.INVOKESTATIC;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatNaNOp;++/**+ * The generator for a {@link JitFloatNaNOp float_nan}.+ *+ * <p>+ * This uses the unary operator generator and emits an invocation of {@link Float#isNaN(float)} or+ * {@link Double#isNaN(double)}, depending on the type.+ */+public enum FloatNaNOpGen implements UnOpGen<JitFloatNaNOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatNaNOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case FloatJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_FLOAT, "isNaN",+ MDESC_FLOAT__IS_NAN, false);+ case DoubleJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_DOUBLE, "isNaN",+ MDESC_DOUBLE__IS_NAN, false);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return IntJitType.I4;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNegOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNegOpGen.javanew file mode 100644index 0000000000..0a4d7d91a4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNegOpGen.java@@ -0,0 +1,51 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.DNEG;+import static org.objectweb.asm.Opcodes.FNEG;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatNegOp;++/**+ * The generator for a {@link JitFloatNegOp float_neg}.+ *+ * <p>+ * This uses the unary operator generator and emits {@link #FNEG} or {@link #DNEG}.+ */+public enum FloatNegOpGen implements UnOpGen<JitFloatNegOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatNegOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case FloatJitType t -> rv.visitInsn(FNEG);+ case DoubleJitType t -> rv.visitInsn(DNEG);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNotEqualOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNotEqualOpGen.javanew file mode 100644index 0000000000..873e5397db--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatNotEqualOpGen.java@@ -0,0 +1,47 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import ghidra.pcode.emu.jit.op.JitFloatNotEqualOp;++/**+ * The generator for a {@link JitFloatNotEqualOp float_notequal}.+ *+ * <p>+ * This uses the float comparison operator generator and simply emits {@link #FCMPL} or+ * {@link #DCMPL} depending on the type and then {@link #IFNE}.+ */+public enum FloatNotEqualOpGen implements CompareFloatOpGen<JitFloatNotEqualOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int fcmpOpcode() {+ return FCMPL;+ }++ @Override+ public int dcmpOpcode() {+ return DCMPL;+ }++ @Override+ public int condOpcode() {+ return IFNE;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatRoundOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatRoundOpGen.javanew file mode 100644index 0000000000..b39ff90c24--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatRoundOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.MDESC_$DOUBLE_UNOP;+import static ghidra.pcode.emu.jit.gen.GenConsts.NAME_MATH;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatRoundOp;++/**+ * The generator for a {@link JitFloatRoundOp float_round}.+ *+ * <p>+ * The JVM does provide a {@link Math#round(float)} method, however it returns an int. (It has+ * similar for doubles with the same problem.) That would be suitable if a type conversion were also+ * desired, but that is not the case. Thus, we construct a rounding function without conversion:+ * {@code round(x) = floor(x + 0.5)}. This uses the unary operator generator and emits the bytecode+ * to implement that definition, applying type conversions as needed.+ */+public enum FloatRoundOpGen implements UnOpGen<JitFloatRoundOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatRoundOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ // Math.round also converts to int/long+ case FloatJitType t -> {+ rv.visitLdcInsn(0.5f);+ rv.visitInsn(FADD);+ rv.visitInsn(F2D);+ rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "floor", MDESC_$DOUBLE_UNOP, false);+ rv.visitInsn(D2F);+ }+ case DoubleJitType t -> {+ rv.visitLdcInsn(0.5d);+ rv.visitInsn(DADD);+ rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "floor", MDESC_$DOUBLE_UNOP, false);+ }+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatSqrtOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatSqrtOpGen.javanew file mode 100644index 0000000000..2ded873509--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatSqrtOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.MDESC_$DOUBLE_UNOP;+import static ghidra.pcode.emu.jit.gen.GenConsts.NAME_MATH;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatSqrtOp;++/**+ * The generator for a {@link JitFloatSqrtOp float_sqrt}.+ *+ * <p>+ * This uses the unary operator generator and emits an invocation of {@link Math#sqrt(double)},+ * possibly surrounding it with conversions from and to float.+ */+public enum FloatSqrtOpGen implements UnOpGen<JitFloatSqrtOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatSqrtOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case FloatJitType t -> {+ rv.visitInsn(F2D);+ rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "sqrt", MDESC_$DOUBLE_UNOP, false);+ rv.visitInsn(D2F);+ }+ case DoubleJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_MATH, "sqrt",+ MDESC_$DOUBLE_UNOP, false);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatSubOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatSubOpGen.javanew file mode 100644index 0000000000..22e963d0d3--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatSubOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.DSUB;+import static org.objectweb.asm.Opcodes.FSUB;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatSubOp;++/**+ * The generator for a {@link JitFloatSubOp float_sub}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #FSUB} or {@link #DSUB} depending+ * on the type.+ */+public enum FloatSubOpGen implements BinOpGen<JitFloatSubOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitFloatSubOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ assert rType == lType;+ switch (lType) {+ case FloatJitType t -> rv.visitInsn(FSUB);+ case DoubleJitType t -> rv.visitInsn(DSUB);+ case MpFloatJitType t -> TODO("MpFloat");+ default -> throw new AssertionError();+ }+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatTruncOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatTruncOpGen.javanew file mode 100644index 0000000000..21f6a817ca--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/FloatTruncOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitFloatTruncOp;++/**+ * The generator for a {@link JitFloatTruncOp float_trunc}.+ *+ * <p>+ * This uses the unary operator generator and emits {@link #F2I}, {@link #F2L}, {@link #D2I}, or+ * {@link #D2L}.+ */+public enum FloatTruncOpGen implements UnOpGen<JitFloatTruncOp> {+ /** The generator singleton */+ GEN;++ private JitType gen(MethodVisitor rv, int opcode, JitType type) {+ rv.visitInsn(opcode);+ return type;+ }++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitFloatTruncOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ JitType outType = op.type().resolve(gen.getTypeModel().typeOf(op.out()));+ return switch (uType) {+ case FloatJitType ut -> switch (outType) {+ case IntJitType ot -> gen(rv, F2I, ot);+ case LongJitType ot -> gen(rv, F2L, ot);+ case MpIntJitType ot -> TODO("MpFloat/Int");+ default -> throw new AssertionError();+ };+ case DoubleJitType ut -> switch (outType) {+ case IntJitType ot -> gen(rv, D2I, ot);+ case LongJitType ot -> gen(rv, D2L, ot);+ case MpIntJitType ot -> TODO("MpFloat/Int");+ default -> throw new AssertionError();+ };+ case MpIntJitType ot -> TODO("MpFloat/Int");+ default -> throw new AssertionError();+ };+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/Int2CompOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/Int2CompOpGen.javanew file mode 100644index 0000000000..9a33514bf6--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/Int2CompOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.INEG;+import static org.objectweb.asm.Opcodes.LNEG;++import org.objectweb.asm.MethodVisitor;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitInt2CompOp;++/**+ * The generator for a {@link JitInt2CompOp int_2comp}.+ *+ * <p>+ * This uses the unary operator generator and emits {@link #INEG} or {@link #LNEG}, depending on+ * type.+ */+public enum Int2CompOpGen implements UnOpGen<JitInt2CompOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitInt2CompOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case IntJitType t -> rv.visitInsn(INEG);+ case LongJitType t -> rv.visitInsn(LNEG);+ case MpIntJitType t -> Unfinished.TODO("MpInt");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntAddOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntAddOpGen.javanew file mode 100644index 0000000000..3441cc33a1--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntAddOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.*;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntAddOp;++/**+ * The generator for a {@link JitIntAddOp int_add}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #IADD} or {@link #LADD} depending+ * on the type.+ *+ * <p>+ * NOTE: The multi-precision integer parts of this are a work in progress.+ */+public enum IntAddOpGen implements BinOpGen<JitIntAddOp> {+ /** The generator singleton */+ GEN;++ static void generateMpIntLegAdd(JitCodeGenerator gen, int idx, boolean takesCarry,+ boolean givesCarry, MethodVisitor mv) {+ if (takesCarry) {+ // [...,llegN:INT,olegN+1:LONG]+ mv.visitLdcInsn(32);+ mv.visitInsn(LUSHR);+ // [...,lleg1...,carryinN:LONG]+ mv.visitInsn(DUP2_X1);+ mv.visitInsn(POP2);+ // [...,carryinN:LONG,llegN:INT]+ TypeConversions.generateIntToLong(IntJitType.I4, LongJitType.I8, mv);+ // [...,carryinN:LONG,llegN:LONG]+ mv.visitInsn(LADD);+ // [...,sumpartN:LONG]+ }+ else {+ // [...,legN:INT]+ TypeConversions.generateIntToLong(IntJitType.I4, LongJitType.I8, mv);+ // [...,sumpartN:LONG] (legN + 0)+ }+ mv.visitVarInsn(ILOAD, idx);+ // [...,sumpartN:LONG,rlegN:INT]+ TypeConversions.generateIntToLong(IntJitType.I4, LongJitType.I8, mv);+ // [...,sumpartN:LONG,rlegN:LONG]+ mv.visitInsn(LADD);+ // [...,olegN:LONG]+ if (givesCarry) {+ mv.visitInsn(DUP2);+ }+ // [...,(olegN:LONG),olegN:LONG]+ TypeConversions.generateLongToInt(LongJitType.I8, IntJitType.I4, mv);+ // [...,(olegN:LONG),olegN:INT]+ /** NB. The store will perform the masking */+ mv.visitVarInsn(ISTORE, idx);+ // [...,(olegN:LONG)]+ }++ private void generateMpIntAdd(JitCodeGenerator gen, MpIntJitType type, MethodVisitor mv) {+ /**+ * The strategy is to allocate a temp local for each leg of the result. First, we'll pop the+ * right operand into the temp. Then, as we work with each leg of the left operand, we'll+ * execute the algorithm. Convert both right and left legs to a long and add them (along+ * with a possible carry in). Store the result back into the temp locals. Shift the leg+ * right 32 to get the carry out, then continue to the next leg up. The final carry out can+ * be dropped (overflow). The result legs are then pushed back to the stack.+ */+ // [lleg1,...,llegN,rleg1,rlegN] (N is least-significant leg)+ int legCount = type.legsAlloc();+ int firstIndex = gen.getAllocationModel().nextFreeLocal();+ Label start = new Label();+ Label end = new Label();+ mv.visitLabel(start);+ for (int i = 0; i < legCount; i++) {+ mv.visitLocalVariable("result" + i, Type.getDescriptor(int.class), null, start, end,+ firstIndex + i);+ mv.visitVarInsn(ISTORE, firstIndex + i);+ // NOTE: More significant legs have higher indices (reverse of stack)+ }+ // [lleg1,...,llegN:INT]+ for (int i = 0; i < legCount; i++) {+ boolean isLast = i == legCount - 1;+ boolean takesCarry = i != 0; // not first+ generateMpIntLegAdd(gen, firstIndex + i, takesCarry, !isLast, mv);+ }++ // Push it all back, in reverse order+ for (int i = 0; i < legCount; i++) {+ mv.visitVarInsn(ILOAD, firstIndex + legCount - i - 1);+ }+ mv.visitLabel(end);+ }++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntAddOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformZExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntAddOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitInsn(IADD);+ case LongJitType t -> rv.visitInsn(LADD);+ case MpIntJitType t when t.size() == lType.size() -> generateMpIntAdd(gen, t, rv);+ case MpIntJitType t -> TODO("MpInt of differing sizes");+ default -> throw new AssertionError();+ }+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntAndOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntAndOpGen.javanew file mode 100644index 0000000000..8393d73bdd--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntAndOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IAND;+import static org.objectweb.asm.Opcodes.LAND;++import ghidra.pcode.emu.jit.op.JitIntAndOp;++/**+ * The generator for a {@link JitIntAndOp int_and}.+ *+ * <p>+ * This uses the bitwise binary operator and emits {@link #IAND} or {@link #LAND} depending on the+ * type.+ */+public enum IntAndOpGen implements BitwiseBinOpGen<JitIntAndOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int intOpcode() {+ return IAND;+ }++ @Override+ public int longOpcode() {+ return LAND;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntCarryOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntCarryOpGen.javanew file mode 100644index 0000000000..7656f2028f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntCarryOpGen.java@@ -0,0 +1,182 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.*;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntCarryOp;++/**+ * The generator for a {@link JitIntCarryOp int_carry}.+ *+ * <p>+ * This uses the binary operator generator. First we have to consider which strategy we are going to+ * use. If the p-code type is strictly smaller than its host JVM type, we can simply add the two+ * operands and examine the next bit up. This is accomplished by emitting {@link #IADD} or+ * {@link #LADD}, depending on the type, followed by a shift right and a mask.+ *+ * <p>+ * If the p-code type exactly fits its host JVM type, we still add, but we will need to compare the+ * result to one of the operands. Thus, we override+ * {@link #afterLeft(JitCodeGenerator, JitIntCarryOp, JitType, JitType, MethodVisitor) afterLeft}+ * and emit code to duplicate the left operand. We can then add and invoke+ * {@link Integer#compareUnsigned(int, int)} to determine whether there was overflow. If there was,+ * then we know the carry bit would have been set. We can spare the conditional flow by just+ * shifting the sign bit into the 1's place.+ *+ * <p>+ * NOTE: The multi-precision integer parts of this are a work in progress.+ */+public enum IntCarryOpGen implements BinOpGen<JitIntCarryOp> {+ /** The generator singleton */+ GEN;++ private void generateMpIntCarry(JitCodeGenerator gen, MpIntJitType type, MethodVisitor mv) {+ /**+ * Similar strategy as for INT_ADD. In fact, we call its per-leg logic.+ */+ // [lleg1,...,llegN,rleg1,rlegN] (N is least-significant leg)+ int legCount = type.legsAlloc();+ int remSize = type.partialSize();+ int firstIndex = gen.getAllocationModel().nextFreeLocal();+ Label start = new Label();+ Label end = new Label();+ mv.visitLabel(start);+ for (int i = 0; i < legCount; i++) {+ mv.visitLocalVariable("temp" + i, Type.getDescriptor(int.class), null, start, end,+ firstIndex + i);+ mv.visitVarInsn(ISTORE, firstIndex + i);+ // NOTE: More significant legs have higher indices (reverse of stack)+ }+ // [lleg1,...,llegN:INT]+ for (int i = 0; i < legCount; i++) {+ boolean takesCarry = i != 0; // not first+ IntAddOpGen.generateMpIntLegAdd(gen, firstIndex + i, takesCarry, true, mv);+ }+ // [olegN:LONG]+ if (remSize == 0) {+ // The last leg was full, so extract bit 32+ mv.visitLdcInsn(32);+ }+ else {+ // The last leg was partial, so get the next more significant bit+ mv.visitLdcInsn(remSize * Byte.SIZE);+ }+ mv.visitInsn(LUSHR);+ TypeConversions.generateLongToInt(LongJitType.I8, IntJitType.I4, mv);+ mv.visitLdcInsn(1);+ mv.visitInsn(IAND);+ mv.visitLabel(end);+ }++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntCarryOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ /**+ * There are two strategies to use here depending on whether or not there's room to capture+ * the carry bit. If there's not room, we have to compare the sum to one of the input+ * operands. If the sum is less, then we can conclude there was a carry. For that strategy,+ * we will need to keep a copy of the left operand, so duplicate it.+ *+ * On the other hand, if there is room to capture the carry, we can just add the two+ * operands and extract the carry bit. There is no need to duplicate the left operand.+ */+ lType = TypeConversions.forceUniformZExt(lType, rType, rv);+ switch (lType) {+ case IntJitType(int size) when size == Integer.BYTES -> rv.visitInsn(DUP);+ case IntJitType lt -> {+ }+ case LongJitType(int size) when size == Long.BYTES -> rv.visitInsn(DUP2);+ case LongJitType lt -> {+ }+ case MpIntJitType lt -> TODO("MpInt");+ default -> throw new AssertionError();+ }+ return lType;+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntCarryOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType(int size) when size == Integer.BYTES -> {+ // [l,l,r]+ rv.visitInsn(IADD);+ // [l,sum]+ rv.visitInsn(SWAP); // spare an LDC,XOR+ // [sum,l]+ rv.visitMethodInsn(INVOKESTATIC, NAME_INTEGER, "compareUnsigned",+ MDESC_INTEGER__COMPARE_UNSIGNED, false);+ // [cmpU(sum,l)] sum < l iff sign bit is 1+ rv.visitLdcInsn(31);+ rv.visitInsn(IUSHR);+ return IntJitType.I1;+ }+ case IntJitType(int size) -> {+ // Just add and extract the carry bit+ rv.visitInsn(IADD);+ rv.visitLdcInsn(size * Byte.SIZE);+ rv.visitInsn(ISHR);+ rv.visitLdcInsn(1);+ rv.visitInsn(IAND);+ return IntJitType.I1;+ }+ case LongJitType(int size) when size == Long.BYTES -> {+ // [l:LONG,l:LONG,r:LONG]+ rv.visitInsn(LADD);+ // [l:LONG,sum:LONG]+ rv.visitInsn(DUP2_X2);+ rv.visitInsn(POP2);+ // [sum:LONG,l:LONG]+ rv.visitMethodInsn(INVOKESTATIC, NAME_LONG, "compareUnsigned",+ MDESC_LONG__COMPARE_UNSIGNED, false);+ // [cmpU(sum,l):INT] sum < l iff sign bit is 1+ rv.visitLdcInsn(31);+ rv.visitInsn(IUSHR);+ return IntJitType.I1;+ }+ case LongJitType(int size) -> {+ // Just add and extract the carry bit+ rv.visitInsn(LADD);+ rv.visitLdcInsn(size * Byte.SIZE);+ rv.visitInsn(LSHR);+ rv.visitInsn(L2I);+ // TODO: This mask may not be necessary+ rv.visitLdcInsn(1);+ rv.visitInsn(IAND);+ return IntJitType.I1;+ }+ case MpIntJitType t when t.size() == lType.size() -> {+ generateMpIntCarry(gen, t, rv);+ return IntJitType.I1;+ }+ case MpIntJitType t -> {+ return TODO("MpInt of differing sizes");+ }+ default -> throw new AssertionError();+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntDivOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntDivOpGen.javanew file mode 100644index 0000000000..dc8efa1cf5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntDivOpGen.java@@ -0,0 +1,65 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.INVOKESTATIC;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntAddOp;+import ghidra.pcode.emu.jit.op.JitIntDivOp;++/**+ * The generator for a {@link JitIntAddOp int_add}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #INVOKESTATIC} on+ * {@link Integer#divideUnsigned(int, int)} or {@link Long#divideUnsigned(long, long)} depending on+ * the type.+ */+public enum IntDivOpGen implements BinOpGen<JitIntDivOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntDivOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformZExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntDivOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_INTEGER, "divideUnsigned",+ MDESC_$INT_BINOP, false);+ case LongJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_LONG, "divideUnsigned",+ MDESC_$LONG_BINOP, false);+ case MpIntJitType t -> TODO("MpInt");+ default -> throw new AssertionError();+ }+ // TODO: For MpInt case, we should use the outvar's size to cull operations.+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntEqualOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntEqualOpGen.javanew file mode 100644index 0000000000..0ed4287bf7--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntEqualOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IFEQ;+import static org.objectweb.asm.Opcodes.IF_ICMPEQ;++import ghidra.pcode.emu.jit.op.JitIntEqualOp;++/**+ * The generator for a {@link JitIntEqualOp int_equal}.+ *+ * <p>+ * This uses the integer comparison operator generator and simply emits {@link #IF_ICMPEQ} or+ * {@link #IFEQ} depending on the type.+ */+public enum IntEqualOpGen implements CompareIntBinOpGen<JitIntEqualOp> {+ /** The generator singleton */+ GEN;++ @Override+ public boolean isSigned() {+ return true; // Doesn't matter. Java favors signed.+ }++ @Override+ public int icmpOpcode() {+ return IF_ICMPEQ;+ }++ @Override+ public int ifOpcode() {+ return IFEQ;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLeftOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLeftOpGen.javanew file mode 100644index 0000000000..9ca3b2fa54--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLeftOpGen.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.pcode.emu.jit.gen.op;++import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.op.JitIntLeftOp;++/**+ * The generator for a {@link JitIntLeftOp int_left}.+ *+ * <p>+ * This uses the integer shift operator generator and simply invokes+ * {@link JitCompiledPassage#intLeft(int, int)}, etc. depending on the types.+ */+public enum IntLeftOpGen implements ShiftIntBinOpGen<JitIntLeftOp> {+ /** The generator singleton */+ GEN;++ @Override+ public String methodName() {+ return "intLeft";+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLessEqualOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLessEqualOpGen.javanew file mode 100644index 0000000000..9782de0937--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLessEqualOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IFLE;++import ghidra.pcode.emu.jit.op.JitIntLessEqualOp;++/**+ * The generator for a {@link JitIntLessEqualOp int_lessequal}.+ *+ * <p>+ * This uses the integer comparison operator generator and simply emits {@link #IFLE}.+ */+public enum IntLessEqualOpGen implements CompareIntBinOpGen<JitIntLessEqualOp> {+ /** The generator singleton */+ GEN;++ @Override+ public boolean isSigned() {+ return false;+ }++ @Override+ public int icmpOpcode() {+ throw new AssertionError();+ }++ @Override+ public int ifOpcode() {+ return IFLE;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLessOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLessOpGen.javanew file mode 100644index 0000000000..517e51f87f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntLessOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IFLT;++import ghidra.pcode.emu.jit.op.JitIntLessOp;++/**+ * The generator for a {@link JitIntLessOp int_less}.+ *+ * <p>+ * This uses the integer comparison operator generator and simply emits {@link #IFLT}.+ */+public enum IntLessOpGen implements CompareIntBinOpGen<JitIntLessOp> {+ /** The generator singleton */+ GEN;++ @Override+ public boolean isSigned() {+ return false;+ }++ @Override+ public int icmpOpcode() {+ throw new AssertionError();+ }++ @Override+ public int ifOpcode() {+ return IFLT;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntMultOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntMultOpGen.javanew file mode 100644index 0000000000..737f2c820a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntMultOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.IMUL;+import static org.objectweb.asm.Opcodes.LMUL;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntMultOp;++/**+ * The generator for a {@link JitIntMultOp int_mult}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #IMUL} or {@link #LMUL} depending+ * on the type.+ */+public enum IntMultOpGen implements BinOpGen<JitIntMultOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntMultOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformZExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntMultOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitInsn(IMUL);+ case LongJitType t -> rv.visitInsn(LMUL);+ case MpIntJitType t -> TODO("MpInt");+ default -> throw new AssertionError();+ }+ // TODO: For MpInt case, we should use the outvar's size to cull operations.+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntNegateOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntNegateOpGen.javanew file mode 100644index 0000000000..95ffac3a44--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntNegateOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitIntNegateOp;++/**+ * The generator for a {@link JitIntNegateOp int_negate}.+ *+ * <p>+ * There is no bitwise "not" operator in the JVM. We borrow the pattern we see output by the Java+ * compiler for <code>int negate(n) {return ~n;}</code>. It XORs the input with a register of 1s.+ * This uses the unary operator generator and emits the equivalent code.+ */+public enum IntNegateOpGen implements UnOpGen<JitIntNegateOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitIntNegateOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case IntJitType t -> {+ rv.visitInsn(ICONST_M1);+ rv.visitInsn(IXOR);+ }+ case LongJitType t -> {+ rv.visitLdcInsn(-1L);+ rv.visitInsn(LXOR);+ }+ case MpIntJitType t -> Unfinished.TODO("MpInt");+ default -> throw new AssertionError();+ }+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntNotEqualOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntNotEqualOpGen.javanew file mode 100644index 0000000000..6c726e9225--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntNotEqualOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IFNE;+import static org.objectweb.asm.Opcodes.IF_ICMPNE;++import ghidra.pcode.emu.jit.op.JitIntNotEqualOp;++/**+ * The generator for a {@link JitIntNotEqualOp int_notequal}.+ *+ * <p>+ * This uses the integer comparison operator generator and simply emits {@link #IF_ICMPNE} or+ * {@link #IFNE} depending on the type.+ */+public enum IntNotEqualOpGen implements CompareIntBinOpGen<JitIntNotEqualOp> {+ /** The generator singleton */+ GEN;++ @Override+ public boolean isSigned() {+ return true; // Doesn't matter. Java favors signed.+ }++ @Override+ public int icmpOpcode() {+ return IF_ICMPNE;+ }++ @Override+ public int ifOpcode() {+ return IFNE;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntOrOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntOrOpGen.javanew file mode 100644index 0000000000..b169e0430a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntOrOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IOR;+import static org.objectweb.asm.Opcodes.LOR;++import ghidra.pcode.emu.jit.op.JitIntOrOp;++/**+ * The generator for a {@link JitIntOrOp int_or}.+ *+ * <p>+ * This uses the bitwise binary operator and emits {@link #IOR} or {@link #LOR} depending on the+ * type.+ */+public enum IntOrOpGen implements BitwiseBinOpGen<JitIntOrOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int intOpcode() {+ return IOR;+ }++ @Override+ public int longOpcode() {+ return LOR;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntRemOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntRemOpGen.javanew file mode 100644index 0000000000..d8d33b37c1--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntRemOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.INVOKESTATIC;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntRemOp;++/**+ * The generator for a {@link JitIntRemOp int_rem}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #INVOKESTATIC} on+ * {@link Integer#remainderUnsigned(int, int)} or {@link Long#remainderUnsigned(long, long)}+ * depending on the type.+ */+public enum IntRemOpGen implements BinOpGen<JitIntRemOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntRemOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformZExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntRemOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_INTEGER, "remainderUnsigned",+ MDESC_$INT_BINOP, false);+ case LongJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_LONG, "remainderUnsigned",+ MDESC_$LONG_BINOP, false);+ case MpIntJitType t -> TODO("MpInt");+ default -> throw new AssertionError();+ }+ // TODO: For MpInt case, we should use the outvar's size to cull operations.+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntRightOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntRightOpGen.javanew file mode 100644index 0000000000..7640a069e2--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntRightOpGen.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.pcode.emu.jit.gen.op;++import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.op.JitIntRightOp;++/**+ * The generator for a {@link JitIntRightOp int_right}.+ *+ * <p>+ * This uses the integer shift operator generator and simply invokes+ * {@link JitCompiledPassage#intRight(int, int)}, etc. depending on the types.+ */+public enum IntRightOpGen implements ShiftIntBinOpGen<JitIntRightOp> {+ /** The generator singleton */+ GEN;++ @Override+ public String methodName() {+ return "intRight";+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSBorrowOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSBorrowOpGen.javanew file mode 100644index 0000000000..f7b2d59283--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSBorrowOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntSBorrowOp;++/**+ * The generator for a {@link JitIntSBorrowOp int_sborrow}.+ *+ * <p>+ * This uses the binary operator generator and emits {@link #INVOKESTATIC} on+ * {@link JitCompiledPassage#sBorrowIntRaw(int, int)} or+ * {@link JitCompiledPassage#sBorrowLongRaw(long, long)} depending on the type. We must then emit a+ * shift and mask to extract the correct bit.+ */+public enum IntSBorrowOpGen implements BinOpGen<JitIntSBorrowOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntSBorrowOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformSExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntSBorrowOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformSExt(rType, lType, rv);+ switch (rType) {+ case IntJitType(int size) -> {+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "sBorrowIntRaw",+ MDESC_JIT_COMPILED_PASSAGE__S_CARRY_INT_RAW, true);+ rv.visitLdcInsn(size * Byte.SIZE - 1);+ rv.visitInsn(ISHR);+ // TODO: This mask may not be necessary+ rv.visitLdcInsn(1);+ rv.visitInsn(IAND);+ return IntJitType.I1;+ }+ case LongJitType(int size) -> {+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "sBorrowLongRaw",+ MDESC_JIT_COMPILED_PASSAGE__S_CARRY_LONG_RAW, true);+ rv.visitLdcInsn(size * Byte.SIZE - 1);+ rv.visitInsn(LSHR);+ rv.visitInsn(L2I);+ // TODO: This mask may not be necessary+ rv.visitLdcInsn(1);+ rv.visitInsn(IAND);+ return IntJitType.I1;+ }+ case MpIntJitType t -> {+ return TODO("MpInt");+ }+ default -> throw new AssertionError();+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSCarryOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSCarryOpGen.javanew file mode 100644index 0000000000..0743102b7c--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSCarryOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntSCarryOp;++/**+ * The generator for a {@link JitIntSCarryOp int_scarry}.+ *+ * <p>+ * This uses the binary operator generator and emits {@link #INVOKESTATIC} on+ * {@link JitCompiledPassage#sCarryIntRaw(int, int)} or+ * {@link JitCompiledPassage#sCarryLongRaw(long, long)} depending on the type. We must then emit a+ * shift and mask to extract the correct bit.+ */+public enum IntSCarryOpGen implements BinOpGen<JitIntSCarryOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntSCarryOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformSExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntSCarryOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformSExt(rType, lType, rv);+ switch (rType) {+ case IntJitType(int size) -> {+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "sCarryIntRaw",+ MDESC_JIT_COMPILED_PASSAGE__S_CARRY_INT_RAW, true);+ rv.visitLdcInsn(size * Byte.SIZE - 1);+ rv.visitInsn(ISHR);+ // TODO: This mask may not be necessary+ rv.visitLdcInsn(1);+ rv.visitInsn(IAND);+ return IntJitType.I1;+ }+ case LongJitType(int size) -> {+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "sCarryLongRaw",+ MDESC_JIT_COMPILED_PASSAGE__S_CARRY_LONG_RAW, true);+ rv.visitLdcInsn(size * Byte.SIZE - 1);+ rv.visitInsn(LSHR);+ rv.visitInsn(L2I);+ // TODO: This mask may not be necessary+ rv.visitLdcInsn(1);+ rv.visitInsn(IAND);+ return IntJitType.I1;+ }+ case MpIntJitType t -> {+ return TODO("MpInt");+ }+ default -> throw new AssertionError();+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSDivOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSDivOpGen.javanew file mode 100644index 0000000000..b40753592c--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSDivOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.IDIV;+import static org.objectweb.asm.Opcodes.LDIV;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntSDivOp;++/**+ * The generator for a {@link JitIntSDivOp int_sdiv}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #IDIV} or {@link #LDIV} depending+ * on the type.+ */+public enum IntSDivOpGen implements BinOpGen<JitIntSDivOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntSDivOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformSExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntSDivOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformSExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitInsn(IDIV);+ case LongJitType t -> rv.visitInsn(LDIV);+ case MpIntJitType t -> TODO("MpInt");+ default -> throw new AssertionError();+ }+ // TODO: For MpInt case, we should use the outvar's size to cull operations.+ return rType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSExtOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSExtOpGen.javanew file mode 100644index 0000000000..013eda3b16--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSExtOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntSExtOp;++/**+ * The generator for a {@link JitIntSExtOp int_sext}.+ *+ * <p>+ * We implement this using a left then signed-right shift. This uses the unary operator generator+ * and emits {@link #ISHL} and {@link #ISHR} or {@link #LSHL} and {@link #LSHR}, depending on type.+ * Additional type conversions may be emitted first. As a special case, sign extension from+ * {@link IntJitType#I4 int4} to {@link LongJitType#I8 int8} is implemented with by emitting only+ * {@link #I2L}.+ */+public enum IntSExtOpGen implements UnOpGen<JitIntSExtOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitIntSExtOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ JitType outType = op.type().resolve(gen.getTypeModel().typeOf(op.out()));++ if (uType == IntJitType.I4 && outType == LongJitType.I8) {+ rv.visitInsn(I2L);+ return outType;+ }++ TypeConversions.generate(gen, uType, outType, rv);+ switch (outType) {+ case IntJitType t -> {+ int shamt = Integer.SIZE - op.u().size() * Byte.SIZE;+ if (shamt != 0) {+ rv.visitLdcInsn(shamt);+ rv.visitInsn(ISHL);+ rv.visitLdcInsn(shamt);+ rv.visitInsn(ISHR);+ }+ }+ case LongJitType t -> {+ int shamt = Long.SIZE - op.u().size() * Byte.SIZE;+ if (shamt != 0) {+ rv.visitLdcInsn(shamt);+ rv.visitInsn(LSHL);+ rv.visitLdcInsn(shamt);+ rv.visitInsn(LSHR);+ }+ }+ case MpIntJitType t -> Unfinished.TODO("MpInt");+ default -> throw new AssertionError();+ }+ return outType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSLessEqualOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSLessEqualOpGen.javanew file mode 100644index 0000000000..7b2b6c6b7b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSLessEqualOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IFLE;+import static org.objectweb.asm.Opcodes.IF_ICMPLE;++import ghidra.pcode.emu.jit.op.JitIntSLessEqualOp;++/**+ * The generator for a {@link JitIntSLessEqualOp int_slessequal}.+ *+ * <p>+ * This uses the integer comparison operator generator and simply emits {@link #IF_ICMPLE} or+ * {@link #IFLE} depending on the type.+ */+public enum IntSLessEqualOpGen implements CompareIntBinOpGen<JitIntSLessEqualOp> {+ /** The generator singleton */+ GEN;++ @Override+ public boolean isSigned() {+ return true;+ }++ @Override+ public int icmpOpcode() {+ return IF_ICMPLE;+ }++ @Override+ public int ifOpcode() {+ return IFLE;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSLessOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSLessOpGen.javanew file mode 100644index 0000000000..ce190afe79--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSLessOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IFLT;+import static org.objectweb.asm.Opcodes.IF_ICMPLT;++import ghidra.pcode.emu.jit.op.JitIntSLessOp;++/**+ * The generator for a {@link JitIntSLessOp int_sless}.+ *+ * <p>+ * This uses the integer comparison operator generator and simply emits {@link #IF_ICMPLT} or+ * {@link #IFLT} depending on the type.+ */+public enum IntSLessOpGen implements CompareIntBinOpGen<JitIntSLessOp> {+ /** The generator singleton */+ GEN;++ @Override+ public boolean isSigned() {+ return true;+ }++ @Override+ public int icmpOpcode() {+ return IF_ICMPLT;+ }++ @Override+ public int ifOpcode() {+ return IFLT;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSRemOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSRemOpGen.javanew file mode 100644index 0000000000..1bd2bef6e8--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSRemOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IREM;+import static org.objectweb.asm.Opcodes.LREM;++import org.objectweb.asm.MethodVisitor;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntSRemOp;++/**+ * The generator for a {@link JitIntSRemOp int_srem}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #IREM} or {@link #LREM} depending+ * on the type.+ */+public enum IntSRemOpGen implements BinOpGen<JitIntSRemOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntSRemOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformSExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntSRemOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformSExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitInsn(IREM);+ case LongJitType t -> rv.visitInsn(LREM);+ case MpIntJitType t -> Unfinished.TODO("MpInt");+ default -> throw new AssertionError();+ }+ // TODO: For MpInt case, we should use the outvar's size to cull operations.+ return rType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSRightOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSRightOpGen.javanew file mode 100644index 0000000000..ffe78ec626--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSRightOpGen.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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntSRightOp;++/**+ * The generator for a {@link JitIntSRightOp int_sright}.+ *+ * <p>+ * This uses the integer shift operator generator and simply invokes+ * {@link JitCompiledPassage#intSRight(int, int)}, etc. depending on the types.+ */+public enum IntSRightOpGen implements ShiftIntBinOpGen<JitIntSRightOp> {+ /** The generator singleton */+ GEN;++ @Override+ public String methodName() {+ return "intSRight";+ }++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntSRightOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ TypeConversions.generateSExt(lType, rv);+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSubOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSubOpGen.javanew file mode 100644index 0000000000..d3433344f8--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntSubOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.*;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.JitIntSubOp;++/**+ * The generator for a {@link JitIntSubOp int_sub}.+ *+ * <p>+ * This uses the binary operator generator and simply emits {@link #ISUB} or {@link #LSUB} depending+ * on the type.+ *+ * <p>+ * NOTE: The multi-precision integer parts of this are a work in progress.+ */+public enum IntSubOpGen implements BinOpGen<JitIntSubOp> {+ /** The generator singleton */+ GEN;++ private void generateMpIntLegSub(JitCodeGenerator gen, int idx, boolean takesBorrow,+ boolean givesBorrow, MethodVisitor mv) {+ if (takesBorrow) {+ // [...,llegN:INT,olegN+1:LONG]+ mv.visitLdcInsn(32);+ mv.visitInsn(LSHR); // signed so that ADD effects subtraction+ // [...,lleg1...,borrowinN:LONG]+ mv.visitInsn(DUP2_X1);+ mv.visitInsn(POP2);+ // [...,borrowinN:LONG,llegN:INT]+ mv.visitInsn(I2L); // yes, signed+ // [...,borrowinN:LONG,llegN:LONG]+ mv.visitInsn(LADD); // Yes, add, because borrow is 0 or -1+ // [...,diffpartN:LONG]+ }+ else {+ // [...,legN:INT]+ TypeConversions.generateIntToLong(IntJitType.I4, LongJitType.I8, mv);+ // [...,diffpartN:LONG] (legN + 0)+ }+ mv.visitVarInsn(ILOAD, idx);+ // [...,diffpartN:LONG,rlegN:INT]+ TypeConversions.generateIntToLong(IntJitType.I4, LongJitType.I8, mv);+ // [...,diffpartN:LONG,rlegN:LONG]+ mv.visitInsn(LSUB);+ // [...,olegN:LONG]+ if (givesBorrow) {+ mv.visitInsn(DUP2);+ }+ // [...,(olegN:LONG),olegN:LONG]+ TypeConversions.generateLongToInt(LongJitType.I8, IntJitType.I4, mv);+ // [...,(olegN:LONG),olegN:INT]+ /** NB. The store will perform the masking */+ mv.visitVarInsn(ISTORE, idx);+ // [...,(olegN:LONG)]+ }++ private void generateMpIntSub(JitCodeGenerator gen, MpIntJitType type, MethodVisitor mv) {+ /**+ * The strategy is to allocate a temp local for each leg of the result. First, we'll pop the+ * right operand into the temp. Then, as we work with each leg of the left operand, we'll+ * execute the algorithm. Convert both right and left legs to a long and add them (along+ * with a possible carry in). Store the result back into the temp locals. Shift the leg+ * right 32 to get the carry out, then continue to the next leg up. The final carry out can+ * be dropped (overflow). The result legs are then pushed back to the stack.+ */+ // [lleg1,...,llegN,rleg1,rlegN] (N is least-significant leg)+ int legCount = type.legsAlloc(); // include partial+ int firstIndex = gen.getAllocationModel().nextFreeLocal();+ Label start = new Label();+ Label end = new Label();+ mv.visitLabel(start);+ for (int i = 0; i < legCount; i++) {+ mv.visitLocalVariable("result" + i, Type.getDescriptor(int.class), null, start, end,+ firstIndex + i);+ mv.visitVarInsn(ISTORE, firstIndex + i);+ // NOTE: More significant legs have higher indices (reverse of stack)+ }+ // [lleg1,...,llegN:INT]+ for (int i = 0; i < legCount; i++) {+ boolean isLast = i == legCount - 1;+ boolean takesCarry = i != 0; // not first+ generateMpIntLegSub(gen, firstIndex + i, takesCarry, !isLast, mv);+ }++ // Push it all back, in reverse order+ for (int i = 0; i < legCount; i++) {+ mv.visitVarInsn(ILOAD, firstIndex + legCount - i - 1);+ }+ mv.visitLabel(end);+ }++ @Override+ public JitType afterLeft(JitCodeGenerator gen, JitIntSubOp op, JitType lType, JitType rType,+ MethodVisitor rv) {+ return TypeConversions.forceUniformZExt(lType, rType, rv);+ }++ @Override+ public JitType generateBinOpRunCode(JitCodeGenerator gen, JitIntSubOp op, JitBlock block,+ JitType lType, JitType rType, MethodVisitor rv) {+ rType = TypeConversions.forceUniformZExt(rType, lType, rv);+ switch (rType) {+ case IntJitType t -> rv.visitInsn(ISUB);+ case LongJitType t -> rv.visitInsn(LSUB);+ case MpIntJitType t when t.size() == lType.size() -> generateMpIntSub(gen, t, rv);+ case MpIntJitType t -> TODO("MpInt of differing sizes");+ default -> throw new AssertionError();+ }+ return lType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntXorOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntXorOpGen.javanew file mode 100644index 0000000000..342d1d95c6--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntXorOpGen.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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.IXOR;+import static org.objectweb.asm.Opcodes.LXOR;++import ghidra.pcode.emu.jit.op.JitIntXorOp;++/**+ * The generator for a {@link JitIntXorOp int_xor}.+ *+ * <p>+ * This uses the bitwise binary operator and emits {@link #IXOR} or {@link #LXOR} depending on the+ * type.+ */+public enum IntXorOpGen implements BitwiseBinOpGen<JitIntXorOp> {+ /** The generator singleton */+ GEN;++ @Override+ public int intOpcode() {+ return IXOR;+ }++ @Override+ public int longOpcode() {+ return LXOR;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntZExtOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntZExtOpGen.javanew file mode 100644index 0000000000..49c8c0cf7f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/IntZExtOpGen.java@@ -0,0 +1,47 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.op.JitIntZExtOp;++/**+ * The generator for a {@link JitIntZExtOp int_zext}.+ *+ * <p>+ * This uses the unary operator generator and emits nothing extra. The unary generator template will+ * emit code to load the input operand, this emits nothing, and then the template emits code to+ * write the output operand, including the necessary type conversion. That type conversion performs+ * the zero extension.+ *+ * <p>+ * Note that this implementation is equivalent to {@link CopyOpGen}, except that differences in+ * operand sizes are expected.+ */+public enum IntZExtOpGen implements UnOpGen<JitIntZExtOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitIntZExtOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ return uType;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/LoadOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/LoadOpGen.javanew file mode 100644index 0000000000..388a5494eb--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/LoadOpGen.java@@ -0,0 +1,211 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;+import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.*;+import ghidra.pcode.emu.jit.op.JitLoadOp;+import ghidra.program.model.lang.Endian;++/**+ * The generator for a {@link JitLoadOp load}.+ *+ * <p>+ * These ops are currently presumed to be indirect memory accesses. <b>TODO</b>: If we fold+ * constants, we could convert some of these to direct.+ *+ * <p>+ * We request a field to pre-fetch the {@link JitBytesPcodeExecutorStateSpace space} and emit code+ * to load it onto the stack. We then emit code to load the offset onto the stack and convert it to+ * a JVM long, if necessary. The varnode size is loaded by emitting an {@link Opcodes#LDC ldc}, and+ * finally we emit an invocation of {@link JitBytesPcodeExecutorStateSpace#read(long, int)}. The+ * result is a byte array, so we finish by emitting the appropriate conversion and write the result+ * to the output operand.+ */+public enum LoadOpGen implements OpGen<JitLoadOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateInitCode(JitCodeGenerator gen, JitLoadOp op, MethodVisitor iv) {+ gen.requestFieldForSpaceIndirect(op.space());+ }++ private void generateConvMpIntRunCodeLegBE(int off, int size, MethodVisitor rv,+ boolean keepByteArr) {+ // [...,bytearr]+ if (keepByteArr) {+ rv.visitInsn(DUP);+ // [...,(bytearr),bytearr]+ }+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ IntReadGen.BE.chooseName(size), MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ // [...,(bytearr),legN]+ if (keepByteArr) {+ rv.visitInsn(SWAP);+ // [...,legN,(bytearr)]+ }+ }++ private void generateConvMpIntRunCodeLegLE(int off, int size, MethodVisitor rv,+ boolean keepByteArr) {+ // [...,bytearr]+ if (keepByteArr) {+ rv.visitInsn(DUP);+ // [...,(bytearr),bytearr]+ }+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ IntReadGen.LE.chooseName(size), MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ // [...,(bytearr),legN]+ if (keepByteArr) {+ rv.visitInsn(SWAP);+ // [...,legN,(bytearr)]+ }+ }++ private void generateConvIntRunCode(Endian endian, IntJitType type, MethodVisitor rv) {+ switch (endian) {+ case BIG -> generateConvMpIntRunCodeLegBE(0, type.size(), rv, false);+ case LITTLE -> generateConvMpIntRunCodeLegLE(0, type.size(), rv, false);+ }+ }++ static String chooseReadLongName(Endian endian, int size) {+ return switch (endian) {+ case BIG -> LongReadGen.BE.chooseName(size);+ case LITTLE -> LongReadGen.LE.chooseName(size);+ };+ }++ private void generateConvLongRunCode(Endian endian, LongJitType type, MethodVisitor rv) {+ // [...,bytearr]+ rv.visitLdcInsn(0);+ // [...,bytearr, offset=0]+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseReadLongName(endian, type.size()), MDESC_JIT_COMPILED_PASSAGE__READ_LONGX, true);+ // [...,value]+ }++ private void generateConvFloatRunCode(Endian endian, FloatJitType type, MethodVisitor rv) {+ // [...,bytearr]+ generateConvIntRunCode(endian, IntJitType.I4, rv);+ // [...,value:INT]+ TypeConversions.generateIntToFloat(IntJitType.I4, type, rv);+ // [...,value:FLOAT]+ }++ private void generateConvDoubleRunCode(Endian endian, DoubleJitType type, MethodVisitor rv) {+ // [...,bytearr]+ generateConvLongRunCode(endian, LongJitType.I8, rv);+ // [...,value:LONG]+ TypeConversions.generateLongToDouble(LongJitType.I8, type, rv);+ // [...,value:DOUBLE]+ }++ private void generateConvMpIntRunCodeBE(MpIntJitType type, MethodVisitor rv) {+ int countFull = type.legsWhole();+ int remSize = type.partialSize();++ int off = 0;+ if (remSize > 0) {+ // [...,bytearr]+ generateConvMpIntRunCodeLegBE(off, remSize, rv, true);+ // [...,legN,bytearr]+ off += remSize;+ }+ for (int i = 0; i < countFull; i++) {+ // [...,legN-1,bytearr]+ generateConvMpIntRunCodeLegBE(off, Integer.BYTES, rv, true);+ // [...,legN-1,legN,bytearr]+ off += Integer.BYTES;+ }+ // [...,leg1,...,legN,bytearr]+ rv.visitInsn(POP);+ // [...,leg1,...,legN]+ }++ private void generateConvMpIntRunCodeLE(MpIntJitType type, MethodVisitor rv) {+ int countFull = type.legsWhole();+ int remSize = type.partialSize();++ int off = type.size();+ if (remSize > 0) {+ off -= remSize;+ // [...,bytearr]+ generateConvMpIntRunCodeLegLE(off, remSize, rv, true);+ // [...,legN,bytearr]+ }+ for (int i = 0; i < countFull; i++) {+ off -= Integer.BYTES;+ // [...,legN-1,bytearr]+ generateConvMpIntRunCodeLegLE(off, Integer.BYTES, rv, true);+ // [...,legN-1,legN,bytearr]+ }+ // [...,leg1,...,legN,bytearr]+ rv.visitInsn(POP);+ // [...,leg1,...,legN]+ }++ private void generateConvMpIntRunCode(Endian endian, MpIntJitType type,+ MethodVisitor rv) {+ switch (endian) {+ case BIG -> generateConvMpIntRunCodeBE(type, rv);+ case LITTLE -> generateConvMpIntRunCodeLE(type, rv);+ }+ }++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitLoadOp op, JitBlock block,+ MethodVisitor rv) {+ // [...]+ gen.requestFieldForSpaceIndirect(op.space()).generateLoadCode(gen, rv);+ // [...,space]+ JitType offsetType = gen.generateValReadCode(op.offset(), op.offsetType());+ // [...,space,offset:?INT/LONG]+ TypeConversions.generateToLong(offsetType, LongJitType.I8, rv);+ // [...,space,offset:LONG]+ rv.visitLdcInsn(op.out().size());+ // [...,space,offset,size]+ rv.visitMethodInsn(INVOKEVIRTUAL, NAME_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE, "read",+ MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE__READ, false);+ // [...,bytearr]+ Endian endian = gen.getAnalysisContext().getEndian();+ JitType outType = gen.getTypeModel().typeOf(op.out());+ switch (outType) {+ case IntJitType iType -> generateConvIntRunCode(endian, iType, rv);+ case LongJitType lType -> generateConvLongRunCode(endian, lType, rv);+ case FloatJitType fType -> generateConvFloatRunCode(endian, fType, rv);+ case DoubleJitType dType -> generateConvDoubleRunCode(endian, dType, rv);+ case MpIntJitType mpType -> generateConvMpIntRunCode(endian, mpType, rv);+ default -> throw new AssertionError();+ }+ // [...,value]+ gen.generateVarWriteCode(op.out(), outType);+ // [...]+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/LzCountOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/LzCountOpGen.javanew file mode 100644index 0000000000..7fcf009d09--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/LzCountOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.INVOKESTATIC;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitLzCountOp;++/**+ * The generator for a {@link JitLzCountOp lzcount}.+ *+ * <p>+ * This uses the unary operator generator and emits an invocation of+ * {@link Integer#numberOfLeadingZeros(int)} or {@link Long#numberOfLeadingZeros(long)}, depending+ * on the type.+ */+public enum LzCountOpGen implements UnOpGen<JitLzCountOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitLzCountOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case IntJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_INTEGER,+ "numberOfLeadingZeros", MDESC_INTEGER__NUMBER_OF_LEADING_ZEROS, false);+ case LongJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_LONG,+ "numberOfLeadingZeros", MDESC_LONG__NUMBER_OF_LEADING_ZEROS, false);+ case MpIntJitType t -> TODO("MpInt");+ default -> throw new AssertionError();+ }+ return IntJitType.I4;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/NopOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/NopOpGen.javanew file mode 100644index 0000000000..ff1412f474--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/NopOpGen.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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitOp;++/**+ * The generator for a {@link JitNopOp nop}.+ *+ * <p>+ * We emit nothing.+ */+public enum NopOpGen implements OpGen<JitOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitOp op, JitBlock block, MethodVisitor rv) {+ // NOP+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/OpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/OpGen.javanew file mode 100644index 0000000000..47ff63bdff--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/OpGen.java@@ -0,0 +1,593 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;+import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.gen.var.VarGen;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.*;+import ghidra.pcode.exec.PcodeExecutor;+import ghidra.pcode.exec.PcodeUseropLibrary;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The bytecode generator for a specific p-code op+ *+ * <p>+ * The {@link JitCodeGenerator} selects the correct generator for each {@link PcodeOp} using+ * {@link JitDataFlowModel#getJitOp(PcodeOp)} and {@link #lookup(JitOp)}. The following table lists+ * each p-code op, its use-def class, its generator class, and a brief strategy for its bytecode+ * implementation.+ *+ * <p>+ * <table border="1">+ * <tr>+ * <th>P-code Op</th>+ * <th>Use-Def Type</th>+ * <th>Generator Type</th>+ * <th>Bytecodes / Methods</th>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Misc Data</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#UNIMPLEMENTED unimplemented}</td>+ * <td>{@link JitUnimplementedOp}</td>+ * <td>{@link UnimplementedOpGen}</td>+ * <td>{@link Opcodes#NEW new}, {@link Opcodes#ATHROW athrow}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#COPY copy}</td>+ * <td>{@link JitCopyOp}</td>+ * <td>{@link CopyOpGen}</td>+ * <td>none; defers to {@link VarGen}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#LOAD load}</td>+ * <td>{@link JitLoadOp}</td>+ * <td>{@link LoadOpGen}</td>+ * <td>{@link JitCompiledPassage#readIntLE4(byte[], int)}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#STORE store}</td>+ * <td>{@link JitStoreOp}</td>+ * <td>{@link StoreOpGen}</td>+ * <td>{@link JitCompiledPassage#writeIntLE4(int, byte[], int)}, etc.</td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Control Flow</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#BRANCH branch},<br/>+ * {@link PcodeOp#CALL call}</td>+ * <td>{@link JitBranchOp}</td>+ * <td>{@link BranchOpGen}</td>+ * <td>{@link Opcodes#GOTO goto}, {@link Opcodes#ARETURN areturn}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#CBRANCH cbranch}</td>+ * <td>{@link JitCBranchOp}</td>+ * <td>{@link CBranchOpGen}</td>+ * <td>{@link Opcodes#IFEQ ifeq}, {@link Opcodes#IFEQ ifne}, {@link Opcodes#GOTO goto},+ * {@link Opcodes#ARETURN areturn}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#BRANCHIND branchind},<br/>+ * {@link PcodeOp#CALLIND callind},<br/>+ * {@link PcodeOp#RETURN return}</td>+ * <td>{@link JitBranchIndOp}</td>+ * <td>{@link BranchIndOpGen}</td>+ * <td>{@link Opcodes#ARETURN areturn}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#CALLOTHER callother}</td>+ * <td>{@link JitCallOtherOp},<br/>+ * {@link JitCallOtherDefOp},<br/>+ * {@link JitCallOtherMissingOp},<br/>+ * {@link JitNopOp}</td>+ * <td>{@link CallOtherOpGen},<br/>+ * {@link CallOtherMissingOpGen},<br/>+ * {@link NopOpGen}</td>+ * <td>See {@link JitDataFlowUseropLibrary}:+ * <ul>+ * <li><b>Standard</b>:+ * {@link PcodeUseropDefinition#execute(PcodeExecutor, PcodeUseropLibrary, PcodeOp)}</li>+ * <li><b>Inlining</b>: userop's p-code</li>+ * <li><b>Direct</b>: {@link Opcodes#INVOKEVIRTUAL invokevirtual}</li>+ * <li><b>Missing</b>: {@link Opcodes#NEW new}, {@link Opcodes#ATHROW athrow}</li>+ * </ul>+ * </td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Integer Comparison</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_EQUAL int_equal}</td>+ * <td>{@link JitIntEqualOp}</td>+ * <td>{@link IntEqualOpGen}</td>+ * <td>{@link Opcodes#IF_ICMPEQ if_icmpeq}, {@link Opcodes#IFEQ ifeq}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_NOTEQUAL int_notequal}</td>+ * <td>{@link JitIntNotEqualOp}</td>+ * <td>{@link IntNotEqualOpGen}</td>+ * <td>{@link Opcodes#IF_ICMPNE if_icmpne}, {@link Opcodes#IFNE ifne}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SLESS int_sless}</td>+ * <td>{@link JitIntSLessOp}</td>+ * <td>{@link IntSLessOpGen}</td>+ * <td>{@link Opcodes#IF_ICMPLT if_icmplt}, {@link Opcodes#IFLT iflt}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SLESSEQUAL int_slessequal}</td>+ * <td>{@link JitIntSLessEqualOp}</td>+ * <td>{@link IntSLessEqualOpGen}</td>+ * <td>{@link Opcodes#IF_ICMPLE if_icmple}, {@link Opcodes#IFLE ifle}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_LESS int_less}</td>+ * <td>{@link JitIntLessOp}</td>+ * <td>{@link IntLessOpGen}</td>+ * <td>{@link Integer#compareUnsigned(int, int)}, {@link Opcodes#IFLT iflt}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_LESSEQUAL int_lessequal}</td>+ * <td>{@link JitIntLessEqualOp}</td>+ * <td>{@link IntLessEqualOpGen}</td>+ * <td>{@link Integer#compareUnsigned(int, int)}, {@link Opcodes#IFLE ifle}, etc.</td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Integer Arithmetic</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_ZEXT int_zext}</td>+ * <td>{@link JitIntZExtOp}</td>+ * <td>{@link IntZExtOpGen}</td>+ * <td>none; defers to {@link VarGen} and {@link TypeConversions}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SEXT int_sext}</td>+ * <td>{@link JitIntSExtOp}</td>+ * <td>{@link IntSExtOpGen}</td>+ * <td>{@link Opcodes#ISHL ishl}, {@link Opcodes#ISHR ishr}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_ADD int_add}</td>+ * <td>{@link JitIntAddOp}</td>+ * <td>{@link IntAddOpGen}</td>+ * <td>{@link Opcodes#IADD iadd}, {@link Opcodes#LADD ladd}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SUB int_sub}</td>+ * <td>{@link JitIntSubOp}</td>+ * <td>{@link IntSubOpGen}</td>+ * <td>{@link Opcodes#ISUB isub}, {@link Opcodes#LSUB lsub}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_CARRY int_carry}</td>+ * <td>{@link JitIntCarryOp}</td>+ * <td>{@link IntCarryOpGen}</td>+ * <td>{@link Integer#compareUnsigned(int, int)}, {@link Opcodes#IADD iadd}, {@link Opcodes#ISHR+ * ishr}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SCARRY int_scarry}</td>+ * <td>{@link JitIntSCarryOp}</td>+ * <td>{@link IntSCarryOpGen}</td>+ * <td>{@link JitCompiledPassage#sCarryIntRaw(int, int)}, {@link Opcodes#ISHR ishr}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SBORROW int_sborrow}</td>+ * <td>{@link JitIntSBorrowOp}</td>+ * <td>{@link IntSBorrowOpGen}</td>+ * <td>{@link JitCompiledPassage#sBorrowIntRaw(int, int)}, {@link Opcodes#ISHR ishr}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_2COMP int_2comp}</td>+ * <td>{@link JitInt2CompOp}</td>+ * <td>{@link Int2CompOpGen}</td>+ * <td>{@link Opcodes#INEG ineg}, {@link Opcodes#LNEG lneg}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_NEGATE int_negate}</td>+ * <td>{@link JitIntNegateOp}</td>+ * <td>{@link IntNegateOpGen}</td>+ * <td>{@link Opcodes#ICONST_M1 iconst_m1}, {@link Opcodes#IXOR ixor}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_XOR int_xor}</td>+ * <td>{@link JitIntXorOp}</td>+ * <td>{@link IntXorOpGen}</td>+ * <td>{@link Opcodes#IXOR ixor}, {@link Opcodes#LXOR lxor}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_AND int_and}</td>+ * <td>{@link JitIntAndOp}</td>+ * <td>{@link IntAndOpGen}</td>+ * <td>{@link Opcodes#IAND iand}, {@link Opcodes#LAND land}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_OR int_or}</td>+ * <td>{@link JitIntOrOp}</td>+ * <td>{@link IntOrOpGen}</td>+ * <td>{@link Opcodes#IOR ior}, {@link Opcodes#LOR lor}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_LEFT int_left}</td>+ * <td>{@link JitIntLeftOp}</td>+ * <td>{@link IntLeftOpGen}</td>+ * <td>{@link JitCompiledPassage#intLeft(int, int)}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_RIGHT int_right}</td>+ * <td>{@link JitIntRightOp}</td>+ * <td>{@link IntRightOpGen}</td>+ * <td>{@link JitCompiledPassage#intRight(int, int)}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SRIGHT int_sright}</td>+ * <td>{@link JitIntSRightOp}</td>+ * <td>{@link IntSRightOpGen}</td>+ * <td>{@link JitCompiledPassage#intSRight(int, int)}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_MULT int_mult}</td>+ * <td>{@link JitIntMultOp}</td>+ * <td>{@link IntMultOpGen}</td>+ * <td>{@link Opcodes#IMUL imul}, {@link Opcodes#LMUL lmul}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_DIV int_div}</td>+ * <td>{@link JitIntDivOp}</td>+ * <td>{@link IntDivOpGen}</td>+ * <td>{@link Integer#divideUnsigned(int, int)}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SDIV int_sdiv}</td>+ * <td>{@link JitIntSDivOp}</td>+ * <td>{@link IntSDivOpGen}</td>+ * <td>{@link Opcodes#IDIV idiv}, {@link Opcodes#LDIV ldiv}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_REM int_rem}</td>+ * <td>{@link JitIntRemOp}</td>+ * <td>{@link IntRemOpGen}</td>+ * <td>{@link Integer#remainderUnsigned(int, int)}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#INT_SREM int_srem}</td>+ * <td>{@link JitIntSRemOp}</td>+ * <td>{@link IntSRemOpGen}</td>+ * <td>{@link Opcodes#IREM irem}, {@link Opcodes#LREM lrem}</td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Boolean Logic</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#BOOL_NEGATE bool_negate}</td>+ * <td>{@link JitBoolNegateOp}</td>+ * <td>{@link BoolNegateOpGen}</td>+ * <td>Conditional jumps to {@link Opcodes#LDC ldc} 0 or 1</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#BOOL_XOR bool_xor}</td>+ * <td>{@link JitBoolXorOp}</td>+ * <td>{@link BoolXorOpGen}</td>+ * <td>Conditional jumps to {@link Opcodes#LDC ldc} 0 or 1</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#BOOL_AND bool_and}</td>+ * <td>{@link JitBoolAndOp}</td>+ * <td>{@link BoolAndOpGen}</td>+ * <td>Conditional jumps to {@link Opcodes#LDC ldc} 0 or 1</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#BOOL_OR bool_or}</td>+ * <td>{@link JitBoolOrOp}</td>+ * <td>{@link BoolOrOpGen}</td>+ * <td>Conditional jumps to {@link Opcodes#LDC ldc} 0 or 1</td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Float Comparison</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_EQUAL float_equal}</td>+ * <td>{@link JitFloatEqualOp}</td>+ * <td>{@link FloatEqualOpGen}</td>+ * <td>{@link Opcodes#FCMPL fcmpl}, {@link Opcodes#FCMPL dcmpl}, {@link Opcodes#IFNE ifeq}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_NOTEQUAL float_notequal}</td>+ * <td>{@link JitFloatNotEqualOp}</td>+ * <td>{@link FloatNotEqualOpGen}</td>+ * <td>{@link Opcodes#FCMPL fcmpl}, {@link Opcodes#FCMPL dcmpl}, {@link Opcodes#IFEQ ifne}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_LESS float_less}</td>+ * <td>{@link JitFloatLessOp}</td>+ * <td>{@link FloatLessOpGen}</td>+ * <td>{@link Opcodes#FCMPG fcmpg}, {@link Opcodes#FCMPL dcmpg}, {@link Opcodes#IFGE iflt}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_LESSEQUAL float_lessequal}</td>+ * <td>{@link JitFloatLessEqualOp}</td>+ * <td>{@link FloatLessEqualOpGen}</td>+ * <td>{@link Opcodes#FCMPG fcmpg}, {@link Opcodes#FCMPL dcmpg}, {@link Opcodes#IFGT ifle}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_NAN float_nan}</td>+ * <td>{@link JitFloatNaNOp}</td>+ * <td>{@link FloatNaNOpGen}</td>+ * <td>{@link Float#isNaN(float)}, {@link Double#isNaN(double)}</td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Float Arithmetic</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_ADD float_add}</td>+ * <td>{@link JitFloatAddOp}</td>+ * <td>{@link FloatAddOpGen}</td>+ * <td>{@link Opcodes#FADD fadd}, {@link Opcodes#DADD dadd}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_DIV float_div}</td>+ * <td>{@link JitFloatDivOp}</td>+ * <td>{@link FloatDivOpGen}</td>+ * <td>{@link Opcodes#FDIV fdiv}, {@link Opcodes#DDIV ddiv}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_MULT float_mult}</td>+ * <td>{@link JitFloatMultOp}</td>+ * <td>{@link FloatMultOpGen}</td>+ * <td>{@link Opcodes#FMUL fmul}, {@link Opcodes#DMUL dmul}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_SUB float_sub}</td>+ * <td>{@link JitFloatSubOp}</td>+ * <td>{@link FloatSubOpGen}</td>+ * <td>{@link Opcodes#FSUB fsub}, {@link Opcodes#DSUB dsub}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_NEG float_neg}</td>+ * <td>{@link JitFloatNegOp}</td>+ * <td>{@link FloatNegOpGen}</td>+ * <td>{@link Opcodes#FNEG fneg}, {@link Opcodes#DNEG dneg}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_ABS float_abs}</td>+ * <td>{@link JitFloatAbsOp}</td>+ * <td>{@link FloatAbsOpGen}</td>+ * <td>{@link Math#abs(float)}, {@link Math#abs(double)}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_SQRT float_sqrt}</td>+ * <td>{@link JitFloatSqrtOp}</td>+ * <td>{@link FloatSqrtOpGen}</td>+ * <td>{@link Math#sqrt(double)}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_INT2FLOAT float_int2float}</td>+ * <td>{@link JitFloatInt2FloatOp}</td>+ * <td>{@link FloatInt2FloatOpGen}</td>+ * <td>{@link Opcodes#I2F i2f}, {@link Opcodes#I2D i2d}, {@link Opcodes#L2F l2f}, {@link Opcodes#L2D+ * l2d}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_FLOAT2FLOAT float_float2float}</td>+ * <td>{@link JitFloatFloat2FloatOp}</td>+ * <td>{@link FloatFloat2FloatOpGen}</td>+ * <td>{@link Opcodes#F2D f2d}, {@link Opcodes#D2F d2f}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_TRUNC float_trunc}</td>+ * <td>{@link JitFloatTruncOp}</td>+ * <td>{@link FloatTruncOpGen}</td>+ * <td>{@link Opcodes#F2I f2i}, {@link Opcodes#F2L f2l}, {@link Opcodes#D2I d2i}, {@link Opcodes#D2L+ * d2l}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_CEIL float_ceil}</td>+ * <td>{@link JitFloatCeilOp}</td>+ * <td>{@link FloatCeilOpGen}</td>+ * <td>{@link Math#ceil(double)}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_FLOOR float_floor}</td>+ * <td>{@link JitFloatFloorOp}</td>+ * <td>{@link FloatFloorOpGen}</td>+ * <td>{@link Math#floor(double)}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#FLOAT_ROUND float_round}</td>+ * <td>{@link JitFloatRoundOp}</td>+ * <td>{@link FloatRoundOpGen}</td>+ * <td>+0.5 then {@link Math#floor(double)}</td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Miscellaneous</em></td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#SUBPIECE subpiece}</td>+ * <td>{@link JitSubPieceOp}</td>+ * <td>{@link SubPieceOpGen}</td>+ * <td>{@link Opcodes#IUSHR iushr}, {@link Opcodes#LUSHR lushr}</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#POPCOUNT popcount}</td>+ * <td>{@link JitPopCountOp}</td>+ * <td>{@link PopCountOpGen}</td>+ * <td>{@link Integer#bitCount(int)}, etc.</td>+ * </tr>+ * <tr>+ * <td>{@link PcodeOp#LZCOUNT lzcount}</td>+ * <td>{@link JitLzCountOp}</td>+ * <td>{@link LzCountOpGen}</td>+ * <td>{@link Integer#numberOfLeadingZeros(int)}, etc.</td>+ * </tr>+ * <tr>+ * <td colspan="4"><em>Synthetic</em></td>+ * </tr>+ * <tr>+ * <td>(none)</td>+ * <td>{@link JitCatenateOp}</td>+ * <td>{@link CatenateOpGen}</td>+ * </tr>+ * <tr>+ * <td>(none)</td>+ * <td>{@link JitSynthSubPieceOp}</td>+ * <td>{@link SynthSubPieceOpGen}</td>+ * </tr>+ * <tr>+ * <td>(none)</td>+ * <td>{@link JitPhiOp}</td>+ * <td>{@link PhiOpGen}</td>+ * </tr>+ * </table>+ *+ * <p>+ * There are other p-code ops. Some are only used in "high" p-code, and so we need not implement+ * them here. Others are used in abstract virtual machines, e.g., {@link PcodeOp#NEW} or are just+ * not yet implemented, e.g., {@link PcodeOp#SEGMENTOP}.+ *+ * <p>+ * The mapping from {@link PcodeOp} opcode to {@link JitOp} is done in, e.g.,+ * {@link JitOp#binOp(PcodeOp, JitOutVar, JitVal, JitVal)}, and the mapping from {@link JitOp} to+ * {@link OpGen} is done in {@link #lookup(JitOp)}.+ *+ * <p>+ * The synthetic use-def nodes do not correspond to any p-code op. They are synthesized based on+ * access patterns to the {@link JitDataFlowState}. Their generators do not emit any bytecode. See+ * {@link JitVarScopeModel} regarding coalescing and allocating variables.+ *+ * @param <T> the class of p-code op node in the use-def graph+ */+public interface OpGen<T extends JitOp> {+ /**+ * Lookup the generator for a given p-code op use-def node+ *+ * @param <T> the class of the op+ * @param op the {@link JitOp} whose generator to look up+ * @return the generator+ */+ @SuppressWarnings("unchecked")+ static <T extends JitOp> OpGen<T> lookup(T op) {+ return (OpGen<T>) switch (op) {+ case JitBoolAndOp andOp -> BoolAndOpGen.GEN;+ case JitBoolNegateOp negOp -> BoolNegateOpGen.GEN;+ case JitBoolOrOp andOp -> BoolOrOpGen.GEN;+ case JitBoolXorOp andOp -> BoolXorOpGen.GEN;+ case JitBranchIndOp branchIndOp -> BranchIndOpGen.GEN;+ case JitBranchOp branchOp -> BranchOpGen.GEN;+ case JitCallOtherOp callOtherOp -> CallOtherOpGen.GEN;+ case JitCallOtherDefOp callOtherOp -> CallOtherOpGen.GEN;+ case JitCallOtherMissingOp callOtherOp -> CallOtherMissingOpGen.GEN;+ case JitCatenateOp catenateOp -> CatenateOpGen.GEN;+ case JitCBranchOp cBranchOp -> CBranchOpGen.GEN;+ case JitCopyOp copyOp -> CopyOpGen.GEN;+ case JitFloatAbsOp absOp -> FloatAbsOpGen.GEN;+ case JitFloatAddOp addOp -> FloatAddOpGen.GEN;+ case JitFloatCeilOp ceilOp -> FloatCeilOpGen.GEN;+ case JitFloatDivOp divOp -> FloatDivOpGen.GEN;+ case JitFloatEqualOp eqOp -> FloatEqualOpGen.GEN;+ case JitFloatFloat2FloatOp f2fOp -> FloatFloat2FloatOpGen.GEN;+ case JitFloatFloorOp floorOp -> FloatFloorOpGen.GEN;+ case JitFloatInt2FloatOp int2FloatOp -> FloatInt2FloatOpGen.GEN;+ case JitFloatLessEqualOp leqOp -> FloatLessEqualOpGen.GEN;+ case JitFloatLessOp lessOp -> FloatLessOpGen.GEN;+ case JitFloatMultOp multOp -> FloatMultOpGen.GEN;+ case JitFloatNaNOp nanOp -> FloatNaNOpGen.GEN;+ case JitFloatNegOp negOp -> FloatNegOpGen.GEN;+ case JitFloatNotEqualOp neqOp -> FloatNotEqualOpGen.GEN;+ case JitFloatRoundOp roundOp -> FloatRoundOpGen.GEN;+ case JitFloatSqrtOp sqrtOp -> FloatSqrtOpGen.GEN;+ case JitFloatSubOp subOp -> FloatSubOpGen.GEN;+ case JitFloatTruncOp truccOp -> FloatTruncOpGen.GEN;+ case JitInt2CompOp twoCompOp -> Int2CompOpGen.GEN;+ case JitIntAddOp addOp -> IntAddOpGen.GEN;+ case JitIntAndOp andOp -> IntAndOpGen.GEN;+ case JitIntCarryOp carryOp -> IntCarryOpGen.GEN;+ case JitIntDivOp divOp -> IntDivOpGen.GEN;+ case JitIntEqualOp eqOp -> IntEqualOpGen.GEN;+ case JitIntNegateOp negOp -> IntNegateOpGen.GEN;+ case JitIntLeftOp leftOp -> IntLeftOpGen.GEN;+ case JitIntLessEqualOp leqOp -> IntLessEqualOpGen.GEN;+ case JitIntLessOp lessOp -> IntLessOpGen.GEN;+ case JitIntMultOp multOp -> IntMultOpGen.GEN;+ case JitIntNotEqualOp neqOp -> IntNotEqualOpGen.GEN;+ case JitIntOrOp orOp -> IntOrOpGen.GEN;+ case JitIntRemOp remOp -> IntRemOpGen.GEN;+ case JitIntRightOp rightOp -> IntRightOpGen.GEN;+ case JitIntSBorrowOp sborrowOp -> IntSBorrowOpGen.GEN;+ case JitIntSCarryOp scarryOp -> IntSCarryOpGen.GEN;+ case JitIntSExtOp sExtOp -> IntSExtOpGen.GEN;+ case JitIntSLessEqualOp sleqOp -> IntSLessEqualOpGen.GEN;+ case JitIntSLessOp sleqOp -> IntSLessOpGen.GEN;+ case JitIntSDivOp sdivOp -> IntSDivOpGen.GEN;+ case JitIntSRemOp sremOp -> IntSRemOpGen.GEN;+ case JitIntSRightOp srightOp -> IntSRightOpGen.GEN;+ case JitIntSubOp subOp -> IntSubOpGen.GEN;+ case JitIntXorOp xorOp -> IntXorOpGen.GEN;+ case JitIntZExtOp sExtOp -> IntZExtOpGen.GEN;+ case JitLoadOp loadOp -> LoadOpGen.GEN;+ case JitLzCountOp lzCountOp -> LzCountOpGen.GEN;+ case JitPhiOp phiOp -> PhiOpGen.GEN;+ case JitPopCountOp popCountOp -> PopCountOpGen.GEN;+ case JitNopOp nopOp -> NopOpGen.GEN;+ case JitStoreOp storeOp -> StoreOpGen.GEN;+ case JitSubPieceOp spOp -> SubPieceOpGen.GEN;+ case JitSynthSubPieceOp subPieceOp -> SynthSubPieceOpGen.GEN;+ case JitUnimplementedOp unimplOp -> UnimplementedOpGen.GEN;+ default -> throw new AssertionError("Unrecognized op: " + op);+ };+ }++ /**+ * Emit bytecode into the class constructor.+ *+ * @param gen the code generator+ * @param op the p-code op (use-def node) to translate+ * @param iv the visitor for the class constructor+ */+ default void generateInitCode(JitCodeGenerator gen, T op, MethodVisitor iv) {+ }++ /**+ * Emit bytecode into the {@link JitCompiledPassage#run(int) run} method.+ *+ * <p>+ * This method must emit the code needed to load any input operands, convert them to the+ * appropriate type, perform the actual operation, and then if applicable, store the output+ * operand. The implementations should delegate to+ * {@link JitCodeGenerator#generateValReadCode(JitVal, JitTypeBehavior)},+ * {@link JitCodeGenerator#generateVarWriteCode(JitVar, JitType)}, and {@link TypeConversions}+ * appropriately.+ *+ * @param gen the code generator+ * @param op the p-code op (use-def node) to translate+ * @param block the basic block containing the p-code op+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method.+ */+ void generateRunCode(JitCodeGenerator gen, T op, JitBlock block, MethodVisitor rv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/PhiOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/PhiOpGen.javanew file mode 100644index 0000000000..9384db2bec--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/PhiOpGen.java@@ -0,0 +1,44 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.analysis.JitVarScopeModel;+import ghidra.pcode.emu.jit.op.JitPhiOp;++/**+ * The generator for a {@link JitPhiOp phi}.+ *+ * <p>+ * We emit nothing. This generator ought not to be invoked, anyway, but things may change. In the+ * meantime, the design is that we allocate a JVM local per varnode. Since phi nodes are meant to+ * track possible definitions of the <em>same</em> varnode, there is no need to a phi node to emit+ * any code. The value, whichever option it happens to be, is already in its local variable.+ *+ * @see JitVarScopeModel+ */+public enum PhiOpGen implements OpGen<JitPhiOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitPhiOp op, JitBlock block,+ MethodVisitor rv) {+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/PopCountOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/PopCountOpGen.javanew file mode 100644index 0000000000..01bd758f66--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/PopCountOpGen.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.pcode.emu.jit.gen.op;++import static ghidra.lifecycle.Unfinished.TODO;+import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.INVOKESTATIC;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitPopCountOp;++/**+ * The generator for a {@link JitPopCountOp popcount}.+ *+ * <p>+ * This uses the unary operator generator and emits an invocation of {@link Integer#bitCount(int)}+ * or {@link Long#bitCount(long)}, depending on the type.+ */+public enum PopCountOpGen implements UnOpGen<JitPopCountOp> {+ /** The generator singleton */+ GEN;++ @Override+ public JitType generateUnOpRunCode(JitCodeGenerator gen, JitPopCountOp op, JitBlock block,+ JitType uType, MethodVisitor rv) {+ switch (uType) {+ case IntJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_INTEGER, "bitCount",+ MDESC_INTEGER__BIT_COUNT, false);+ case LongJitType t -> rv.visitMethodInsn(INVOKESTATIC, NAME_LONG, "bitCount",+ MDESC_LONG__BIT_COUNT, false);+ case MpIntJitType t -> TODO("MpInt");+ default -> throw new AssertionError();+ }+ return IntJitType.I4;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/ShiftIntBinOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/ShiftIntBinOpGen.javanew file mode 100644index 0000000000..9de81c8811--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/ShiftIntBinOpGen.java@@ -0,0 +1,75 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.INVOKESTATIC;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.IntJitType;+import ghidra.pcode.emu.jit.analysis.JitType.LongJitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.op.JitIntBinOp;++/**+ * An extension for integer shift operators+ *+ * <p>+ * This is just going to invoke one of the {@link JitCompiledPassage#intLeft(int, int)},+ * {@link JitCompiledPassage#intRight(int, int)}, {@link JitCompiledPassage#intSRight(int, int)},+ * etc. methods, depending on the operand types.+ *+ * @param <T> the class of p-code op node in the use-def graph+ */+public interface ShiftIntBinOpGen<T extends JitIntBinOp> extends BinOpGen<T> {+ /**+ * The name of the static method in {@link JitCompiledPassage} to invoke+ *+ * @return the name+ */+ String methodName();++ /**+ * {@inheritDoc}+ *+ * <p>+ * This reduces the implementation to just the name of the method to invoke. This will select+ * the JVM signature of the method based on the p-code operand types.+ */+ @Override+ default JitType generateBinOpRunCode(JitCodeGenerator gen, T op, JitBlock block, JitType lType,+ JitType rType, MethodVisitor rv) {+ String mdesc = switch (lType) {+ case IntJitType lt -> switch (rType) {+ case IntJitType rt -> MDESC_$SHIFT_II;+ case LongJitType rt -> MDESC_$SHIFT_IJ;+ default -> throw new AssertionError();+ };+ case LongJitType lt -> switch (rType) {+ case IntJitType rt -> MDESC_$SHIFT_JI;+ case LongJitType rt -> MDESC_$SHIFT_JJ;+ default -> throw new AssertionError();+ };+ default -> throw new AssertionError();+ };+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, methodName(), mdesc, true);+ return lType.ext();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/StoreOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/StoreOpGen.javanew file mode 100644index 0000000000..3ed1402346--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/StoreOpGen.java@@ -0,0 +1,217 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;+import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorStatePiece.JitBytesPcodeExecutorStateSpace;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.*;+import ghidra.pcode.emu.jit.op.JitStoreOp;+import ghidra.program.model.lang.Endian;++/**+ * The generator for a {@link JitStoreOp store}.+ *+ * <p>+ * These ops are currently presumed to be indirect memory accesses. <b>TODO</b>: If we fold+ * constants, we could convert some of these to direct.+ *+ * <p>+ * We request a field to pre-fetch the {@link JitBytesPcodeExecutorStateSpace space} and emit code+ * to load it onto the stack. We then emit code to load the offset onto the stack and convert it to+ * a JVM long, if necessary. The varnode size is loaded by emitting an {@link Opcodes#LDC ldc}. We+ * must now emit code to load the value and convert it to a byte array. The conversion depends on+ * the type of the value. Finally, we emit an invocation of+ * {@link JitBytesPcodeExecutorStateSpace#write(long, byte[], int, int)}.+ */+public enum StoreOpGen implements OpGen<JitStoreOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateInitCode(JitCodeGenerator gen, JitStoreOp op, MethodVisitor iv) {+ gen.requestFieldForSpaceIndirect(op.space());+ }++ private void generateConvMpIntRunCodeLegBE(int off, int size, MethodVisitor rv) {+ // [...,legN,bytearr]+ rv.visitInsn(DUP_X1);+ // [...,bytearr,legN,bytearr]+ rv.visitLdcInsn(off);+ // [...,bytearr,legN,bytearr,off]+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ IntWriteGen.BE.chooseName(size), MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);+ // [...,bytearr]+ }++ private void generateConvMpIntRunCodeLegLE(int off, int size, MethodVisitor rv) {+ // [...,legN,bytearr]+ rv.visitInsn(DUP_X1);+ // [...,bytearr,legN,bytearr]+ rv.visitLdcInsn(off);+ // [...,bytearr,legN,bytearr,off]+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ IntWriteGen.LE.chooseName(size), MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);+ // [...,bytearr]+ }++ private void generateConvIntRunCode(Endian endian, IntJitType type, MethodVisitor rv) {+ switch (endian) {+ case BIG -> generateConvMpIntRunCodeLegBE(0, type.size(), rv);+ case LITTLE -> generateConvMpIntRunCodeLegLE(0, type.size(), rv);+ }+ }++ private String chooseWriteLongName(Endian endian, int size) {+ return switch (endian) {+ case BIG -> LongWriteGen.BE.chooseName(size);+ case LITTLE -> LongWriteGen.LE.chooseName(size);+ };+ }++ private void generateConvLongRunCode(Endian endian, LongJitType type, MethodVisitor rv) {+ // [...,value:LONG,bytearr]+ rv.visitInsn(DUP_X2);+ // [...,bytearr,value:LONG,bytearr]+ rv.visitLdcInsn(0);+ // [...,bytearr,value:LONG,bytearr,offset=0]+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseWriteLongName(endian, type.size()),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX, true);+ // [...,bytearr])+ }++ private void generateConvFloatRunCode(Endian endian, FloatJitType type, MethodVisitor rv) {+ // [...,value:FLOAT,bytearr]+ rv.visitInsn(SWAP);+ // [...,bytearr,value:FLOAT]+ TypeConversions.generateFloatToInt(type, IntJitType.I4, rv);+ // [...,bytearr,value:INT]+ rv.visitInsn(SWAP);+ // [...,value:INT,bytearr]+ generateConvIntRunCode(endian, IntJitType.I4, rv);+ // [...,bytearr]+ }++ private void generateConvDoubleRunCode(Endian endian, DoubleJitType type, MethodVisitor rv) {+ // [...,value:DOUBLE,bytearr]+ rv.visitInsn(DUP_X2);+ // [...,bytearr,value:DOUBLE,bytearr]+ rv.visitInsn(POP);+ // [...,bytearr,value:DOUBLE]+ TypeConversions.generateDoubleToLong(type, LongJitType.I8, rv);+ // [...,bytearr,value:LONG]+ rv.visitInsn(DUP2_X1);+ // [...,value:LONG,bytearr,value:LONG]+ rv.visitInsn(POP2);+ // [...,value:LONG,bytearr]+ generateConvLongRunCode(endian, LongJitType.I8, rv);+ // [...,bytearr]+ }++ private void generateConvMpIntRunCodeBE(MpIntJitType type, MethodVisitor rv) {+ // [...,leg1,...,legN,bytearr]+ int countFull = type.legsWhole();+ int remSize = type.partialSize();++ int off = type.size();+ for (int i = 0; i < countFull; i++) {+ off -= Integer.BYTES;+ // [...,legN-1,legN,bytearr]+ generateConvMpIntRunCodeLegBE(off, Integer.BYTES, rv);+ // [...,legN-1,bytearr]+ }+ if (remSize > 0) {+ off -= remSize;+ // [...,leg1,bytearr]+ generateConvMpIntRunCodeLegBE(off, remSize, rv);+ // [...,bytearr]+ }+ // [...,bytearr]+ }++ private void generateConvMpIntRunCodeLE(MpIntJitType type, MethodVisitor rv) {+ // [...,leg1,...,legN,bytearr]+ int countFull = type.legsWhole();+ int remSize = type.partialSize();++ int off = 0;+ for (int i = 0; i < countFull; i++) {+ // [...,legN-1,legN,bytearr]+ generateConvMpIntRunCodeLegLE(off, Integer.BYTES, rv);+ // [...,legN-1,bytearr]+ off += Integer.BYTES;+ }+ if (remSize > 0) {+ // [...,leg1,bytearr]+ generateConvMpIntRunCodeLegLE(off, remSize, rv);+ // [...,bytearr]+ off += remSize;+ }+ // [...,bytearr]+ }++ private void generateConvMpIntRunCode(Endian endian, MpIntJitType type, MethodVisitor rv) {+ switch (endian) {+ case BIG -> generateConvMpIntRunCodeBE(type, rv);+ case LITTLE -> generateConvMpIntRunCodeLE(type, rv);+ }+ }++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitStoreOp op, JitBlock block,+ MethodVisitor rv) {+ // [...]+ gen.requestFieldForSpaceIndirect(op.space()).generateLoadCode(gen, rv);+ // [...,space]+ JitType offsetType = gen.generateValReadCode(op.offset(), op.offsetType());+ // [...,space,offset:?]+ TypeConversions.generateToLong(offsetType, LongJitType.I8, rv);+ // [...,space,offset:LONG]+ JitType valueType = gen.generateValReadCode(op.value(), op.valueType());+ // [...,space,offset,value]+ rv.visitLdcInsn(op.value().size());+ // [...,space,offset,value,size]+ rv.visitIntInsn(NEWARRAY, T_BYTE);+ // [...,space,offset,value,bytearray]+ Endian endian = gen.getAnalysisContext().getEndian();+ switch (valueType) {+ case IntJitType iType -> generateConvIntRunCode(endian, iType, rv);+ case LongJitType lType -> generateConvLongRunCode(endian, lType, rv);+ case FloatJitType fType -> generateConvFloatRunCode(endian, fType, rv);+ case DoubleJitType dType -> generateConvDoubleRunCode(endian, dType, rv);+ case MpIntJitType mpType -> generateConvMpIntRunCode(endian, mpType, rv);+ default -> throw new AssertionError();+ }+ // [...,space,offset,bytearray]+ rv.visitLdcInsn(0);+ // [...,space,offset,bytearray,srcOffset=0]+ rv.visitLdcInsn(op.value().size());+ // [...,space,offset,bytearray,srcOffset=0,size]+ rv.visitMethodInsn(+ INVOKEVIRTUAL, NAME_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE, "write",+ MDESC_JIT_BYTES_PCODE_EXECUTOR_STATE_SPACE__WRITE, false);+ // [...]+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/SubPieceOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/SubPieceOpGen.javanew file mode 100644index 0000000000..e823da1184--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/SubPieceOpGen.java@@ -0,0 +1,155 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.*;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitSubPieceOp;++/**+ * The generator for a {@link JitSubPieceOp subpiece}.+ *+ * <p>+ * NOTE: The multi-precision int parts of this are a work in progress.+ *+ * <p>+ * This is not quite like a normal binary operator, because the second operand is always a constant.+ * It behaves more like a class of unary operators, if you ask me. Thus, we do not extend+ * {@link BinOpGen}. We first emit code to load the operand. Then, because the shift amount is+ * constant, we can deal with it at <em>generation time</em>. We emit code to shift right by that+ * constant amount, accounting for bits and bytes. The masking, if required, is taken care of by the+ * variable writing code, given the resulting type.+ */+public enum SubPieceOpGen implements OpGen<JitSubPieceOp> {+ /** The generator singleton */+ GEN;++ /**+ * <b>WIP</b>: Assumes the previous (next more significant) leg is on the stack and the current+ * (unshifted) leg is in the given variable. Computes the resulting output leg and puts in into+ * the given local variable, but leaves a copy of the current unshifted leg on the stack.+ *+ * @param rv the method visitor+ * @param bitShift the number of <em>bits</em> to shift+ * @param index the index of the local variable for the current leg+ */+ private void generateShiftWithPrevLeg(MethodVisitor rv, int bitShift, int index) {+ // [...,prevLegIn]+ rv.visitLdcInsn(Integer.SIZE - bitShift);+ rv.visitInsn(ISHR);+ // [...,prevLegIn:SLACK]+ rv.visitVarInsn(ILOAD, index);+ // [...,prevLegIn:SLACK,legIn]+ rv.visitInsn(DUP_X1);+ // [...,legIn,prevLegIn:SLACK,legIn]+ rv.visitLdcInsn(bitShift);+ rv.visitInsn(IUSHR);+ // [...,legIn,prevLegIn:SLACK,legIn:SHIFT]+ rv.visitInsn(IOR);+ // [...,legIn,legOut]+ rv.visitVarInsn(ISTORE, index);+ // [...,legIn]+ }++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitSubPieceOp op, JitBlock block,+ MethodVisitor rv) {+ JitType vType = gen.generateValReadCode(op.u(), op.uType());+ JitType outType;+ switch (vType) {+ case IntJitType vIType -> {+ rv.visitLdcInsn(op.offset() * Byte.SIZE);+ rv.visitInsn(IUSHR);+ outType = vIType;+ }+ case LongJitType vLType -> {+ rv.visitLdcInsn(op.offset() * Byte.SIZE);+ rv.visitInsn(LUSHR);+ outType = vLType;+ }+ case MpIntJitType vMpType -> {+ // WIP+ MpIntJitType outMpType = MpIntJitType.forSize(op.out().size());+ int outLegCount = outMpType.legsAlloc();+ int legsLeft = vMpType.legsAlloc();+ int popCount = op.offset() / Integer.BYTES;+ int byteShift = op.offset() % Integer.BYTES;+ for (int i = 0; i < popCount; i++) {+ rv.visitInsn(POP);+ }+ int firstIndex = gen.getAllocationModel().nextFreeLocal();+ Label start = new Label();+ Label end = new Label();+ rv.visitLabel(start);+ for (int i = 0; i < outLegCount; i++) {+ rv.visitLocalVariable("subpiece" + i, Type.getDescriptor(int.class), null,+ start, end, firstIndex + i);+ rv.visitVarInsn(ISTORE, firstIndex + i);+ // NOTE: More significant legs have higher indices (reverse of stack)+ legsLeft--;+ }++ if (byteShift > 0) {+ int curLeg = outLegCount - 1;+ if (legsLeft > 0) {+ // [...,prevLegIn]+ generateShiftWithPrevLeg(rv, byteShift * Byte.SIZE, firstIndex + curLeg);+ // [...,legIn]+ legsLeft--;+ curLeg--;+ }+ else {+ // [...]+ rv.visitVarInsn(ILOAD, firstIndex + curLeg);+ // [...,legIn]+ rv.visitInsn(DUP);+ // [...,legIn,legIn]+ rv.visitLdcInsn(byteShift * Byte.SIZE);+ rv.visitInsn(IUSHR);+ // [...,legIn,legOut]+ rv.visitVarInsn(ISTORE, firstIndex + curLeg);+ // [...,legIn]+ curLeg--;+ }+ while (curLeg >= 0) {+ generateShiftWithPrevLeg(rv, byteShift * Byte.SIZE, firstIndex + curLeg);+ legsLeft--;+ curLeg--;+ }+ }+ while (legsLeft > 0) {+ rv.visitInsn(POP);+ legsLeft--;+ }+ // NOTE: More significant legs have higher indices+ for (int i = outLegCount - 1; i >= 0; i--) {+ rv.visitVarInsn(ILOAD, firstIndex + i);+ }+ rv.visitLabel(end);+ outType = outMpType;+ }+ default -> throw new AssertionError();+ }+ gen.generateVarWriteCode(op.out(), outType);+ }++}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/SynthSubPieceOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/SynthSubPieceOpGen.javanew file mode 100644index 0000000000..702b12d517--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/SynthSubPieceOpGen.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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.analysis.JitVarScopeModel;+import ghidra.pcode.emu.jit.op.JitSynthSubPieceOp;++/**+ * The generator for a {@link JitSynthSubPieceOp synth-subpiece}.+ *+ * <p>+ * We emit nothing. This generator ought never to be invoked, anyway, but things may change. The+ * argument here is similar to that of {@link PhiOpGen}.+ *+ * @see JitVarScopeModel+ */+public enum SynthSubPieceOpGen implements OpGen<JitSynthSubPieceOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitSynthSubPieceOp op, JitBlock block,+ MethodVisitor rv) {+ throw new AssertionError("Cannnot generate synthetic op");+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/UnOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/UnOpGen.javanew file mode 100644index 0000000000..50d6d39f71--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/UnOpGen.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.pcode.emu.jit.gen.op;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.op.JitUnOp;++/**+ * An extension that provides conveniences and common implementations for unary p-code operators+ *+ * @param <T> the class of p-code op node in the use-def graph+ */+public interface UnOpGen<T extends JitUnOp> extends OpGen<T> {++ /**+ * Emit code for the unary operator+ *+ * <p>+ * At this point the operand is on the stack. After this returns, code to write the result from+ * the stack into the destination operand will be emitted.+ *+ * @param gen the code generator+ * @param op the operator+ * @param block the block containing the operator+ * @param uType the actual type of the operand+ * @param rv the method visitor+ * @return the actual type of the result+ */+ JitType generateUnOpRunCode(JitCodeGenerator gen, T op, JitBlock block, JitType uType,+ MethodVisitor rv);++ /**+ * {@inheritDoc}+ *+ * <p>+ * This default implementation emits code to load the operand, invokes+ * {@link #generateUnOpRunCode(JitCodeGenerator, JitUnOp, JitBlock, JitType, MethodVisitor)+ * gen-unop}, and finally emits code to write the destination operand.+ */+ @Override+ default void generateRunCode(JitCodeGenerator gen, T op, JitBlock block, MethodVisitor rv) {+ JitType uType = gen.generateValReadCode(op.u(), op.uType());+ JitType outType = generateUnOpRunCode(gen, op, block, uType, rv);+ gen.generateVarWriteCode(op.out(), outType);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/UnimplementedOpGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/UnimplementedOpGen.javanew file mode 100644index 0000000000..28cd82cf8b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/op/UnimplementedOpGen.java@@ -0,0 +1,75 @@+/* ###+ * 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.pcode.emu.jit.gen.op;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitPassage.DecodeErrorPcodeOp;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.op.JitUnimplementedOp;+import ghidra.pcode.error.LowlevelError;+import ghidra.pcode.exec.DecodePcodeExecutionException;++/**+ * The generator for a {@link JitUnimplementedOp unimplemented}.+ *+ * <p>+ * This emits code to retire the program counter, context, and live variables, then throw a+ * {@link DecodePcodeExecutionException} or {@link LowlevelError}. The former case is constructed by+ * {@link JitCompiledPassage#createDecodeError(String, long)}.+ */+public enum UnimplementedOpGen implements OpGen<JitUnimplementedOp> {+ /** The generator singleton */+ GEN;++ @Override+ public void generateRunCode(JitCodeGenerator gen, JitUnimplementedOp op, JitBlock block,+ MethodVisitor rv) {+ long counter = gen.getAddressForOp(op.op()).getOffset();++ gen.generatePassageExit(block, () -> {+ rv.visitLdcInsn(counter);+ }, gen.getExitContext(op.op()), rv);++ String message = gen.getErrorMessage(op.op());+ if (op.op() instanceof DecodeErrorPcodeOp) {+ rv.visitVarInsn(ALOAD, 0);+ rv.visitLdcInsn(message);+ rv.visitLdcInsn(counter);+ rv.visitMethodInsn(INVOKEINTERFACE, NAME_JIT_COMPILED_PASSAGE, "createDecodeError",+ MDESC_JIT_COMPILED_PASSAGE__CREATE_DECODE_ERROR, true);+ rv.visitInsn(ATHROW);+ }+ else {+ // [...]+ rv.visitTypeInsn(NEW, NAME_LOW_LEVEL_ERROR);+ // [...,error:NEW]+ rv.visitInsn(DUP);+ // [...,error:NEW,error:NEW]+ rv.visitLdcInsn(message);+ // [...,error:NEW,error:NEW,message]+ rv.visitMethodInsn(INVOKESPECIAL, NAME_LOW_LEVEL_ERROR, "<init>",+ MDESC_LOW_LEVEL_ERROR__$INIT, false);+ // [...,error]+ rv.visitInsn(ATHROW);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/tgt/JitCompiledPassage.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/tgt/JitCompiledPassage.javanew file mode 100644index 0000000000..39197d5bd0--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/tgt/JitCompiledPassage.java@@ -0,0 +1,1495 @@+/* ###+ * 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.pcode.emu.jit.gen.tgt;++import java.math.BigInteger;+import java.util.*;++import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.PcodeThread;+import ghidra.pcode.emu.jit.JitCompiler;+import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.emu.jit.JitPcodeThread;+import ghidra.pcode.emu.jit.analysis.JitDataFlowUseropLibrary;+import ghidra.pcode.emu.jit.analysis.JitType.IntJitType;+import ghidra.pcode.emu.jit.analysis.JitType.LongJitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.exec.*;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressFactory;+import ghidra.program.model.lang.*;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;+import ghidra.program.util.DefaultLanguageService;++/**+ * The interface implemented by classfiles generated by {@link JitCompiler}.+ *+ * <p>+ * This also serves as a run-time library of routines that implement p-code ops not trivially+ * implemented by the JVM or its run-time library. In theory, they can be inlined by the JVM's JIT+ * at its discretion.+ */+public interface JitCompiledPassage {++ /**+ * An entry point that is not yet bound to a specific thread+ *+ * @implNote This would be a {@code record} except that it maintains the cache of instances per+ * thread+ */+ class EntryPointPrototype {+ private final JitCompiledPassageClass cls;+ private final int blockId;+ private final Map<JitPcodeThread, EntryPoint> perThread = new HashMap<>();++ /**+ * Construct an entry prototype+ *+ * @param cls the compiled passage class (i.e., passage not yet bound to a specific thread)+ * @param blockId the block at which to enter the passage+ */+ public EntryPointPrototype(JitCompiledPassageClass cls, int blockId) {+ this.cls = cls;+ this.blockId = blockId;+ }++ @Override+ public String toString() {+ return "EntryPointPrototype[%s,%d]".formatted(cls, blockId);+ }++ @Override+ public boolean equals(Object obj) {+ if (!(obj instanceof EntryPointPrototype that)) {+ return false;+ }+ if (!this.cls.equals(that.cls)) {+ return false;+ }+ if (this.blockId != that.blockId) {+ return false;+ }+ return true;+ }++ @Override+ public int hashCode() {+ return Objects.hash(cls, blockId);+ }++ /**+ * Create (or get) the entry point for the given thread+ *+ * @param thread the thread to bind to the entry point+ * @return the resulting entry point+ * @see JitPcodeThread#getEntry(AddrCtx)+ */+ public EntryPoint createInstance(JitPcodeThread thread) {+ synchronized (perThread) {+ return perThread.computeIfAbsent(thread,+ t -> new EntryPoint(this, cls.createInstance(t), blockId));+ }+ }+ }++ /**+ * An entry point into a translated passage+ *+ * <p>+ * This represents a translated passage and an index into its list of entry points. For an+ * overview of how this fits into the JIT-accelerated execution loop, see+ * {@link JitPcodeThread}, especially the <b>Translate</b> and <b>Execute</b> sections. For+ * details of how the entry points and their metadata are exported, see+ * {@link JitCodeGenerator}, especially the <b>Entry Point Dispatch</b> section.+ *+ * @param prototype the entry point prototype (passage class and blockId without bound thread)+ * @param passage the compiled passage, instantiated for the bound thread+ * @param blockId an index identifying the block at the target address and contextreg value of+ * this entry point+ */+ record EntryPoint(EntryPointPrototype prototype, JitCompiledPassage passage, int blockId) {+ /**+ * Start/resume execution of the bound thread at this entry point.+ *+ * <p>+ * The associated passage is invoked, starting at the given block via+ * {@link JitCompiledPassage#run(int)}, which was generated by {@link JitCodeGenerator}.+ *+ * @return as in {@link JitCompiledPassage#run(int)}+ */+ public EntryPoint run() {+ return passage.run(blockId);+ }+ }++ /**+ * A cache slot for a chained entry point+ *+ * <p>+ * One of these is constructed for each target of a direct branch that exits the passage,+ * including those of synthetic {@link ExitPcodeOp exit} ops. For each such branch, the+ * {@link JitCodeGenerator} emits code to invoke {@link #getChained()} on the target's exit slot+ * and to return the resulting entry point.+ */+ public static class ExitSlot {+ private final JitPcodeThread thread;+ private final AddrCtx pcCtx;++ private EntryPoint chained;++ /**+ * Construct an exit slot for the given target and bound thread+ *+ * @param thread the bound thread for the passage constructing this slot+ * @param target the offset of the target address+ * @param ctx the target decode context+ */+ public ExitSlot(JitPcodeThread thread, long target, RegisterValue ctx) {+ this.thread = thread;+ this.pcCtx =+ new AddrCtx(ctx, thread.getLanguage().getDefaultSpace().getAddress(target));+ }++ /**+ * Get the entry point for this target+ *+ * <p>+ * This may cause the emulator to translate a new passage.+ *+ * @return the entry point+ * @implNote This will always return a non-null entry point, even if the branch target is+ * invalid. In that case, the "passage" will consist of a single+ * {@link DecodeErrorInstruction}, which will ensure the emulator crashes upon+ * trying to execute at the target address.+ */+ public EntryPoint getChained() {+ if (chained == null) {+ chained = computeChained();+ }+ return chained;+ }++ private EntryPoint computeChained() {+ return thread.getEntry(pcCtx);+ }+ }++ /**+ * Run the compiled passage of code+ *+ * <p>+ * Except during testing, this is ordinarily called by {@link EntryPoint#run()}. Too see how+ * this fits into the overall JIT-accelerated execution loop, see {@link JitPcodeThread}. All+ * implementations of this interface are generated dynamically. To understand that process and+ * how the entry points are generated and exported, see {@link JitCompiler}.+ *+ * <p>+ * This method may or may not return a chained entry point. Each passage caches a chained entry+ * point for each of its direct branch targets. This averts a map lookup on subsequent exits via+ * the same branch. If a chained entry point is returned, the thread ought to execute it+ * immediately, unless it has become suspended. Otherwise, the thread must repeat its execution+ * loop at the <b>Fetch</b> step.+ *+ * @param blockId an index identifying the target address and contextreg where execution should+ * enter+ * @return a chained entry point, or {@code null}+ */+ EntryPoint run(int blockId);++ /**+ * Read an {@link IntJitType#I1 int1} from the given array at the given offset+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM int+ */+ static int readInt1(byte[] arr, int offset) {+ return Byte.toUnsignedInt(arr[offset]);+ }++ /**+ * Read an {@link IntJitType#I2 int2} from the given array at the given offset in big endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM int+ */+ static int readIntBE2(byte[] arr, int offset) {+ return Byte.toUnsignedInt(arr[offset]) << 8 |+ Byte.toUnsignedInt(arr[offset + 1]);+ }++ /**+ * Read an {@link IntJitType#I3 int3} from the given array at the given offset in big endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM int+ */+ static int readIntBE3(byte[] arr, int offset) {+ return Byte.toUnsignedInt(arr[offset]) << 16 |+ Byte.toUnsignedInt(arr[offset + 1]) << 8 |+ Byte.toUnsignedInt(arr[offset + 2]);+ }++ /**+ * Read an {@link IntJitType#I4 int4} from the given array at the given offset in big endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM int+ */+ static int readIntBE4(byte[] arr, int offset) {+ return Byte.toUnsignedInt(arr[offset]) << 24 |+ Byte.toUnsignedInt(arr[offset + 1]) << 16 |+ Byte.toUnsignedInt(arr[offset + 2]) << 8 |+ Byte.toUnsignedInt(arr[offset + 3]);+ }++ /**+ * Read an {@link IntJitType#I2 int2} from the given array at the given offset in little endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM int+ */+ static int readIntLE2(byte[] arr, int offset) {+ return Byte.toUnsignedInt(arr[offset]) |+ Byte.toUnsignedInt(arr[offset + 1]) << 8;+ }++ /**+ * Read an {@link IntJitType#I3 int3} from the given array at the given offset in little endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM int+ */+ static int readIntLE3(byte[] arr, int offset) {+ return Byte.toUnsignedInt(arr[offset]) |+ Byte.toUnsignedInt(arr[offset + 1]) << 8 |+ Byte.toUnsignedInt(arr[offset + 2]) << 16;+ }++ /**+ * Read an {@link IntJitType#I4 int4} from the given array at the given offset in little endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM int+ */+ static int readIntLE4(byte[] arr, int offset) {+ return Byte.toUnsignedInt(arr[offset]) |+ Byte.toUnsignedInt(arr[offset + 1]) << 8 |+ Byte.toUnsignedInt(arr[offset + 2]) << 16 |+ Byte.toUnsignedInt(arr[offset + 3]) << 24;+ }++ /**+ * Write an {@link IntJitType#I1 int1} into the given array at the given offset+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM int+ * @param arr the array+ * @param offset the offset+ */+ static void writeInt1(int value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I2 int2} into the given array at the given offset in big endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM int+ * @param arr the array+ * @param offset the offset+ */+ static void writeIntBE2(int value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 8);+ arr[offset + 1] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I3 int3} into the given array at the given offset in big endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM int+ * @param arr the array+ * @param offset the offset+ */+ static void writeIntBE3(int value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 16);+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I4 int4} into the given array at the given offset in big endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM int+ * @param arr the array+ * @param offset the offset+ */+ static void writeIntBE4(int value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 24);+ arr[offset + 1] = (byte) (value >> 16);+ arr[offset + 2] = (byte) (value >> 8);+ arr[offset + 3] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I2 int2} into the given array at the given offset in litte endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM int+ * @param arr the array+ * @param offset the offset+ */+ static void writeIntLE2(int value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ }++ /**+ * Write an {@link IntJitType#I3 int3} into the given array at the given offset in litte endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM int+ * @param arr the array+ * @param offset the offset+ */+ static void writeIntLE3(int value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ }++ /**+ * Write an {@link IntJitType#I4 int4} into the given array at the given offset in litte endian+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM int+ * @param arr the array+ * @param offset the offset+ */+ static void writeIntLE4(int value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ arr[offset + 3] = (byte) (value >> 24);+ }++ /**+ * Read an {@link IntJitType#I1 int1} from the given array at the given offset.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I1 int1} can fit in+ * a JVM int, this method is used when reading 1 byte of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLong1(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]);+ }++ /**+ * Read an {@link IntJitType#I2 int2} from the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I2 int2} can fit in+ * a JVM int, this method is used when reading 2 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongBE2(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) << 8 |+ Byte.toUnsignedLong(arr[offset + 1]);+ }++ /**+ * Read an {@link IntJitType#I3 int3} from the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I3 int3} can fit in+ * a JVM int, this method is used when reading 3 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongBE3(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) << 16 |+ Byte.toUnsignedLong(arr[offset + 1]) << 8 |+ Byte.toUnsignedLong(arr[offset + 2]);+ }++ /**+ * Read an {@link IntJitType#I4 int4} from the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I4 int4} can fit in+ * a JVM int, this method is used when reading 4 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongBE4(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) << 24 |+ Byte.toUnsignedLong(arr[offset + 1]) << 16 |+ Byte.toUnsignedLong(arr[offset + 2]) << 8 |+ Byte.toUnsignedLong(arr[offset + 3]);+ }++ /**+ * Read an {@link LongJitType#I5 int5} from the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongBE5(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) << 32 |+ Byte.toUnsignedLong(arr[offset + 1]) << 24 |+ Byte.toUnsignedLong(arr[offset + 2]) << 16 |+ Byte.toUnsignedLong(arr[offset + 3]) << 8 |+ Byte.toUnsignedLong(arr[offset + 4]);+ }++ /**+ * Read an {@link LongJitType#I6 int6} from the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongBE6(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) << 40 |+ Byte.toUnsignedLong(arr[offset + 1]) << 32 |+ Byte.toUnsignedLong(arr[offset + 2]) << 24 |+ Byte.toUnsignedLong(arr[offset + 3]) << 16 |+ Byte.toUnsignedLong(arr[offset + 4]) << 8 |+ Byte.toUnsignedLong(arr[offset + 5]);+ }++ /**+ * Read an {@link LongJitType#I7 int7} from the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongBE7(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) << 48 |+ Byte.toUnsignedLong(arr[offset + 1]) << 40 |+ Byte.toUnsignedLong(arr[offset + 2]) << 32 |+ Byte.toUnsignedLong(arr[offset + 3]) << 24 |+ Byte.toUnsignedLong(arr[offset + 4]) << 16 |+ Byte.toUnsignedLong(arr[offset + 5]) << 8 |+ Byte.toUnsignedLong(arr[offset + 6]);+ }++ /**+ * Read an {@link LongJitType#I8 int8} from the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongBE8(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) << 56 |+ Byte.toUnsignedLong(arr[offset + 1]) << 48 |+ Byte.toUnsignedLong(arr[offset + 2]) << 40 |+ Byte.toUnsignedLong(arr[offset + 3]) << 32 |+ Byte.toUnsignedLong(arr[offset + 4]) << 24 |+ Byte.toUnsignedLong(arr[offset + 5]) << 16 |+ Byte.toUnsignedLong(arr[offset + 6]) << 8 |+ Byte.toUnsignedLong(arr[offset + 7]);+ }++ /**+ * Read an {@link IntJitType#I2 int2} from the given array at the given offset in little endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I2 int2} can fit in+ * a JVM int, this method is used when reading 2 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongLE2(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) |+ Byte.toUnsignedLong(arr[offset + 1]) << 8;+ }++ /**+ * Read an {@link IntJitType#I3 int3} from the given array at the given offset in little endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I3 int3} can fit in+ * a JVM int, this method is used when reading 3 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongLE3(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) |+ Byte.toUnsignedLong(arr[offset + 1]) << 8 |+ Byte.toUnsignedLong(arr[offset + 2]) << 16;+ }++ /**+ * Read an {@link IntJitType#I4 int4} from the given array at the given offset in little endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I4 int4} can fit in+ * a JVM int, this method is used when reading 4 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongLE4(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) |+ Byte.toUnsignedLong(arr[offset + 1]) << 8 |+ Byte.toUnsignedLong(arr[offset + 2]) << 16 |+ Byte.toUnsignedLong(arr[offset + 3]) << 24;+ }++ /**+ * Read an {@link LongJitType#I5 int5} from the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongLE5(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) |+ Byte.toUnsignedLong(arr[offset + 1]) << 8 |+ Byte.toUnsignedLong(arr[offset + 2]) << 16 |+ Byte.toUnsignedLong(arr[offset + 3]) << 24 |+ Byte.toUnsignedLong(arr[offset + 4]) << 32;+ }++ /**+ * Read an {@link LongJitType#I6 int6} from the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongLE6(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) |+ Byte.toUnsignedLong(arr[offset + 1]) << 8 |+ Byte.toUnsignedLong(arr[offset + 2]) << 16 |+ Byte.toUnsignedLong(arr[offset + 3]) << 24 |+ Byte.toUnsignedLong(arr[offset + 4]) << 32 |+ Byte.toUnsignedLong(arr[offset + 5]) << 40;+ }++ /**+ * Read an {@link LongJitType#I7 int7} from the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongLE7(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) |+ Byte.toUnsignedLong(arr[offset + 1]) << 8 |+ Byte.toUnsignedLong(arr[offset + 2]) << 16 |+ Byte.toUnsignedLong(arr[offset + 3]) << 24 |+ Byte.toUnsignedLong(arr[offset + 4]) << 32 |+ Byte.toUnsignedLong(arr[offset + 5]) << 40 |+ Byte.toUnsignedLong(arr[offset + 6]) << 48;+ }++ /**+ * Read an {@link LongJitType#I8 int8} from the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param arr the array+ * @param offset the offset+ * @return the value as a JVM long+ */+ static long readLongLE8(byte[] arr, int offset) {+ return Byte.toUnsignedLong(arr[offset]) |+ Byte.toUnsignedLong(arr[offset + 1]) << 8 |+ Byte.toUnsignedLong(arr[offset + 2]) << 16 |+ Byte.toUnsignedLong(arr[offset + 3]) << 24 |+ Byte.toUnsignedLong(arr[offset + 4]) << 32 |+ Byte.toUnsignedLong(arr[offset + 5]) << 40 |+ Byte.toUnsignedLong(arr[offset + 6]) << 48 |+ Byte.toUnsignedLong(arr[offset + 7]) << 56;+ }++ /**+ * Write an {@link IntJitType#I1 int1} into the given array at the given offset.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I1 int1} can fit in+ * a JVM int, this method is used when writing 1 byte of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLong1(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I2 int2} into the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I2 int2} can fit in+ * a JVM int, this method is used when writing 2 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongBE2(long value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 8);+ arr[offset + 1] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I3 int3} into the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I3 int3} can fit in+ * a JVM int, this method is used when writing 3 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongBE3(long value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 16);+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I4 int4} into the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I4 int4} can fit in+ * a JVM int, this method is used when writing 4 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongBE4(long value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 24);+ arr[offset + 1] = (byte) (value >> 16);+ arr[offset + 2] = (byte) (value >> 8);+ arr[offset + 3] = (byte) value;+ }++ /**+ * Write an {@link LongJitType#I5 int5} into the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongBE5(long value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 32);+ arr[offset + 1] = (byte) (value >> 24);+ arr[offset + 2] = (byte) (value >> 16);+ arr[offset + 3] = (byte) (value >> 8);+ arr[offset + 4] = (byte) value;+ }++ /**+ * Write an {@link LongJitType#I6 int6} into the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongBE6(long value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 40);+ arr[offset + 1] = (byte) (value >> 32);+ arr[offset + 2] = (byte) (value >> 24);+ arr[offset + 3] = (byte) (value >> 16);+ arr[offset + 4] = (byte) (value >> 8);+ arr[offset + 5] = (byte) value;+ }++ /**+ * Write an {@link LongJitType#I7 int7} into the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongBE7(long value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 48);+ arr[offset + 1] = (byte) (value >> 40);+ arr[offset + 2] = (byte) (value >> 32);+ arr[offset + 3] = (byte) (value >> 24);+ arr[offset + 4] = (byte) (value >> 16);+ arr[offset + 5] = (byte) (value >> 8);+ arr[offset + 6] = (byte) value;+ }++ /**+ * Write an {@link LongJitType#I8 int8} into the given array at the given offset in big endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongBE8(long value, byte[] arr, int offset) {+ arr[offset] = (byte) (value >> 56);+ arr[offset + 1] = (byte) (value >> 48);+ arr[offset + 2] = (byte) (value >> 40);+ arr[offset + 3] = (byte) (value >> 32);+ arr[offset + 4] = (byte) (value >> 24);+ arr[offset + 5] = (byte) (value >> 16);+ arr[offset + 6] = (byte) (value >> 8);+ arr[offset + 7] = (byte) value;+ }++ /**+ * Write an {@link IntJitType#I2 int2} into the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I2 int2} can fit in+ * a JVM int, this method is used when writing 2 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongLE2(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ }++ /**+ * Write an {@link IntJitType#I3 int3} into the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I3 int3} can fit in+ * a JVM int, this method is used when writing 3 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongLE3(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ }++ /**+ * Write an {@link IntJitType#I4 int4} into the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code. While an {@link IntJitType#I4 int4} can fit in+ * a JVM int, this method is used when writing 4 bytes of a {@link LongJitType larger int} that+ * spans a page boundary.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongLE4(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ arr[offset + 3] = (byte) (value >> 24);+ }++ /**+ * Write an {@link LongJitType#I5 int5} into the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongLE5(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ arr[offset + 3] = (byte) (value >> 24);+ arr[offset + 4] = (byte) (value >> 32);+ }++ /**+ * Write an {@link LongJitType#I6 int6} into the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongLE6(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ arr[offset + 3] = (byte) (value >> 24);+ arr[offset + 4] = (byte) (value >> 32);+ arr[offset + 5] = (byte) (value >> 40);+ }++ /**+ * Write an {@link LongJitType#I7 int7} into the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongLE7(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ arr[offset + 3] = (byte) (value >> 24);+ arr[offset + 4] = (byte) (value >> 32);+ arr[offset + 5] = (byte) (value >> 40);+ arr[offset + 6] = (byte) (value >> 48);+ }++ /**+ * Write an {@link LongJitType#I8 int8} into the given array at the given offset in little+ * endian.+ *+ * <p>+ * This is invoked by dynamically generated code.+ *+ * @param value the value as a JVM long+ * @param arr the array+ * @param offset the offset+ */+ static void writeLongLE8(long value, byte[] arr, int offset) {+ arr[offset] = (byte) value;+ arr[offset + 1] = (byte) (value >> 8);+ arr[offset + 2] = (byte) (value >> 16);+ arr[offset + 3] = (byte) (value >> 24);+ arr[offset + 4] = (byte) (value >> 32);+ arr[offset + 5] = (byte) (value >> 40);+ arr[offset + 6] = (byte) (value >> 48);+ arr[offset + 7] = (byte) (value >> 56);+ }++ /**+ * Convert two integers into a single long+ *+ * <p>+ * In terms of the JVM stack, this simply converts the top two ints to an equivalent long.+ * <b>TODO</b>: This no longer appears to be used, but may be in anticipation of multi-precision+ * integer support.+ *+ * @param msl the more significant leg+ * @param lsl the less significant leg+ * @return the long+ */+ static long conv2IntToLong(int msl, int lsl) {+ return Integer.toUnsignedLong(msl) << Integer.SIZE | Integer.toUnsignedLong(lsl);+ }++ /**+ * The implementation of {@link PcodeOp#INT_SBORROW int_sborrow} on JVM ints.+ *+ * <p>+ * This actually computes all the borrow bits. To extract a specific one, the generator should+ * emit a shift and mask.+ *+ * @param a the first operand as in {@code a - b}+ * @param b the second operand as in {@code a - b}+ * @return the register of borrow bits+ */+ static int sBorrowIntRaw(int a, int b) {+ int r = a - b;+ a ^= r;+ r ^= b;+ r ^= -1;+ a &= r;+ return a;+ }++ /**+ * The implementation of {@link PcodeOp#INT_SBORROW int_sborrow} on JVM longs.+ *+ * <p>+ * This actually computes all the borrow bits. To extract a specific one, the generator should+ * emit a shift and mask.+ *+ * @param a the first operand as in {@code a - b}+ * @param b the second operand as in {@code a - b}+ * @return the register of borrow bits+ */+ static long sBorrowLongRaw(long a, long b) {+ long r = a - b;+ a ^= r;+ r ^= b;+ r ^= -1;+ a &= r;+ return a;+ }++ /**+ * The implementation of {@link PcodeOp#INT_SCARRY int_scarry} on JVM ints.+ *+ * <p>+ * This actually computes all the carry bits. To extract a specific one, the generator should+ * emit a shift and mask.+ *+ * @param a the first operand as in {@code a + b}+ * @param b the second operand as in {@code a + b}+ * @return the register of carry bits+ */+ static int sCarryIntRaw(int a, int b) {+ int r = a + b;+ r ^= a;+ a ^= b;+ a ^= -1;+ r &= a;+ return r;+ }++ /**+ * The implementation of {@link PcodeOp#INT_SCARRY int_scarry} on JVM longs.+ *+ * <p>+ * This actually computes all the carry bits. To extract a specific one, the generator should+ * emit a shift and mask.+ *+ * @param a the first operand as in {@code a + b}+ * @param b the second operand as in {@code a + b}+ * @return the register of carry bits+ */+ static long sCarryLongRaw(long a, long b) {+ long r = a + b;+ r ^= a;+ a ^= b;+ a ^= -1;+ r &= a;+ return r;+ }++ /**+ * The implementation of {@link PcodeOp#INT_LEFT int_left} on JVM longs.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHL ishl}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val << amt}+ * @param amt the amt as in {@code val << amt}+ * @return the value+ */+ static long intLeft(long val, long amt) {+ if (Long.compareUnsigned(amt, Long.SIZE) >= 0) {+ return 0;+ }+ return val << amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_LEFT int_left} on JVM long with int amt.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHL ishl}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val << amt}+ * @param amt the amt as in {@code val << amt}+ * @return the value+ */+ static long intLeft(long val, int amt) {+ if (Integer.compareUnsigned(amt, Long.SIZE) >= 0) {+ return 0;+ }+ return val << amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_LEFT int_left} on JVM int with long amt.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHL ishl}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val << amt}+ * @param amt the amt as in {@code val << amt}+ * @return the value+ */+ static int intLeft(int val, long amt) {+ if (Long.compareUnsigned(amt, Integer.SIZE) >= 0) {+ return 0;+ }+ return val << amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_LEFT int_left} on JVM ints.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHL ishl}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val << amt}+ * @param amt the amt as in {@code val << amt}+ * @return the value+ */+ static int intLeft(int val, int amt) {+ if (Long.compareUnsigned(amt, Integer.SIZE) >= 0) {+ return 0;+ }+ return val << amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_RIGHT int_right} on JVM longs.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#IUSHR iushr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val >> amt}+ * @param amt the amt as in {@code val >> amt}+ * @return the value+ */+ static long intRight(long val, long amt) {+ if (Long.compareUnsigned(amt, Long.SIZE) >= 0) {+ return 0;+ }+ return val >>> amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_RIGHT int_right} on JVM long with int amt.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#IUSHR iushr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val >> amt}+ * @param amt the amt as in {@code val >> amt}+ * @return the value+ */+ static long intRight(long val, int amt) {+ if (Integer.compareUnsigned(amt, Long.SIZE) >= 0) {+ return 0;+ }+ return val >>> amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_RIGHT int_right} on JVM int with long amt.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#IUSHR iushr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val >> amt}+ * @param amt the amt as in {@code val >> amt}+ * @return the value+ */+ static int intRight(int val, long amt) {+ if (Long.compareUnsigned(amt, Integer.SIZE) >= 0) {+ return 0;+ }+ return val >>> amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_RIGHT int_right} on JVM ints.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#IUSHR iushr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size clear the register.+ *+ * @param val the value as in {@code val >> amt}+ * @param amt the amt as in {@code val >> amt}+ * @return the value+ */+ static int intRight(int val, int amt) {+ if (Long.compareUnsigned(amt, Integer.SIZE) >= 0) {+ return 0;+ }+ return val >>> amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_SRIGHT int_sright} on JVM longs.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHR ishr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size fill the register with+ * the sign bit.+ *+ * @param val the value as in {@code val s>> amt}+ * @param amt the amt as in {@code val s>> amt}+ * @return the value+ */+ static long intSRight(long val, long amt) {+ if (Long.compareUnsigned(amt, Long.SIZE) >= 0) {+ return val >> (Long.SIZE - 1);+ }+ return val >> amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_SRIGHT int_sright} on JVM long with int amt.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHR ishr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size fill the register with+ * the sign bit.+ *+ * @param val the value as in {@code val s>> amt}+ * @param amt the amt as in {@code val s>> amt}+ * @return the value+ */+ static long intSRight(long val, int amt) {+ if (Integer.compareUnsigned(amt, Long.SIZE) >= 0) {+ return val >> (Long.SIZE - 1);+ }+ return val >> amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_SRIGHT int_sright} on JVM int with long amt.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHR ishr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size fill the register with+ * the sign bit.+ *+ * @param val the value as in {@code val s>> amt}+ * @param amt the amt as in {@code val s>> amt}+ * @return the value+ */+ static int intSRight(int val, long amt) {+ if (Long.compareUnsigned(amt, Integer.SIZE) >= 0) {+ return val >> (Integer.SIZE - 1);+ }+ return val >> amt;+ }++ /**+ * The implementation of {@link PcodeOp#INT_SRIGHT int_sright} on JVM ints.+ *+ * <p>+ * The semantics here are subtly different than the JVM's {@link Opcodes#ISHR ishr}: 1) The+ * amount must be treated as unsigned. 2) Shifts in excess of val's size fill the register with+ * the sign bit.+ *+ * @param val the value as in {@code val s>> amt}+ * @param amt the amt as in {@code val s>> amt}+ * @return the value+ */+ static int intSRight(int val, int amt) {+ if (Long.compareUnsigned(amt, Integer.SIZE) >= 0) {+ return val >> (Integer.SIZE - 1);+ }+ return val >> amt;+ }++ /**+ * Get the language for the given string language ID+ *+ * <p>+ * This is called by generated static initializers.+ *+ * @param languageID the language ID+ * @return the language+ * @throws LanguageNotFoundException if the language is not found+ */+ static Language getLanguage(String languageID) throws LanguageNotFoundException {+ return DefaultLanguageService.getLanguageService().getLanguage(new LanguageID(languageID));+ }++ /**+ * Construct a contextreg value from the given language and hex value+ *+ * <p>+ * This is called by generated static initializers to pre-construct context values.+ *+ * @param language the language+ * @param value the value as a string of hexadecimal digits+ * @return the value+ */+ static RegisterValue createContext(Language language, String value) {+ return new RegisterValue(language.getContextBaseRegister(),+ new BigInteger(value, 16));+ }++ /**+ * Construct a varnode+ *+ * <p>+ * This is called by generated static initializers to pre-construct any varnodes it needs to+ * re-create, mostly for invoking userops with the Standard strategy.+ *+ * @param factory the language's address factory+ * @param space the name of the space+ * @param offset the byte offset+ * @param size the size (in bytes)+ * @return the varnode+ */+ static Varnode createVarnode(AddressFactory factory, String space, long offset, int size) {+ return new Varnode(factory.getAddressSpace(space).getAddress(offset), size);+ }++ /**+ * Get this instance's bound thread.+ *+ * <p>+ * The generator implements a standard getter. This is frequently used by other default methods+ * of this interface, which are in turn invoked by generated code.+ *+ * @return the thread+ */+ JitPcodeThread thread();++ /**+ * Set the bound thread's program counter and decode context.+ *+ * <p>+ * This is called during retirement, i.e., upon exiting a passage or entering a hazard. This+ * just converts things to the right type and invokes+ * {@link PcodeThread#overrideCounter(Address)} and+ * {@link PcodeThread#overrideContext(RegisterValue)}.+ *+ * @param counter the offset of the next instruction to execute+ * @param context the decode context for the next instruction+ */+ default void retireCounterAndContext(long counter, RegisterValue context) {+ JitPcodeThread thread = thread();+ Address pc = thread.getLanguage().getDefaultSpace().getAddress(counter);+ thread.overrideCounter(pc);+ if (context != null) {+ thread.overrideContext(context);+ }+ }++ /**+ * Retrieve a userop definition from the bound thread.+ *+ * <p>+ * This is invoked by generated constructors to retain a userop reference for later invocation.+ * Note that it is the userop as defined by the user or emulator, not any wrapper used during+ * decode or translation. Depending on the invocation strategy, this reference may be saved and+ * later used with {@link #invokeUserop(PcodeUseropDefinition, Varnode, Varnode[])}, or its+ * method and instance may be extracted and saved for Direct invocation later.+ *+ * @param name the name of the userop+ * @return the userop or {@code null}+ * @see JitDataFlowUseropLibrary+ */+ default PcodeUseropDefinition<byte[]> getUseropDefinition(String name) {+ return thread().getUseropLibrary().getUserops().get(name);+ }++ /**+ * Invoke the given userop on the bound thread with the given operands+ *+ * <p>+ * This is invoked by generated code in {@link JitCompiledPassage#run(int)} to invoke a userop+ * via the Standard strategy.+ *+ * @param userop the userop definition+ * @param output an optional output operand+ * @param inputs the input operands+ * @see JitDataFlowUseropLibrary+ * @see PcodeUseropDefinition#execute(PcodeExecutor, PcodeUseropLibrary, Varnode, List)+ */+ default void invokeUserop(PcodeUseropDefinition<byte[]> userop, Varnode output,+ Varnode[] inputs) {+ userop.execute(thread().getExecutor(), thread().getUseropLibrary(), output,+ Arrays.asList(inputs));+ }++ /**+ * Construct an exception when attempting to execute an "instruction" that could not be decoded.+ *+ * <p>+ * When the decoder encounters an error, instead of crashing immediately, it must consider that+ * execution may not actually reach the error, so it instead emits pseudo-instructions+ * describing the error. The translator then emits code that will invoke this method and throw+ * the result. Thus, we only crash if the erroneous condition is actually met.+ *+ * @param message the human-readable message+ * @param counter the program counter where the decode error was encountered+ * @return the exception, which should be thrown immediately+ */+ default DecodePcodeExecutionException createDecodeError(String message, long counter) {+ return new DecodePcodeExecutionException(message,+ thread().getLanguage().getDefaultSpace().getAddress(counter));+ }++ /**+ * Construct an exit slot for the given branch target+ *+ * <p>+ * This is invoked by generated constructors for each branch target that exits the passage. Each+ * is saved as a field and will be filled lazily with its chained entry point the first time the+ * branch is taken.+ *+ * @param target the target program counter+ * @param ctx the target decode context+ * @return the exit slot+ */+ default ExitSlot createExitSlot(long target, RegisterValue ctx) {+ return new ExitSlot(thread(), target, ctx);+ }++ /**+ * Get the chained entry point for the given exit point's target+ *+ * <p>+ * This is invoked by generated code in {@link JitCompiledPassage#run(int)} to take a branch+ * exiting the passage. The first time, the exit slot is lazily filled, possibly requiring+ * further JIT translation.+ *+ * @param slot the slot for the target of the branch we're taking+ * @return the chained entry point+ */+ static EntryPoint getChained(ExitSlot slot) {+ return slot.getChained();+ }++ /**+ * Invoke {@link JitPcodeThread#count(int, int)} for the bound thread+ *+ * @param instructions as in {@link JitPcodeThread#count(int, int)}+ * @param trailingOps as in {@link JitPcodeThread#count(int, int)}+ */+ default void count(int instructions, int trailingOps) {+ thread().count(instructions, trailingOps);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/tgt/JitCompiledPassageClass.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/tgt/JitCompiledPassageClass.javanew file mode 100644index 0000000000..b5f7ed89f7--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/tgt/JitCompiledPassageClass.java@@ -0,0 +1,124 @@+/* ###+ * 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.pcode.emu.jit.gen.tgt;++import java.lang.invoke.MethodHandle;+import java.lang.invoke.MethodHandles.Lookup;+import java.lang.invoke.MethodType;+import java.util.*;++import ghidra.pcode.emu.jit.*;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPointPrototype;++/**+ * A compiled passage that is not yet bound/instantiated to a thread.+ *+ * <p>+ * This is the output of {@link JitCompiler#compilePassage(Lookup, JitPassage)}, and it will be+ * cached (indirectly) by {@link JitPcodeEmulator}. The emulator actually caches the various entry+ * points returned by {@link #getBlockEntries()}. Each of those retains a reference to this object.+ * An {@link EntryPointPrototype} pairs this with a entry block ID. That prototype can then be+ * instantiated/bound to a thread, producing an {@link EntryPoint}. That bound entry point is+ * produced by invoking {@link #createInstance(JitPcodeThread)} and just copying the block id.+ *+ * <p>+ * This object wraps the generated (and now loaded) class and provides the mechanisms for reflecting+ * and processing the {@code ENTRIES} field, and for reflecting and invoking the generated+ * constructor. Note that explicit invocation of the static initializer via reflection is not+ * necessary.+ *+ * @param lookup the means of accessing the generated class's elements+ * @param cls the generated class as loaded into this JVM+ * @param constructor the reflected constructor having signature {@link #CONSTRUCTOR_TYPE}+ */+public record JitCompiledPassageClass(Lookup lookup, Class<? extends JitCompiledPassage> cls,+ MethodHandle constructor) {++ /**+ * The constructor signature: {@code Passage$at_[entry](JitPcodeThread)}+ */+ public static final MethodType CONSTRUCTOR_TYPE =+ MethodType.methodType(void.class, JitPcodeThread.class);++ /**+ * Load the generated class from the given bytes+ *+ * <p>+ * The bytes must define a class that implements {@link JitCompiledPassage}. It must define a+ * constructor having the signature {@link #CONSTRUCTOR_TYPE}, and it must define a static field+ * {@code List<AddrCtx> ENTRIES}.+ *+ * @param lookup a lookup that can see all the elements the generated class needs. Likely, this+ * should be from the emulator implementation, which may be an extension in a script.+ * @param bytes the classfile bytes+ * @return the wrapped class+ */+ public static JitCompiledPassageClass load(Lookup lookup, byte[] bytes) {+ try {+ Lookup defLookup = lookup.defineHiddenClass(bytes, true);+ @SuppressWarnings("unchecked")+ Class<? extends JitCompiledPassage> cls =+ (Class<? extends JitCompiledPassage>) defLookup.lookupClass();+ MethodHandle constructor = defLookup.findConstructor(cls, CONSTRUCTOR_TYPE);+ return new JitCompiledPassageClass(defLookup, cls, constructor);+ }+ catch (Exception e) {+ throw new AssertionError(e);+ }+ }++ /**+ * Create an instance bound to the given thread+ *+ * @param thread the thread+ * @return the instance, prepared to execute on the given thread+ */+ public JitCompiledPassage createInstance(JitPcodeThread thread) {+ try {+ return (JitCompiledPassage) constructor.invoke(thread);+ }+ catch (Throwable e) {+ throw new AssertionError(e);+ }+ }++ /**+ * Get the entry points for this compiled passage+ *+ * <p>+ * This processes the {@code ENTRIES} field, which is just a list of targets. The position of+ * each target in the list corresponds to the block id accepted by the generated+ * {@link JitCompiledPassage#run(int)} method.+ *+ * @return the map of targets to their corresponding entry point prototypes+ */+ public Map<AddrCtx, EntryPointPrototype> getBlockEntries() {+ try {+ MethodHandle getter = lookup.findStaticGetter(cls, "ENTRIES", List.class);+ List<AddrCtx> entries = (List<AddrCtx>) getter.invoke();+ Map<AddrCtx, EntryPointPrototype> result = new HashMap<>();+ for (int i = 0; i < entries.size(); i++) {+ result.put(entries.get(i), new EntryPointPrototype(this, i));+ }+ return result;+ }+ catch (Throwable e) {+ throw new AssertionError(e);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/DoubleReadGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/DoubleReadGen.javanew file mode 100644index 0000000000..15b88602fe--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/DoubleReadGen.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.pcode.emu.jit.gen.type;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType.DoubleJitType;+import ghidra.pcode.emu.jit.analysis.JitType.LongJitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for reading doubles+ *+ * <p>+ * This is accomplished by reading a long and then converting it.+ */+public enum DoubleReadGen implements TypedAccessGen {+ /** The big-endian instance */+ BE(LongReadGen.BE),+ /** The little-endian instance */+ LE(LongReadGen.LE);++ final LongReadGen longGen;++ private DoubleReadGen(LongReadGen longGen) {+ this.longGen = longGen;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ longGen.generateCode(gen, vn, rv);+ TypeConversions.generateLongToDouble(LongJitType.forSize(vn.getSize()), DoubleJitType.F8,+ rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/DoubleWriteGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/DoubleWriteGen.javanew file mode 100644index 0000000000..04bc6ff920--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/DoubleWriteGen.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.pcode.emu.jit.gen.type;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType.DoubleJitType;+import ghidra.pcode.emu.jit.analysis.JitType.LongJitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for writing doubles+ *+ * <p>+ * This is accomplished by converting to a long and then writing it.+ */+public enum DoubleWriteGen implements TypedAccessGen {+ /** The big-endian instance */+ BE(LongWriteGen.BE),+ /** The little-endian instance */+ LE(LongWriteGen.LE);++ final LongWriteGen longGen;++ private DoubleWriteGen(LongWriteGen longGen) {+ this.longGen = longGen;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ TypeConversions.generateDoubleToLong(DoubleJitType.F8, LongJitType.forSize(vn.getSize()),+ rv);+ longGen.generateCode(gen, vn, rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/ExportsLegAccessGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/ExportsLegAccessGen.javanew file mode 100644index 0000000000..2d035842a0--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/ExportsLegAccessGen.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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.BLOCK_SIZE;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.Varnode;++/**+ * A generator that exports part of its implementation for use in a {@link MpTypedAccessGen}.+ *+ * <p>+ * This really just avoids the re-creation of {@link Varnode} objects for each leg of a large+ * varnode. The method instead takes the (space,offset,size) triple as well as the offset of the+ * block containing its start.+ */+public interface ExportsLegAccessGen extends TypedAccessGen {+ /**+ * Emit code to access one JVM int, either a whole variable or one leg of a multi-precision int+ * variable.+ *+ * <p>+ * Legs that span blocks are handled as in+ * {@link #generateCode(JitCodeGenerator, Varnode, MethodVisitor)}.+ *+ *+ * @param gen the code generator+ * @param space the address space of the varnode+ * @param block the block offset containing the varnode (or leg)+ * @param off the offset of the varnode (or leg)+ * @param size the size of the varnode in bytes (or leg)+ * @param rv the method visitor+ */+ void generateMpCodeLeg(JitCodeGenerator gen, AddressSpace space, long block, int off,+ int size, MethodVisitor rv);++ @Override+ default void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ AddressSpace space = vn.getAddress().getAddressSpace();+ long offset = vn.getOffset();+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ int size = vn.getSize();+ generateMpCodeLeg(gen, space, block, off, size, rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/FloatReadGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/FloatReadGen.javanew file mode 100644index 0000000000..3e1ed83f63--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/FloatReadGen.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.pcode.emu.jit.gen.type;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType.FloatJitType;+import ghidra.pcode.emu.jit.analysis.JitType.IntJitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for reading floats+ *+ * <p>+ * This is accomplished by reading an int and then converting it.+ */+public enum FloatReadGen implements TypedAccessGen {+ /** The big-endian instance */+ BE(IntReadGen.BE),+ /** The little-endian instance */+ LE(IntReadGen.LE);++ final IntReadGen intGen;++ private FloatReadGen(IntReadGen intGen) {+ this.intGen = intGen;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ intGen.generateCode(gen, vn, rv);+ TypeConversions.generateIntToFloat(IntJitType.forSize(vn.getSize()), FloatJitType.F4, rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/FloatWriteGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/FloatWriteGen.javanew file mode 100644index 0000000000..7ac955615b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/FloatWriteGen.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.pcode.emu.jit.gen.type;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType.FloatJitType;+import ghidra.pcode.emu.jit.analysis.JitType.IntJitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for writing floats+ *+ * <p>+ * This is accomplished by converting to an int and then writing it.+ */+public enum FloatWriteGen implements TypedAccessGen {+ /** The big-endian instance */+ BE(IntWriteGen.BE),+ /** The little-endian instance */+ LE(IntWriteGen.LE);++ final IntWriteGen intGen;++ private FloatWriteGen(IntWriteGen intGen) {+ this.intGen = intGen;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ TypeConversions.generateFloatToInt(FloatJitType.F4, IntJitType.forSize(vn.getSize()), rv);+ intGen.generateCode(gen, vn, rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/IntReadGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/IntReadGen.javanew file mode 100644index 0000000000..744dc92199--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/IntReadGen.java@@ -0,0 +1,115 @@+/* ###+ * 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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.FieldForArrDirect;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;++/**+ * The generator for reading integers.+ */+public enum IntReadGen implements MethodAccessGen, ExportsLegAccessGen {+ /** The big-endian instance */+ BE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "readInt1";+ case 2 -> "readIntBE2";+ case 3 -> "readIntBE3";+ case 4 -> "readIntBE4";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateMpCodeLeg(JitCodeGenerator gen, AddressSpace space, long block,+ int off, int size, MethodVisitor rv) {+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ rv.visitLdcInsn(off + size - BLOCK_SIZE);+ rv.visitInsn(ISHL);++ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ rv.visitInsn(IOR);+ }+ },+ /** The little-endian instance */+ LE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "readInt1";+ case 2 -> "readIntLE2";+ case 3 -> "readIntLE3";+ case 4 -> "readIntLE4";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateMpCodeLeg(JitCodeGenerator gen, AddressSpace space, long block,+ int off, int size, MethodVisitor rv) {+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ rv.visitLdcInsn(BLOCK_SIZE - off);+ rv.visitInsn(ISHL);++ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__READ_INTX, true);+ rv.visitInsn(IOR);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/IntWriteGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/IntWriteGen.javanew file mode 100644index 0000000000..56563a3c57--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/IntWriteGen.java@@ -0,0 +1,115 @@+/* ###+ * 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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.FieldForArrDirect;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;++/**+ * The generator for writing integers.+ */+public enum IntWriteGen implements MethodAccessGen, ExportsLegAccessGen {+ /** The big-endian instance */+ BE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "writeInt1";+ case 2 -> "writeIntBE2";+ case 3 -> "writeIntBE3";+ case 4 -> "writeIntBE4";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateMpCodeLeg(JitCodeGenerator gen, AddressSpace space, long block,+ int off, int size, MethodVisitor rv) {+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ rv.visitInsn(DUP);+ rv.visitLdcInsn(off + size - BLOCK_SIZE);+ rv.visitInsn(IUSHR);+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);++ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);+ }+ },+ /** The little-endian instance */+ LE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "writeInt1";+ case 2 -> "writeIntLE2";+ case 3 -> "writeIntLE3";+ case 4 -> "writeIntLE4";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateMpCodeLeg(JitCodeGenerator gen, AddressSpace space, long block,+ int off, int size, MethodVisitor rv) {+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ rv.visitInsn(DUP);+ rv.visitLdcInsn(BLOCK_SIZE - off);+ rv.visitInsn(IUSHR);+ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);++ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_INTX, true);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/LongReadGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/LongReadGen.javanew file mode 100644index 0000000000..12a486949b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/LongReadGen.java@@ -0,0 +1,132 @@+/* ###+ * 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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.FieldForArrDirect;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for reading longs.+ */+public enum LongReadGen implements MethodAccessGen {+ /** The big-endian instance */+ BE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "readLong1";+ case 2 -> "readLongBE2";+ case 3 -> "readLongBE3";+ case 4 -> "readLongBE4";+ case 5 -> "readLongBE5";+ case 6 -> "readLongBE6";+ case 7 -> "readLongBE7";+ case 8 -> "readLongBE8";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ long offset = vn.getOffset();+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ int size = vn.getSize();+ AddressSpace space = vn.getAddress().getAddressSpace();+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__READ_LONGX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__READ_LONGX, true);+ rv.visitLdcInsn(off + size - BLOCK_SIZE);+ rv.visitInsn(LSHL);++ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__READ_LONGX, true);+ rv.visitInsn(LOR);+ }+ },+ /** The little-endian instance */+ LE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "readLong1";+ case 2 -> "readLongLE2";+ case 3 -> "readLongLE3";+ case 4 -> "readLongLE4";+ case 5 -> "readLongLE5";+ case 6 -> "readLongLE6";+ case 7 -> "readLongLE7";+ case 8 -> "readLongLE8";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ long offset = vn.getOffset();+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ int size = vn.getSize();+ AddressSpace space = vn.getAddress().getAddressSpace();+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__READ_LONGX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__READ_LONGX, true);+ rv.visitLdcInsn(BLOCK_SIZE - off);+ rv.visitInsn(LSHL);++ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__READ_LONGX, true);+ rv.visitInsn(LOR);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/LongWriteGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/LongWriteGen.javanew file mode 100644index 0000000000..d912ffe264--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/LongWriteGen.java@@ -0,0 +1,132 @@+/* ###+ * 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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.FieldForArrDirect;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.Varnode;++/**+ * Bytes writer for longs in big endian order.+ */+public enum LongWriteGen implements MethodAccessGen {+ /** The big-endian instance */+ BE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "writeLong1";+ case 2 -> "writeLongBE2";+ case 3 -> "writeLongBE3";+ case 4 -> "writeLongBE4";+ case 5 -> "writeLongBE5";+ case 6 -> "writeLongBE6";+ case 7 -> "writeLongBE7";+ case 8 -> "writeLongBE8";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ long offset = vn.getOffset();+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ int size = vn.getSize();+ AddressSpace space = vn.getAddress().getAddressSpace();+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ rv.visitInsn(DUP2);+ rv.visitInsn(off + size - BLOCK_SIZE);+ rv.visitInsn(LUSHR);+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX, true);++ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX, true);+ }+ },+ /** The little-endian instance */+ LE {+ @Override+ public String chooseName(int size) {+ return switch (size) {+ case 1 -> "writeLong1";+ case 2 -> "writeLongLE2";+ case 3 -> "writeLongLE3";+ case 4 -> "writeLongLE4";+ case 5 -> "writeLongLE5";+ case 6 -> "writeLongLE6";+ case 7 -> "writeLongLE7";+ case 8 -> "writeLongLE8";+ default -> throw new AssertionError();+ };+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ long offset = vn.getOffset();+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ int size = vn.getSize();+ AddressSpace space = vn.getAddress().getAddressSpace();+ FieldForArrDirect blkField = gen.requestFieldForArrDirect(space.getAddress(block));+ if (off + size <= BLOCK_SIZE) {+ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, chooseName(size),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX, true);+ return;+ }++ FieldForArrDirect nxtField =+ gen.requestFieldForArrDirect(space.getAddress(block + BLOCK_SIZE));+ rv.visitInsn(DUP2);+ rv.visitLdcInsn(BLOCK_SIZE - off);+ rv.visitInsn(LUSHR);+ nxtField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(0);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(off + size - BLOCK_SIZE), MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX, true);++ blkField.generateLoadCode(gen, rv);+ rv.visitLdcInsn(off);+ rv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE,+ chooseName(BLOCK_SIZE - off),+ MDESC_JIT_COMPILED_PASSAGE__WRITE_LONGX, true);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MethodAccessGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MethodAccessGen.javanew file mode 100644index 0000000000..8b6567d05e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MethodAccessGen.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.pcode.emu.jit.gen.type;++import ghidra.pcode.emu.jit.gen.op.LoadOpGen;+import ghidra.pcode.emu.jit.gen.op.StoreOpGen;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;++/**+ * A generator whose implementation is to emit invocations of a named method in+ * {@link JitCompiledPassage}.+ *+ * <p>+ * This is needed by {@link LoadOpGen} and {@link StoreOpGen}.+ */+public interface MethodAccessGen extends TypedAccessGen {+ /**+ * Choose the name of a method, e.g. {@link JitCompiledPassage#readInt1(byte[], int)} to use for+ * the given variable size.+ *+ * @param size the size in bytes+ * @return the name of the method+ */+ String chooseName(int size);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpIntReadGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpIntReadGen.javanew file mode 100644index 0000000000..dc4b744f0f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpIntReadGen.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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.BLOCK_SIZE;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for reading multi-precision ints.+ */+public enum MpIntReadGen implements MpTypedAccessGen {+ /** The big-endian instance */+ BE {+ @Override+ public IntReadGen getLegGen() {+ return IntReadGen.BE;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ ExportsLegAccessGen legGen = getLegGen();++ AddressSpace space = vn.getAddress().getAddressSpace();+ int countFull = vn.getSize() / Integer.BYTES;+ int remSize = vn.getSize() % Integer.BYTES;+ long offset = vn.getOffset();+ if (remSize > 0) {+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, remSize, rv);+ offset += remSize;+ }+ for (int i = 0; i < countFull; i++) {+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, Integer.BYTES, rv);+ offset += Integer.BYTES;+ }+ }+ },+ /** The little-endian instance */+ LE {+ @Override+ public IntReadGen getLegGen() {+ return IntReadGen.LE;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ ExportsLegAccessGen legGen = getLegGen();++ AddressSpace space = vn.getAddress().getAddressSpace();+ int countFull = vn.getSize() / Integer.BYTES;+ int remSize = vn.getSize() % Integer.BYTES;+ long offset = vn.getOffset() + vn.getSize();+ if (remSize > 0) {+ offset -= remSize;+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, remSize, rv);+ }+ for (int i = 0; i < countFull; i++) {+ offset -= Integer.BYTES;+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, Integer.BYTES, rv);+ }+ }+ };++ @Override+ public abstract IntReadGen getLegGen();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpIntWriteGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpIntWriteGen.javanew file mode 100644index 0000000000..3bb76b84d1--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpIntWriteGen.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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.BLOCK_SIZE;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.Varnode;++/**+ * The generator for writing multi-precision ints.+ */+public enum MpIntWriteGen implements MpTypedAccessGen {+ /** The big-endian instance */+ BE {+ @Override+ public IntWriteGen getLegGen() {+ return IntWriteGen.BE;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ ExportsLegAccessGen legGen = getLegGen();++ // Stack semantics, so must work in reverse of read+ AddressSpace space = vn.getAddress().getAddressSpace();+ int countFull = vn.getSize() / Integer.BYTES;+ int remSize = vn.getSize() % Integer.BYTES;+ long offset = vn.getOffset() + vn.getSize();+ for (int i = 0; i < countFull; i++) {+ offset -= Integer.BYTES;+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, Integer.BYTES, rv);+ }+ if (remSize > 0) {+ offset -= remSize;+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, remSize, rv);+ }+ }+ },+ /** The little-endian instance */+ LE {+ @Override+ public IntWriteGen getLegGen() {+ return IntWriteGen.LE;+ }++ @Override+ public void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv) {+ ExportsLegAccessGen legGen = getLegGen();++ // Stack semantics, so must work in reverse of read+ AddressSpace space = vn.getAddress().getAddressSpace();+ int countFull = vn.getSize() / Integer.BYTES;+ int remSize = vn.getSize() % Integer.BYTES;+ long offset = vn.getOffset();+ for (int i = 0; i < countFull; i++) {+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, Integer.BYTES, rv);+ offset += Integer.BYTES;+ }+ if (remSize > 0) {+ long block = offset / BLOCK_SIZE * BLOCK_SIZE;+ int off = (int) (offset - block);+ legGen.generateMpCodeLeg(gen, space, block, off, remSize, rv);+ offset += remSize;+ }+ }+ };++ @Override+ public abstract IntWriteGen getLegGen();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpTypedAccessGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpTypedAccessGen.javanew file mode 100644index 0000000000..64ba908239--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/MpTypedAccessGen.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.pcode.emu.jit.gen.type;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.Varnode;++/**+ * A generator for a multi-precision integer type.+ *+ * <p>+ * This depends on the generator for single integer types. Each will need to work out how to compose+ * the leg generator given the stack ordering, byte order, and read/write operation.+ */+public interface MpTypedAccessGen extends TypedAccessGen {+ /**+ * Get a generator for individual legs of this multi-precision access generator+ *+ * @return the leg generator+ */+ ExportsLegAccessGen getLegGen();++ /**+ * {@inheritDoc}+ *+ * <p>+ * This uses several JVM stack entries. The varnode must be too large to fit in a single JVM+ * primitive, or else it does not require "multi-precision" handling. A leg that spans blocks is+ * handled as in+ * {@link ExportsLegAccessGen#generateMpCodeLeg(JitCodeGenerator, AddressSpace, long, int, int, MethodVisitor)}.+ * The legs are ordered on the stack such that the least significant portion is on top.+ *+ * @param gen the code generator+ * @param vn the varnode+ * @param rv the method visitor+ */+ @Override+ void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/TypeConversions.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/TypeConversions.javanew file mode 100644index 0000000000..b8c1435bfd--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/TypeConversions.java@@ -0,0 +1,830 @@+/* ###+ * 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.pcode.emu.jit.gen.type;++import static ghidra.pcode.emu.jit.gen.GenConsts.*;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.*;++import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.op.BinOpGen;+import ghidra.pcode.emu.jit.gen.op.IntSExtOpGen;+import ghidra.pcode.emu.jit.op.JitBinOp;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The generator for various type conversion.+ *+ * <p>+ * These conversions are no more than bitwise casts. The underlying bits are unchanged, but the+ * interpretation and/or the way the JVM has tagged them does.+ *+ * <p>+ * Many of the methods (and also many other bits of the code generator) follow a convention where+ * the input type(s) are passed as parameter(s), and the resulting type is returned. In many cases+ * the desired type is also taken as a parameter. Upon success, we'd expect that desired type to be+ * the exact type returned, but this may not always be the case. This convention ensures all pieces+ * of the generator know the p-code type (and thus JVM type) of the variable at the top of the JVM+ * stack.+ *+ * <p>+ * Type conversions are applicable at a few boundaries:+ * <ul>+ * <li>To ensure use-def values conform to the requirements of the operands where they are used and+ * defined. The {@link JitTypeModel} aims to reduce the number of conversions required by assigning+ * appropriate types to the use-def value nodes, but this will not necessarily eliminate them+ * all.</li>+ * <li>Within the implementation of an operator, type conversions may be necessary to ensure the+ * p-code types of input operands conform with the JVM types required by the emitted bytecodes, and+ * that the output JVM type conforms to the p-code type of the output operand.</li>+ * <li>When loading or storing as bytes from the {@link JitBytesPcodeExecutorState state}. The+ * conversion from and to bytes is done using JVM integral types, and so the value may be converted+ * if the operand requires a floating-point type.</li>+ * </ul>+ */+public interface TypeConversions {+ /**+ * Emit an {@link Opcodes#IAND} to reduce the number of bits to those permitted in an int of the+ * given size.+ *+ * <p>+ * For example to mask from an {@link IntJitType#I4 int4} to an {@link IntJitType#I2}, this+ * would emit {@code iand 0xffff}. If the source size is smaller than or equal to that of the+ * destination, nothing is emitted.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ */+ static void checkGenIntMask(JitType from, IntJitType to, MethodVisitor mv) {+ if (to.size() < from.size() && to.size() < Integer.BYTES) {+ mv.visitLdcInsn(-1 >>> (Integer.SIZE - to.size() * Byte.SIZE));+ mv.visitInsn(IAND);+ }+ }++ /**+ * Emit bytecode to convert one p-code in (in a JVM int) to another+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static IntJitType generateIntToInt(IntJitType from, IntJitType to, MethodVisitor mv) {+ checkGenIntMask(from, to, mv);+ return to;+ }++ /**+ * Emit bytecode to convert one p-code int (in a JVM long) to one in a JVM int.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static IntJitType generateLongToInt(LongJitType from, IntJitType to, MethodVisitor mv) {+ mv.visitInsn(L2I);+ checkGenIntMask(from, to, mv);+ return to;+ }++ /**+ * Emit bytecode to convert a {@link FloatJitType#F4 float4} to an {@link IntJitType#I4 int4}.+ *+ * @param from the source type (must be {@link FloatJitType#F4 float4})+ * @param to the destination type (must be {@link IntJitType#I4 int4})+ * @param mv the method visitor+ * @return the destination type ({@link IntJitType#I4 int4})+ */+ static IntJitType generateFloatToInt(FloatJitType from, IntJitType to, MethodVisitor mv) {+ if (to.size() != from.size()) {+ throw new AssertionError("Size mismatch");+ }+ mv.visitMethodInsn(INVOKESTATIC, NAME_FLOAT, "floatToRawIntBits",+ MDESC_FLOAT__FLOAT_TO_RAW_INT_BITS, false);+ return to;+ }++ /**+ * Emit bytecode to convert a mult-precision int to a p-code int that fits in a JVM int.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static IntJitType generateMpIntToInt(MpIntJitType from, IntJitType to, MethodVisitor mv) {+ if (to.size() == from.size()) {+ // We're done. The one leg on the stack becomes the int+ return to;+ }+ // Remove all but the least-significant leg+ for (int i = 1; i < from.legsAlloc(); i++) {+ // [...,legN-1,legN]+ mv.visitInsn(SWAP);+ // [...,legN,legN-1]+ mv.visitInsn(POP);+ // [...,legN]+ }+ checkGenIntMask(from, to, mv);+ return to;+ }++ /**+ * Emit bytecode to convert any (compatible) type to a p-code int that fits in a JVM int.+ *+ * <p>+ * The only acceptable floating-point source type is {@link FloatJitType#F4 float4}.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static IntJitType generateToInt(JitType from, IntJitType to, MethodVisitor mv) {+ return switch (from) {+ case IntJitType iFrom -> generateIntToInt(iFrom, to, mv); // in case of mask+ case LongJitType lFrom -> generateLongToInt(lFrom, to, mv);+ case FloatJitType fFrom -> generateFloatToInt(fFrom, to, mv);+ case DoubleJitType dFrom -> throw new AssertionError("Size mismatch");+ case MpIntJitType mpFrom -> generateMpIntToInt(mpFrom, to, mv);+ default -> throw new AssertionError();+ };+ }++ /**+ * Emit an {@link Opcodes#LAND} to reduce the number of bits to those permitted in an int of the+ * given size.+ *+ * <p>+ * For example to mask from a {@link LongJitType#I8 int8} to a {@link LongJitType#I6}, this+ * would emit {@code land 0x0ffffffffffffL}. If the source size is smaller than or equal to that+ * of the destination, nothing is emitted.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ */+ static void checkGenLongMask(JitType from, LongJitType to, MethodVisitor mv) {+ if (to.size() < from.size()) {+ mv.visitLdcInsn(-1L >>> (Long.SIZE - to.size() * Byte.SIZE));+ mv.visitInsn(LAND);+ }+ }++ /**+ * Emit bytecode to convert one p-code int (in a JVM int) to one in a JVM long.+ *+ * <p>+ * Care must be taken to ensure conversions to larger types extend with zeros (unsigned).+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static LongJitType generateIntToLong(IntJitType from, LongJitType to, MethodVisitor mv) {+ mv.visitMethodInsn(INVOKESTATIC, NAME_INTEGER, "toUnsignedLong",+ MDESC_INTEGER__TO_UNSIGNED_LONG, false);+ // In theory, never necessary, unless long is used temporarily with size 1-4.+ checkGenLongMask(from, to, mv);+ return to;+ }++ /**+ * Emit bytecode to convert one p-code in (in a JVM long) to another+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static LongJitType generateLongToLong(LongJitType from, LongJitType to, MethodVisitor mv) {+ checkGenLongMask(from, to, mv);+ return to;+ }++ /**+ * Emit bytecode to convert a {@link DoubleJitType#F8 float8} to an {@link LongJitType#I8 int8}.+ *+ * @param from the source type (must be {@link DoubleJitType#F8 float8})+ * @param to the destination type (must be {@link LongJitType#I8 int8})+ * @param mv the method visitor+ * @return the destination type ({@link LongJitType#I8 int8})+ */+ static LongJitType generateDoubleToLong(DoubleJitType from, LongJitType to, MethodVisitor mv) {+ if (to.size() != from.size()) {+ throw new AssertionError("Size mismatch");+ }+ mv.visitMethodInsn(INVOKESTATIC, NAME_DOUBLE, "doubleToRawLongBits",+ MDESC_DOUBLE__DOUBLE_TO_RAW_LONG_BITS, false);+ return to;+ }++ /**+ * Emit bytecode to convert a mult-precision int to a p-code int that fits in a JVM long.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static LongJitType generateMpIntToLong(MpIntJitType from, LongJitType to, MethodVisitor mv) {+ if (from.legsAlloc() == 1) {+ generateIntToLong(IntJitType.forSize(from.size()), to, mv);+ return to;+ }+ // Remove all but the 2 least-significant legs+ for (int i = 2; i < from.legsAlloc(); i++) {+ // [...,legN-2,legN-1,legN]+ mv.visitInsn(DUP2_X1);+ // [...,legN-1,legN,legN-2,legN-1,legN]+ mv.visitInsn(POP2);+ // [...,legN-1,legN,legN-2]+ mv.visitInsn(POP);+ // [...,legN-1,legN]+ }+ mv.visitMethodInsn(INVOKESTATIC, NAME_JIT_COMPILED_PASSAGE, "conv2IntToLong",+ MDESC_JIT_COMPILED_PASSAGE__CONV_OFFSET2_TO_LONG, false);+ return to;+ }++ /**+ * Emit bytecode to convert any (compatible) type to a p-code that fits in a JVM long.+ *+ * <p>+ * The only acceptable floating-point source type is {@link DoubleJitType#F8 float8}.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static LongJitType generateToLong(JitType from, LongJitType to, MethodVisitor mv) {+ return switch (from) {+ case IntJitType iFrom -> generateIntToLong(iFrom, to, mv);+ case LongJitType lFrom -> generateLongToLong(lFrom, to, mv); // in case of mask+ case FloatJitType fFrom -> throw new AssertionError("Size mismatch");+ case DoubleJitType dFrom -> generateDoubleToLong(dFrom, to, mv);+ case MpIntJitType mpFrom -> generateMpIntToLong(mpFrom, to, mv);+ default -> throw new AssertionError();+ };+ }++ /**+ * Emit bytecode to convert an {@link IntJitType#I4 int4} to a {@link FloatJitType#F4 float4}.+ *+ * @param from the source type (must be {@link IntJitType#I4 int4})+ * @param to the destination type (must be {@link FloatJitType#F4 float4})+ * @param mv the method visitor+ * @return the destination type ({@link FloatJitType#F4 float4})+ */+ static FloatJitType generateIntToFloat(IntJitType from, FloatJitType to, MethodVisitor mv) {+ if (to.size() != from.size()) {+ throw new AssertionError("Size mismatch");+ }+ mv.visitMethodInsn(INVOKESTATIC, NAME_FLOAT, "intBitsToFloat",+ MDESC_FLOAT__INT_BITS_TO_FLOAT, false);+ return to;+ }++ /**+ * Emit bytecode to convert any (compatible) type to a {@link FloatJitType#F4 float4}.+ *+ * @param from the source type ({@link IntJitType#I4 int4} or {@link FloatJitType#F4 float4})+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type ({@link FloatJitType#F4 float4})+ */+ static FloatJitType generateToFloat(JitType from, FloatJitType to, MethodVisitor mv) {+ return switch (from) {+ case IntJitType iFrom -> generateIntToFloat(iFrom, to, mv);+ case LongJitType lFrom -> throw new AssertionError("Size mismatch");+ case FloatJitType fFrom -> to;+ case DoubleJitType dFrom -> throw new AssertionError("Size mismatch");+ case MpIntJitType mpFrom -> throw new AssertionError("Size mismatch");+ default -> throw new AssertionError();+ };+ }++ /**+ * Emit bytecode to convert an {@link LongJitType#I8 int8} to a {@link DoubleJitType#F8 float8}.+ *+ * @param from the source type (must be {@link LongJitType#I8 int8})+ * @param to the destination type (must be {@link DoubleJitType#F8 float8})+ * @param mv the method visitor+ * @return the destination type ({@link DoubleJitType#F8 float8})+ */+ static DoubleJitType generateLongToDouble(LongJitType from, DoubleJitType to,+ MethodVisitor mv) {+ if (to.size() != from.size()) {+ throw new AssertionError("Size mismatch");+ }+ mv.visitMethodInsn(INVOKESTATIC, NAME_DOUBLE, "longBitsToDouble",+ MDESC_DOUBLE__LONG_BITS_TO_DOUBLE, false);+ return to;+ }++ /**+ * Emit bytecode to convert any (compatible) type to a {@link DoubleJitType#F8 float8}.+ *+ * @param from the source type ({@link LongJitType#I8 int8} or {@link DoubleJitType#F8 float8})+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type ({@link DoubleJitType#F8 float8})+ */+ static DoubleJitType generateToDouble(JitType from, DoubleJitType to, MethodVisitor mv) {+ return switch (from) {+ case IntJitType iFrom -> throw new AssertionError("Size mismatch");+ case LongJitType lFrom -> generateLongToDouble(lFrom, to, mv);+ case FloatJitType fFrom -> throw new AssertionError("Size mismatch");+ case DoubleJitType dFrom -> to;+ case MpIntJitType mpFrom -> throw new AssertionError("Size mismatch");+ default -> throw new AssertionError();+ };+ }++ /**+ * Emit bytecode to convert a p-code int that fits in a JVM int to a multi-precision int.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static MpIntJitType generateIntToMpInt(IntJitType from, MpIntJitType to, MethodVisitor mv) {+ if (to.legsAlloc() == 1) {+ checkGenIntMask(from, IntJitType.forSize(to.size()), mv);+ return to;+ }+ // Insert as many more significant legs as needed+ for (int i = 1; i < to.legsAlloc(); i++) {+ mv.visitLdcInsn(0);+ mv.visitInsn(SWAP);+ }+ return to;+ }++ /**+ * Emit bytecode to convert a p-code int that its int a JVM long to multi-precision int.+ *+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static MpIntJitType generateLongToMpInt(LongJitType from, MpIntJitType to, MethodVisitor mv) {+ if (to.legsAlloc() == 1) {+ mv.visitInsn(L2I);+ checkGenIntMask(from, IntJitType.forSize(to.size()), mv);+ return to;+ }+ if (from.size() <= Integer.BYTES) {+ mv.visitInsn(L2I);+ generateIntToMpInt(IntJitType.forSize(from.size()), to, mv);+ return to;+ }+ // Convert, then insert as many more significant legs as needed++ /** Can't just invoke a static method, because two ints have to result */+ // [val:LONG]+ mv.visitInsn(DUP2);+ // [val:LONG,val:LONG]+ mv.visitLdcInsn(Integer.SIZE);+ mv.visitInsn(LUSHR);+ mv.visitInsn(L2I);+ /** This is the upper leg, which may need masking */+ checkGenIntMask(IntJitType.forSize(from.size() - Integer.BYTES),+ IntJitType.forSize(to.partialSize()), mv);+ // [val:LONG,msl:INT]+ mv.visitInsn(DUP_X2);+ // [msl:INT,val:LONG,msl:INT]+ mv.visitInsn(POP);+ // [msl:INT,val:LONG]+ mv.visitInsn(L2I);+ // [msl:INT,lsl:INT]++ // Now add legs+ if (to.legsAlloc() > 2) {+ mv.visitLdcInsn(0);+ // [msl:INT,lsl:INT,0]+ for (int i = 2; i < to.legsAlloc(); i++) {+ // [msl:INT,lsl:INT,0]+ mv.visitInsn(DUP_X2);+ // [0,msl:INT,lsl:INT,0]+ }+ // [...,0,msl:INT,lsl:INT,0]+ mv.visitInsn(POP);+ // [...,0,msl:INT,lsl:INT]+ }+ return to;+ }++ /**+ * Emit bytecode to convert a mult-precision int from one size to another+ *+ * @param gen the code generator+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static MpIntJitType generateMpIntToMpInt(JitCodeGenerator gen, MpIntJitType from,+ MpIntJitType to, MethodVisitor mv) {+ if (to.size() == from.size()) {+ // Nothing to convert+ return to;+ }+ // Some special cases to avoid use of local variables:+ if (to.legsAlloc() == 1) {+ generateMpIntToInt(from, IntJitType.forSize(to.size()), mv);+ return to;+ }+ if (from.legsAlloc() == 1) {+ generateIntToMpInt(IntJitType.forSize(from.size()), to, mv);+ return to;+ }++ // Okay, now it's complicated+ int legsIn = from.legsAlloc();+ int legsOut = to.legsAlloc();+ int localsCount = Integer.min(legsIn, legsOut);+ int firstIndex = gen.getAllocationModel().nextFreeLocal();+ Label localsStart = new Label();+ Label localsEnd = new Label();+ mv.visitLabel(localsStart);+ for (int i = 0; i < localsCount; i++) {+ mv.visitLocalVariable("temp" + i, Type.getDescriptor(int.class), null, localsStart,+ localsEnd, firstIndex + i);+ mv.visitVarInsn(ISTORE, firstIndex + i);+ }++ // Add or remove legs+ int toAdd = legsOut - legsIn;+ for (int i = 0; i < toAdd; i++) {+ mv.visitLdcInsn(0);+ }+ int toRemove = legsIn - legsOut;+ for (int i = 0; i < toRemove; i++) {+ mv.visitInsn(POP);+ }++ // Start pushing them back, but the most significant may need masking+ int idx = firstIndex + localsCount;+ idx--;+ mv.visitVarInsn(ILOAD, idx);+ if (to.size() < from.size()) {+ checkGenIntMask(+ from, // already checked size, so anything greater+ IntJitType.forSize(to.partialSize()), mv);+ }+ // push the rest back+ for (int i = 0; i < localsCount; i++) {+ idx--;+ mv.visitVarInsn(ILOAD, idx);+ }++ mv.visitLabel(localsEnd);+ return to;+ }++ /**+ * Emit bytecode to convert any (compatible) type to a p-code int that fits in a JVM int.+ *+ * <p>+ * No floating-point source types are currently acceptable. Support for floats of size other+ * than 4 and 8 bytes is a work in progress.+ *+ * @param gen the code generator+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the destination type+ */+ static MpIntJitType generateToMpInt(JitCodeGenerator gen, JitType from, MpIntJitType to,+ MethodVisitor mv) {+ return switch (from) {+ case IntJitType iFrom -> generateIntToMpInt(iFrom, to, mv);+ case LongJitType lFrom -> generateLongToMpInt(lFrom, to, mv);+ case FloatJitType fFrom -> throw new AssertionError("Size mismatch");+ case DoubleJitType dFrom -> throw new AssertionError("Size mismatch");+ case MpIntJitType mpFrom -> generateMpIntToMpInt(gen, mpFrom, to, mv);+ default -> throw new AssertionError();+ };+ }++ /**+ * Emit bytecode to convert the value on top of the JVM stack from one p-code type to another.+ *+ * <p>+ * If the source and destination are already of the same type, or if conversion between them+ * does not require any bytecode, then no bytecode is emitted.+ *+ * @param gen the code generator+ * @param from the source type+ * @param to the destination type+ * @param mv the method visitor+ * @return the resulting (destination) type+ */+ static JitType generate(JitCodeGenerator gen, JitType from, JitType to, MethodVisitor mv) {+ return switch (to) {+ case IntJitType iTo -> generateToInt(from, iTo, mv);+ case LongJitType lTo -> generateToLong(from, lTo, mv);+ case FloatJitType fTo -> generateToFloat(from, fTo, mv);+ case DoubleJitType dTo -> generateToDouble(from, dTo, mv);+ case MpIntJitType mpTo -> generateToMpInt(gen, from, mpTo, mv);+ default -> throw new AssertionError();+ };+ }++ /**+ * Collapse an mp-int or long to a single int.+ *+ * <p>+ * If and only if the input is all zeros will the output also be all zeros. Otherwise, the+ * output can be any non-zero value.+ *+ * <p>+ * There is no explicit "{@code boolean}" p-code type. Instead, like C, many of the operators+ * take an {@link JitTypeBehavior#INTEGER int} type and require "false" to be represented by the+ * value 0. Any non-zero value is interpreted as "true." That said, conventionally, all p-code+ * booleans ought to be an {@link IntJitType#I1 int1} where "true" is represented by 1 and+ * "false" is represented by 0. The p-code operators that output "boolean" values are all+ * implemented to follow this convention, except that size is determined by the Slaspec author.+ *+ * <p>+ * This conversion deals with input operands used as booleans that do not conform to these+ * conventions. If, e.g., a {@link PcodeOp#CBRANCH cbranch} is given a condition operand of type+ * {@link LongJitType#I8 int8}, we have to ensure that all bits, not just the lower 32, are+ * considered. This is trivially accomplished by pushing {@code 0L} and emitting an+ * {@link #LCMP}, which consumes the JVM long and replaces it with a JVM int representing the+ * same boolean value. For multi-precision ints, we reduce all the legs using {@link #IOR}. If a+ * float is used as a boolean, it must be converted to an int first.+ *+ * @param from the type of the value currently on the stack+ * @param size the size in bytes of the value on the stack+ * @param mv the method visitor+ * @see #generateLdcFalse(JitType, MethodVisitor)+ * @see #generateLdcTrue(JitType, MethodVisitor)+ */+ static void generateIntToBool(JitType from, MethodVisitor mv) {+ switch (from) {+ case IntJitType iFrom -> {+ }+ case LongJitType lFrom -> {+ mv.visitLdcInsn(0L);+ mv.visitInsn(LCMP);+ }+ case MpIntJitType(int size) -> {+ for (int i = 0; i < size - Integer.BYTES; i += Integer.BYTES) {+ mv.visitInsn(IOR);+ }+ }+ default -> throw new AssertionError();+ }+ }++ /**+ * Remove a value of the given type from the JVM stack.+ *+ * <p>+ * Depending on the type, we must emit either {@link #POP} or {@link #POP2}. This is used to+ * ignore an input or drop an output. For example, the boolean operators may short circuit+ * examination of the second operand, in which case it must be popped. Also, if a userop returns+ * a value, but the p-code does not provide an output operand, the return value must be popped.+ *+ * @param type the type+ * @param mv the method visitor+ */+ static void generatePop(JitType type, MethodVisitor mv) {+ switch (type) {+ case IntJitType iType -> mv.visitInsn(POP);+ case LongJitType lType -> mv.visitInsn(POP2);+ case FloatJitType fType -> mv.visitInsn(POP);+ case DoubleJitType dType -> mv.visitInsn(POP2);+ case MpIntJitType(int size) -> {+ for (int i = 0; i < size; i += Integer.BYTES) {+ mv.visitInsn(POP);+ }+ }+ case MpFloatJitType(int size) -> Unfinished.TODO("MpFloat");+ default -> throw new AssertionError();+ }+ }++ /**+ * Generate a "boolean" true value of the given type+ *+ * <p>+ * This performs the inverse of {@link #generateIntToBool(JitType, MethodVisitor)}, but for the+ * constant "true." Instead of loading a constant 1 into an {@link IntJitType#I1 int1} and then+ * converting to the desired type, this can just load the constant 1 directly as the desired+ * type.+ *+ * <p>+ * This is often used with conditional jumps to produce a boolean output.+ *+ * @param type an integer type+ * @param mv the method visitor+ * @see #generateLdcFalse(JitType, MethodVisitor)+ * @see #generateIntToBool(JitType, MethodVisitor)+ */+ static void generateLdcTrue(JitType type, MethodVisitor mv) {+ switch (type) {+ case IntJitType iType -> mv.visitLdcInsn(1);+ case LongJitType lType -> mv.visitLdcInsn(1L);+ case MpIntJitType(int size) -> {+ for (int i = 0; i < size - Integer.BYTES; i += Integer.BYTES) {+ mv.visitLdcInsn(0);+ }+ mv.visitLdcInsn(1);+ }+ default -> throw new AssertionError();+ }+ }++ /**+ * Generate a "boolean" false value of the given type+ *+ * <p>+ * This performs the inverse of {@link #generateIntToBool(JitType, MethodVisitor)}, but for the+ * constant "false." Instead of loading a constant 0 into an {@link IntJitType#I1 int1} and then+ * converting to the desired type, this can just load the constant 0 directly as the desired+ * type.+ *+ * <p>+ * This is often used with conditional jumps to produce a boolean output.+ *+ * @param type an integer type+ * @param mv the method visitor+ * @see #generateLdcFalse(JitType, MethodVisitor)+ * @see #generateIntToBool(JitType, MethodVisitor)+ */+ static void generateLdcFalse(JitType type, MethodVisitor mv) {+ switch (type) {+ case IntJitType iType -> mv.visitLdcInsn(0);+ case LongJitType lType -> mv.visitLdcInsn(0L);+ case MpIntJitType(int size) -> {+ for (int i = 0; i < size; i += Integer.BYTES) {+ mv.visitLdcInsn(0);+ }+ }+ default -> throw new AssertionError();+ }+ }++ /**+ * Emit code to extend a signed value of the given type to fill its host JVM type.+ *+ * <p>+ * This is implemented in the same manner as {@link IntSExtOpGen int_sext}.+ *+ * @param type the p-code type+ * @param mv the method visitor+ * @return the p-code type that exactly fits the host JVM type, i.e., the resulting p-code type.+ */+ static JitType generateSExt(JitType type, MethodVisitor mv) {+ switch (type) {+ case IntJitType(int size) -> {+ int shamt = Integer.SIZE - size * Byte.SIZE;+ if (shamt != 0) {+ mv.visitLdcInsn(shamt);+ mv.visitInsn(ISHL);+ mv.visitLdcInsn(shamt);+ mv.visitInsn(ISHR);+ }+ }+ case LongJitType(int size) -> {+ int shamt = Long.SIZE - size * Byte.SIZE;+ if (shamt != 0) {+ mv.visitLdcInsn(shamt);+ mv.visitInsn(LSHL);+ mv.visitLdcInsn(shamt);+ mv.visitInsn(LSHR);+ }+ }+ default -> throw new AssertionError();+ }+ return type.ext();+ }++ /**+ * Convert a signed {@link IntJitType#I4 int4} to {@link LongJitType#I8 int8}.+ *+ * <p>+ * Note that if conversion from a smaller int type is needed, the generator must first call+ * {@link #generateSExt(JitType, MethodVisitor)}.+ *+ * @param mv the method visitor+ * @return the resulting type ({@link LongJitType#I8 int8})+ */+ static LongJitType generateSExtIntToLong(MethodVisitor mv) {+ mv.visitInsn(I2L);+ return LongJitType.I8;+ }++ /**+ * Select the larger of two types and emit code to convert an unsigned value of the first type+ * to the host JVM type of the selected type.+ *+ * <p>+ * JVM bytecodes for binary operators often require that both operands have the same size.+ * Consider that the JVM provides a {@link #IADD} and a {@link #LADD}, but no "{@code ILADD}".+ * Both operands must be JVM ints, or both must be JVM longs. This method provides an idiom for+ * converting both operands to the same type. Ideally, we choose the smallest type possible (as+ * opposed to just converting everything to long always), but we must choose a type large enough+ * to accommodate the larger of the two p-code operands.+ *+ * <p>+ * For a binary operator requiring type uniformity, we must apply this method immediately after+ * loading each operand onto the stack. That operand's type is passed as {@code myType} and the+ * type of the other operand as {@code otherType}. Consider the left operand. We must override+ * {@link BinOpGen#afterLeft(JitCodeGenerator, JitBinOp, JitType, JitType, MethodVisitor)+ * afterLeft} if we're using {@link BinOpGen}. If the left type is the larger, then we select it+ * and we need only extend the left operand to fill its host JVM type. (We'll deal with the+ * right operand in a moment.) If the right type is larger, then we select it and we extend the+ * left to fill <em>the right's</em> host JVM type. We then return the resulting left type so+ * that we'll know what it was when emitting the actual operator bytecodes. Things work+ * similarly for the right operand, which we handle within+ * {@link BinOpGen#generateBinOpRunCode(JitCodeGenerator, JitBinOp, JitBlock, JitType, JitType, MethodVisitor)+ * generateBinOpRunCode} if we're using it. The two resulting types should now be equal, and we+ * can examine them and emit the correct bytecodes.+ *+ * @param myType the type of an operand, probably in a binary operator+ * @param otherType the type of the other operand of a binary operator+ * @param mv the method visitor+ * @return the new type of the operand+ */+ static JitType forceUniformZExt(JitType myType, JitType otherType, MethodVisitor mv) {+ return switch (myType.ext()) {+ case IntJitType mt -> switch (otherType.ext()) {+ case IntJitType ot -> mt;+ case LongJitType ot -> generateIntToLong(mt, ot, mv);+ case MpIntJitType ot -> generateIntToMpInt(mt, MpIntJitType.forSize(mt.size()),+ mv);+ default -> throw new AssertionError();+ };+ case LongJitType mt -> switch (otherType) {+ case IntJitType ot -> mt; // Other operand needs up-conversion+ case LongJitType ot -> mt;+ case MpIntJitType ot -> generateLongToMpInt(mt, MpIntJitType.forSize(mt.size()),+ mv);+ default -> throw new AssertionError();+ };+ case MpIntJitType mt -> mt; // Other may need up-conversion+ default -> throw new AssertionError();+ };+ }++ /**+ * Do the same as {@link #forceUniformZExt(JitType, JitType, MethodVisitor)}, but with signed+ * values.+ *+ * @param myType the type of an operand, probably in a binary operator+ * @param otherType the type of the other operand of a binary operator+ * @param mv the method visitor+ * @return the new type of the operand+ */+ static JitType forceUniformSExt(JitType myType, JitType otherType, MethodVisitor mv) {+ JitType myExtType = generateSExt(myType, mv);+ return switch (myExtType) {+ case IntJitType mt -> switch (otherType.ext()) { // Don't extend other, yet+ case IntJitType ot -> mt;+ case LongJitType ot -> generateSExtIntToLong(mv);+ case MpIntJitType ot -> generateIntToMpInt(mt, MpIntJitType.forSize(mt.size()),+ mv);+ default -> throw new AssertionError();+ };+ case LongJitType mt -> switch (otherType.ext()) {+ case IntJitType ot -> mt; // Other operand needs up-conversion+ case LongJitType ot -> mt;+ case MpIntJitType ot -> generateLongToMpInt(mt, MpIntJitType.forSize(mt.size()),+ mv);+ default -> throw new AssertionError();+ };+ case MpIntJitType mt -> mt; // Other may need up-conversion+ default -> throw new AssertionError();+ };+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/TypedAccessGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/TypedAccessGen.javanew file mode 100644index 0000000000..93ebfa1873--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/type/TypedAccessGen.java@@ -0,0 +1,115 @@+/* ###+ * 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.pcode.emu.jit.gen.type;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitLoadOp;+import ghidra.pcode.emu.jit.op.JitStoreOp;+import ghidra.program.model.lang.Endian;+import ghidra.program.model.pcode.Varnode;++/**+ * A generator to emit code that accesses variables of various size in a+ * {@link JitBytesPcodeExecutorState state}, for a specific type, byte order, and access.+ *+ * <p>+ * This is used by variable birthing and retirement as well as direct memory accesses. Dynamic+ * memory accesses, i.e., {@link JitLoadOp load} and {@link JitStoreOp store} op do not use this,+ * though they may borrow some portions.+ */+public interface TypedAccessGen {++ /**+ * Lookup the generator for reading variables for the given type+ *+ * @param endian the byte order+ * @param type the variable's type+ * @return the access generator+ */+ public static TypedAccessGen lookupReader(Endian endian, JitType type) {+ return switch (endian) {+ case BIG -> switch (type) {+ case IntJitType t -> IntReadGen.BE;+ case LongJitType t -> LongReadGen.BE;+ case FloatJitType t -> FloatReadGen.BE;+ case DoubleJitType t -> DoubleReadGen.BE;+ case MpIntJitType t -> MpIntReadGen.BE;+ default -> throw new AssertionError();+ };+ case LITTLE -> switch (type) {+ case IntJitType t -> IntReadGen.LE;+ case LongJitType t -> LongReadGen.LE;+ case FloatJitType t -> FloatReadGen.LE;+ case DoubleJitType t -> DoubleReadGen.LE;+ case MpIntJitType t -> MpIntReadGen.LE;+ default -> throw new AssertionError();+ };+ };+ }++ /**+ * Lookup the generator for writing variables for the given type+ *+ * @param endian the byte order+ * @param type the variable's type+ * @return the access generator+ */+ public static TypedAccessGen lookupWriter(Endian endian, JitType type) {+ return switch (endian) {+ case BIG -> switch (type) {+ case IntJitType t -> IntWriteGen.BE;+ case LongJitType t -> LongWriteGen.BE;+ case FloatJitType t -> FloatWriteGen.BE;+ case DoubleJitType t -> DoubleWriteGen.BE;+ case MpIntJitType t -> MpIntWriteGen.BE;+ default -> throw new AssertionError();+ };+ case LITTLE -> switch (type) {+ case IntJitType t -> IntWriteGen.LE;+ case LongJitType t -> LongWriteGen.LE;+ case FloatJitType t -> FloatWriteGen.LE;+ case DoubleJitType t -> DoubleWriteGen.LE;+ case MpIntJitType t -> MpIntWriteGen.LE;+ default -> throw new AssertionError();+ };+ };+ }++ /**+ * Emit code to access a varnode.+ *+ * <p>+ * If reading, the result is placed on the JVM stack. If writing, the value is popped from the+ * JVM stack.+ *+ * <p>+ * If the varnode fits completely in the block (the common case), then this accesses the bytes+ * from the one block, using the method chosen by size. If the varnode extends into the next+ * block, then this will split the varnode into two portions according to machine byte order.+ * Each portion is accessed using the method for the size of that portion. If reading, the+ * results are reassembled into a single value and pushed onto the JVM stack.+ *+ * @param gen the code generator+ * @param vn the varnode+ * @param rv the method visitor+ */+ void generateCode(JitCodeGenerator gen, Varnode vn, MethodVisitor rv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/ConstValGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/ConstValGen.javanew file mode 100644index 0000000000..0a5c1939b9--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/ConstValGen.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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;+import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitType.*;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.var.JitConstVal;++/**+ * The generator for a constant value.+ *+ * <p>+ * This can load directly the requested constant as the required JVM type onto the JVM stack. It+ * simply emits an {@link Opcodes#LDC ldc} bytecode.+ */+public enum ConstValGen implements ValGen<JitConstVal> {+ /** Singleton */+ GEN;++ @Override+ public void generateValInitCode(JitCodeGenerator gen, JitConstVal v, MethodVisitor iv) {+ }++ @Override+ public JitType generateValReadCode(JitCodeGenerator gen, JitConstVal v, JitTypeBehavior typeReq,+ MethodVisitor rv) {+ JitType type = typeReq.resolve(gen.getTypeModel().typeOf(v));+ switch (type) {+ case IntJitType t -> rv.visitLdcInsn(v.value().intValue());+ case LongJitType t -> rv.visitLdcInsn(v.value().longValue());+ case FloatJitType t -> rv.visitLdcInsn(Float.intBitsToFloat(v.value().intValue()));+ case DoubleJitType t -> rv.visitLdcInsn(Double.longBitsToDouble(v.value().longValue()));+ case MpIntJitType t -> {+ // Push most significant first, so least is at top of stack+ int count = t.legsAlloc();+ for (int i = 0; i < count; i++) {+ int leg = v.value().shiftRight(Integer.SIZE * (count - 1 - i)).intValue();+ rv.visitLdcInsn(leg);+ }+ }+ default -> throw new AssertionError();+ }+ return type;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/DirectMemoryVarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/DirectMemoryVarGen.javanew file mode 100644index 0000000000..9b50afd829--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/DirectMemoryVarGen.java@@ -0,0 +1,39 @@+/* ###+ * 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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.var.JitDirectMemoryVar;++/**+ * The generator for a direct memory variable.+ *+ * <p>+ * This prohibits generation of code to write the variable.+ */+public enum DirectMemoryVarGen implements MemoryVarGen<JitDirectMemoryVar> {+ /** Singleton */+ GEN;++ @Override+ public void generateVarWriteCode(JitCodeGenerator gen, JitDirectMemoryVar v, JitType type,+ MethodVisitor rv) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/InputVarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/InputVarGen.javanew file mode 100644index 0000000000..6842fbdbf5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/InputVarGen.java@@ -0,0 +1,39 @@+/* ###+ * 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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.var.JitInputVar;++/**+ * The generator for a local variable that is input to the passage.+ *+ * <p>+ * This prohibits generation of code to write the variable.+ */+public enum InputVarGen implements LocalVarGen<JitInputVar> {+ /** Singleton */+ GEN;++ @Override+ public void generateVarWriteCode(JitCodeGenerator gen, JitInputVar v, JitType type,+ MethodVisitor rv) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/LocalOutVarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/LocalOutVarGen.javanew file mode 100644index 0000000000..e7fe36c0cb--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/LocalOutVarGen.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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitAllocationModel.VarHandler;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.var.JitLocalOutVar;++/**+ * The generator for a local variable that is defined within the passage.+ */+public enum LocalOutVarGen implements LocalVarGen<JitLocalOutVar> {+ /** Singleton */+ GEN;++ @Override+ public void generateVarWriteCode(JitCodeGenerator gen, JitLocalOutVar v, JitType type,+ MethodVisitor rv) {+ VarHandler handler = gen.getAllocationModel().getHandler(v);+ handler.generateStoreCode(gen, type, rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/LocalVarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/LocalVarGen.javanew file mode 100644index 0000000000..b324240632--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/LocalVarGen.java@@ -0,0 +1,51 @@+/* ###+ * 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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;+import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.analysis.JitAllocationModel.VarHandler;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.var.JitVarnodeVar;++/**+ * The generator for local variable access.+ *+ * <p>+ * These variables are presumed to be allocated as JVM locals. The generator emits+ * {@link Opcodes#ILOAD iload} and {@link Opcodes#ISTORE istore} and or depending on the assigned+ * type.+ *+ * @param <V> the class of p-code variable node in the use-def graph+ */+public interface LocalVarGen<V extends JitVarnodeVar> extends VarGen<V> {+ @Override+ default void generateValInitCode(JitCodeGenerator gen, V v, MethodVisitor iv) {+ gen.getAllocationModel().getHandler(v).generateInitCode(gen, iv);+ }++ @Override+ default JitType generateValReadCode(JitCodeGenerator gen, V v, JitTypeBehavior typeReq,+ MethodVisitor rv) {+ VarHandler handler = gen.getAllocationModel().getHandler(v);+ JitType type = typeReq.resolve(gen.getTypeModel().typeOf(v));+ handler.generateLoadCode(gen, type, rv);+ return type;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MemoryOutVarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MemoryOutVarGen.javanew file mode 100644index 0000000000..80fc3a10f9--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MemoryOutVarGen.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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.var.JitMemoryOutVar;++/**+ * The generator for a memory output variable.+ */+public enum MemoryOutVarGen implements MemoryVarGen<JitMemoryOutVar> {+ /** Singleton */+ GEN;++ @Override+ public void generateVarWriteCode(JitCodeGenerator gen, JitMemoryOutVar v, JitType type,+ MethodVisitor rv) {+ VarGen.generateValWriteCodeDirect(gen, v, type, rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MemoryVarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MemoryVarGen.javanew file mode 100644index 0000000000..d28aa4d94a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MemoryVarGen.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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.type.TypedAccessGen;+import ghidra.pcode.emu.jit.var.JitVarnodeVar;++/**+ * The generator for memory variables.+ *+ * <p>+ * These variables affect the {@link JitBytesPcodeExecutorState state} immediately, i.e., they are+ * not birthed or retired as local JVM variables. The generator delegates to the appropriate+ * {@link TypedAccessGen} for this variable's varnode and assigned type.+ *+ * @param <V> the class of p-code variable node in the use-def graph+ */+public interface MemoryVarGen<V extends JitVarnodeVar> extends VarGen<V> {+ @Override+ default void generateValInitCode(JitCodeGenerator gen, V v, MethodVisitor iv) {+ VarGen.generateValInitCode(gen, v.varnode());+ }++ @Override+ default JitType generateValReadCode(JitCodeGenerator gen, V v, JitTypeBehavior typeReq,+ MethodVisitor rv) {+ return VarGen.generateValReadCodeDirect(gen, v, typeReq, rv);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MissingVarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MissingVarGen.javanew file mode 100644index 0000000000..c5063b2748--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/MissingVarGen.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.pcode.emu.jit.gen.var;++import static ghidra.pcode.emu.jit.gen.GenConsts.MDESC_ASSERTION_ERROR__$INIT;+import static ghidra.pcode.emu.jit.gen.GenConsts.NAME_ASSERTION_ERROR;+import static org.objectweb.asm.Opcodes.*;++import org.objectweb.asm.MethodVisitor;+import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.analysis.JitType;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.op.JitPhiOp;+import ghidra.pcode.emu.jit.var.JitMissingVar;++/**+ * The generator for a missing (local) variable.+ *+ * <p>+ * In principle, a {@link JitMissingVar} should never show up in the use-def graph, since they+ * should all be replaced by {@link JitPhiOp phi} outputs. We can be certain these should never show+ * up as an output, so we prohibit any attempt to generate code that writes to a missing variable.+ * However, we wait until run time to make that assertion about reads. In theory, it's possible the+ * generator will generate unreachable code that reads from a variable; however, that code is+ * unreachable. First how does this happen? Second, what if it does?+ *+ * <p>+ * To answer the first question, we note that the passage decoder should never decode any statically+ * unreachable instructions. However, the p-code emitted by those instructions may technically+ * contain unreachable ops.+ *+ * <p>+ * To answer the second, we note that the ASM library has a built-in control-flow analyzer, and it+ * ought to detect the unreachable code. In my observation, it replaces that code with+ * {@link Opcodes#NOP nop} and/or {@link Opcodes#ATHROW athrow}. Still, in case it doesn't, or in+ * case something changes in a later version (or if/when we port this to the JDK's upcoming+ * classfile API), we emit our own bytecode to throw an {@link AssertionError}.+ */+public enum MissingVarGen implements VarGen<JitMissingVar> {+ /** Singleton */+ GEN;++ @Override+ public void generateValInitCode(JitCodeGenerator gen, JitMissingVar v, MethodVisitor iv) {+ }++ @Override+ public JitType generateValReadCode(JitCodeGenerator gen, JitMissingVar v,+ JitTypeBehavior typeReq, MethodVisitor rv) {+ // [...]+ rv.visitTypeInsn(NEW, NAME_ASSERTION_ERROR);+ // [...,error:NEW]+ rv.visitInsn(DUP);+ // [...,error:NEW,error:NEW]+ rv.visitLdcInsn("Tried to read " + v);+ // [...,error:NEW,error:NEW,message]+ rv.visitMethodInsn(INVOKESPECIAL, NAME_ASSERTION_ERROR, "<init>",+ MDESC_ASSERTION_ERROR__$INIT, false);+ // [...,error]+ rv.visitInsn(ATHROW);+ // [...]+ JitType type = typeReq.resolve(gen.getTypeModel().typeOf(v));+ return type;+ }++ @Override+ public void generateVarWriteCode(JitCodeGenerator gen, JitMissingVar v, JitType type,+ MethodVisitor rv) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/ValGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/ValGen.javanew file mode 100644index 0000000000..cd3ca2f570--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/ValGen.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.pcode.emu.jit.gen.var;++import org.objectweb.asm.MethodVisitor;+import org.objectweb.asm.Opcodes;++import ghidra.pcode.emu.jit.JitConfiguration;+import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.analysis.JitType.SimpleJitType;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypeConversions;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.*;+import ghidra.program.model.pcode.Varnode;++/**+ * The bytecode generator for a specific value (operand) access.+ *+ * <p>+ * The {@link JitCodeGenerator} selects the correct generator for each input operand using+ * {@link #lookup(JitVal)} and each output operand {@link VarGen#lookup(JitVar)}. The op generator+ * has already retrieved the {@link JitOp} whose operands are of the {@link JitVal} class.+ *+ * <p>+ * <table border="1">+ * <tr>+ * <th>Varnode Type</th>+ * <th>Use-Def Type</th>+ * <th>Generator Type</th>+ * <th>Read Bytecodes / Methods</th>+ * <th>Write Bytecodes / Methods</th>+ * </tr>+ * <tr>+ * <td>{@link Varnode#isConstant() constant}</td>+ * <td>{@link JitConstVal}</td>+ * <td>{@link ConstValGen}</td>+ * <td>{@link Opcodes#LDC ldc}</td>+ * </tr>+ * <tr>+ * <td>{@link Varnode#isUnique() unique},<br/>+ * {@link Varnode#isRegister() register}<br/>+ * </td>+ * <td>{@link JitInputVar},<br/>+ * {@link JitLocalOutVar},<br/>+ * {@link JitMissingVar}</td>+ * <td>{@link InputVarGen},<br/>+ * {@link LocalOutVarGen}</td>+ * <td>See {@link SimpleJitType#opcodeLoad()}:<br/>+ * {@link Opcodes#ILOAD iload}, {@link Opcodes#LLOAD lload}, {@link Opcodes#FLOAD fload},+ * {@link Opcodes#DLOAD dload}</td>+ * <td>See {@link SimpleJitType#opcodeStore()}:<br/>+ * {@link Opcodes#ISTORE istore}, {@link Opcodes#LSTORE lstore}, {@link Opcodes#FSTORE fstore},+ * {@link Opcodes#DSTORE dstore}</td>+ * </tr>+ * <tr>+ * <td>{@link Varnode#isAddress() memory}</td>+ * <td>{@link JitDirectMemoryVar},<br/>+ * {@link JitMemoryOutVar}</td>+ * <td>{@link DirectMemoryVarGen},<br/>+ * {@link MemoryOutVarGen}</td>+ * <td>{@link JitCompiledPassage#readInt1(byte[], int) readInt*},+ * {@link JitCompiledPassage#readLong1(byte[], int) readLong*}, etc.</td>+ * <td>{@link JitCompiledPassage#writeInt1(int, byte[], int) writeInt*},+ * {@link JitCompiledPassage#writeLong1(long, byte[], int) writeLong*}, etc.</td>+ * </tr>+ * <tr>+ * <td>*indirect</td>+ * <td>{@link JitIndirectMemoryVar}</td>+ * <td>None</td>+ * </tr>+ * </table>+ *+ * @implNote Memory-mapped registers are treated as {@code memory} varnodes, not {@code register},+ * because they are shared by all threads. <b>TODO</b>: A {@link JitConfiguration} flag+ * that says "the machine is single threaded!" so we can optimize memory accesses in the+ * same manner we do registers and uniques.+ * @implNote There are remnants of experiments and fragments in anticipation of multi-precision+ * integer variables. These are not supported yet, but some of the components for mp-int+ * support are used in degenerate form to support normal ints. Many of these components+ * have "{@code Mp}" in the name.+ * @implNote The memory variables are all generally handled as if ints, and then+ * {@link TypeConversions type conversions} are applied if necessary to access them as+ * floating point.+ * @implNote {@link JitMissingVar} is a special case of {@code unique} and {@code register} variable+ * where the definition could not be found. It is used as an intermediate result the+ * {@link JitDataFlowModel}, but should be converted to a {@link JitOutVar} defined by a+ * {@link JitPhiOp} before it enters the use-def graph.+ * @implNote {@link JitIndirectMemoryVar} is a singleton dummy used in the {@link JitDataFlowModel}.+ * It is immediately thrown away, as indirect memory access is instead modeled by+ * {@link JitLoadOp} and {@link JitStoreOp}.+ *+ * @see VarGen+ * @param <V> the class op p-code value node in the use-def graph+ */+public interface ValGen<V extends JitVal> {+ /**+ * Lookup the generator for a given p-code value use-def node+ *+ * @param <V> the class of the value+ * @param v the {@link JitVal} whose generator to look up+ * @return the generator+ */+ @SuppressWarnings("unchecked")+ static <V extends JitVal> ValGen<V> lookup(V v) {+ return (ValGen<V>) switch (v) {+ case JitConstVal c -> ConstValGen.GEN;+ case JitVar vv -> VarGen.lookup(vv);+ default -> throw new AssertionError();+ };+ }++ /**+ * Prepare any class-level items required to use this variable+ *+ * <p>+ * For example, if this represents a direct memory variable, then this can prepare a reference+ * to the portion of the state involved, allowing it to access it readily.+ *+ * @param gen the code generator+ * @param v the value+ * @param iv the constructor visitor+ */+ void generateValInitCode(JitCodeGenerator gen, V v, MethodVisitor iv);++ /**+ * Read the value onto the stack+ *+ * @param gen the code generator+ * @param v the value to read+ * @param typeReq the required type of the value+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ * @return the actual p-code type (which determines the JVM type) of the value on the stack+ */+ JitType generateValReadCode(JitCodeGenerator gen, V v, JitTypeBehavior typeReq,+ MethodVisitor rv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/VarGen.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/VarGen.javanew file mode 100644index 0000000000..678ec85c43--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/var/VarGen.java@@ -0,0 +1,313 @@+/* ###+ * 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.pcode.emu.jit.gen.var;++import static ghidra.pcode.emu.jit.gen.GenConsts.BLOCK_SIZE;++import java.util.LinkedHashSet;+import java.util.Set;++import org.objectweb.asm.MethodVisitor;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.analysis.JitAllocationModel.JvmLocal;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.gen.JitCodeGenerator;+import ghidra.pcode.emu.jit.gen.op.CBranchOpGen;+import ghidra.pcode.emu.jit.gen.op.CallOtherOpGen;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.type.TypedAccessGen;+import ghidra.pcode.emu.jit.var.*;+import ghidra.program.model.address.Address;+import ghidra.program.model.pcode.Varnode;++/**+ * The bytecode generator for a specific use-def variable (operand) access+ *+ * <p>+ * For a table of value types, their use-def types, their generator classes, and relevant read/write+ * opcodes, see {@link JitVal}. This interface is an extension of the {@link JitVal} interface that+ * allows writing. The only non-{@link JitVar} {@link JitVal} is {@link JitConstVal}. As such, most+ * of the variable-access logic is actually contained here.+ *+ * @param <V> the class of p-code variable node in the use-def graph+ * @see ValGen+ */+public interface VarGen<V extends JitVar> extends ValGen<V> {+ /**+ * Lookup the generator for a given p-code variable use-def node+ *+ * @param <V> the class of the variable+ * @param v the {@link JitVar} whose generator to look up+ * @return the generator+ */+ @SuppressWarnings("unchecked")+ static <V extends JitVar> VarGen<V> lookup(V v) {+ return (VarGen<V>) switch (v) {+ case JitIndirectMemoryVar imv -> throw new AssertionError();+ case JitDirectMemoryVar dmv -> DirectMemoryVarGen.GEN;+ case JitInputVar iv -> InputVarGen.GEN;+ case JitMissingVar mv -> MissingVarGen.GEN;+ case JitMemoryOutVar mov -> MemoryOutVarGen.GEN;+ case JitLocalOutVar lov -> LocalOutVarGen.GEN;+ default -> throw new AssertionError();+ };+ }++ /**+ * Emit bytecode necessary to support access to the given varnode+ *+ * <p>+ * This applies to all varnode types: {@code memory}, {@code unique}, and {@code register}, but+ * not {@code const}. For memory varnodes, we need to pre-fetch the byte arrays backing their+ * pages, so we can access them at the translation site. For unique and register varnodes, we+ * also need to pre-fetch the byte arrays backing their pages, so we can birth and retire them+ * at {@link BlockTransition transitions}. Technically, the methods for generating the read and+ * write code will already call {@link JitCodeGenerator#requestFieldForArrDirect(Address)};+ * however, we'd like to ensure the fields appear in the classfile in a comprehensible order, so+ * we have the generator iterate the variables in address order and invoke this method, where we+ * make the request first.+ *+ * @param gen the code generator+ * @param vn the varnode+ */+ static void generateValInitCode(JitCodeGenerator gen, Varnode vn) {+ long start = vn.getOffset();+ long endIncl = start + vn.getSize() - 1;+ long startBlock = start / BLOCK_SIZE * BLOCK_SIZE;+ long endBlockIncl = endIncl / BLOCK_SIZE * BLOCK_SIZE;+ // Use != to allow wrap-around.+ for (long block = startBlock; block != endBlockIncl + BLOCK_SIZE; block += BLOCK_SIZE) {+ gen.requestFieldForArrDirect(vn.getAddress().getNewAddress(block));+ }+ }++ /**+ * Emit bytecode that loads the given varnode with the given p-code type from the+ * {@link JitBytesPcodeExecutorState state} onto the JVM stack.+ *+ * <p>+ * This is used for direct memory accesses and for register/unique scope transitions. The JVM+ * type of the stack variable is determined by the {@code type} argument.+ *+ * @param gen the code generator+ * @param type the p-code type of the variable+ * @param vn the varnode to read from the state+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ static void generateValReadCodeDirect(JitCodeGenerator gen, JitType type, Varnode vn,+ MethodVisitor rv) {+ TypedAccessGen.lookupReader(gen.getAnalysisContext().getEndian(), type)+ .generateCode(gen, vn, rv);+ }++ /**+ * Emit bytecode that loads the given use-def variable from the+ * {@link JitBytesPcodeExecutorState state} onto the JVM stack.+ *+ * <p>+ * The actual type is determined by resolving the {@code typeReq} argument against the given+ * variable. Since the variable is being loaded directly from the state, which is just raw+ * bytes/bits, we ignore the "assigned" type and convert directly the type required by the+ * operand.+ *+ * @param gen the code generator+ * @param v the use-def variable node+ * @param typeReq the type (behavior) required by the operand.+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ * @return the resulting p-code type (which also describes the JVM type) of the value on the JVM+ * stack+ */+ static JitType generateValReadCodeDirect(JitCodeGenerator gen, JitVarnodeVar v,+ JitTypeBehavior typeReq, MethodVisitor rv) {+ JitType type = typeReq.resolve(gen.getTypeModel().typeOf(v));+ generateValReadCodeDirect(gen, type, v.varnode(), rv);+ return type;+ }++ /**+ * Emit bytecode that writes the given varnode with the given p-code type in the+ * {@link JitBytesPcodeExecutorState state} from the JVM stack.+ *+ * <p>+ * This is used for direct memory accesses and for register/unique scope transitions. The+ * expected JVM type of the stack variable is described by the {@code type} argument.+ *+ * @param gen the code generator+ * @param type the p-code type of the variable+ * @param vn the varnode to write in the state+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ static void generateValWriteCodeDirect(JitCodeGenerator gen, JitType type, Varnode vn,+ MethodVisitor rv) {+ TypedAccessGen.lookupWriter(gen.getAnalysisContext().getEndian(), type)+ .generateCode(gen, vn, rv);+ }++ /**+ * Emit bytecode that writes the given use-def variable in the {@link JitBytesPcodeExecutorState+ * state} from the JVM stack.+ *+ * <p>+ * The expected type is given by the {@code type} argument. Since the variable is being written+ * directly into the state, which is just raw bytes/bits, we ignore the "assigned" type and+ * convert using the given type instead.+ *+ * @param gen the code generator+ * @param v the use-def variable node+ * @param type the p-code type of the value on the stack, as required by the operand+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ static void generateValWriteCodeDirect(JitCodeGenerator gen, JitVarnodeVar v,+ JitType type, MethodVisitor rv) {+ generateValWriteCodeDirect(gen, type, v.varnode(), rv);+ }++ /**+ * For block transitions: emit bytecode that births (loads) variables from the+ * {@link JitBytesPcodeExecutorState state} into their allocated JVM locals.+ *+ * @param gen the code generator+ * @param toBirth the set of varnodes to load+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ static void generateBirthCode(JitCodeGenerator gen, Set<Varnode> toBirth, MethodVisitor rv) {+ for (Varnode vn : toBirth) {+ for (JvmLocal local : gen.getAllocationModel().localsForVn(vn)) {+ local.generateBirthCode(gen, rv);+ }+ }+ }++ /**+ * For block transitions: emit bytecode the retires (writes) variables into the+ * {@link JitBytesPcodeExecutorState state} from their allocated JVM locals.+ *+ * @param gen the code generator+ * @param toRetire the set of varnodes to write+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ static void generateRetireCode(JitCodeGenerator gen, Set<Varnode> toRetire, MethodVisitor rv) {+ for (Varnode vn : toRetire) {+ for (JvmLocal local : gen.getAllocationModel().localsForVn(vn)) {+ local.generateRetireCode(gen, rv);+ }+ }+ }++ /**+ * A means to emit bytecode on transitions between {@link JitBlock blocks}+ *+ * @param gen the code generator+ * @param toRetire the varnodes to retire on the transition+ * @param toBirth the varnodes to birth on the transition+ */+ public record BlockTransition(JitCodeGenerator gen, Set<Varnode> toRetire,+ Set<Varnode> toBirth) {+ /**+ * Construct a "nop" or blank transition.+ *+ * <p>+ * The transition is mutable, so it's common to create one in this fashion and then populate+ * it.+ *+ * @param gen the code generator+ */+ public BlockTransition(JitCodeGenerator gen) {+ this(gen, new LinkedHashSet<>(), new LinkedHashSet<>());+ }++ /**+ * Check if a transition is actually needed.+ *+ * <p>+ * When a transition is not needed, some smaller control-flow constructs (e.g., in+ * {@link CBranchOpGen}) can be averted.+ *+ * @return true if bytecode must be emitted+ */+ public boolean needed() {+ return !toRetire.isEmpty() || !toBirth().isEmpty();+ }++ /**+ * Emit bytecode for the transition+ *+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generate(MethodVisitor rv) {+ generateRetireCode(gen, toRetire, rv);+ generateBirthCode(gen, toBirth, rv);+ }++ /**+ * Emit bytecode for the reverse transition+ *+ * <p>+ * Sometimes "transitions" are used around hazards, notably {@link CallOtherOpGen}. This+ * method is used after the hazard to restore the live variables in scope.+ * ({@link #generate(MethodVisitor)} is used before the hazard.) Variables that were retired+ * and re-birthed here. There should not have been any variables birthed going into the+ * hazard.+ *+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ public void generateInv(MethodVisitor rv) {+ generateRetireCode(gen, toBirth, rv);+ generateBirthCode(gen, toRetire, rv);+ }+ }++ /**+ * Compute the retired and birthed varnodes for a transition between the given blocks.+ *+ * <p>+ * Either block may be {@code null} to indicate entering or leaving the passage. Additionally,+ * the {@code to} block should be {@code null} when generating transitions around a hazard.+ *+ * @param gen the code generator+ * @param from the block control flow is leaving (whether by branch or fall through)+ * @param to the block control flow is entering+ * @return the means of generating bytecode at the transition+ */+ static BlockTransition computeBlockTransition(JitCodeGenerator gen, JitBlock from,+ JitBlock to) {+ JitVarScopeModel scopeModel = gen.getVariableScopeModel();+ Set<Varnode> liveFrom = from == null ? Set.of() : scopeModel.getLiveVars(from);+ Set<Varnode> liveTo = to == null ? Set.of() : scopeModel.getLiveVars(to);+ BlockTransition result = new BlockTransition(gen);++ result.toRetire.addAll(liveFrom);+ result.toRetire.removeAll(liveTo);++ result.toBirth.addAll(liveTo);+ result.toBirth.removeAll(liveFrom);++ return result;+ }++ /**+ * Write a value from the stack into the given variable+ *+ * @param gen the code generator+ * @param v the variable to write+ * @param type the p-code type (which also determines the expected JVM type) of the value on the+ * stack+ * @param rv the visitor for the {@link JitCompiledPassage#run(int) run} method+ */+ void generateVarWriteCode(JitCodeGenerator gen, V v, JitType type, MethodVisitor rv);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBinOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBinOp.javanew file mode 100644index 0000000000..283f19dd78--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBinOp.java@@ -0,0 +1,82 @@+/* ###+ * 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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;++/**+ * A p-code operator use-def node with two inputs and one output.+ */+public interface JitBinOp extends JitDefOp {+ /**+ * The use-def node for the left input operand+ *+ * @return the input+ */+ JitVal l();++ /**+ * The use-def node for the right input operand+ *+ * @return the input+ */+ JitVal r();++ @Override+ default void link() {+ JitDefOp.super.link();+ l().addUse(this, 0);+ r().addUse(this, 1);+ }++ @Override+ default void unlink() {+ JitDefOp.super.unlink();+ l().removeUse(this, 0);+ r().removeUse(this, 1);+ }++ @Override+ default List<JitVal> inputs() {+ return List.of(l(), r());+ }++ /**+ * The required type behavior for the left operand+ *+ * @return the behavior+ */+ JitTypeBehavior lType();++ /**+ * The required type behavior for the right operand+ *+ * @return the behavior+ */+ JitTypeBehavior rType();++ @Override+ default JitTypeBehavior typeFor(int position) {+ return switch (position) {+ case 0 -> lType();+ case 1 -> rType();+ default -> throw new AssertionError();+ };+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolAndOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolAndOp.javanew file mode 100644index 0000000000..c0fbdb564e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolAndOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#BOOL_AND}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitBoolAndOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitBoolBinOp {}diff --git a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/ComparatorMath.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolBinOp.javasimilarity index 53%rename from Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/ComparatorMath.javarename to Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolBinOp.javaindex 4498a49bb4..76cd0091a7 100644--- a/Ghidra/Debug/ProposedUtils/src/main/java/ghidra/util/ComparatorMath.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolBinOp.java@@ -4,35 +4,35 @@* 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.util;--import java.util.Comparator;+package ghidra.pcode.emu.jit.op;-public enum ComparatorMath {- ;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;- public static <C> C cmin(C a, C b, Comparator<C> comp) {- return comp.compare(a, b) <= 0 ? a : b;- }-- public static <C extends Comparable<C>> C cmin(C a, C b) {- return cmin(a, b, Comparator.naturalOrder());+/**+ * A binary p-code operator use-def node with boolean ({@link JitTypeBehavior#INTEGER int}) types.+ */+public interface JitBoolBinOp extends JitBinOp {+ @Override+ default JitTypeBehavior lType() {+ return JitTypeBehavior.INTEGER;}- public static <C> C cmax(C a, C b, Comparator<C> comp) {- return comp.compare(a, b) >= 0 ? a : b;+ @Override+ default JitTypeBehavior rType() {+ return JitTypeBehavior.INTEGER;}- public static <C extends Comparable<C>> C cmax(C a, C b) {- return cmax(a, b, Comparator.naturalOrder());+ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;}}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolNegateOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolNegateOp.javanew file mode 100644index 0000000000..a8fadf98af--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolNegateOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#BOOL_NEGATE}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitBoolNegateOp(PcodeOp op, JitOutVar out, JitVal u) implements JitBoolUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolOrOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolOrOp.javanew file mode 100644index 0000000000..e28f6180a4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolOrOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#BOOL_OR}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitBoolOrOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitBoolBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolUnOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolUnOp.javanew file mode 100644index 0000000000..2c571b327a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolUnOp.java@@ -0,0 +1,33 @@+/* ###+ * 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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;++/**+ * A unary p-code operator use-def node with boolean ({@link JitTypeBehavior#INTEGER int}) types.+ */+public interface JitBoolUnOp extends JitUnOp {+ @Override+ default JitTypeBehavior uType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolXorOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolXorOp.javanew file mode 100644index 0000000000..c6b6bbc205--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBoolXorOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#BOOL_XOR}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitBoolXorOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitBoolBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBranchIndOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBranchIndOp.javanew file mode 100644index 0000000000..124624345e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBranchIndOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.JitPassage.IndBranch;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#BRANCHIND}.+ *+ * @param op the p-code op+ * @param target the use-def node for the target offset+ * @param branch the branch record created for the p-code op+ */+public record JitBranchIndOp(PcodeOp op, JitVal target, IndBranch branch) implements JitOp {++ @Override+ public boolean canBeRemoved() {+ return false;+ }++ @Override+ public void link() {+ target.addUse(this, 0);+ }++ @Override+ public void unlink() {+ target.removeUse(this, 0);+ }++ @Override+ public List<JitVal> inputs() {+ return List.of(target);+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ return switch (position) {+ case 0 -> targetType();+ default -> throw new AssertionError();+ };+ }++ /**+ * We'd like the offset to be an {@link JitTypeBehavior#INTEGER int}.+ *+ * @return {@link JitTypeBehavior#INTEGER}+ */+ public JitTypeBehavior targetType() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBranchOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBranchOp.javanew file mode 100644index 0000000000..4be0a42c40--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitBranchOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.JitPassage.Branch;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#BRANCH}.+ *+ * @param op the p-code op+ * @param branch the branch record created for the p-code op+ */+public record JitBranchOp(PcodeOp op, Branch branch) implements JitOp {++ @Override+ public boolean canBeRemoved() {+ return false;+ }++ @Override+ public void link() {+ // Nothing+ }++ @Override+ public void unlink() {+ // Nothing+ }++ @Override+ public List<JitVal> inputs() {+ return List.of();+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCBranchOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCBranchOp.javanew file mode 100644index 0000000000..48f66e32ef--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCBranchOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.JitPassage.Branch;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#CBRANCH}.+ *+ * @param op the p-code op+ * @param branch the branch record created for the p-code op+ * @param cond the use-def node for the branch condition+ */+public record JitCBranchOp(PcodeOp op, Branch branch, JitVal cond)+ implements JitOp {++ @Override+ public boolean canBeRemoved() {+ return false;+ }++ @Override+ public void link() {+ cond.addUse(this, 0);+ }++ @Override+ public void unlink() {+ cond.removeUse(this, 0);+ }++ @Override+ public List<JitVal> inputs() {+ return List.of(cond);+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ return switch (position) {+ case 0 -> condType();+ default -> throw new AssertionError();+ };+ }++ /**+ * We'd like the condition to be an {@link JitTypeBehavior#INTEGER int} (boolean).+ *+ * @return {@link JitTypeBehavior#INTEGER}+ */+ public JitTypeBehavior condType() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherDefOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherDefOp.javanew file mode 100644index 0000000000..b4a6efe62e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherDefOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitDataFlowState.MiniDFState;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#CALLOTHER} with an output operand.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param type the behavior of the output+ * @param userop the userop definition+ * @param args the list of use-def values nodes given as arguments+ * @param inputTypes the type behavior for each parameter+ * @param dfState the captured data flow state at the call site+ */+public record JitCallOtherDefOp(PcodeOp op, JitOutVar out, JitTypeBehavior type,+ PcodeUseropDefinition<Object> userop, List<JitVal> args, List<JitTypeBehavior> inputTypes,+ MiniDFState dfState) implements JitCallOtherOpIf, JitDefOp {++ @Override+ public boolean canBeRemoved() {+ return JitCallOtherOpIf.super.canBeRemoved() && JitDefOp.super.canBeRemoved();+ }++ @Override+ public void link() {+ JitDefOp.super.link();+ JitCallOtherOpIf.super.link();+ }++ @Override+ public void unlink() {+ JitDefOp.super.unlink();+ JitCallOtherOpIf.super.unlink();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherMissingOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherMissingOp.javanew file mode 100644index 0000000000..689e6b64cb--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherMissingOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#CALLOTHER} when the userop turns up missing.+ *+ * @param op the p-code op+ * @param opName the name of the missing userop+ */+public record JitCallOtherMissingOp(PcodeOp op, String opName) implements JitOp {+ @Override+ public boolean canBeRemoved() {+ return false;+ }++ @Override+ public void link() {+ }++ @Override+ public void unlink() {+ }++ @Override+ public List<JitVal> inputs() {+ return List.of();+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherOp.javanew file mode 100644index 0000000000..8a8687ddcb--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitDataFlowState.MiniDFState;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#CALLOTHER} without an output operand.+ *+ * @param op the p-code op+ * @param userop the userop definition+ * @param args the list of use-def values nodes given as arguments+ * @param inputTypes the type behavior for each parameter+ * @param dfState the captured data flow state at the call site+ */+public record JitCallOtherOp(PcodeOp op, PcodeUseropDefinition<Object> userop, List<JitVal> args,+ List<JitTypeBehavior> inputTypes, MiniDFState dfState) implements JitCallOtherOpIf {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherOpIf.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherOpIf.javanew file mode 100644index 0000000000..6b1db488da--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCallOtherOpIf.java@@ -0,0 +1,114 @@+/* ###+ * 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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitDataFlowState.MiniDFState;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;+import ghidra.program.model.pcode.PcodeOp;++/**+ * A use-def node for a {@link PcodeOp#CALLOTHER}.+ *+ * <p>+ * This requires the {@link #userop()} to exist. For the case of a missing userop, we use+ * {@link JitCallOtherMissingOp}.+ *+ * <p>+ * <b>TODO</b>: We have several considerations remaining, esp., since we'd like to handle system+ * calls via userops efficiently:+ *+ * <ol>+ *+ * <li>There are more inputs than listed in the op itself. In fact, the invocation is just+ * {@code syscall()}. The actual inputs are at least {@code RAX} and whatever parameters that+ * specific syscall wants.</li>+ *+ * <li>We'd like to be able to evaluate {@code RAX} statically.</li>+ *+ * <li>We Might like to inject the p-code rather than trying to compile and run it separately. Then,+ * in the case of a syscall, the actual Java callback should have known inputs and outputs. Would+ * probably <em>not</em> want to embed a huge if-elseif tree for syscall numbers, though, which is+ * why we'd like to evaluate RAX ahead of time. What if we can't, though? My thought is to retire+ * all the variables and just interpret the syscall.</li>+ *+ * </ol>+ */+public interface JitCallOtherOpIf extends JitOp {++ /**+ * The userop definition.+ *+ * @return the definition from the library+ */+ PcodeUseropDefinition<Object> userop();++ /**+ * The arguments to the userop.+ *+ * @return the list of use-def value nodes+ */+ List<JitVal> args();++ @Override+ default List<JitVal> inputs() {+ return args();+ }++ /**+ * The type behavior for each parameter in the userop definition+ *+ * <p>+ * These should correspond to each argument (input).+ *+ * @return the list of behaviors+ */+ List<JitTypeBehavior> inputTypes();++ @Override+ default JitTypeBehavior typeFor(int position) {+ return inputTypes().get(position);+ }++ /**+ * Get the captured data flow state at the call site.+ *+ * @return the state+ */+ MiniDFState dfState();++ @Override+ default boolean canBeRemoved() {+ return !userop().hasSideEffects();+ }++ @Override+ default void link() {+ for (int i = 0; i < args().size(); i++) {+ args().get(i).addUse(this, i);+ }+ }++ @Override+ default void unlink() {+ for (int i = 0; i < args().size(); i++) {+ args().get(i).removeUse(this, i);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCatenateOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCatenateOp.javanew file mode 100644index 0000000000..0ae239d90a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCatenateOp.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.pcode.emu.jit.op;++import java.util.List;++import org.apache.commons.collections4.iterators.ReverseListIterator;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;++/**+ * The synthetic use-def node for concatenation.+ *+ * <p>+ * These are synthesized when memory/register access patterns cause multiple use-def variable nodes+ * to be "read" at the same time. E.g., consider {@code AL} and {@code AH} to be written and then+ * {@code AX} read.+ *+ * @param out the use-def variable node for the output+ * @param parts the inputs to be concatenated+ */+public record JitCatenateOp(JitOutVar out, List<JitVal> parts) implements JitDefOp, JitSyntheticOp {+ /**+ * Compact constructor for validation+ *+ * @param out the use-def variable node for the output+ * @param parts the inputs to be concatenated+ */+ public JitCatenateOp {+ if (parts.size() <= 1) {+ throw new IllegalArgumentException("Must have at least 2 parts");+ }+ }++ @Override+ public void link() {+ JitDefOp.super.link();+ for (int i = 0; i < parts.size(); i++) {+ parts.get(i).addUse(this, i);+ }+ }++ @Override+ public void unlink() {+ JitDefOp.super.unlink();+ for (int i = 0; i < parts.size(); i++) {+ parts.get(i).removeUse(this, i);+ }+ }++ /**+ * Iterate over the parts from most to least significant+ *+ * @param bigEndian the byte order off the machine+ * @return an iterable over the parts+ */+ public Iterable<JitVal> iterParts(boolean bigEndian) {+ if (bigEndian) {+ return parts;+ }+ return () -> new ReverseListIterator<>(parts);+ }++ @Override+ public List<JitVal> inputs() {+ return parts;+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ if (position > parts.size() || position < 0) {+ throw new AssertionError();+ }+ return partType();+ }++ /**+ * We'd like every part to be an {@link JitTypeBehavior#INTEGER int}.+ *+ * @return {@link JitTypeBehavior#INTEGER}+ */+ public JitTypeBehavior partType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCopyOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCopyOp.javanew file mode 100644index 0000000000..de362be091--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitCopyOp.java@@ -0,0 +1,40 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#COPY}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitCopyOp(PcodeOp op, JitOutVar out, JitVal u) implements JitUnOp {+ @Override+ public JitTypeBehavior uType() {+ return JitTypeBehavior.COPY;+ }++ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.COPY;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitDefOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitDefOp.javanew file mode 100644index 0000000000..7fd7b826e1--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitDefOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.program.model.address.AddressSpace;++/**+ * A p-code operator use-def node with an output+ */+public interface JitDefOp extends JitOp {+ @Override+ default boolean canBeRemoved() {+ AddressSpace space = out().varnode().getAddress().getAddressSpace();+ return space.isUniqueSpace() || space.isRegisterSpace();+ }++ /**+ * The the use-def variable node for the output.+ *+ * @return the output+ */+ JitOutVar out();++ @Override+ default void link() {+ out().setDefinition(this);+ }++ @Override+ default void unlink() {+ if (out().definition() == this) {+ out().setDefinition(null);+ }+ }++ /**+ * The required type behavior for the output+ *+ * @return the behavior+ */+ JitTypeBehavior type();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatAbsOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatAbsOp.javanew file mode 100644index 0000000000..8d381461d2--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatAbsOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_ABS}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatAbsOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatAddOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatAddOp.javanew file mode 100644index 0000000000..78d8652cd2--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatAddOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_ADD}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatAddOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatBinOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatBinOp.javanew file mode 100644index 0000000000..4a0f55441b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatBinOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;++/**+ * A binary p-code operator use-def node with {@link JitTypeBehavior#FLOAT float} types.+ */+public interface JitFloatBinOp extends JitBinOp {+ @Override+ default JitTypeBehavior lType() {+ return JitTypeBehavior.FLOAT;+ }++ @Override+ default JitTypeBehavior rType() {+ return JitTypeBehavior.FLOAT;+ }++ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.FLOAT;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatCeilOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatCeilOp.javanew file mode 100644index 0000000000..37de464440--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatCeilOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_CEIL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatCeilOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatDivOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatDivOp.javanew file mode 100644index 0000000000..12ebaca2e9--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatDivOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_DIV}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatDivOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatEqualOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatEqualOp.javanew file mode 100644index 0000000000..98e1b8f562--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatEqualOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_EQUAL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatEqualOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatFloat2FloatOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatFloat2FloatOp.javanew file mode 100644index 0000000000..147994a946--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatFloat2FloatOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_FLOAT2FLOAT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatFloat2FloatOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatFloorOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatFloorOp.javanew file mode 100644index 0000000000..8349079a03--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatFloorOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_FLOOR}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatFloorOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatInt2FloatOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatInt2FloatOp.javanew file mode 100644index 0000000000..34866ef4fe--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatInt2FloatOp.java@@ -0,0 +1,40 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_INT2FLOAT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatInt2FloatOp(PcodeOp op, JitOutVar out, JitVal u) implements JitUnOp {+ @Override+ public JitTypeBehavior uType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.FLOAT;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatLessEqualOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatLessEqualOp.javanew file mode 100644index 0000000000..e14ac83874--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatLessEqualOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_LESSEQUAL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatLessEqualOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatLessOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatLessOp.javanew file mode 100644index 0000000000..1c2de13206--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatLessOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_LESS}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatLessOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatMultOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatMultOp.javanew file mode 100644index 0000000000..85ff55f610--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatMultOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_MULT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatMultOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNaNOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNaNOp.javanew file mode 100644index 0000000000..facae764c6--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNaNOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_NAN}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatNaNOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {+ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNegOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNegOp.javanew file mode 100644index 0000000000..cd69e1f9a1--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNegOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_NEG}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatNegOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNotEqualOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNotEqualOp.javanew file mode 100644index 0000000000..e7482377a5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatNotEqualOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_NOTEQUAL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatNotEqualOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatRoundOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatRoundOp.javanew file mode 100644index 0000000000..2929bfb085--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatRoundOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_ROUND}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatRoundOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatSqrtOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatSqrtOp.javanew file mode 100644index 0000000000..c601841737--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatSqrtOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_SQRT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatSqrtOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatSubOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatSubOp.javanew file mode 100644index 0000000000..bb23a13528--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatSubOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_SUB}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitFloatSubOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitFloatBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatTestOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatTestOp.javanew file mode 100644index 0000000000..480c8300fa--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatTestOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;++/**+ * A binary p-code operator use-def node with {@link JitTypeBehavior#FLOAT float} inputs and a+ * boolean ({@link JitTypeBehavior#INTEGER int}) output.+ */+public interface JitFloatTestOp extends JitFloatBinOp {+ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatTruncOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatTruncOp.javanew file mode 100644index 0000000000..12c2626384--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatTruncOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#FLOAT_TRUNC}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitFloatTruncOp(PcodeOp op, JitOutVar out, JitVal u) implements JitFloatUnOp {+ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatUnOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatUnOp.javanew file mode 100644index 0000000000..dadf9071fd--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitFloatUnOp.java@@ -0,0 +1,33 @@+/* ###+ * 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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;++/**+ * A unary p-code operator use-def node with {@link JitTypeBehavior#FLOAT float} types.+ */+public interface JitFloatUnOp extends JitUnOp {+ @Override+ default JitTypeBehavior uType() {+ return JitTypeBehavior.FLOAT;+ }++ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.FLOAT;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitInt2CompOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitInt2CompOp.javanew file mode 100644index 0000000000..b79ae23042--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitInt2CompOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_2COMP}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitInt2CompOp(PcodeOp op, JitOutVar out, JitVal u) implements JitIntUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntAddOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntAddOp.javanew file mode 100644index 0000000000..a20af4ad84--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntAddOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_ADD}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntAddOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntAndOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntAndOp.javanew file mode 100644index 0000000000..740e3a26dc--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntAndOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_AND}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntAndOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntBinOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntBinOp.javanew file mode 100644index 0000000000..2029409b3f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntBinOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;++/**+ * A binary p-code operator use-def node with {@link JitTypeBehavior#INTEGER int} types.+ */+public interface JitIntBinOp extends JitBinOp {+ @Override+ default JitTypeBehavior lType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ default JitTypeBehavior rType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntCarryOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntCarryOp.javanew file mode 100644index 0000000000..4ff20bd156--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntCarryOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_CARRY}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntCarryOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntDivOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntDivOp.javanew file mode 100644index 0000000000..898b74564e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntDivOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_DIV}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntDivOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntEqualOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntEqualOp.javanew file mode 100644index 0000000000..8915bab5e1--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntEqualOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_EQUAL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntEqualOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLeftOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLeftOp.javanew file mode 100644index 0000000000..2143f7e7d5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLeftOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_LEFT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntLeftOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLessEqualOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLessEqualOp.javanew file mode 100644index 0000000000..b436900f83--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLessEqualOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_LESSEQUAL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntLessEqualOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLessOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLessOp.javanew file mode 100644index 0000000000..876e377f26--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntLessOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_LESS}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntLessOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntMultOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntMultOp.javanew file mode 100644index 0000000000..5c3f5d080c--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntMultOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_MULT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntMultOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntNegateOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntNegateOp.javanew file mode 100644index 0000000000..340e1856c2--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntNegateOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_NEGATE}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitIntNegateOp(PcodeOp op, JitOutVar out, JitVal u) implements JitIntUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntNotEqualOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntNotEqualOp.javanew file mode 100644index 0000000000..b7c0d84bce--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntNotEqualOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_NOTEQUAL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntNotEqualOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntOrOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntOrOp.javanew file mode 100644index 0000000000..da802df58e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntOrOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_OR}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntOrOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntRemOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntRemOp.javanew file mode 100644index 0000000000..464a0cded0--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntRemOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_REM}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntRemOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntRightOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntRightOp.javanew file mode 100644index 0000000000..e3fa4ac3e5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntRightOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_RIGHT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntRightOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSBorrowOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSBorrowOp.javanew file mode 100644index 0000000000..304b19701d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSBorrowOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SBORROW}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSBorrowOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSCarryOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSCarryOp.javanew file mode 100644index 0000000000..fd7c1944fd--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSCarryOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SCARRY}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSCarryOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSDivOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSDivOp.javanew file mode 100644index 0000000000..644ac5bf5d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSDivOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SDIV}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSDivOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSExtOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSExtOp.javanew file mode 100644index 0000000000..ba69e11e34--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSExtOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SEXT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitIntSExtOp(PcodeOp op, JitOutVar out, JitVal u) implements JitIntUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSLessEqualOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSLessEqualOp.javanew file mode 100644index 0000000000..01b73d1f05--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSLessEqualOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SLESSEQUAL}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSLessEqualOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSLessOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSLessOp.javanew file mode 100644index 0000000000..17bfc28a2a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSLessOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SLESS}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSLessOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntTestOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSRemOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSRemOp.javanew file mode 100644index 0000000000..14592b2cc0--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSRemOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SREM}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSRemOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSRightOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSRightOp.javanew file mode 100644index 0000000000..42b06385ec--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSRightOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SRIGHT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSRightOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r)+ implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSubOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSubOp.javanew file mode 100644index 0000000000..9b26a6d9c1--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntSubOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_SUB}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntSubOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntTestOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntTestOp.javanew file mode 100644index 0000000000..bd3b7cf451--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntTestOp.java@@ -0,0 +1,33 @@+/* ###+ * 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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;++/**+ * A binary p-code operator use-def node with {@link JitTypeBehavior#INTEGER int} inputs and a+ * boolean ({@link JitTypeBehavior#INTEGER int}) output.+ *+ * @implNote Correct. This doesn't change anything, because boolean is int. Nevertheless, we keep+ * this here because it forms a useful category of p-code ops. Also, if we ever need to+ * formalize the "boolean" type, we'll already have this in place.+ */+public interface JitIntTestOp extends JitIntBinOp {+ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntUnOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntUnOp.javanew file mode 100644index 0000000000..88abf42ee6--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntUnOp.java@@ -0,0 +1,33 @@+/* ###+ * 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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;++/**+ * A unary p-code operator use-def node with {@link JitTypeBehavior#INTEGER int} types.+ */+public interface JitIntUnOp extends JitUnOp {+ @Override+ default JitTypeBehavior uType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ default JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntXorOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntXorOp.javanew file mode 100644index 0000000000..5b1e3c75e3--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntXorOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_XOR}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param l the use-def node for the left input operand+ * @param r the use-def node for the right input operand+ */+public record JitIntXorOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) implements JitIntBinOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntZExtOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntZExtOp.javanew file mode 100644index 0000000000..1b45b9ceff--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitIntZExtOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#INT_ZEXT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitIntZExtOp(PcodeOp op, JitOutVar out, JitVal u) implements JitIntUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitLoadOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitLoadOp.javanew file mode 100644index 0000000000..3772d9dced--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitLoadOp.java@@ -0,0 +1,75 @@+/* ###+ * 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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#LOAD}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param space the address space+ * @param offset the use-def node for the offset+ */+public record JitLoadOp(PcodeOp op, JitOutVar out, AddressSpace space, JitVal offset)+ implements JitDefOp {++ @Override+ public void link() {+ JitDefOp.super.link();+ offset.addUse(this, 0);+ }++ @Override+ public void unlink() {+ JitDefOp.super.unlink();+ offset.removeUse(this, 0);+ }++ @Override+ public List<JitVal> inputs() {+ return List.of(offset);+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ return switch (position) {+ case 0 -> offsetType();+ default -> throw new AssertionError();+ };+ }++ /**+ * We'd like the offset to be an {@link JitTypeBehavior#INTEGER int}.+ *+ * @return {@link JitTypeBehavior#INTEGER}+ */+ public JitTypeBehavior offsetType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.ANY;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitLzCountOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitLzCountOp.javanew file mode 100644index 0000000000..276f049d95--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitLzCountOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#LZCOUNT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitLzCountOp(PcodeOp op, JitOutVar out, JitVal u) implements JitIntUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitNopOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitNopOp.javanew file mode 100644index 0000000000..51187a4bd2--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitNopOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.JitPassage.NopPcodeOp;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link NopPcodeOp} or an inlined {@link PcodeOp#CALLOTHER}.+ *+ * <p>+ * When a callother is inlined, we preserve the original op for bookkeeping, but ensure that no code+ * is emitted for it by wrapping it in this use-def node class.+ *+ * @param op the p-code op+ */+public record JitNopOp(PcodeOp op) implements JitOp {++ @Override+ public boolean canBeRemoved() {+ return true;+ }++ @Override+ public void link() {+ // Nothing+ }++ @Override+ public void unlink() {+ // Nothing+ }++ @Override+ public List<JitVal> inputs() {+ return List.of();+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitOp.javanew file mode 100644index 0000000000..a780cbf56d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.JitPassage.NopPcodeOp;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.gen.op.OpGen;+import ghidra.pcode.emu.jit.var.*;+import ghidra.program.model.pcode.PcodeOp;++/**+ * A p-code operator use-def node.+ *+ * <p>+ * For a table of p-code ops, use-def nodes, and code generators, see {@link OpGen}.+ */+public interface JitOp {+ /**+ * Create a use-def node for a nop or unimplemented op.+ *+ * @param op the p-code op+ * @return the use-def node+ */+ static JitOp stubOp(PcodeOp op) {+ if (op instanceof NopPcodeOp) {+ return new JitNopOp(op);+ }+ return switch (op.getOpcode()) {+ case PcodeOp.UNIMPLEMENTED -> new JitUnimplementedOp(op);+ default -> throw new UnsupportedOperationException(+ "Unrecognized stub op: " + op.getMnemonic());+ };+ }++ /**+ * Create a use-def node for a unary p-coe op+ *+ * @param op the p-code op+ * @param out the (pre-made) output operand use-def node+ * @param u the input operand use-def node+ * @return the use-def node+ */+ static JitUnOp unOp(PcodeOp op, JitOutVar out, JitVal u) {+ return switch (op.getOpcode()) {+ case PcodeOp.COPY -> new JitCopyOp(op, out, u);++ case PcodeOp.INT_ZEXT -> new JitIntZExtOp(op, out, u);+ case PcodeOp.INT_SEXT -> new JitIntSExtOp(op, out, u);+ case PcodeOp.INT_2COMP -> new JitInt2CompOp(op, out, u);+ case PcodeOp.INT_NEGATE -> new JitIntNegateOp(op, out, u);++ case PcodeOp.POPCOUNT -> new JitPopCountOp(op, out, u);+ case PcodeOp.LZCOUNT -> new JitLzCountOp(op, out, u);++ case PcodeOp.BOOL_NEGATE -> new JitBoolNegateOp(op, out, u);++ case PcodeOp.FLOAT_NAN -> new JitFloatNaNOp(op, out, u);+ case PcodeOp.FLOAT_NEG -> new JitFloatNegOp(op, out, u);+ case PcodeOp.FLOAT_ABS -> new JitFloatAbsOp(op, out, u);+ case PcodeOp.FLOAT_SQRT -> new JitFloatSqrtOp(op, out, u);++ case PcodeOp.FLOAT_INT2FLOAT -> new JitFloatInt2FloatOp(op, out, u);+ case PcodeOp.FLOAT_FLOAT2FLOAT -> new JitFloatFloat2FloatOp(op, out, u);+ case PcodeOp.FLOAT_TRUNC -> new JitFloatTruncOp(op, out, u);+ case PcodeOp.FLOAT_CEIL -> new JitFloatCeilOp(op, out, u);+ case PcodeOp.FLOAT_FLOOR -> new JitFloatFloorOp(op, out, u);+ case PcodeOp.FLOAT_ROUND -> new JitFloatRoundOp(op, out, u);++ default -> throw new UnsupportedOperationException(+ "Unrecognized un op: " + op.getMnemonic());+ };+ }++ /**+ * Create a use-def node for a binary p-coe op+ *+ * @param op the p-code op+ * @param out the (pre-made) output operand use-def node+ * @param l the left input operand use-def node+ * @param r the right input operand use-def node+ * @return the use-def node+ */+ static JitDefOp binOp(PcodeOp op, JitOutVar out, JitVal l, JitVal r) {+ return switch (op.getOpcode()) {+ case PcodeOp.INT_EQUAL -> new JitIntEqualOp(op, out, l, r);+ case PcodeOp.INT_NOTEQUAL -> new JitIntNotEqualOp(op, out, l, r);+ case PcodeOp.INT_SLESS -> new JitIntSLessOp(op, out, l, r);+ case PcodeOp.INT_SLESSEQUAL -> new JitIntSLessEqualOp(op, out, l, r);+ case PcodeOp.INT_LESS -> new JitIntLessOp(op, out, l, r);+ case PcodeOp.INT_LESSEQUAL -> new JitIntLessEqualOp(op, out, l, r);+ case PcodeOp.INT_ADD -> new JitIntAddOp(op, out, l, r);+ case PcodeOp.INT_SUB -> new JitIntSubOp(op, out, l, r);+ case PcodeOp.INT_CARRY -> new JitIntCarryOp(op, out, l, r);+ case PcodeOp.INT_SCARRY -> new JitIntSCarryOp(op, out, l, r);+ case PcodeOp.INT_SBORROW -> new JitIntSBorrowOp(op, out, l, r);+ case PcodeOp.INT_XOR -> new JitIntXorOp(op, out, l, r);+ case PcodeOp.INT_AND -> new JitIntAndOp(op, out, l, r);+ case PcodeOp.INT_OR -> new JitIntOrOp(op, out, l, r);+ case PcodeOp.INT_LEFT -> new JitIntLeftOp(op, out, l, r);+ case PcodeOp.INT_RIGHT -> new JitIntRightOp(op, out, l, r);+ case PcodeOp.INT_SRIGHT -> new JitIntSRightOp(op, out, l, r);+ case PcodeOp.INT_MULT -> new JitIntMultOp(op, out, l, r);+ case PcodeOp.INT_DIV -> new JitIntDivOp(op, out, l, r);+ case PcodeOp.INT_SDIV -> new JitIntSDivOp(op, out, l, r);+ case PcodeOp.INT_REM -> new JitIntRemOp(op, out, l, r);+ case PcodeOp.INT_SREM -> new JitIntSRemOp(op, out, l, r);++ case PcodeOp.BOOL_XOR -> new JitBoolXorOp(op, out, l, r);+ case PcodeOp.BOOL_AND -> new JitBoolAndOp(op, out, l, r);+ case PcodeOp.BOOL_OR -> new JitBoolOrOp(op, out, l, r);++ case PcodeOp.FLOAT_EQUAL -> new JitFloatEqualOp(op, out, l, r);+ case PcodeOp.FLOAT_NOTEQUAL -> new JitFloatNotEqualOp(op, out, l, r);+ case PcodeOp.FLOAT_LESS -> new JitFloatLessOp(op, out, l, r);+ case PcodeOp.FLOAT_LESSEQUAL -> new JitFloatLessEqualOp(op, out, l, r);++ case PcodeOp.FLOAT_ADD -> new JitFloatAddOp(op, out, l, r);+ case PcodeOp.FLOAT_DIV -> new JitFloatDivOp(op, out, l, r);+ case PcodeOp.FLOAT_MULT -> new JitFloatMultOp(op, out, l, r);+ case PcodeOp.FLOAT_SUB -> new JitFloatSubOp(op, out, l, r);++ case PcodeOp.SUBPIECE -> new JitSubPieceOp(op, out, l,+ ((JitConstVal) r).value().intValue());++ default -> throw new UnsupportedOperationException(+ "Unrecognized bin op: " + op.getMnemonic());+ };+ }++ /**+ * The p-code op represented by this use-def node+ *+ * @return the p-code op+ */+ PcodeOp op();++ /**+ * Indicates the operation can be removed if its output is never used.+ *+ * @return true if removable+ */+ boolean canBeRemoved();++ /**+ * The input operand use-def nodes in some defined order+ *+ * @return the list of inputs+ */+ List<JitVal> inputs();++ /**+ * Get the required type behavior for the input at the given position in {@link #inputs()}+ *+ * @param position the input position+ * @return the behavior+ */+ JitTypeBehavior typeFor(int position);++ /**+ * Add this op to the {@link JitVal#uses()} of each input operand, and (if applicable) set the+ * {@link JitOutVar#definition()} of the output operand to this op.+ */+ void link();++ /**+ * Remove this op from the {@link JitVal#uses()} of each input operand, and (if applicable)+ * unset the {@link JitOutVar#definition()} of the output operand.+ */+ void unlink();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitPhiOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitPhiOp.javanew file mode 100644index 0000000000..ada7279a14--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitPhiOp.java@@ -0,0 +1,125 @@+/* ###+ * 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.pcode.emu.jit.op;++import java.util.List;++import org.apache.commons.collections4.BidiMap;+import org.apache.commons.collections4.bidimap.DualHashBidiMap;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.*;++/**+ * The synthetic use-def node for phi nodes.+ *+ * @param block the block containing the op that generated this phi node+ * @param out the use-def variable node for the output+ * @param options the map between block flows and options+ */+public record JitPhiOp(JitBlock block, JitOutVar out, BidiMap<BlockFlow, JitVal> options)+ implements JitDefOp, JitSyntheticOp {+ /**+ * Construct a phi node without any options, yet.+ *+ * @param block the block containing the op that generated this phi node+ * @param out the use-def variable node for the output+ */+ public JitPhiOp(JitBlock block, JitOutVar out) {+ this(block, out, new DualHashBidiMap<>());+ }++ /**+ * Add an option assuming the given flow is taken+ *+ * @param flow the flow+ * @param option the option+ */+ public void addOption(BlockFlow flow, JitVal option) {+ options.put(flow, option);+ option.addUse(this, 0); // HACK: 0 is as good as any position+ }++ /**+ * Check if one of the options is an {@link JitInputVar input} to the passage.+ *+ * @return true if an input option is present.+ */+ public boolean hasInputOption() {+ return options.values().stream().anyMatch(opt -> opt instanceof JitInputVar);+ }++ /**+ * Add the {@link JitInputVar input} option, if not already present+ */+ public void addInputOption() {+ if (!hasInputOption()) {+ addOption(BlockFlow.entry(block), new JitInputVar(out.varnode()));+ }+ }++ @Override+ public void link() {+ JitDefOp.super.link();+ for (JitVal input : options.values()) {+ input.addUse(this, 0);+ }+ }++ @Override+ public void unlink() {+ JitDefOp.super.unlink();+ for (JitVal input : options.values()) {+ input.removeUse(this, 0);+ }+ }++ /**+ * {@inheritDoc}+ *+ * @implNote While this says I should care about some defined order, it's only so that the type+ * of each operand can be derived. They all take the {@link JitTypeBehavior#COPY copy}+ * type, so I'm not concerned.+ */+ @Override+ public List<JitVal> inputs() {+ return List.copyOf(options.values());+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ if (position > options.size() || position < 0) {+ throw new AssertionError();+ }+ return optionType();+ }++ /**+ * We do not require a particular type for the value, but we note the result is the same.+ *+ * @return {@link JitTypeBehavior#COPY}+ */+ public JitTypeBehavior optionType() {+ return JitTypeBehavior.COPY;+ }++ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.COPY;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitPopCountOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitPopCountOp.javanew file mode 100644index 0000000000..eb0393d174--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitPopCountOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#POPCOUNT}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ */+public record JitPopCountOp(PcodeOp op, JitOutVar out, JitVal u) implements JitIntUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitStoreOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitStoreOp.javanew file mode 100644index 0000000000..37e4d19282--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitStoreOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#STORE}.+ *+ * @param op the p-code op+ * @param space the address space+ * @param offset the use-def node for the offset+ * @param value the use-def node for the value to store+ */+public record JitStoreOp(PcodeOp op, AddressSpace space, JitVal offset, JitVal value)+ implements JitOp {++ @Override+ public boolean canBeRemoved() {+ return false;+ }++ @Override+ public void link() {+ offset.addUse(this, 0);+ value.addUse(this, 1);+ }++ @Override+ public void unlink() {+ offset.removeUse(this, 0);+ value.removeUse(this, 1);+ }++ @Override+ public List<JitVal> inputs() {+ return List.of(offset, value);+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ return switch (position) {+ case 0 -> offsetType();+ case 1 -> valueType();+ default -> throw new AssertionError();+ };+ }++ /**+ * We'd like the offset to be an {@link JitTypeBehavior#INTEGER int}.+ *+ * @return {@link JitTypeBehavior#INTEGER}+ */+ public JitTypeBehavior offsetType() {+ return JitTypeBehavior.INTEGER;+ }++ /**+ * We do not require a particular type for the value.+ *+ * @return {@link JitTypeBehavior#ANY}+ */+ public JitTypeBehavior valueType() {+ return JitTypeBehavior.ANY;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSubPieceOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSubPieceOp.javanew file mode 100644index 0000000000..34ed01a50b--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSubPieceOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#SUBPIECE}.+ *+ * @param op the p-code op+ * @param out the use-def variable node for the output+ * @param u the use-def node for the input operand+ * @param offset the number of bytes to shift right+ */+public record JitSubPieceOp(PcodeOp op, JitOutVar out, JitVal u, int offset)+ implements JitIntUnOp {}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSynthSubPieceOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSynthSubPieceOp.javanew file mode 100644index 0000000000..70bee82ca8--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSynthSubPieceOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitOutVar;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The synthetic use-def node for subpiece.+ *+ * <p>+ * These are synthesized when memory/register access patterns cause only part of a use-def variable+ * node to be "read." E.g., consider {@code AX} to be written and then {@code AL} read. These are+ * different than {@link JitSubPieceOp} in that the latter have an actual {@link PcodeOp}+ * associated.+ *+ *+ * @param out the use-def variable node for the output+ * @param offset the offset, in bytes, to shift right+ * @param v the input use-def value node+ * @implNote Bits are shifted to the right by offset bytes. Then bits are truncated from the left to+ * force it to match the out var's size.+ */+public record JitSynthSubPieceOp(JitOutVar out, int offset, JitVal v)+ implements JitDefOp, JitSyntheticOp {+ /**+ * Compact constructor for validation.+ *+ * @param out the use-def variable node for the output+ * @param offset the offset, in bytes, to shift right+ * @param v the input use-def value node+ */+ public JitSynthSubPieceOp {+ if (offset < 0) {+ throw new IllegalArgumentException("Subpiece offset cannot be negative");+ }+ if (offset + out.size() > v.size()) {+ throw new IllegalArgumentException("Subpiece is outside input");+ }+ if (v.size() == out.size() && offset == 0) {+ throw new IllegalArgumentException("Subpiece is whole input");+ }+ }++ @Override+ public void link() {+ JitDefOp.super.link();+ v.addUse(this, 0);+ }++ @Override+ public void unlink() {+ JitDefOp.super.link();+ v.removeUse(this, 0);+ }++ @Override+ public List<JitVal> inputs() {+ return List.of(v);+ }++ /**+ * We'd like the input to be an {@link JitTypeBehavior#INTEGER int}.+ *+ * @return {@link JitTypeBehavior#INTEGER}+ */+ public JitTypeBehavior vType() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ public JitTypeBehavior type() {+ return JitTypeBehavior.INTEGER;+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ return switch (position) {+ case 0 -> vType();+ default -> throw new AssertionError();+ };+ }++ /**+ * Check if this piece abuts the given piece.+ *+ * <p>+ * To "abut," the pieces must take the same value as input, and then this piece's offset must be+ * exactly the other's offset plus its size. Consider this diagram:+ *+ * <pre>+ * [this][right]+ * </pre>+ *+ * <p>+ * We want this piece to be in the more-significant position immediately before the given piece.+ * We thus compute {@code diff} the difference in offsets and check if that is equal to the size+ * of the right piece. If it is, then we have:+ *+ * <pre>+ * [offset=x+diff,size=s][offset=x,size=diff]+ * </pre>+ *+ * <p>+ * And the "whole piece" is+ *+ * <pre>+ * [offset=x,size=s+diff]+ * </pre>+ *+ * @param right the piece to the right, i.e., less significant+ * @return true if the two pieces can be expressed as one whole+ */+ public boolean abuts(JitSynthSubPieceOp right) {+ int diff = this.offset() - right.offset();+ return right.out().size() == diff && this.v() == right.v();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSyntheticOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSyntheticOp.javanew file mode 100644index 0000000000..a9f448ea0a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitSyntheticOp.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.pcode.emu.jit.op;++import ghidra.pcode.emu.jit.analysis.JitVarScopeModel;+import ghidra.program.model.pcode.PcodeOp;++/**+ * A synthetic p-code operator use-def node.+ *+ * <p>+ * Synthetic nodes do not correspond to a {@link PcodeOp} emitted in the actual decoded passage.+ * Instead, they are created as part of the data flow analysis. They are used by downstream+ * analyzers, but do not directly result in any emitted bytecode.+ *+ * @see JitVarScopeModel+ */+public interface JitSyntheticOp extends JitOp {+ @Override+ default PcodeOp op() {+ throw new UnsupportedOperationException();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitUnOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitUnOp.javanew file mode 100644index 0000000000..40991e0021--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitUnOp.java@@ -0,0 +1,65 @@+/* ###+ * 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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;++/**+ * A p-code operator use-def node with one input and one output.+ */+public interface JitUnOp extends JitDefOp {+ /**+ * The use-def node for the input operand+ *+ * @return the input+ */+ JitVal u();++ @Override+ default void link() {+ JitDefOp.super.link();+ u().addUse(this, 0);+ }++ @Override+ default void unlink() {+ JitDefOp.super.unlink();+ u().removeUse(this, 0);+ }++ @Override+ default List<JitVal> inputs() {+ return List.of(u());+ }++ @Override+ default JitTypeBehavior typeFor(int position) {+ return switch (position) {+ case 0 -> uType();+ default -> throw new AssertionError();+ };+ }++ /**+ * The required type behavior for the operand+ *+ * @return the behavior+ */+ JitTypeBehavior uType();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitUnimplementedOp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitUnimplementedOp.javanew file mode 100644index 0000000000..cdddb80fd9--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/op/JitUnimplementedOp.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.pcode.emu.jit.op;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.program.model.pcode.PcodeOp;++/**+ * The use-def node for a {@link PcodeOp#UNIMPLEMENTED}.+ *+ * @param op the p-code op+ */+public record JitUnimplementedOp(PcodeOp op) implements JitOp {++ @Override+ public boolean canBeRemoved() {+ return false;+ }++ @Override+ public void link() {+ }++ @Override+ public void unlink() {+ }++ @Override+ public List<JitVal> inputs() {+ return List.of();+ }++ @Override+ public JitTypeBehavior typeFor(int position) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitOutVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitOutVar.javanew file mode 100644index 0000000000..d766db11f8--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitOutVar.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.pcode.emu.jit.var;++import ghidra.pcode.emu.jit.op.JitDefOp;+import ghidra.program.model.pcode.Varnode;++/**+ * An abstract implementation of {@link JitOutVar}.+ */+public abstract class AbstractJitOutVar extends AbstractJitVarnodeVar implements JitOutVar {+ private JitDefOp definition;++ /**+ * Construct a variable.+ *+ * @param id the unique id+ * @param varnode the varnode+ */+ public AbstractJitOutVar(int id, Varnode varnode) {+ super(id, varnode);+ }++ @Override+ public void setDefinition(JitDefOp definition) {+ this.definition = definition;+ }++ @Override+ public JitDefOp definition() {+ return definition;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVal.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVal.javanew file mode 100644index 0000000000..7ac5b9e475--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVal.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.pcode.emu.jit.var;++import java.util.ArrayList;+import java.util.List;++import ghidra.pcode.emu.jit.op.JitOp;++/**+ * An abstract implementation of {@link JitVal}.+ */+public abstract class AbstractJitVal implements JitVal {+ protected final int size;+ protected final List<ValUse> uses = new ArrayList<>();++ /**+ * Construct a value of the given size.+ *+ * @param size the size in bytes+ */+ public AbstractJitVal(int size) {+ this.size = size;+ }++ @Override+ public int size() {+ return size;+ }++ @Override+ public List<ValUse> uses() {+ return uses;+ }++ @Override+ public void addUse(JitOp op, int position) {+ uses.add(new ValUse(op, position));+ }++ @Override+ public void removeUse(JitOp op, int position) {+ uses.remove(new ValUse(op, position));+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVar.javanew file mode 100644index 0000000000..d72dc2fd07--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVar.java@@ -0,0 +1,44 @@+/* ###+ * 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.pcode.emu.jit.var;++/**+ * An abstract implementation of {@link JitVar}.+ */+public abstract class AbstractJitVar extends AbstractJitVal implements JitVar {+ protected final int id;++ /**+ * Construct a variable with the given id and size.+ *+ * @param id a unique id among all variables in the same use-def graph+ * @param size the size in bytes+ */+ public AbstractJitVar(int id, int size) {+ super(size);+ this.id = id;+ }++ @Override+ public int id() {+ return id;+ }++ @Override+ public String toString() {+ return "%s[id=%d]".formatted(getClass().getSimpleName(), id);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVarnodeVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVarnodeVar.javanew file mode 100644index 0000000000..b585468caa--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/AbstractJitVarnodeVar.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.pcode.emu.jit.var;++import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.Varnode;++/**+ * An abstract implementation of {@link JitVarnodeVar}.+ */+public abstract class AbstractJitVarnodeVar extends AbstractJitVar implements JitVarnodeVar {+ protected final Varnode varnode;++ /**+ * Construct a variable.+ *+ * @param id the unique id+ * @param varnode the varnode+ */+ public AbstractJitVarnodeVar(int id, Varnode varnode) {+ super(id, varnode.getSize());+ if (varnode.getSize() < 1) {+ throw new IllegalArgumentException("Varnode must have size at least 1");+ }+ this.varnode = varnode;+ }++ @Override+ public Varnode varnode() {+ return varnode;+ }++ @Override+ public AddressSpace space() {+ return varnode.getAddress().getAddressSpace();+ }++ @Override+ public String toString() {+ return "%s[id=%d,varnode=%s]".formatted(getClass().getSimpleName(), id, varnode);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitConstVal.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitConstVal.javanew file mode 100644index 0000000000..1d9ead7fc4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitConstVal.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.pcode.emu.jit.var;++import java.math.BigInteger;++/**+ * A p-code constant use-def node.+ */+public class JitConstVal extends AbstractJitVal {+ private final BigInteger value;++ /**+ * Construct a constant.+ *+ * <p>+ * Use {@link JitVal#constant(int, BigInteger)} instead.+ *+ * @param size the size in bytes+ * @param value the value+ */+ public JitConstVal(int size, BigInteger value) {+ super(size);+ this.value = value;+ }++ @Override+ public String toString() {+ return "%s[value=%s]".formatted(getClass().getSimpleName(), value);+ }++ /**+ * The value of this constant.+ *+ * @return the value+ */+ public BigInteger value() {+ return value;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitDirectMemoryVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitDirectMemoryVar.javanew file mode 100644index 0000000000..ec9cc7c42a--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitDirectMemoryVar.java@@ -0,0 +1,42 @@+/* ###+ * 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.pcode.emu.jit.var;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.analysis.JitDataFlowModel;+import ghidra.program.model.pcode.Varnode;++/**+ * A p-code variable node with a fixed location in memory.+ *+ * <p>+ * This represents an input operand located in memory. Its value can be accessed directly from the+ * {@link JitBytesPcodeExecutorState state} at run time.+ *+ * @see JitMemoryOutVar+ */+public class JitDirectMemoryVar extends AbstractJitVarnodeVar implements JitMemoryVar {+ /**+ * Construct a variable.+ *+ * @param id the unique id+ * @param varnode the varnode+ * @see JitDataFlowModel#generateDirectMemoryVar(Varnode)+ */+ public JitDirectMemoryVar(int id, Varnode varnode) {+ super(id, varnode);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitIndirectMemoryVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitIndirectMemoryVar.javanew file mode 100644index 0000000000..6865d3f379--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitIndirectMemoryVar.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.pcode.emu.jit.var;++import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitDataFlowArithmetic;+import ghidra.pcode.emu.jit.analysis.JitDataFlowState;+import ghidra.pcode.emu.jit.op.JitLoadOp;+import ghidra.pcode.emu.jit.op.JitOp;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.pcode.PcodeOp;++/**+ * A dummy variable node representing an indirect memory access.+ *+ * <p>+ * These are caused by {@link PcodeOp#LOAD}, since that is the only manner in which the+ * {@link JitDataFlowState} can be accessed with a non-constant offset. However, the node is+ * immediately dropped on the floor by+ * {@link JitDataFlowArithmetic#modAfterLoad(PcodeOp, AddressSpace, JitVal, JitVal)}, which instead+ * places the {@link JitLoadOp} into the use-def graph. This just exists so we don't return+ * {@code null}.+ */+public enum JitIndirectMemoryVar implements JitMemoryVar {+ /** Singleton */+ INSTANCE;++ @Override+ public int size() {+ return 0;+ }++ @Override+ public List<ValUse> uses() {+ return List.of();+ }++ @Override+ public void addUse(JitOp op, int position) {+ throw new UnsupportedOperationException();+ }++ @Override+ public void removeUse(JitOp op, int position) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int id() {+ return -1;+ }++ @Override+ public AddressSpace space() {+ return null;+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitInputVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitInputVar.javanew file mode 100644index 0000000000..ed46870369--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitInputVar.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.pcode.emu.jit.var;++import ghidra.pcode.emu.jit.op.JitPhiOp;+import ghidra.program.model.pcode.Varnode;++/**+ * A p-code variable that is an input to a passage, i.e., there are reads possible before writes.+ *+ * <p>+ * These only appear as options to a {@link JitPhiOp phi} node. They are very common, because any+ * block that is also a valid passage entry (which is most of them) can have an option that is+ * defined outside the passage. It may very well be the only option.+ *+ * @implNote We delay creation of passage-input variables until inter-block analysis, because the+ * variable must turn up missing (i.e., not be defined prior in the same block) before we+ * can consider it might be a passage input. We thus create a {@link JitPhiOp phi} node+ * for it and record the input as just one of many options. We had at one point+ * "simplified" single-option phi nodes, which covered the case where the varnode is+ * <em>certainly</em> a passage input, but we found it difficult in terms of bookkeeping.+ * Also, because of our variable allocation strategy, such simplification offered no real+ * value during code generation.+ */+public class JitInputVar extends AbstractJitVarnodeVar {+ /**+ * Construct a variable.+ *+ * @param varnode the varnode+ * @see JitPhiOp#addInputOption()+ */+ public JitInputVar(Varnode varnode) {+ super(-1, varnode);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitLocalOutVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitLocalOutVar.javanew file mode 100644index 0000000000..4e76f23169--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitLocalOutVar.java@@ -0,0 +1,40 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.pcode.emu.jit.var;++import ghidra.pcode.emu.jit.analysis.JitDataFlowModel;+import ghidra.program.model.pcode.Varnode;++/**+ * A p-code register or unique variable with a defining p-code op.+ *+ * <p>+ * This represents an output operand located in a thread's "local" state, i.e., it is a+ * {@code register} or {@code unique} variable. These can be used by downstream p-code ops in the+ * use-def graph, because we wish to analyze this flow and optimize the generated code.+ */+public class JitLocalOutVar extends AbstractJitOutVar {+ /**+ * Construct a variable.+ *+ * @param id the unique id+ * @param varnode the varnode+ * @see JitDataFlowModel#generateOutVar(Varnode)+ */+ public JitLocalOutVar(int id, Varnode varnode) {+ super(id, varnode);+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMemoryOutVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMemoryOutVar.javanew file mode 100644index 0000000000..ab8b281bca--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMemoryOutVar.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.pcode.emu.jit.var;++import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;+import ghidra.pcode.emu.jit.analysis.JitDataFlowModel;+import ghidra.pcode.emu.jit.op.JitOp;+import ghidra.program.model.pcode.Varnode;++/**+ * A p-code variable node with a fixed location in memory and a defining p-code op.+ *+ * <p>+ * This represents an output operand located in memory. It can be addressed directly. In contrast to+ * {@link JitLocalOutVar}, these <em>may not</em> be used by downstream p-code ops in the use-def+ * graph, because the output is written to the {@link JitBytesPcodeExecutorState state} immediately.+ * There's no benefit to further analysis. Instead, ops that use the same varnode will take a+ * {@link JitDirectMemoryVar}, which indicate input immediately from the+ * {@link JitBytesPcodeExecutorState state}.+ *+ * @see JitDirectMemoryVar+ */+public class JitMemoryOutVar extends AbstractJitOutVar implements JitMemoryVar {+ /**+ * Construct a variable.+ *+ * @param id the unique id+ * @param varnode the varnode+ * @see JitDataFlowModel#generateOutVar(Varnode)+ */+ public JitMemoryOutVar(int id, Varnode varnode) {+ super(id, varnode);+ }++ @Override+ public void addUse(JitOp op, int position) {+ throw new AssertionError();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMemoryVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMemoryVar.javanew file mode 100644index 0000000000..6298488dea--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMemoryVar.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.pcode.emu.jit.var;++/**+ * A p-code variable located in memory.+ *+ * <p>+ * The offset could be fixed or variable. The variable is shared among all threads.+ */+public interface JitMemoryVar extends JitVar {+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMissingVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMissingVar.javanew file mode 100644index 0000000000..1c54f05bda--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitMissingVar.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.pcode.emu.jit.var;++import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitDataFlowModel;+import ghidra.pcode.emu.jit.analysis.JitDataFlowState;+import ghidra.pcode.emu.jit.op.JitPhiOp;+import ghidra.program.model.pcode.Varnode;++/**+ * A p-code variable whose definition could not be determined.+ *+ * <p>+ * This is only applicable to {@code register} and {@code unique} variables. It indicates the+ * {@link JitDataFlowState} had not recorded a definition for the variable's varnode (or some+ * portion of it) prior in the same block. These should never enter the use-def graph. Instead, each+ * should be replaced by a {@link JitOutVar} defined by a {@link JitPhiOp phi} node. The phi node's+ * options are determined later during {@link JitDataFlowModel inter-block} analysis.+ *+ * @see #generatePhi(JitDataFlowModel, JitBlock)+ */+public class JitMissingVar extends AbstractJitVarnodeVar {+ /**+ * Construct a variable.+ *+ * @param varnode the varnode+ */+ public JitMissingVar(Varnode varnode) {+ super(-1, varnode);+ }++ /**+ * Create the {@link JitPhiOp phi} node for this missing variable.+ *+ * The resulting node and its {@link JitPhiOp#out() output} are added to the use-def graph. Note+ * that this missing variable never enters the use-def graph. The phi's output takes the place+ * of this variable.+ *+ * @param dfm the data flow model+ * @param block the block containing the op that accessed the varnode+ * @return the generated phi op+ * @see JitDataFlowModel Inter-block data flow analysis+ */+ public JitPhiOp generatePhi(JitDataFlowModel dfm, JitBlock block) {+ return dfm.notifyOp(new JitPhiOp(block, dfm.generateOutVar(varnode)));+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitOutVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitOutVar.javanew file mode 100644index 0000000000..e5f9bfa87f--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitOutVar.java@@ -0,0 +1,42 @@+/* ###+ * 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.pcode.emu.jit.var;++import ghidra.pcode.emu.jit.op.JitDefOp;++/**+ * A p-code variable node with a defining p-code op.+ */+public interface JitOutVar extends JitVarnodeVar {+ /**+ * Set the defining p-code operator node+ *+ * @param definition the defining node+ */+ void setDefinition(JitDefOp definition);++ /**+ * The defining p-code operator node+ *+ * <p>+ * This should "never" be null. The only exception is the short interim between constructing the+ * node and setting its definition. Once this variable has been entered into the use-def graph,+ * the definition should be non-null and final.+ *+ * @return the defining node+ */+ JitDefOp definition();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVal.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVal.javanew file mode 100644index 0000000000..f11a6a9d9d--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVal.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.pcode.emu.jit.var;++import java.math.BigInteger;+import java.util.List;++import ghidra.pcode.emu.jit.analysis.JitOpUseModel;+import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;+import ghidra.pcode.emu.jit.gen.var.ValGen;+import ghidra.pcode.emu.jit.op.JitOp;+import ghidra.pcode.emu.jit.op.JitPhiOp;++/**+ * A p-code value use-def node.+ *+ * <p>+ * For a table of value/variable node classes and generators, see {@link ValGen}.+ */+public interface JitVal {+ /**+ * The use of a value node by an operator node.+ *+ * @param op the operator node+ * @param position the position of the operand in the operator's inputs+ */+ record ValUse(JitOp op, int position) {+ public JitTypeBehavior type() {+ return op.typeFor(position);+ }+ }++ /**+ * Create a constant value.+ *+ * @param size the size in bytes+ * @param value the value+ * @return the value node+ */+ static JitConstVal constant(int size, BigInteger value) {+ return new JitConstVal(size, value);+ }++ /**+ * The size in bytes.+ *+ * @return the size+ */+ int size();++ /**+ * The list of uses.+ *+ * @return the uses+ */+ List<ValUse> uses();++ /**+ * Add a use.+ *+ * <p>+ * In most cases, uses should be final, once this value node has been entered into the use-def+ * graph. An exception deals with {@link JitPhiOp phi} nodes, as this analysis occurs after each+ * intra-block portion of the graph has been constructed. During inter-block analysis,+ * additional uses will get recorded. Even further uses may be recorded uding+ * {@link JitOpUseModel op-use} analysis, since it may generate more {@link JitPhiOp phi} nodes.+ *+ * @param op the operator node using this one+ * @param position the position of this value in the operator's input operands+ */+ void addUse(JitOp op, int position);++ /**+ * Remove a use.+ *+ * @param op as in {@link #addUse(JitOp, int)}+ * @param position as in {@link #addUse(JitOp, int)}+ * @see #addUse(JitOp, int)+ */+ void removeUse(JitOp op, int position);+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVar.javanew file mode 100644index 0000000000..f4442887f3--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVar.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.pcode.emu.jit.var;++import ghidra.program.model.address.AddressSpace;++/**+ * A p-code variable use-def node.+ */+public interface JitVar extends JitVal {+ /**+ * A unique id for this variable+ *+ * @return the id+ */+ int id();++ /**+ * The address space of this variable.+ *+ * @return the space+ */+ AddressSpace space();+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVarnodeVar.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVarnodeVar.javanew file mode 100644index 0000000000..0f860138e4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitVarnodeVar.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.pcode.emu.jit.var;++import ghidra.program.model.pcode.Varnode;++/**+ * A p-code variable node with a fixed address (given by a {@link Varnode}).+ */+public interface JitVarnodeVar extends JitVar {+ /**+ * The location of the variable.+ *+ * @return the varnode+ */+ Varnode varnode();++ @Override+ default int size() {+ return varnode().getSize();+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AddressesReadPcodeArithmetic.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AddressesReadPcodeArithmetic.javaindex 433e5df88b..316a46b2b5 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AddressesReadPcodeArithmetic.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AddressesReadPcodeArithmetic.java@@ -19,8 +19,7 @@ import java.math.BigInteger;import javax.help.UnsupportedOperationException;-import ghidra.program.model.address.AddressSet;-import ghidra.program.model.address.AddressSetView;+import ghidra.program.model.address.*;import ghidra.program.model.lang.Endian;/**@@ -48,15 +47,15 @@ public enum AddressesReadPcodeArithmetic implements PcodeArithmetic<AddressSetVi}@Override- public AddressSetView modBeforeStore(int sizeout, int sizeinAddress, AddressSetView inAddress,- int sizeinValue, AddressSetView inValue) {+ public AddressSetView modBeforeStore(int sizeinOffset, AddressSpace space,+ AddressSetView inOffset, int sizeinValue, AddressSetView inValue) {return inValue;}@Override- public AddressSetView modAfterLoad(int sizeout, int sizeinAddress, AddressSetView inAddress,- int sizeinValue, AddressSetView inValue) {- return inValue == null || inAddress == null ? null : inValue.union(inAddress);+ public AddressSetView modAfterLoad(int sizeinAddress, AddressSpace space,+ AddressSetView inOffset, int sizeinValue, AddressSetView inValue) {+ return inValue == null || inOffset == null ? null : inValue.union(inOffset);}@Overridediff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibrary.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibrary.javaindex dd3fd1cf8e..55a0f1422e 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibrary.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibrary.java@@ -4,9 +4,9 @@* 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.@@ -26,6 +26,7 @@ import java.util.stream.Stream;import org.apache.commons.lang3.reflect.TypeUtils;+import ghidra.pcode.exec.PcodeArithmetic.Purpose;import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;import ghidra.program.model.pcode.Varnode;import utilities.util.AnnotationUtilities;@@ -179,19 +180,41 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibraprotected static abstract class AnnotatedPcodeUseropDefinition<T>implements PcodeUseropDefinition<T> {+ protected static boolean isPrimitive(Type type) {+ return type instanceof Class<?> cls && cls.isPrimitive();+ }+protected static <T> AnnotatedPcodeUseropDefinition<T> create(PcodeUserop annot,AnnotatedPcodeUseropLibrary<T> library, Type opType, Lookup lookup, Method method) {if (annot.variadic()) {return new VariadicAnnotatedPcodeUseropDefinition<>(library, opType, lookup,- method);- }- else {- return new FixedArgsAnnotatedPcodeUseropDefinition<>(library, opType, lookup,- method);+ method, annot);}+ return new FixedArgsAnnotatedPcodeUseropDefinition<>(library, opType, lookup,+ method, annot);+ }++ @SuppressWarnings("unchecked")+ protected static <T> T fromPrimitive(Object value, int size,+ PcodeArithmetic<T> arithmetic) {+ return switch (value) {+ case null -> null;+ case Byte v -> arithmetic.fromConst(v, size);+ case Short v -> arithmetic.fromConst(v, size);+ case Integer v -> arithmetic.fromConst(v, size);+ case Long v -> arithmetic.fromConst(v, size);+ case Float v -> arithmetic.fromConst(v, size);+ case Double v -> arithmetic.fromConst(v, size);+ case Boolean v -> arithmetic.fromConst(v, size);+ default -> (T) value;+ };}protected final Method method;+ private final AnnotatedPcodeUseropLibrary<T> library;+ private final boolean isFunctional;+ private final boolean hasSideEffects;+ private final boolean canInline;private final MethodHandle handle;private int posExecutor = -1;@@ -200,9 +223,10 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibraprivate int posOut = -1;public AnnotatedPcodeUseropDefinition(AnnotatedPcodeUseropLibrary<T> library, Type opType,- Lookup lookup, Method method) {+ Lookup lookup, Method method, PcodeUserop annot) {initStarting();this.method = method;+ this.library = library;try {this.handle = lookup.unreflect(method).bindTo(library);}@@ -214,11 +238,12 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibra}Type declClsOpType = PcodeUseropLibrary.getOperandType(method.getDeclaringClass());Type rType = method.getGenericReturnType();- if (rType != void.class && !TypeUtils.isAssignable(rType, declClsOpType)) {- throw new IllegalArgumentException(- "Method " + method.getName() + " with @" +- PcodeUserop.class.getSimpleName() +- " annotation must return void or a type assignable to " + declClsOpType);+ if (!isPrimitive(rType) && !TypeUtils.isAssignable(rType, declClsOpType) ||+ rType == char.class) {+ throw new IllegalArgumentException("""+ Method %s with @%s annotation must return a non-char primitive type, \+ void, or a type assignable to %s.""".formatted(+ method.getName(), PcodeUserop.class.getSimpleName(), declClsOpType));}Parameter[] params = method.getParameters();@@ -230,6 +255,9 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibra}}initFinished();+ this.isFunctional = annot.functional();+ this.canInline = annot.canInline();+ this.hasSideEffects = annot.hasSideEffects();}@Override@@ -260,10 +288,10 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibraplaceInputs(executor, args, inVars);try {- @SuppressWarnings("unchecked")- T result = (T) handle.invokeWithArguments(args);+ Object result = handle.invokeWithArguments(args);if (result != null && outVar != null) {- state.setVar(outVar, result);+ state.setVar(outVar,+ fromPrimitive(result, outVar.getSize(), executor.getArithmetic()));}}catch (PcodeExecutionException e) {@@ -274,6 +302,31 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibra}}+ @Override+ public boolean isFunctional() {+ return isFunctional;+ }++ @Override+ public boolean hasSideEffects() {+ return hasSideEffects;+ }++ @Override+ public boolean canInlinePcode() {+ return canInline;+ }++ @Override+ public Method getJavaMethod() {+ return method;+ }++ @Override+ public PcodeUseropLibrary<T> getDefiningLibrary() {+ return library;+ }+protected void initStarting() {// Optional override}@@ -301,18 +354,103 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibraprotected static class FixedArgsAnnotatedPcodeUseropDefinition<T>extends AnnotatedPcodeUseropDefinition<T> {- private List<Integer> posIns;- private Set<Integer> posTs;+ interface UseropInputParam {+ int position();++ <T> Object convert(Varnode vn, PcodeExecutor<T> executor);+ }++ record VarnodeUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ return vn;+ }+ }++ record TValUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<?, ?> state = executor.getState();+ return state.getVar(vn, executor.getReason());+ }+ }++ record ByteUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<T, T> state = executor.getState();+ PcodeArithmetic<T> arithmetic = executor.getArithmetic();+ return (byte) arithmetic.toLong(state.getVar(vn, executor.getReason()),+ Purpose.OTHER);+ }+ }++ record ShortUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<T, T> state = executor.getState();+ PcodeArithmetic<T> arithmetic = executor.getArithmetic();+ return (short) arithmetic.toLong(state.getVar(vn, executor.getReason()),+ Purpose.OTHER);+ }+ }++ record IntUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<T, T> state = executor.getState();+ PcodeArithmetic<T> arithmetic = executor.getArithmetic();+ return (int) arithmetic.toLong(state.getVar(vn, executor.getReason()),+ Purpose.OTHER);+ }+ }++ record LongUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<T, T> state = executor.getState();+ PcodeArithmetic<T> arithmetic = executor.getArithmetic();+ return arithmetic.toLong(state.getVar(vn, executor.getReason()), Purpose.OTHER);+ }+ }++ record FloatUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<T, T> state = executor.getState();+ PcodeArithmetic<T> arithmetic = executor.getArithmetic();+ return arithmetic.toFloat(state.getVar(vn, executor.getReason()), Purpose.OTHER);+ }+ }++ record DoubleUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<T, T> state = executor.getState();+ PcodeArithmetic<T> arithmetic = executor.getArithmetic();+ return arithmetic.toDouble(state.getVar(vn, executor.getReason()), Purpose.OTHER);+ }+ }++ record BooleanUseropInputParam(int position) implements UseropInputParam {+ @Override+ public <T> Object convert(Varnode vn, PcodeExecutor<T> executor) {+ PcodeExecutorStatePiece<T, T> state = executor.getState();+ PcodeArithmetic<T> arithmetic = executor.getArithmetic();+ return arithmetic.toBoolean(state.getVar(vn, executor.getReason()), Purpose.OTHER);+ }+ }++ private List<UseropInputParam> paramsIn;public FixedArgsAnnotatedPcodeUseropDefinition(AnnotatedPcodeUseropLibrary<T> library,- Type opType, Lookup lookup, Method method) {- super(library, opType, lookup, method);+ Type opType, Lookup lookup, Method method, PcodeUserop annot) {+ super(library, opType, lookup, method, annot);}@Overrideprotected void initStarting() {- posIns = new ArrayList<>();- posTs = new HashSet<>();+ paramsIn = new ArrayList<>();}@Override@@ -320,26 +458,49 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibraParameter p) {Type pType = p.getParameterizedType();if (TypeUtils.isAssignable(Varnode.class, pType)) {- // Just use the Varnode by default+ paramsIn.add(new VarnodeUseropInputParam(i));}else if (TypeUtils.isAssignable(declClsOpType, pType)) {- posTs.add(i);+ paramsIn.add(new TValUseropInputParam(i));+ }+ else if (pType == byte.class) {+ paramsIn.add(new ByteUseropInputParam(i));+ }+ else if (pType == short.class) {+ paramsIn.add(new ShortUseropInputParam(i));+ }+ else if (pType == int.class) {+ paramsIn.add(new IntUseropInputParam(i));+ }+ else if (pType == long.class) {+ paramsIn.add(new LongUseropInputParam(i));+ }+ else if (pType == float.class) {+ paramsIn.add(new FloatUseropInputParam(i));+ }+ else if (pType == double.class) {+ paramsIn.add(new DoubleUseropInputParam(i));+ }+ else if (pType == boolean.class) {+ paramsIn.add(new BooleanUseropInputParam(i));}else {- throw new IllegalArgumentException("Input parameter " + p.getName() +- " of userop " + method.getName() + " must be " +- Varnode.class.getSimpleName() + " or accept " + declClsOpType);+ throw new IllegalArgumentException("""+ Input parameter %s of userop %s must be non-char primitive type, \+ %s, or accept %s. Was %s.+ """.formatted(+ p.getName(), method.getName(), Varnode.class.getSimpleName(), declClsOpType,+ pType));}- posIns.add(i);}@Overrideprotected void validateInputs(List<Varnode> inVars)throws PcodeExecutionException {- if (inVars.size() != posIns.size()) {+ if (inVars.size() != paramsIn.size()) {throw new PcodeExecutionException("Incorrect input parameter count for userop " +- method.getName() + ". Expected " + posIns.size() + " but got " ++ method.getName() + ". Expected " + paramsIn.size() + " but got " +inVars.size());}}@@ -347,21 +508,15 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibra@Overrideprotected void placeInputs(PcodeExecutor<T> executor, List<Object> args,List<Varnode> inVars) {- PcodeExecutorStatePiece<T, T> state = executor.getState();- for (int i = 0; i < posIns.size(); i++) {- int pos = posIns.get(i);- if (posTs.contains(pos)) {- args.set(pos, state.getVar(inVars.get(i), executor.getReason()));- }- else {- args.set(pos, inVars.get(i));- }+ for (int i = 0; i < paramsIn.size(); i++) {+ UseropInputParam ip = paramsIn.get(i);+ args.set(ip.position(), ip.convert(inVars.get(i), executor));}}@Overridepublic int getInputCount() {- return posIns.size();+ return paramsIn.size();}}@@ -377,8 +532,8 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibraprivate Class<?> opRawType;public VariadicAnnotatedPcodeUseropDefinition(AnnotatedPcodeUseropLibrary<T> library,- Type opType, Lookup lookup, Method method) {- super(library, opType, lookup, method);+ Type opType, Lookup lookup, Method method, PcodeUserop annot) {+ super(library, opType, lookup, method, annot);}@Override@@ -483,9 +638,36 @@ public abstract class AnnotatedPcodeUseropLibrary<T> implements PcodeUseropLibra@Target(ElementType.METHOD)public @interface PcodeUserop {/**- * Set to true to receive all inputs in an array+ * Set to true to receive all inputs in an array.*/boolean variadic() default false;++ /**+ * Set to true to attest that the userop is a pure function.+ *+ * <p>+ * An incorrect attestation can lead to erroneous execution results.+ *+ * @see PcodeUseropLibrary.PcodeUseropDefinition#isFunctional()+ */+ boolean functional() default false;++ /**+ * Set to false to attest the userop has no side effects.+ *+ * <p>+ * An incorrect attestation can lead to erroneous execution results.+ *+ * @see PcodeUseropLibrary.PcodeUseropDefinition#hasSideEffects()+ */+ boolean hasSideEffects() default true;++ /**+ * Set to true to suggest inlining.+ *+ * @see PcodeUseropLibrary.PcodeUseropDefinition#canInlinePcode()+ */+ boolean canInline() default false;}/**diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeArithmetic.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeArithmetic.javaindex 83a55ad284..4806d47874 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeArithmetic.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeArithmetic.java@@ -19,6 +19,7 @@ import java.math.BigInteger;import ghidra.pcode.opbehavior.*;import ghidra.pcode.utils.Utils;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.Endian;import ghidra.program.model.lang.Language;@@ -102,14 +103,14 @@ public enum BytesPcodeArithmetic implements PcodeArithmetic<byte[]> {}@Override- public byte[] modBeforeStore(int sizeout, int sizeinAddress, byte[] inAddress, int sizeinValue,- byte[] inValue) {+ public byte[] modBeforeStore(int sizeinOffset, AddressSpace space, byte[] inOffset,+ int sizeinValue, byte[] inValue) {return inValue;}@Override- public byte[] modAfterLoad(int sizeout, int sizeinAddress, byte[] inAddress, int sizeinValue,- byte[] inValue) {+ public byte[] modAfterLoad(int sizeinOffset, AddressSpace space, byte[] inOffset,+ int sizeinValue, byte[] inValue) {return inValue;}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeExecutorStateSpace.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeExecutorStateSpace.javaindex 9905227b50..d08ef6f869 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeExecutorStateSpace.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/BytesPcodeExecutorStateSpace.java@@ -4,9 +4,9 @@* 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.@@ -69,6 +69,8 @@ public class BytesPcodeExecutorStateSpace<B> {** @param offset the offset* @param val the value+ * @param srcOffset offset within val to start+ * @param length the number of bytes to write*/public void write(long offset, byte[] val, int srcOffset, int length) {bytes.putData(offset, val, srcOffset, length);@@ -160,6 +162,25 @@ public class BytesPcodeExecutorStateSpace<B> {warnAddressSet("Emulator read from uninitialized state", uninitialized);}+ /**+ * Compute the uninitialized span set, considering possible wrap-around+ *+ * @param offset the offset+ * @param size the number of bytes+ * @return the uninitialized offset ranges+ */+ protected ULongSpanSet computeUninitialized(long offset, int size) {+ long max = offset + size - 1;+ if (max <= space.getMaxAddress().getOffset()) {+ return bytes.getUninitialized(offset, max);+ }+ long end = space.getMinAddress().getOffset() + max - space.getMaxAddress().getOffset() - 1;+ MutableULongSpanSet result = new DefaultULongSpanSet();+ result.addAll(bytes.getUninitialized(offset, space.getMaxAddress().getOffset()));+ result.addAll(bytes.getUninitialized(space.getMinAddress().getOffset(), end));+ return result;+ }+/*** Read a value from the space at the given offset*@@ -174,7 +195,7 @@ public class BytesPcodeExecutorStateSpace<B> {* @return the bytes read*/public byte[] read(long offset, int size, Reason reason) {- ULongSpanSet uninitialized = bytes.getUninitialized(offset, offset + size - 1);+ ULongSpanSet uninitialized = computeUninitialized(offset, size);if (uninitialized.isEmpty()) {return readBytes(offset, size, reason);}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/LocationPcodeArithmetic.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/LocationPcodeArithmetic.javaindex 36dfb9670a..f84049fda7 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/LocationPcodeArithmetic.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/LocationPcodeArithmetic.java@@ -18,6 +18,7 @@ package ghidra.pcode.exec;import java.math.BigInteger;import ghidra.pcode.utils.Utils;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.Endian;import ghidra.program.model.pcode.PcodeOp;@@ -79,13 +80,13 @@ public enum LocationPcodeArithmetic implements PcodeArithmetic<ValueLocation> {}@Override- public ValueLocation modBeforeStore(int sizeout, int sizeinAddress, ValueLocation inAddress,- int sizeinValue, ValueLocation inValue) {+ public ValueLocation modBeforeStore(int sizeinOffset, AddressSpace space,+ ValueLocation inOffset, int sizeinValue, ValueLocation inValue) {return inValue;}@Override- public ValueLocation modAfterLoad(int sizeout, int sizeinAddress, ValueLocation inAddress,+ public ValueLocation modAfterLoad(int sizeinOffset, AddressSpace space, ValueLocation inOffset,int sizeinValue, ValueLocation inValue) {return inValue;}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PairedPcodeArithmetic.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PairedPcodeArithmetic.javaindex c620802fb8..53dabfa98a 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PairedPcodeArithmetic.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PairedPcodeArithmetic.java@@ -19,6 +19,7 @@ import java.util.Objects;import org.apache.commons.lang3.tuple.Pair;+import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.Endian;import ghidra.program.model.pcode.PcodeOp;@@ -115,22 +116,38 @@ public class PairedPcodeArithmetic<L, R> implements PcodeArithmetic<Pair<L, R>>}@Override- public Pair<L, R> modBeforeStore(int sizeout, int sizeinAddress, Pair<L, R> inAddress,+ public Pair<L, R> modBeforeStore(PcodeOp op, AddressSpace space, Pair<L, R> inOffset,+ Pair<L, R> inValue) {+ return Pair.of(+ leftArith.modBeforeStore(op, space, inOffset.getLeft(), inValue.getLeft()),+ rightArith.modBeforeStore(op, space, inOffset.getRight(), inValue.getRight()));+ }++ @Override+ public Pair<L, R> modBeforeStore(int sizeinOffset, AddressSpace space, Pair<L, R> inOffset,int sizeinValue, Pair<L, R> inValue) {return Pair.of(- leftArith.modBeforeStore(sizeout, sizeinAddress, inAddress.getLeft(), sizeinValue,+ leftArith.modBeforeStore(sizeinOffset, space, inOffset.getLeft(), sizeinValue,inValue.getLeft()),- rightArith.modBeforeStore(sizeout, sizeinAddress, inAddress.getRight(), sizeinValue,+ rightArith.modBeforeStore(sizeinOffset, space, inOffset.getRight(), sizeinValue,inValue.getRight()));}@Override- public Pair<L, R> modAfterLoad(int sizeout, int sizeinAddress, Pair<L, R> inAddress,+ public Pair<L, R> modAfterLoad(PcodeOp op, AddressSpace space, Pair<L, R> inOffset,+ Pair<L, R> inValue) {+ return Pair.of(+ leftArith.modAfterLoad(op, space, inOffset.getLeft(), inValue.getLeft()),+ rightArith.modAfterLoad(op, space, inOffset.getRight(), inValue.getRight()));+ }++ @Override+ public Pair<L, R> modAfterLoad(int sizeinOffset, AddressSpace space, Pair<L, R> inOffset,int sizeinValue, Pair<L, R> inValue) {return Pair.of(- leftArith.modAfterLoad(sizeout, sizeinAddress, inAddress.getLeft(), sizeinValue,+ leftArith.modAfterLoad(sizeinOffset, space, inOffset.getLeft(), sizeinValue,inValue.getLeft()),- rightArith.modAfterLoad(sizeout, sizeinAddress, inAddress.getRight(), sizeinValue,+ rightArith.modAfterLoad(sizeinOffset, space, inOffset.getRight(), sizeinValue,inValue.getRight()));}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeArithmetic.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeArithmetic.javaindex d8a3fd2e89..152f849202 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeArithmetic.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeArithmetic.java@@ -4,9 +4,9 @@* 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.@@ -20,7 +20,8 @@ import java.math.BigInteger;import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;import ghidra.pcode.opbehavior.*;import ghidra.pcode.utils.Utils;-import ghidra.program.model.lang.Endian;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.*;import ghidra.program.model.pcode.PcodeOp;/**@@ -239,32 +240,70 @@ public interface PcodeArithmetic<T> {** <p>* This implements any abstractions associated with {@link PcodeOp#STORE}. This is called on the- * address/offset and the value before the value is actually stored into the state.+ * offset and the value before the value is actually stored into the state. <b>NOTE:</b> STORE+ * ops always quantize the offset.*- * @param sizeout the size (in bytes) of the output variable- * @param sizeinAddress the size (in bytes) of the variable used for indirection- * @param inAddress the value used as the address (or offset)- * @param sizeinValue the size (in bytes) of the variable to store+ * @param sizeinOffset the size (in bytes) of the variable used for indirection+ * @param space the address space+ * @param inOffset the value used as the address (or offset)+ * @param sizeinValue the size (in bytes) of the variable to store and of the output variable+ * @param inValue the value to store+ * @return the modified value to store+ */+ T modBeforeStore(int sizeinOffset, AddressSpace space, T inOffset, int sizeinValue, T inValue);++ /**+ * Apply any modifications before a value is stored+ *+ * <p>+ * This provides the full p-code op, allowing deeper inspection of the code. <b>NOTE:</b> STORE+ * ops always quantize the offset.+ *+ * @param op the operation+ * @param space the address space+ * @param inOffset the value used as the offset* @param inValue the value to store* @return the modified value to store*/- T modBeforeStore(int sizeout, int sizeinAddress, T inAddress, int sizeinValue, T inValue);+ default T modBeforeStore(PcodeOp op, AddressSpace space, T inOffset, T inValue) {+ return modBeforeStore(op.getInput(1).getSize(), space, inOffset, op.getInput(2).getSize(),+ inValue);+ }/*** Apply any modifications after a value is loaded** <p>* This implements any abstractions associated with {@link PcodeOp#LOAD}. This is called on the- * address/offset and the value after the value is actually loaded from the state.+ * address/offset and the value after the value is actually loaded from the state. <b>NOTE:</b>+ * LOAD ops always quantize the offset.*- * @param sizeout the size (in bytes) of the output variable- * @param sizeinAddress the size (in bytes) of the variable used for indirection- * @param inAddress the value used as the address (or offset)- * @param sizeinValue the size (in bytes) of the variable loaded+ * @param sizeinOffset the size (in bytes) of the variable used for indirection+ * @param space the address space+ * @param inOffset the value used as the offset+ * @param sizeinValue the size (in bytes) of the variable loaded and of the output variable+ * @param inValue the value loaded+ * @return the modified value loaded+ */+ T modAfterLoad(int sizeinOffset, AddressSpace space, T inOffset, int sizeinValue, T inValue);++ /**+ * Apply any modifications after a value is loaded+ *+ * <p>+ * This provides the full p-code op, allowing deeper inspection of the code. <b>NOTE:</b> LOAD+ * ops always quantize the offset.+ *+ * @param op the operation+ * @param space the address space+ * @param inOffset the value used as the offset* @param inValue the value loaded* @return the modified value loaded*/- T modAfterLoad(int sizeout, int sizeinAddress, T inAddress, int sizeinValue, T inValue);+ default T modAfterLoad(PcodeOp op, AddressSpace space, T inOffset, T inValue) {+ return modAfterLoad(op.getInput(1).getSize(), space, inOffset, op.getOutput().getSize(),+ inValue);+ }/*** Convert the given constant concrete value to type {@code T} having the same size.@@ -274,6 +313,39 @@ public interface PcodeArithmetic<T> {*/T fromConst(byte[] value);+ /**+ * Convert a {@code byte} to {@code T}, with unsigned extension+ *+ * @param value the constant value+ * @param size the size in bytes+ * @return the value+ */+ default T fromConst(byte value, int size) {+ return fromConst(Byte.toUnsignedLong(value), size);+ }++ /**+ * Convert a {@code short} to {@code T}, with unsigned extension+ *+ * @param value the constant value+ * @param size the size in bytes+ * @return the value+ */+ default T fromConst(short value, int size) {+ return fromConst(Short.toUnsignedLong(value), size);+ }++ /**+ * Convert an {@code int} to {@code T}, with unsigned extension+ *+ * @param value the constant value+ * @param size the size in bytes+ * @return the value+ */+ default T fromConst(int value, int size) {+ return fromConst(Integer.toUnsignedLong(value), size);+ }+/*** Convert the given constant concrete value to type {@code T} having the given size.*@@ -290,6 +362,50 @@ public interface PcodeArithmetic<T> {return fromConst(Utils.longToBytes(value, size, getEndian().isBigEndian()));}+ /**+ * Convert a {@code float} to {@code T}+ *+ * <p>+ * If size is not {@value Float#BYTES}, bytes are truncated or passed with 0s, according to+ * machine endianness.+ *+ * @param value the constant value+ * @param size the size in bytes+ * @return the value+ */+ default T fromConst(float value, int size) {+ return fromConst(Float.floatToRawIntBits(value), size);+ }++ /**+ * Convert a {@code double} to {@code T}+ *+ * <p>+ * If size is not {@value Double#BYTES}, bytes are truncated or passed with 0s, according to+ * machine endianness.+ *+ * @param value the constant value+ * @param size the size in bytes+ * @return the value+ */+ default T fromConst(double value, int size) {+ return fromConst(Double.doubleToRawLongBits(value), size);+ }++ /**+ * Convert a {@code boolean} to {@code T}+ *+ * <p>+ * {@code true} is represented as 1, and {@code false} as 0, padded to the given size.+ *+ * @param value the constant value+ * @param size the size in bytes+ * @return the value+ */+ default T fromConst(boolean value, int size) {+ return fromConst(value ? 1L : 0L, size);+ }+/*** Convert the given constant concrete value to type {@code T} having the given size.*@@ -310,6 +426,17 @@ public interface PcodeArithmetic<T> {Utils.bigIntegerToBytes(value, size, isContextreg || getEndian().isBigEndian()));}+ /**+ * Convert the given constant concrete register value to type {@code T}+ *+ * @param value the register value+ * @return the value as a {@code T}+ */+ default T fromConst(RegisterValue value) {+ return fromConst(value.getUnsignedValue(), value.getRegister().getNumBytes(),+ value.getRegister().isProcessorContext());+ }+/*** Convert the given constant concrete value to type {@code T} having the given size.*@@ -317,6 +444,9 @@ public interface PcodeArithmetic<T> {* The value is assumed <em>not</em> to be for the disassembly context register.** @see #fromConst(BigInteger, int, boolean)+ * @param value the constant value+ * @param size the size (in bytes) of the variable into which the value is to be stored+ * @return the value as a {@code T}*/default T fromConst(BigInteger value, int size) {return fromConst(value, size, false);@@ -349,6 +479,22 @@ public interface PcodeArithmetic<T> {return false;}+ /**+ * Convert, if possible, the given abstract value to a concrete register value+ *+ * @param register the register+ * @param value the abstract value+ * @param purpose the reason why the emulator needs a concrete value+ * @return the concrete value+ * @throws ConcretionError if the value cannot be made concrete+ */+ default RegisterValue toRegisterValue(Register register, T value, Purpose purpose) {+ if (register.isProcessorContext()) {+ purpose = Purpose.CONTEXT;+ }+ return new RegisterValue(register, toBigInteger(value, purpose));+ }+/*** Convert, if possible, the given abstract value to a concrete big integer*@@ -383,6 +529,58 @@ public interface PcodeArithmetic<T> {purpose == Purpose.CONTEXT || getEndian().isBigEndian());}+ /**+ * Convert, if possible, the given abstract value to a concrete float+ *+ * <p>+ * If value does not have size {@value Float#BYTES}, it is truncated or padded, according to+ * machine endianness, before the raw bits are converted to a float.+ *+ * @param value the abstract value+ * @param purpose the reason why the emulator needs a concrete value+ * @return the concrete value+ * @throws ConcretionError if the value cannot be made concrete+ */+ default float toFloat(T value, Purpose purpose) {+ return Float.intBitsToFloat((int) toLong(value, purpose));+ }++ /**+ * Convert, if possible, the given abstract value to a concrete double+ *+ * <p>+ * If value does not have size {@value Double#BYTES}, it is truncated or padded, according to+ * machine endianness, before the raw bits are converted to a double.+ *+ * @param value the abstract value+ * @param purpose the reason why the emulator needs a concrete value+ * @return the concrete value+ * @throws ConcretionError if the value cannot be made concrete+ */+ default double toDouble(T value, Purpose purpose) {+ return Double.longBitsToDouble(toLong(value, purpose));+ }++ /**+ * Convert, if possible, the given abstract value to a concrete boolean+ *+ * <p>+ * Any non-zero value is considered true+ *+ * @param value the abstract value+ * @param purpose the reason why the emulator needs a concrete value+ * @return the concrete value+ * @throws ConcretionError if the value cannot be made concrete+ */+ default boolean toBoolean(T value, Purpose purpose) {+ for (byte b : toConcrete(value, purpose)) {+ if (b != 0) {+ return true;+ }+ }+ return false;+ }+/*** Get the size in bytes, if possible, of the given abstract value*diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutor.javaindex a5ce01bc07..4ca4de3e36 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutor.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutor.java@@ -4,9 +4,9 @@* 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.@@ -203,7 +203,7 @@ public class PcodeExecutor<T> {}/**- * Step on p-code op+ * Step one p-code op** @param op the op* @param frame the current frame@@ -211,49 +211,24 @@ public class PcodeExecutor<T> {*/public void stepOp(PcodeOp op, PcodeFrame frame, PcodeUseropLibrary<T> library) {OpBehavior b = OpBehaviorFactory.getOpBehavior(op.getOpcode());- if (b == null) {- badOp(op);- return;- }- if (b instanceof UnaryOpBehavior unOp) {- executeUnaryOp(op, unOp);- return;- }- if (b instanceof BinaryOpBehavior binOp) {- executeBinaryOp(op, binOp);- return;- }- switch (op.getOpcode()) {- case PcodeOp.LOAD:- executeLoad(op);- return;- case PcodeOp.STORE:- executeStore(op);- return;- case PcodeOp.BRANCH:- executeBranch(op, frame);- return;- case PcodeOp.CBRANCH:- executeConditionalBranch(op, frame);- return;- case PcodeOp.BRANCHIND:- executeIndirectBranch(op, frame);- return;- case PcodeOp.CALL:- executeCall(op, frame, library);- return;- case PcodeOp.CALLIND:- executeIndirectCall(op, frame);- return;- case PcodeOp.CALLOTHER:- executeCallother(op, frame, library);- return;- case PcodeOp.RETURN:- executeReturn(op, frame);- return;- default:- badOp(op);- return;+ switch (b) {+ case null -> badOp(op);+ case UnaryOpBehavior unOp -> executeUnaryOp(op, unOp);+ case BinaryOpBehavior binOp -> executeBinaryOp(op, binOp);+ default -> {+ switch (op.getOpcode()) {+ case PcodeOp.LOAD -> executeLoad(op);+ case PcodeOp.STORE -> executeStore(op);+ case PcodeOp.BRANCH -> executeBranch(op, frame);+ case PcodeOp.CBRANCH -> executeConditionalBranch(op, frame);+ case PcodeOp.BRANCHIND -> executeIndirectBranch(op, frame);+ case PcodeOp.CALL -> executeCall(op, frame, library);+ case PcodeOp.CALLIND -> executeIndirectCall(op, frame);+ case PcodeOp.CALLOTHER -> executeCallother(op, frame, library);+ case PcodeOp.RETURN -> executeReturn(op, frame);+ default -> badOp(op);+ }+ }}}@@ -339,22 +314,41 @@ public class PcodeExecutor<T> {protected void checkLoad(AddressSpace space, T offset, int size) {}+ /**+ * Get the address space for a {@link PcodeOp#LOAD load} or {@link PcodeOp#STORE store} op+ *+ * @param op the op+ * @return the address space (derived from const input 0)+ */+ protected AddressSpace getLoadStoreSpace(PcodeOp op) {+ int spaceID = getIntConst(op.getInput(0));+ return language.getAddressFactory().getAddressSpace(spaceID);+ }++ /**+ * Get the offset varnode for a {@link PcodeOp#LOAD load} or {@link PcodeOp#STORE store} op+ *+ * @param op the op+ * @return the offset varnode (input 1)+ */+ protected Varnode getLoadStoreOffset(PcodeOp op) {+ return op.getInput(1);+ }+/*** Execute a load** @param op the op*/public void executeLoad(PcodeOp op) {- int spaceID = getIntConst(op.getInput(0));- AddressSpace space = language.getAddressFactory().getAddressSpace(spaceID);- Varnode inOffset = op.getInput(1);+ AddressSpace space = getLoadStoreSpace(op);+ Varnode inOffset = getLoadStoreOffset(op);T offset = state.getVar(inOffset, reason);Varnode outVar = op.getOutput();checkLoad(space, offset, outVar.getSize());T out = state.getVar(space, offset, outVar.getSize(), true, reason);- T mod = arithmetic.modAfterLoad(outVar.getSize(), inOffset.getSize(), offset,- outVar.getSize(), out);+ T mod = arithmetic.modAfterLoad(op, space, offset, out);state.setVar(outVar, mod);}@@ -368,22 +362,30 @@ public class PcodeExecutor<T> {protected void checkStore(AddressSpace space, T offset, int size) {}+ /**+ * Get the value varnode for a {@link PcodeOp#STORE store} op+ *+ * @param op the op+ * @return the value varnode (input 2)+ */+ protected Varnode getStoreValue(PcodeOp op) {+ return op.getInput(2);+ }+/*** Execute a store** @param op the op*/public void executeStore(PcodeOp op) {- int spaceID = getIntConst(op.getInput(0));- AddressSpace space = language.getAddressFactory().getAddressSpace(spaceID);- Varnode inOffset = op.getInput(1);+ AddressSpace space = getLoadStoreSpace(op);+ Varnode inOffset = getLoadStoreOffset(op);T offset = state.getVar(inOffset, reason);- Varnode valVar = op.getInput(2);+ Varnode valVar = getStoreValue(op);checkStore(space, offset, valVar.getSize());T val = state.getVar(valVar, reason);- T mod = arithmetic.modBeforeStore(valVar.getSize(), inOffset.getSize(), offset,- valVar.getSize(), val);+ T mod = arithmetic.modBeforeStore(op, space, offset, val);state.setVar(space, offset, valVar.getSize(), true, mod);}@@ -395,7 +397,23 @@ public class PcodeExecutor<T> {** @param target the target address*/- protected void branchToAddress(Address target) {+ protected void branchToAddress(PcodeOp op, Address target) {+ }++ /**+ * Convert the given offset to the machine's type and delegate to+ * {@link #branchToOffset(PcodeOp, Object, PcodeFrame)}.+ *+ * <p>+ * Overriding this allows extension to avert attempted uses of the arithmetic, when it may not+ * be applicable.+ *+ * @param op the op+ * @param offset the offset (the new value of the program counter)+ * @param frame the frame to finish+ */+ protected void branchToOffset(PcodeOp op, long offset, PcodeFrame frame) {+ branchToOffset(op, arithmetic.fromConst(offset, pcSize), frame);}/**@@ -407,16 +425,38 @@ public class PcodeExecutor<T> {* counter. The emulator could just read the program counter from the state after <em>every</em>* completed frame, but receiving it "out of band" is faster.*+ * @param op the op* @param offset the offset (the new value of the program counter)* @param frame the frame to finish*/- protected void branchToOffset(T offset, PcodeFrame frame) {+ protected void branchToOffset(PcodeOp op, T offset, PcodeFrame frame) {T truncOff = arithmetic.unaryOp(PcodeOp.COPY, pc.getMinimumByteSize(),(int) arithmetic.sizeOf(offset), offset);state.setVar(pc, truncOff);frame.finishAsBranch();}+ /**+ * Branch internally+ *+ * @param frame the frame+ * @param relative the relative offset to branch+ */+ protected void branchInternal(PcodeOp op, PcodeFrame frame, int relative) {+ frame.branch(relative);+ }++ /**+ * Get the target address of a {@link PcodeOp#BRANCH branch}, {@link PcodeOp#CBRANCH conditional+ * branch}, or {@link PcodeOp#CALL call} op+ *+ * @param op the op+ * @return the target address (input 0's address)+ */+ protected Address getBranchTarget(PcodeOp op) {+ return op.getInput(0).getAddress();+ }+/*** Perform the actual logic of a branch p-code op*@@ -428,13 +468,13 @@ public class PcodeExecutor<T> {* @param frame the frame*/protected void doExecuteBranch(PcodeOp op, PcodeFrame frame) {- Address target = op.getInput(0).getAddress();+ Address target = getBranchTarget(op);if (target.isConstantAddress()) {- frame.branch((int) target.getOffset());+ branchInternal(op, frame, (int) target.getOffset());}else {- branchToOffset(arithmetic.fromConst(target.getOffset(), pcSize), frame);- branchToAddress(target);+ branchToOffset(op, target.getOffset(), frame);+ branchToAddress(op, target);}}@@ -444,8 +484,9 @@ public class PcodeExecutor<T> {* <p>* This merely defers to {@link #doExecuteBranch(PcodeOp, PcodeFrame)}. To instrument the* operation, override this. To modify or instrument branching in general, override- * {@link #doExecuteBranch(PcodeOp, PcodeFrame)}, {@link #branchToOffset(Object, PcodeFrame)},- * and/or {@link #branchToAddress(Address)}.+ * {@link #doExecuteBranch(PcodeOp, PcodeFrame)},+ * {@link #branchToOffset(PcodeOp, Object, PcodeFrame)}, and/or+ * {@link #branchToAddress(PcodeOp, Address)}.** @param op the op* @param frame the frame@@ -454,6 +495,16 @@ public class PcodeExecutor<T> {doExecuteBranch(op, frame);}+ /**+ * Get the predicate varnode of a {@link PcodeOp#CBRANCH conditional branch} op+ *+ * @param op the op+ * @return the predicate varnode (input 1)+ */+ protected Varnode getConditionalBranchPredicate(PcodeOp op) {+ return op.getInput(1);+ }+/*** Execute a conditional branch*@@ -461,13 +512,24 @@ public class PcodeExecutor<T> {* @param frame the frame*/public void executeConditionalBranch(PcodeOp op, PcodeFrame frame) {- Varnode condVar = op.getInput(1);+ Varnode condVar = getConditionalBranchPredicate(op);T cond = state.getVar(condVar, reason);if (arithmetic.isTrue(cond, Purpose.CONDITION)) {doExecuteBranch(op, frame);}}+ /**+ * Get the target of an {@link PcodeOp#BRANCHIND indirect branch}, {@link PcodeOp#CALLIND+ * indirect call}, or {@link PcodeOp#RETURN return} op.+ *+ * @param op the op+ * @return the target varnode (input 0)+ */+ protected Varnode getIndirectBranchTarget(PcodeOp op) {+ return op.getInput(0);+ }+/*** Perform the actual logic of an indirect branch p-code op*@@ -481,12 +543,12 @@ public class PcodeExecutor<T> {* @param frame the frame*/protected void doExecuteIndirectBranch(PcodeOp op, PcodeFrame frame) {- T offset = state.getVar(op.getInput(0), reason);- branchToOffset(offset, frame);+ T offset = state.getVar(getIndirectBranchTarget(op), reason);+ branchToOffset(op, offset, frame);long concrete = arithmetic.toLong(offset, Purpose.BRANCH);Address target = op.getSeqnum().getTarget().getNewAddress(concrete, true);- branchToAddress(target);+ branchToAddress(op, target);}/**@@ -509,11 +571,12 @@ public class PcodeExecutor<T> {** @param op the op* @param frame the frame+ * @param library the userop library*/public void executeCall(PcodeOp op, PcodeFrame frame, PcodeUseropLibrary<T> library) {- Address target = op.getInput(0).getAddress();- branchToOffset(arithmetic.fromConst(target.getOffset(), pcSize), frame);- branchToAddress(target);+ Address target = getBranchTarget(op);+ branchToOffset(op, target.getOffset(), frame);+ branchToAddress(op, target);}/**@@ -540,6 +603,16 @@ public class PcodeExecutor<T> {return frame.getUseropName(opNo);}+ /**+ * Get the userop number of a {@link PcodeOp#CALLOTHER callother} op+ *+ * @param op the op+ * @return the userop number (const input 0)+ */+ protected int getCallotherOpNumber(PcodeOp op) {+ return getIntConst(op.getInput(0));+ }+/*** Execute a userop call*@@ -548,15 +621,14 @@ public class PcodeExecutor<T> {* @param library the library of userops*/public void executeCallother(PcodeOp op, PcodeFrame frame, PcodeUseropLibrary<T> library) {- int opNo = getIntConst(op.getInput(0));+ int opNo = getCallotherOpNumber(op);String opName = getUseropName(opNo, frame);if (opName == null) {throw new AssertionError("Pcode userop " + opNo + " is not defined");}PcodeUseropDefinition<T> opDef = library.getUserops().get(opName);if (opDef != null) {- opDef.execute(this, library, op.getOutput(),- List.of(op.getInputs()).subList(1, op.getNumInputs()));+ opDef.execute(this, library, op);return;}onMissingUseropDef(op, frame, opName, library);diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeFrame.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeFrame.javaindex be91c89aff..ac486a9cb9 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeFrame.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeFrame.java@@ -331,7 +331,7 @@ public class PcodeFrame {* instruction) completed with fall-through, then this will return -1. If it completed on a* branch, then this will return the index of that branch.*- * @return+ * @return the last index executed*/public int getBranched() {return branched;diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeProgram.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeProgram.javaindex a3039136aa..b6adc5f17b 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeProgram.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeProgram.java@@ -4,9 +4,9 @@* 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.@@ -38,12 +38,17 @@ import ghidra.util.exception.NotFoundException;*/public class PcodeProgram {protected static class MyAppender extends AbstractAppender<String> {+ protected int opIdx = 0;protected final PcodeProgram program;+ protected final boolean numberOps;+protected final StringBuffer buf = new StringBuffer();- public MyAppender(PcodeProgram program, Language language) {+ public MyAppender(PcodeProgram program, Language language, boolean numberOps) {super(language, true);this.program = program;+ this.numberOps = numberOps;+buf.append("<" + program.getHead() + ":\n");}@@ -70,18 +75,34 @@ public class PcodeProgram {buf.append(">");return buf.toString();}++ @Override+ public void appendIndent() {+ super.appendIndent();+ if (numberOps) {+ PcodeOp op = program.getCode().get(opIdx);+ buf.append(opIdx++);+ buf.append(",");+ buf.append(op.getSeqnum().getTarget());+ buf.append(".");+ buf.append(op.getSeqnum().getTime());+ buf.append(": ");+ }+ }}protected static class MyFormatter extends AbstractPcodeFormatter<String, MyAppender> {protected final PcodeProgram program;+ protected final boolean numberOps;- public MyFormatter(PcodeProgram program) {+ public MyFormatter(PcodeProgram program, boolean numberOps) {this.program = program;+ this.numberOps = numberOps;}@Overrideprotected MyAppender createAppender(Language language, boolean indent) {- return new MyAppender(program, language);+ return new MyAppender(program, language, numberOps);}@Override@@ -111,12 +132,11 @@ public class PcodeProgram {*/public static PcodeProgram fromInstruction(Instruction instruction, boolean includeOverrides) {Language language = instruction.getPrototype().getLanguage();- if (!(language instanceof SleighLanguage)) {+ if (!(language instanceof SleighLanguage slang)) {throw new IllegalArgumentException("Instruction must be parsed using Sleigh");}PcodeOp[] pcode = instruction.getPcode(includeOverrides);- return new PcodeProgram((SleighLanguage) language, List.of(pcode),- Map.of());+ return new PcodeProgram(slang, List.of(pcode), Map.of());}/**@@ -143,7 +163,7 @@ public class PcodeProgram {protected final SleighLanguage language;protected final List<PcodeOp> code;- protected final Map<Integer, String> useropNames = new HashMap<>();+ protected final Map<Integer, String> useropNames;/*** Construct a p-code program with the given bindings@@ -156,6 +176,7 @@ public class PcodeProgram {Map<Integer, UserOpSymbol> useropSymbols) {this.language = language;this.code = code;+ this.useropNames = new HashMap<>();int langOpCount = language.getNumberOfUserDefinedOpNames();for (Map.Entry<Integer, UserOpSymbol> ent : useropSymbols.entrySet()) {int index = ent.getKey();@@ -168,6 +189,19 @@ public class PcodeProgram {}}+ /**+ * Construct a p-code program from a derivative of the given one+ *+ * @param program the original program+ * @param code the code portion for this program+ */+ public PcodeProgram(PcodeProgram program, List<PcodeOp> code) {+ assert !code.isEmpty();+ this.language = program.language;+ this.code = code;+ this.useropNames = program.useropNames;+ }+/*** Get the language generating this program*@@ -203,6 +237,14 @@ public class PcodeProgram {@Overridepublic String toString() {- return new MyFormatter(this).formatOps(language, code);+ return format();+ }++ public String format(boolean numberOps) {+ return new MyFormatter(this, numberOps).formatOps(language, code);+ }++ public String format() {+ return format(false);}}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeUseropLibrary.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeUseropLibrary.javaindex 91daf85621..1563226019 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeUseropLibrary.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeUseropLibrary.java@@ -15,14 +15,15 @@*/package ghidra.pcode.exec;-import java.lang.reflect.Type;-import java.lang.reflect.TypeVariable;+import java.lang.reflect.*;import java.util.*;import org.apache.commons.lang3.reflect.TypeUtils;import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.PcodeUserop;import ghidra.pcodeCPort.slghsymbol.UserOpSymbol;+import ghidra.program.model.pcode.PcodeOp;import ghidra.program.model.pcode.Varnode;import ghidra.sleigh.grammar.Location;@@ -112,7 +113,7 @@ public interface PcodeUseropLibrary<T> {String getName();/**- * Get the number of <em>input</em> operands acccepted by the userop.+ * Get the number of <em>input</em> operands accepted by the userop.** @return the count or -1 if the userop is variadic*/@@ -131,6 +132,104 @@ public interface PcodeUseropLibrary<T> {*/void execute(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library, Varnode outVar,List<Varnode> inVars);++ /**+ * Invoke/execute the raw userop.+ *+ * <p>+ * <b>NOTE:</b> The first input to the raw p-code op is the id of this userop. The userop+ * inputs are thus at indices 1..N.+ *+ * @param executor the executor invoking this userop.+ * @param library the complete library for this execution. Note the library may have been+ * composed from more than the one defining this userop.+ * @param op the {@link PcodeOp#CALLOTHER} op+ */+ default void execute(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library, PcodeOp op) {+ execute(executor, library, op.getOutput(),+ Arrays.asList(op.getInputs()).subList(1, op.getNumInputs()));+ }++ /**+ * Indicates whether this userop is a "pure function."+ *+ * <p>+ * This means all inputs are given in the arguments to the userop and the output, if+ * applicable, is given via the return. Technically, this is only with respect to the+ * emulated machine state. If the library carries its own state, and the userop is stateful+ * with respect to the library, it is still okay to set this to true. When this is set to+ * false, the underlying execution engine must ensure the machine state is consistent,+ * because the userop may access any part of it directly. Functional userops ought to take+ * primitive parameters and return primitives, and should receive neither the executor nor+ * its state object.+ *+ * <p>+ * <b>WARNING:</b> The term "inputs" include disassembly context. Unfortunately, there is+ * currently no way to access that context via p-code ops generated by Sleigh, so the only+ * way to obtain it is to ask the emulator thread for it out of band. Userops that require+ * this are <em>not</em> "pure functions."+ *+ * @return true if a pure function.+ * @see PcodeUserop#functional()+ */+ boolean isFunctional();++ /**+ * Indicates whether this userop may have side effects.+ *+ * <p>+ * This means that the function may have an output or an effect other than returning a+ * value. Even if {@link #isFunctional()} is true, it is possible for a userop to have side+ * effects, e.g., updating a field in a library or printing to the screen.+ *+ * @return true if it has side effects.+ * @see PcodeUserop#hasSideEffects()+ */+ boolean hasSideEffects();++ /**+ * Indicates whether or not this userop definition produces p-code suitable for inlining in+ * place of its invocation.+ *+ * <p>+ * Generally, if all the userop definition does is feed additional p-code to the executor+ * with the same userop library, then it is suitable for inlining. It is possible for the+ * p-code to depend on other factors, but care must be taken, since the decision could be+ * fixed by the underlying execution system at any time. E.g., if the p-code is translated+ * to JVM byte code, then the userop may be inlined at translation time rather than+ * execution time. Recommended factors include configuration, placement within surrounding+ * instructions, static analysis, etc., but the p-code should probably not depend on the+ * machine's dynamic run-time state.+ *+ * @return true if inlining is possible, false otherwise.+ * @see PcodeUserop#canInline()+ */+ boolean canInlinePcode();++ /**+ * If this userop is defined as a java callback, get the method+ *+ * @return the method, or null+ */+ Method getJavaMethod();++ /**+ * Get the library that defines (or "owns") this userop+ *+ * <p>+ * A userop can become part of other composed libraries, so the library from which this+ * userop was retrieved may not be the same as the one that defined it. This returns the one+ * that defined it.+ *+ * <p>+ * As a special consideration, if this userop is a wrapper around another, and this wrapper+ * returns the java method of the delegate, this <em>must</em> return the defining library+ * of the delegate. If this is not defined by a java callback, this method (the defining+ * library) may be null.+ *+ * @return the defining library+ */+ PcodeUseropLibrary<?> getDefiningLibrary();}/**diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighPcodeUseropDefinition.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighPcodeUseropDefinition.javaindex 6236bb22a3..c749f65b0d 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighPcodeUseropDefinition.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighPcodeUseropDefinition.java@@ -4,9 +4,9 @@* 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.@@ -15,6 +15,7 @@*/package ghidra.pcode.exec;+import java.lang.reflect.Method;import java.util.*;import ghidra.app.plugin.processors.sleigh.SleighLanguage;@@ -86,6 +87,8 @@ public class SleighPcodeUseropDefinition<T> implements PcodeUseropDefinition<T>/*** @see #params(Collection)+ * @param additionalParams the additional parameter names+ * @return this builder*/public Builder params(String... additionalParams) {return this.params(Arrays.asList(additionalParams));@@ -95,6 +98,7 @@ public class SleighPcodeUseropDefinition<T> implements PcodeUseropDefinition<T>* Add Sleigh source to the body** @param additionalBody the additional source+ * @return this builder*/public Builder body(CharSequence additionalBody) {body.append(additionalBody);@@ -188,4 +192,29 @@ public class SleighPcodeUseropDefinition<T> implements PcodeUseropDefinition<T>public String getBody() {return body;}++ @Override+ public boolean isFunctional() {+ return false;+ }++ @Override+ public boolean hasSideEffects() {+ return true;+ }++ @Override+ public boolean canInlinePcode() {+ return true;+ }++ @Override+ public Method getJavaMethod() {+ return null;+ }++ @Override+ public PcodeUseropLibrary<T> getDefiningLibrary() {+ return null;+ }}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighProgramCompiler.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighProgramCompiler.javaindex cca42b564f..29e3348896 100644--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighProgramCompiler.java+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SleighProgramCompiler.java@@ -4,9 +4,9 @@* 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.@@ -164,7 +164,8 @@ public enum SleighProgramCompiler {*/public static List<PcodeOp> buildOps(Language language, ConstructTpl template)throws UnknownInstructionException, MemoryAccessException, IOException {- Address zero = language.getDefaultSpace().getAddress(0);+ //Address zero = language.getDefaultSpace().getAddress(0);+ Address zero = Address.NO_ADDRESS;SleighParserContext c = new SleighParserContext(zero, zero, zero, zero);ParserWalker walk = new ParserWalker(c);PcodeEmitObjects emit = new PcodeEmitObjects(walk);diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/AbstractPcodeEmulatorTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/AbstractPcodeEmulatorTest.javanew file mode 100644index 0000000000..5d9f8b10a4--- /dev/null+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/AbstractPcodeEmulatorTest.java@@ -0,0 +1,301 @@+/* ###+ * 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.pcode.emu.jit;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.fail;++import java.io.File;+import java.io.IOException;++import org.junit.Before;+import org.junit.Test;++import generic.test.AbstractGTest;+import ghidra.GhidraTestApplicationLayout;+import ghidra.app.plugin.assembler.Assemblers;+import ghidra.app.plugin.assembler.AssemblyBuffer;+import ghidra.framework.Application;+import ghidra.framework.ApplicationConfiguration;+import ghidra.pcode.emu.PcodeEmulator;+import ghidra.pcode.emu.PcodeThread;+import ghidra.pcode.exec.*;+import ghidra.pcode.exec.PcodeArithmetic.Purpose;+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.*;+import ghidra.program.util.DefaultLanguageService;+import ghidra.util.SystemUtilities;++public abstract class AbstractPcodeEmulatorTest extends AbstractGTest {++ protected abstract PcodeEmulator createEmulator(Language language);++ public static final LanguageID LANGID_TOY_BE = new LanguageID("Toy:BE:64:default");+ public static final LanguageID LANGID_TOY_LE = new LanguageID("Toy:BE:64:default");+ public static final LanguageID LANGID_X64 = new LanguageID("x86:LE:64:default");++ public static final int FIB_ITER_N = 100000;+ public static final long FIB_ITER_VAL = 2754320626097736315L;++ public static final int FIB_REC_N = 25;+ public static final long FIB_REC_VAL = 75025;++ public static int getFibIterN() {+ if (SystemUtilities.isInTestingBatchMode()) {+ return 10;+ }+ return FIB_ITER_N;+ }++ public static long getFibIterVal() {+ if (SystemUtilities.isInTestingBatchMode()) {+ return 55;+ }+ return FIB_ITER_VAL;+ }++ public static int getFibRecN() {+ if (SystemUtilities.isInTestingBatchMode()) {+ return 10;+ }+ return FIB_REC_N;+ }++ public static long getFibRecVal() {+ if (SystemUtilities.isInTestingBatchMode()) {+ return 55;+ }+ return FIB_REC_VAL;+ }++ public static Language getLanguage(LanguageID id) throws LanguageNotFoundException {+ return DefaultLanguageService.getLanguageService().getLanguage(id);+ }++ @Before+ public void setUp() throws IOException {+ if (!Application.isInitialized()) {+ Application.initializeApplication(+ new GhidraTestApplicationLayout(new File(getTestDirectoryPath())),+ new ApplicationConfiguration());+ }+ }++ @Test+ public void testRunFibonacciIterativeToy() throws Exception {+ PcodeEmulator emu = createEmulator(getLanguage(LANGID_TOY_BE));+ PcodeArithmetic<byte[]> arithmetic = emu.getArithmetic();+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r1, #1");+ Address loop = asm.getNext();+ asm.assemble("mov r2, r0");+ asm.assemble("add r2, r1");+ asm.assemble("mov r0, r1");+ asm.assemble("mov r1, r2");+ asm.assemble("sub r3, #1");+ asm.assemble("brne 0x%s".formatted(loop));++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ PcodeThread<byte[]> thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());++ Register r0 = emu.getLanguage().getRegister("r0");+ Register r3 = emu.getLanguage().getRegister("r3");++ thread.getState().setVar(r3, arithmetic.fromConst(getFibIterN(), 8));++ long start = System.currentTimeMillis();+ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ }+ long time = System.currentTimeMillis() - start;++ System.out.println("Took %f seconds".formatted(time / 1000.0));++ assertEquals(getFibIterVal(),+ arithmetic.toLong(thread.getState().getVar(r0, Reason.INSPECT), Purpose.INSPECT));+ }++ @Test+ public void testRunFibonacciIterativeX64() throws Exception {+ PcodeEmulator emu = createEmulator(getLanguage(LANGID_X64));+ PcodeArithmetic<byte[]> arithmetic = emu.getArithmetic();+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("MOV RBX, 1");+ Address loop = asm.getNext();+ asm.assemble("LEA RDX, [RAX+RBX*1]");+ asm.assemble("MOV RAX, RBX");+ asm.assemble("MOV RBX, RDX");+ asm.assemble("DEC RCX");+ asm.assemble("JNZ 0x%s".formatted(loop));++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ PcodeThread<byte[]> thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());+ thread.overrideContextWithDefault();++ Register rax = emu.getLanguage().getRegister("RAX");+ Register rcx = emu.getLanguage().getRegister("RCX");++ thread.getState().setVar(rcx, arithmetic.fromConst(getFibIterN(), 8));++ long start = System.currentTimeMillis();+ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ }+ long time = System.currentTimeMillis() - start;++ System.out.println("Took %f seconds".formatted(time / 1000.0));++ assertEquals(getFibIterVal(),+ arithmetic.toLong(thread.getState().getVar(rax, Reason.INSPECT), Purpose.INSPECT));+ }++ @Test+ public void testRunFibonacciRecursiveX64() throws Exception {+ PcodeEmulator emu = createEmulator(getLanguage(LANGID_X64));+ PcodeArithmetic<byte[]> arithmetic = emu.getArithmetic();+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("CMP RCX, 1"); // n in RCX+ Address patchJbe = asm.getNext();+ asm.assemble("JBE 0x%s".formatted(asm.getNext())); // placeholder+ asm.assemble("PUSH R8"); // Temp to save n+ asm.assemble("PUSH R9"); // Temp to save fib(n-1)+ asm.assemble("MOV R8, RCX");+ asm.assemble("DEC RCX");+ asm.assemble("CALL 0x%s".formatted(asm.getEntry()));+ asm.assemble("MOV R9, RAX");+ asm.assemble("LEA RCX, [R8 + -2]");+ asm.assemble("CALL 0x%s".formatted(asm.getEntry()));+ asm.assemble("ADD RAX, R9");+ asm.assemble("POP R9");+ asm.assemble("POP R8");+ asm.assemble("RET");+ Address jbeTarget = asm.getNext();+ asm.assemble("MOV RAX, RCX");+ asm.assemble("RET");++ asm.assemble(patchJbe, "JBE 0x%s".formatted(jbeTarget));++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ PcodeThread<byte[]> thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());+ thread.overrideContextWithDefault();++ Register rax = emu.getLanguage().getRegister("RAX");+ Register rcx = emu.getLanguage().getRegister("RCX");++ thread.getState().setVar(rcx, arithmetic.fromConst(getFibRecN(), 8));++ long start = System.currentTimeMillis();+ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ }+ long time = System.currentTimeMillis() - start;++ System.out.println("Took %f seconds".formatted(time / 1000.0));++ assertEquals(getFibRecVal(),+ arithmetic.toLong(thread.getState().getVar(rax, Reason.INSPECT), Purpose.INSPECT));+ }++ @Test+ public void testSwi() throws Exception {+ PcodeEmulator emu = createEmulator(getLanguage(LANGID_TOY_BE));+ PcodeArithmetic<byte[]> arithmetic = emu.getArithmetic();+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r1, #1");+ Address brk = asm.getNext();+ asm.assemble("add r1, #1");++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ PcodeThread<byte[]> thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());++ emu.addBreakpoint(brk, "1:1");++ try {+ thread.run();+ fail("Should have failed on breakpoint");+ }+ catch (InterruptPcodeExecutionException e) {+ }++ Register r1 = emu.getLanguage().getRegister("r1");+ assertEquals(1,+ arithmetic.toLong(thread.getState().getVar(r1, Reason.INSPECT), Purpose.INSPECT));+ assertEquals(brk, thread.getCounter());+ }++ @Test+ public void testInjectionError() throws Exception {+ PcodeEmulator emu = createEmulator(getLanguage(LANGID_TOY_BE));+ PcodeArithmetic<byte[]> arithmetic = emu.getArithmetic();+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r1, #1");+ Address inject = asm.getNext();+ asm.assemble("add r1, #1");++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ PcodeThread<byte[]> thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());++ emu.inject(inject, "emu_injection_err();");++ try {+ thread.run();+ fail("Should have failed on injection error");+ }+ catch (InjectionErrorPcodeExecutionException e) {+ }++ Register r1 = emu.getLanguage().getRegister("r1");+ assertEquals(1,+ arithmetic.toLong(thread.getState().getVar(r1, Reason.INSPECT), Purpose.INSPECT));+ assertEquals(inject, thread.getCounter());+ }+}diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/JitJvmTypeUtilsTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/JitJvmTypeUtilsTest.javanew file mode 100644index 0000000000..3f1826f066--- /dev/null+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/JitJvmTypeUtilsTest.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.pcode.emu.jit;++import static org.junit.Assert.assertEquals;++import java.io.InputStream;+import java.util.*;++import org.apache.commons.lang3.reflect.TypeLiteral;+import org.junit.Ignore;+import org.junit.Test;+import org.objectweb.asm.*;++import ghidra.pcode.emu.jit.JitPassage.AddrCtx;++@Ignore("Too tightly bound to java version")+public class JitJvmTypeUtilsTest {++ public static class HasFieldTypeSignatures {+ public static final List<AddrCtx> RECS = new ArrayList<>();+ public static final List<?> WILDS = new ArrayList<>();+ public static final List<? super AddrCtx> SUPERS = new ArrayList<>();+ public static final List<? extends AddrCtx> EXTENDS = new ArrayList<>();+ }++ @Test+ public void testTypeToSignature() throws Exception {+ Map<String, String> signatures = new HashMap<>();+ String filename = Type.getInternalName(HasFieldTypeSignatures.class) + ".class";+ try (InputStream is = getClass().getClassLoader().getResourceAsStream(filename)) {+ ClassReader cr = new ClassReader(is);+ //ClassNode cn = new ClassNode(Opcodes.ASM9);+ //ClassVisitor trace = new TraceClassVisitor(cn, new PrintWriter(System.out));+ ClassVisitor trace = null;+ cr.accept(new ClassVisitor(Opcodes.ASM9, trace) {+ @Override+ public FieldVisitor visitField(int access, String name, String descriptor,+ String signature, Object value) {+ signatures.put(name, signature);+ return super.visitField(access, filename, descriptor, signature, value);+ }+ }, 0);+ }++ assertEquals(signatures.get("RECS"), JitJvmTypeUtils+ .typeToSignature(new TypeLiteral<List<AddrCtx>>() {}.value));+ assertEquals(signatures.get("WILDS"), JitJvmTypeUtils+ .typeToSignature(new TypeLiteral<List<?>>() {}.value));+ assertEquals(signatures.get("SUPERS"), JitJvmTypeUtils+ .typeToSignature(new TypeLiteral<List<? super AddrCtx>>() {}.value));+ assertEquals(signatures.get("EXTENDS"), JitJvmTypeUtils+ .typeToSignature(new TypeLiteral<List<? extends AddrCtx>>() {}.value));+ }+}diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/JitPcodeEmulatorTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/JitPcodeEmulatorTest.javanew file mode 100644index 0000000000..26d2f80f1e--- /dev/null+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/JitPcodeEmulatorTest.java@@ -0,0 +1,305 @@+/* ###+ * 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.pcode.emu.jit;++import static org.junit.Assert.*;++import java.lang.invoke.MethodHandles;++import org.junit.Test;++import ghidra.app.plugin.assembler.Assemblers;+import ghidra.app.plugin.assembler.AssemblyBuffer;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;+import ghidra.pcode.exec.*;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.Language;+import ghidra.program.model.lang.LanguageID;++public class JitPcodeEmulatorTest extends AbstractPcodeEmulatorTest {++ public static class TestUseropLibrary extends AnnotatedPcodeUseropLibrary<byte[]> {+ public int value4;+ public long value8;++ @PcodeUserop(functional = true, hasSideEffects = true)+ public void capture4(int value4) {+ this.value4 = value4;+ }++ @PcodeUserop(functional = true, hasSideEffects = true)+ public void capture8(long value8) {+ this.value8 = value8;+ }+ }++ TestUseropLibrary lib = new TestUseropLibrary();++ @Override+ protected JitPcodeEmulator createEmulator(Language language) {+ return new JitPcodeEmulator(language, new JitConfiguration(), MethodHandles.lookup()) {+ @Override+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {+ return super.createUseropLibrary().compose(lib);+ }+ };+ }++ @Test+ public void testDropAtDecodeError() throws Throwable {+ JitPcodeEmulator emu = createEmulator(getLanguage(LANGID_TOY_BE));+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r0,#123");+ asm.assemble("add r0,#7");+ Address after = asm.getNext();++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ EntryPoint entry = thread.getEntry(new AddrCtx(null, asm.getEntry()));+ try {+ entry.passage().run(0);+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ }++ assertEquals(after, thread.getCounter());+ }++ @Test+ public void testDropAtExistingEntry() throws Throwable {+ JitPcodeEmulator emu = createEmulator(getLanguage(LANGID_TOY_BE));+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r0,#123");+ Address i2 = asm.getNext();+ asm.assemble("add r0,#7");++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ EntryPoint second = thread.getEntry(new AddrCtx(null, i2));+ EntryPoint first = thread.getEntry(new AddrCtx(null, asm.getEntry()));++ assertEquals(second, first.run());+ assertEquals(i2, thread.getCounter());+ }++ @Test+ public void testRunInvolvesTranslation() throws Throwable {+ JitPcodeEmulator emu = createEmulator(getLanguage(LANGID_TOY_BE));+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r0,#123");+ asm.assemble("add r0,#7");++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());++ assertFalse(thread.hasEntry(new AddrCtx(null, asm.getEntry())));++ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ }++ assertTrue(thread.hasEntry(new AddrCtx(null, asm.getEntry())));+ }++ public void runTestLowSubValReads(LanguageID langID) throws Exception {+ JitPcodeEmulator emu = createEmulator(getLanguage(langID));+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r0, #0x123"); // Not really used+ Address injectAt = asm.getNext();+ asm.assemble("or r1, r1"); // an instruction to inject o++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());+ thread.overrideContextWithDefault();+ thread.inject(injectAt, """+ r0 = 0x1122334455667788;+ capture4(r0l);+ emu_exec_decoded();+ """);++ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ // expected+ }++ assertEquals(0x55667788, lib.value4);+ }++ @Test+ public void testLowSubValReadsBE() throws Exception {+ runTestLowSubValReads(LANGID_TOY_BE);+ }++ @Test+ public void testLowSubValReadsLE() throws Exception {+ runTestLowSubValReads(LANGID_TOY_LE);+ }++ public void runTestLowSubValWrites(LanguageID langID) throws Exception {+ JitPcodeEmulator emu = createEmulator(getLanguage(langID));+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r0, #0x123"); // Not really used+ Address injectAt = asm.getNext();+ asm.assemble("or r1, r1"); // an instruction to inject o++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());+ thread.overrideContextWithDefault();+ thread.inject(injectAt, """+ r0 = 0x1122334455667788;+ r0l = 0x44332211;+ capture8(r0);+ emu_exec_decoded();+ """);++ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ // expected+ }++ assertEquals(0x1122334444332211L, lib.value8);+ }++ @Test+ public void testLowSubValWritesBE() throws Exception {+ runTestLowSubValWrites(LANGID_TOY_BE);+ }++ @Test+ public void testLowSubValWritesLE() throws Exception {+ runTestLowSubValWrites(LANGID_TOY_LE);+ }++ public void runTestHighSubValReads(LanguageID langID) throws Exception {+ JitPcodeEmulator emu = createEmulator(getLanguage(langID));+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r0, #0x123"); // Not really used+ Address injectAt = asm.getNext();+ asm.assemble("or r1, r1"); // an instruction to inject o++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());+ thread.overrideContextWithDefault();+ thread.inject(injectAt, """+ r0 = 0x1122334455667788;+ capture4(r0h);+ emu_exec_decoded();+ """);++ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ // expected+ }++ assertEquals(0x11223344, lib.value4);+ }++ @Test+ public void testHighSubValReadsBE() throws Exception {+ runTestHighSubValReads(LANGID_TOY_BE);+ }++ @Test+ public void testHighSubValReadsLE() throws Exception {+ runTestHighSubValReads(LANGID_TOY_LE);+ }++ public void runTestHighSubValWrites(LanguageID langID) throws Exception {+ JitPcodeEmulator emu = createEmulator(getLanguage(langID));+ AddressSpace space = emu.getLanguage().getDefaultSpace();+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(emu.getLanguage()),+ space.getAddress(0x00400000));++ asm.assemble("imm r0, #0x123"); // Not really used+ Address injectAt = asm.getNext();+ asm.assemble("or r1, r1"); // an instruction to inject o++ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());+ thread.overrideContextWithDefault();+ thread.inject(injectAt, """+ r0 = 0x1122334455667788;+ r0h = 0x44332211;+ capture8(r0);+ emu_exec_decoded();+ """);++ try {+ thread.run();+ fail("Should have crashed on decode error");+ }+ catch (DecodePcodeExecutionException e) {+ // expected+ }++ assertEquals(0x4433221155667788L, lib.value8);+ }++ @Test+ public void testHighSubValWritesBE() throws Exception {+ runTestHighSubValWrites(LANGID_TOY_BE);+ }++ @Test+ public void testHighSubValWritesLE() throws Exception {+ runTestHighSubValWrites(LANGID_TOY_LE);+ }+}diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/PlainPcodeEmulatorTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/PlainPcodeEmulatorTest.javanew file mode 100644index 0000000000..e1cf19cbf5--- /dev/null+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/PlainPcodeEmulatorTest.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.pcode.emu.jit;++import ghidra.pcode.emu.PcodeEmulator;+import ghidra.program.model.lang.Language;++public class PlainPcodeEmulatorTest extends AbstractPcodeEmulatorTest {+ @Override+ protected PcodeEmulator createEmulator(Language language) {+ return new PcodeEmulator(language);+ }+}diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibraryTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibraryTest.javaindex b14d97043f..7af33d6627 100644--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibraryTest.java+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibraryTest.java@@ -4,9 +4,9 @@* 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.@@ -18,7 +18,8 @@ package ghidra.pcode.exec;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertTrue;-import java.io.*;+import java.io.File;+import java.io.IOException;import java.lang.invoke.MethodHandles;import java.lang.invoke.MethodHandles.Lookup;@@ -121,6 +122,26 @@ public class AnnotatedPcodeUseropLibraryTest extends AbstractGTest {assertBytes(1234, 4, library.input);}+ @Test+ public void testIntInputIntOutput() throws Exception {+ var library = new TestUseropLibrary() {+ int input;++ @PcodeUserop+ private int __testop(int input) {+ this.input = input;+ return 5678;+ }+ };++ PcodeExecutor<byte[]> executor = createBytesExecutor();+ Register r0 = executor.getLanguage().getRegister("r0");++ executeSleigh(executor, library, "r0 = __testop(1234:4);");+ assertEquals(1234, library.input);+ assertBytes(5678, 8, executor.getState().getVar(r0, Reason.INSPECT));+ }+@Testpublic void testVariadicInputT() throws Exception {var library = new TestUseropLibrary() {@@ -331,7 +352,7 @@ public class AnnotatedPcodeUseropLibraryTest extends AbstractGTest {public void testErrReturnType() throws Exception {new TestUseropLibrary() {@PcodeUserop- private int __testop() {+ private char __testop() {return 0;}};@@ -341,7 +362,7 @@ public class AnnotatedPcodeUseropLibraryTest extends AbstractGTest {public void testErrInputType() throws Exception {new TestUseropLibrary() {@PcodeUserop- private void __testop(int in0) {+ private void __testop(char in0) {}};}diff --git a/Ghidra/Framework/Emulation/src/test/resources/mock.pspec b/Ghidra/Framework/Emulation/src/test/resources/mock.pspecindex be3ce4f3a4..17e268bb21 100644--- a/Ghidra/Framework/Emulation/src/test/resources/mock.pspec+++ b/Ghidra/Framework/Emulation/src/test/resources/mock.pspec@@ -1,5 +1,6 @@<?xml version="1.0" encoding="UTF-8"?><processor_spec>+ <programcounter register="pc"/></processor_spec>diff --git a/Ghidra/Framework/Emulation/src/test/resources/mock.slaspec b/Ghidra/Framework/Emulation/src/test/resources/mock.slaspecindex 5596dc9500..a197c9b57c 100644--- a/Ghidra/Framework/Emulation/src/test/resources/mock.slaspec+++ b/Ghidra/Framework/Emulation/src/test/resources/mock.slaspec@@ -14,7 +14,9 @@ define space register type=register_space size=4;# AT LEAST ONE REGISTER, AND STACK POINTER ARE REQUIRED# # # # # # # # # # # # # # # # # # # # # # # # # # # #-define register offset=0x0 size=8 [ sp r0 r1 r2 r3 r4 r5 r6 r7 ];+define register offset=0x0 size=8 [ sp r0 r1 r2 r3 r4 r5 r6 r7 pc ];+define register offset=0xa size=2 [ r0hole ];+define register offset=0x8 size=6 [ r0sz6 ];# Define context bitsdefine register offset=0x100 size=4 contextreg;diff --git a/Ghidra/Framework/Generic/build.gradle b/Ghidra/Framework/Generic/build.gradleindex a465b3b090..17222fa6ca 100644--- a/Ghidra/Framework/Generic/build.gradle+++ b/Ghidra/Framework/Generic/build.gradle@@ -4,9 +4,9 @@* 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.@@ -40,9 +40,10 @@ dependencies {api "org.bouncycastle:bcpkix-jdk15on:1.69" // requires bcutil and bcprovapi "org.bouncycastle:bcprov-jdk15on:1.69"api "org.bouncycastle:bcutil-jdk15on:1.69"-+compileOnly "junit:junit:4.12"-+ compileOnly "org.hamcrest:hamcrest:2.2"+constraints {api("com.google.guava:guava") {attributes {diff --git a/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGTest.java b/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGTest.javaindex f3450065e2..c50652034e 100644--- a/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGTest.java+++ b/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGTest.java@@ -4,9 +4,9 @@* 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.@@ -29,7 +29,9 @@ import java.util.function.Supplier;import org.junit.Assert;import org.junit.Rule;import org.junit.rules.TestName;+import org.junit.rules.TestRule;+import generic.test.rule.*;import ghidra.framework.Application;import ghidra.framework.TestApplicationUtils;import ghidra.util.SystemUtilities;@@ -41,11 +43,12 @@ import utility.application.ApplicationUtilities;/*** A root for system tests that provides known system information.*- * <P>This class exists so that fast unit tests have a place to share data without having the- * slowness of more heavy weight concepts like {@link Application}, logging, etc.+ * <P>+ * This class exists so that fast unit tests have a place to share data without having the slowness+ * of more heavy weight concepts like {@link Application}, logging, etc.*- * <P> !! WARNING !!- * This test is meant to initialize quickly. All file I/O should be avoided.+ * <P>+ * !! WARNING !! This test is meant to initialize quickly. All file I/O should be avoided.*/public abstract class AbstractGTest {@@ -75,8 +78,25 @@ public abstract class AbstractGTest {public TestName testName = new TestName();/**- * Get the directory path within which all temporary test- * data files should be created.+ * This rule handles the {@link Repeated} annotation+ *+ * <p>+ * During batch mode, this rule should never be needed. This rule is included here as a+ * convenience, in case a developer wants to use the {@link Repeated} annotation to diagnose a+ * non-deterministic test failure. Without this rule, the annotation would be silently ignored.+ */+ @Rule+ public TestRule repeatedRule = new RepeatedTestRule();++ /**+ * This rule handles the {@link IgnoreUnfinished} annotation+ */+ @Rule+ public TestRule ignoreUnfinishedRule = new IgnoreUnfinishedRule();++ /**+ * Get the directory path within which all temporary test data files should be created.+ ** @return test directory path ending with a File.separator character*/private static String createTestDirectoryPath() {@@ -161,9 +181,9 @@ public abstract class AbstractGTest {}/**- * Compares the contents of two arrays to determine if they are equal. The contents must- * match in the same order. If <code>message</code>- * is <code>null</code>, then a generic error message will be printed.+ * Compares the contents of two arrays to determine if they are equal. The contents must match+ * in the same order. If <code>message</code> is <code>null</code>, then a generic error message+ * will be printed.** @param message The message to print upon failure; can be null* @param expected The expected array.@@ -180,9 +200,9 @@ public abstract class AbstractGTest {}/**- * Compares the contents of two arrays to determine if they are equal. The contents do not have- * to be in the same order. If <code>message</code>- * is <code>null</code>, then a generic error message will be printed.+ * Compares the contents of two arrays to determine if they are equal. The contents do not have+ * to be in the same order. If <code>message</code> is <code>null</code>, then a generic error+ * message will be printed.** @param message The message to print upon failure; can be null* @param expected The expected array.@@ -394,7 +414,7 @@ public abstract class AbstractGTest {}/**- * Waits for the given AtomicBoolean to return true. This is a convenience method for+ * Waits for the given AtomicBoolean to return true. This is a convenience method for* {@link #waitFor(BooleanSupplier)}.** @param ab the atomic boolean@@ -441,8 +461,8 @@ public abstract class AbstractGTest {* Waits for the given condition to return true** @param condition the condition that returns true when satisfied- * @param failureMessageSupplier the function that will supply the failure message in the- * event of a timeout.+ * @param failureMessageSupplier the function that will supply the failure message in the event+ * of a timeout.* @throws AssertionFailedError if the condition is not met within the timeout period*/public static void waitForCondition(BooleanSupplier condition,@@ -452,11 +472,12 @@ public abstract class AbstractGTest {}/**- * Waits for the given condition to return true. Most of the <code>waitForCondition()</code>- * methods throw an {@link AssertionFailedError} if the timeout period expires.- * This method allows you to setup a longer wait period by repeatedly calling this method.+ * Waits for the given condition to return true. Most of the <code>waitForCondition()</code>+ * methods throw an {@link AssertionFailedError} if the timeout period expires. This method+ * allows you to setup a longer wait period by repeatedly calling this method.*- * <P>Most clients should use {@link #waitForCondition(BooleanSupplier)}.+ * <P>+ * Most clients should use {@link #waitForCondition(BooleanSupplier)}.** @param supplier the supplier that returns true when satisfied*/@@ -496,8 +517,8 @@ public abstract class AbstractGTest {}/**- * Waits for the value returned by the supplier to be non-null, throwing an exception if- * that does not happen by the default timeout.+ * Waits for the value returned by the supplier to be non-null, throwing an exception if that+ * does not happen by the default timeout.** @param supplier the supplier of the value* @param failureMessage the message to print upon the timeout being reached@@ -509,8 +530,8 @@ public abstract class AbstractGTest {}/**- * Waits for the value returned by the supplier to be non-null, throwing an exception if- * that does not happen by the default timeout.+ * Waits for the value returned by the supplier to be non-null, throwing an exception if that+ * does not happen by the default timeout.** @param supplier the supplier of the value* @return the non-null value@@ -521,8 +542,8 @@ public abstract class AbstractGTest {}/**- * Waits for the value returned by the supplier to be non-null, throwing an exception if- * that does not happen by the default timeout.+ * Waits for the value returned by the supplier to be non-null, throwing an exception if that+ * does not happen by the default timeout.** @param supplier the supplier of the value* @return the non-null value@@ -533,12 +554,13 @@ public abstract class AbstractGTest {}/**- * Waits for the value returned by the supplier to be non-null. If the timeout period- * expires, then null will be returned. Most of the <code>waitXyz()</code> methods- * throw an {@link AssertionFailedError} if the timeout period expires. This method allows- * you to setup a longer wait period by repeatedly calling this method.+ * Waits for the value returned by the supplier to be non-null. If the timeout period expires,+ * then null will be returned. Most of the <code>waitXyz()</code> methods throw an+ * {@link AssertionFailedError} if the timeout period expires. This method allows you to setup a+ * longer wait period by repeatedly calling this method.*- * <P>Most clients should use {@link #waitForValue(Supplier)}.+ * <P>+ * Most clients should use {@link #waitForValue(Supplier)}.** @param supplier the supplier of the value* @return the value; may be null@@ -549,8 +571,8 @@ public abstract class AbstractGTest {}/**- * Waits for the value returned by the supplier to be non-null, optionally- * throwing an exception if that does not happen by the given timeout.+ * Waits for the value returned by the supplier to be non-null, optionally throwing an exception+ * if that does not happen by the given timeout.** @param supplier the supplier of the value* @param failureMessage the message to print upon the timeout being reacheddiff --git a/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGenericTest.java b/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGenericTest.javaindex d7bff8ff89..203945711d 100644--- a/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGenericTest.java+++ b/Ghidra/Framework/Generic/src/main/java/generic/test/AbstractGenericTest.java@@ -4,9 +4,9 @@* 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.@@ -15,7 +15,7 @@*/package generic.test;-import static org.junit.Assert.*;+import static org.junit.Assert.fail;import java.awt.*;import java.awt.image.BufferedImage;@@ -39,8 +39,6 @@ import org.junit.rules.*;import org.junit.runner.Description;import generic.jar.ResourceFile;-import generic.test.rule.Repeated;-import generic.test.rule.RepeatedTestRule;import generic.util.WindowUtilities;import ghidra.GhidraTestApplicationLayout;import ghidra.framework.*;@@ -111,17 +109,6 @@ public abstract class AbstractGenericTest extends AbstractGTest {@Rulepublic RuleChain ruleChain = RuleChain.outerRule(testName).around(watchman);// control rule ordering- /**- * This rule handles the {@link Repeated} annotation- *- * <p>- * During batch mode, this rule should never be needed. This rule is included here as a- * convenience, in case a developer wants to use the {@link Repeated} annotation to diagnose a- * non-deterministic test failure. Without this rule, the annotation would be silently ignored.- */- @Rule- public TestRule repeatedRule = new RepeatedTestRule();-@Afterpublic void resetLogging() {if (logSettingsChanged) {@@ -237,9 +224,9 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * A callback for subclasses when a test has failed. This will be called- * <b>after</b> <code>tearDown()</code>. This means that any diagnostics will have to- * take into account items that have already been disposed.+ * A callback for subclasses when a test has failed. This will be called <b>after</b>+ * <code>tearDown()</code>. This means that any diagnostics will have to take into account items+ * that have already been disposed.** @param e the exception that happened when the test failed*/@@ -258,10 +245,10 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * A convenience method to change the log level of the given logger name. The logger name is- * typically the class name that contains specialized logging. You may also pass a package- * name to get logging for all classes in that package.- * See {@link Configurator#setLevel(String, Level)}+ * A convenience method to change the log level of the given logger name. The logger name is+ * typically the class name that contains specialized logging. You may also pass a package name+ * to get logging for all classes in that package. See+ * {@link Configurator#setLevel(String, Level)}* <P>* The console appender's log level will be changed if needed to ensure that messages for the* given log level are displayed.@@ -316,9 +303,8 @@ public abstract class AbstractGenericTest extends AbstractGTest {* Returns the window parent of c. If c is a window, then c is returned.** <P>- * Warning: this differs from- * {@link SwingUtilities#windowForComponent(Component)} in that the latter- * method will not return the given component if it is a window.+ * Warning: this differs from {@link SwingUtilities#windowForComponent(Component)} in that the+ * latter method will not return the given component if it is a window.** @param c the component* @return the window@@ -328,8 +314,8 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Load a text resource file into an ArrayList. Each line of the file is- * stored as an item in the list.+ * Load a text resource file into an ArrayList. Each line of the file is stored as an item in+ * the list.** @param cls class where resource exists* @param name resource filename@@ -372,15 +358,14 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Returns the file within the data directory of the TestResources module- * that matches the given relative path+ * Returns the file within the data directory of the TestResources module that matches the given+ * relative path* <p>* A {@link FileNotFoundException} is throw if the file does not exist.*- * @param path path relative to the data directory of the TestResources- * module.- * @return the file within the data directory of the TestResources module- * that matches the given relative path+ * @param path path relative to the data directory of the TestResources module.+ * @return the file within the data directory of the TestResources module that matches the given+ * relative path* @throws FileNotFoundException if the given file does not exist*/public static File getTestDataFile(String path) throws FileNotFoundException {@@ -390,8 +375,8 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Returns a file that points to the location on disk of the given relative- * path name. The path is relative to the test resources directory.+ * Returns a file that points to the location on disk of the given relative path name. The path+ * is relative to the test resources directory.** @param relativePath the path of the file* @return a file that points to the location on disk of the relative path.@@ -406,15 +391,14 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Returns the file within the data directory of the TestResources module- * that matches the given relative path.+ * Returns the file within the data directory of the TestResources module that matches the given+ * relative path.* <p>* Null is returned if the file could not be found.*- * @param path path relative to the data directory of the TestResources- * module.- * @return the file within the data directory of the TestResources module- * that matches the given relative path+ * @param path path relative to the data directory of the TestResources module.+ * @return the file within the data directory of the TestResources module that matches the given+ * relative path*/public static File findTestDataFile(String path) {try {@@ -445,9 +429,9 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Get the first field object contained within object ownerInstance which- * has the type classType. This method is only really useful if it is known- * that only a single field of classType exists within the ownerInstance.+ * Get the first field object contained within object ownerInstance which has the type+ * classType. This method is only really useful if it is known that only a single field of+ * classType exists within the ownerInstance.** @param <T> the type* @param classType the class type of the desired field@@ -461,17 +445,15 @@ public abstract class AbstractGenericTest extends AbstractGTest {/*** Sets the instance field by the given name on the given object instance.* <p>- * Note: if the field is static, then the <code>ownerInstance</code> field can- * be the class of the object that contains the variable.+ * Note: if the field is static, then the <code>ownerInstance</code> field can be the class of+ * the object that contains the variable.** @param fieldName The name of the field to retrieve.- * @param ownerInstance The object instance from which to get the variable- * instance.+ * @param ownerInstance The object instance from which to get the variable instance.* @param value The value to use when setting the given field- * @throws RuntimeException if there is a problem accessing the field using- * reflection. A RuntimeException is used so that calling tests- * can avoid using a try/catch block, but will still fail when- * an error is encountered.+ * @throws RuntimeException if there is a problem accessing the field using reflection. A+ * RuntimeException is used so that calling tests can avoid using a try/catch block,+ * but will still fail when an error is encountered.* @see Field#set(Object, Object)*/public static void setInstanceField(String fieldName, Object ownerInstance, Object value)@@ -480,20 +462,18 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Gets the instance field by the given name on the given object instance.- * The value is a primitive wrapper if it is a primitive type.+ * Gets the instance field by the given name on the given object instance. The value is a+ * primitive wrapper if it is a primitive type.* <p>- * Note: if the field is static, then the <code>ownerInstance</code> field can- * be the class of the object that contains the variable.+ * Note: if the field is static, then the <code>ownerInstance</code> field can be the class of+ * the object that contains the variable.** @param fieldName The name of the field to retrieve.- * @param ownerInstance The object instance from which to get the variable- * instance.+ * @param ownerInstance The object instance from which to get the variable instance.* @return The field instance.- * @throws RuntimeException if there is a problem accessing the field using- * reflection. A RuntimeException is used so that calling tests- * can avoid using a try/catch block, but will still fail when- * an error is encountered.+ * @throws RuntimeException if there is a problem accessing the field using reflection. A+ * RuntimeException is used so that calling tests can avoid using a try/catch block,+ * but will still fail when an error is encountered.* @see Field#get(java.lang.Object)* @since Tracker Id 267*/@@ -503,22 +483,19 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Uses reflection to execute the constructor for the given class with the- * given parameters. The new instance of the given class will be returned.+ * Uses reflection to execute the constructor for the given class with the given parameters. The+ * new instance of the given class will be returned.* <p>** @param containingClass The class that contains the desired constructor.- * @param parameterTypes The parameter <b>types</b> that the constructor- * takes. This value can be null or zero length if there are no- * parameters to pass- * @param args The parameter values that should be passed to the- * constructor. This value can be null or zero length if there- * are no parameters to pass+ * @param parameterTypes The parameter <b>types</b> that the constructor takes. This value can+ * be null or zero length if there are no parameters to pass+ * @param args The parameter values that should be passed to the constructor. This value can be+ * null or zero length if there are no parameters to pass* @return The new class instance- * @throws RuntimeException if there is a problem accessing the constructor- * using reflection. A RuntimeException is used so that calling- * tests can avoid using a try/catch block, but will still fail- * when an error is encountered.+ * @throws RuntimeException if there is a problem accessing the constructor using reflection. A+ * RuntimeException is used so that calling tests can avoid using a try/catch block,+ * but will still fail when an error is encountered.*/public static Object invokeConstructor(Class<?> containingClass, Class<?>[] parameterTypes,Object[] args) throws RuntimeException {@@ -527,26 +504,23 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Uses reflection to execute the method denoted by the given method name.- * If any value is returned from the method execution, then it will be- * returned from this method. Otherwise, <code>null</code> is returned.+ * Uses reflection to execute the method denoted by the given method name. If any value is+ * returned from the method execution, then it will be returned from this method. Otherwise,+ * <code>null</code> is returned.* <p>- * Note: if the method is static, then the <code>ownerInstance</code> field can- * be the class of the object that contains the method.+ * Note: if the method is static, then the <code>ownerInstance</code> field can be the class of+ * the object that contains the method.** @param methodName The name of the method to execute.- * @param ownerInstance The object instance of which the method will be- * executed.+ * @param ownerInstance The object instance of which the method will be executed.* @param parameterTypes The parameter <b>types</b> that the method takes.- * @param args The parameter values that should be passed to the method.- * This value can be null or zero length if there are no- * parameters to pass+ * @param args The parameter values that should be passed to the method. This value can be null+ * or zero length if there are no parameters to pass* @return The return value as returned from executing the method.* @see Method#invoke(java.lang.Object, java.lang.Object[])- * @throws RuntimeException if there is a problem accessing the field using- * reflection. A RuntimeException is used so that calling tests- * can avoid using a try/catch block, but will still fail when- * an error is encountered.+ * @throws RuntimeException if there is a problem accessing the field using reflection. A+ * RuntimeException is used so that calling tests can avoid using a try/catch block,+ * but will still fail when an error is encountered.* @since Tracker Id 267*/public static Object invokeInstanceMethod(String methodName, Object ownerInstance,@@ -557,19 +531,16 @@ public abstract class AbstractGenericTest extends AbstractGTest {/*** This method is just a "pass through" method for- * {@link #invokeInstanceMethod(String, Object, Class[], Object[])} so that- * callers do not need to pass null to that method when the underlying- * instance method does not have any parameters.+ * {@link #invokeInstanceMethod(String, Object, Class[], Object[])} so that callers do not need+ * to pass null to that method when the underlying instance method does not have any parameters.** @param methodName The name of the method to execute.- * @param ownerInstance The object instance of which the method will be- * executed.+ * @param ownerInstance The object instance of which the method will be executed.* @return The return value as returned from executing the method.* @see Method#invoke(java.lang.Object, java.lang.Object[])- * @throws RuntimeException if there is a problem accessing the field using- * reflection. A RuntimeException is used so that calling tests- * can avoid using a try/catch block, but will still fail when- * an error is encountered.+ * @throws RuntimeException if there is a problem accessing the field using reflection. A+ * RuntimeException is used so that calling tests can avoid using a try/catch block,+ * but will still fail when an error is encountered.* @see #invokeInstanceMethod(String, Object, Class[], Object[])*/public static Object invokeInstanceMethod(String methodName, Object ownerInstance)@@ -578,8 +549,8 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Returns a string which is a printout of a stack trace for each thread- * running in the current JVM+ * Returns a string which is a printout of a stack trace for each thread running in the current+ * JVM** @return the stack trace string*/@@ -588,8 +559,7 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Prints the contents of the given collection by way of the- * {@link Object#toString()} method.+ * Prints the contents of the given collection by way of the {@link Object#toString()} method.** @param collection The contents of which to print* @return A string representation of the given collection@@ -616,6 +586,7 @@ public abstract class AbstractGenericTest extends AbstractGTest {/*** Returns a font metrics for the given font using a generic buffered image graphics context.+ ** @param font the font* @return the font metrics*/@@ -628,10 +599,10 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Signals that the client expected the System Under Test (SUT) to report errors. Use this- * when you wish to verify that errors are reported and you do not want those errors to- * fail the test. The default value for this setting is false, which means that any- * errors reported will fail the running test.+ * Signals that the client expected the System Under Test (SUT) to report errors. Use this when+ * you wish to verify that errors are reported and you do not want those errors to fail the+ * test. The default value for this setting is false, which means that any errors reported will+ * fail the running test.** @param expected true if errors are expected.*/@@ -651,12 +622,12 @@ public abstract class AbstractGenericTest extends AbstractGTest {//==================================================================================================/**- * Returns the directory into which tests can write debug files, such as- * files containing print statements or image files.+ * Returns the directory into which tests can write debug files, such as files containing print+ * statements or image files.** <P>- * This is not a temporary directory that will be deleted between tests,- * which is useful in that the debug files will persist after a test run.+ * This is not a temporary directory that will be deleted between tests, which is useful in that+ * the debug files will persist after a test run.** <P>* Examples of this directory:@@ -701,16 +672,14 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Creates a <b>sub-directory</b> with the given name as a child of the Java- * temp directory. The given name will be the prefix of the new directory- * name, with any additional text as created by- * {@link Files#createTempDirectory(Path, String, java.nio.file.attribute.FileAttribute...)}.- * Any left-over test directories will be cleaned-up before creating the new- * directory.+ * Creates a <b>sub-directory</b> with the given name as a child of the Java temp directory. The+ * given name will be the prefix of the new directory name, with any additional text as created+ * by {@link Files#createTempDirectory(Path, String, java.nio.file.attribute.FileAttribute...)}.+ * Any left-over test directories will be cleaned-up before creating the new directory.** <p>- * Note: you should not call this method multiple times, as each call will- * cleanup the previously created directories.+ * Note: you should not call this method multiple times, as each call will cleanup the+ * previously created directories.** @param name the name of the directory to create* @return the newly created directory@@ -738,14 +707,13 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Creates a file path with a filename that is under the system temp- * directory. The path returned will not point to an existing file. The- * suffix of the file will be <code>.tmp</code>.+ * Creates a file path with a filename that is under the system temp directory. The path+ * returned will not point to an existing file. The suffix of the file will be+ * <code>.tmp</code>.** @param name the filename* @return a new file path- * @throws IOException if there is any problem ensuring that the created- * path is non-existent+ * @throws IOException if there is any problem ensuring that the created path is non-existent* @see #createTempFilePath(String, String)*/public String createTempFilePath(String name) throws IOException {@@ -754,16 +722,14 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Creates a file path with a filename that is under the system temp- * directory. The path returned will not point to an existing file. This- * method is the same as {@link #createTempFilePath(String)}, except that- * you must provide the extension.+ * Creates a file path with a filename that is under the system temp directory. The path+ * returned will not point to an existing file. This method is the same as+ * {@link #createTempFilePath(String)}, except that you must provide the extension.** @param name the filename* @param extension the file extension* @return a new file path- * @throws IOException if there is any problem ensuring that the created- * path is non-existent+ * @throws IOException if there is any problem ensuring that the created path is non-existent* @see #createTempFile(String, String)*/public String createTempFilePath(String name, String extension) throws IOException {@@ -773,10 +739,10 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Creates a temp file for the current test, using the test name as a prefix- * for the filename. This method calls {@link #createTempFile(String)},- * which will cleanup any pre-existing temp files whose name pattern matches- * this test name. This helps to avoid old temp files from accumulating.+ * Creates a temp file for the current test, using the test name as a prefix for the filename.+ * This method calls {@link #createTempFile(String)}, which will cleanup any pre-existing temp+ * files whose name pattern matches this test name. This helps to avoid old temp files from+ * accumulating.** @return the new temp file* @throws IOException if there is a problem creating the new file@@ -786,10 +752,10 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Creates a temp file for the current test, using the test name as a prefix- * for the filename. This method calls {@link #createTempFile(String)},- * which will cleanup any pre-existing temp files whose name pattern matches- * this test name. This helps to avoid old temp files from accumulating.+ * Creates a temp file for the current test, using the test name as a prefix for the filename.+ * This method calls {@link #createTempFile(String)}, which will cleanup any pre-existing temp+ * files whose name pattern matches this test name. This helps to avoid old temp files from+ * accumulating.** @param suffix the suffix to provide for the temp file* @return the new temp file@@ -800,15 +766,13 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Creates a file in the Application temp directory using the given name as a- * prefix and the given suffix. The final filename will also include the- * current test name, as well as any data added by- * {@link File#createTempFile(String, String, File)}. The file suffix will be+ * Creates a file in the Application temp directory using the given name as a prefix and the+ * given suffix. The final filename will also include the current test name, as well as any data+ * added by {@link File#createTempFile(String, String, File)}. The file suffix will be* <code>.tmp</code>* <p>- * The file will be marked to delete on JVM exit. This will not work if the- * JVM is taken down the hard way, as when pressing the stop button in- * Eclipse.+ * The file will be marked to delete on JVM exit. This will not work if the JVM is taken down+ * the hard way, as when pressing the stop button in Eclipse.** @param name the prefix to put on the file, before the test name* @return the newly created file@@ -821,25 +785,22 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Creates a file in the Application temp directory using the given name as a- * prefix and the given suffix. The final filename will also include the- * current test name, as well as any data added by- * {@link File#createTempFile(String, String, File)}.+ * Creates a file in the Application temp directory using the given name as a prefix and the+ * given suffix. The final filename will also include the current test name, as well as any data+ * added by {@link File#createTempFile(String, String, File)}.* <p>- * The file will be marked to delete on JVM exit. This will not work if the- * JVM is taken down the hard way, as when pressing the stop button in- * Eclipse.+ * The file will be marked to delete on JVM exit. This will not work if the JVM is taken down+ * the hard way, as when pressing the stop button in Eclipse.* <p>- * Note: This method <b>will</b> create the file on disk! If you need the- * file to not exist, then you must delete the file yourself. Alternatively,- * you could instead call {@link #createTempFilePath(String, String)}, which- * will ensure that the created temp file is deleted.+ * Note: This method <b>will</b> create the file on disk! If you need the file to not exist,+ * then you must delete the file yourself. Alternatively, you could instead call+ * {@link #createTempFilePath(String, String)}, which will ensure that the created temp file is+ * deleted.** <p>- * Finally, this method will delete any files that match the given name and- * suffix values before creating the given temp file. <b>This is important,- * as it will delete any files already created by the test that match this- * info.</b>+ * Finally, this method will delete any files that match the given name and suffix values before+ * creating the given temp file. <b>This is important, as it will delete any files already+ * created by the test that match this info.</b>** @param name the prefix to put on the file, before the test name* @param suffix the file suffix@@ -866,8 +827,7 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Delete any files under the Java temp directory that have the given text- * in their name.+ * Delete any files under the Java temp directory that have the given text in their name.** @param nameText the partial name text to match against the files* @see #deleteMatchingTempFiles(String)@@ -880,8 +840,8 @@ public abstract class AbstractGenericTest extends AbstractGTest {}/**- * Delete any files under the this test case's specific temp directory that- * match the give regex {@link Pattern}+ * Delete any files under the this test case's specific temp directory that match the give regex+ * {@link Pattern}** @param namePattern the pattern to match against the files* @see #deleteSimilarTempFiles(String)diff --git a/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinished.java b/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinished.javanew file mode 100644index 0000000000..916ac38f94--- /dev/null+++ b/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinished.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 generic.test.rule;++import java.lang.annotation.*;++import ghidra.lifecycle.Unfinished.TODOException;++/**+ * Ignore failures due to {@link TODOException}+ *+ * <p>+ * As a matter of practice, tests ought not to be committed into source control with this+ * annotation. Or, if they are, they should only have this for a short period. Production code ought+ * not to be throwing {@link TODOException}, anyway, but the reality is, sometimes things are+ * "production ready," despite having some unfinished components. This annotation allows tests that+ * identify those unfinished portions to remain active, but ignored. During development, the+ * developer may also apply this annotation to distinguish "real" failures from those already+ * identified as "unfinished." The annotation ought to be removed when it's time to finish those+ * components, so that failures due to unfinished code are quickly identified.+ */+@Retention(RetentionPolicy.RUNTIME)+@Target({ ElementType.METHOD, ElementType.TYPE })+public @interface IgnoreUnfinished {+}diff --git a/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinishedRule.java b/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinishedRule.javanew file mode 100644index 0000000000..1f6b65c1cf--- /dev/null+++ b/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinishedRule.java@@ -0,0 +1,47 @@+/* ###+ * 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 generic.test.rule;++import org.junit.Rule;+import org.junit.rules.TestRule;+import org.junit.runner.Description;+import org.junit.runners.model.Statement;++import generic.test.AbstractGenericTest;++/**+ * A test rule which processes the {@link IgnoreUnfinished} annotation+ *+ * <p>+ * This must be included in your test case (or a superclass) as a field with the {@link Rule}+ * annotation. It's included in the {@link AbstractGenericTest}, so most Ghidra test classes already+ * have it.+ */+public class IgnoreUnfinishedRule implements TestRule {+ @Override+ public Statement apply(Statement base, Description description) {+ IgnoreUnfinished annot;+ annot = description.getAnnotation(IgnoreUnfinished.class);+ if (annot != null) {+ return new IgnoreUnfinishedStatement(base);+ }+ annot = description.getTestClass().getAnnotation(IgnoreUnfinished.class);+ if (annot != null) {+ return new IgnoreUnfinishedStatement(base);+ }+ return base;+ }+}diff --git a/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinishedStatement.java b/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinishedStatement.javanew file mode 100644index 0000000000..163489fb96--- /dev/null+++ b/Ghidra/Framework/Generic/src/main/java/generic/test/rule/IgnoreUnfinishedStatement.java@@ -0,0 +1,44 @@+/* ###+ * 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 generic.test.rule;++import org.junit.AssumptionViolatedException;+import org.junit.runners.model.Statement;++import ghidra.lifecycle.Unfinished.TODOException;++/**+ * A JUnit test statement that ignores {@link TODOException}+ *+ * @see IgnoreUnfinished+ */+public class IgnoreUnfinishedStatement extends Statement {+ private final Statement base;++ public IgnoreUnfinishedStatement(Statement base) {+ this.base = base;+ }++ @Override+ public void evaluate() throws Throwable {+ try {+ base.evaluate();+ }+ catch (TODOException e) {+ throw new AssumptionViolatedException("Unfinished", e);+ }+ }+}diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Experimental.java b/Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Experimental.javasimilarity index 100%rename from Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Experimental.javarename to Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Experimental.javadiff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Internal.java b/Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Internal.javasimilarity index 100%rename from Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Internal.javarename to Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Internal.javadiff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Transitional.java b/Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Transitional.javasimilarity index 100%rename from Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Transitional.javarename to Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Transitional.javadiff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Unfinished.java b/Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Unfinished.javasimilarity index 100%rename from Ghidra/Framework/Emulation/src/main/java/ghidra/lifecycle/Unfinished.javarename to Ghidra/Framework/Generic/src/main/java/ghidra/lifecycle/Unfinished.javadiff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/util/MathUtilities.java b/Ghidra/Framework/Generic/src/main/java/ghidra/util/MathUtilities.javaindex 6a548c380c..46bb1fbd4f 100644--- a/Ghidra/Framework/Generic/src/main/java/ghidra/util/MathUtilities.java+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/util/MathUtilities.java@@ -15,6 +15,8 @@*/package ghidra.util;+import java.util.Comparator;+public class MathUtilities {private MathUtilities() {@@ -204,4 +206,20 @@ public class MathUtilities {public static long unsignedMax(long a, int b) {return (Long.compareUnsigned(a, b & 0x0ffffffffL) > 0) ? a : b;}++ public static <C> C cmin(C a, C b, Comparator<C> comp) {+ return comp.compare(a, b) <= 0 ? a : b;+ }++ public static <C extends Comparable<C>> C cmin(C a, C b) {+ return cmin(a, b, Comparator.naturalOrder());+ }++ public static <C> C cmax(C a, C b, Comparator<C> comp) {+ return comp.compare(a, b) >= 0 ? a : b;+ }++ public static <C extends Comparable<C>> C cmax(C a, C b) {+ return cmax(a, b, Comparator.naturalOrder());+ }}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/assembler/AssemblyBuffer.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/assembler/AssemblyBuffer.javaindex 0fc34e3b62..0e351cd914 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/assembler/AssemblyBuffer.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/plugin/assembler/AssemblyBuffer.java@@ -4,9 +4,9 @@* 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.@@ -18,6 +18,7 @@ package ghidra.app.plugin.assembler;import java.io.ByteArrayOutputStream;import java.io.IOException;+import ghidra.app.plugin.assembler.sleigh.sem.AssemblyPatternBlock;import ghidra.program.model.address.Address;import ghidra.program.model.listing.Program;@@ -68,6 +69,21 @@ public class AssemblyBuffer {return entry.add(baos.size());}+ /**+ * Assemble a line and append it to the buffer+ *+ * @param line the line+ * @param ctx the assembly context+ * @return the resulting bytes for the assembled instruction+ * @throws AssemblySyntaxException if the instruction cannot be parsed+ * @throws AssemblySemanticException if the instruction cannot be encoded+ * @throws IOException if the buffer cannot be written+ */+ public byte[] assemble(String line, AssemblyPatternBlock ctx)+ throws AssemblySyntaxException, AssemblySemanticException, IOException {+ return emit(asm.assembleLine(getNext(), line, ctx));+ }+/*** Assemble a line and append it to the buffer*@@ -109,6 +125,28 @@ public class AssemblyBuffer {** @param at the address of the instruction to patch* @param line the line+ * @param ctx the assembly context+ * @return the resulting bytes for the assembled instruction+ * @throws AssemblySyntaxException if the instruction cannot be parsed+ * @throws AssemblySemanticException if the instruction cannot be encoded+ * @throws IOException if the buffer cannot be written+ */+ public byte[] assemble(Address at, String line, AssemblyPatternBlock ctx)+ throws AssemblySyntaxException, AssemblySemanticException, IOException {+ byte[] full = baos.toByteArray();+ byte[] bytes = asm.assembleLine(at, line, ctx);+ System.arraycopy(bytes, 0, full, (int) at.subtract(entry), bytes.length);+ baos.reset();+ baos.write(full);+ return bytes;+ }++ /**+ * Assemble a line and patch into the buffer+ *+ * @see #assemble(Address, String, AssemblyPatternBlock)+ * @param at the address of the instruction to patch+ * @param line the line* @return the resulting bytes for the assembled instruction* @throws AssemblySyntaxException if the instruction cannot be parsed* @throws AssemblySemanticException if the instruction cannot be encoded@@ -148,4 +186,22 @@ public class AssemblyBuffer {public byte[] getBytes() {return baos.toByteArray();}++ /**+ * Get the starting address+ *+ * @return the address+ */+ public Address getEntry() {+ return entry;+ }++ /**+ * Get the assembler for this buffer+ *+ * @return the assembler+ */+ public Assembler getAssembler() {+ return asm;+ }}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/AbstractPcodeFormatter.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/AbstractPcodeFormatter.javaindex 33380a2ebe..e0a52013d6 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/AbstractPcodeFormatter.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/AbstractPcodeFormatter.java@@ -31,6 +31,7 @@ import ghidra.util.Msg;* {@link #formatOpTemplate(Appender, OpTpl)}. Otherwise, most formatting logic is implemented by* the appender.*+ * @see StringPcodeFormatter for an example* @param <T> the type of this formatter's output, e.g., {@link String}* @param <A> the type of the appender* @see AbstractAppenderdiff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/PcodeFormatter.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/PcodeFormatter.javaindex c2878e54c9..11f454984c 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/PcodeFormatter.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/PcodeFormatter.java@@ -4,9 +4,9 @@* 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.@@ -19,7 +19,6 @@ import java.util.*;import ghidra.app.plugin.processors.sleigh.template.*;import ghidra.program.model.address.AddressFactory;-import ghidra.program.model.address.AddressSpace;import ghidra.program.model.lang.Language;import ghidra.program.model.pcode.PcodeOp;import ghidra.program.model.pcode.Varnode;@@ -37,11 +36,11 @@ public interface PcodeFormatter<T> {}/**- * Format the pcode ops with a specified {@link AddressFactory}. For use when the- * pcode ops can reference program-specific address spaces.+ * Format the pcode ops with a specified {@link AddressFactory}. For use when the pcode ops can+ * reference program-specific address spaces.** @param language the language generating the p-code- * @param addrFactory addressFactory to use when generating pcodeop templates+ * @param addrFactory addressFactory to use when generating pcodeop templates* @param pcodeOps p-code ops to format* @return the formatted result*@@ -71,8 +70,8 @@ public interface PcodeFormatter<T> {ArrayList<OpTpl> list = new ArrayList<OpTpl>();HashMap<Integer, Integer> labelMap = new HashMap<Integer, Integer>(); // label offset to index map- for (PcodeOp pcodeOp : pcodeOps) {-+ for (int seq = 0; seq < pcodeOps.size(); seq++) {+ PcodeOp pcodeOp = pcodeOps.get(seq);int opcode = pcodeOp.getOpcode();VarnodeTpl outputTpl = null;@@ -90,7 +89,7 @@ public interface PcodeFormatter<T> {if (i == 0 && (opcode == PcodeOp.BRANCH || opcode == PcodeOp.CBRANCH)) {// Handle internal branch destination represented by constant destinationif (input.isConstant()) {- int labelOffset = pcodeOp.getSeqnum().getTime() + (int) input.getOffset();+ int labelOffset = seq + (int) input.getOffset();int labelIndex;if (labelMap.containsKey(labelOffset)) {labelIndex = labelMap.get(labelOffset);@@ -117,6 +116,10 @@ public interface PcodeFormatter<T> {Collections.sort(offsetList);for (int i = offsetList.size() - 1; i >= 0; i--) {int labelOffset = offsetList.get(i);+ if (labelOffset > pcodeOps.size()) {+ // Skip jumps out of this block/program+ continue;+ }int labelIndex = labelMap.get(labelOffset);OpTpl labelTpl = getLabelOpTemplate(addrFactory, labelIndex);list.add(labelOffset, labelTpl);@@ -142,11 +145,7 @@ public interface PcodeFormatter<T> {private static VarnodeTpl getVarnodeTpl(AddressFactory addrFactory, Varnode v) {ConstTpl offsetTpl = new ConstTpl(ConstTpl.REAL, v.getOffset());- AddressSpace addressSpace = addrFactory.getAddressSpace(v.getSpace());- if (addressSpace == null) {- throw new IllegalArgumentException("Unknown varnode space ID: " + v.getSpace());- }- ConstTpl spaceTpl = new ConstTpl(addressSpace);+ ConstTpl spaceTpl = new ConstTpl(v.getAddress().getAddressSpace());ConstTpl sizeTpl = new ConstTpl(ConstTpl.REAL, v.getSize());return new VarnodeTpl(spaceTpl, offsetTpl, sizeTpl);}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/pcode/floatformat/FloatFormat.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/pcode/floatformat/FloatFormat.javaindex 6b34dd3c10..c6e82cc029 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/pcode/floatformat/FloatFormat.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/pcode/floatformat/FloatFormat.java@@ -4,9 +4,9 @@* 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.@@ -24,8 +24,8 @@ import ghidra.util.SystemUtilities;/*** {@link FloatFormat} provides IEEE 754 floating-point encoding formats in support of- * floating-point data types and floating-point emulation. A combination of Java- * float/double and {@link BigFloat} are used to facilitate floating-point operations.+ * floating-point data types and floating-point emulation. A combination of Java float/double and+ * {@link BigFloat} are used to facilitate floating-point operations.*/public class FloatFormat {@@ -116,8 +116,8 @@ public class FloatFormat {}else if (size == 10) {/**- * 80-bit double extended precision format- * See https://en.wikipedia.org/wiki/Extended_precision+ * 80-bit double extended precision format. See+ * https://en.wikipedia.org/wiki/Extended_precision*/signbit_pos = 79;exp_pos = 64;@@ -155,6 +155,7 @@ public class FloatFormat {/*** Get the maximum finite {@link BigFloat} value for this format+ ** @return maximum finite {@link BigFloat} value*/public BigFloat getMaxBigFloat() {@@ -163,6 +164,7 @@ public class FloatFormat {/*** Get the minimum finite subnormal {@link BigFloat} value for this format+ ** @return minimum finite subnormal {@link BigFloat} value*/public BigFloat getMinBigFloat() {@@ -318,8 +320,8 @@ public class FloatFormat {/*** Decode {@code encoding} to a BigFloat using this format.*- * The method {@link #decodeBigFloat(BigInteger)} should be used for encodings- * larger than 8 bytes.+ * The method {@link #decodeBigFloat(BigInteger)} should be used for encodings larger than 8+ * bytes.** @param encoding the encoding* @return the decoded value as a BigFloat@@ -495,7 +497,7 @@ public class FloatFormat {switch (value.kind) {case QUIET_NAN:case SIGNALING_NAN:- return getNaNEncoding(false);+ return getNaNEncoding(value.sign < 0);case INFINITE:return getInfinityEncoding(value.sign < 0);case FINITE:@@ -621,8 +623,9 @@ public class FloatFormat {}/**- * Perform appropriate rounding and conversion to BigDecimal prior to generating- * a formatted decimal string of the specified BigFloat value.+ * Perform appropriate rounding and conversion to BigDecimal prior to generating a formatted+ * decimal string of the specified BigFloat value.+ ** @param bigFloat value* @return decimal string representation*/@@ -631,11 +634,13 @@ public class FloatFormat {}/**- * Perform appropriate rounding and conversion to BigDecimal prior to generating- * a formatted decimal string of the specified BigFloat value.+ * Perform appropriate rounding and conversion to BigDecimal prior to generating a formatted+ * decimal string of the specified BigFloat value.+ ** @param bigFloat value* @param compact if true the precision will be reduced to a form which is still equivalent at- * the binary encoding level for this format. Enabling this will incur additional overhead.+ * the binary encoding level for this format. Enabling this will incur additional+ * overhead.* @return decimal string representation*/public String toDecimalString(BigFloat bigFloat, boolean compact) {@@ -643,8 +648,8 @@ public class FloatFormat {}/**- * Convert an encoded value to a binary floating point representation.- * This is intended for diagnostic purposes only.+ * Convert an encoded value to a binary floating point representation. This is intended for+ * diagnostic purposes only.** NB: this method should not be used if {@link #size}>8*@@ -692,8 +697,8 @@ public class FloatFormat {}/**- * Convert an encoded value to a binary floating point representation.- * This is intended for diagnostic purposes only.+ * Convert an encoded value to a binary floating point representation. This is intended for+ * diagnostic purposes only.** @param encoding the encoding of a floating point value in this format* @return a binary string representation of the encoded floating point {@code encoding}@@ -741,6 +746,7 @@ public class FloatFormat {/*** Convert a native float to {@link BigFloat} using 4-byte IEEE 754 encoding+ ** @param f a float* @return {@link BigFloat} equal to {@code f}*/@@ -750,6 +756,7 @@ public class FloatFormat {/*** Convert a native double to {@link BigFloat} using 8-byte IEEE 754 encoding+ ** @param d a double* @return {@link BigFloat} equal to {@code f}*/@@ -762,8 +769,9 @@ public class FloatFormat {}/**- * Get 4-byte binary encoding for the specified native float value.- * This is intended for diagnostic purposes only.+ * Get 4-byte binary encoding for the specified native float value. This is intended for+ * diagnostic purposes only.+ ** @param f a float* @return binary representation of {@code f}*/@@ -772,8 +780,9 @@ public class FloatFormat {}/**- * Get 8-byte binary encoding for the specified native double value.- * This is intended for diagnostic purposes only.+ * Get 8-byte binary encoding for the specified native double value. This is intended for+ * diagnostic purposes only.+ ** @param d a double* @return binary representation of {@code f}*/@@ -782,8 +791,9 @@ public class FloatFormat {}/**- * Get binary encoding for the specified rounded {@link BigFloat} value.- * This is intended for diagnostic purposes only.+ * Get binary encoding for the specified rounded {@link BigFloat} value. This is intended for+ * diagnostic purposes only.+ ** @param value floating point value* @return binary representation of {@code value}*/@@ -800,9 +810,11 @@ public class FloatFormat {}/**- * right shift and round to nearest even or left shift to an integer with lead bit at newLeadBit.+ * right shift and round to nearest even or left shift to an integer with lead bit at+ * newLeadBit.*- * The final round up might cause a carry that propagates up, so this must be followed by a test.+ * The final round up might cause a carry that propagates up, so this must be followed by a+ * test.** @param i integer representation of mantissa 1.xxxxx* @param newLeadBit the bit position we want as a new lead bit@@ -866,8 +878,8 @@ public class FloatFormat {/*** Construct SmallFloat Data. (similar to BigFloat)*- * @param fracbits number of fractional bits (positive non-zero value; includes additional- * implied bit if relavent).+ * @param fracbits number of fractional bits (positive non-zero value; includes additional+ * implied bit if relavent).* @param expbits maximum number of bits in exponent* @param kind the Kind, FINITE, INFINITE, ...* @param sign +1 or -1@@ -1178,16 +1190,15 @@ public class FloatFormat {}/**- * Constructs a {@code BigFloat} initialized to the value- * represented by the specified decimal {@code String}, as performed- * by {@link BigDecimal#BigDecimal(String)}. Other values permitted- * are (case-insenstive): "NaN", "Infinity", "+Infinity", "-Infinity"- * (See {@link BigFloat#NAN}, {@link BigFloat#INFINITY}, {@link BigFloat#POSITIVE_INFINITY},+ * Constructs a {@code BigFloat} initialized to the value represented by the specified decimal+ * {@code String}, as performed by {@link BigDecimal#BigDecimal(String)}. Other values permitted+ * are (case-insenstive): "NaN", "Infinity", "+Infinity", "-Infinity" (See {@link BigFloat#NAN},+ * {@link BigFloat#INFINITY}, {@link BigFloat#POSITIVE_INFINITY},* {@link BigFloat#NEGATIVE_INFINITY}).** @param string the string to be parsed.* @return value as a {@link BigFloat}- * @throws NullPointerException if the string is null+ * @throws NullPointerException if the string is null* @throws NumberFormatException if the string parse fails.*/public BigFloat getBigFloat(String string) throws NumberFormatException {@@ -1206,12 +1217,12 @@ public class FloatFormat {}/**- * Constructs a {@code BigFloat} initialized to the value- * represented by the specified {@code BigDecimal}.+ * Constructs a {@code BigFloat} initialized to the value represented by the specified+ * {@code BigDecimal}.** @param value the decimal value.* @return value as a {@link BigFloat}- * @throws NullPointerException if the string is null+ * @throws NullPointerException if the string is null* @throws NumberFormatException if the string parse fails.*/public BigFloat getBigFloat(BigDecimal value) {diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/address/SpecialAddress.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/address/SpecialAddress.javaindex cd8874958c..781f35dfaa 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/address/SpecialAddress.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/address/SpecialAddress.java@@ -4,9 +4,9 @@* 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.@@ -16,33 +16,26 @@package ghidra.program.model.address;/**- * Class used represent "special addresses"+ * Class used to represent "special addresses"*/public class SpecialAddress extends GenericAddress {-+SpecialAddress(String name) {super(new GenericAddressSpace(name, 0, 1, AddressSpace.TYPE_NONE, -1), 0);}-- /**- * @see java.lang.Object#toString()- */+@Override- public String toString() {+ public String toString() {return addrSpace.getName();}- /**- * @see ghidra.program.model.address.Address#toString(boolean)- */+@Override- public String toString(boolean showAddressSpace) {+ public String toString(boolean showAddressSpace) {return addrSpace.getName();}- /**- * @see ghidra.program.model.address.Address#toString(java.lang.String)- */+@Override- public String toString(String prefix) {+ public String toString(String prefix) {return addrSpace.getName();}}diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/PcodeOp.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/PcodeOp.javaindex fedc30abfe..dabeebec5a 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/PcodeOp.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/PcodeOp.java@@ -62,7 +62,7 @@ public class PcodeOp {public static final int INT_SLESS = 13; // Return TRUE if signed op1 < signed op2public static final int INT_SLESSEQUAL = 14; // Return TRUE if signed op1 <= signed op2public static final int INT_LESS = 15; // Return TRUE if unsigned op1 < unsigned op2- // Also indicates borrow on unsigned substraction+ // Also indicates borrow on unsigned subtractionpublic static final int INT_LESSEQUAL = 16; // Return TRUE if unsigned op1 <= unsigned op2public static final int INT_ZEXT = 17; // Zero extend operandpublic static final int INT_SEXT = 18; // Sign extend operanddiff --git a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/app/plugin/assembler/sleigh/x64AssemblyTest.java b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/app/plugin/assembler/sleigh/x64AssemblyTest.javaindex 53d947a070..f3ea4c4103 100644--- a/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/app/plugin/assembler/sleigh/x64AssemblyTest.java+++ b/Ghidra/Framework/SoftwareModeling/src/test/java/ghidra/app/plugin/assembler/sleigh/x64AssemblyTest.java@@ -4,9 +4,9 @@* 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.@@ -15,7 +15,8 @@*/package ghidra.app.plugin.assembler.sleigh;-import static org.junit.Assert.*;+import static org.junit.Assert.assertTrue;+import static org.junit.Assert.fail;import org.junit.Test;@@ -281,6 +282,11 @@ public class x64AssemblyTest extends AbstractAssemblyTest {"48:81:65:f8:00:00:ff:ff");}+ @Test+ public void testAssemble_PUSH_R8() {+ assertOneCompatRestExact("PUSH R8", "41:50");+ }+//@Ignore("This is a demonstration of an issue with signedness and scalar print pieces.")//@Testpublic void testAssembly_AND_mRBP_n0x8m_0x80()diff --git a/Ghidra/Processors/Toy/data/languages/toy.sinc b/Ghidra/Processors/Toy/data/languages/toy.sincindex babaca006a..260ffad8a2 100644--- a/Ghidra/Processors/Toy/data/languages/toy.sinc+++ b/Ghidra/Processors/Toy/data/languages/toy.sinc@@ -20,6 +20,10 @@ define register offset=0x1000 size=$(SIZE) [r8 r9 r10 r11 r12 sp lr pc];+define ram offset=0x0 size=$(SIZE) [+ mmr0+];+# STATUS REGISTER MAP: (LOW)# C - CARRY# Z - ZEROdiff --git a/Ghidra/Processors/Toy/data/languages/toyInstructions.sinc b/Ghidra/Processors/Toy/data/languages/toyInstructions.sincindex 119108bbdf..f685025595 100644--- a/Ghidra/Processors/Toy/data/languages/toyInstructions.sinc+++ b/Ghidra/Processors/Toy/data/languages/toyInstructions.sinc@@ -206,7 +206,7 @@ define pcodeop pcodeop_three;:br^COND Rel82 is $(INSTR_PHASE) op1215=0xe & op0303=0x0 & COND & Rel82 { build COND; goto Rel82; }:brds^COND Rel82 is $(INSTR_PHASE) op1215=0xe & op0303=0x1 & COND & Rel82 { build COND; delayslot(1); goto Rel82; }:br^COND rs is $(INSTR_PHASE) op1215=0xf & op0811=0x0 & COND & rs & op0303=0x0 { build COND; goto [rs]; }-:brds^COND rs is $(INSTR_PHASE) op1215=0xf & op0811=0x1 & COND & rs & op0303=0x0 { build COND; delayslot(1); goto [rs]; }+:brds^COND rs is $(INSTR_PHASE) op1215=0xf & op0811=0x1 & COND & rs & op0303=0x0 { build COND; temp:$(SIZE) = rs; delayslot(1); goto [temp]; }@ifdef POS_STACK:push rs is $(INSTR_PHASE) op1215=0xf & op0811=0x2 & rs & op0003=0x0 { *[ram]:$(SIZE) sp = rs; sp = sp + $(SIZE); logicflags(); resultflags(rs); }:pop rs is $(INSTR_PHASE) op1215=0xf & op0811=0x3 & rs & op0003=0x0 { sp = sp - $(SIZE); rs = *[ram]:$(SIZE) sp; logicflags(); resultflags(rs); }diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/AbstractJitTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/AbstractJitTest.javanew file mode 100644index 0000000000..b52c4e68b8--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/AbstractJitTest.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.pcode.emu.jit;++import static org.junit.Assert.assertEquals;++import java.io.File;+import java.io.IOException;+import java.lang.invoke.MethodHandles;++import org.junit.Before;++import generic.test.AbstractGTest;+import ghidra.GhidraTestApplicationLayout;+import ghidra.app.plugin.assembler.AssemblyBuffer;+import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.framework.Application;+import ghidra.framework.ApplicationConfiguration;+import ghidra.lifecycle.Unfinished;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.JitPassage.ExitPcodeOp;+import ghidra.pcode.emu.jit.analysis.JitAnalysisContext;+import ghidra.pcode.emu.jit.decode.JitPassageDecoderTestAccess;+import ghidra.pcode.exec.PcodeProgram;+import ghidra.pcode.exec.PcodeUseropLibrary;+import ghidra.program.model.listing.Instruction;+import ghidra.program.model.pcode.PcodeOp;++public class AbstractJitTest extends AbstractGTest {++ public static PcodeOp assertOp(int opcode, PcodeOp op) {+ assertEquals(opcode, op.getOpcode());+ return op;+ }++ @Before+ public void setUp() throws IOException {+ if (!Application.isInitialized()) {+ Application.initializeApplication(+ new GhidraTestApplicationLayout(new File(getTestDirectoryPath())),+ new ApplicationConfiguration());+ }+ }++ /**+ * Generate a p-code program from the given instruction sequence+ *+ * <p>+ * The instructions are considered in list order, regardless of their addresses. The caller must+ * ensure the order is consistent. An empty instruction list is not allowed, and all+ * instructions must be from the same Sleigh language.+ *+ * <p>+ * If there are gaps with fall-through a special {@link ExitPcodeOp} is inserted that, if+ * executed blindly, would result in an infinite loop. The intent here is to cue the executor to+ * abandon this program and re-visit the decoder for further ops.+ *+ * <p>+ * An entry address must be given, because the lowest address instruction is not necessarily the+ * entry point, but must appear first in the list. If the given entry is not the lowest address,+ * this will insert a {@link PcodeOp#BRANCH} op at the start to ensure control is immediately+ * given to the specified entry.+ *+ * @param instructions the instructions+ * @param entry the address of the first instruction to execute+ * @return the p-code program+ */+ public static JitPassage makePassageFromInstructions(Iterable<Instruction> instructions,+ AddrCtx entry) {+ return Unfinished.TODO("Don't use this");+ }++ public static JitPassage makePassageFromPcode(PcodeProgram program, JitPcodeThread thread) {+ if (program instanceof JitPassage passage) {+ return passage;+ }+ return JitPassageDecoderTestAccess.simulateFromPcode(program, thread);+ }++ public static JitAnalysisContext makeContext(SleighLanguage language, String sleigh,+ PcodeUseropLibrary<?> library) {+ @SuppressWarnings("unchecked")+ final PcodeUseropLibrary<byte[]> myLib = (PcodeUseropLibrary<byte[]>) library;+ JitPcodeEmulator emu = new JitPcodeEmulator(language, new JitConfiguration(),+ MethodHandles.publicLookup()) {+ @Override+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {+ return super.createUseropLibrary().compose(myLib);+ }+ };+ JitPcodeThread thread = emu.newThread();+ PcodeProgram program = emu.compileSleigh("test", sleigh);+ return makeContext(program, thread);+ }++ public static JitAnalysisContext makeContext(PcodeProgram program) {+ JitPcodeEmulator emu = new JitPcodeEmulator(program.getLanguage(), new JitConfiguration(),+ MethodHandles.publicLookup());+ JitPcodeThread thread = emu.newThread();+ return makeContext(program, thread);+ }++ public static JitAnalysisContext makeContext(PcodeProgram program, JitPcodeThread thread) {+ return new JitAnalysisContext(thread.getMachine().getConfiguration(),+ makePassageFromPcode(program, thread));+ }++ public JitPassage decodePassage(JitPcodeThread thread) {+ int maxOps = thread.getMachine().getConfiguration().maxPassageOps();+ return thread.passageDecoder.decodePassage(thread.getCounter(), thread.getContext(),+ maxOps);+ }++ public JitPassage decodePassage(AssemblyBuffer asm) {+ JitPcodeEmulator emu = new JitPcodeEmulator(asm.getAssembler().getLanguage(),+ new JitConfiguration(), MethodHandles.lookup());+ byte[] bytes = asm.getBytes();+ emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);+ JitPcodeThread thread = emu.newThread();+ thread.overrideCounter(asm.getEntry());+ return decodePassage(thread);+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitAllocationModelTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitAllocationModelTest.javanew file mode 100644index 0000000000..1ef4ad4288--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitAllocationModelTest.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.pcode.emu.jit.analysis;++import static org.junit.Assert.assertEquals;++import java.util.Comparator;+import java.util.List;+import java.util.stream.Stream;++import org.junit.Test;++import generic.Unique;+import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.app.plugin.processors.sleigh.SleighLanguageHelper;+import ghidra.pcode.emu.jit.AbstractJitTest;+import ghidra.pcode.emu.jit.analysis.JitAllocationModel.MultiLocalVarHandler;+import ghidra.pcode.emu.jit.analysis.JitType.DoubleJitType;+import ghidra.pcode.emu.jit.var.JitVar;+import ghidra.pcode.emu.jit.var.JitVarnodeVar;+import ghidra.pcode.exec.*;+import junit.framework.AssertionFailedError;++public class JitAllocationModelTest extends AbstractJitTest {+ public static <T> Stream<T> filterByType(Stream<?> in, Class<T> cls) {+ return in.<T> mapMulti((e, d) -> {+ if (cls.isInstance(e)) {+ d.accept(cls.cast(e));+ }+ });+ }++ public static Stream<JitVarnodeVar> varnodeVars(JitDataFlowModel dfm) {+ return filterByType(dfm.allValues().stream(), JitVarnodeVar.class);+ }++ @Test+ public void testMultiPrecisionInt() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ temp:32 = zext(0x1234:2);+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm);+ JitTypeModel tm = new JitTypeModel(dfm);+ JitAllocationModel am = new JitAllocationModel(context, dfm, vsm, tm);++ JitVarnodeVar tempVar = Unique.assertOne(varnodeVars(dfm)+ .filter(v -> v.varnode().isUnique()));++ if (!(am.getHandler(tempVar) instanceof MultiLocalVarHandler handler)) {+ throw new AssertionFailedError();+ }++ /**+ * TODO: Might like to assert more details, but this mp-int aspect of the JIT-based emulator+ * is still a work in progress.+ */+ assertEquals(8, handler.parts().size());+ }++ @Test+ public void testVarnodeReuse() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r0 = r1 + r2;+ r0 = r0 f+ r2;+ r0 = r0 f+ r2;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm);+ JitTypeModel tm = new JitTypeModel(dfm);+ JitAllocationModel am = new JitAllocationModel(context, dfm, vsm, tm);++ List<JitVarnodeVar> r0Vars = varnodeVars(dfm)+ .filter(v -> v.varnode().toString(language).equals("r0"))+ .sorted(Comparator.comparing(JitVar::id))+ .toList();++ /**+ * NOTE: Variables are coalesced by varnode, so all of these will receive the same handler,+ * and so will all have the same type. There being two float ops will cause the type and+ * allocation models to choose F8 for that handler.+ */+ assertEquals(List.of(DoubleJitType.F8, DoubleJitType.F8, DoubleJitType.F8),+ r0Vars.stream().map(v -> am.getHandler(v).type()).toList());+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitControlFlowModelTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitControlFlowModelTest.javanew file mode 100644index 0000000000..4031e26236--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitControlFlowModelTest.java@@ -0,0 +1,482 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import static org.junit.Assert.*;++import java.util.*;+import java.util.stream.Collectors;++import org.junit.Test;++import ghidra.app.plugin.assembler.*;+import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.app.plugin.processors.sleigh.SleighLanguageHelper;+import ghidra.pcode.emu.jit.AbstractJitTest;+import ghidra.pcode.emu.jit.JitPassage;+import ghidra.pcode.emu.jit.JitPassage.*;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.*;+import ghidra.pcode.exec.*;+import ghidra.program.model.address.Address;+import ghidra.program.model.lang.LanguageID;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;+import ghidra.program.util.DefaultLanguageService;+import junit.framework.AssertionFailedError;++public class JitControlFlowModelTest extends AbstractJitTest {++ public static PcodeOp assertCopyConst(long imm, PcodeOp op) {+ assertOp(PcodeOp.COPY, op);+ Varnode input = op.getInput(0);+ assertTrue(input.isConstant());+ assertEquals(imm, input.getOffset());+ return op;+ }++ record ExpectedBlock(List<PcodeOp> ops) {+ public static ExpectedBlock sub(PcodeProgram program, PcodeOp start, PcodeOp endIncl) {+ int startIdx = program.getCode().indexOf(start);+ int endIdxIncl = program.getCode().indexOf(endIncl);+ return new ExpectedBlock(+ List.copyOf(program.getCode().subList(startIdx, endIdxIncl + 1)));+ }+ }++ enum BrType {+ INT, ERR, EXT, IND+ }++ enum BrFlow {+ BR, FT+ }++ record ExpectedBranch(PcodeOp from, PcodeOp to, BrType type, BrFlow flow, long addr) {}++ record From(PcodeOp op, BrFlow flow) {+ From {+ assertNotNull(op);+ }+ }++ public static class ExpectationsAsserter {+ private final List<ExpectedBlock> eBlocks;+ private final Set<ExpectedBranch> eBranches;+ private final JitControlFlowModel cfm;++ private final Map<PcodeOp, PcodeOp> opMap = new HashMap<>(); // because of rewrites+ private final Map<PcodeOp, JitBlock> aOpToBlock = new HashMap<>();++ private final Map<JitBlock, Set<ExpectedBranch>> eBranchesFrom = new HashMap<>();+ private final Map<JitBlock, Set<ExpectedBranch>> eBranchesTo = new HashMap<>();+ private final Map<JitBlock, Set<ExpectedBranch>> eBranchesOut = new HashMap<>();++ public ExpectationsAsserter(List<ExpectedBlock> eBlocks, Set<ExpectedBranch> eBranches,+ JitControlFlowModel cfm) {+ this.eBlocks = eBlocks;+ this.eBranches = eBranches;+ this.cfm = cfm;+ }++ public void assertOpEquivalence(PcodeOp eOp, PcodeOp aOp) {+ assertEquals("expected: %s but was: %s".formatted(+ PcodeOp.getMnemonic(eOp.getOpcode()),+ PcodeOp.getMnemonic(aOp.getOpcode())),+ eOp.getOpcode(), aOp.getOpcode());+ assertEquals(eOp.getOutput(), aOp.getOutput());+ assertEquals(eOp.getNumInputs(), aOp.getNumInputs());+ for (int i = 0; i < eOp.getNumInputs(); i++) {+ assertEquals(eOp.getInput(i), aOp.getInput(i));+ }+ opMap.put(eOp, aOp);+ }++ public void assertBlockEquivalence(ExpectedBlock eBlock, JitBlock aBlock) {+ assertEquals(eBlock.ops.size(), aBlock.getCode().size());+ for (int i = 0; i < eBlock.ops.size(); i++) {+ PcodeOp aOp = aBlock.getCode().get(i);+ assertOpEquivalence(eBlock.ops.get(i), aOp);+ aOpToBlock.put(aOp, aBlock);+ }+ }++ public void checkAndSortBranches() {+ for (ExpectedBranch eBranch : eBranches) {+ PcodeOp aFromOp = opMap.get(eBranch.from);+ JitBlock aFromBlock = aOpToBlock.get(aFromOp);+ assertEquals(aFromOp, aFromBlock.getCode().getLast());+ if (eBranch.to != null) {+ PcodeOp aToOp = opMap.get(eBranch.to);+ JitBlock aToBlock = aOpToBlock.get(aToOp);+ assertEquals(aToOp, aToBlock.getCode().getFirst());+ eBranchesFrom.computeIfAbsent(aFromBlock, fb -> new HashSet<>()).add(eBranch);+ eBranchesTo.computeIfAbsent(aToBlock, tb -> new HashSet<>()).add(eBranch);+ }+ else {+ eBranchesOut.computeIfAbsent(aFromBlock, fb -> new HashSet<>()).add(eBranch);+ }+ }+ }++ public void assertBranchEquivalence(ExpectedBranch eBranch, Branch aBranch) {+ assertEquals(opMap.get(eBranch.from), aBranch.from());+ assertEquals("expected: %s but was %s".formatted(eBranch, aBranch),+ eBranch.flow == BrFlow.FT, aBranch.isFall());+ switch (eBranch.type) {+ case INT -> {+ if (!(aBranch instanceof IntBranch ib)) {+ throw new AssertionFailedError();+ }+ assertEquals(opMap.get(eBranch.to), ib.to());+ }+ case ERR -> {+ if (!(aBranch instanceof ErrBranch)) {+ throw new AssertionFailedError();+ }+ }+ case EXT -> {+ if (!(aBranch instanceof ExtBranch ext)) {+ throw new AssertionFailedError();+ }+ assertEquals(eBranch.addr, ext.to().address.getOffset());+ }+ case IND -> {+ if (!(aBranch instanceof IndBranch)) {+ throw new AssertionFailedError();+ }+ }+ default -> throw new AssertionFailedError();+ }+ }++ public void assertBranchesEquivalent(Set<ExpectedBranch> eBranches,+ Set<? extends Branch> aBranches) {+ assertEquals("expected:" + eBranches + " but was " + aBranches, eBranches.size(),+ aBranches.size());+ Map<From, ? extends Branch> aBranchMap = aBranches.stream()+ .collect(Collectors.toMap(+ b -> new From(b.from(), b.isFall() ? BrFlow.FT : BrFlow.BR), b -> b));+ for (ExpectedBranch eBranch : eBranches) {+ Branch aBranch = aBranchMap.get(new From(opMap.get(eBranch.from), eBranch.flow));+ assertNotNull("Did not see expected branch " + eBranch + " in " + aBranches,+ aBranch);+ assertBranchEquivalence(eBranch, aBranch);+ }+ }++ public void assertBlockBranchEquivalence(ExpectedBlock eBlock, JitBlock aBlock) {+ assertBranchesEquivalent(eBranchesFrom.getOrDefault(aBlock, Set.of()),+ Set.copyOf(aBlock.branchesFrom()));+ assertBranchesEquivalent(eBranchesTo.getOrDefault(aBlock, Set.of()),+ Set.copyOf(aBlock.branchesTo()));+ assertBranchesEquivalent(eBranchesOut.getOrDefault(aBlock, Set.of()),+ Set.copyOf(aBlock.branchesOut()));+ }++ public void assertFlowEquivalence(ExpectedBranch eBranch, BlockFlow aFlow) {+ assertBranchEquivalence(eBranch, aFlow.branch());+ assertEquals(aOpToBlock.get(aFlow.branch().to()), aFlow.to());+ }++ public void assertFlowsEquivalent(Set<ExpectedBranch> eBranches, Set<BlockFlow> aFlows) {+ assertEquals(eBranches.size(), aFlows.size());+ Map<From, BlockFlow> aFlowMap = aFlows.stream()+ .collect(Collectors.toMap(b -> new From(b.branch().from(),+ b.branch().isFall() ? BrFlow.FT : BrFlow.BR), b -> b));+ for (ExpectedBranch eBranch : eBranches) {+ BlockFlow aFlow = aFlowMap.get(new From(opMap.get(eBranch.from), eBranch.flow));+ assertNotNull("Did not see expected flow " + eBranch + " in " + aFlows, aFlow);+ assertFlowEquivalence(eBranch, aFlow);+ }+ }++ public void assertBlockFlowEquivalence(ExpectedBlock eBlock, JitBlock aBlock) {+ assertFlowsEquivalent(eBranchesFrom.getOrDefault(aBlock, Set.of()),+ Set.copyOf(aBlock.flowsFrom().values()));+ assertFlowsEquivalent(eBranchesTo.getOrDefault(aBlock, Set.of()),+ Set.copyOf(aBlock.flowsTo().values()));+ }++ public void assertEquivalence() {+ List<JitBlock> aBlocks = List.copyOf(cfm.getBlocks());+ assertEquals(eBlocks.size(), aBlocks.size());+ for (int i = 0; i < eBlocks.size(); i++) {+ assertBlockEquivalence(eBlocks.get(i), aBlocks.get(i));+ }++ checkAndSortBranches();++ for (int i = 0; i < eBlocks.size(); i++) {+ assertBlockBranchEquivalence(eBlocks.get(i), aBlocks.get(i));+ assertBlockFlowEquivalence(eBlocks.get(i), aBlocks.get(i));+ }+ }+ }++ public static void assertCfmExpectations(List<ExpectedBlock> eBlocks,+ Set<ExpectedBranch> eBranches, JitControlFlowModel cfm) {+ new ExpectationsAsserter(eBlocks, eBranches, cfm).assertEquivalence();+ }++ @Test(expected = UnterminatedFlowException.class)+ public void testSingleBlockNoBranching() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r0 = r1;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ new JitControlFlowModel(context);+ }++ @Test+ public void testSingleBlockTerminatingBranch() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ PcodeOp opBranch = assertOp(PcodeOp.BRANCH, program.getCode().get(0));++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ new ExpectedBlock(List.of(opBranch))),+ Set.of(+ new ExpectedBranch(opBranch, null, BrType.EXT, BrFlow.BR, 0x1234)),+ cfm);+ }++ @Test+ public void testSingleBlockTerminatingConditionalBranch() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ if (r0) goto 0x5678;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ PcodeOp opCBranch = assertOp(PcodeOp.CBRANCH, program.getCode().get(0));+ PcodeOp opBranch = assertOp(PcodeOp.BRANCH, program.getCode().get(1));++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ new ExpectedBlock(List.of(opCBranch)),+ new ExpectedBlock(List.of(opBranch))),+ Set.of(+ new ExpectedBranch(opCBranch, null, BrType.EXT, BrFlow.BR, 0x5678),+ new ExpectedBranch(opCBranch, opBranch, BrType.INT, BrFlow.FT, 0),+ new ExpectedBranch(opBranch, null, BrType.EXT, BrFlow.BR, 0x1234)),+ cfm);+ }++ @Test+ public void testSingleBlockLoop() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ <L1>+ goto <L1>;+ """, PcodeUseropLibrary.NIL);+ PcodeOp opBranch = assertOp(PcodeOp.BRANCH, program.getCode().get(0));++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ new ExpectedBlock(List.of(opBranch))),+ Set.of(+ new ExpectedBranch(opBranch, opBranch, BrType.INT, BrFlow.BR, 0)),+ cfm);+ }++ @Test+ public void testSingleBlockConditionalLoop() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ <L1>+ if (r0) goto <L1>;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ PcodeOp opCBranch = assertOp(PcodeOp.CBRANCH, program.getCode().get(0));+ PcodeOp opBranch = assertOp(PcodeOp.BRANCH, program.getCode().get(1));++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ new ExpectedBlock(List.of(opCBranch)),+ new ExpectedBlock(List.of(opBranch))),+ Set.of(+ new ExpectedBranch(opCBranch, opCBranch, BrType.INT, BrFlow.BR, 0),+ new ExpectedBranch(opCBranch, opBranch, BrType.INT, BrFlow.FT, 0),+ new ExpectedBranch(opBranch, null, BrType.EXT, BrFlow.BR, 0x1234)),+ cfm);+ }++ @Test+ public void testDegenerateIf() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ if (r0) goto <L1>;+ <L1>+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ PcodeOp opCBranch = assertOp(PcodeOp.CBRANCH, program.getCode().get(0));+ PcodeOp opBranch = assertOp(PcodeOp.BRANCH, program.getCode().get(1));++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ new ExpectedBlock(List.of(opCBranch)),+ new ExpectedBlock(List.of(opBranch))),+ Set.of(+ new ExpectedBranch(opCBranch, opBranch, BrType.INT, BrFlow.BR, 0),+ new ExpectedBranch(opCBranch, opBranch, BrType.INT, BrFlow.FT, 0),+ new ExpectedBranch(opBranch, null, BrType.EXT, BrFlow.BR, 0x1234)),+ cfm);+ }++ @Test+ public void testIfWithManyOps() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ if (r0 == r1 + 0x12) goto <L1>;+ r1 = 1;+ r2 = 2;+ <L1>+ r3 = 3;+ r4 = 4;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ PcodeOp opFirst = program.getCode().get(0);+ PcodeOp opCBranch = assertOp(PcodeOp.CBRANCH, program.getCode().get(2));+ PcodeOp opAfterCBranch = assertCopyConst(1, program.getCode().get(3));+ PcodeOp opBeforeL1 = assertCopyConst(2, program.getCode().get(4));+ PcodeOp opAtL1 = assertCopyConst(3, program.getCode().get(5));+ PcodeOp opBranch = assertOp(PcodeOp.BRANCH, program.getCode().get(7));++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ ExpectedBlock.sub(program, opFirst, opCBranch),+ ExpectedBlock.sub(program, opAfterCBranch, opBeforeL1),+ ExpectedBlock.sub(program, opAtL1, opBranch)),+ Set.of(+ new ExpectedBranch(opCBranch, opAfterCBranch, BrType.INT, BrFlow.FT, 0),+ new ExpectedBranch(opCBranch, opAtL1, BrType.INT, BrFlow.BR, 0),+ new ExpectedBranch(opBeforeL1, opAtL1, BrType.INT, BrFlow.FT, 0),+ new ExpectedBranch(opBranch, null, BrType.EXT, BrFlow.BR, 0x1234)),+ cfm);+ }++ @Test+ public void testTwoInstructionsNoBranching() throws Exception {+ SleighLanguage language = (SleighLanguage) DefaultLanguageService.getLanguageService()+ .getLanguage(new LanguageID("Toy:BE:64:default"));++ Address addr0 = language.getDefaultSpace().getAddress(0);+ Assembler asm = Assemblers.getAssembler(language);+ AssemblyBuffer buf = new AssemblyBuffer(asm, addr0);+ buf.assemble("imm r0, #0x123");+ buf.assemble("add r0, r0");+ JitPassage passage = decodePassage(buf);+ PcodeOp opLast = assertOp(PcodeOp.UNIMPLEMENTED, passage.getCode().getLast());++ JitAnalysisContext context = makeContext(passage);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ new ExpectedBlock(passage.getCode())),+ Set.of(+ new ExpectedBranch(opLast, null, BrType.ERR, BrFlow.BR, 0x4)),+ cfm);+ }++ @Test+ public void testInstructionsConditionalBranch() throws Exception {+ SleighLanguage language = (SleighLanguage) DefaultLanguageService.getLanguageService()+ .getLanguage(new LanguageID("Toy:BE:64:default"));++ Address addr0 = language.getDefaultSpace().getAddress(0);+ Assembler asm = Assemblers.getAssembler(language);+ AssemblyBuffer buf = new AssemblyBuffer(asm, addr0);+ Address patchAt = buf.getNext();+ buf.assemble("breq 0"); // Uses CBRANCH to skip BRANCH+ buf.assemble("imm r0, #123");+ Address breqTo = buf.getNext();+ buf.assemble("add r0, r0");+ buf.assemble(patchAt, "breq 0x%x".formatted(breqTo.getOffset()));+ JitPassage passage = decodePassage(buf);+ // For sanity, and so I can reason out the results+ assertEquals("""+ <JitPassage:+ 0,00000000.0: $U800:1 = BOOL_NEGATE Z+ 1,00000000.1: CBRANCH *[ram]0x2:8, $U800:1+ 2,00000000.2: BRANCH *[ram]0x4:8+ 3,00000002.0: C = COPY 0:1+ 4,00000002.1: V = COPY 0:1+ 5,00000002.2: r0 = COPY 0x7b:8+ 6,00000002.3: N = INT_SLESS r0, 0:8+ 7,00000002.4: Z = INT_EQUAL r0, 0:8+ 8,00000004.0: C = INT_CARRY r0, r0+ 9,00000004.1: V = INT_SCARRY r0, r0+ 10,00000004.2: r0 = INT_ADD r0, r0+ 11,00000004.3: N = INT_SLESS r0, 0:8+ 12,00000004.4: Z = INT_EQUAL r0, 0:8+ 13,00000006.0: UNIMPLEMENTED+ >""", passage.format(true));+ PcodeOp opFirst = passage.getCode().getFirst();+ PcodeOp opCBranch = assertOp(PcodeOp.CBRANCH, passage.getCode().get(1));+ PcodeOp opBranch = assertOp(PcodeOp.BRANCH, passage.getCode().get(2));+ PcodeOp opStartImm = assertCopyConst(0, passage.getCode().get(3));+ PcodeOp opEndImm = assertOp(PcodeOp.INT_EQUAL, passage.getCode().get(7));+ PcodeOp opStartAdd = assertOp(PcodeOp.INT_CARRY, passage.getCode().get(8));+ PcodeOp opLast = assertOp(PcodeOp.UNIMPLEMENTED, passage.getCode().getLast());++ JitAnalysisContext context = makeContext(passage);+ JitControlFlowModel cfm = new JitControlFlowModel(context);++ assertCfmExpectations(+ List.of(+ ExpectedBlock.sub(passage, opFirst, opCBranch),+ ExpectedBlock.sub(passage, opBranch, opBranch),+ ExpectedBlock.sub(passage, opStartImm, opEndImm),+ ExpectedBlock.sub(passage, opStartAdd, opLast)),+ Set.of(+ new ExpectedBranch(opCBranch, opStartImm, BrType.INT, BrFlow.BR, 0),+ new ExpectedBranch(opCBranch, opBranch, BrType.INT, BrFlow.FT, 0),+ new ExpectedBranch(opBranch, opStartAdd, BrType.INT, BrFlow.BR, 0),+ new ExpectedBranch(opEndImm, opStartAdd, BrType.INT, BrFlow.FT, 0),+ new ExpectedBranch(opLast, null, BrType.ERR, BrFlow.BR, 0)),+ cfm);+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitDataFlowModelTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitDataFlowModelTest.javanew file mode 100644index 0000000000..583fb544af--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitDataFlowModelTest.java@@ -0,0 +1,660 @@+/* ###+ * 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.pcode.emu.jit.analysis;++import static org.junit.Assert.*;++import java.util.*;+import java.util.Map.Entry;+import java.util.function.Function;+import java.util.function.Predicate;+import java.util.stream.Collectors;++import org.apache.commons.collections4.BidiMap;+import org.apache.commons.collections4.bidimap.DualHashBidiMap;+import org.junit.Test;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.app.plugin.processors.sleigh.SleighLanguageHelper;+import ghidra.pcode.emu.jit.AbstractJitTest;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.*;+import ghidra.pcode.emu.jit.var.JitVal.ValUse;+import ghidra.pcode.exec.*;+import ghidra.program.model.pcode.PcodeOp;+import junit.framework.AssertionFailedError;++public class JitDataFlowModelTest extends AbstractJitTest {++ private Predicate<JitOp> opType(Class<? extends JitOp> cls) {+ return cls::isInstance;+ }++ private Function<JitCallOtherOpIf, JitVal> otherArg(int i) {+ return op -> op.args().get(i);+ }++ record ExpectedOp<T extends JitOp>(int e, Class<T> cls) {+ private static int nextE = 0;++ public ExpectedOp(Class<T> cls) {+ this(nextE++, cls);+ }+ }++ record ExpectedVal<T extends JitVal>(int e, Class<T> cls, String str, int size) {++ private static int nextE = 0;++ public ExpectedVal(Class<T> cls, String str, int size) {+ this(nextE++, cls, str, size);+ }+ }++ enum Dir {+ IN, OUT+ }++ record ExpectedEdge<OT extends JitOp, VT extends JitVal>(Dir dir, ExpectedOp<OT> op,+ Function<? super OT, JitVal> valGetter, Function<VT, JitOp> opGetter,+ ExpectedVal<VT> v) {++ public static <OT extends JitOp, VT extends JitVal> ExpectedEdge<OT, VT> in(+ ExpectedOp<OT> op, Function<? super OT, JitVal> valGetter,+ Predicate<JitOp> opPredicate, ExpectedVal<VT> v) {++ return new ExpectedEdge<>(Dir.IN, op, valGetter, val -> {+ for (ValUse use : val.uses()) {+ if (opPredicate.test(use.op())) {+ return use.op();+ }+ }+ throw new NoSuchElementException();+ }, v);+ }++ public static <VT extends JitOutVar, OT extends JitDefOp> ExpectedEdge<OT, VT> out(+ ExpectedVal<VT> v, ExpectedOp<OT> op) {++ return new ExpectedEdge<>(Dir.OUT, op, JitDefOp::out, JitOutVar::definition, v);+ }++ public static <VT extends JitVal> ExpectedEdge<JitPhiOp, VT> phi(ExpectedOp<JitPhiOp> op,+ Predicate<BlockFlow> flowPredicate, ExpectedVal<VT> v) {++ return in(op, phi -> {+ for (Entry<BlockFlow, JitVal> ent : phi.options().entrySet()) {+ if (flowPredicate.test(ent.getKey())) {+ return ent.getValue();+ }+ }+ throw new NoSuchElementException();+ }, jitOp -> jitOp instanceof JitPhiOp, v);+ }++ public VT getActualVal(JitOp jitOp) {+ try {+ return Objects.requireNonNull(v.cls.cast(valGetter.apply(op.cls.cast(jitOp))));+ }+ catch (Exception e) {+ throw new AssertionError(+ "Could not get actual value for " + this + " where op=" + jitOp, e);+ }+ }++ public OT getActualOp(JitVal jitVal) {+ try {+ return Objects.requireNonNull(op.cls.cast(opGetter.apply(v.cls.cast(jitVal))));+ }+ catch (Exception e) {+ throw new AssertionError(+ "Could not get actual op for " + this + " where value=" + jitVal, e);+ }+ }+ }++ record OpMatch(ExpectedOp<?> eOp, JitOp aOp) {}++ record ValMatch(ExpectedVal<?> eVal, JitVal aVal) {}++ public static class ExpectationsAsserter {+ private final List<ExpectedOp<?>> eOps;+ private final Set<ExpectedVal<?>> eVals;+ private final Set<ExpectedEdge<?, ?>> eEdges;+ private final JitDataFlowModel dfm;++ private final SleighLanguage language;++ private final Deque<OpMatch> opQueue = new LinkedList<>();+ private final Deque<ValMatch> valQueue = new LinkedList<>();+ private final BidiMap<JitOp, ExpectedOp<?>> opsMap = new DualHashBidiMap<>();+ private final BidiMap<JitVal, ExpectedVal<?>> valsMap = new DualHashBidiMap<>();+ private final Set<ExpectedEdge<?, ?>> edgesVisitedO2V = new HashSet<>();+ private final Set<ExpectedEdge<?, ?>> edgesVisitedV2O = new HashSet<>();+ private final Map<ExpectedOp<?>, Set<ExpectedEdge<?, ?>>> edgesO2V = new HashMap<>();+ private final Map<ExpectedVal<?>, Set<ExpectedEdge<?, ?>>> edgesV2O = new HashMap<>();++ public ExpectationsAsserter(List<ExpectedOp<?>> eOps, Set<ExpectedVal<?>> eVals,+ Set<ExpectedEdge<?, ?>> eEdges, JitAnalysisContext context, JitDataFlowModel dfm) {+ this.eOps = eOps;+ this.eEdges = eEdges;+ this.eVals = eVals;+ this.dfm = dfm;++ this.language = context.getLanguage();++ // Queue only those matching the listing+ // synthetic ones should be at end of list, but must be included+ List<PcodeOp> ops = context.getPassage().getCode();+ for (int i = 0; i < ops.size(); i++) {+ JitOp aOp = dfm.getJitOp(ops.get(i));+ ExpectedOp<?> eOp = eOps.get(i);+ opQueue.add(new OpMatch(eOp, aOp));+ }++ for (ExpectedEdge<?, ?> ee : eEdges) {+ edgesO2V.computeIfAbsent(ee.op, e -> new HashSet<>()).add(ee);+ edgesV2O.computeIfAbsent(ee.v, e -> new HashSet<>()).add(ee);+ }+ }++ public void assertOpMatch(OpMatch match) {+ ExpectedOp<?> ePrior = opsMap.get(match.aOp);+ JitOp aPrior = opsMap.getKey(match.eOp);+ if (ePrior != null || aPrior != null) {+ assertSame(ePrior, match.eOp);+ assertSame(aPrior, match.aOp);+ return;+ }++ assertTrue("Expected op of type %s but got %s".formatted(match.eOp.cls, match.aOp),+ match.eOp.cls.isInstance(match.aOp));+ opsMap.put(match.aOp, match.eOp);++ Set<JitVal> aAllIn = Set.copyOf(match.aOp.inputs());+ Set<JitVal> aAllOut =+ match.aOp instanceof JitDefOp defOp ? Set.of(defOp.out()) : Set.of();+ Set<JitVal> eAllIn = new HashSet<>();+ Set<JitVal> eAllOut = new HashSet<>();+ for (ExpectedEdge<?, ?> ee : edgesO2V.getOrDefault(match.eOp, Set.of())) {+ edgesVisitedO2V.add(ee);+ JitVal aVal = ee.getActualVal(match.aOp);+ valQueue.add(new ValMatch(ee.v, aVal));+ (switch (ee.dir) {+ case IN -> eAllIn;+ case OUT -> eAllOut;+ }).add(aVal);+ }+ assertEquals("Values input to %s do not match".formatted(match.aOp), eAllIn, aAllIn);+ assertEquals("Value output from %s does not match".formatted(match.aOp),+ eAllOut, aAllOut);+ }++ private String varnodeToString(JitVarnodeVar vv) {+ if (vv.varnode().isUnique()) {+ return "$U";+ }+ return vv.varnode().toString(language);+ }++ public void assertValMatch(ValMatch match) {+ ExpectedVal<?> ePrior = valsMap.get(match.aVal);+ JitVal aPrior = valsMap.getKey(match.eVal);+ if (ePrior != null || aPrior != null) {+ assertSame(ePrior, match.eVal);+ assertSame(aPrior, match.aVal);+ return;+ }++ assertTrue(match.eVal.cls.isInstance(match.aVal));+ valsMap.put(match.aVal, match.eVal);++ assertEquals(match.eVal.size, match.aVal.size());+ switch (match.aVal) {+ case JitConstVal cv -> assertEquals(match.eVal.str, cv.value().toString(16));+ case JitVarnodeVar vv -> assertEquals(match.eVal.str, varnodeToString(vv));+ default -> throw new AssertionFailedError("Unrecognized val type: " + match.aVal);+ }++ Set<JitOp> aAllUses =+ match.aVal.uses().stream().map(ValUse::op).collect(Collectors.toSet());+ Set<JitOp> aAllDefs =+ match.aVal instanceof JitOutVar out ? Set.of(out.definition()) : Set.of();+ Set<JitOp> eAllUses = new HashSet<>();+ Set<JitOp> eAllDefs = new HashSet<>();+ for (ExpectedEdge<?, ?> ee : edgesV2O.getOrDefault(match.eVal, Set.of())) {+ edgesVisitedV2O.add(ee);+ JitOp aOp = ee.getActualOp(match.aVal);+ opQueue.add(new OpMatch(ee.op, aOp));+ (switch (ee.dir) {+ case IN -> eAllUses;+ case OUT -> eAllDefs;+ }).add(aOp);+ }+ assertEquals("Ops using %s do not match".formatted(match.aVal), eAllUses, aAllUses);+ assertEquals("Op defining %s does not match".formatted(match.aVal), eAllDefs, aAllDefs);+ }++ public void processQueues() {+ while (!opQueue.isEmpty() || !valQueue.isEmpty()) {+ while (!opQueue.isEmpty()) {+ assertOpMatch(opQueue.poll());+ }+ while (!valQueue.isEmpty()) {+ assertValMatch(valQueue.poll());+ }+ }+ }++ public void assertEquivalence() {+ processQueues();++ assertEquals(opsMap.keySet(), dfm.allOps());+ assertEquals(valsMap.keySet(), dfm.allValues());++ assertEquals("Not all expected ops were found.", Set.copyOf(eOps),+ Set.copyOf(opsMap.values()));+ assertEquals("Not all expected values were found.", eVals,+ Set.copyOf(valsMap.values()));++ assertEquals(eEdges, edgesVisitedO2V);+ assertEquals(eEdges, edgesVisitedV2O);+ }+ }++ public static void assertDfmExpectations(List<ExpectedOp<?>> eOps, Set<ExpectedVal<?>> eVals,+ Set<ExpectedEdge<?, ?>> eEdges, JitAnalysisContext context, JitDataFlowModel dfm) {+ new ExpectationsAsserter(eOps, eVals, eEdges, context, dfm).assertEquivalence();+ }++ @Test+ public void testOnlyConstant() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r0 = 0x5678;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);++ ExpectedOp<JitCopyOp> eCopy = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedVal<JitConstVal> e5678 = new ExpectedVal<>(JitConstVal.class, "5678", 8);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ assertDfmExpectations(+ List.of(+ eCopy,+ eBranch),+ Set.of(e5678, eR0),+ Set.of(+ ExpectedEdge.in(eCopy, JitCopyOp::u, op -> true, e5678),+ ExpectedEdge.out(eR0, eCopy)),+ context, dfm);+ }++ @Test+ public void testInput() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r0 = r1;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);++ ExpectedOp<JitCopyOp> eCopy = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ ExpectedVal<JitOutVar> eR1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);+ ExpectedVal<JitInputVar> eR1In = new ExpectedVal<>(JitInputVar.class, "r1", 8);+ assertDfmExpectations(+ List.of(+ eCopy,+ eBranch,+ ePhi),+ Set.of(eR1In, eR1, eR0),+ Set.of(+ ExpectedEdge.phi(ePhi, flow -> true, eR1In),+ ExpectedEdge.out(eR1, ePhi),+ ExpectedEdge.in(eCopy, JitCopyOp::u, op -> true, eR1),+ ExpectedEdge.out(eR0, eCopy)),+ context, dfm);+ }++ @Test+ public void testThroughReg() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r1 = 0x5678;+ r0 = r1;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);++ // Just checking that the r1 used is the same as the r1 defined above+ ExpectedOp<JitCopyOp> eCopy1 = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitCopyOp> eCopy2 = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedVal<JitConstVal> e5678 = new ExpectedVal<>(JitConstVal.class, "5678", 8);+ ExpectedVal<JitOutVar> eR1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ assertDfmExpectations(+ List.of(eCopy1,+ eCopy2,+ eBranch),+ Set.of(e5678, eR1, eR0),+ Set.of(+ ExpectedEdge.in(eCopy1, JitCopyOp::u, op -> true, e5678),+ ExpectedEdge.out(eR1, eCopy1),+ ExpectedEdge.in(eCopy2, JitCopyOp::u, op -> true, eR1),+ ExpectedEdge.out(eR0, eCopy2)),+ context, dfm);+ }++ @Test+ public void testThroughUnique() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ temp:8 = 0x5678;+ r0 = temp;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);++ ExpectedOp<JitCopyOp> eCopy1 = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitCopyOp> eCopy2 = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedVal<JitConstVal> e5678 = new ExpectedVal<>(JitConstVal.class, "5678", 8);+ ExpectedVal<JitOutVar> eTemp = new ExpectedVal<>(JitOutVar.class, "$U", 8);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ assertDfmExpectations(+ List.of(eCopy1,+ eCopy2,+ eBranch),+ Set.of(e5678, eTemp, eR0),+ Set.of(+ ExpectedEdge.in(eCopy1, JitCopyOp::u, op -> true, e5678),+ ExpectedEdge.out(eTemp, eCopy1),+ ExpectedEdge.in(eCopy2, JitCopyOp::u, op -> true, eTemp),+ ExpectedEdge.out(eR0, eCopy2)),+ context, dfm);+ }++ @Test+ public void testInputLoop() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ <loop>+ r0 = r1;+ goto <loop>;+ """, PcodeUseropLibrary.NIL);+ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);++ ExpectedOp<JitCopyOp> eCopy = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ ExpectedVal<JitOutVar> eR1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);+ ExpectedVal<JitInputVar> eR1In = new ExpectedVal<>(JitInputVar.class, "r1", 8);+ assertDfmExpectations(+ List.of(+ eCopy,+ eBranch,+ ePhi),+ Set.of(eR1In, eR1, eR0),+ Set.of(+ ExpectedEdge.phi(ePhi, flow -> flow.from() == null, eR1In),+ ExpectedEdge.phi(ePhi, flow -> flow.from() != null, eR1),+ ExpectedEdge.out(eR1, ePhi),+ ExpectedEdge.in(eCopy, JitCopyOp::u, opType(JitCopyOp.class), eR1),+ ExpectedEdge.out(eR0, eCopy)),+ context, dfm);+ }++ @Test+ public void testOnlyConstLoop() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r1 = 0x5678;+ <loop>+ r0 = r1;+ goto <loop>;+ """, PcodeUseropLibrary.NIL);+ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);++ ExpectedOp<JitCopyOp> eCopy1 = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitCopyOp> eCopy2 = new ExpectedOp<>(JitCopyOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);+ ExpectedVal<JitConstVal> e5678 = new ExpectedVal<>(JitConstVal.class, "5678", 8);+ ExpectedVal<JitOutVar> eR1_1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);+ ExpectedVal<JitOutVar> eR1_2 = new ExpectedVal<>(JitOutVar.class, "r1", 8);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ assertDfmExpectations(+ List.of(+ eCopy1,+ eCopy2,+ eBranch,+ ePhi),+ Set.of(e5678, eR1_1, eR1_2, eR0),+ Set.of(+ ExpectedEdge.in(eCopy1, JitCopyOp::u, opType(JitCopyOp.class), e5678),+ ExpectedEdge.out(eR1_1, eCopy1),+ ExpectedEdge.phi(ePhi, flow -> flow.from().start().getTime() == 0, eR1_1),+ ExpectedEdge.phi(ePhi, flow -> flow.from().start().getTime() == 1, eR1_2),+ ExpectedEdge.out(eR1_2, ePhi),+ ExpectedEdge.in(eCopy2, JitCopyOp::u, opType(JitCopyOp.class), eR1_2),+ ExpectedEdge.out(eR0, eCopy2)),+ context, dfm);+ }++ @Test+ public void testForLoop() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ // Want to see r0 as input or as previous iteration's value+ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ <loop>+ r0 = r0 - 1;+ if r0 > 0 goto <loop>;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);+ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);++ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);+ ExpectedOp<JitIntSubOp> eIntSub = new ExpectedOp<>(JitIntSubOp.class);+ ExpectedOp<JitIntLessOp> eIntLess = new ExpectedOp<>(JitIntLessOp.class);+ ExpectedOp<JitCBranchOp> eCBranch = new ExpectedOp<>(JitCBranchOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedVal<JitConstVal> e1 = new ExpectedVal<>(JitConstVal.class, "1", 8);+ ExpectedVal<JitOutVar> eR0_1 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ ExpectedVal<JitInputVar> eR0In = new ExpectedVal<>(JitInputVar.class, "r0", 8);+ ExpectedVal<JitOutVar> eU = new ExpectedVal<>(JitOutVar.class, "$U", 1);+ ExpectedVal<JitOutVar> eR0_2 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ ExpectedVal<JitConstVal> e0 = new ExpectedVal<>(JitConstVal.class, "0", 8);+ assertDfmExpectations(+ List.of(+ eIntSub,+ eIntLess,+ eCBranch,+ eBranch,+ ePhi),+ Set.of(e1, eR0_1, eR0In, eU, eR0_2, e0),+ Set.of(+ ExpectedEdge.phi(ePhi, flow -> flow.from() == null, eR0In),+ ExpectedEdge.phi(ePhi, flow -> flow.from() != null, eR0_2),+ ExpectedEdge.out(eR0_1, ePhi),+ ExpectedEdge.in(eIntSub, JitIntSubOp::l, opType(JitIntSubOp.class), eR0_1),+ ExpectedEdge.in(eIntSub, JitIntSubOp::r, opType(JitIntSubOp.class), e1),+ ExpectedEdge.out(eR0_2, eIntSub),+ ExpectedEdge.in(eIntLess, JitIntLessOp::l, opType(JitIntLessOp.class), e0),+ ExpectedEdge.in(eIntLess, JitIntLessOp::r, opType(JitIntLessOp.class), eR0_2),+ ExpectedEdge.out(eU, eIntLess),+ ExpectedEdge.in(eCBranch, JitCBranchOp::cond, opType(JitCBranchOp.class), eU)),+ context, dfm);+ }++ public static class MyLibrary extends AnnotatedPcodeUseropLibrary<Object> {+ @PcodeUserop(functional = true)+ public void v_op0() {+ }++ @PcodeUserop(functional = true)+ public void v_op1(long p1) {+ }++ @PcodeUserop(functional = true)+ public long l_op0() {+ return 0;+ }++ @PcodeUserop(functional = true)+ public long l_op1(long p1) {+ return p1;+ }+ }++ public static final PcodeUseropLibrary<?> MY_LIB = new MyLibrary();++ @Test+ public void testCallOtherVoidOp0() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ JitAnalysisContext context = makeContext(language, """+ v_op0();+ goto 0x1234;+ """, MY_LIB);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ ExpectedOp<JitCallOtherOp> eCallOther = new ExpectedOp<>(JitCallOtherOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ assertDfmExpectations(+ List.of(+ eCallOther,+ eBranch),+ Set.of(),+ Set.of(),+ context, dfm);+ }++ @Test+ public void testCallOtherVoidOp1() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ JitAnalysisContext context = makeContext(language, """+ v_op1(r0);+ goto 0x1234;+ """, MY_LIB);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ ExpectedOp<JitCallOtherOp> eCallOther = new ExpectedOp<>(JitCallOtherOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);+ ExpectedVal<JitInputVar> eR0In = new ExpectedVal<>(JitInputVar.class, "r0", 8);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ assertDfmExpectations(+ List.of(+ eCallOther,+ eBranch,+ ePhi),+ Set.of(eR0In, eR0),+ Set.of(+ ExpectedEdge.phi(ePhi, flow -> true, eR0In),+ ExpectedEdge.out(eR0, ePhi),+ ExpectedEdge.in(eCallOther, otherArg(0), opType(JitCallOtherOp.class), eR0)),+ context, dfm);+ }++ @Test+ public void testCallOtherLongOp0() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ JitAnalysisContext context = makeContext(language, """+ r1 = l_op0();+ goto 0x1234;+ """, MY_LIB);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ ExpectedOp<JitCallOtherDefOp> eCallOther = new ExpectedOp<>(JitCallOtherDefOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedVal<JitOutVar> eR1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);+ assertDfmExpectations(+ List.of(+ eCallOther,+ eBranch),+ Set.of(eR1),+ Set.of(+ ExpectedEdge.out(eR1, eCallOther)),+ context, dfm);+ }++ @Test+ public void testCallOtherLongOp1() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ JitAnalysisContext context = makeContext(language, """+ r1 = l_op1(r0);+ goto 0x1234;+ """, MY_LIB);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ ExpectedOp<JitCallOtherDefOp> eCallOther = new ExpectedOp<>(JitCallOtherDefOp.class);+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);+ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);+ ExpectedVal<JitInputVar> eR0In = new ExpectedVal<>(JitInputVar.class, "r0", 8);+ ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);+ ExpectedVal<JitOutVar> eR1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);+ assertDfmExpectations(+ List.of(+ eCallOther,+ eBranch,+ ePhi),+ Set.of(eR0In, eR0, eR1),+ Set.of(+ ExpectedEdge.phi(ePhi, flow -> true, eR0In),+ ExpectedEdge.out(eR0, ePhi),+ ExpectedEdge.in(eCallOther, otherArg(0), opType(JitCallOtherDefOp.class), eR0),+ ExpectedEdge.out(eR1, eCallOther)),+ context, dfm);+ }++ /**+ * NOTE: cat, subpiece, etc., do not currrently have much meaning except to indicate a+ * dependence. At one point these "synthetic" ops were meant to be translated into JVM bytecode,+ * but instead, variable accesses are coalesced during allocation/assignment, and then+ * sub-accesses are encoded as such.+ */+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitOpUseModelTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitOpUseModelTest.javanew file mode 100644index 0000000000..06d66a9167--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitOpUseModelTest.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.pcode.emu.jit.analysis;++import static org.junit.Assert.assertFalse;+import static org.junit.Assert.assertTrue;++import org.junit.Test;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.app.plugin.processors.sleigh.SleighLanguageHelper;+import ghidra.pcode.emu.jit.AbstractJitTest;+import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary;+import ghidra.pcode.exec.PcodeExecutorState;+import ghidra.program.model.pcode.PcodeOp;+import ghidra.program.model.pcode.Varnode;++public class JitOpUseModelTest extends AbstractJitTest {++ public static class MyLib extends AnnotatedPcodeUseropLibrary<byte[]> {+ @PcodeUserop+ public void pcodeop_one(@OpState PcodeExecutorState<byte[]> state, @OpOutput Varnode out,+ Varnode in1) {+ }+ }++ MyLib lib = new MyLib();++ @Test+ public void testImmediateOverwrite() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ JitAnalysisContext context = makeContext(language, """+ r0 = r1;+ r0 = r2;+ goto 0x1234;+ """, lib);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm);+ JitOpUseModel oum = new JitOpUseModel(context, cfm, dfm, vsm);++ PcodeOp copyOp = assertOp(PcodeOp.COPY, context.getPassage().getCode().getFirst());+ assertFalse(oum.isUsed(dfm.getJitOp(copyOp)));+ }++ /**+ * Because the userop could technically access any varnode, then any live varnode at the time of+ * the userop call must be considered used.+ *+ * @throws Exception because+ */+ @Test+ public void testInterveningCallOther() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ JitAnalysisContext context = makeContext(language, """+ r0 = r1;+ r0 = pcodeop_one(r1);+ goto 0x1234;+ """, lib);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm);+ JitOpUseModel oum = new JitOpUseModel(context, cfm, dfm, vsm);++ PcodeOp copyOp = assertOp(PcodeOp.COPY, context.getPassage().getCode().getFirst());+ assertTrue(oum.isUsed(dfm.getJitOp(copyOp)));+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitTypeModelTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitTypeModelTest.javanew file mode 100644index 0000000000..40b0d7ddbf--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitTypeModelTest.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.pcode.emu.jit.analysis;++import static org.junit.Assert.assertEquals;++import org.junit.Test;++import generic.Unique;+import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.app.plugin.processors.sleigh.SleighLanguageHelper;+import ghidra.pcode.emu.jit.AbstractJitTest;+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;+import ghidra.pcode.emu.jit.analysis.JitType.DoubleJitType;+import ghidra.pcode.emu.jit.analysis.JitType.LongJitType;+import ghidra.pcode.emu.jit.op.*;+import ghidra.pcode.emu.jit.var.JitConstVal;+import ghidra.pcode.emu.jit.var.JitVal;+import ghidra.pcode.exec.*;+import ghidra.program.model.pcode.PcodeOp;++public class JitTypeModelTest extends AbstractJitTest {+ @Test+ public void testDefault() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r0 = r1;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitTypeModel tm = new JitTypeModel(dfm);++ JitBlock block = Unique.assertOne(cfm.getBlocks());+ JitVal r0 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r0")));+ assertEquals(LongJitType.I8, tm.typeOf(r0));+ }++ @Test+ public void testFloatThroughTerminalCopy() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r1 = r1 f+ r1;+ r0 = r1;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitTypeModel tm = new JitTypeModel(dfm);++ JitBlock block = Unique.assertOne(cfm.getBlocks());+ JitVal r0 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r0")));+ assertEquals(DoubleJitType.F8, tm.typeOf(r0));+ }++ @Test+ public void testFloatConstant() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r0 = r1 f+ 0x5678;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitTypeModel tm = new JitTypeModel(dfm);++ PcodeOp op = assertOp(PcodeOp.FLOAT_ADD, context.getPassage().getCode().getFirst());+ JitFloatAddOp fAddOp = (JitFloatAddOp) dfm.getJitOp(op);+ JitConstVal c1234 = (JitConstVal) fAddOp.r();+ assertEquals(DoubleJitType.F8, tm.typeOf(c1234));+ }++ @Test+ public void testCBranchInput() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ <loop>+ if (r0) goto <loop>;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitTypeModel tm = new JitTypeModel(dfm);++ PcodeOp op = assertOp(PcodeOp.CBRANCH, context.getPassage().getCode().getFirst());+ JitCBranchOp cbranch = (JitCBranchOp) dfm.getJitOp(op);+ JitVal r0 = cbranch.cond();+ assertEquals(LongJitType.I8, tm.typeOf(r0));+ }++ @Test+ public void testBranchIndInput() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ goto [r0];+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitTypeModel tm = new JitTypeModel(dfm);++ PcodeOp op = Unique.assertOne(context.getPassage().getCode());+ JitBranchIndOp branchind = (JitBranchIndOp) dfm.getJitOp(op);+ JitVal r0 = branchind.target();+ assertEquals(LongJitType.I8, tm.typeOf(r0));+ }++ @Test+ public void testLoop() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ <loop>+ r0 = r0 f+ r1;+ goto <loop>;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitTypeModel tm = new JitTypeModel(dfm);++ JitBlock block = Unique.assertOne(cfm.getBlocks());+ JitVal r0 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r0")));+ assertEquals(DoubleJitType.F8, tm.typeOf(r0));+ }++ @Test+ public void testViaSharedUse() throws Exception {+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();++ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """+ r0 = r0 f+ r1;+ r2 = r1;+ goto 0x1234;+ """, PcodeUseropLibrary.NIL);++ JitAnalysisContext context = makeContext(program);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitTypeModel tm = new JitTypeModel(dfm);++ JitBlock block = Unique.assertOne(cfm.getBlocks());+ JitVal r0 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r0")));+ assertEquals(DoubleJitType.F8, tm.typeOf(r0));+ JitVal r2 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r2")));+ assertEquals(DoubleJitType.F8, tm.typeOf(r2));+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/decode/JitPassageDecoderTestAccess.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/decode/JitPassageDecoderTestAccess.javanew file mode 100644index 0000000000..46ff0a72fc--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/decode/JitPassageDecoderTestAccess.java@@ -0,0 +1,39 @@+/* ###+ * 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.pcode.emu.jit.decode;++import ghidra.pcode.emu.jit.JitPassage;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.JitPcodeThread;+import ghidra.pcode.exec.PcodeProgram;++public class JitPassageDecoderTestAccess {++ public static JitPassage simulateFromPcode(PcodeProgram program, JitPcodeThread thread) {+ JitPassageDecoder decoder = new JitPassageDecoder(thread);+ DecoderForOnePassage d4passage = new DecoderForOnePassage(decoder, AddrCtx.NOWHERE, 0);+ d4passage.externalBranches.clear();+ DecoderForOneStride d4stride = new DecoderForOneStride(decoder, d4passage, AddrCtx.NOWHERE);+ DecoderExecutor exec = new DecoderExecutor(d4stride, AddrCtx.NOWHERE);+ d4passage.firstOps.put(AddrCtx.NOWHERE, exec.rewrite(program.getCode().getFirst()));++ exec.execute(program);+ exec.checkFallthroughAndAccumulate(program);+ d4passage.strides.add(d4stride.toStride());++ return d4passage.finish();+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/JitCodeGeneratorTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/JitCodeGeneratorTest.javanew file mode 100644index 0000000000..04f2d3543e--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/JitCodeGeneratorTest.java@@ -0,0 +1,2263 @@+/* ###+ * 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.pcode.emu.jit.gen;++import static ghidra.lifecycle.Unfinished.TODO;+import static org.junit.Assert.*;++import java.io.*;+import java.lang.invoke.MethodHandles;+import java.math.BigInteger;+import java.nio.file.Files;+import java.util.*;+import java.util.Map.Entry;+import java.util.stream.Collectors;+import java.util.stream.Stream;++import org.junit.Ignore;+import org.junit.Test;+import org.objectweb.asm.ClassReader;+import org.objectweb.asm.Opcodes;+import org.objectweb.asm.tree.*;+import org.objectweb.asm.util.TraceClassVisitor;++import generic.Unique;+import ghidra.app.plugin.assembler.*;+import ghidra.app.plugin.assembler.sleigh.sem.AssemblyPatternBlock;+import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.pcode.emu.PcodeEmulator;+import ghidra.pcode.emu.PcodeThread;+import ghidra.pcode.emu.jit.*;+import ghidra.pcode.emu.jit.JitPassage.AddrCtx;+import ghidra.pcode.emu.jit.analysis.*;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPointPrototype;+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassageClass;+import ghidra.pcode.error.LowlevelError;+import ghidra.pcode.exec.*;+import ghidra.pcode.exec.PcodeArithmetic.Purpose;+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;+import ghidra.pcode.floatformat.FloatFormat;+import ghidra.pcode.opbehavior.OpBehaviorBoolAnd;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.lang.*;+import ghidra.program.model.pcode.Varnode;+import ghidra.program.util.DefaultLanguageService;+import ghidra.util.NumericUtilities;++@SuppressWarnings("javadoc")+public class JitCodeGeneratorTest extends AbstractJitTest {+ private static final LanguageID ID_TOYBE64 = new LanguageID("Toy:BE:64:default");+ private static final LanguageID ID_TOYLE64 = new LanguageID("Toy:LE:64:default");+ private static final LanguageID ID_TOYBE32 = new LanguageID("Toy:BE:32:default");+ private static final LanguageID ID_ARMv8LE = new LanguageID("ARM:LE:32:v8");+ private static final LanguageID ID_X8664 = new LanguageID("x86:LE:64:default");++ private static final long LONG_CONST = 0xdeadbeefcafebabeL;++ public static void dumpProgram(PcodeProgram program) {+ System.out.println(program);+ }++ public static void dumpClass(byte[] classbytes) throws Exception {+ File tmp = Files.createTempFile("gen", ".class").toFile();+ try (FileOutputStream out = new FileOutputStream(tmp)) {+ out.write(classbytes);+ }+ new ProcessBuilder("javap", "-c", tmp.getPath()).inheritIO().start().waitFor();+ }++ record Translation(PcodeProgram program, MethodNode init, MethodNode run, JitPcodeThread thread,+ TestUseropLibrary library, JitBytesPcodeExecutorState state,+ JitCompiledPassageClass passageCls, JitCompiledPassage passage) {++ public void runErr(Class<? extends Throwable> excType, String message) {+ try {+ passage.run(0);+ }+ catch (Throwable e) {+ if (!excType.isInstance(e)) {+ fail("Expected error of type " + excType.getSimpleName() + ", but was " + e);+ }+ assertEquals(message, e.getMessage());+ return;+ }+ fail("Expected error of type " + excType.getSimpleName() + ", but there was none.");+ }++ public void runLowlevelErr(String message) {+ runErr(LowlevelError.class, message);+ }++ public void runDecodeErr(long pc) {+ runErr(DecodePcodeExecutionException.class,+ "Unknown disassembly error (PC=%08x)".formatted(pc));+ }++ public void runFallthrough() {+ assertEquals(0xdeadbeef, runClean());+ }++ public void runFallthrough32() {+ assertEquals(0xdeadbeef, (int) runClean());+ }++ public long runClean() {+ passage.run(0);+ return thread.getCounter().getOffset();+ }++ public long getLongRegVal(Register reg) {+ byte[] raw = state.getVar(reg, Reason.INSPECT);+ return thread.getArithmetic().toLong(raw, Purpose.INSPECT);+ }++ public RegisterValue getRegVal(Register reg) {+ byte[] raw = state.getVar(reg, Reason.INSPECT);+ return thread.getArithmetic().toRegisterValue(reg, raw, Purpose.INSPECT);+ }++ public long getLongRegVal(String name) {+ Register reg = thread.getLanguage().getRegister(name);+ return getLongRegVal(reg);+ }++ public long getLongVnVal(Varnode vn) {+ byte[] raw = state.getVar(vn, Reason.INSPECT);+ return thread.getArithmetic().toLong(raw, Purpose.INSPECT);+ }++ public long getLongMemVal(long offset, int size) {+ AddressSpace space = thread.getLanguage().getDefaultSpace();+ byte[] raw = state.getVar(space, offset, size, false, Reason.INSPECT);+ return thread.getArithmetic().toLong(raw, Purpose.INSPECT);+ }++ public void setLongRegVal(Register reg, long value) {+ byte[] raw = thread.getArithmetic().fromConst(value, reg.getNumBytes());+ state.setVar(reg, raw);+ }++ public void setLongRegVal(String name, long value) {+ Register reg = thread.getLanguage().getRegister(name);+ setLongRegVal(reg, value);+ }++ public void setLongVnVal(Varnode vn, long value) {+ byte[] raw = thread.getArithmetic().fromConst(value, vn.getSize());+ state.setVar(vn, raw);+ }++ public void setLongMemVal(long offset, long value, int size) {+ byte[] raw = thread.getArithmetic().fromConst(value, size);+ AddressSpace space = thread.getLanguage().getDefaultSpace();+ state.setVar(space, offset, size, false, raw);+ }++ public Entry<AddrCtx, EntryPointPrototype> entryPrototype(Address addr, RegisterValue ctx,+ int blockId) {+ return Map.entry(new AddrCtx(ctx, addr), new EntryPointPrototype(passageCls, blockId));+ }+ }++ public Translation translateProgram(PcodeProgram program, JitPcodeThread thread)+ throws Exception {+ dumpProgram(program);++ JitAnalysisContext context = makeContext(program, thread);+ JitControlFlowModel cfm = new JitControlFlowModel(context);+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm);+ JitTypeModel tm = new JitTypeModel(dfm);+ JitAllocationModel am = new JitAllocationModel(context, dfm, vsm, tm);+ JitOpUseModel oum = new JitOpUseModel(context, cfm, dfm, vsm);++ JitCodeGenerator gen =+ new JitCodeGenerator(MethodHandles.lookup(), context, cfm, dfm, vsm, tm, am, oum);++ byte[] classbytes = gen.generate();++ dumpClass(classbytes);++ ClassNode cn = new ClassNode(Opcodes.ASM9);+ ClassReader cr = new ClassReader(classbytes);+ cr.accept(new TraceClassVisitor(cn, new PrintWriter(System.out)), 0);++ // Have the JVM validate this thing+ JitBytesPcodeExecutorState state = thread.getState();+ JitCompiledPassageClass passageCls =+ JitCompiledPassageClass.load(MethodHandles.lookup(), classbytes);+ JitCompiledPassage passage = passageCls.createInstance(thread);++ assertEquals(Set.of(+ "<clinit>", "<init>", "run", "thread"),+ cn.methods.stream().map(m -> m.name).collect(Collectors.toSet()));++ MethodNode initMethod =+ Unique.assertOne(cn.methods.stream().filter(m -> "<init>".equals(m.name)));+ MethodNode runMethod =+ Unique.assertOne(cn.methods.stream().filter(m -> "run".equals(m.name)));+ return new Translation(program, initMethod, runMethod, thread,+ (TestUseropLibrary) thread.getMachine().getUseropLibrary(), state, passageCls, passage);+ }++ public static class TestUseropLibrary extends AnnotatedPcodeUseropLibrary<byte[]> {+ boolean gotJavaUseropCall = false;+ boolean gotFuncUseropCall = false;+ boolean gotSleighUseropCall = false;++ @PcodeUserop+ public long java_userop(long a, long b) {+ gotJavaUseropCall = true;+ return 2 * a + b;+ }++ @PcodeUserop(functional = true)+ public long func_userop(long a, long b) {+ gotFuncUseropCall = true;+ return 2 * a + b;+ }++ @PcodeUserop(canInline = true)+ public void sleigh_userop(@OpExecutor PcodeExecutor<byte[]> executor,+ @OpLibrary PcodeUseropLibrary<byte[]> library,+ @OpOutput Varnode out, Varnode a, Varnode b) {+ gotSleighUseropCall = true;+ PcodeProgram opProg = SleighProgramCompiler.compileUserop(executor.getLanguage(),+ "sleigh_userop", List.of("__result", "a", "b"), """+ __result = 2*a + b;+ """, library, List.of(out, a, b));+ executor.execute(opProg, library);+ }+ }++ public static class TestJitPcodeEmulator extends JitPcodeEmulator {+ public TestJitPcodeEmulator(Language language) {+ super(language, new JitConfiguration(), MethodHandles.lookup());+ }++ @Override+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {+ return new TestUseropLibrary();+ }+ }++ public static class TestPlainPcodeEmulator extends PcodeEmulator {+ public TestPlainPcodeEmulator(Language language) {+ super(language);+ }++ @Override+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {+ return new TestUseropLibrary();+ }+ }++ record Case(String name, String init, List<String> evals) {}++ protected void runEquivalenceTest(Translation tr, List<Case> cases) {+ PcodeEmulator plainEmu = new TestPlainPcodeEmulator(tr.program.getLanguage());+ PcodeThread<byte[]> plainThread = plainEmu.newThread();++ for (Case c : cases) {+ if (!c.init.isBlank()) {+ plainThread.getExecutor().executeSleigh(c.init);+ tr.thread.getExecutor().executeSleigh(c.init);+ }++ plainThread.getExecutor().execute(tr.program, plainThread.getUseropLibrary());+ assertEquals("Mismatch of PC.", plainThread.getCounter().getOffset(), tr.runClean());++ for (String e : c.evals) {+ PcodeExpression expr =+ SleighProgramCompiler.compileExpression(tr.program.getLanguage(), e);+ BigInteger expected = plainThread.getArithmetic()+ .toBigInteger(expr.evaluate(plainThread.getExecutor()), Purpose.INSPECT);+ BigInteger actual = tr.thread.getArithmetic()+ .toBigInteger(expr.evaluate(tr.thread.getExecutor()), Purpose.INSPECT);+ assertEquals("For case '%s': Mismatch of '%s'.".formatted(c.name, e),+ expected, actual);+ }+ }+ }++ public Translation translateSleigh(LanguageID langId, String source) throws Exception {+ SleighLanguage language = (SleighLanguage) DefaultLanguageService.getLanguageService()+ .getLanguage(langId);+ List<String> lines = new ArrayList<>(Arrays.asList(source.split("\n")));+ if (!lines.getLast().startsWith("goto ")) {+ // Cannot end with fall-through+ // TODO: how to specify positive?+ lines.add("goto 0xdeadbeef;");+ source = lines.stream().collect(Collectors.joining("\n"));+ }+ JitPcodeEmulator emu = new TestJitPcodeEmulator(language);+ JitPcodeThread thread = emu.newThread();+ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", source,+ thread.getUseropLibrary());+ return translateProgram(program, thread);+ }++ public AssemblyBuffer createBuffer(LanguageID languageID, long entry) throws Exception {+ Language language = DefaultLanguageService.getLanguageService().getLanguage(languageID);+ Address addr = language.getDefaultSpace().getAddress(entry);+ Assembler asm = Assemblers.getAssembler(language);+ return new AssemblyBuffer(asm, addr);+ }++ public Translation translateBuffer(AssemblyBuffer buf, Address entry, Map<Long, String> injects)+ throws Exception {+ Language language = buf.getAssembler().getLanguage();++ JitPcodeEmulator emu = new TestJitPcodeEmulator(language);+ AddressSpace space = language.getDefaultSpace();+ for (Map.Entry<Long, String> ent : injects.entrySet()) {+ emu.inject(space.getAddress(ent.getKey()), ent.getValue());+ }+ JitPcodeThread thread = emu.newThread();+ byte[] bytes = buf.getBytes();+ emu.getSharedState().setVar(buf.getEntry(), bytes.length, false, bytes);++ thread.setCounter(entry);+ thread.overrideContextWithDefault();+ JitPassage passage = decodePassage(thread);+ return translateProgram(passage, thread);+ }++ public Translation translateLang(LanguageID languageID, long offset, String source,+ Map<Long, String> injects)+ throws Exception {+ AssemblyBuffer buf = createBuffer(languageID, offset);+ for (String line : source.split("\n")) {+ if (line.isBlank()) {+ }+ else if (line.startsWith(".emit ")) {+ buf.emit(NumericUtilities+ .convertStringToBytes(line.substring(".emit ".length()).replace(" ", "")));+ }+ else {+ buf.assemble(line);+ }+ }+ return translateBuffer(buf, buf.getEntry(), injects);+ }++ public Translation translateToy(long offset, String source) throws Exception {+ return translateLang(ID_TOYBE64, offset, source, Map.of());+ }++ @Test+ public void testSimpleInt() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:4 = 0x1234;+ """);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(0x1234, tr.getLongVnVal(temp));+ }++ @Test+ public void testToyOneBlockHasFallthroughExit() throws Exception {+ Translation tr = translateToy(0x00400000, """+ imm r0, #0x123+ """);+ tr.runDecodeErr(0x00400002);+ assertEquals(0x123, tr.getLongRegVal("r0"));+ }++ @Test+ public void testSimpleLong() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:8 = 0x1234;+ """);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(0x1234, tr.getLongVnVal(temp));+ }++ @Test+ public void testSimpleFloat() throws Exception {+ int fDot5 = Float.floatToRawIntBits(0.5f);+ int fDot75 = Float.floatToRawIntBits(0.75f);+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:4 = 0x%x f+ 0x%x;+ """.formatted(fDot5, fDot75));+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(1.25f, Float.intBitsToFloat((int) tr.getLongVnVal(temp)), 0);+ }++ @Test+ public void testSimpleDouble() throws Exception {+ long dDot5 = Double.doubleToRawLongBits(0.5);+ long dDot75 = Double.doubleToRawLongBits(0.75);+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:8 = 0x%x f+ 0x%x;+ """.formatted(dDot5, dDot75));+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(1.25f, Double.longBitsToDouble(tr.getLongVnVal(temp)), 0);+ }++ @Test+ @Ignore("MpInt is TODO")+ public void test3LeggedInt() {+ TODO();+ }++ @Test+ @Ignore("MpInt is TODO")+ public void test2LeggedWithResidue() {+ TODO();+ }++ @Test+ public void testReadMemMappedRegBE() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ * 0:8 = 0x%x:8;+ temp:8 = mmr0;+ """.formatted(LONG_CONST));+ Varnode temp = tr.program.getCode().get(1).getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ @Test+ public void testReadMemDirectWithPartsSpanningBlockBE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:8 = * 0x%x:8;+ """.formatted(offset));+ tr.setLongMemVal(offset, LONG_CONST, 8);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ @Test+ public void testReadMemDirectWithPartsSpanningBlockLE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYLE64, """+ temp:8 = * 0x%x:8;+ """.formatted(offset));+ tr.setLongMemVal(offset, LONG_CONST, 8);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ @Test+ @Ignore("Undefined")+ public void testReadMemDirectWithSpanWrapSpaceBE() throws Exception {+ long offset = -2;+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:8 = * 0x%x:8;+ """.formatted(offset));+ tr.setLongMemVal(offset, LONG_CONST, 8);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ @Test+ @Ignore("Undefined")+ public void testReadMemDirectWithSpanWrapSpaceLE() throws Exception {+ long offset = -2;+ Translation tr = translateSleigh(ID_TOYLE64, """+ temp:8 = * 0x%x:8;+ """.formatted(offset));+ tr.setLongMemVal(offset, LONG_CONST, 8);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp.isUnique());+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ @Test+ public void testWriteMemDirectWithPartsSpanningBlockBE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYBE64, """+ local temp:8;+ * 0x%x:8 = temp;+ """.formatted(offset));+ Varnode temp = tr.program.getCode().getFirst().getInput(2);+ assertTrue(temp.isUnique());+ tr.setLongVnVal(temp, LONG_CONST);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongMemVal(offset, 8));+ }++ @Test+ public void testWriteMemDirectWithPartsSpanningBlockLE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYLE64, """+ local temp:8;+ * 0x%x:8 = temp;+ """.formatted(offset));+ Varnode temp = tr.program.getCode().getFirst().getInput(2);+ assertTrue(temp.isUnique());+ tr.setLongVnVal(temp, LONG_CONST);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongMemVal(offset, 8));+ }++ @Test+ @Ignore("Undefined")+ public void testWriteMemDirectWithSpanWrapSpaceBE() throws Exception {+ long offset = -2;+ Translation tr = translateSleigh(ID_TOYBE64, """+ local temp:8;+ * 0x%x:8 = temp;+ """.formatted(offset));+ Varnode temp = tr.program.getCode().getFirst().getInput(2);+ assertTrue(temp.isUnique());+ tr.setLongVnVal(temp, LONG_CONST);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongMemVal(offset, 8));+ }++ @Test+ @Ignore("Undefined")+ public void testWriteMemDirectWithSpanWrapSpaceLE() throws Exception {+ long offset = -2;+ Translation tr = translateSleigh(ID_TOYLE64, """+ local temp:8;+ * 0x%x:8 = temp;+ """.formatted(offset));+ Varnode temp = tr.program.getCode().getFirst().getInput(2);+ assertTrue(temp.isUnique());+ tr.setLongVnVal(temp, LONG_CONST);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongMemVal(offset, 8));+ }++ @Test+ public void testReadMemIndirectBE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYBE64, """+ local temp:8;+ local addr:8;+ temp = * addr;+ """);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ Varnode addr = tr.program.getCode().getFirst().getInput(1);+ assertTrue(temp.isUnique());+ assertTrue(addr.isUnique());+ tr.setLongMemVal(offset, LONG_CONST, 8);+ tr.setLongVnVal(addr, offset);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ @Test+ public void testReadMemIndirectLE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYLE64, """+ local temp:8;+ local addr:8;+ temp = * addr;+ """);+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ Varnode addr = tr.program.getCode().getFirst().getInput(1);+ assertTrue(temp.isUnique());+ assertTrue(addr.isUnique());+ tr.setLongMemVal(offset, LONG_CONST, 8);+ tr.setLongVnVal(addr, offset);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ @Test+ public void testWriteMemIndirectBE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYBE64, """+ local temp:8;+ local addr:8;+ * addr = temp;+ """);+ Varnode temp = tr.program.getCode().getFirst().getInput(2);+ Varnode addr = tr.program.getCode().getFirst().getInput(1);+ assertTrue(temp.isUnique());+ assertTrue(addr.isUnique());+ tr.setLongVnVal(temp, LONG_CONST);+ tr.setLongVnVal(addr, offset);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongMemVal(offset, 8));+ }++ @Test+ public void testWriteMemIndirectLE() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYLE64, """+ local temp:8;+ local addr:8;+ * addr = temp;+ """);+ Varnode temp = tr.program.getCode().getFirst().getInput(2);+ Varnode addr = tr.program.getCode().getFirst().getInput(1);+ assertTrue(temp.isUnique());+ assertTrue(addr.isUnique());+ tr.setLongVnVal(temp, LONG_CONST);+ tr.setLongVnVal(addr, offset);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongMemVal(offset, 8));+ }++ @Test+ public void testAddressSize32() throws Exception {+ long offset = GenConsts.BLOCK_SIZE - 2;+ Translation tr = translateSleigh(ID_TOYBE32, """+ local temp:8;+ local addr:4;+ * addr = temp;+ """);+ Varnode temp = tr.program.getCode().getFirst().getInput(2);+ Varnode addr = tr.program.getCode().getFirst().getInput(1);+ assertTrue(temp.isUnique());+ assertTrue(addr.isUnique());+ tr.setLongVnVal(temp, LONG_CONST);+ tr.setLongVnVal(addr, offset);+ tr.runFallthrough32();+ assertEquals(LONG_CONST, tr.getLongMemVal(offset, 8));+ }++ @Test+ public void testVariablesAreRetiredBranchInd() throws Exception {+ /**+ * Considering detection of inter-passage indirect branching, I think this will complicate+ * things way too much. All of the control-flow analysis must consider indirect flows, and+ * then, the dataflow could be affected by that, so there's a circular dependency. With some+ * care, that can be done, though I'm not sure it's always guaranteed to converge. Another+ * possibility is to retire all the variables, but then, there has to be a special branch+ * target that knows to birth the appropriate ones before entering the real block.+ */+ Translation tr = translateSleigh(ID_TOYBE64, """+ local jump:8;+ temp:8 = 0x%x;+ goto [jump];+ """.formatted(LONG_CONST));+ Varnode temp = tr.program.getCode().getFirst().getOutput();+ Varnode jump = tr.program.getCode().get(1).getInput(0);+ assertTrue(temp.isUnique());+ assertTrue(jump.isUnique());+ tr.setLongVnVal(jump, 0x1234);+ assertEquals(0x1234, tr.runClean());+ assertEquals(LONG_CONST, tr.getLongVnVal(temp));+ }++ /**+ * Test reading from a variable in an unreachable block.+ *+ * <p>+ * Yes, this test is valid, because, even though no slaspec should produce this, they could, but+ * more to the point, a user injection could. Note that the underlying classfile writer may+ * analyze and remove the unreachable code. Doesn't matter. What matters is that it doesn't+ * crash, and that it produces correct results.+ */+ @Test+ public void testWithMissingVariable() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ local temp:8;+ local temp2:8;+ temp2 = 1;+ goto 0xdeadbeef;+ temp2 = temp;+ """);+ Varnode temp2 = tr.program.getCode().getFirst().getOutput();+ assertTrue(temp2.isUnique());+ tr.runFallthrough();+ assertEquals(1, tr.getLongVnVal(temp2));+ }++ @Test+ public void testCallOtherSleighDef() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ r0 = sleigh_userop(6:8, 2:8);+ """);+ assertTrue(tr.library.gotSleighUseropCall);+ tr.library.gotSleighUseropCall = false;+ tr.runFallthrough();+ assertFalse(tr.library.gotSleighUseropCall);+ assertEquals(14, tr.getLongRegVal("r0"));+ }++ @Test+ public void testCallOtherJavaDef() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ r0 = java_userop(6:8, 2:8);+ """);+ assertFalse(tr.library.gotJavaUseropCall);+ tr.runFallthrough();+ assertTrue(tr.library.gotJavaUseropCall);+ assertEquals(14, tr.getLongRegVal("r0"));+ }++ @Test+ public void testCallOtherJavaDefNoOut() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ java_userop(6:8, 2:8);+ """);+ assertFalse(tr.library.gotJavaUseropCall);+ tr.runFallthrough();+ assertTrue(tr.library.gotJavaUseropCall);+ assertEquals(0, tr.getLongRegVal("r0"));+ }++ @Test+ public void testCallOtherFuncJavaDef() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ r0 = func_userop(6:8, 2:8);+ """);+ assertFalse(tr.library.gotFuncUseropCall);+ tr.runFallthrough();+ assertTrue(tr.library.gotFuncUseropCall);+ assertEquals(14, tr.getLongRegVal("r0"));+ }++ @Test+ public void testCallOtherFuncJavaDefNoOut() throws Exception {+ Translation tr = translateSleigh(ID_TOYBE64, """+ func_userop(6:8, 2:8);+ """);+ assertFalse(tr.library.gotFuncUseropCall);+ tr.runFallthrough();+ assertTrue(tr.library.gotFuncUseropCall);+ assertEquals(0, tr.getLongRegVal("r0"));+ }++ /**+ * Test that the emulator doesn't throw until the userop is actually encountered at run time.+ *+ * <p>+ * NOTE: The userop must be defined by the language, but left undefined by the library.+ * Otherwise, we cannot even compile the sample Sleigh.+ *+ * <p>+ * NOTE: Must also use actual instructions, because the test passage constructor will fail fast+ * on the undefined userop.+ */+ @Test+ public void testCallOtherUndef() throws Exception {+ Translation tr = translateToy(0x00400000, """+ user_one r0+ """);+ tr.runErr(SleighLinkException.class, "Sleigh userop 'pcodeop_one' is not in the library");+ assertEquals(0x00400000, tr.thread.getCounter().getOffset());+ }++ /**+ * I need to find an example of this:+ *+ * <pre>+ * *[register] OFFSET = ... ?+ * </pre>+ *+ * <p>+ * Honestly, if this actually occurs frequently, we could be in trouble. We would need either:+ * 1) To re-write all the offending semantic blocks, or 2) Work out a way to re-write them+ * during JIT compilation. People tell me this is done by some vector instructions, which makes+ * me thing re-writing would be possible, since they should all fold to constants. If we're+ * lucky, the planned constant folding would just take care of these; however, I'd still want to+ * allocate them as locals, not just direct array access. For now, I'm just going to feign+ * ignorance. If it becomes a problem, then we can treat all register accesses like memory+ * within the entire passage containing one of these "indirect-register-access" ops.+ */+ @Test+ @Ignore("No examples, yet")+ public void testComputedOffsetsInRegisterSpace() throws Exception {+ TODO();+ }++ /**+ * This is interesting, because it may necessitate MpInt DIV+ */+ @Test+ @Ignore("TODO")+ public void testX86DIV() throws Exception {+ TODO();+ }++ @Test+ public void testBranchOpGenInternal() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = 0xbeef;+ goto <skip>;+ r0 = 0xdead;+ <skip>+ """),+ List.of(+ new Case("only", "", List.of("r0"))));+ }++ @Test+ public void testBranchOpGenExternal() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = 0xbeef;+ goto 0xdeadbeef;+ r0 = 0xdead;+ """),+ List.of(+ new Case("only", "", List.of("r0"))));+ }++ @Test+ public void testCBranchOpGenInternalIntPredicate() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = 0xbeef;+ if (r1!=0) goto <skip>;+ r0 = 0xdead;+ <skip>+ """),+ List.of(+ new Case("take", "r1=1;", List.of("r0")),+ new Case("fall", "r1=0;", List.of("r0"))));+ }++ @Test+ public void testCBranchOpGenExternalLongPredicate() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = 0xbeef;+ if (r1) goto 0xdeadbeef;+ r0 = 0xdead;+ """),+ List.of(+ new Case("take", "r1=1;", List.of("r0")),+ new Case("fall", "r1=0;", List.of("r0"))));+ }++ @Test+ public void testBoolNegateOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = !r1;+ r6l = !r7l;+ """),+ List.of(+ new Case("f", """+ r1 =0;+ r7l =0;+ """, List.of("r0", "r6")),+ new Case("t", """+ r1 =1;+ r7l =1;+ """, List.of("r0", "r6"))+ /*, new Case("T", """+ r1 =0x400000000;+ r7l =4;+ """, List.of("r0", "r6"))*/));+ }++ /**+ * TODO: The last case (commented out) here actually fails because {@link OpBehaviorBoolAnd},+ * from the standard emulator, does bitwise AND instead of boolean AND. I do not know which+ * should be corrected.+ */+ @Test+ public void testBoolAndOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 && r2;+ r3 = r4 && r5l;+ r6l = r7l && r8;+ r9l = r10l && r11l;+ """),+ List.of(+ new Case("ff", """+ r1 =0; r2 =0;+ r4 =0; r5l =0;+ r7l =0; r8 =0;+ r10l=0; r11l=0;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("ft", """+ r1 =0; r2 =1;+ r4 =0; r5l =1;+ r7l =0; r8 =1;+ r10l=0; r11l=1;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("tf", """+ r1 =1; r2 =0;+ r4 =1; r5l =0;+ r7l =1; r8 =0;+ r10l=1; r11l=0;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("tt", """+ r1 =1; r2 =1;+ r4 =1; r5l =1;+ r7l =1; r8 =1;+ r10l=1; r11l=1;+ """,+ List.of("r0", "r3", "r6", "r9"))+ /*, new Case("tT", """+ r1 =100; r2 =0x400000000;+ r4 =100; r5l =4;+ r7l =100; r8 =0x400000000;+ r10l=100; r11l=4;+ """,+ List.of("r0", "r3", "r6", "r9"))*/));+ }++ @Test+ public void testBoolOrOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 || r2;+ r3 = r4 || r5l;+ r6l = r7l || r8;+ r9l = r10l || r11l;+ """),+ List.of(+ new Case("ff", """+ r1 =0; r2 =0;+ r4 =0; r5l =0;+ r7l =0; r8 =0;+ r10l=0; r11l=0;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("ft", """+ r1 =0; r2 =1;+ r4 =0; r5l =1;+ r7l =0; r8 =1;+ r10l=0; r11l=1;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("tf", """+ r1 =1; r2 =0;+ r4 =1; r5l =0;+ r7l =1; r8 =0;+ r10l=1; r11l=0;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("tt", """+ r1 =1; r2 =1;+ r4 =1; r5l =1;+ r7l =1; r8 =1;+ r10l=1; r11l=1;+ """,+ List.of("r0", "r3", "r6", "r9"))+ /*, new Case("tT", """+ r1 =100; r2 =0x400000000;+ r4 =100; r5l =4;+ r7l =100; r8 =0x400000000;+ r10l=100; r11l=4;+ """,+ List.of("r0", "r3", "r6", "r9"))*/));+ }++ @Test+ public void testBoolXorOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 ^^ r2;+ r3 = r4 ^^ r5l;+ r6l = r7l ^^ r8;+ r9l = r10l ^^ r11l;+ """),+ List.of(+ new Case("ff", """+ r1 =0; r2 =0;+ r4 =0; r5l =0;+ r7l =0; r8 =0;+ r10l=0; r11l=0;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("ft", """+ r1 =0; r2 =1;+ r4 =0; r5l =1;+ r7l =0; r8 =1;+ r10l=0; r11l=1;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("tf", """+ r1 =1; r2 =0;+ r4 =1; r5l =0;+ r7l =1; r8 =0;+ r10l=1; r11l=0;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("tt", """+ r1 =1; r2 =1;+ r4 =1; r5l =1;+ r7l =1; r8 =1;+ r10l=1; r11l=1;+ """,+ List.of("r0", "r3", "r6", "r9"))+ /*, new Case("tT", """+ r1 =100; r2 =0x400000000;+ r4 =100; r5l =4;+ r7l =100; r8 =0x400000000;+ r10l=100; r11l=4;+ """,+ List.of("r0", "r3", "r6", "r9"))*/));+ }++ @Test+ public void testFloatAbsOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ long dn0dot5 = Double.doubleToLongBits(-0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ int fn0dot5 = Float.floatToIntBits(-0.5f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = abs(r1);+ r6l = abs(r7l);+ """),+ List.of(+ new Case("p", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d0dot5, f0dot5), List.of("r0", "r6")),+ new Case("n", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn0dot5, fn0dot5), List.of("r0", "r6"))));+ }++ /**+ * Note that the test case for sqrt(n) where n is negative could be brittle, because of+ * undefined behavior in the IEEE 754 spec. My JVM will result in "negative NaN." It used to be+ * this test failed, but I've made an adjustment to {@link FloatFormat} to ensure it keeps+ * whatever sign bit was returned by {@link Math#sqrt(double)}. It shouldn't matter to the+ * emulation target one way or another (in theory), but I do want to ensure the two emulators+ * behave the same. It seems easier to me to have {@link FloatFormat} keep the sign bit than to+ * have the JIT compile in code that checks for and fixes "negative NaN." Less run-time cost,+ * too.+ */+ @Test+ public void testFloatSqrtOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ long dn0dot5 = Double.doubleToLongBits(-0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ int fn0dot5 = Float.floatToIntBits(-0.5f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = sqrt(r1);+ r6l = sqrt(r7l);+ """),+ List.of(+ new Case("p", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d0dot5, f0dot5), List.of("r0", "r6")),+ new Case("n", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn0dot5, fn0dot5), List.of("r0", "r6"))));+ }++ @Test+ public void testFloatCeilOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ long dn0dot5 = Double.doubleToLongBits(-0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ int fn0dot5 = Float.floatToIntBits(-0.5f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = ceil(r1);+ r6l = ceil(r7l);+ """),+ List.of(+ new Case("p", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d0dot5, f0dot5), List.of("r0", "r6")),+ new Case("n", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn0dot5, fn0dot5), List.of("r0", "r6"))));+ }++ @Test+ public void testFloatFloorOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ long dn0dot5 = Double.doubleToLongBits(-0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ int fn0dot5 = Float.floatToIntBits(-0.5f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = floor(r1);+ r6l = floor(r7l);+ """),+ List.of(+ new Case("p", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d0dot5, f0dot5), List.of("r0", "r6")),+ new Case("n", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn0dot5, fn0dot5), List.of("r0", "r6"))));+ }++ @Test+ public void testFloatRoundOpGen() throws Exception {+ long d0dot25 = Double.doubleToLongBits(0.25);+ long dn0dot25 = Double.doubleToLongBits(-0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ int fn0dot25 = Float.floatToIntBits(-0.25f);+ long d0dot5 = Double.doubleToLongBits(0.5);+ long dn0dot5 = Double.doubleToLongBits(-0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ int fn0dot5 = Float.floatToIntBits(-0.5f);+ long d0dot75 = Double.doubleToLongBits(0.75);+ long dn0dot75 = Double.doubleToLongBits(-0.75);+ int f0dot75 = Float.floatToIntBits(0.75f);+ int fn0dot75 = Float.floatToIntBits(-0.75f);+ long d1dot0 = Double.doubleToLongBits(1.0);+ long dn1dot0 = Double.doubleToLongBits(-1.0);+ int f1dot0 = Float.floatToIntBits(1.0f);+ int fn1dot0 = Float.floatToIntBits(-1.0f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = round(r1);+ r6l = round(r7l);+ """),+ List.of(+ new Case("+0.25", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d0dot25, f0dot25), List.of("r0", "r6")),+ new Case("-0.25", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn0dot25, fn0dot25), List.of("r0", "r6")),+ new Case("+0.5", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d0dot5, f0dot5), List.of("r0", "r6")),+ new Case("-0.5", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn0dot5, fn0dot5), List.of("r0", "r6")),+ new Case("+0.75", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d0dot75, f0dot75), List.of("r0", "r6")),+ new Case("-0.75", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn0dot75, fn0dot75), List.of("r0", "r6")),+ new Case("+1.0", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(d1dot0, f1dot0), List.of("r0", "r6")),+ new Case("-1.0", """+ r1 =0x%x;+ r7l =0x%x;+ """.formatted(dn1dot0, fn1dot0), List.of("r0", "r6"))));+ }++ @Test+ public void testFloat2FloatOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = float2float(r1l);+ r6l = float2float(r7);+ """),+ List.of(+ new Case("only", """+ r1l =0x%x;+ r7 =0x%x;+ """.formatted(f0dot5, d0dot5), List.of("r0", "r6"))));+ }++ @Test+ public void testFloatInt2FloatOpGen() throws Exception {+ /**+ * The size swap is not necessary, but test anyway.+ */+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = int2float(r1l);+ r6l = int2float(r7);+ """),+ List.of(+ new Case("only", """+ r1l =1;+ r7 =2;+ """, List.of("r0", "r6"))));+ }++ @Test+ public void testFloatTruncOpGen() throws Exception {+ long d1dot0 = Double.doubleToLongBits(1.0);+ long d0dot5 = Double.doubleToLongBits(0.5);+ long dn0dot5 = Double.doubleToLongBits(-0.5);+ int f1dot0 = Float.floatToIntBits(1.0f);+ int f0dot5 = Float.floatToIntBits(0.5f);+ int fn0dot5 = Float.floatToIntBits(-0.5f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = trunc(r1);+ r3 = trunc(r4l);+ r6l = trunc(r7);+ r9l = trunc(r10l);+ """),+ List.of(+ new Case("+1.0", """+ r1 =0x%x;+ r4l =0x%x;+ r7 =0x%x;+ r10l=0x%x;+ """.formatted(d1dot0, f1dot0, d1dot0, f1dot0), List.of("r0", "r6")),+ new Case("+0.5", """+ r1 =0x%x;+ r4l =0x%x;+ r7 =0x%x;+ r10l=0x%x;+ """.formatted(d0dot5, f0dot5, d0dot5, f0dot5), List.of("r0", "r6")),+ new Case("-0.5", """+ r1 =0x%x;+ r4l =0x%x;+ r7 =0x%x;+ r10l=0x%x;+ """.formatted(dn0dot5, dn0dot5, dn0dot5, fn0dot5), List.of("r0", "r6"))));+ }++ @Test+ public void testFloatNaNOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long dNaN = Double.doubleToRawLongBits(Double.NaN);+ int fNaN = Float.floatToRawIntBits(Float.NaN);+ /**+ * The size swap is not necessary, but test anyway.+ */+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = nan(r1l);+ r6l = nan(r7);+ """),+ List.of(+ new Case("num", """+ r1l =0x%x;+ r7 =0x%x;+ """.formatted(f0dot5, d0dot5), List.of("r0", "r6")),+ new Case("nan", """+ r1l =0x%x;+ r7 =0x%x;+ """.formatted(fNaN, dNaN), List.of("r0", "r6"))));+ }++ @Test+ public void testFloatNegOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = f-r1;+ r6l = f-r7l;+ """),+ List.of(+ new Case("num", """+ r1l =0x%x;+ r7 =0x%x;+ """.formatted(f0dot5, d0dot5), List.of("r0", "r6"))));+ }++ @Test+ public void testFloatAddOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f+ r2;+ r9l = r10l f+ r11l;+ """),+ List.of(+ new Case("only", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testFloatSubOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f- r2;+ r9l = r10l f- r11l;+ """),+ List.of(+ new Case("only", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testFloatMultOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f* r2;+ r9l = r10l f* r11l;+ """),+ List.of(+ new Case("only", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testFloatDivOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f/ r2;+ r9l = r10l f/ r11l;+ """),+ List.of(+ new Case("only", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testFloatEqualOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f== r2;+ r9l = r10l f== r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot25, d0dot5, f0dot25, f0dot5),+ List.of("r0", "r9")),+ new Case("eq", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot5, f0dot5, f0dot5),+ List.of("r0", "r9")),+ new Case("gt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testFloatNotEqualOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f!= r2;+ r9l = r10l f!= r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot25, d0dot5, f0dot25, f0dot5),+ List.of("r0", "r9")),+ new Case("eq", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot5, f0dot5, f0dot5),+ List.of("r0", "r9")),+ new Case("gt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testFloatLessEqualOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f<= r2;+ r9l = r10l f<= r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot25, d0dot5, f0dot25, f0dot5),+ List.of("r0", "r9")),+ new Case("eq", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot5, f0dot5, f0dot5),+ List.of("r0", "r9")),+ new Case("gt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testFloatLessOpGen() throws Exception {+ long d0dot5 = Double.doubleToLongBits(0.5);+ int f0dot5 = Float.floatToIntBits(0.5f);+ long d0dot25 = Double.doubleToLongBits(0.25);+ int f0dot25 = Float.floatToIntBits(0.25f);+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 f< r2;+ r9l = r10l f< r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot25, d0dot5, f0dot25, f0dot5),+ List.of("r0", "r9")),+ new Case("eq", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot5, f0dot5, f0dot5),+ List.of("r0", "r9")),+ new Case("gt", """+ r1 =0x%x; r2 =0x%x;+ r10l=0x%x; r11l=0x%x;+ """.formatted(d0dot5, d0dot25, f0dot5, f0dot25),+ List.of("r0", "r9"))));+ }++ @Test+ public void testInt2CompOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = -r1;+ r6l = -r7l;+ """),+ List.of(+ new Case("pos", """+ r1l =4;+ r7 =4;+ """, List.of("r0", "r6")),+ new Case("neg", """+ r1l =-4;+ r7 =-4;+ """, List.of("r0", "r6"))));+ }++ @Test+ public void testIntNegateOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = ~r1;+ r6l = ~r7l;+ """),+ List.of(+ new Case("pos", """+ r1l =4;+ r7 =4;+ """, List.of("r0", "r6")),+ new Case("neg", """+ r1l =-4;+ r7 =-4;+ """, List.of("r0", "r6"))));+ }++ @Test+ public void testIntSExtOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = sext(r1l);+ """),+ List.of(+ new Case("pos", """+ r1l =4;+ """, List.of("r0")),+ new Case("neg", """+ r1l =-4;+ """, List.of("r0"))));+ }++ @Test+ public void testIntZExtOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = zext(r1l);+ """),+ List.of(+ new Case("pos", """+ r1l =4;+ """, List.of("r0")),+ new Case("neg", """+ r1l =-4;+ """, List.of("r0"))));+ }++ @Test+ public void testLzCountOpGen() throws Exception {+ // Test size change, even though not necessary here+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = lzcount(r1l);+ """),+ List.of(+ new Case("pos", """+ r1l =4;+ """, List.of("r0")),+ new Case("neg", """+ r1l =-4;+ """, List.of("r0"))));+ }++ @Test+ public void testPopCountOpGen() throws Exception {+ // Test size change, even though not necessary here+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = popcount(r1l);+ """),+ List.of(+ new Case("pos", """+ r1l =4;+ """, List.of("r0")),+ new Case("neg", """+ r1l =-4;+ """, List.of("r0"))));+ }++ @Test+ public void testSubPieceOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0l = r1(3);+ r3 = r4l(3);+ """),+ List.of(+ new Case("only", """+ r1 =0x%x;+ r4l=0x12345678;+ """.formatted(LONG_CONST), List.of("r0"))));+ }++ @Test+ public void testIntAddOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 + r2;+ r9l = r10l + r11l;+ """),+ List.of(+ new Case("only", """+ r1 =2; r2 =2;+ r10l=2; r11l=2;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntSubOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 - r2;+ r9l = r10l - r11l;+ """),+ List.of(+ new Case("only", """+ r1 =2; r2 =2;+ r10l=2; r11l=2;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntMultOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 * r2;+ r9l = r10l * r11l;+ """),+ List.of(+ new Case("only", """+ r1 =2; r2 =2;+ r10l=2; r11l=2;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntDivOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 / r2;+ r9l = r10l / r11l;+ """),+ List.of(+ new Case("pp", """+ r1 =5; r2 =2;+ r10l=5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("pn", """+ r1 =5; r2 =-2;+ r10l=5; r11l=-2;+ """, List.of("r0", "r9")),+ new Case("np", """+ r1 =-5; r2 =2;+ r10l=-5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("nn", """+ r1 =-5; r2 =-2;+ r10l=-5; r11l=-2;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntSDivOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 s/ r2;+ r9l = r10l s/ r11l;+ """),+ List.of(+ new Case("pp", """+ r1 =5; r2 =2;+ r10l=5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("pn", """+ r1 =5; r2 =-2;+ r10l=5; r11l=-2;+ """, List.of("r0", "r9")),+ new Case("np", """+ r1 =-5; r2 =2;+ r10l=-5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("nn", """+ r1 =-5; r2 =-2;+ r10l=-5; r11l=-2;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntRemOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 % r2;+ r9l = r10l % r11l;+ """),+ List.of(+ new Case("pp", """+ r1 =5; r2 =2;+ r10l=5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("pn", """+ r1 =5; r2 =-2;+ r10l=5; r11l=-2;+ """, List.of("r0", "r9")),+ new Case("np", """+ r1 =-5; r2 =2;+ r10l=-5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("nn", """+ r1 =-5; r2 =-2;+ r10l=-5; r11l=-2;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntSRemOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 s% r2;+ r9l = r10l s% r11l;+ """),+ List.of(+ new Case("pp", """+ r1 =5; r2 =2;+ r10l=5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("pn", """+ r1 =5; r2 =-2;+ r10l=5; r11l=-2;+ """, List.of("r0", "r9")),+ new Case("np", """+ r1 =-5; r2 =2;+ r10l=-5; r11l=2;+ """, List.of("r0", "r9")),+ new Case("nn", """+ r1 =-5; r2 =-2;+ r10l=-5; r11l=-2;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntAndOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 & r2;+ r9l = r10l & r11l;+ """),+ List.of(+ new Case("only", """+ r1 =0x3; r2 =0x5;+ r10l=0x3; r11l=0x5;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntOrOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 | r2;+ r9l = r10l | r11l;+ """),+ List.of(+ new Case("only", """+ r1 =0x3; r2 =0x5;+ r10l=0x3; r11l=0x5;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntXorOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 ^ r2;+ r9l = r10l ^ r11l;+ """),+ List.of(+ new Case("only", """+ r1 =0x3; r2 =0x5;+ r10l=0x3; r11l=0x5;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntEqualOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 == r2;+ r9l = r10l == r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =1; r2 =2;+ r10l=1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("slt", """+ r1 =-1; r2 =2;+ r10l=-1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("eq", """+ r1 =1; r2 =1;+ r10l=1; r11l=1;+ """, List.of("r0", "r9")),+ new Case("gt", """+ r1 =2; r2 =1;+ r10l=2; r11l=1;+ """, List.of("r0", "r9")),+ new Case("sgt", """+ r1 =2; r2 =-1;+ r10l=2; r11l=-1;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntNotEqualOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 != r2;+ r9l = r10l != r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =1; r2 =2;+ r10l=1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("slt", """+ r1 =-1; r2 =2;+ r10l=-1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("eq", """+ r1 =1; r2 =1;+ r10l=1; r11l=1;+ """, List.of("r0", "r9")),+ new Case("gt", """+ r1 =2; r2 =1;+ r10l=2; r11l=1;+ """, List.of("r0", "r9")),+ new Case("sgt", """+ r1 =2; r2 =-1;+ r10l=2; r11l=-1;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntLessEqualOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 <= r2;+ r9l = r10l <= r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =1; r2 =2;+ r10l=1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("slt", """+ r1 =-1; r2 =2;+ r10l=-1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("eq", """+ r1 =1; r2 =1;+ r10l=1; r11l=1;+ """, List.of("r0", "r9")),+ new Case("gt", """+ r1 =2; r2 =1;+ r10l=2; r11l=1;+ """, List.of("r0", "r9")),+ new Case("sgt", """+ r1 =2; r2 =-1;+ r10l=2; r11l=-1;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntSLessEqualOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 s<= r2;+ r9l = r10l s<= r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =1; r2 =2;+ r10l=1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("slt", """+ r1 =-1; r2 =2;+ r10l=-1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("eq", """+ r1 =1; r2 =1;+ r10l=1; r11l=1;+ """, List.of("r0", "r9")),+ new Case("gt", """+ r1 =2; r2 =1;+ r10l=2; r11l=1;+ """, List.of("r0", "r9")),+ new Case("sgt", """+ r1 =2; r2 =-1;+ r10l=2; r11l=-1;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntLessOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 < r2;+ r9l = r10l < r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =1; r2 =2;+ r10l=1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("slt", """+ r1 =-1; r2 =2;+ r10l=-1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("eq", """+ r1 =1; r2 =1;+ r10l=1; r11l=1;+ """, List.of("r0", "r9")),+ new Case("gt", """+ r1 =2; r2 =1;+ r10l=2; r11l=1;+ """, List.of("r0", "r9")),+ new Case("sgt", """+ r1 =2; r2 =-1;+ r10l=2; r11l=-1;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntSLessOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 s< r2;+ r9l = r10l s< r11l;+ """),+ List.of(+ new Case("lt", """+ r1 =1; r2 =2;+ r10l=1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("slt", """+ r1 =-1; r2 =2;+ r10l=-1; r11l=2;+ """, List.of("r0", "r9")),+ new Case("eq", """+ r1 =1; r2 =1;+ r10l=1; r11l=1;+ """, List.of("r0", "r9")),+ new Case("gt", """+ r1 =2; r2 =1;+ r10l=2; r11l=1;+ """, List.of("r0", "r9")),+ new Case("sgt", """+ r1 =2; r2 =-1;+ r10l=2; r11l=-1;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntCarryOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = carry(r1, r2);+ r9l = carry(r10l, r11l);+ """),+ List.of(+ new Case("f", """+ r1 =0x1000000000000000; r2 =0x0100000000000000;+ r10l=0x10000000; r11l=0x01000000;+ """, List.of("r0", "r9")),+ new Case("t", """+ r1 =0x1000000000000000; r2 =0x1000000000000000;+ r10l=0x10000000; r11l=0x10000000;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntSCarryOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = carry(r1, r2);+ r9l = carry(r10l, r11l);+ """),+ List.of(+ new Case("f", """+ r1 =0x1000000000000000; r2 =0x0100000000000000;+ r10l=0x10000000; r11l=0x01000000;+ """, List.of("r0", "r9")),+ new Case("t", """+ r1 =0x0100000000000000; r2 =0x0100000000000000;+ r10l=0x01000000; r11l=0x01000000;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntSBorrowOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = sborrow(r1, r2);+ r9l = sborrow(r10l, r11l);+ """),+ List.of(+ new Case("f", """+ r1 =0x1000000000000000; r2 =0x0100000000000000;+ r10l=0x10000000; r11l=0x01000000;+ """, List.of("r0", "r9")),+ new Case("t", """+ r1 =0x1100000000000000; r2 =0x0100000000000000;+ r10l=0x11000000; r11l=0x01000000;+ """, List.of("r0", "r9"))));+ }++ @Test+ public void testIntLeftOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 << r2;+ r3 = r4 << r5l;+ r6l = r7l << r8;+ r9l = r10l << r11l;+ """),+ List.of(+ new Case("posLposR", """+ r1 =100; r2 =4;+ r4 =100; r5l =4;+ r7l =100; r8 =4;+ r10l=100; r11l=4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("posLbigR", """+ r1 =100; r2 =0x100000004;+ r4 =100; r5l =0x100000004;+ r7l =100; r8 =0x100000004;+ r10l=100; r11l=0x100000004;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("posLnegR", """+ r1 =100; r2 =-4;+ r4 =100; r5l =-4;+ r7l =100; r8 =-4;+ r10l=100; r11l=-4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("negLposR", """+ r1 =-100; r2 =4;+ r4 =-100; r5l =4;+ r7l =-100; r8 =4;+ r10l=-100; r11l=4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("negLnegR", """+ r1 =-100; r2 =-4;+ r4 =-100; r5l =-4;+ r7l =-100; r8 =-4;+ r10l=-100; r11l=-4;+ """, List.of("r0", "r3", "r6", "r9"))));+ }++ @Test+ public void testIntRightOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 >> r2;+ r3 = r4 >> r5l;+ r6l = r7l >> r8;+ r9l = r10l >> r11l;+ """),+ List.of(+ new Case("posLposR", """+ r1 =100; r2 =4;+ r4 =100; r5l =4;+ r7l =100; r8 =4;+ r10l=100; r11l=4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("posLbigR", """+ r1 =100; r2 =0x100000004;+ r4 =100; r5l =0x100000004;+ r7l =100; r8 =0x100000004;+ r10l=100; r11l=0x100000004;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("posLnegR", """+ r1 =100; r2 =-4;+ r4 =100; r5l =-4;+ r7l =100; r8 =-4;+ r10l=100; r11l=-4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("negLposR", """+ r1 =-100; r2 =4;+ r4 =-100; r5l =4;+ r7l =-100; r8 =4;+ r10l=-100; r11l=4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("negLnegR", """+ r1 =-100; r2 =-4;+ r4 =-100; r5l =-4;+ r7l =-100; r8 =-4;+ r10l=-100; r11l=-4;+ """, List.of("r0", "r3", "r6", "r9"))));+ }++ @Test+ public void testIntSRightOpGen() throws Exception {+ runEquivalenceTest(translateSleigh(ID_TOYBE64, """+ r0 = r1 s>> r2;+ r3 = r4 s>> r5l;+ r6l = r7l s>> r8;+ r9l = r10l s>> r11l;+ """),+ List.of(+ new Case("posLposR", """+ r1 =100; r2 =4;+ r4 =100; r5l =4;+ r7l =100; r8 =4;+ r10l=100; r11l=4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("posLbigR", """+ r1 =100; r2 =0x100000004;+ r4 =100; r5l =0x100000004;+ r7l =100; r8 =0x100000004;+ r10l=100; r11l=0x100000004;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("posLnegR", """+ r1 =100; r2 =-4;+ r4 =100; r5l =-4;+ r7l =100; r8 =-4;+ r10l=100; r11l=-4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("negLposR", """+ r1 =-100; r2 =4;+ r4 =-100; r5l =4;+ r7l =-100; r8 =4;+ r10l=-100; r11l=4;+ """, List.of("r0", "r3", "r6", "r9")),+ new Case("negLnegR", """+ r1 =-100; r2 =-4;+ r4 =-100; r5l =-4;+ r7l =-100; r8 =-4;+ r10l=-100; r11l=-4;+ """, List.of("r0", "r3", "r6", "r9"))));+ }++ @Test+ public void testFloatAsOffset() throws Exception {+ int fDot5 = Float.floatToRawIntBits(0.5f);+ int f1Dot0 = Float.floatToRawIntBits(1.0f);+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:4 = 0x%x f+ 0x%x;+ temp2:8 = *temp;+ """.formatted(fDot5, fDot5));+ Varnode temp2 = tr.program.getCode().get(1).getOutput();+ assertTrue(temp2.isUnique());+ tr.setLongMemVal(f1Dot0, LONG_CONST, 8);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp2));+ }++ @Test+ public void testDoubleAsOffset() throws Exception {+ long dDot5 = Double.doubleToRawLongBits(0.5);+ long d1Dot0 = Double.doubleToRawLongBits(1.0);+ Translation tr = translateSleigh(ID_TOYBE64, """+ temp:8 = 0x%x f+ 0x%x;+ temp2:8 = *temp;+ """.formatted(dDot5, dDot5));+ Varnode temp2 = tr.program.getCode().get(1).getOutput();+ assertTrue(temp2.isUnique());+ tr.setLongMemVal(d1Dot0, LONG_CONST, 8);+ tr.runFallthrough();+ assertEquals(LONG_CONST, tr.getLongVnVal(temp2));+ }++ @Test+ public void testArmThumbFunc() throws Exception {+ AssemblyBuffer asm = createBuffer(ID_ARMv8LE, 0x00400000);++ Language language = asm.getAssembler().getLanguage();+ Register regCtx = language.getContextBaseRegister();+ Register regT = language.getRegister("T");+ RegisterValue rvDefault = new RegisterValue(regCtx,+ asm.getAssembler().getContextAt(asm.getNext()).toBigInteger(regCtx.getNumBytes()));+ RegisterValue rvArm = rvDefault.assign(regT, BigInteger.ZERO);+ RegisterValue rvThumb = rvDefault.assign(regT, BigInteger.ONE);++ AssemblyPatternBlock ctxThumb = AssemblyPatternBlock.fromRegisterValue(rvThumb);++ asm.assemble("mov r1, #456");+ Address addrBlx = asm.getNext();+ asm.assemble("blx 0x0");+ Address addrRet = asm.getNext(); // The address where we expect to return+ asm.assemble("bx lr"); // Follows CALL, so principally, must be here, but not decoded+ Address addrThumb = asm.getNext();+ asm.assemble("add r0, r1", ctxThumb);+ asm.assemble("bx lr", ctxThumb);++ asm.assemble(addrBlx, "blx 0x%s".formatted(addrThumb));++ Translation tr = translateBuffer(asm, asm.getEntry(), Map.of());++ assertEquals(Map.ofEntries(+ tr.entryPrototype(asm.getEntry(), rvArm, 0),+ tr.entryPrototype(addrThumb, rvThumb, 1)),+ tr.passageCls.getBlockEntries());++ /**+ * The blx will be a direct branch, so that will get executed in the bytecode. However, the+ * bx lr (from THUMB) will be an indirect jump, causing a passage exit, so we should expect+ * the return value to be the address immediately after the blx. Of course, that's not all+ * that convincing.... So, we'll assert that r0 was set, too.+ */+ assertEquals(addrRet.getOffset(), tr.runClean());+ assertEquals(456, tr.getLongRegVal("r0"));+ }++ /**+ * This is more diagnostics, but at the least, I should document that it doesn't work as+ * expected, or perhaps just turn it completely off.+ */+ @Test+ @Ignore("TODO")+ public void testUninitializedVsInitializedReads() {+ TODO();+ }++ @Test+ public void testExitAsThumb() throws Exception {+ Translation tr = translateLang(ID_ARMv8LE, 0x00400000, """+ blx 0x00500000+ """, Map.of());+ Language language = tr.state.getLanguage();+ Register regCtx = language.getContextBaseRegister();+ Register regT = language.getRegister("T");++ tr.runDecodeErr(0x00500000);+ RegisterValue actualCtx = tr.getRegVal(regCtx);+ RegisterValue expectedCtx = actualCtx.assign(regT, BigInteger.ONE);+ assertEquals(expectedCtx, actualCtx);+ }++ @Test+ public void testDelaySlot() throws Exception {+ Translation tr = translateLang(ID_TOYBE64, 0x00400000, """+ brds r0+ imm r0, #123+ """, Map.of());+ tr.setLongRegVal("r0", 0x1234);+ assertEquals(0x1234, tr.runClean());+ assertEquals(123, tr.getLongRegVal("r0"));+ }++ @Test+ public void testX86OffcutJump() throws Exception {+ Translation tr = translateLang(ID_X8664, 0x00400000, """+ .emit eb ff c0+ CALL 0x0dedbeef+ """.formatted(LONG_CONST), Map.of());+ tr.runDecodeErr(0x0dedbeef);+ }++ @Test+ public void testEmuInjectionCallEmuSwi() throws Exception {+ Translation tr = translateLang(ID_TOYBE64, 0x00400000, """+ imm r0,#123+ add r0,#7+ """,+ Map.ofEntries(+ Map.entry(0x00400002L, "emu_swi();")));++ tr.runErr(InterruptPcodeExecutionException.class, "Execution hit breakpoint");++ /**+ * Two reasons we don't reach the add: 1) It's overridden, and there's no deferral to the+ * decoded instruction. 2) Even if there were, we got interrupted before it executed.+ */+ assertEquals(123, tr.getLongRegVal("r0"));+ }++ @Test+ public void testEmuInjectionCallEmuExecDecoded() throws Exception {+ Translation tr = translateLang(ID_TOYBE64, 0x00400000, """+ imm r0,#123+ add r0,#7+ """,+ Map.ofEntries(+ Map.entry(0x00400002L, """+ r1 = sleigh_userop(r0, 4:8);+ emu_exec_decoded();+ """)));++ tr.runDecodeErr(0x00400004);+ assertEquals(123 + 7, tr.getLongRegVal("r0"));+ assertEquals(123 * 2 + 4, tr.getLongRegVal("r1"));+ }++ @Test+ public void testEmuInjectionCallEmuSkipDecoded() throws Exception {+ Translation tr = translateLang(ID_TOYBE64, 0x00400000, """+ imm r0,#123+ add r0,#7+ """,+ Map.ofEntries(+ Map.entry(0x00400002L, """+ r1 = sleigh_userop(r0, 4:8);+ emu_skip_decoded();+ """)));++ tr.runDecodeErr(0x00400004);+ assertEquals(123, tr.getLongRegVal("r0"));+ assertEquals(123 * 2 + 4, tr.getLongRegVal("r1"));+ }++ @Test+ public void testFlagOpsRemoved() throws Exception {+ Translation tr = translateLang(ID_TOYBE64, 0x00400000, """+ add r0,#6+ add r0,#7+ """, Map.of());++ tr.runDecodeErr(0x00400004);+ assertEquals(13, tr.getLongRegVal("r0"));++ long countSCarrys = Stream.of(tr.run.instructions.toArray()).filter(i -> {+ if (!(i instanceof MethodInsnNode mi)) {+ return false;+ }+ return "sCarryLongRaw".equals(mi.name);+ }).count();+ assertEquals(1, countSCarrys);+ }+}diff --git a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.html b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.htmlindex e504550416..b1929f6147 100644--- a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.html+++ b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.html@@ -634,47 +634,46 @@ class="sourceCode numberSource java numberLines"><code class="sourceCode java"><<span id="cb7-39"><a href="#cb7-39"></a> <span class="op">}</span></span><span id="cb7-40"><a href="#cb7-40"></a></span><span id="cb7-41"><a href="#cb7-41"></a> <span class="at">@Override</span></span>-<span id="cb7-42"><a href="#cb7-42"></a> <span class="kw">public</span> Expr <span class="fu">modBeforeStore</span><span class="op">(</span><span class="dt">int</span> sizeout<span class="op">,</span> <span class="dt">int</span> sizeinAddress<span class="op">,</span> Expr inAddress<span class="op">,</span> <span class="dt">int</span> sizeinValue<span class="op">,</span></span>+<span id="cb7-42"><a href="#cb7-42"></a> <span class="kw">public</span> Expr <span class="fu">modBeforeStore</span><span class="op">(</span><span class="dt">int</span> sizeinAddress<span class="op">,</span> Expr inAddress<span class="op">,</span> <span class="dt">int</span> sizeinValue<span class="op">,</span></span><span id="cb7-43"><a href="#cb7-43"></a> Expr inValue<span class="op">)</span> <span class="op">{</span></span><span id="cb7-44"><a href="#cb7-44"></a> <span class="cf">return</span> inValue<span class="op">;</span></span><span id="cb7-45"><a href="#cb7-45"></a> <span class="op">}</span></span><span id="cb7-46"><a href="#cb7-46"></a></span><span id="cb7-47"><a href="#cb7-47"></a> <span class="at">@Override</span></span>-<span id="cb7-48"><a href="#cb7-48"></a> <span class="kw">public</span> Expr <span class="fu">modAfterLoad</span><span class="op">(</span><span class="dt">int</span> sizeout<span class="op">,</span> <span class="dt">int</span> sizeinAddress<span class="op">,</span> Expr inAddress<span class="op">,</span> <span class="dt">int</span> sizeinValue<span class="op">,</span></span>-<span id="cb7-49"><a href="#cb7-49"></a> Expr inValue<span class="op">)</span> <span class="op">{</span></span>-<span id="cb7-50"><a href="#cb7-50"></a> <span class="cf">return</span> inValue<span class="op">;</span></span>-<span id="cb7-51"><a href="#cb7-51"></a> <span class="op">}</span></span>-<span id="cb7-52"><a href="#cb7-52"></a></span>-<span id="cb7-53"><a href="#cb7-53"></a> <span class="at">@Override</span></span>-<span id="cb7-54"><a href="#cb7-54"></a> <span class="kw">public</span> Expr <span class="fu">fromConst</span><span class="op">(</span><span class="dt">byte</span><span class="op">[]</span> value<span class="op">)</span> <span class="op">{</span></span>-<span id="cb7-55"><a href="#cb7-55"></a> <span class="cf">if</span> <span class="op">(</span>endian<span class="op">.</span><span class="fu">isBigEndian</span><span class="op">())</span> <span class="op">{</span></span>-<span id="cb7-56"><a href="#cb7-56"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">LitExpr</span><span class="op">(</span><span class="kw">new</span> <span class="bu">BigInteger</span><span class="op">(</span><span class="dv">1</span><span class="op">,</span> value<span class="op">),</span> value<span class="op">.</span><span class="fu">length</span><span class="op">);</span></span>-<span id="cb7-57"><a href="#cb7-57"></a> <span class="op">}</span></span>-<span id="cb7-58"><a href="#cb7-58"></a> <span class="dt">byte</span><span class="op">[]</span> reversed <span class="op">=</span> <span class="bu">Arrays</span><span class="op">.</span><span class="fu">copyOf</span><span class="op">(</span>value<span class="op">,</span> value<span class="op">.</span><span class="fu">length</span><span class="op">);</span></span>-<span id="cb7-59"><a href="#cb7-59"></a> ArrayUtils<span class="op">.</span><span class="fu">reverse</span><span class="op">(</span>reversed<span class="op">);</span></span>-<span id="cb7-60"><a href="#cb7-60"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">LitExpr</span><span class="op">(</span><span class="kw">new</span> <span class="bu">BigInteger</span><span class="op">(</span><span class="dv">1</span><span class="op">,</span> reversed<span class="op">),</span> reversed<span class="op">.</span><span class="fu">length</span><span class="op">);</span></span>-<span id="cb7-61"><a href="#cb7-61"></a> <span class="op">}</span></span>-<span id="cb7-62"><a href="#cb7-62"></a></span>-<span id="cb7-63"><a href="#cb7-63"></a> <span class="at">@Override</span></span>-<span id="cb7-64"><a href="#cb7-64"></a> <span class="kw">public</span> Expr <span class="fu">fromConst</span><span class="op">(</span><span class="bu">BigInteger</span> value<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> <span class="dt">boolean</span> isContextreg<span class="op">)</span> <span class="op">{</span></span>-<span id="cb7-65"><a href="#cb7-65"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">LitExpr</span><span class="op">(</span>value<span class="op">,</span> size<span class="op">);</span></span>-<span id="cb7-66"><a href="#cb7-66"></a> <span class="op">}</span></span>-<span id="cb7-67"><a href="#cb7-67"></a></span>-<span id="cb7-68"><a href="#cb7-68"></a> <span class="at">@Override</span></span>-<span id="cb7-69"><a href="#cb7-69"></a> <span class="kw">public</span> Expr <span class="fu">fromConst</span><span class="op">(</span><span class="dt">long</span> value<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="op">{</span></span>-<span id="cb7-70"><a href="#cb7-70"></a> <span class="cf">return</span> <span class="fu">fromConst</span><span class="op">(</span><span class="bu">BigInteger</span><span class="op">.</span><span class="fu">valueOf</span><span class="op">(</span>value<span class="op">),</span> size<span class="op">);</span></span>-<span id="cb7-71"><a href="#cb7-71"></a> <span class="op">}</span></span>-<span id="cb7-72"><a href="#cb7-72"></a></span>-<span id="cb7-73"><a href="#cb7-73"></a> <span class="at">@Override</span></span>-<span id="cb7-74"><a href="#cb7-74"></a> <span class="kw">public</span> <span class="dt">byte</span><span class="op">[]</span> <span class="fu">toConcrete</span><span class="op">(</span>Expr value<span class="op">,</span> Purpose purpose<span class="op">)</span> <span class="op">{</span></span>-<span id="cb7-75"><a href="#cb7-75"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>-<span id="cb7-76"><a href="#cb7-76"></a> <span class="op">}</span></span>-<span id="cb7-77"><a href="#cb7-77"></a></span>-<span id="cb7-78"><a href="#cb7-78"></a> <span class="at">@Override</span></span>-<span id="cb7-79"><a href="#cb7-79"></a> <span class="kw">public</span> <span class="dt">long</span> <span class="fu">sizeOf</span><span class="op">(</span>Expr value<span class="op">)</span> <span class="op">{</span></span>-<span id="cb7-80"><a href="#cb7-80"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>-<span id="cb7-81"><a href="#cb7-81"></a> <span class="op">}</span></span>-<span id="cb7-82"><a href="#cb7-82"></a><span class="op">}</span></span></code></pre></div>+<span id="cb7-48"><a href="#cb7-48"></a> <span class="kw">public</span> Expr <span class="fu">modAfterLoad</span><span class="op">(</span><span class="dt">int</span> sizeinAddress<span class="op">,</span> Expr inAddress<span class="op">,</span> <span class="dt">int</span> sizeinValue<span class="op">,</span> Expr inValue<span class="op">)</span> <span class="op">{</span></span>+<span id="cb7-49"><a href="#cb7-49"></a> <span class="cf">return</span> inValue<span class="op">;</span></span>+<span id="cb7-50"><a href="#cb7-50"></a> <span class="op">}</span></span>+<span id="cb7-51"><a href="#cb7-51"></a></span>+<span id="cb7-52"><a href="#cb7-52"></a> <span class="at">@Override</span></span>+<span id="cb7-53"><a href="#cb7-53"></a> <span class="kw">public</span> Expr <span class="fu">fromConst</span><span class="op">(</span><span class="dt">byte</span><span class="op">[]</span> value<span class="op">)</span> <span class="op">{</span></span>+<span id="cb7-54"><a href="#cb7-54"></a> <span class="cf">if</span> <span class="op">(</span>endian<span class="op">.</span><span class="fu">isBigEndian</span><span class="op">())</span> <span class="op">{</span></span>+<span id="cb7-55"><a href="#cb7-55"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">LitExpr</span><span class="op">(</span><span class="kw">new</span> <span class="bu">BigInteger</span><span class="op">(</span><span class="dv">1</span><span class="op">,</span> value<span class="op">),</span> value<span class="op">.</span><span class="fu">length</span><span class="op">);</span></span>+<span id="cb7-56"><a href="#cb7-56"></a> <span class="op">}</span></span>+<span id="cb7-57"><a href="#cb7-57"></a> <span class="dt">byte</span><span class="op">[]</span> reversed <span class="op">=</span> <span class="bu">Arrays</span><span class="op">.</span><span class="fu">copyOf</span><span class="op">(</span>value<span class="op">,</span> value<span class="op">.</span><span class="fu">length</span><span class="op">);</span></span>+<span id="cb7-58"><a href="#cb7-58"></a> ArrayUtils<span class="op">.</span><span class="fu">reverse</span><span class="op">(</span>reversed<span class="op">);</span></span>+<span id="cb7-59"><a href="#cb7-59"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">LitExpr</span><span class="op">(</span><span class="kw">new</span> <span class="bu">BigInteger</span><span class="op">(</span><span class="dv">1</span><span class="op">,</span> reversed<span class="op">),</span> reversed<span class="op">.</span><span class="fu">length</span><span class="op">);</span></span>+<span id="cb7-60"><a href="#cb7-60"></a> <span class="op">}</span></span>+<span id="cb7-61"><a href="#cb7-61"></a></span>+<span id="cb7-62"><a href="#cb7-62"></a> <span class="at">@Override</span></span>+<span id="cb7-63"><a href="#cb7-63"></a> <span class="kw">public</span> Expr <span class="fu">fromConst</span><span class="op">(</span><span class="bu">BigInteger</span> value<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> <span class="dt">boolean</span> isContextreg<span class="op">)</span> <span class="op">{</span></span>+<span id="cb7-64"><a href="#cb7-64"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">LitExpr</span><span class="op">(</span>value<span class="op">,</span> size<span class="op">);</span></span>+<span id="cb7-65"><a href="#cb7-65"></a> <span class="op">}</span></span>+<span id="cb7-66"><a href="#cb7-66"></a></span>+<span id="cb7-67"><a href="#cb7-67"></a> <span class="at">@Override</span></span>+<span id="cb7-68"><a href="#cb7-68"></a> <span class="kw">public</span> Expr <span class="fu">fromConst</span><span class="op">(</span><span class="dt">long</span> value<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="op">{</span></span>+<span id="cb7-69"><a href="#cb7-69"></a> <span class="cf">return</span> <span class="fu">fromConst</span><span class="op">(</span><span class="bu">BigInteger</span><span class="op">.</span><span class="fu">valueOf</span><span class="op">(</span>value<span class="op">),</span> size<span class="op">);</span></span>+<span id="cb7-70"><a href="#cb7-70"></a> <span class="op">}</span></span>+<span id="cb7-71"><a href="#cb7-71"></a></span>+<span id="cb7-72"><a href="#cb7-72"></a> <span class="at">@Override</span></span>+<span id="cb7-73"><a href="#cb7-73"></a> <span class="kw">public</span> <span class="dt">byte</span><span class="op">[]</span> <span class="fu">toConcrete</span><span class="op">(</span>Expr value<span class="op">,</span> Purpose purpose<span class="op">)</span> <span class="op">{</span></span>+<span id="cb7-74"><a href="#cb7-74"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>+<span id="cb7-75"><a href="#cb7-75"></a> <span class="op">}</span></span>+<span id="cb7-76"><a href="#cb7-76"></a></span>+<span id="cb7-77"><a href="#cb7-77"></a> <span class="at">@Override</span></span>+<span id="cb7-78"><a href="#cb7-78"></a> <span class="kw">public</span> <span class="dt">long</span> <span class="fu">sizeOf</span><span class="op">(</span>Expr value<span class="op">)</span> <span class="op">{</span></span>+<span id="cb7-79"><a href="#cb7-79"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>+<span id="cb7-80"><a href="#cb7-80"></a> <span class="op">}</span></span>+<span id="cb7-81"><a href="#cb7-81"></a><span class="op">}</span></span></code></pre></div><p>We have implemented two arithmetic models: one for big-endianlanguages and one for little-endian. The endianness comes into play whenwe encode constant values passed to <code>fromConst()</code>. We mustdiff --git a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.md b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.mdindex f1d20623bb..aa5931a2ea 100644--- a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.md+++ b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.md@@ -435,14 +435,14 @@ public enum ExprPcodeArithmetic implements PcodeArithmetic<Expr> {}@Override- public Expr modBeforeStore(int sizeout, int sizeinAddress, Expr inAddress, int sizeinValue,- Expr inValue) {+ public Expr modBeforeStore(int sizeinOffset, AddressSpace space, Expr inOffset,+ int sizeinValue, Expr inValue) {return inValue;}@Override- public Expr modAfterLoad(int sizeout, int sizeinAddress, Expr inAddress, int sizeinValue,- Expr inValue) {+ public Expr modAfterLoad(int sizeinOffset, AddressSpace space, Expr inOffset,+ int sizeinValue, Expr inValue) {return inValue;}@@ -497,8 +497,8 @@ They provide an opportunity to capture dereferencing information.We do not need that information, so we just return the value.The `mod` methods tread a bit into storage and addressing, which we cover more thoroughly later, but they model memory operations to the extent they do not actually require a storage mechanism.For example, were this a dynamic taint analyzer, we could use `modAfterLoad()` to record that a value was retrieved via a tainted address.-The `inValue` parameter gives the `Expr` actually retrieved from the emulator's storage, and `inAddress` gives the address (really just the `Expr` piece) used to retrieve it.-Conversely, in `modBeforeStore()`, `inValue` gives the value about to be stored, and `inAddress` gives the address used to store it.+The `inValue` parameter gives the `Expr` actually retrieved from the emulator's storage, and `inOffset` gives the offset used to retrieve it.+Conversely, in `modBeforeStore()`, `inValue` gives the value about to be stored, and `inOffset` gives the offset used to store it.We implement neither `toConcrete()` nor `sizeOf()`.Since we will be augmenting a concrete emulator, these methods will be provided by the concrete piece.diff --git a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.java b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.javaindex f2ef831912..016aebb1bd 100644--- a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.java+++ b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.java@@ -270,14 +270,14 @@ public class ModelingScript extends GhidraScript {}@Override- public Expr modBeforeStore(int sizeout, int sizeinAddress, Expr inAddress, int sizeinValue,- Expr inValue) {+ public Expr modBeforeStore(int sizeinOffset, AddressSpace space, Expr inOffset,+ int sizeinValue, Expr inValue) {return inValue;}@Override- public Expr modAfterLoad(int sizeout, int sizeinAddress, Expr inAddress, int sizeinValue,- Expr inValue) {+ public Expr modAfterLoad(int sizeinOffset, AddressSpace space, Expr inOffset,+ int sizeinValue, Expr inValue) {return inValue;}