Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-5976: Implement constant folding and other optimizations in JIT emulator.

Dan9d186a3e30ef
diff --git a/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintEmuUnixFileSystem.java b/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintEmuUnixFileSystem.java
index a7e95c857f..c11eff3ce1 100644
--- a/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintEmuUnixFileSystem.java
+++ b/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintEmuUnixFileSystem.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.
@@ -31,13 +31,13 @@ public class TaintEmuUnixFileSystem extends AbstractEmuUnixFileSystem<Pair<byte[
*/
public static class UntaintedFileContents implements EmuFileContents<TaintVec> {
@Override
- public long read(long offset, TaintVec buf, long fileSize) {
+ public int read(long offset, TaintVec buf, long fileSize) {
buf.setEmpties();
return buf.length;
}
@Override
- public long write(long offset, TaintVec buf, long curSize) {
+ public int write(long offset, TaintVec buf, long curSize) {
return 0; // I don't care
}
@@ -57,13 +57,13 @@ public class TaintEmuUnixFileSystem extends AbstractEmuUnixFileSystem<Pair<byte[
}
@Override
- public long read(long offset, TaintVec buf, long fileSize) {
+ public int read(long offset, TaintVec buf, long fileSize) {
buf.setArray(filename, offset);
return buf.length;
}
@Override
- public long write(long offset, TaintVec buf, long curSize) {
+ public int write(long offset, TaintVec buf, long curSize) {
return 0; // I don't care
}
diff --git a/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintFileReadsLinuxAmd64SyscallLibrary.java b/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintFileReadsLinuxAmd64SyscallLibrary.java
index 51859b4bf1..431987c6a5 100644
--- a/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintFileReadsLinuxAmd64SyscallLibrary.java
+++ b/Ghidra/Debug/TaintAnalysis/src/main/java/ghidra/pcode/emu/taint/lib/TaintFileReadsLinuxAmd64SyscallLibrary.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.
@@ -27,14 +27,11 @@ import ghidra.taint.model.TaintVec;
/**
* A library for performing Taint Analysis on a Linux-amd64 program that reads from tainted files
- *
* <p>
* This library is not currently accessible from the UI. It can be used with scripts by overriding a
* taint emulator's userop library factory method.
- *
* <p>
* TODO: A means of adding and configuring userop libraries in the UI.
- *
* <p>
* TODO: Example scripts.
*/
@@ -51,12 +48,14 @@ public class TaintFileReadsLinuxAmd64SyscallLibrary
super(machine, fs, program);
}
- @Override
- public Pair<byte[], TaintVec> unix_read(PcodeExecutorState<Pair<byte[], TaintVec>> state,
+ @PcodeUserop
+ @EmuSyscall(value = "read", override = true)
+ public Pair<byte[], TaintVec> unix_read(
+ @OpState PcodeExecutorState<Pair<byte[], TaintVec>> state,
Pair<byte[], TaintVec> fd, Pair<byte[], TaintVec> bufPtr,
Pair<byte[], TaintVec> count) {
- Pair<byte[], TaintVec> result = super.unix_read(state, fd, bufPtr, count);
+ Pair<byte[], TaintVec> result = abstract_unix_read(state, fd, bufPtr, count);
TaintVec taintResult = result.getRight();
// TODO: Some representation of a "min" function. For now, just mix everything
diff --git a/Ghidra/Features/SystemEmulation/ghidra_scripts/DebuggerEmuExampleScript.java b/Ghidra/Features/SystemEmulation/ghidra_scripts/DebuggerEmuExampleScript.java
index 436a143567..99b75fb282 100644
--- a/Ghidra/Features/SystemEmulation/ghidra_scripts/DebuggerEmuExampleScript.java
+++ b/Ghidra/Features/SystemEmulation/ghidra_scripts/DebuggerEmuExampleScript.java
@@ -80,7 +80,7 @@ public class DebuggerEmuExampleScript extends GhidraScript implements FlatDebugg
.getProjectData()
.getRootFolder()
.createFile("emu_example", program, monitor);
- try (Transaction tx = program.openTransaction("Init")) {
+ try (Transaction _ = program.openTransaction("Init")) {
AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
entry = space.getAddress(0x00400000);
Address dataEntry = space.getAddress(0x00600000);
@@ -167,7 +167,7 @@ public class DebuggerEmuExampleScript extends GhidraScript implements FlatDebugg
*/
TraceTimeManager time = trace.getTimeManager();
TraceSnapshot snapshot = time.getSnapshot(0, true);
- try (Transaction tx = trace.openTransaction("Emulate")) {
+ try (Transaction _ = trace.openTransaction("Emulate")) {
for (int i = 0; i < 10; i++) {
println("Executing: " + thread.getCounter());
thread.stepInstruction();
diff --git a/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoPcodeUseropLibrary.java b/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoPcodeUseropLibrary.java
index 1314f40d14..18bc4ed43e 100644
--- a/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoPcodeUseropLibrary.java
+++ b/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoPcodeUseropLibrary.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.
@@ -66,12 +66,12 @@ public class DemoPcodeUseropLibrary extends AnnotatedPcodeUseropLibrary<byte[]>
*
* <p>
* Because we want to dereference start, we will need access to the emulator's state, so we
- * employ the {@link OpState} annotation. {@code start} takes the one input we expect. Because
- * its type is the value type rather than {@link Varnode}, we will get the input's value.
- * Similarly, we can just return the resulting value, and the emulator will place that into the
- * output variable for us.
+ * employ the {@link ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.OpExecutor} annotation.
+ * {@code start} takes the one input we expect. Because its type is the value type rather than
+ * {@link Varnode}, we will get the input's value. Similarly, we can just return the resulting
+ * value, and the emulator will place that into the output variable for us.
*
- * @param state the calling thread's state
+ * @param executor the calling thread's executor
* @param start the offset of the first character
* @return the length of the string in bytes
*/
@@ -108,11 +108,9 @@ public class DemoPcodeUseropLibrary extends AnnotatedPcodeUseropLibrary<byte[]>
/**
* Not really a syscall dispatcher
- *
* <p>
* In cases where the userop expects parameters, you would annotate them with {@link Param}
* and use them just like other {@link Var}s. See the javadocs.
- *
* <p>
* This is just a cheesy demo: If RAX is 1, then this method computes the number of bytes in
* the C-style string pointed to by RCX and stores the result in RAX. Otherwise, interrupt
diff --git a/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoSyscallLibrary.java b/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoSyscallLibrary.java
index bca15ca36d..6387126d98 100644
--- a/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoSyscallLibrary.java
+++ b/Ghidra/Features/SystemEmulation/ghidra_scripts/DemoSyscallLibrary.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,28 +24,26 @@ import ghidra.pcode.emu.sys.AnnotatedEmuSyscallUseropLibrary;
import ghidra.pcode.emu.sys.EmuSyscallLibrary;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeArithmetic.Purpose;
-import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.pcode.struct.StructuredSleigh;
import ghidra.pcode.utils.Utils;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.data.DataTypeManager;
-import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.Program;
/**
* A userop library that includes system call simulation
- *
* <p>
* Such a library needs to implement {@link EmuSyscallLibrary}. Here we extend
* {@link AnnotatedEmuSyscallUseropLibrary}, which allows us to implement it using annotated
- * methods. {@link EmuSyscallLibrary#syscall(PcodeExecutor, PcodeUseropLibrary)} is the system call
- * dispatcher, and it requires that each system call implement {@link EmuSyscallDefinition}. System
- * call libraries typically implement that interface by annotating p-code userops with
- * {@link EmuSyscall}. This allows system calls to be implemented via Java callback or Structured
- * Sleigh. Conventionally, the Java method names of system calls should be
- * <em>platform</em>_<em>name</em>. This is to prevent name conflicts among userops when several
- * libraries are composed.
- *
+ * methods. {@link EmuSyscallLibrary#emu_syscall} is the system call dispatcher, and it requires
+ * that each system call implement
+ * {@link ghidra.pcode.emu.sys.EmuSyscallLibrary.EmuSyscallDefinition}. System call libraries
+ * typically implement that interface by annotating p-code userops with
+ * {@link ghidra.pcode.emu.sys.AnnotatedEmuSyscallUseropLibrary.EmuSyscall}. This allows system
+ * calls to be implemented via Java callback or Sleigh. Conventionally, the Java method names of
+ * system calls should be <em>platform</em>_<em>name</em>. This is to prevent name conflicts among
+ * userops when several libraries are composed.
* <p>
* Stock implementations for a limited set of Linux system calls are provided for x86 and amd64 in
* {@link EmuLinuxX86SyscallUseropLibrary} and {@link EmuLinuxAmd64SyscallUseropLibrary},
@@ -53,7 +51,6 @@ import ghidra.program.model.listing.Program;
* without (too much) code duplication. Because they derive from the annotation-based
* implementations, you can add missing system calls by extending one and adding annotated methods
* as needed.
- *
* <p>
* For demonstration, this will implement one from scratch for no particular operating system, but
* it will borrow many conventions from Linux-amd64.
@@ -61,74 +58,21 @@ import ghidra.program.model.listing.Program;
public class DemoSyscallLibrary extends AnnotatedEmuSyscallUseropLibrary<byte[]> {
private final static Charset UTF8 = Charset.forName("utf8");
- // Implement all the required plumbing first:
-
- /**
- * An exception type for "user errors." These errors should be communicated back to the target
- * program rather than causing the emulator to interrupt. This is a bare minimum implementation.
- * In practice more information should be communicated internally, in case things go further
- * wrong. Also, a hierarchy of exceptions may be appropriate.
- */
- static class UserError extends PcodeExecutionException {
- private final int errno;
-
- public UserError(int errno) {
- super("errno: " + errno);
- this.errno = errno;
- }
- }
-
- private final Register regRAX;
private final GhidraScript script;
/**
* Because the system call numbering is derived from the "syscall" overlay on OTHER space, a
* program is required. Use the system call analyzer on your program to populate this space. The
* program and its compiler spec are also used to derive (what it can of) the system call ABI.
- * Notably, it applies the calling convention of the functions placed in syscall overlay. Those
- * parts which cannot (yet) be derived from the program are instead implemented as abstract
- * methods of this class, e.g., {@link #readSyscallNumber(PcodeExecutorStatePiece)} and
- * {@link #handleError(PcodeExecutor, PcodeExecutionException)}.
+ * Notably, it applies the calling convention of the functions placed in the syscall overlay.
*
* @param machine the emulator
* @param program the program being emulated
+ * @param script the script
*/
public DemoSyscallLibrary(PcodeMachine<byte[]> machine, Program program, GhidraScript script) {
super(machine, program);
this.script = script;
- this.regRAX = machine.getLanguage().getRegister("RAX");
- if (regRAX == null) {
- throw new AssertionError("This library only works on x64 targets");
- }
- }
-
- /**
- * {@inheritDoc}
- *
- * The dispatcher doesn't know where the system call number is stored. It relies on this method
- * to read that number from the state. Here we'll assume the target is x64 and RAX contains the
- * syscall number.
- */
- @Override
- public long readSyscallNumber(PcodeExecutorState<byte[]> state, Reason reason) {
- return Utils.bytesToLong(state.getVar(regRAX, reason), regRAX.getNumBytes(),
- machine.getLanguage().isBigEndian());
- }
-
- /**
- * If the error is a user error, put the errno into the machine as expected by the target
- * program. Here we negate the errno and put it into RAX. If it's not a user error, we return
- * false letting the dispatcher know it should interrupt the emulator.
- */
- @Override
- public boolean handleError(PcodeExecutor<byte[]> executor, PcodeExecutionException err) {
- if (err instanceof UserError) {
- executor.getState()
- .setVar(regRAX, executor.getArithmetic()
- .fromConst(-((UserError) err).errno, regRAX.getNumBytes()));
- return true;
- }
- return false;
}
/**
@@ -152,31 +96,28 @@ public class DemoSyscallLibrary extends AnnotatedEmuSyscallUseropLibrary<byte[]>
/**
* Write a buffer of utf-8 characters to the console
- *
* <p>
- * The {@link EmuSyscall} annotation allows us to specify the system call name, because the
- * userop name should be prefixed with the platform name, to avoid naming collisions among
- * composed libraries.
- *
+ * The {@link ghidra.pcode.emu.sys.AnnotatedEmuSyscallUseropLibrary.EmuSyscall} annotation
+ * allows us to specify the system call name, because the userop name should be prefixed with
+ * the platform name, to avoid naming collisions among composed libraries.
* <p>
* For demonstration, we will export this as a system call, though that is not required for
* {@link DemoStructuredPart#demo_console(StructuredSleigh.Var)} to invoke it. It does need to
* be a userop, but it doesn't need to be a syscall.
*
+ * @param executor the emulator's underlying p-code executor
* @param str a pointer to the start of the buffer
* @param end a pointer to the end (exclusive) of the buffer
+ * @implNote Because we have concrete {@code byte[]}, we could use {@link Utils#bytesToLong},
+ * but for demonstration, here's how it can be done if we extended
+ * {@link AnnotatedEmuSyscallUseropLibrary}{@code <T>} instead. If the value cannot be
+ * made concrete, an exception will be thrown. For abstract types, it's a good idea to
+ * save a copy of the arithmetic as a field at library construction time.
*/
@PcodeUserop
@EmuSyscall("write")
public void demo_write(@OpExecutor PcodeExecutor<byte[]> executor, byte[] str, byte[] end) {
AddressSpace space = machine.getLanguage().getDefaultSpace();
- /**
- * Because we have concrete {@code byte[]}, we could use Utils.bytesToLong, but for
- * demonstration, here's how it can be done if we extended
- * {@link AnnotatedEmuSyscallUseropLibrary}{@code <T>} instead. If the value cannot be made
- * concrete, an exception will be thrown. For abstract types, it's a good idea to save a
- * copy of the arithmetic as a field at library construction time.
- */
PcodeArithmetic<byte[]> arithmetic = machine.getArithmetic();
long strLong = arithmetic.toLong(str, Purpose.LOAD);
long endLong = arithmetic.toLong(end, Purpose.OTHER);
@@ -191,7 +132,8 @@ public class DemoSyscallLibrary extends AnnotatedEmuSyscallUseropLibrary<byte[]>
/**
* The nested class for syscalls implemented using Structured Sleigh. Note that no matter the
- * implementation type, the Java method is annotated with {@link EmuSyscall}. We declare the
+ * implementation type, the Java method is annotated with
+ * {@link ghidra.pcode.emu.sys.AnnotatedEmuSyscallUseropLibrary.EmuSyscall}. We declare the
* class public so that the annotation processor can access the methods. Alternatively, we could
* override {@link #getMethodLookup()} to provide the processor private access.
*/
@@ -218,4 +160,13 @@ public class DemoSyscallLibrary extends AnnotatedEmuSyscallUseropLibrary<byte[]>
write.call(str, end);
}
}
+
+ // Finally, the actual syscall userop, which we implement in plain Sleigh.
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition syscall(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
+ RAX = emu_syscall(RAX);
+ """).build();
+ }
}
diff --git a/Ghidra/Features/SystemEmulation/ghidra_scripts/EmuDeskCheckScript.java b/Ghidra/Features/SystemEmulation/ghidra_scripts/EmuDeskCheckScript.java
index 4559616de9..3c0a45b817 100644
--- a/Ghidra/Features/SystemEmulation/ghidra_scripts/EmuDeskCheckScript.java
+++ b/Ghidra/Features/SystemEmulation/ghidra_scripts/EmuDeskCheckScript.java
@@ -32,6 +32,7 @@ import ghidra.pcode.emu.BytesPcodeThread;
import ghidra.pcode.emu.PcodeEmulator;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
import ghidra.pcode.exec.trace.TraceEmulationIntegration.Writer;
import ghidra.pcode.struct.StructuredSleigh;
import ghidra.pcode.utils.Utils;
@@ -169,8 +170,9 @@ public class EmuDeskCheckScript extends GhidraScript implements FlatDebuggerAPI
}
};
- for (SleighPcodeUseropDefinition<?> inject : new Injects().generate().values()) {
- String source = inject.getBody();
+ for (PcodeUseropDefinition<?> inject : new Injects().generate().values()) {
+ String source =
+ inject instanceof SleighPcodeUseropDefinition sleigh ? sleigh.getBody() : "(java)";
println("Injecting " + inject.getName() + ":\n" + source);
for (Symbol sym : currentProgram.getSymbolTable()
.getExternalSymbols(inject.getName())) {
@@ -190,9 +192,9 @@ public class EmuDeskCheckScript extends GhidraScript implements FlatDebuggerAPI
schedule.execute(trace, emu, monitor);
}
- ///////////////////////////////////////////
+ // ////////////////////////////////////////
// Configuration and support kruft below //
- ///////////////////////////////////////////
+ // ////////////////////////////////////////
public record Watch(String expression, TypeRec type, Settings settings) {}
diff --git a/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneStructuredSleighScript.java b/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneStructuredSleighScript.java
index 20bf2320f9..e5a72a3bca 100644
--- a/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneStructuredSleighScript.java
+++ b/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneStructuredSleighScript.java
@@ -28,7 +28,7 @@ import java.util.stream.Collectors;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.app.script.GhidraScript;
import ghidra.pcode.exec.FixedSleighPcodeUseropDefinition;
-import ghidra.pcode.exec.SleighPcodeUseropDefinition;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
import ghidra.pcode.exec.SleighPcodeUseropDefinition.SignatureDef;
import ghidra.pcode.struct.StructuredSleigh;
import ghidra.program.model.lang.LanguageID;
@@ -61,7 +61,7 @@ public class StandAloneStructuredSleighScript extends GhidraScript {
*/
language = (SleighLanguage) getLanguage(new LanguageID("DATA:BE:64:default"));
- Map<String, SleighPcodeUseropDefinition<Object>> ops = new LookupStructuredSleigh() {
+ Map<String, PcodeUseropDefinition<Object>> ops = new LookupStructuredSleigh() {
/**
* Add two in-memory vectors of 16 longs and store the result in memory
*
@@ -101,8 +101,8 @@ public class StandAloneStructuredSleighScript extends GhidraScript {
/*
* Now, dump the generated Sleigh source
*/
- for (SleighPcodeUseropDefinition<?> userop : ops.values()) {
- if (!(userop instanceof FixedSleighPcodeUseropDefinition<?> fixed)) {
+ for (PcodeUseropDefinition<?> userop : ops.values()) {
+ if (!(userop instanceof FixedSleighPcodeUseropDefinition fixed)) {
println("WARN: Unexpected userop type for " + userop.getName());
continue;
}
diff --git a/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneSyscallEmuExampleScript.java b/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneSyscallEmuExampleScript.java
index ad03ea3fba..72958f0e85 100644
--- a/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneSyscallEmuExampleScript.java
+++ b/Ghidra/Features/SystemEmulation/ghidra_scripts/StandAloneSyscallEmuExampleScript.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.
@@ -70,7 +70,7 @@ public class StandAloneSyscallEmuExampleScript extends GhidraScript {
program =
new ProgramDB("syscall_example", language,
language.getCompilerSpecByID(new CompilerSpecID("gcc")), this);
- try (Transaction tx = program.openTransaction("Init")) {
+ try (Transaction _ = program.openTransaction("Init")) {
AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
entry = space.getAddress(0x00400000);
Address dataEntry = space.getAddress(0x00600000);
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibrary.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibrary.java
index c3f4138623..95a89923ba 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibrary.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibrary.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,13 +24,10 @@ import ghidra.framework.Application;
import ghidra.pcode.emu.PcodeMachine;
import ghidra.pcode.emu.unix.EmuUnixFileSystem;
import ghidra.pcode.emu.unix.EmuUnixUser;
-import ghidra.pcode.exec.PcodeArithmetic.Purpose;
-import ghidra.pcode.exec.PcodeExecutor;
-import ghidra.pcode.exec.PcodeExecutorState;
-import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.program.model.data.DataTypeManager;
import ghidra.program.model.data.FileDataTypeManager;
-import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.Program;
/**
@@ -40,8 +37,6 @@ import ghidra.program.model.listing.Program;
*/
public class EmuLinuxAmd64SyscallUseropLibrary<T> extends AbstractEmuLinuxSyscallUseropLibrary<T> {
- protected final Register regRAX;
-
protected FileDataTypeManager clib64;
/**
@@ -55,7 +50,6 @@ public class EmuLinuxAmd64SyscallUseropLibrary<T> extends AbstractEmuLinuxSyscal
public EmuLinuxAmd64SyscallUseropLibrary(PcodeMachine<T> machine, EmuUnixFileSystem<T> fs,
Program program) {
super(machine, fs, program);
- regRAX = machine.getLanguage().getRegister("RAX");
}
/**
@@ -70,7 +64,6 @@ public class EmuLinuxAmd64SyscallUseropLibrary<T> extends AbstractEmuLinuxSyscal
public EmuLinuxAmd64SyscallUseropLibrary(PcodeMachine<T> machine, EmuUnixFileSystem<T> fs,
Program program, EmuUnixUser user) {
super(machine, fs, program, user);
- regRAX = machine.getLanguage().getRegister("RAX");
}
@Override
@@ -91,16 +84,10 @@ public class EmuLinuxAmd64SyscallUseropLibrary<T> extends AbstractEmuLinuxSyscal
clib64.close();
}
- @Override
- public long readSyscallNumber(PcodeExecutorState<T> state, Reason reason) {
- return machine.getArithmetic().toLong(state.getVar(regRAX, reason), Purpose.OTHER);
- }
-
- @Override
- protected boolean returnErrno(PcodeExecutor<T> executor, int errno) {
- executor.getState()
- .setVar(regRAX,
- executor.getArithmetic().fromConst(-errno, regRAX.getMinimumByteSize()));
- return true;
+ @PcodeUserop
+ public SleighPcodeUseropDefinition syscall(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
+ RAX = emu_syscall(RAX);
+ """).build();
}
}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibrary.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibrary.java
index 711f19e5a2..b80347bbb4 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibrary.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibrary.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,19 +20,18 @@ import java.util.Collection;
import java.util.List;
import generic.jar.ResourceFile;
+import ghidra.app.util.PseudoInstruction;
import ghidra.framework.Application;
-import ghidra.pcode.emu.DefaultPcodeThread.PcodeThreadExecutor;
import ghidra.pcode.emu.PcodeMachine;
+import ghidra.pcode.emu.jit.decode.CanDecode;
import ghidra.pcode.emu.unix.EmuUnixFileSystem;
import ghidra.pcode.emu.unix.EmuUnixUser;
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.data.DataTypeManager;
import ghidra.program.model.data.FileDataTypeManager;
-import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.Program;
-import ghidra.program.model.pcode.PcodeOp;
+import ghidra.program.model.pcode.Varnode;
/**
* A system call library simulating Linux for x86 (32-bit)
@@ -40,8 +39,6 @@ import ghidra.program.model.pcode.PcodeOp;
* @param <T> the type of values processed by the library
*/
public class EmuLinuxX86SyscallUseropLibrary<T> extends AbstractEmuLinuxSyscallUseropLibrary<T> {
- protected final Register regEIP;
- protected final Register regEAX;
protected FileDataTypeManager clib32;
@@ -70,8 +67,6 @@ public class EmuLinuxX86SyscallUseropLibrary<T> extends AbstractEmuLinuxSyscallU
public EmuLinuxX86SyscallUseropLibrary(PcodeMachine<T> machine, EmuUnixFileSystem<T> fs,
Program program, EmuUnixUser user) {
super(machine, fs, program, user);
- regEIP = machine.getLanguage().getRegister("EIP");
- regEAX = machine.getLanguage().getRegister("EAX");
}
@Override
@@ -92,45 +87,40 @@ public class EmuLinuxX86SyscallUseropLibrary<T> extends AbstractEmuLinuxSyscallU
clib32.close();
}
- @Override
- public long readSyscallNumber(PcodeExecutorState<T> state, Reason reason) {
- return machine.getArithmetic().toLong(state.getVar(regEAX, reason), Purpose.OTHER);
- }
-
- @Override
- protected boolean returnErrno(PcodeExecutor<T> executor, int errno) {
- executor.getState()
- .setVar(regEAX,
- executor.getArithmetic().fromConst(-errno, regEAX.getMinimumByteSize()));
- return true;
- }
-
/**
* Implement this to detect and interpret the {@code INT 0x80} instruction as the syscall
* convention
*
* @param executor to receive the executor
* @param library to receive the userop library, presumably replete with syscalls
- * @param number the interrupt number
- * @return the address of the fall-through, to hack the {@link PcodeOp#CALLIND}
+ * @param out the output varnode
+ * @param intNo the interrupt number
*/
- @PcodeUserop
- public T swi(@OpExecutor PcodeExecutor<T> executor, @OpLibrary PcodeUseropLibrary<T> library,
- T number) {
- PcodeArithmetic<T> arithmetic = executor.getArithmetic();
- long intNo = arithmetic.toLong(number, Purpose.OTHER);
+ @PcodeUserop(canInline = true)
+ public void swi(@OpExecutor PcodeExecutor<T> executor, @OpLibrary PcodeUseropLibrary<T> library,
+ @OpOutput Varnode out, int intNo) {
+ // A CALLIND follows to the return of swi().... OK.
+ // We'll just cause that to "fall through" instead
+ // Thus, we need the instruction, and we must compile invocation-specific p-code
if (intNo == 0x80) {
- // A CALLIND follows to the return of swi().... OK.
- // We'll just make that "fall through" instead
- T next = executor.getState().getVar(regEIP, executor.getReason());
- PcodeThreadExecutor<T> te = (PcodeThreadExecutor<T>) executor;
- int pcSize = regEIP.getNumBytes();
- int iLen = te.getThread().getInstruction().getLength();
- next = arithmetic.binaryOp(PcodeOp.INT_ADD, pcSize, pcSize, next, pcSize,
- arithmetic.fromConst(iLen, pcSize));
- syscall(executor, library);
- return next;
+ if (!(executor instanceof CanDecode decoder)) {
+ throw new PcodeExecutionException(
+ "Cannot interpret swi(0x80) without the instruction decoder");
+ }
+ PseudoInstruction instruction = decoder.decodeInstruction();
+ Address next = instruction.getAddress().add(instruction.getLength());
+ PcodeProgram prog =
+ SleighProgramCompiler.compileUserop(executor.getLanguage(), "swi",
+ List.of(SleighPcodeUseropDefinition.OUT_SYMBOL_NAME), """
+ EAX = emu_syscall(EAX);
+ %s = 0x%x;
+ """.formatted(
+ SleighPcodeUseropDefinition.OUT_SYMBOL_NAME, next.getOffset()),
+ library, List.of(out));
+ executor.execute(prog, library);
+ }
+ else {
+ throw new PcodeExecutionException("Unknown interrupt: 0x%x".formatted(intNo));
}
- throw new PcodeExecutionException("Unknown interrupt: 0x" + Long.toString(intNo, 16));
}
}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/AnnotatedEmuSyscallUseropLibrary.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/AnnotatedEmuSyscallUseropLibrary.java
index 6a9aa07e73..b8488358ed 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/AnnotatedEmuSyscallUseropLibrary.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/AnnotatedEmuSyscallUseropLibrary.java
@@ -35,7 +35,6 @@ import utilities.util.AnnotationUtilities;
/**
* A syscall library wherein Java methods are exported via a special annotated
- *
* <p>
* This library is both a system call and a sleigh userop library. To export a system call, it must
* also be exported as a sleigh userop. This is more conventional, as the system call dispatcher
@@ -55,9 +54,38 @@ public abstract class AnnotatedEmuSyscallUseropLibrary<T> extends AnnotatedPcode
return AnnotationUtilities.collectAnnotatedMethods(EmuSyscall.class, cls);
}
+ private static Method chooseOrThrow(Method m1, Method m2) {
+ Class<?> cls1 = m1.getDeclaringClass();
+ Class<?> cls2 = m2.getDeclaringClass();
+ if (cls1 != cls2) {
+ EmuSyscall an1 = m1.getAnnotation(EmuSyscall.class);
+ EmuSyscall an2 = m2.getAnnotation(EmuSyscall.class);
+ if (cls1.isAssignableFrom(cls2) && an2.override()) {
+ return m2;
+ }
+ if (cls2.isAssignableFrom(cls1) && an1.override()) {
+ return m1;
+ }
+ }
+ throw new IllegalArgumentException("Duplicate @" +
+ EmuSyscall.class.getSimpleName() + " annotated methods with name " + m1.getName());
+ }
+
+ private static Map<String, Method> resolveOverrides(Set<Method> methods) {
+ Map<String, Method> result = new HashMap<>();
+ for (Method method : methods) {
+ String name = method.getName();
+ Method exists = result.get(name);
+ if (exists != null) {
+ method = chooseOrThrow(exists, method);
+ }
+ result.put(name, method);
+ }
+ return result;
+ }
+
/**
* An annotation to export a method as a system call in the library.
- *
* <p>
* The method must also be exported in the userop library, likely via
* {@link ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.PcodeUserop @PcodeUserop}.
@@ -65,11 +93,25 @@ public abstract class AnnotatedEmuSyscallUseropLibrary<T> extends AnnotatedPcode
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EmuSyscall {
+ /**
+ * The name of the syscall, which must match the actual name given in the syscall map.
+ *
+ * @return the name
+ * @see EmuSyscallLibrary#loadSyscallNumberMap(String)
+ */
String value();
- }
- private final SyscallPcodeUseropDefinition<T> syscallUserop =
- new SyscallPcodeUseropDefinition<>(this);
+ /**
+ * Set to indicate this name overrides the same name inherited from any
+ * superclass/interface.
+ * <p>
+ * If names collide from the same class, or that from the extension class does not have this
+ * flag, an error occurs at library construction.
+ *
+ * @return true to allow overrides.
+ */
+ boolean override() default false;
+ }
protected final PcodeMachine<T> machine;
protected final CompilerSpec cSpec;
@@ -81,7 +123,11 @@ public abstract class AnnotatedEmuSyscallUseropLibrary<T> extends AnnotatedPcode
protected final Collection<DataTypeManager> additionalArchives;
/**
- * Construct a new library including the "syscall" userop
+ * Construct a new library including the "emu_syscall" userop
+ * <p>
+ * Note that the final library must export the system call entry point. Often, this is the
+ * "syscall" userop. That userop must read the system call number, pass it as an argument to
+ * "emu_syscall," and store the result according to the ABI of the target platform.
*
* @param machine the machine using this library
* @param program a program from which to derive syscall configuration, conventions, etc.
@@ -121,12 +167,12 @@ public abstract class AnnotatedEmuSyscallUseropLibrary<T> extends AnnotatedPcode
/**
* Export a userop as a system call
*
- * @param number the opIndex assigned to the userop
+ * @param number the syscall number
* @param opdef the userop
* @param convention the syscall calling convention for the emulated platform
* @return the syscall definition
*/
- public UseropEmuSyscallDefinition<T> newBoundSyscall(long number,
+ protected UseropEmuSyscallDefinition<T> newBoundSyscall(long number,
PcodeUseropDefinition<T> opdef, PrototypeModel convention) {
return new UseropEmuSyscallDefinition<>(number, opdef, program, convention, dtMachineWord);
}
@@ -136,8 +182,8 @@ public abstract class AnnotatedEmuSyscallUseropLibrary<T> extends AnnotatedPcode
new DualHashBidiMap<>(EmuSyscallLibrary.loadSyscallNumberMap(program));
Map<Long, PrototypeModel> mapConventions =
EmuSyscallLibrary.loadSyscallConventionMap(program);
- Set<Method> methods = collectSyscalls(cls);
- for (Method m : methods) {
+ Map<String, Method> methods = resolveOverrides(collectSyscalls(cls));
+ for (Method m : methods.values()) {
String name = m.getAnnotation(EmuSyscall.class).value();
Long number = mapNames.getKey(name);
if (number == null) {
@@ -151,12 +197,7 @@ public abstract class AnnotatedEmuSyscallUseropLibrary<T> extends AnnotatedPcode
" must also be a p-code userop");
}
PrototypeModel convention = mapConventions.get(number);
- EmuSyscallDefinition<T> existed =
- syscallMap.put(number, newBoundSyscall(number, opdef, convention));
- if (existed != null) {
- throw new IllegalArgumentException("Duplicate @" +
- EmuSyscall.class.getSimpleName() + " annotated methods with name " + name);
- }
+ syscallMap.put(number, newBoundSyscall(number, opdef, convention));
}
}
@@ -164,11 +205,6 @@ public abstract class AnnotatedEmuSyscallUseropLibrary<T> extends AnnotatedPcode
mapAndBindSyscalls(this.getClass());
}
- @Override
- public PcodeUseropDefinition<T> getSyscallUserop() {
- return syscallUserop;
- }
-
@Override
public Map<Long, EmuSyscallDefinition<T>> getSyscalls() {
return syscallMap;
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/BytesEmuFileContents.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/BytesEmuFileContents.java
index 3d8b891227..81cd3a54a8 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/BytesEmuFileContents.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/BytesEmuFileContents.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.
@@ -17,7 +17,6 @@ package ghidra.pcode.emu.sys;
/**
* A concrete in-memory bytes store for simulated file contents
- *
* <p>
* Note that currently, the total contents cannot exceed a Java array, so the file must remain less
* than 2GB in size.
@@ -28,21 +27,21 @@ public class BytesEmuFileContents implements EmuFileContents<byte[]> {
protected byte[] content = new byte[INIT_CONTENT_SIZE];
@Override
- public synchronized long read(long offset, byte[] buf, long fileSize) {
+ public synchronized int read(long offset, byte[] buf, long fileSize) {
// We're using an in-memory array, so limited to int offsets
if (offset > Integer.MAX_VALUE) {
throw new EmuIOException("Offset is past end of file");
}
- long len = Math.min(buf.length, fileSize - offset);
+ int len = (int) Math.min(buf.length, fileSize - offset);
if (len < 0) {
throw new EmuIOException("Offset is past end of file");
}
- System.arraycopy(content, (int) offset, buf, 0, (int) len);
+ System.arraycopy(content, (int) offset, buf, 0, len);
return len;
}
@Override
- public synchronized long write(long offset, byte[] buf, long curSize) {
+ public synchronized int write(long offset, byte[] buf, long curSize) {
long newSize = offset + buf.length;
if (newSize > Integer.MAX_VALUE || newSize < 0) {
throw new EmuIOException("File size cannot exceed " + Integer.MAX_VALUE + " bytes");
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuFileContents.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuFileContents.java
index cf2e5be28a..b61e614e68 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuFileContents.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuFileContents.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.
@@ -17,13 +17,11 @@ package ghidra.pcode.emu.sys;
/**
* The content store to back a simulated file
- *
* <p>
* TODO: Could/should this just be the same interface as an execute state? If so, we'd need to
* formalize the store interface and require one for each address space in the state. Sharing that
* interface may not be a good idea.... I think implementors can use a common realization if that
* suits them.
- *
* <p>
* TODO: Actually, a better idea might be to introduce an address factory with custom spaces into
* the emulator. Then a library/file could just create an address space and use the state to store
@@ -39,9 +37,9 @@ public interface EmuFileContents<T> {
* @param offset the offset in the file to read
* @param buf the destination buffer, whose size must be known
* @param fileSize the size of the file
- * @return the number of bytes (not necessarily concrete) read
+ * @return the number of bytes read
*/
- long read(long offset, T buf, long fileSize);
+ int read(long offset, T buf, long fileSize);
/**
* Write values from the given buffer into the file
@@ -49,13 +47,12 @@ public interface EmuFileContents<T> {
* @param offset the offset in the file to write
* @param buf the source buffer, whose size must be known
* @param curSize the current size of the file
- * @return the number of bytes (not necessarily concrete) written
+ * @return the number of bytes written
*/
- long write(long offset, T buf, long curSize);
+ int write(long offset, T buf, long curSize);
/**
* Erase the contents
- *
* <p>
* Note that the file's size will be set to 0, so actual erasure of the contents may not be
* necessary, but if the contents are expensive to store, they ought to be disposed.
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuProcessExitedException.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuProcessExitedException.java
index d4bde08d83..2bc964e439 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuProcessExitedException.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/EmuProcessExitedException.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.
@@ -30,7 +30,7 @@ import ghidra.pcode.exec.PcodeArithmetic.Purpose;
public class EmuProcessExitedException extends EmuSystemException {
/**
- * Attempt to concretize a value and convert it to hex
+ * Attempt to concretize a value and convert it to decimal
*
* @param <T> the type of the status
* @param arithmetic the arithmetic to operate on the value
@@ -51,20 +51,29 @@ public class EmuProcessExitedException extends EmuSystemException {
/**
* Construct a process-exited exception with the given status code
- *
* <p>
* This will attempt to concretize the status according to the given arithmetic, for display
* purposes. The original status remains accessible via {@link #getStatus()}
*
* @param <T> the type values processed by the library
* @param arithmetic the machine's arithmetic
- * @param status
+ * @param status the status code
*/
public <T> EmuProcessExitedException(PcodeArithmetic<T> arithmetic, T status) {
super("Process exited with status " + tryConcereteToString(arithmetic, status));
this.status = status;
}
+ /**
+ * Construct a process-exited exception with the given status code
+ *
+ * @param status the status code
+ */
+ public EmuProcessExitedException(long status) {
+ super("Process exited with status %d".formatted(status));
+ this.status = status;
+ }
+
/**
* Get the status code as a {@code T} of the throwing machine
*
diff --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.java
index f6a6268091..2577f71b00 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
@@ -16,16 +16,17 @@
package ghidra.pcode.emu.sys;
import java.io.*;
-import java.lang.reflect.Method;
-import java.util.*;
+import java.util.HashMap;
+import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import generic.jar.ResourceFile;
import ghidra.framework.Application;
+import ghidra.pcode.emu.jit.folding.MaskedBytes;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.*;
-import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.lang.PrototypeModel;
import ghidra.program.model.listing.Function;
@@ -36,16 +37,15 @@ import ghidra.program.model.symbol.*;
/**
* A library of system calls
- *
* <p>
* A system call library is a collection of p-code executable routines, invoked by a system call
* dispatcher. That dispatcher is represented by
- * {@link #syscall(PcodeExecutor, PcodeUseropLibrary)}, and is exported as a sleigh userop. If this
- * interface is "mixed in" with {@link AnnotatedPcodeUseropLibrary}, that userop is automatically
- * included in the userop library. The simplest means of implementing a syscall library is probably
- * via {@link AnnotatedEmuSyscallUseropLibrary}. It implements this interface and extends
- * {@link AnnotatedPcodeUseropLibrary}. In addition, it provides its own annotation system for
- * exporting userops as system calls.
+ * {@link #emu_syscall(PcodeExecutor, PcodeUseropLibrary, PcodeOp, Varnode)}, and is exported as a
+ * Sleigh userop. If this interface is "mixed in" with {@link AnnotatedPcodeUseropLibrary}, that
+ * userop is automatically included in the userop library. The simplest means of implementing a
+ * syscall library is probably via {@link AnnotatedEmuSyscallUseropLibrary}. It implements this
+ * interface and extends {@link AnnotatedPcodeUseropLibrary}. In addition, it provides its own
+ * annotation system for exporting userops as system calls.
*
* @param <T> the type of data processed by the system calls, typically {@code byte[]}
*/
@@ -143,77 +143,6 @@ public interface EmuSyscallLibrary<T> extends PcodeUseropLibrary<T> {
.collect(Collectors.toMap(Entry::getKey, e -> e.getValue().getCallingConvention()));
}
- /**
- * The {@link EmuSyscallLibrary#syscall(PcodeExecutor, PcodeUseropLibrary)} method wrapped as a
- * userop definition
- *
- * @param <T> the type of data processed by the userop, typically {@code byte[]}
- */
- final class SyscallPcodeUseropDefinition<T> implements PcodeUseropDefinition<T> {
- private final EmuSyscallLibrary<T> syslib;
-
- public SyscallPcodeUseropDefinition(EmuSyscallLibrary<T> syslib) {
- this.syslib = syslib;
- }
-
- @Override
- public String getName() {
- return "syscall";
- }
-
- @Override
- public int getInputCount() {
- return 0;
- }
-
- @Override
- public void execute(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library,
- PcodeOp op, Varnode outVar, List<Varnode> inVars) {
- syslib.syscall(executor, library);
- }
-
- @Override
- public boolean isFunctional() {
- return false;
- }
-
- @Override
- public boolean hasSideEffects() {
- return true;
- }
-
- @Override
- public boolean modifiesContext() {
- return false;
- }
-
- @Override
- public boolean canInlinePcode() {
- return false;
- }
-
- @Override
- public Class<?> getOutputType() {
- return void.class;
- }
-
- @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);
- }
- }
- }
-
/**
* The definition of a system call
*
@@ -230,83 +159,86 @@ public interface EmuSyscallLibrary<T> extends PcodeUseropLibrary<T> {
}
/**
- * In case this is not an {@link AnnotatedEmuSyscallUseropLibrary} or
- * {@link AnnotatedPcodeUseropLibrary}, get the definition of the "syscall" userop for inclusion
- * in the {@link PcodeUseropLibrary}.
- *
+ * A Java-callback implementation of "emu_syscall" that reads the syscall number and dispatches
+ * to the appropriate system call implementation at run time.
* <p>
- * Implementors may wish to override this to use a pre-constructed definition. That definition
- * can be easily constructed using {@link SyscallPcodeUseropDefinition}.
+ * This is the normal behavior for the interpretation-based p-code emulator anyway. However, for
+ * an execution engine that attempts to resolve system calls "just in time," it may be necessary
+ * to explicitly defer to this implementation to prevent any further attempt to resolve the
+ * system call, when it becomes impossible to do so.
*
- * @return the syscall userop definition
+ * @param executor the executor
+ * @param library the p-code userop library (often including exported system calls)
+ * @param syscallNumber the system call number
*/
- default PcodeUseropDefinition<T> getSyscallUserop() {
- return new SyscallPcodeUseropDefinition<>(this);
+ @PcodeUserop(canInline = false)
+ default void emu_rt_syscall(@OpExecutor PcodeExecutor<T> executor,
+ @OpLibrary PcodeUseropLibrary<T> library, long syscallNumber) {
+ EmuSyscallDefinition<T> syscall = getSyscalls().get(syscallNumber);
+ if (syscall == null) {
+ throw new EmuInvalidSystemCallException(syscallNumber);
+ }
+ syscall.invoke(executor, library);
}
/**
- * Retrieve the desired system call number according to the emulated system's conventions
- *
- * <p>
- * TODO: This should go away in favor of some specification stored in the emulated program
- * database. Until then, we require system-specific implementations.
- *
- * @param state the executor's state
- * @param reason the reason for reading state, probably {@link Reason#EXECUTE_READ}, but should
- * be taken from the executor
- * @return the system call number
- */
- long readSyscallNumber(PcodeExecutorState<T> state, Reason reason);
-
- /**
- * Try to handle an error, usually by returning it to the user program
- *
- * <p>
- * If the particular error was not expected, it is best practice to return false, causing the
- * emulator to interrupt. Otherwise, some state is set in the machine that, by convention,
- * communicates the error back to the user program.
- *
- * @param executor the executor for the thread that caused the error
- * @param err the error
- * @return true if execution can continue uninterrupted
+ * The Sleigh code to defer to run-time system call resolution
*/
- boolean handleError(PcodeExecutor<T> executor, PcodeExecutionException err);
+ SleighPcodeUseropDefinition FALLBACK_EMU_SYSCALL =
+ SleighPcodeUseropDefinition.FACTORY.define("emu_syscall")
+ .params("number")
+ .body(_ -> """
+ __op_output = emu_rt_syscall(number);
+ """)
+ .build();
/**
* The entry point for executing a system call on the given executor
- *
* <p>
* The executor's state must already be prepared according to the relevant system calling
- * conventions. This will determine the system call number, according to
- * {@link #readSyscallNumber(PcodeExecutorState, Reason)}, retrieve the relevant system call
- * definition, and invoke it.
+ * conventions. The extended or composed library must provide the "syscall" and/or other
+ * relevant userops defined in the Sleigh. That "syscall" userop should invoke this userop,
+ * passing the system call number then place the result where it belongs according to the target
+ * ABI.
*
* @param executor the executor
* @param library the library
+ * @param op the callother userop
+ * @param syscallNumber the varnode containing the syscall number
+ * @implNote At run time, the logic here will do exactly as it says. For the
+ * interpretation-based emulator, nothing special happens. We read the system call
+ * number and defer to {@link #emu_rt_syscall}, which looks it up and executes it. The
+ * try-catch for {@link ConcretionError} appears totally useless.
+ * <p>
+ * For the JIT-accelerated emulator, things are more interesting. Because
+ * {@link PcodeUserop#canInline()} is set here, we receive this callback during the
+ * decode phase of the translation. We read the system call number and defer to
+ * {@link #emu_rt_syscall} as before. (Note that {@link PcodeUserop#canInline()} being
+ * false does not prevent us from invoking it from Java, even though the engine is
+ * currently trying to inline us.) The try-catch thus protects the attempt to
+ * concretize the syscall number. During decode, {@code T := }{@link MaskedBytes}, so
+ * if the syscall turns out to be a constant (which it often does), then we can
+ * dispatch it at decode time. That syscall (or at least the logic that reads
+ * arguments and stores the result) can thus be inlined. If concretization fails, then
+ * we fall back to invoking {#emu_rt_syscall} at run time.
*/
- @PcodeUserop
- default void syscall(@OpExecutor PcodeExecutor<T> executor,
- @OpLibrary PcodeUseropLibrary<T> library) {
- long syscallNumber = readSyscallNumber(executor.getState(), executor.getReason());
- EmuSyscallDefinition<T> syscall = getSyscalls().get(syscallNumber);
- if (syscall == null) {
- throw new EmuInvalidSystemCallException(syscallNumber);
- }
+ @PcodeUserop(canInline = true)
+ default void emu_syscall(@OpExecutor PcodeExecutor<T> executor,
+ @OpLibrary PcodeUseropLibrary<T> library, @OpOp PcodeOp op, Varnode syscallNumber) {
+ T tSyscallNo = executor.getState().getVar(syscallNumber, executor.getReason());
try {
- syscall.invoke(executor, library);
+ long lSyscallNo = executor.getArithmetic().toLong(tSyscallNo, Purpose.OTHER);
+ emu_rt_syscall(executor, library, lSyscallNo);
}
- catch (PcodeExecutionException e) {
- if (!handleError(executor, e)) {
- throw e;
- }
+ catch (ConcretionError e) {
+ FALLBACK_EMU_SYSCALL.<T> cast().execute(executor, library, op);
}
}
/**
* Get the map of syscalls by number
- *
* <p>
- * Note this method will be invoked for every emulated syscall, so it should be a simple
+ * Note this method will be invoked for every interpreted syscall, so it should be a simple
* accessor. Any computations needed to create the map should be done ahead of time.
*
* @return the system call map
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/PairedEmuFileContents.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/PairedEmuFileContents.java
index ed4ec315f7..a5cea4b51c 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/PairedEmuFileContents.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/PairedEmuFileContents.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.
@@ -41,15 +41,15 @@ public class PairedEmuFileContents<L, R> implements EmuFileContents<Pair<L, R>>
}
@Override
- public long read(long offset, Pair<L, R> buf, long fileSize) {
- long result = left.read(offset, buf.getLeft(), fileSize);
+ public int read(long offset, Pair<L, R> buf, long fileSize) {
+ int result = left.read(offset, buf.getLeft(), fileSize);
right.read(offset, buf.getRight(), fileSize);
return result;
}
@Override
- public long write(long offset, Pair<L, R> buf, long curSize) {
- long result = left.write(offset, buf.getLeft(), curSize);
+ public int write(long offset, Pair<L, R> buf, long curSize) {
+ int result = left.write(offset, buf.getLeft(), curSize);
right.write(offset, buf.getRight(), curSize);
return result;
}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/UseropEmuSyscallDefinition.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/UseropEmuSyscallDefinition.java
index 27e707da3e..1d83a76e45 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/UseropEmuSyscallDefinition.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/sys/UseropEmuSyscallDefinition.java
@@ -15,15 +15,18 @@
*/
package ghidra.pcode.emu.sys;
-import java.util.Arrays;
import java.util.List;
+import java.util.stream.Stream;
+import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.lifecycle.Unfinished;
import ghidra.pcode.emu.sys.EmuSyscallLibrary.EmuSyscallDefinition;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.DataType;
+import ghidra.program.model.data.VoidDataType;
import ghidra.program.model.lang.PrototypeModel;
import ghidra.program.model.listing.Program;
import ghidra.program.model.listing.VariableStorage;
@@ -31,7 +34,6 @@ import ghidra.program.model.pcode.*;
/**
* A system call that is defined by delegating to a p-code userop
- *
* <p>
* This is essentially a wrapper of the p-code userop. Knowing the number of inputs to the userop
* and by applying the calling conventions of the platform, the wrapper aliases each parameter's
@@ -57,7 +59,7 @@ public class UseropEmuSyscallDefinition<T> implements EmuSyscallDefinition<T> {
return dtPointer;
}
- protected final PcodeOp op; // fabricated for analyses that provide originating op info
+ protected PcodeOp op; // fabricate the CALLOTHER, so the executor can choose what to do
protected final PcodeUseropDefinition<T> opdef;
protected final List<Varnode> inVars;
protected final Varnode outVar;
@@ -83,43 +85,52 @@ public class UseropEmuSyscallDefinition<T> implements EmuSyscallDefinition<T> {
" cannot be used as a syscall");
}
DataType[] locs = new DataType[inputCount + 1];
- for (int i = 0; i < locs.length; i++) {
+ locs[0] = opdef.getOutputType() == void.class ? VoidDataType.dataType : dtMachineWord;
+ for (int i = 1; i < locs.length; i++) {
locs[i] = dtMachineWord;
}
VariableStorage[] vss = convention.getStorageLocations(program, locs, false, false);
outVar = getSingleVnStorage(vss[0]);
- inVars = Arrays.asList(new Varnode[inputCount]);
- Varnode[] opIns = new Varnode[inputCount + 1];
- opIns[0] = new Varnode(program.getAddressFactory().getConstantAddress(number), 4);
- for (int i = 0; i < inputCount; i++) {
- Varnode vnIn = getSingleVnStorage(vss[i + 1]);
- inVars.set(i, vnIn);
- opIns[i + 1] = vnIn;
- }
-
- op = new PcodeOp(new SequenceNumber(Address.NO_ADDRESS, 0), PcodeOp.CALLOTHER, opIns,
- outVar);
+ inVars = Stream.of(vss).skip(1).map(this::getSingleVnStorage).toList();
}
/**
- * Assert variable storage is a single varnode, and get that varnode
+ * Assert variable storage is empty or a single varnode, and get that varnode
*
* @param vs the storage
- * @return the single varnode
+ * @return the single varnode, or null if empty
*/
protected Varnode getSingleVnStorage(VariableStorage vs) {
Varnode[] vns = vs.getVarnodes();
- if (vns.length != 1) {
- Unfinished.TODO();
+ return switch (vns.length) {
+ case 0 -> null;
+ case 1 -> vns[0];
+ default -> Unfinished.TODO();
+ };
+ }
+
+ PcodeOp constructOp(SleighLanguage language, PcodeUseropLibrary<?> library) {
+ PcodeUseropSymbolMap userops = library.getSymbols(language);
+ int opNumber = userops.getUseropIndex(opdef.getName());
+ if (opNumber == -1) {
+ throw new AssertionError();
}
- return vns[0];
+ Varnode[] opIns = Stream.concat(
+ Stream.of(new Varnode(language.getAddressFactory().getConstantAddress(opNumber), 4)),
+ inVars.stream()).toArray(Varnode[]::new);
+ return new PcodeOp(new SequenceNumber(Address.NO_ADDRESS, 0), PcodeOp.CALLOTHER, opIns,
+ outVar);
}
@Override
public void invoke(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library) {
+ SleighLanguage language = executor.getLanguage();
+ if (op == null) {
+ op = constructOp(language, library);
+ }
try {
- opdef.execute(executor, library, op, outVar, inVars);
+ executor.execute(List.of(op), library);
}
catch (PcodeExecutionException e) {
throw e;
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbsEmuUnixFileHandle.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbsEmuUnixFileHandle.java
new file mode 100644
index 0000000000..765eefc7d0
--- /dev/null
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbsEmuUnixFileHandle.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.unix;
+
+import java.util.Set;
+
+import ghidra.pcode.emu.PcodeMachine;
+import ghidra.pcode.emu.sys.EmuIOException;
+import ghidra.pcode.emu.unix.EmuUnixFileSystem.OpenFlag;
+import ghidra.pcode.exec.PcodeArithmetic.Purpose;
+import ghidra.program.model.lang.CompilerSpec;
+import ghidra.program.model.pcode.PcodeOp;
+
+/**
+ * A file descriptor for non-concrete types
+ *
+ * @param <T> the type
+ */
+public class AbsEmuUnixFileHandle<T> extends AbstractEmuUnixFileHandle<T> {
+ private T offset;
+
+ public AbsEmuUnixFileHandle(PcodeMachine<T> machine, CompilerSpec cSpec, EmuUnixFile<T> file,
+ Set<OpenFlag> flags, EmuUnixUser user) {
+ super(machine, cSpec, file, flags, user);
+ long off = flags.contains(OpenFlag.O_APPEND) ? file.getStat().st_size : 0;
+ this.offset = arithmetic.fromConst(off, offsetBytes);
+ }
+
+ /**
+ * Advance the handle's offset (negative to rewind)
+ *
+ * @param len the number of bytes to advance
+ */
+ protected void advanceOffset(T len) {
+ int sizeofLen = (int) arithmetic.sizeOf(len);
+ offset =
+ arithmetic.binaryOp(PcodeOp.INT_ADD, offsetBytes, offsetBytes, offset, sizeofLen, len);
+ }
+
+ protected boolean isPositive(T len) {
+ int sizeofLen = (int) arithmetic.sizeOf(len);
+ return arithmetic.isTrue(
+ arithmetic.binaryOp(PcodeOp.INT_SLESS, 1, sizeofLen, arithmetic.fromConst(0, sizeofLen),
+ sizeofLen, len),
+ Purpose.OTHER);
+ }
+
+ @Override
+ public T getAbstractOffset() {
+ return offset;
+ }
+
+ @Override
+ public long getOffset() {
+ return arithmetic.toLong(offset, Purpose.OTHER);
+ }
+
+ @Override
+ public void seek(T offset) throws EmuIOException {
+ // TODO: Bounds check?
+ this.offset = offset;
+ }
+
+ @Override
+ public void seek(long offset) throws EmuIOException {
+ seek(arithmetic.fromConst(offset, offsetBytes));
+ }
+
+ @Override
+ public T readAbstract(T buf) throws EmuIOException {
+ checkReadable();
+ T len = file.read(arithmetic, offset, buf);
+ if (isPositive(len)) {
+ advanceOffset(len);
+ }
+ return len;
+ }
+
+ @Override
+ public int read(T buf) throws EmuIOException {
+ return (int) arithmetic.toLong(readAbstract(buf), Purpose.OTHER);
+ }
+
+ @Override
+ public T writeAbstract(T buf) throws EmuIOException {
+ checkWritable();
+ T len = file.write(arithmetic, offset, buf);
+ if (isPositive(len)) {
+ advanceOffset(len);
+ }
+ return len;
+ }
+
+ @Override
+ public int write(T buf) throws EmuIOException {
+ return (int) arithmetic.toLong(writeAbstract(buf), Purpose.OTHER);
+ }
+}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixFile.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixFile.java
index bc34cfa28f..47cadd1bdd 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixFile.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixFile.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.
@@ -22,7 +22,6 @@ import ghidra.util.MathUtilities;
/**
* An abstract file contained in an emulated file system
- *
* <p>
* Contrast this with {@link DefaultEmuUnixFileHandle}, which is a particular process's handle when
* opening the file, not the file itself.
@@ -37,7 +36,6 @@ public abstract class AbstractEmuUnixFile<T> implements EmuUnixFile<T> {
/**
* Construct a new file
- *
* <p>
* TODO: Technically, a file can be hardlinked to several pathnames, but for simplicity, or for
* diagnostics, we let the file know its own original name.
@@ -79,18 +77,31 @@ public abstract class AbstractEmuUnixFile<T> implements EmuUnixFile<T> {
return stat;
}
+ @Override
+ public int read(long offset, T buf) {
+ return contents.read(offset, buf, stat.st_size);
+ }
+
@Override
public T read(PcodeArithmetic<T> arithmetic, T offset, T buf) {
long off = arithmetic.toLong(offset, Purpose.OTHER);
- long len = contents.read(off, buf, stat.st_size);
+ long len = read(off, buf); // Assure signed extension
return arithmetic.fromConst(len, (int) arithmetic.sizeOf(offset));
}
+ @Override
+ public int write(long offset, T buf) {
+ int len = contents.write(offset, buf, stat.st_size);
+ if (len > 0) {
+ stat.st_size = MathUtilities.unsignedMax(stat.st_size, offset + len);
+ }
+ return len;
+ }
+
@Override
public T write(PcodeArithmetic<T> arithmetic, T offset, T buf) {
long off = arithmetic.toLong(offset, Purpose.OTHER);
- long len = contents.write(off, buf, stat.st_size);
- stat.st_size = MathUtilities.unsignedMax(stat.st_size, off + len);
+ long len = write(off, buf); // Assure signed extension
return arithmetic.fromConst(len, (int) arithmetic.sizeOf(offset));
}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixFileHandle.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixFileHandle.java
new file mode 100644
index 0000000000..f7a968fb72
--- /dev/null
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixFileHandle.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.unix;
+
+import java.util.Set;
+
+import ghidra.pcode.emu.PcodeMachine;
+import ghidra.pcode.emu.sys.EmuIOException;
+import ghidra.pcode.emu.unix.EmuUnixFileSystem.OpenFlag;
+import ghidra.pcode.exec.PcodeArithmetic;
+import ghidra.program.model.lang.CompilerSpec;
+
+/**
+ * Abstract for a file descriptor associated with a file on a simulated UNIX file system
+ *
+ * @param <T> the type
+ */
+public abstract class AbstractEmuUnixFileHandle<T> implements EmuUnixFileDescriptor<T> {
+ protected final PcodeArithmetic<T> arithmetic;
+ protected final EmuUnixFile<T> file;
+ // TODO: T flags? Meh.
+ protected final Set<OpenFlag> flags;
+ protected final EmuUnixUser user;
+ protected final int offsetBytes;
+
+ /**
+ * Construct a new handle on the given file
+ *
+ * @see AbstractEmuUnixSyscallUseropLibrary#createHandle(EmuUnixFile, int)
+ * @param machine the machine emulating the hardware
+ * @param cSpec the ABI of the target platform
+ * @param file the file opened by this handle
+ * @param flags the user-specified flags, as defined by the simulator
+ * @param user the user that opened the file
+ */
+ public AbstractEmuUnixFileHandle(PcodeMachine<T> machine, CompilerSpec cSpec,
+ EmuUnixFile<T> file, Set<OpenFlag> flags, EmuUnixUser user) {
+ this.arithmetic = machine.getArithmetic();
+ this.file = file;
+ this.flags = flags;
+ this.user = user;
+ this.offsetBytes = cSpec.getDataOrganization().getLongSize(); // off_t's fundamental type
+ }
+
+ /**
+ * Get the file opened to this handle
+ *
+ * @return the file
+ */
+ public EmuUnixFile<T> getFile() {
+ return file;
+ }
+
+ /**
+ * Check if the file is readable, throwing {@link EmuIOException} if not
+ */
+ public void checkReadable() {
+ if (!OpenFlag.isRead(flags)) {
+ throw new EmuIOException("File not opened for reading");
+ }
+ }
+
+ /**
+ * Check if the file is writable, throwing {@link EmuIOException} if not
+ */
+ public void checkWritable() {
+ if (!OpenFlag.isWrite(flags)) {
+ throw new EmuIOException("File not opened for writing");
+ }
+ }
+
+ @Override
+ public EmuUnixFileStat stat() {
+ return file.getStat();
+ }
+
+ @Override
+ public void close() {
+ // TODO: Let the file know a handle was closed?
+ }
+}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixSyscallUseropLibrary.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixSyscallUseropLibrary.java
index 570c1d8abc..da4cf947b1 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixSyscallUseropLibrary.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractEmuUnixSyscallUseropLibrary.java
@@ -22,8 +22,9 @@ import ghidra.pcode.emu.PcodeMachine;
import ghidra.pcode.emu.sys.AnnotatedEmuSyscallUseropLibrary;
import ghidra.pcode.emu.sys.EmuProcessExitedException;
import ghidra.pcode.emu.unix.EmuUnixFileSystem.OpenFlag;
-import ghidra.pcode.exec.*;
+import ghidra.pcode.exec.PcodeArithmetic;
import ghidra.pcode.exec.PcodeArithmetic.Purpose;
+import ghidra.pcode.exec.PcodeExecutorState;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.data.StringDataInstance;
@@ -33,11 +34,9 @@ import ghidra.program.model.mem.MemBuffer;
/**
* An abstract library of UNIX system calls, suitable for use with any processor
- *
* <p>
* See the UNIX manual pages for more information about each specific system call, error numbers,
* etc.
- *
* <p>
* TODO: The rest of the system calls common to UNIX.
*
@@ -105,7 +104,6 @@ public abstract class AbstractEmuUnixSyscallUseropLibrary<T>
/**
* Claim the lowest available file descriptor number for the given descriptor object
- *
* <p>
* The descriptor will be added to the descriptor table for the claimed number
*
@@ -206,121 +204,115 @@ public abstract class AbstractEmuUnixSyscallUseropLibrary<T>
}
}
- /**
- * Place the errno into the machine as expected by the simulated platform's ABI
- *
- * @param executor the executor for the thread running this system call
- * @param errno the error number
- * @return true if the errno was successfully placed
- */
- protected abstract boolean returnErrno(PcodeExecutor<T> executor, int errno);
-
- @Override
- public boolean handleError(PcodeExecutor<T> executor, PcodeExecutionException err) {
- if (err instanceof EmuUnixException) {
- Integer errno = ((EmuUnixException) err).getErrno();
- if (errno == null) {
- return false;
- }
- return returnErrno(executor, errno);
- }
- return false;
- }
-
/**
* The UNIX {@code exit} system call
- *
* <p>
* This just throws an exception, which the overall simulator or script should catch.
*
* @param status the status code
- * @return never
* @throws EmuProcessExitedException always
*/
- @PcodeUserop
+ @PcodeUserop(functional = true)
@EmuSyscall("exit")
- public T unix_exit(T status) {
- throw new EmuProcessExitedException(machine.getArithmetic(), status);
+ public void unix_exit(long status) {
+ throw new EmuProcessExitedException(status);
+ }
+
+ protected T abstract_unix_read(PcodeExecutorState<T> state, T fd, T bufPtr, T count) {
+ PcodeArithmetic<T> arithmetic = machine.getArithmetic();
+ try {
+ int ifd = (int) arithmetic.toLong(fd, Purpose.OTHER);
+ EmuUnixFileDescriptor<T> desc = findFd(ifd);
+ AddressSpace space = machine.getLanguage().getAddressFactory().getDefaultAddressSpace();
+ int icount = (int) arithmetic.toLong(count, Purpose.OTHER);
+ T buf = arithmetic.fromConst(0, icount);
+ int result = desc.read(buf);
+ machine.getSharedState().setVar(space, bufPtr, result, true, buf);
+ return arithmetic.fromConst((long) result, intSize);
+ }
+ catch (EmuUnixException e) {
+ // TODO: Does this generalize to all UNIX, or just Linux x86/amd64?
+ return arithmetic.fromConst((long) -e.getErrno(), intSize);
+ }
}
/**
* The UNIX {@code read} system call
*
- * @param state to receive the thread's state
* @param fd the file descriptor
* @param bufPtr the pointer to the buffer to receive the data
* @param count the number of bytes to read
* @return the number of bytes successfully read
*/
- @PcodeUserop
+ @PcodeUserop(functional = true, signed = true)
@EmuSyscall("read")
- public T unix_read(@OpState PcodeExecutorState<T> state, T fd, T bufPtr, T count) {
+ public int unix_read(int fd, long bufPtr, int count) {
PcodeArithmetic<T> arithmetic = machine.getArithmetic();
- int ifd = (int) arithmetic.toLong(fd, Purpose.OTHER);
- EmuUnixFileDescriptor<T> desc = findFd(ifd);
- AddressSpace space = machine.getLanguage().getAddressFactory().getDefaultAddressSpace();
- // TODO: Not ideal to require concrete size, but gets unwieldy to leave it abstract
- int size = (int) arithmetic.toLong(count, Purpose.OTHER);
- T buf = arithmetic.fromConst(0, size);
- T result = desc.read(buf);
- int iresult = (int) arithmetic.toLong(result, Purpose.OTHER);
- state.setVar(space, bufPtr, iresult, true, buf);
- return result;
+ try {
+ EmuUnixFileDescriptor<T> desc = findFd(fd);
+ AddressSpace space = machine.getLanguage().getAddressFactory().getDefaultAddressSpace();
+ T buf = arithmetic.fromConst(0, count);
+ int result = desc.read(buf);
+ machine.getSharedState().setVar(space, bufPtr, result, true, buf);
+ return result;
+ }
+ catch (EmuUnixException e) {
+ // TODO: Does this generalize to all UNIX, or just Linux x86/amd64?
+ return -e.getErrno();
+ }
}
/**
* The UNIX {@code write} system call
*
- * @param state to receive the thread's state
* @param fd the file descriptor
* @param bufPtr the pointer to the buffer of data to write
* @param count the number of bytes to write
* @return the number of bytes successfully written
*/
- @PcodeUserop
+ @PcodeUserop(functional = true, signed = true)
@EmuSyscall("write")
- public T unix_write(@OpState PcodeExecutorState<T> state, T fd, T bufPtr, T count) {
- PcodeArithmetic<T> arithmetic = machine.getArithmetic();
- int ifd = (int) arithmetic.toLong(fd, Purpose.OTHER);
- EmuUnixFileDescriptor<T> desc = findFd(ifd);
- AddressSpace space = machine.getLanguage().getAddressFactory().getDefaultAddressSpace();
- // TODO: Not ideal to require concrete size. What are the alternatives, though?
- // TODO: size should actually be long (size_t)
- int size = (int) arithmetic.toLong(count, Purpose.OTHER);
- T buf = state.getVar(space, bufPtr, size, true, Reason.EXECUTE_READ);
- // TODO: Write back into state? "write" shouldn't touch the buffer....
- return desc.write(buf);
+ public int unix_write(int fd, long bufPtr, int count) {
+ try {
+ EmuUnixFileDescriptor<T> desc = findFd(fd);
+ AddressSpace space = machine.getLanguage().getAddressFactory().getDefaultAddressSpace();
+ T buf =
+ machine.getSharedState().getVar(space, bufPtr, count, true, Reason.EXECUTE_READ);
+ return desc.write(buf);
+ }
+ catch (EmuUnixException e) {
+ return -e.getErrno();
+ }
}
/**
* The UNIX {@code open} system call
*
- * @param state to receive the thread's state
* @param pathnamePtr the file's path (pointer to character string)
* @param flags the flags
* @param mode the mode
* @return the file descriptor
*/
- @PcodeUserop
+ @PcodeUserop(functional = true, signed = true)
@EmuSyscall("open")
- public T unix_open(@OpState PcodeExecutorState<T> state, T pathnamePtr, T flags, T mode) {
- PcodeArithmetic<T> arithmetic = machine.getArithmetic();
- int iflags = (int) arithmetic.toLong(flags, Purpose.OTHER);
- int imode = (int) arithmetic.toLong(mode, Purpose.OTHER);
- long pathnameOff = arithmetic.toLong(pathnamePtr, Purpose.OTHER);
- AddressSpace space = machine.getLanguage().getAddressFactory().getDefaultAddressSpace();
-
- SettingsImpl settings = new SettingsImpl();
- MemBuffer buffer = state.getConcreteBuffer(space.getAddress(pathnameOff), Purpose.OTHER);
- StringDataInstance sdi =
- new StringDataInstance(StringDataType.dataType, settings, buffer, -1);
- sdi = new StringDataInstance(StringDataType.dataType, settings, buffer,
- sdi.getStringLength());
- // TODO: Can NPE here be mapped to a unix error
- String pathname = Objects.requireNonNull(sdi.getStringValue());
- EmuUnixFile<T> file = fs.open(pathname, convertFlags(iflags), user, imode);
- int ifd = claimFd(createHandle(file, iflags));
- return arithmetic.fromConst(ifd, intSize);
+ public int unix_open(long pathnamePtr, int flags, int mode) {
+ try {
+ AddressSpace space = machine.getLanguage().getAddressFactory().getDefaultAddressSpace();
+ SettingsImpl settings = new SettingsImpl();
+ MemBuffer buffer = machine.getSharedState()
+ .getConcreteBuffer(space.getAddress(pathnamePtr), Purpose.OTHER);
+ StringDataInstance sdi =
+ new StringDataInstance(StringDataType.dataType, settings, buffer, -1);
+ sdi = new StringDataInstance(StringDataType.dataType, settings, buffer,
+ sdi.getStringLength());
+ // TODO: Can NPE here be mapped to a unix error
+ String pathname = Objects.requireNonNull(sdi.getStringValue());
+ EmuUnixFile<T> file = fs.open(pathname, convertFlags(flags), user, mode);
+ return claimFd(createHandle(file, flags));
+ }
+ catch (EmuUnixException e) {
+ return -e.getErrno();
+ }
}
/**
@@ -329,30 +321,32 @@ public abstract class AbstractEmuUnixSyscallUseropLibrary<T>
* @param fd the file descriptor
* @return 0 for success
*/
- @PcodeUserop
+ @PcodeUserop(functional = true, signed = true)
@EmuSyscall("close")
- public T unix_close(T fd) {
- PcodeArithmetic<T> arithmetic = machine.getArithmetic();
- int ifd = (int) arithmetic.toLong(fd, Purpose.OTHER);
- // TODO: Some fs.close or file.close, when all handles have released it?
- EmuUnixFileDescriptor<T> desc = releaseFd(ifd);
- desc.close();
- return arithmetic.fromConst(0, intSize);
+ public int unix_close(int fd) {
+ try {
+ // TODO: Some fs.close or file.close, when all handles have released it?
+ EmuUnixFileDescriptor<T> desc = releaseFd(fd);
+ desc.close();
+ return 0;
+ }
+ catch (EmuUnixException e) {
+ return -e.getErrno();
+ }
}
/**
* The UNIX {@code group_exit} system call
- *
* <p>
* This just throws an exception, which the overall simulator or script should catch.
*
* @param status the status code
* @throws EmuProcessExitedException always
*/
- @PcodeUserop
+ @PcodeUserop(functional = true)
@EmuSyscall("group_exit")
- public void unix_group_exit(T status) {
- throw new EmuProcessExitedException(machine.getArithmetic(), status);
+ public void unix_group_exit(long status) {
+ throw new EmuProcessExitedException(status);
}
/**
@@ -368,7 +362,6 @@ public abstract class AbstractEmuUnixSyscallUseropLibrary<T>
/**
* Inline the gather or scatter pattern for an iovec syscall
- *
* <p>
* This is essentially a macro by virtue of the host (Java) language. Note that
* {@link #_result(RVal)} from here will cause the whole userop to return, not just from
@@ -385,6 +378,7 @@ public abstract class AbstractEmuUnixSyscallUseropLibrary<T>
Var tmp_base = local("tmp_base", tmp_io.field("iov_base").deref());
Var tmp_len = local("tmp_len", tmp_io.field("iov_len").deref());
tmp_ret.set(subOp.call(in_fd, tmp_base, tmp_len));
+ _if(tmp_ret.ltis(0), () -> _result(tmp_ret));
tmp_total.addiTo(tmp_ret);
_if(tmp_ret.ltiu(tmp_len), () -> _break()); // We got less than this buffer
});
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractStreamEmuUnixFileHandle.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractStreamEmuUnixFileHandle.java
index 5a31cd13d8..47a677b6d9 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractStreamEmuUnixFileHandle.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/AbstractStreamEmuUnixFileHandle.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.
@@ -30,8 +30,6 @@ public abstract class AbstractStreamEmuUnixFileHandle<T> implements EmuUnixFileD
protected final PcodeArithmetic<T> arithmetic;
protected final int offsetBytes;
- private final T offset;
-
/**
* Construct a new handle
*
@@ -42,12 +40,16 @@ public abstract class AbstractStreamEmuUnixFileHandle<T> implements EmuUnixFileD
public AbstractStreamEmuUnixFileHandle(PcodeMachine<T> machine, CompilerSpec cSpec) {
this.arithmetic = machine.getArithmetic();
this.offsetBytes = cSpec.getDataOrganization().getLongSize(); // off_t's fundamental type
- this.offset = arithmetic.fromConst(0, offsetBytes);
}
@Override
- public T getOffset() {
- return offset;
+ public T getAbstractOffset() {
+ return arithmetic.fromConst(0, offsetBytes);
+ }
+
+ @Override
+ public long getOffset() {
+ return 0;
}
@Override
@@ -55,6 +57,21 @@ public abstract class AbstractStreamEmuUnixFileHandle<T> implements EmuUnixFileD
// No effect
}
+ @Override
+ public void seek(long offset) throws EmuIOException {
+ // No effect
+ }
+
+ @Override
+ public T readAbstract(T buf) throws EmuIOException {
+ return arithmetic.fromConst(read(buf), offsetBytes);
+ }
+
+ @Override
+ public T writeAbstract(T buf) throws EmuIOException {
+ return arithmetic.fromConst(write(buf), offsetBytes);
+ }
+
@Override
public EmuUnixFileStat stat() {
return Unfinished.TODO();
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/DefaultEmuUnixFileHandle.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/DefaultEmuUnixFileHandle.java
index 1cfbea0121..e73b147c15 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/DefaultEmuUnixFileHandle.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/DefaultEmuUnixFileHandle.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,25 +20,16 @@ import java.util.Set;
import ghidra.pcode.emu.PcodeMachine;
import ghidra.pcode.emu.sys.EmuIOException;
import ghidra.pcode.emu.unix.EmuUnixFileSystem.OpenFlag;
-import ghidra.pcode.exec.PcodeArithmetic;
+import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.program.model.lang.CompilerSpec;
-import ghidra.program.model.pcode.PcodeOp;
/**
- * A file descriptor associated with a file on a simulated UNIX file system
- *
- * @param <T> the type of values stored by the file
+ * A concrete file descriptor
+ *
+ * @param <T> the type of values stored in the file
*/
-public class DefaultEmuUnixFileHandle<T> implements EmuUnixFileDescriptor<T> {
-
- protected final PcodeArithmetic<T> arithmetic;
- protected final EmuUnixFile<T> file;
- // TODO: T flags? Meh.
- protected final Set<OpenFlag> flags;
- protected final EmuUnixUser user;
- protected final int offsetBytes;
-
- private T offset;
+public class DefaultEmuUnixFileHandle<T> extends AbstractEmuUnixFileHandle<T> {
+ long offset;
/**
* Construct a new handle on the given file
@@ -52,90 +43,58 @@ public class DefaultEmuUnixFileHandle<T> implements EmuUnixFileDescriptor<T> {
*/
public DefaultEmuUnixFileHandle(PcodeMachine<T> machine, CompilerSpec cSpec,
EmuUnixFile<T> file, Set<OpenFlag> flags, EmuUnixUser user) {
- this.arithmetic = machine.getArithmetic();
- this.file = file;
- this.flags = flags;
- this.user = user;
- this.offsetBytes = cSpec.getDataOrganization().getLongSize(); // off_t's fundamental type
-
- this.offset = arithmetic.fromConst(0, offsetBytes);
- }
-
- /**
- * Get the file opened to this handle
- *
- * @return the file
- */
- public EmuUnixFile<T> getFile() {
- return file;
- }
-
- /**
- * Check if the file is readable, throwing {@link EmuIOException} if not
- */
- public void checkReadable() {
- if (!OpenFlag.isRead(flags)) {
- throw new EmuIOException("File not opened for reading");
- }
+ super(machine, cSpec, file, flags, user);
+ this.offset = flags.contains(OpenFlag.O_APPEND) ? file.getStat().st_size : 0;
}
- /**
- * Check if the file is writable, throwing {@link EmuIOException} if not
- */
- public void checkWritable() {
- if (!OpenFlag.isWrite(flags)) {
- throw new EmuIOException("File not opened for writing");
- }
+ @Override
+ public long getOffset() {
+ return offset;
}
- /**
- * Advance the handle's offset (negative to rewind)
- *
- * @param len the number of bytes to advance
- */
- protected void advanceOffset(T len) {
- int sizeofLen = (int) arithmetic.sizeOf(len);
- offset =
- arithmetic.binaryOp(PcodeOp.INT_ADD, offsetBytes, offsetBytes, offset, sizeofLen, len);
+ @Override
+ public T getAbstractOffset() {
+ return arithmetic.fromConst(offset, offsetBytes);
}
@Override
- public T getOffset() {
- return offset;
+ public void seek(T offset) throws EmuIOException {
+ seek(arithmetic.toLong(offset, Purpose.OTHER));
}
@Override
- public void seek(T offset) throws EmuIOException {
+ public void seek(long offset) throws EmuIOException {
// TODO: Where does bounds check happen?
this.offset = offset;
}
@Override
- public T read(T buf) throws EmuIOException {
+ public int read(T buf) throws EmuIOException {
checkReadable();
- T len = file.read(arithmetic, offset, buf);
- advanceOffset(len);
+ int len = file.read(offset, buf);
+ if (len > 0) {
+ offset += len;
+ }
return len;
}
@Override
- public T write(T buf) throws EmuIOException {
- checkWritable();
- if (flags.contains(OpenFlag.O_APPEND)) {
- offset = arithmetic.fromConst(file.getStat().st_size, offsetBytes);
- }
- T len = file.write(arithmetic, offset, buf);
- advanceOffset(len);
- return len;
+ public T readAbstract(T buf) throws EmuIOException {
+ return arithmetic.fromConst(read(buf), offsetBytes);
}
@Override
- public EmuUnixFileStat stat() {
- return file.getStat();
+ public int write(T buf) throws EmuIOException {
+ checkWritable();
+ int len = file.write(offset, buf);
+ if (len > 0) {
+ offset += len;
+ }
+ return len;
}
@Override
- public void close() {
- // TODO: Let the file know a handle was closed?
+ public T writeAbstract(T buf) throws EmuIOException {
+ return arithmetic.fromConst(write(buf), offsetBytes);
}
}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFile.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFile.java
index e57837e2ae..2986143f4d 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFile.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFile.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,6 @@ import ghidra.pcode.exec.PcodeArithmetic;
/**
* A simulated UNIX file
- *
* <p>
* Contrast this with {@link EmuUnixFileDescriptor}, which is a process's handle to an open file,
* not the file itself.
@@ -31,7 +30,6 @@ public interface EmuUnixFile<T> {
/**
* Get the original pathname of this file
- *
* <p>
* Depending on the fidelity of the file system simulator, and the actions taken by the target
* program, the file may no longer actually exist at this path, but it ought be have been the
@@ -43,7 +41,6 @@ public interface EmuUnixFile<T> {
/**
* Read contents from the file starting at the given offset into the given buffer
- *
* <p>
* This roughly follows the semantics of the UNIX {@code read()}. While the offset and return
* value may depend on the arithmetic, the actual contents read from the file should not.
@@ -56,8 +53,19 @@ public interface EmuUnixFile<T> {
T read(PcodeArithmetic<T> arithmetic, T offset, T buf);
/**
- * Write contents into the file starting at the given offset from the given buffer
+ * Read contents from the file starting at the given offset into the given buffer
+ * <p>
+ * This roughly follows the semantics of the UNIX {@code read()}. While the offset and return
+ * value may depend on the arithmetic, the actual contents read from the file should not.
*
+ * @param offset the offset
+ * @param buf the buffer
+ * @return the number of bytes read
+ */
+ int read(long offset, T buf);
+
+ /**
+ * Write contents into the file starting at the given offset from the given buffer
* <p>
* This roughly follows the semantics of the UNIX {@code write()}. While the offset and return
* value may depend on the arithmetic, the actual contents written to the file should not.
@@ -69,6 +77,18 @@ public interface EmuUnixFile<T> {
*/
T write(PcodeArithmetic<T> arithmetic, T offset, T buf);
+ /**
+ * Write contents into the file starting at the given offset from the given buffer
+ * <p>
+ * This roughly follows the semantics of the UNIX {@code write()}. While the offset and return
+ * value may depend on the arithmetic, the actual contents written to the file should not.
+ *
+ * @param offset the offset
+ * @param buf the buffer
+ * @return the number of bytes written
+ */
+ int write(long offset, T buf);
+
/**
* Erase the contents of the file
*/
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFileDescriptor.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFileDescriptor.java
index cf4d890b14..e88d6fadb5 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFileDescriptor.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/EmuUnixFileDescriptor.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.emu.unix;
+import ghidra.lifecycle.Experimental;
import ghidra.pcode.emu.sys.EmuIOException;
/**
@@ -22,6 +23,7 @@ import ghidra.pcode.emu.sys.EmuIOException;
*
* @param <T> the type of values stored in the file
*/
+@Experimental
public interface EmuUnixFileDescriptor<T> {
/**
* The default file descriptor for stdin (standard input)
@@ -37,20 +39,31 @@ public interface EmuUnixFileDescriptor<T> {
int FD_STDERR = 2;
/**
- * Get the current offset of the file, or 0 if not applicable
- *
- * @return the offset
+ * {@return the current offset of the file, or 0 if not applicable}
*/
- T getOffset();
+ T getAbstractOffset();
/**
- * See to the given offset
+ * {@return the current offset of the file, or 0 if not applicable}
+ */
+ long getOffset();
+
+ /**
+ * Seek to the given offset
*
* @param offset the desired offset
* @throws EmuIOException if an error occurred
*/
void seek(T offset) throws EmuIOException;
+ /**
+ * Seek to the given offset
+ *
+ * @param offset the desired offset
+ * @throws EmuIOException if an error occurred
+ */
+ void seek(long offset) throws EmuIOException;
+
/**
* Read from the file opened by this handle
*
@@ -58,19 +71,37 @@ public interface EmuUnixFileDescriptor<T> {
* @return the number of bytes read
* @throws EmuIOException if an error occurred
*/
- T read(T buf) throws EmuIOException;
+ T readAbstract(T buf) throws EmuIOException;
+
+ /**
+ * Read from the file opened by this handle
+ *
+ * @param buf the destination buffer
+ * @return the number of bytes read
+ * @throws EmuIOException if an error occurred
+ */
+ int read(T buf) throws EmuIOException;
+
+ /**
+ * Write into the file opened by this handle
+ *
+ * @param buf the source buffer
+ * @return the number of bytes written
+ * @throws EmuIOException if an error occurred
+ */
+ T writeAbstract(T buf) throws EmuIOException;
/**
- * Read into the file opened by this handle
+ * Write into the file opened by this handle
*
* @param buf the source buffer
* @return the number of bytes written
* @throws EmuIOException if an error occurred
*/
- T write(T buf) throws EmuIOException;
+ int write(T buf) throws EmuIOException;
/**
- * Obtain the {@code stat} structure of the file opened by this handle
+ * {@return the {@code stat} structure of the file opened by this handle}
*/
EmuUnixFileStat stat();
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/IOStreamEmuUnixFileHandle.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/IOStreamEmuUnixFileHandle.java
index 43c03a2f4a..e0ee6f1684 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/IOStreamEmuUnixFileHandle.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/emu/unix/IOStreamEmuUnixFileHandle.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.
@@ -67,7 +67,6 @@ public class IOStreamEmuUnixFileHandle extends AbstractStreamEmuUnixFileHandle<b
/**
* Construct a proxy for a host resource
- *
* <p>
* <b>WARNING:</b> Think carefully before proxying any host resource to a temperamental target
* program.
@@ -85,13 +84,12 @@ public class IOStreamEmuUnixFileHandle extends AbstractStreamEmuUnixFileHandle<b
}
@Override
- public byte[] read(byte[] buf) throws EmuIOException {
+ public int read(byte[] buf) throws EmuIOException {
if (input == null) {
- return arithmetic.fromConst(0, offsetBytes);
+ return 0;
}
try {
- int result = input.read(buf);
- return arithmetic.fromConst(result, offsetBytes);
+ return input.read(buf);
}
catch (IOException e) {
throw new EmuIOException("Could not read host input stream", e);
@@ -99,13 +97,13 @@ public class IOStreamEmuUnixFileHandle extends AbstractStreamEmuUnixFileHandle<b
}
@Override
- public byte[] write(byte[] buf) throws EmuIOException {
+ public int write(byte[] buf) throws EmuIOException {
if (output == null) {
- return arithmetic.fromConst(0, offsetBytes);
+ return 0;
}
try {
output.write(buf);
- return arithmetic.fromConst(buf.length, offsetBytes);
+ return buf.length;
}
catch (IOException e) {
throw new EmuIOException("Could not write host output stream", e);
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/IndexExpr.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/IndexExpr.java
index 3fc473f0aa..01841a6201 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/IndexExpr.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/IndexExpr.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.
@@ -52,8 +52,10 @@ class IndexExpr extends Expr implements LValInternal {
st.append(base.generate(this));
st.append(" + (");
st.append(index.generate(this));
- st.append("*");
- st.append(Integer.toString(elemLen));
+ if (elemLen != 1) {
+ st.append("*");
+ st.append(Integer.toString(elemLen));
+ }
st.append("))");
return st;
}
diff --git a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/StructuredSleigh.java b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/StructuredSleigh.java
index f7cdb0d2fd..0320d30573 100644
--- a/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/StructuredSleigh.java
+++ b/Ghidra/Features/SystemEmulation/src/main/java/ghidra/pcode/struct/StructuredSleigh.java
@@ -30,8 +30,8 @@ import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.lifecycle.Internal;
import ghidra.pcode.emu.unix.AbstractEmuUnixSyscallUseropLibrary;
import ghidra.pcode.exec.*;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
-import ghidra.pcode.exec.SleighPcodeUseropDefinition.Factory;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.pcode.struct.DefaultVar.Check;
import ghidra.program.model.address.AddressSpace;
@@ -46,14 +46,12 @@ import utilities.util.AnnotationUtilities;
/**
* The primary class for using the "structured sleigh" DSL
- *
* <p>
* This provides some conveniences for generating Sleigh source code, which is otherwise completely
* typeless and lacks basic control structure. In general, the types are not used so much for type
* checking as they are for easing access to fields of C structures, array indexing, etc.
* Furthermore, it becomes possible to re-use code when data types differ among platforms, so long
* as those variations are limited to field offsets and type sizes.
- *
* <p>
* Start by declaring an extension of {@link StructuredSleigh}. Then put any necessary "forward
* declarations" as fields of the class. Then declare methods annotated with
@@ -75,14 +73,12 @@ import utilities.util.AnnotationUtilities;
* }
* }
* </pre>
- *
* <p>
* This will simply generate the source "{@code r0 = 0xdeadbeef:4}", but it also provides all the
* scaffolding to compile and invoke the userop as in a {@link PcodeUseropLibrary}. Internal methods
* -- which essentially behave like macros -- may be used, so only annotate methods to export as
* userops. For a more complete and practical example of using structured sleigh in a userop
* library, see {@link AbstractEmuUnixSyscallUseropLibrary}.
- *
* <p>
* Structured sleigh is also usable in a more standalone manner:
*
@@ -103,7 +99,6 @@ import utilities.util.AnnotationUtilities;
* System.out.println(myUserop.programFor(new Varnode(r0.getAddress(), r0.getNumBytes()), List.of(),
* PcodeUseropLibrary.NIL));
* </pre>
- *
* <p>
* Known limitations:
* <ul>
@@ -128,7 +123,6 @@ public class StructuredSleigh {
/**
* "Export" a method as a p-code userop implemented using p-code compiled from structured Sleigh
- *
* <p>
* This is applied to methods used to generate Sleigh source code. Take note that the method is
* only invoked once (for a given library instance) to generate code. Thus, beware of
@@ -141,12 +135,10 @@ public class StructuredSleigh {
* r0.set(Random.nextLong()); // BAD: Die rolled once at compile time
* }
* </pre>
- *
* <p>
* The random number will be generated once at structured Sleigh compilation time, and then that
* same number used on every invocation of the p-code userop. Instead, this userop should be
* implemented using a Java callback, i.e., {@link AnnotatedPcodeUseropLibrary.PcodeUserop}.
- *
* <p>
* The userop may accept parameters and return a result. To accept parameters, declare them in
* the Java method signature and annotate them with {@link Param}. To return a result, name the
@@ -162,12 +154,11 @@ public class StructuredSleigh {
* The data type path for the "return type" of the userop. See
* {@link StructuredSleigh#type(String)}.
*/
- String type() default "void";
+ String type() default "undefined";
}
/**
* Declare a parameter of the p-code userop
- *
* <p>
* This is attached to parameters of methods annotated with {@link StructuredUserop}, providing
* the type and name of the parameter. The Java type of the parameter must be {@link Var}. For
@@ -191,7 +182,6 @@ public class StructuredSleigh {
/**
* The name of the parameter in the output Sleigh code
- *
* <p>
* If the variable is referenced via {@link StructuredSleigh#s(String)} or
* {@link StructuredSleigh#e(String)}, then is it necessary to specify the name used in the
@@ -206,7 +196,6 @@ public class StructuredSleigh {
/**
* The declaration of an "imported" userop
- *
* <p>
* Because Sleigh is typeless, structured Sleigh needs additional type information about the
* imported userop. The referenced userop may be implemented by another library and may be a
@@ -238,7 +227,6 @@ public class StructuredSleigh {
/**
* Generate an invocation of the userop
- *
* <p>
* If the userop has a result type, then the resulting statement will also have a value. If
* the user has a {@code void} result type, the "value" should not be used. Otherwise, a
@@ -263,7 +251,6 @@ public class StructuredSleigh {
/**
* Cast the value to the given type
- *
* <p>
* This functions like a C-style pointer cast. There are no implied operations or
* conversions. Notably, casting between integers and floats is just a re-interpretation of
@@ -276,7 +263,6 @@ public class StructuredSleigh {
/**
* Generate a dereference (in the C sense)
- *
* <p>
* The value is treated as an address, and the result is essentially a variable in the given
* target address space.
@@ -813,7 +799,6 @@ public class StructuredSleigh {
/**
* Generate a field offset
- *
* <p>
* This departs subtly from expected C semantics. This value's type is assumed to be a
* pointer to a {@link Composite}. That type is retrieved and the field located. This then
@@ -821,7 +806,6 @@ public class StructuredSleigh {
* a pointer to the type of the field. The C equivalent is "{@code &(val->field)}".
* Essentially, it's just address computation. Note that this operator will fail if the type
* is not a pointer. It cannot be used directly on the {@link Composite} type.
- *
* <p>
* TODO: Allow direct use on the composite type? Some mechanism for dealing with bitfields?
* Bitfields cannot really work if this is just pointer manipulation. If it's also allowed
@@ -838,7 +822,6 @@ public class StructuredSleigh {
/**
* Generate an array index
- *
* <p>
* This departs subtly from expected C semantics. This value's type is assumed to be a
* pointer to the element type. The size of the element type is computed, and this generates
@@ -846,8 +829,6 @@ public class StructuredSleigh {
* the result is the same as this value's type. The C equivalent is "{@code &(val[index])}".
* Essentially, it's just address computation. Note that this operator will fail if the type
* is not a pointer. It cannot be used on an {@link Array} type.
- *
- *
* <p>
* TODO: Allow use of {@link Array} type? While it's possible for authors to specify pointer
* types for their variables, the types of fields they access may not be under their
@@ -972,7 +953,6 @@ public class StructuredSleigh {
protected interface Label {
/**
* Borrow this label
- *
* <p>
* This should be used whenever a statement (or its children) may need to generate a goto
* using the "next" label passed into it. If "next" is the fall-through label, this will
@@ -986,7 +966,6 @@ public class StructuredSleigh {
/**
* Generate code for this label
- *
* <p>
* This must be the last method called on the label, because it relies on knowing whether or
* not the label is actually used. (The Sleigh compiler rejects code if it contains unused
@@ -1137,7 +1116,6 @@ public class StructuredSleigh {
/**
* The virtual fall-through label
- *
* <p>
* The idea is that no one should ever need to generate labels or gotos to achieve fall-through.
* Any attempt to do so probably indicates an implementation error where code generation failed
@@ -1178,7 +1156,6 @@ public class StructuredSleigh {
// Used only for variable name validation
final PcodeParser parser;
final SleighLanguage language;
- private final Factory factory;
private BlockStmt root;
// Used to determine statement binding, e.g., for "_break" and "_result"
@@ -1214,7 +1191,6 @@ public class StructuredSleigh {
protected StructuredSleigh(CompilerSpec cs) {
this.language = (SleighLanguage) cs.getLanguage();
this.parser = SleighProgramCompiler.createParser(language);
- this.factory = new Factory(language);
this.dtm = new StandAloneDataTypeManager("/", cs.getDataOrganization());
addDataTypeSource(dtm);
@@ -1282,7 +1258,6 @@ public class StructuredSleigh {
/**
* Declare a local variable with the given name and type
- *
* <p>
* If the variable has no definitive type, but has a known size, use e.g.,
* {@link Undefined8DataType} or {@link #type(String)} with "{@code /undefined8}". If the
@@ -1301,7 +1276,6 @@ public class StructuredSleigh {
/**
* Declare a local variable with the given name and initial value
- *
* <p>
* The type is taken from that of the initial value.
*
@@ -1377,7 +1351,6 @@ public class StructuredSleigh {
/**
* Generate a literal (or immediate or constant) value
- *
* <p>
* <b>WARNING:</b> Passing a literal int that turns out to be negative (easy to do in hex
* notation) can be perilous. For example, 0xdeadbeef will actually result in 0xffffffffdeadbeef
@@ -1425,7 +1398,6 @@ public class StructuredSleigh {
/**
* Generate Sleigh code
- *
* <p>
* This is similar in concept to inline assembly. It allows the embedding of Sleigh code into
* Structured Sleigh that is otherwise impossible or inconvenient to state. No effort is made to
@@ -1440,7 +1412,6 @@ public class StructuredSleigh {
/**
* Generate a Sleigh expression
- *
* <p>
* This is similar in concept to inline assembly, except it also has a value. It allows the
* embedding of Sleigh code into Structured Sleigh that is otherwise impossible or inconvenient
@@ -1476,7 +1447,6 @@ public class StructuredSleigh {
/**
* Generate an "else if" clause for the wrapped "if" statement
- *
* <p>
* This is shorthand for {@code _else(_if(...))} but avoids the unnecessary nesting of
* parentheses.
@@ -1498,7 +1468,6 @@ public class StructuredSleigh {
/**
* Generate an "if" statement
- *
* <p>
* The body is usually a lambda containing additional statements, predicated on this statement's
* condition, so that it resembles Java / C syntax:
@@ -1508,7 +1477,6 @@ public class StructuredSleigh {
* r1.set(1);
* });
* </pre>
- *
* <p>
* The returned "wrapper" provides for additional follow-on syntax, e.g.:
*
@@ -1532,7 +1500,6 @@ public class StructuredSleigh {
/**
* Generate a "while" statement
- *
* <p>
* The body is usually a lambda containing the controlled statements, so that it resembles Java
* / C syntax:
@@ -1553,7 +1520,6 @@ public class StructuredSleigh {
/**
* Generate a "for" statement
- *
* <p>
* The body is usually a lambda containing the controlled statements, so that it resembles Java
* / C syntax:
@@ -1566,7 +1532,6 @@ public class StructuredSleigh {
* total.addiTo(temp);
* });
* </pre>
- *
* <p>
* TIP: If the number of repetitions is known at generation time, consider using a standard Java
* for loop, as a sort of Structured Sleigh macro. For example, to broadcast element 0 to an
@@ -1578,7 +1543,6 @@ public class StructuredSleigh {
* arr.index(i).deref().set(arr.index(0).deref());
* }
* </pre>
- *
* <p>
* Instead of generating a loop, this will generate 15 Sleigh statements.
*
@@ -1593,7 +1557,6 @@ public class StructuredSleigh {
/**
* Generate a "break" statement
- *
* <p>
* This must appear in the body of a loop statement. It binds to the innermost loop statement in
* which it appears, generating code to leave that loop.
@@ -1604,7 +1567,6 @@ public class StructuredSleigh {
/**
* Generate a "continue" statement
- *
* <p>
* This must appear in the body of a loop statement. It binds to the innermost loop statement in
* which it appears, generating code to immediately repeat the loop, skipping the remainder of
@@ -1616,7 +1578,6 @@ public class StructuredSleigh {
/**
* Generate a "result" statement
- *
* <p>
* This is semantically similar to a C "return" statement, but is named differently to avoid
* confusion with Sleigh's return statement. When this is code implementing a p-code userop,
@@ -1634,12 +1595,10 @@ public class StructuredSleigh {
/**
* Generate a "return" statement
- *
* <p>
* This models (in part) a C-style return from the current target function to its caller. It
* simply generates the "return" Sleigh statement, which is an indirect branch to the given
* target. Target is typically popped from the stack or read from a link register.
- *
* <p>
* Contrast with {@link #_result(RVal)}
*
@@ -1660,7 +1619,6 @@ public class StructuredSleigh {
/**
* Get the method lookup for this context
- *
* <p>
* If the annotated methods cannot be accessed by {@link StructuredSleigh}, this method must be
* overridden. It should simply return {@link MethodHandles#lookup()}. This is necessary when
@@ -1673,7 +1631,7 @@ public class StructuredSleigh {
return MethodHandles.lookup();
}
- private <T> SleighPcodeUseropDefinition<T> compile(StructuredUserop annot, Lookup lookup,
+ private SleighPcodeUseropDefinition compile(StructuredUserop annot, Lookup lookup,
Method method) {
if (annot == null) {
throw new IllegalArgumentException("Method " + method + " is missing @" +
@@ -1691,7 +1649,7 @@ public class StructuredSleigh {
throw new IllegalArgumentException("Cannot access " + method + " having @" +
StructuredUserop.class.getSimpleName() + " annotation. Override getMethodLookup()");
}
- BuilderStage1 builder = factory.define(method.getName());
+ BuilderStage1 builder = SleighPcodeUseropDefinition.FACTORY.define(method.getName());
DataType retType = type(annot.type());
@@ -1733,7 +1691,7 @@ public class StructuredSleigh {
}
});
StringTree source = root.generate(FALL, FALL);
- builder.body(args -> source.toString());
+ builder.body(_ -> source.toString());
return builder.build();
}
@@ -1743,43 +1701,58 @@ public class StructuredSleigh {
* @param <T> the type of values used by the userops. For sleigh, this can be anything.
* @param into the destination map, usually belonging to a {@link PcodeUseropLibrary}.
*/
- public <T> void generate(Map<String, ? super SleighPcodeUseropDefinition<T>> into) {
+ public <T> void generate(Map<String, PcodeUseropDefinition<T>> into) {
Lookup lookup = getMethodLookup();
Class<? extends StructuredSleigh> cls = this.getClass();
- Set<Method> methods =
- CACHE_BY_CLASS.computeIfAbsent(cls, __ -> collectDefinitions(cls));
+ Set<Method> methods = CACHE_BY_CLASS.computeIfAbsent(cls, _ -> collectDefinitions(cls));
for (Method m : methods) {
- into.put(m.getName(), doGenerate(lookup, m));
+ into.put(m.getName(), doGenerate(lookup, m).cast());
}
}
/**
* Generate the userop for a given Java method
*
- * @param <T> the type of values used by the userop. For sleigh, this can be anything.
* @param m the method exported as a userop
* @return the userop
*/
- public <T> SleighPcodeUseropDefinition<T> generate(Method m) {
+ public SleighPcodeUseropDefinition generate(Method m) {
return doGenerate(getMethodLookup(), m);
}
- protected <T> SleighPcodeUseropDefinition<T> doGenerate(Lookup lookup, Method m) {
+ /**
+ * Generate the userop for the Java method with the given name
+ * <p>
+ * If more than one annotated method with the given name exists, one is chosen arbitrarily.
+ *
+ * @param name the method name exported as a userop
+ * @return the userop
+ */
+ public SleighPcodeUseropDefinition generate(String name) {
+ Class<? extends StructuredSleigh> cls = this.getClass();
+ Method method =
+ CACHE_BY_CLASS.computeIfAbsent(this.getClass(), _ -> collectDefinitions(cls))
+ .stream()
+ .filter(m -> m.getName().equals(name))
+ .findAny()
+ .orElseThrow();
+ return generate(method);
+ }
+
+ protected SleighPcodeUseropDefinition doGenerate(Lookup lookup, Method m) {
return compile(m.getAnnotation(StructuredUserop.class), lookup, m);
}
/**
* Generate all the exported userops and return them in a map
- *
* <p>
* This is typically only used when not part of a larger {@link PcodeUseropLibrary}, for example
* to aid in developing a Sleigh module or for generating injects.
*
- * @param <T> the type of values used by the userop. For sleigh, this can be anything.
* @return the userop
*/
- public <T> Map<String, SleighPcodeUseropDefinition<T>> generate() {
- Map<String, SleighPcodeUseropDefinition<T>> ops = new HashMap<>();
+ public <T> Map<String, PcodeUseropDefinition<T>> generate() {
+ Map<String, PcodeUseropDefinition<T>> ops = new HashMap<>();
generate(ops);
return ops;
}
diff --git a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibraryTest.java b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibraryTest.java
index 40de1f901e..bc3aa4ddbd 100644
--- a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibraryTest.java
+++ b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxAmd64SyscallUseropLibraryTest.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.
@@ -21,28 +21,26 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.util.ArrayList;
import java.util.List;
import org.junit.*;
import db.Transaction;
-import ghidra.app.plugin.assembler.Assembler;
-import ghidra.app.plugin.assembler.Assemblers;
-import ghidra.pcode.emu.PcodeEmulator;
-import ghidra.pcode.emu.PcodeThread;
+import ghidra.app.plugin.assembler.*;
+import ghidra.pcode.emu.*;
import ghidra.pcode.emu.sys.EmuProcessExitedException;
import ghidra.pcode.emu.sys.SyscallTestHelper;
import ghidra.pcode.emu.sys.SyscallTestHelper.SyscallName;
import ghidra.pcode.emu.unix.*;
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.Language;
-import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryBlock;
+import ghidra.program.model.pcode.PcodeOp;
import ghidra.test.AbstractGhidraHeadlessIntegrationTest;
import ghidra.util.task.TaskMonitor;
@@ -79,9 +77,16 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
}
}
- protected final class LinuxAmd64PcodeEmulator extends PcodeEmulator {
- protected EmuLinuxAmd64SyscallUseropLibrary<byte[]> syscalls;
+ public static final class CaptureUseropLibrary extends AnnotatedPcodeUseropLibrary<byte[]> {
+ public final List<Long> captured = new ArrayList<>();
+
+ @PcodeUserop(functional = true)
+ public void capture(@OpInput(signed = true) long value) {
+ captured.add(value);
+ }
+ }
+ protected final class LinuxAmd64PcodeEmulator extends PcodeEmulator {
public LinuxAmd64PcodeEmulator() {
super(program.getLanguage());
}
@@ -89,7 +94,30 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
@Override
protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
syscalls = new EmuLinuxAmd64SyscallUseropLibrary<>(this, fs, program);
- return syscalls;
+ capture = new CaptureUseropLibrary();
+ return syscalls.compose(capture);
+ }
+
+ @Override
+ protected BytesPcodeThread createThread(String name) {
+ return new BytesPcodeThread(name, this) {
+ int count = 0;
+
+ @Override
+ protected PcodeThreadExecutor<byte[]> createExecutor() {
+ return new PcodeThreadExecutor<>(this) {
+ @Override
+ public void stepOp(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<byte[]> library) {
+ count++;
+ if (count > 1000) {
+ fail("Probably an infinite loop");
+ }
+ super.stepOp(op, frame, library);
+ }
+ };
+ }
+ };
}
}
@@ -104,13 +132,13 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
Language language;
Assembler asm;
- Register regRIP;
- Register regRAX;
AddressSpace space;
Address start;
int size;
MemoryBlock block;
- private EmuUnixFileSystem<byte[]> fs;
+ EmuLinuxAmd64SyscallUseropLibrary<byte[]> syscalls;
+ CaptureUseropLibrary capture;
+ EmuUnixFileSystem<byte[]> fs;
PcodeArithmetic<byte[]> arithmetic;
@Before
@@ -119,13 +147,11 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
language = program.getLanguage();
arithmetic = BytesPcodeArithmetic.forLanguage(language);
- regRIP = program.getRegister("RIP");
- regRAX = program.getRegister("RAX");
space = program.getAddressFactory().getDefaultAddressSpace();
start = space.getAddress(0x00400000);
size = 0x1000;
- try (Transaction tx = program.openTransaction("Initialize")) {
+ try (Transaction _ = program.openTransaction("Initialize")) {
block = program.getMemory()
.createInitializedBlock(".text", start, size, (byte) 0, TaskMonitor.DUMMY,
false);
@@ -146,8 +172,12 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
}
}
- public LinuxAmd64PcodeEmulator prepareEmulator() throws Exception {
- LinuxAmd64PcodeEmulator emu = new LinuxAmd64PcodeEmulator();
+ protected PcodeEmulator createEmulator() {
+ return new LinuxAmd64PcodeEmulator();
+ }
+
+ public PcodeEmulator prepareEmulator() throws Exception {
+ PcodeEmulator emu = createEmulator();
// The emulator is not itself bound to the program or a trace, so copy bytes in
byte[] buf = new byte[size];
assertEquals(size, block.getBytes(start, buf));
@@ -155,7 +185,7 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
return emu;
}
- public PcodeThread<byte[]> launchThread(LinuxAmd64PcodeEmulator emu, Address pc) {
+ public PcodeThread<byte[]> launchThread(PcodeEmulator emu, Address pc) {
PcodeThread<byte[]> thread = emu.newThread();
thread.overrideCounter(start);
thread.overrideContextWithDefault();
@@ -163,22 +193,9 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
return thread;
}
- public void stepGroupExit(PcodeThread<byte[]> thread) {
- // Step up to the group_exit
- thread.stepInstruction(2);
- // Then verify the syscall interrupts execution
- try {
- thread.stepInstruction();
- fail();
- }
- catch (EmuProcessExitedException e) {
- // pass
- }
- }
-
public void execute(PcodeThread<byte[]> thread) {
try {
- thread.stepInstruction(1000);
+ thread.run();
fail();
}
catch (EmuProcessExitedException e) {
@@ -187,208 +204,268 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
@Test
public void testWriteStdout() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV RAX," + Syscall.WRITE.number,
- "MOV RDI," + EmuUnixFileDescriptor.FD_STDOUT,
- "LEA RSI,[0x00400800]",
- "MOV RDX," + BYTES_HW.length,
- "SYSCALL",
- "MOV RAX," + Syscall.GROUP_EXIT.number,
- "MOV RDI,0",
- "SYSCALL");
- block.putBytes(space.getAddress(0x00400800), BYTES_HW);
+ Address hwAddr = space.getAddress(0x00400800);
+
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+ buf.assemble("MOV RAX, %d".formatted(Syscall.WRITE.number));
+ buf.assemble("MOV RDI, %d".formatted(EmuUnixFileDescriptor.FD_STDOUT));
+ buf.assemble("LEA RSI, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV RDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("SYSCALL");
+ final Address captureAt = buf.getNext();
+ buf.assemble("MOV RAX, %d".formatted(Syscall.GROUP_EXIT.number));
+ buf.assemble("MOV RDI, 0");
+ buf.assemble("SYSCALL");
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
+ block.putBytes(hwAddr, BYTES_HW);
}
- LinuxAmd64PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(RAX); emu_exec_decoded();");
// Capture stdout into a byte array
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), null, stdout));
+ execute(thread);
- // Step through write and verify return value and actual output effect
- thread.stepInstruction(5);
- assertArrayEquals(arithmetic.fromConst(BYTES_HW.length, regRAX.getNumBytes()),
- thread.getState().getVar(regRAX, Reason.INSPECT));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HW, stdout.toByteArray());
-
- stepGroupExit(thread);
}
@Test
public void testReadStdin() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV RAX," + Syscall.READ.number,
- "MOV RDI," + EmuUnixFileDescriptor.FD_STDIN,
- "LEA RSI,[0x00400800]",
- "MOV RDX," + BYTES_HW.length,
- "SYSCALL",
- "MOV RAX," + Syscall.GROUP_EXIT.number,
- "MOV RDI,0",
- "SYSCALL");
+ Address hwAddr = space.getAddress(0x00400800);
+
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+ buf.assemble("MOV RAX, %d".formatted(Syscall.READ.number));
+ buf.assemble("MOV RDI, %d".formatted(EmuUnixFileDescriptor.FD_STDIN));
+ buf.assemble("LEA RSI, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV RDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("SYSCALL");
+ final Address captureAt = buf.getNext();
+ buf.assemble("MOV RAX, %d".formatted(Syscall.GROUP_EXIT.number));
+ buf.assemble("MOV RDI, 0");
+ buf.assemble("SYSCALL");
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
}
- LinuxAmd64PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(RAX); emu_exec_decoded();");
// Provide stdin via a byte array
ByteArrayInputStream stdin = new ByteArrayInputStream(BYTES_HW);
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), stdin, null));
+ execute(thread);
- // Step through write and verify return value and actual output effect
- thread.stepInstruction(5);
- assertArrayEquals(arithmetic.fromConst(BYTES_HW.length, regRAX.getNumBytes()),
- thread.getState().getVar(regRAX, Reason.INSPECT));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HW,
- emu.getSharedState().getVar(space, 0x00400800, BYTES_HW.length, true, Reason.INSPECT));
-
- stepGroupExit(thread);
+ emu.getSharedState().getVar(hwAddr, BYTES_HW.length, true, Reason.INSPECT));
}
@Test
public void testWritevStdout() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- Address data = space.getAddress(0x00400800);
- ByteBuffer buf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
-
- Address strHello = data.add(buf.position());
- buf.put(BYTES_HELLO);
- Address endHello = data.add(buf.position());
- Address iov = data.add(buf.position());
- buf.putLong(strHello.getOffset());
- buf.putLong(endHello.subtract(strHello));
- int posIov1base = buf.position();
- buf.putLong(0);
- int posIov1len = buf.position();
- buf.putLong(0);
- Address strWorld = data.add(buf.position());
- buf.put(BYTES_WORLD);
- Address endWorld = data.add(buf.position());
- // Backpatch
- buf.putLong(posIov1base, strWorld.getOffset());
- buf.putLong(posIov1len, endWorld.subtract(strWorld));
-
- asm.assemble(start,
- "MOV RAX," + Syscall.WRITEV.number,
- "MOV RDI," + EmuUnixFileDescriptor.FD_STDOUT,
- "LEA RSI,[0x" + iov + "]",
- "MOV RDX,2",
- "SYSCALL",
- "MOV RAX," + Syscall.GROUP_EXIT.number,
- "MOV RDI,0",
- "SYSCALL");
- block.putBytes(data, buf.array());
+ Address data = space.getAddress(0x00400800);
+
+ ByteBuffer dBuf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
+ Address strHello = data.add(dBuf.position());
+ dBuf.put(BYTES_HELLO);
+ Address endHello = data.add(dBuf.position());
+ Address iov = data.add(dBuf.position());
+ dBuf.putLong(strHello.getOffset());
+ dBuf.putLong(endHello.subtract(strHello));
+ int posIov1base = dBuf.position();
+ dBuf.putLong(0);
+ int posIov1len = dBuf.position();
+ dBuf.putLong(0);
+ Address strWorld = data.add(dBuf.position());
+ dBuf.put(BYTES_WORLD);
+ Address endWorld = data.add(dBuf.position());
+ // Backpatch
+ dBuf.putLong(posIov1base, strWorld.getOffset());
+ dBuf.putLong(posIov1len, endWorld.subtract(strWorld));
+
+ AssemblyBuffer cBuf = new AssemblyBuffer(asm, start);
+ cBuf.assemble("MOV RAX, %d".formatted(Syscall.WRITEV.number));
+ cBuf.assemble("MOV RDI, %d".formatted(EmuUnixFileDescriptor.FD_STDOUT));
+ cBuf.assemble("LEA RSI, [0x%x]".formatted(iov.getOffset()));
+ cBuf.assemble("MOV RDX, 2");
+ cBuf.assemble("SYSCALL");
+ final Address captureAt = cBuf.getNext();
+ cBuf.assemble("MOV RAX, %d".formatted(Syscall.GROUP_EXIT.number));
+ cBuf.assemble("MOV RDI, 0");
+ cBuf.assemble("SYSCALL");
+ cBuf.assemble("JMP 0x%x".formatted(cBuf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, cBuf.getBytes());
+ block.putBytes(data, dBuf.array());
}
- LinuxAmd64PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(RAX); emu_exec_decoded();");
// Capture stdout into a byte array
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), null, stdout));
+ execute(thread);
- // Step through writev and verify return value and actual output effect
- thread.stepInstruction(5);
-
- assertEquals(BYTES_HW.length,
- arithmetic.toLong(thread.getState().getVar(regRAX, Reason.INSPECT), Purpose.OTHER));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HW, stdout.toByteArray());
-
- stepGroupExit(thread);
}
@Test
public void testReadvStdin() throws Exception {
- Address strHello;
- Address strWorld;
- try (Transaction tx = program.openTransaction("Initialize")) {
- Address data = space.getAddress(0x00400800);
- ByteBuffer buf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
-
- strHello = data.add(buf.position());
- buf.put(new byte[BYTES_HELLO.length]);
- Address endHello = data.add(buf.position());
- Address iov = data.add(buf.position());
- buf.putLong(strHello.getOffset());
- buf.putLong(endHello.subtract(strHello));
- int posIov1base = buf.position();
- buf.putLong(0);
- int posIov1len = buf.position();
- buf.putLong(0);
- strWorld = data.add(buf.position());
- buf.put(new byte[BYTES_WORLD.length]);
- Address endWorld = data.add(buf.position());
- // Backpatch
- buf.putLong(posIov1base, strWorld.getOffset());
- buf.putLong(posIov1len, endWorld.subtract(strWorld));
-
- asm.assemble(start,
- "MOV RAX," + Syscall.READV.number,
- "MOV RDI," + EmuUnixFileDescriptor.FD_STDIN,
- "LEA RSI,[0x" + iov + "]",
- "MOV RDX,2",
- "SYSCALL",
- "MOV RAX," + Syscall.GROUP_EXIT.number,
- "MOV RDI,0",
- "SYSCALL");
- block.putBytes(data, buf.array());
+ Address data = space.getAddress(0x00400800);
+
+ ByteBuffer dBuf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
+ Address strHello = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_HELLO.length]);
+ Address endHello = data.add(dBuf.position());
+ Address iov = data.add(dBuf.position());
+ dBuf.putLong(strHello.getOffset());
+ dBuf.putLong(endHello.subtract(strHello));
+ int posIov1base = dBuf.position();
+ dBuf.putLong(0);
+ int posIov1len = dBuf.position();
+ dBuf.putLong(0);
+ Address strWorld = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_WORLD.length]);
+ Address endWorld = data.add(dBuf.position());
+ // Backpatch
+ dBuf.putLong(posIov1base, strWorld.getOffset());
+ dBuf.putLong(posIov1len, endWorld.subtract(strWorld));
+
+ AssemblyBuffer cBuf = new AssemblyBuffer(asm, start);
+ cBuf.assemble("MOV RAX, %d".formatted(Syscall.READV.number));
+ cBuf.assemble("MOV RDI, %d".formatted(EmuUnixFileDescriptor.FD_STDIN));
+ cBuf.assemble("LEA RSI, [0x%x]".formatted(iov.getOffset()));
+ cBuf.assemble("MOV RDX, 2");
+ cBuf.assemble("SYSCALL");
+ final Address captureAt = cBuf.getNext();
+ cBuf.assemble("MOV RAX, %d".formatted(Syscall.GROUP_EXIT.number));
+ cBuf.assemble("MOV RDI, 0");
+ cBuf.assemble("SYSCALL");
+ cBuf.assemble("JMP 0x%x".formatted(cBuf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, cBuf.getBytes());
+ block.putBytes(data, dBuf.array());
}
- LinuxAmd64PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(RAX); emu_exec_decoded();");
// Provide stdin via a byte array
ByteArrayInputStream stdin = new ByteArrayInputStream(BYTES_HW);
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), stdin, null));
+ execute(thread);
- // Step through readv and verify return value and actual output effect
- thread.stepInstruction(5);
-
- assertEquals(BYTES_HW.length,
- arithmetic.toLong(thread.getState().getVar(regRAX, Reason.INSPECT), Purpose.OTHER));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HELLO, emu.getSharedState()
.getVar(space, strHello.getOffset(), BYTES_HELLO.length, true, Reason.INSPECT));
assertArrayEquals(BYTES_WORLD, emu.getSharedState()
.getVar(space, strWorld.getOffset(), BYTES_WORLD.length, true, Reason.INSPECT));
+ }
- stepGroupExit(thread);
+ @Test
+ public void testReadvStdinErr() throws Exception {
+ Address data = space.getAddress(0x00400800);
+
+ ByteBuffer dBuf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
+ Address strHello = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_HELLO.length]);
+ Address endHello = data.add(dBuf.position());
+ Address iov = data.add(dBuf.position());
+ dBuf.putLong(strHello.getOffset());
+ dBuf.putLong(endHello.subtract(strHello));
+ int posIov1base = dBuf.position();
+ dBuf.putLong(0);
+ int posIov1len = dBuf.position();
+ dBuf.putLong(0);
+ Address strWorld = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_WORLD.length]);
+ Address endWorld = data.add(dBuf.position());
+ // Backpatch
+ dBuf.putLong(posIov1base, strWorld.getOffset());
+ dBuf.putLong(posIov1len, endWorld.subtract(strWorld));
+
+ AssemblyBuffer cBuf = new AssemblyBuffer(asm, start);
+ cBuf.assemble("MOV RAX, %d".formatted(Syscall.READV.number));
+ cBuf.assemble("MOV RDI, %d".formatted(EmuUnixFileDescriptor.FD_STDIN));
+ cBuf.assemble("LEA RSI, [0x%x]".formatted(iov.getOffset()));
+ cBuf.assemble("MOV RDX, 2");
+ cBuf.assemble("SYSCALL");
+ final Address captureAt = cBuf.getNext();
+ cBuf.assemble("MOV RAX, %d".formatted(Syscall.GROUP_EXIT.number));
+ cBuf.assemble("MOV RDI, 0");
+ cBuf.assemble("SYSCALL");
+ cBuf.assemble("JMP 0x%x".formatted(cBuf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, cBuf.getBytes());
+ block.putBytes(data, dBuf.array());
+ }
+
+ PcodeEmulator emu = prepareEmulator();
+ PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(RAX); emu_exec_decoded();");
+
+ // DO NOT provide FD_STDIN, so that we get EBADF
+ execute(thread);
+
+ assertEquals(List.of((long) -9), capture.captured);
+ assertArrayEquals(new byte[BYTES_HELLO.length], emu.getSharedState()
+ .getVar(space, strHello.getOffset(), BYTES_HELLO.length, true, Reason.INSPECT));
+ assertArrayEquals(new byte[BYTES_WORLD.length], emu.getSharedState()
+ .getVar(space, strWorld.getOffset(), BYTES_WORLD.length, true, Reason.INSPECT));
}
@Test
public void testOpenWriteClose() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV RAX," + Syscall.OPEN.number,
- "LEA RDI,[0x00400880]",
- "MOV RSI," + (AbstractEmuLinuxSyscallUseropLibrary.O_WRONLY |
- AbstractEmuLinuxSyscallUseropLibrary.O_CREAT),
- "MOV RDX," + (0600),
- "SYSCALL",
- "MOV RBP, RAX",
-
- "MOV RAX," + Syscall.WRITE.number,
- "MOV RDI,RBP",
- "LEA RSI,[0x00400800]",
- "MOV RDX," + BYTES_HW.length,
- "SYSCALL",
-
- "MOV RAX," + Syscall.CLOSE.number,
- "MOV RDI,RBP",
-
- "MOV RAX," + Syscall.GROUP_EXIT.number,
- "MOV RDI,0",
- "SYSCALL");
- block.putBytes(space.getAddress(0x00400800), BYTES_HW);
- block.putBytes(space.getAddress(0x00400880), "myfile\0".getBytes());
+ Address myFileAddr = space.getAddress(0x00400880);
+ Address hwAddr = space.getAddress(0x00400800);
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.OPEN.number));
+ buf.assemble("LEA RDI, [0x%x]".formatted(myFileAddr.getOffset()));
+ buf.assemble("MOV RSI, 0x%x".formatted(AbstractEmuLinuxSyscallUseropLibrary.O_WRONLY |
+ AbstractEmuLinuxSyscallUseropLibrary.O_CREAT));
+ buf.assemble("MOV RDX, 0x%x".formatted(0600));
+ buf.assemble("SYSCALL");
+ buf.assemble("MOV RBP, RAX");
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.WRITE.number));
+ buf.assemble("MOV RDI, RBP");
+ buf.assemble("LEA RSI, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV RDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("SYSCALL");
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.CLOSE.number));
+ buf.assemble("MOV RDI, RBP");
+ buf.assemble("SYSCALL");
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.GROUP_EXIT.number));
+ buf.assemble("MOV RDI, 0");
+ buf.assemble("SYSCALL");
+
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
+ block.putBytes(hwAddr, BYTES_HW);
+ block.putBytes(myFileAddr, "myfile\0".getBytes());
}
- LinuxAmd64PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
execute(thread);
@@ -400,38 +477,46 @@ public class EmuLinuxAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadles
@Test
public void testOpenReadClose() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV RAX," + Syscall.OPEN.number,
- "LEA RDI,[0x00400880]",
- "MOV RSI," + (AbstractEmuLinuxSyscallUseropLibrary.O_RDONLY),
- "MOV RDX," + (0600),
- "SYSCALL",
- "MOV RBP, RAX",
-
- "MOV RAX," + Syscall.READ.number,
- "MOV RDI,RBP",
- "LEA RSI,[0x00400800]",
- "MOV RDX," + BYTES_HW.length,
- "SYSCALL",
-
- "MOV RAX," + Syscall.CLOSE.number,
- "MOV RDI,RBP",
-
- "MOV RAX," + Syscall.GROUP_EXIT.number,
- "MOV RDI,0",
- "SYSCALL");
- block.putBytes(space.getAddress(0x00400880), "myfile\0".getBytes());
+ Address myFileAddr = space.getAddress(0x00400880);
+ Address hwAddr = space.getAddress(0x00400800);
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.OPEN.number));
+ buf.assemble("LEA RDI, [0x%x]".formatted(myFileAddr.getOffset()));
+ buf.assemble("MOV RSI, 0x%x".formatted(AbstractEmuLinuxSyscallUseropLibrary.O_RDONLY));
+ buf.assemble("MOV RDX, 0x%x".formatted(0600));
+ buf.assemble("SYSCALL");
+ buf.assemble("MOV RBP, RAX");
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.READ.number));
+ buf.assemble("MOV RDI, RBP");
+ buf.assemble("LEA RSI, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV RDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("SYSCALL");
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.CLOSE.number));
+ buf.assemble("MOV RDI, RBP");
+ buf.assemble("SYSCALL");
+
+ buf.assemble("MOV RAX, %d".formatted(Syscall.GROUP_EXIT.number));
+ buf.assemble("MOV RDI, 0");
+ buf.assemble("SYSCALL");
+
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
+ block.putBytes(myFileAddr, "myfile\0".getBytes());
}
EmuUnixFile<byte[]> file = fs.createOrGetFile("myfile", 0600);
file.write(arithmetic, arithmetic.fromConst(0, 8), BYTES_HW);
- LinuxAmd64PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
execute(thread);
assertArrayEquals(BYTES_HW,
- emu.getSharedState().getVar(space, 0x00400800, BYTES_HW.length, true, Reason.INSPECT));
+ emu.getSharedState().getVar(hwAddr, BYTES_HW.length, true, Reason.INSPECT));
}
}
diff --git a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibraryTest.java b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibraryTest.java
index 8defdc7a58..809348cbbd 100644
--- a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibraryTest.java
+++ b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/EmuLinuxX86SyscallUseropLibraryTest.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,23 +26,21 @@ import java.util.List;
import org.junit.*;
import db.Transaction;
-import ghidra.app.plugin.assembler.Assembler;
-import ghidra.app.plugin.assembler.Assemblers;
+import ghidra.app.plugin.assembler.*;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
-import ghidra.pcode.emu.PcodeEmulator;
-import ghidra.pcode.emu.PcodeThread;
+import ghidra.pcode.emu.*;
+import ghidra.pcode.emu.linux.EmuLinuxAmd64SyscallUseropLibraryTest.CaptureUseropLibrary;
import ghidra.pcode.emu.sys.EmuProcessExitedException;
import ghidra.pcode.emu.sys.SyscallTestHelper;
import ghidra.pcode.emu.sys.SyscallTestHelper.SyscallName;
import ghidra.pcode.emu.unix.*;
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.Register;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryBlock;
+import ghidra.program.model.pcode.PcodeOp;
import ghidra.test.AbstractGhidraHeadlessIntegrationTest;
import ghidra.util.task.TaskMonitor;
@@ -80,7 +78,6 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
}
protected final class LinuxX86PcodeEmulator extends PcodeEmulator {
- protected EmuLinuxX86SyscallUseropLibrary<byte[]> syscalls;
public LinuxX86PcodeEmulator() {
super(program.getLanguage());
@@ -89,7 +86,30 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
@Override
protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
syscalls = new EmuLinuxX86SyscallUseropLibrary<>(this, fs, program);
- return syscalls;
+ capture = new CaptureUseropLibrary();
+ return syscalls.compose(capture);
+ }
+
+ @Override
+ protected BytesPcodeThread createThread(String name) {
+ return new BytesPcodeThread(name, this) {
+ int count = 0;
+
+ @Override
+ protected PcodeThreadExecutor<byte[]> createExecutor() {
+ return new PcodeThreadExecutor<>(this) {
+ @Override
+ public void stepOp(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<byte[]> library) {
+ count++;
+ if (count > 1000) {
+ fail("Probably an infinite loop");
+ }
+ super.stepOp(op, frame, library);
+ }
+ };
+ }
+ };
}
}
@@ -104,13 +124,13 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
SleighLanguage language;
Assembler asm;
- Register regEIP;
- Register regEAX;
AddressSpace space;
Address start;
int size;
MemoryBlock block;
- private EmuUnixFileSystem<byte[]> fs;
+ EmuLinuxX86SyscallUseropLibrary<byte[]> syscalls;
+ CaptureUseropLibrary capture;
+ EmuUnixFileSystem<byte[]> fs;
PcodeArithmetic<byte[]> arithmetic;
@Before
@@ -119,13 +139,11 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
language = (SleighLanguage) program.getLanguage();
arithmetic = BytesPcodeArithmetic.forLanguage(language);
- regEIP = program.getRegister("EIP");
- regEAX = program.getRegister("EAX");
space = program.getAddressFactory().getDefaultAddressSpace();
start = space.getAddress(0x00400000);
size = 0x1000;
- try (Transaction tx = program.openTransaction("Initialize")) {
+ try (Transaction _ = program.openTransaction("Initialize")) {
block = program.getMemory()
.createInitializedBlock(".text", start, size, (byte) 0, TaskMonitor.DUMMY,
false);
@@ -146,8 +164,12 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
}
}
- public LinuxX86PcodeEmulator prepareEmulator() throws Exception {
- LinuxX86PcodeEmulator emu = new LinuxX86PcodeEmulator();
+ protected PcodeEmulator createEmulator() {
+ return new LinuxX86PcodeEmulator();
+ }
+
+ public PcodeEmulator prepareEmulator() throws Exception {
+ PcodeEmulator emu = createEmulator();
// The emulator is not itself bound to the program or a trace, so copy bytes in
byte[] buf = new byte[size];
assertEquals(size, block.getBytes(start, buf));
@@ -155,7 +177,7 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
return emu;
}
- public PcodeThread<byte[]> launchThread(LinuxX86PcodeEmulator emu, Address pc) {
+ public PcodeThread<byte[]> launchThread(PcodeEmulator emu, Address pc) {
PcodeThread<byte[]> thread = emu.newThread();
thread.overrideCounter(start);
thread.overrideContextWithDefault();
@@ -163,22 +185,9 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
return thread;
}
- public void stepGroupExit(PcodeThread<byte[]> thread) {
- // Step up to the group_exit
- thread.stepInstruction(2);
- // Then verify the syscall interrupts execution
- try {
- thread.stepInstruction();
- fail();
- }
- catch (EmuProcessExitedException e) {
- // pass
- }
- }
-
public void execute(PcodeThread<byte[]> thread) {
try {
- thread.stepInstruction(1000);
+ thread.run();
fail();
}
catch (EmuProcessExitedException e) {
@@ -187,208 +196,268 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
@Test
public void testWriteStdout() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV EAX," + Syscall.WRITE.number,
- "MOV EBX," + EmuUnixFileDescriptor.FD_STDOUT,
- "LEA ECX,[0x00400800]",
- "MOV EDX," + BYTES_HW.length,
- "INT 0x80",
- "MOV EAX," + Syscall.EXIT.number,
- "MOV EBX,0",
- "INT 0x80");
- block.putBytes(space.getAddress(0x00400800), BYTES_HW);
+ Address hwAddr = space.getAddress(0x00400800);
+
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+ buf.assemble("MOV EAX, %d".formatted(Syscall.WRITE.number));
+ buf.assemble("MOV EBX, %d".formatted(EmuUnixFileDescriptor.FD_STDOUT));
+ buf.assemble("LEA ECX, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV EDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("INT 0x80");
+ final Address captureAt = buf.getNext();
+ buf.assemble("MOV EAX, %d".formatted(Syscall.EXIT.number));
+ buf.assemble("MOV EBX, 0");
+ buf.assemble("INT 0x80");
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
+ block.putBytes(hwAddr, BYTES_HW);
}
- LinuxX86PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(EAX); emu_exec_decoded();");
// Capture stdout into a byte array
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), null, stdout));
+ execute(thread);
- // Step through write and verify return value and actual output effect
- thread.stepInstruction(5);
- assertArrayEquals(arithmetic.fromConst(BYTES_HW.length, regEAX.getNumBytes()),
- thread.getState().getVar(regEAX, Reason.INSPECT));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HW, stdout.toByteArray());
-
- stepGroupExit(thread);
}
@Test
public void testReadStdin() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV EAX," + Syscall.READ.number,
- "MOV EBX," + EmuUnixFileDescriptor.FD_STDIN,
- "LEA ECX,[0x00400800]",
- "MOV EDX," + BYTES_HW.length,
- "INT 0x80",
- "MOV EAX," + Syscall.EXIT.number,
- "MOV EBX,0",
- "INT 0x80");
+ Address hwAddr = space.getAddress(0x00400800);
+
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+ buf.assemble("MOV EAX, %d".formatted(Syscall.READ.number));
+ buf.assemble("MOV EBX, %d".formatted(EmuUnixFileDescriptor.FD_STDIN));
+ buf.assemble("LEA ECX, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV EDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("INT 0x80");
+ final Address captureAt = buf.getNext();
+ buf.assemble("MOV EAX, %d".formatted(Syscall.EXIT.number));
+ buf.assemble("MOV EBX, 0");
+ buf.assemble("INT 0x80");
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
}
- LinuxX86PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(EAX); emu_exec_decoded();");
// Provide stdin via a byte array
ByteArrayInputStream stdin = new ByteArrayInputStream(BYTES_HW);
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), stdin, null));
+ execute(thread);
- // Step through write and verify return value and actual output effect
- thread.stepInstruction(5);
- assertArrayEquals(arithmetic.fromConst(BYTES_HW.length, regEAX.getNumBytes()),
- thread.getState().getVar(regEAX, Reason.INSPECT));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HW,
- emu.getSharedState().getVar(space, 0x00400800, BYTES_HW.length, true, Reason.INSPECT));
-
- stepGroupExit(thread);
+ emu.getSharedState().getVar(hwAddr, BYTES_HW.length, true, Reason.INSPECT));
}
@Test
public void testWritevStdout() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- Address data = space.getAddress(0x00400800);
- ByteBuffer buf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
-
- Address strHello = data.add(buf.position());
- buf.put(BYTES_HELLO);
- Address endHello = data.add(buf.position());
- Address iov = data.add(buf.position());
- buf.putInt((int) strHello.getOffset());
- buf.putInt((int) endHello.subtract(strHello));
- int posIov1base = buf.position();
- buf.putInt(0);
- int posIov1len = buf.position();
- buf.putInt(0);
- Address strWorld = data.add(buf.position());
- buf.put(BYTES_WORLD);
- Address endWorld = data.add(buf.position());
- // Backpatch
- buf.putInt(posIov1base, (int) strWorld.getOffset());
- buf.putInt(posIov1len, (int) endWorld.subtract(strWorld));
-
- asm.assemble(start,
- "MOV EAX," + Syscall.WRITEV.number,
- "MOV EBX," + EmuUnixFileDescriptor.FD_STDOUT,
- "LEA ECX,[0x" + iov + "]",
- "MOV EDX,2",
- "INT 0x80",
- "MOV EAX," + Syscall.EXIT.number,
- "MOV EBX,0",
- "INT 0x80");
- block.putBytes(data, buf.array());
+ Address data = space.getAddress(0x00400800);
+
+ ByteBuffer dBuf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
+ Address strHello = data.add(dBuf.position());
+ dBuf.put(BYTES_HELLO);
+ Address endHello = data.add(dBuf.position());
+ Address iov = data.add(dBuf.position());
+ dBuf.putInt((int) strHello.getOffset());
+ dBuf.putInt((int) endHello.subtract(strHello));
+ int posIov1base = dBuf.position();
+ dBuf.putInt(0);
+ int posIov1len = dBuf.position();
+ dBuf.putInt(0);
+ Address strWorld = data.add(dBuf.position());
+ dBuf.put(BYTES_WORLD);
+ Address endWorld = data.add(dBuf.position());
+ // Backpatch
+ dBuf.putInt(posIov1base, (int) strWorld.getOffset());
+ dBuf.putInt(posIov1len, (int) endWorld.subtract(strWorld));
+
+ AssemblyBuffer cBuf = new AssemblyBuffer(asm, start);
+ cBuf.assemble("MOV EAX, %d".formatted(Syscall.WRITEV.number));
+ cBuf.assemble("MOV EBX, %d".formatted(EmuUnixFileDescriptor.FD_STDOUT));
+ cBuf.assemble("LEA ECX, [0x%x]".formatted(iov.getOffset()));
+ cBuf.assemble("MOV EDX, 2");
+ cBuf.assemble("INT 0x80");
+ final Address captureAt = cBuf.getNext();
+ cBuf.assemble("MOV EAX, %d".formatted(Syscall.EXIT.number));
+ cBuf.assemble("MOV EBX, 0");
+ cBuf.assemble("INT 0x80");
+ cBuf.assemble("JMP 0x%x".formatted(cBuf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, cBuf.getBytes());
+ block.putBytes(data, dBuf.array());
}
- LinuxX86PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(EAX); emu_exec_decoded();");
// Capture stdout into a byte array
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDOUT,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), null, stdout));
+ execute(thread);
- // Step through writev and verify return value and actual output effect
- thread.stepInstruction(5);
-
- assertEquals(BYTES_HW.length,
- arithmetic.toLong(thread.getState().getVar(regEAX, Reason.INSPECT), Purpose.OTHER));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HW, stdout.toByteArray());
-
- stepGroupExit(thread);
}
@Test
public void testReadvStdin() throws Exception {
- Address strHello;
- Address strWorld;
- try (Transaction tx = program.openTransaction("Initialize")) {
- Address data = space.getAddress(0x00400800);
- ByteBuffer buf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
-
- strHello = data.add(buf.position());
- buf.put(new byte[BYTES_HELLO.length]);
- Address endHello = data.add(buf.position());
- Address iov = data.add(buf.position());
- buf.putInt((int) strHello.getOffset());
- buf.putInt((int) endHello.subtract(strHello));
- int posIov1base = buf.position();
- buf.putInt(0);
- int posIov1len = buf.position();
- buf.putInt(0);
- strWorld = data.add(buf.position());
- buf.put(new byte[BYTES_WORLD.length]);
- Address endWorld = data.add(buf.position());
- // Backpatch
- buf.putInt(posIov1base, (int) strWorld.getOffset());
- buf.putInt(posIov1len, (int) endWorld.subtract(strWorld));
-
- asm.assemble(start,
- "MOV EAX," + Syscall.READV.number,
- "MOV EBX," + EmuUnixFileDescriptor.FD_STDIN,
- "LEA ECX,[0x" + iov + "]",
- "MOV EDX,2",
- "INT 0x80",
- "MOV EAX," + Syscall.EXIT.number,
- "MOV EBX,0",
- "INT 0x80");
- block.putBytes(data, buf.array());
+ Address data = space.getAddress(0x00400800);
+
+ ByteBuffer dBuf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
+ Address strHello = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_HELLO.length]);
+ Address endHello = data.add(dBuf.position());
+ Address iov = data.add(dBuf.position());
+ dBuf.putInt((int) strHello.getOffset());
+ dBuf.putInt((int) endHello.subtract(strHello));
+ int posIov1base = dBuf.position();
+ dBuf.putInt(0);
+ int posIov1len = dBuf.position();
+ dBuf.putInt(0);
+ Address strWorld = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_WORLD.length]);
+ Address endWorld = data.add(dBuf.position());
+ // Backpatch
+ dBuf.putInt(posIov1base, (int) strWorld.getOffset());
+ dBuf.putInt(posIov1len, (int) endWorld.subtract(strWorld));
+
+ AssemblyBuffer cBuf = new AssemblyBuffer(asm, start);
+ cBuf.assemble("MOV EAX, %d".formatted(Syscall.READV.number));
+ cBuf.assemble("MOV EBX, %d".formatted(EmuUnixFileDescriptor.FD_STDIN));
+ cBuf.assemble("LEA ECX, [0x%x]".formatted(iov.getOffset()));
+ cBuf.assemble("MOV EDX, 2");
+ cBuf.assemble("INT 0x80");
+ final Address captureAt = cBuf.getNext();
+ cBuf.assemble("MOV EAX, %d".formatted(Syscall.EXIT.number));
+ cBuf.assemble("MOV EBX, 0");
+ cBuf.assemble("INT 0x80");
+ cBuf.assemble("JMP 0x%x".formatted(cBuf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, cBuf.getBytes());
+ block.putBytes(data, dBuf.array());
}
- LinuxX86PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(EAX); emu_exec_decoded();");
// Provide stdin via a byte array
ByteArrayInputStream stdin = new ByteArrayInputStream(BYTES_HW);
- emu.syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
+ syscalls.putDescriptor(EmuUnixFileDescriptor.FD_STDIN,
new IOStreamEmuUnixFileHandle(emu, program.getCompilerSpec(), stdin, null));
+ execute(thread);
- // Step through readv and verify return value and actual output effect
- thread.stepInstruction(5);
-
- assertEquals(BYTES_HW.length,
- arithmetic.toLong(thread.getState().getVar(regEAX, Reason.INSPECT), Purpose.OTHER));
+ assertEquals(List.of((long) BYTES_HW.length), capture.captured);
assertArrayEquals(BYTES_HELLO, emu.getSharedState()
.getVar(space, strHello.getOffset(), BYTES_HELLO.length, true, Reason.INSPECT));
assertArrayEquals(BYTES_WORLD, emu.getSharedState()
.getVar(space, strWorld.getOffset(), BYTES_WORLD.length, true, Reason.INSPECT));
+ }
+
+ @Test
+ public void testReadvStdinErr() throws Exception {
+ Address data = space.getAddress(0x00400800);
+
+ ByteBuffer dBuf = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN);
+ Address strHello = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_HELLO.length]);
+ Address endHello = data.add(dBuf.position());
+ Address iov = data.add(dBuf.position());
+ dBuf.putInt((int) strHello.getOffset());
+ dBuf.putInt((int) endHello.subtract(strHello));
+ int posIov1base = dBuf.position();
+ dBuf.putInt(0);
+ int posIov1len = dBuf.position();
+ dBuf.putInt(0);
+ Address strWorld = data.add(dBuf.position());
+ dBuf.put(new byte[BYTES_WORLD.length]);
+ Address endWorld = data.add(dBuf.position());
+ // Backpatch
+ dBuf.putInt(posIov1base, (int) strWorld.getOffset());
+ dBuf.putInt(posIov1len, (int) endWorld.subtract(strWorld));
+
+ AssemblyBuffer cBuf = new AssemblyBuffer(asm, start);
+ cBuf.assemble("MOV EAX, %d".formatted(Syscall.READV.number));
+ cBuf.assemble("MOV EBX, %d".formatted(EmuUnixFileDescriptor.FD_STDIN));
+ cBuf.assemble("LEA ECX, [0x%x]".formatted(iov.getOffset()));
+ cBuf.assemble("MOV EDX, 2");
+ cBuf.assemble("INT 0x80");
+ final Address captureAt = cBuf.getNext();
+ cBuf.assemble("MOV EAX, %d".formatted(Syscall.EXIT.number));
+ cBuf.assemble("MOV EBX, 0");
+ cBuf.assemble("INT 0x80");
+ cBuf.assemble("JMP 0x%x".formatted(cBuf.getNext().getOffset())); // Snuff JIT look-ahead
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, cBuf.getBytes());
+ block.putBytes(data, dBuf.array());
+ }
+
+ PcodeEmulator emu = prepareEmulator();
+ PcodeThread<byte[]> thread = launchThread(emu, start);
+ thread.inject(captureAt, "capture(EAX); emu_exec_decoded();");
- stepGroupExit(thread);
+ // DO NOT provide FD_STDIN, so that we get EBADF
+ execute(thread);
+
+ assertEquals(List.of((long) -9), capture.captured);
+ assertArrayEquals(new byte[BYTES_HELLO.length], emu.getSharedState()
+ .getVar(space, strHello.getOffset(), BYTES_HELLO.length, true, Reason.INSPECT));
+ assertArrayEquals(new byte[BYTES_WORLD.length], emu.getSharedState()
+ .getVar(space, strWorld.getOffset(), BYTES_WORLD.length, true, Reason.INSPECT));
}
@Test
public void testOpenWriteClose() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV EAX," + Syscall.OPEN.number,
- "LEA EBX,[0x00400880]",
- "MOV ECX," + (AbstractEmuLinuxSyscallUseropLibrary.O_WRONLY |
- AbstractEmuLinuxSyscallUseropLibrary.O_CREAT),
- "MOV EDX," + (0600),
- "INT 0x80",
- "MOV EBP, EAX",
-
- "MOV EAX," + Syscall.WRITE.number,
- "MOV EBX,EBP",
- "LEA ECX,[0x00400800]",
- "MOV EDX," + BYTES_HW.length,
- "INT 0x80",
-
- "MOV EAX," + Syscall.CLOSE.number,
- "MOV EBX,EBP",
-
- "MOV EAX," + Syscall.EXIT.number,
- "MOV EBX,0",
- "INT 0x80");
- block.putBytes(space.getAddress(0x00400800), BYTES_HW);
- block.putBytes(space.getAddress(0x00400880), "myfile\0".getBytes());
+ Address myFileAddr = space.getAddress(0x00400880);
+ Address hwAddr = space.getAddress(0x00400800);
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.OPEN.number));
+ buf.assemble("LEA EBX, [0x%x]".formatted(myFileAddr.getOffset()));
+ buf.assemble("MOV ECX, 0x%x".formatted(AbstractEmuLinuxSyscallUseropLibrary.O_WRONLY |
+ AbstractEmuLinuxSyscallUseropLibrary.O_CREAT));
+ buf.assemble("MOV EDX, 0x%x".formatted(0600));
+ buf.assemble("INT 0x80");
+ buf.assemble("MOV EBP, EAX");
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.WRITE.number));
+ buf.assemble("MOV EBX, EBP");
+ buf.assemble("LEA ECX, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV EDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("INT 0x80");
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.CLOSE.number));
+ buf.assemble("MOV EBX, EBP");
+ buf.assemble("INT 0x80");
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.EXIT.number));
+ buf.assemble("MOV EBX, 0");
+ buf.assemble("INT 0x80");
+
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
+ block.putBytes(hwAddr, BYTES_HW);
+ block.putBytes(myFileAddr, "myfile\0".getBytes());
}
- LinuxX86PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
execute(thread);
@@ -400,38 +469,46 @@ public class EmuLinuxX86SyscallUseropLibraryTest extends AbstractGhidraHeadlessI
@Test
public void testOpenReadClose() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
- asm.assemble(start,
- "MOV EAX," + Syscall.OPEN.number,
- "LEA EBX,[0x00400880]",
- "MOV ECX," + (AbstractEmuLinuxSyscallUseropLibrary.O_RDONLY),
- "MOV EDX," + (0600),
- "INT 0x80",
- "MOV EBP, EAX",
-
- "MOV EAX," + Syscall.READ.number,
- "MOV EBX,EBP",
- "LEA ECX,[0x00400800]",
- "MOV EDX," + BYTES_HW.length,
- "INT 0x80",
-
- "MOV EAX," + Syscall.CLOSE.number,
- "MOV EBX,EBP",
-
- "MOV EAX," + Syscall.EXIT.number,
- "MOV EBX,0",
- "INT 0x80");
- block.putBytes(space.getAddress(0x00400880), "myfile\0".getBytes());
+ Address myFileAddr = space.getAddress(0x00400880);
+ Address hwAddr = space.getAddress(0x00400800);
+ AssemblyBuffer buf = new AssemblyBuffer(asm, start);
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.OPEN.number));
+ buf.assemble("LEA EBX, [0x%x]".formatted(myFileAddr.getOffset()));
+ buf.assemble("MOV ECX, 0x%x".formatted(AbstractEmuLinuxSyscallUseropLibrary.O_RDONLY));
+ buf.assemble("MOV EDX, 0x%x".formatted(0600));
+ buf.assemble("INT 0x80");
+ buf.assemble("MOV EBP, EAX");
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.READ.number));
+ buf.assemble("MOV EBX, EBP");
+ buf.assemble("LEA ECX, [0x%x]".formatted(hwAddr.getOffset()));
+ buf.assemble("MOV EDX, %d".formatted(BYTES_HW.length));
+ buf.assemble("INT 0x80");
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.CLOSE.number));
+ buf.assemble("MOV EBX, EBP");
+ buf.assemble("INT 0x80");
+
+ buf.assemble("MOV EAX, %d".formatted(Syscall.EXIT.number));
+ buf.assemble("MOV EBX, 0");
+ buf.assemble("INT 0x80");
+
+ buf.assemble("JMP 0x%x".formatted(buf.getNext().getOffset())); // Snuff JIT look-ahead
+
+ try (Transaction _ = program.openTransaction("Initialize")) {
+ block.putBytes(start, buf.getBytes());
+ block.putBytes(myFileAddr, "myfile\0".getBytes());
}
EmuUnixFile<byte[]> file = fs.createOrGetFile("myfile", 0600);
file.write(arithmetic, arithmetic.fromConst(0, 8), BYTES_HW);
- LinuxX86PcodeEmulator emu = prepareEmulator();
+ PcodeEmulator emu = prepareEmulator();
PcodeThread<byte[]> thread = launchThread(emu, start);
execute(thread);
assertArrayEquals(BYTES_HW,
- emu.getSharedState().getVar(space, 0x00400800, BYTES_HW.length, true, Reason.INSPECT));
+ emu.getSharedState().getVar(hwAddr, BYTES_HW.length, true, Reason.INSPECT));
}
}
diff --git a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/JitLinuxAmd64SyscallUseropLibraryTest.java b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/JitLinuxAmd64SyscallUseropLibraryTest.java
new file mode 100644
index 0000000000..6c97a84ede
--- /dev/null
+++ b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/JitLinuxAmd64SyscallUseropLibraryTest.java
@@ -0,0 +1,106 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.linux;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.lang.invoke.MethodHandles;
+
+import ghidra.pcode.emu.PcodeEmulator;
+import ghidra.pcode.emu.jit.*;
+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;
+import ghidra.pcode.exec.PcodeUseropLibrary;
+
+public class JitLinuxAmd64SyscallUseropLibraryTest extends EmuLinuxAmd64SyscallUseropLibraryTest {
+
+ protected final class LinuxAmd64JitPcodeEmulator extends JitPcodeEmulator {
+ public LinuxAmd64JitPcodeEmulator() {
+ super(program.getLanguage(), new JitConfiguration(), MethodHandles.lookup());
+ }
+
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ syscalls = new EmuLinuxAmd64SyscallUseropLibrary<>(this, fs, program) {
+ @Override
+ public void unix_exit(long status) {
+ fail("Linux-amd64 shoud use group_exit");
+ super.unix_exit(status);
+ }
+
+ @Override
+ public void unix_group_exit(long status) {
+ checkStackIsDirect();
+ super.unix_group_exit(status);
+ }
+
+ @Override
+ public int unix_read(int fd, long bufPtr, int count) {
+ checkStackIsDirect();
+ return super.unix_read(fd, bufPtr, count);
+ }
+
+ @Override
+ public int unix_write(int fd, long bufPtr, int count) {
+ checkStackIsDirect();
+ return super.unix_write(fd, bufPtr, count);
+ }
+
+ @Override
+ public int unix_open(long pathnamePtr, int flags, int mode) {
+ checkStackIsDirect();
+ return super.unix_open(pathnamePtr, flags, mode);
+ }
+
+ @Override
+ public int unix_close(int fd) {
+ checkStackIsDirect();
+ return super.unix_close(fd);
+ }
+ };
+ capture = new CaptureUseropLibrary();
+ return syscalls.compose(capture);
+ }
+
+ @Override
+ protected JitPcodeThread createThread(String name) {
+ return new JitPcodeThread(name, this) {
+ int count = 0;
+
+ @Override
+ public void count(int instructions, int trailingOps) {
+ count += (instructions + trailingOps);
+ if (count > 1000) {
+ fail("Probably an infinite loop");
+ }
+ super.count(instructions, trailingOps);
+ }
+ };
+ }
+ }
+
+ void checkStackIsDirect() {
+ Throwable here = new Throwable();
+ StackTraceElement oneUp = here.getStackTrace()[2]; // The userop and checkStack
+ assertEquals(EntryPoint.class.getName(), oneUp.getClassName());
+ assertEquals("run", oneUp.getMethodName());
+ }
+
+ @Override
+ protected PcodeEmulator createEmulator() {
+ return new LinuxAmd64JitPcodeEmulator();
+ }
+}
diff --git a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/JitLinuxX86SyscallUseropLibraryTest.java b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/JitLinuxX86SyscallUseropLibraryTest.java
new file mode 100644
index 0000000000..71c6dd6c0e
--- /dev/null
+++ b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/linux/JitLinuxX86SyscallUseropLibraryTest.java
@@ -0,0 +1,107 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.linux;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.lang.invoke.MethodHandles;
+
+import ghidra.pcode.emu.PcodeEmulator;
+import ghidra.pcode.emu.jit.*;
+import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPoint;
+import ghidra.pcode.emu.linux.EmuLinuxAmd64SyscallUseropLibraryTest.CaptureUseropLibrary;
+import ghidra.pcode.exec.PcodeUseropLibrary;
+
+public class JitLinuxX86SyscallUseropLibraryTest extends EmuLinuxX86SyscallUseropLibraryTest {
+
+ protected final class LinuxX86JitPcodeEmulator extends JitPcodeEmulator {
+ public LinuxX86JitPcodeEmulator() {
+ super(program.getLanguage(), new JitConfiguration(), MethodHandles.lookup());
+ }
+
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ syscalls = new EmuLinuxX86SyscallUseropLibrary<byte[]>(this, fs, program) {
+ @Override
+ public void unix_exit(long status) {
+ checkStackIsDirect();
+ super.unix_exit(status);
+ }
+
+ @Override
+ public void unix_group_exit(long status) {
+ fail("Linux-x86 shoud use exit");
+ super.unix_group_exit(status);
+ }
+
+ @Override
+ public int unix_read(int fd, long bufPtr, int count) {
+ checkStackIsDirect();
+ return super.unix_read(fd, bufPtr, count);
+ }
+
+ @Override
+ public int unix_write(int fd, long bufPtr, int count) {
+ checkStackIsDirect();
+ return super.unix_write(fd, bufPtr, count);
+ }
+
+ @Override
+ public int unix_open(long pathnamePtr, int flags, int mode) {
+ checkStackIsDirect();
+ return super.unix_open(pathnamePtr, flags, mode);
+ }
+
+ @Override
+ public int unix_close(int fd) {
+ checkStackIsDirect();
+ return super.unix_close(fd);
+ }
+ };
+ capture = new CaptureUseropLibrary();
+ return syscalls.compose(capture);
+ }
+
+ @Override
+ protected JitPcodeThread createThread(String name) {
+ return new JitPcodeThread(name, this) {
+ int count = 0;
+
+ @Override
+ public void count(int instructions, int trailingOps) {
+ count += (instructions + trailingOps);
+ if (count > 1000) {
+ fail("Probably an infinite loop");
+ }
+ super.count(instructions, trailingOps);
+ }
+ };
+ }
+ }
+
+ void checkStackIsDirect() {
+ Throwable here = new Throwable();
+ StackTraceElement oneUp = here.getStackTrace()[2]; // The userop and checkStack
+ assertEquals(EntryPoint.class.getName(), oneUp.getClassName());
+ assertEquals("run", oneUp.getMethodName());
+ }
+
+ @Override
+ protected PcodeEmulator createEmulator() {
+ return new LinuxX86JitPcodeEmulator();
+ }
+}
diff --git a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/sys/EmuAmd64SyscallUseropLibraryTest.java b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/sys/EmuAmd64SyscallUseropLibraryTest.java
index 6ee1493556..26065ed4fc 100644
--- a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/sys/EmuAmd64SyscallUseropLibraryTest.java
+++ b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/emu/sys/EmuAmd64SyscallUseropLibraryTest.java
@@ -26,8 +26,7 @@ import ghidra.app.plugin.assembler.Assemblers;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.emu.*;
import ghidra.pcode.exec.*;
-import ghidra.pcode.exec.PcodeArithmetic.Purpose;
-import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.program.model.address.*;
import ghidra.program.model.data.DataTypeConflictHandler;
import ghidra.program.model.data.PointerDataType;
@@ -44,26 +43,25 @@ public class EmuAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadlessInte
/**
* A library with two 4-argument syscalls.
- *
* <p>
* For x86:LE:64:default:gcc, the storage for the 4th argument varies by calling convention. For
- * __stdcall, it's RCX. For syscall, it's R10. Both syscalls just return the 4th argument. Thus,
- * it's possible to detect whether the emulator heeds conventions by binding each to a different
- * convention, then invoking them with distinct values placed in RCX and R10 and verifying that
- * the correct value shows in RAX, the return register.
+ * {@code __stdcall}, it's RCX. For syscall, it's R10. Both syscalls just return the 4th
+ * argument. Thus, it's possible to detect whether the emulator heeds conventions by binding
+ * each to a different convention, then invoking them with distinct values placed in RCX and R10
+ * and verifying that the correct value shows in RAX, the return register.
*/
- protected final class SyscallTestUseropLibrary
+ protected static final class SyscallTestUseropLibrary
extends AnnotatedEmuSyscallUseropLibrary<byte[]> {
- protected final Register regRAX;
public SyscallTestUseropLibrary(PcodeMachine<byte[]> machine, Program program) {
super(machine, program);
- regRAX = machine.getLanguage().getRegister("RAX");
}
- @Override
- public long readSyscallNumber(PcodeExecutorState<byte[]> state, Reason reason) {
- return machine.getArithmetic().toLong(state.getVar(regRAX, reason), Purpose.OTHER);
+ @PcodeUserop
+ public SleighPcodeUseropDefinition syscall(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
+ RAX = emu_syscall(RAX);
+ """).build();
}
@PcodeUserop
@@ -77,11 +75,6 @@ public class EmuAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadlessInte
public byte[] test_syscall1(byte[] arg0, byte[] arg1, byte[] arg2, byte[] arg3) {
return arg3;
}
-
- @Override
- public boolean handleError(PcodeExecutor<byte[]> executor, PcodeExecutionException err) {
- return false;
- }
}
protected final class SyscallTestPcodeEmulator extends PcodeEmulator {
@@ -129,7 +122,7 @@ public class EmuAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadlessInte
start = space.getAddress(0x00400000);
size = 0x1000;
- try (Transaction tx = program.openTransaction("Initialize")) {
+ try (Transaction _ = program.openTransaction("Initialize")) {
block = program.getMemory()
.createInitializedBlock(".text", start, size, (byte) 0, TaskMonitor.DUMMY,
false);
@@ -178,7 +171,7 @@ public class EmuAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadlessInte
@Test
public void testSyscallWithStdcallConvention() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
+ try (Transaction _ = program.openTransaction("Initialize")) {
asm.assemble(start,
"MOV RAX,0",
"MOV RCX,0xbeef", // Will be clobbered with RIP by SYSCALL
@@ -204,7 +197,7 @@ public class EmuAmd64SyscallUseropLibraryTest extends AbstractGhidraHeadlessInte
@Test
public void testSyscallWithSyscallConvention() throws Exception {
- try (Transaction tx = program.openTransaction("Initialize")) {
+ try (Transaction _ = program.openTransaction("Initialize")) {
asm.assemble(start,
"MOV RAX,1",
"MOV RCX,0xdead", // Will be clobbered with RIP by SYSCALL
diff --git a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/struct/sub/StructuredSleighTest.java b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/struct/sub/StructuredSleighTest.java
index f997061237..bcfa1687e5 100644
--- a/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/struct/sub/StructuredSleighTest.java
+++ b/Ghidra/Features/SystemEmulation/src/test/java/ghidra/pcode/struct/sub/StructuredSleighTest.java
@@ -26,6 +26,7 @@ import org.junit.Before;
import org.junit.Test;
import ghidra.app.plugin.processors.sleigh.SleighException;
+import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.exec.*;
import ghidra.pcode.struct.StructuredSleigh;
import ghidra.program.model.lang.*;
@@ -34,7 +35,7 @@ import ghidra.test.AbstractGhidraHeadlessIntegrationTest;
import ghidra.test.ToyProgramBuilder;
public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest {
- private Language toy;
+ private SleighLanguage toy;
private CompilerSpec cs;
private Register r0;
@@ -51,7 +52,8 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
@Before
public void setUp() throws Exception {
- toy = getLanguageService().getLanguage(new LanguageID(ToyProgramBuilder._TOY64_BE));
+ toy = (SleighLanguage) getLanguageService()
+ .getLanguage(new LanguageID(ToyProgramBuilder._TOY64_BE));
cs = toy.getDefaultCompilerSpec();
r0 = toy.getRegister("r0");
}
@@ -64,7 +66,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
_result(param_1.muli(2));
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("__op_output = (param_1 * 0x2:4);\n", myUserop.getBody());
}
@@ -89,7 +91,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
_result(vR0.muli(2));
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("__op_output = (r0 * 0x2:4);\n", myUserop.getBody());
}
@@ -102,13 +104,13 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
_result(myVar.muli(2));
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("""
local my_var:4;
__op_output = (my_var * 0x2:4);
""", myUserop.getBody());
// Verify the source compiles
- myUserop.programFor(List.of(new Varnode(r0.getAddress(), r0.getNumBytes())),
+ myUserop.programFor(toy, List.of(new Varnode(r0.getAddress(), r0.getNumBytes())),
PcodeUseropLibrary.NIL);
}
@@ -120,7 +122,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
// Don't need to do anything
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("", myUserop.getBody());
}
@@ -136,7 +138,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
});
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("""
if 0x1:1 goto <L1>;
tmp = 0x2:4;
@@ -157,7 +159,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
});
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("""
if (!0x1:1) goto <L1>;
tmp = 0x1:4;
@@ -178,7 +180,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
_result(sum);
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("""
local i:4;
local sum:4;
@@ -209,7 +211,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
_result(sum);
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("""
local i:4;
local sum:4;
@@ -233,7 +235,7 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
_return(lit(0xdeadbeefL, 8));
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
assertEquals("return [0xdeadbeef:8];\n", myUserop.getBody());
// TODO: Test that the generated code compiles in a slaspec file.
// It's rejected for injects because "return" is not valid there.
@@ -246,9 +248,9 @@ public class StructuredSleighTest extends AbstractGhidraHeadlessIntegrationTest
public void my_userop() {
}
};
- SleighPcodeUseropDefinition<Object> myUserop = ss.generate().get("my_userop");
- PcodeProgram program =
- myUserop.programFor(SleighPcodeUseropDefinition.EMPTY_ARGS, PcodeUseropLibrary.nil());
+ SleighPcodeUseropDefinition myUserop = ss.generate("my_userop");
+ PcodeProgram program = myUserop.programFor(toy, SleighPcodeUseropDefinition.EMPTY_ARGS,
+ PcodeUseropLibrary.nil());
assertTrue(program.getCode().isEmpty());
}
}
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.java
index f008e937b2..bfdda023a3 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
@@ -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.
@@ -120,7 +120,7 @@ public class SemisparseByteArray {
if (blockOffset != 0) {
throw new IllegalArgumentException("Offset must be at block boundary");
}
- return blocks.computeIfAbsent(blockNum, n -> new byte[BLOCK_SIZE]);
+ return blocks.computeIfAbsent(blockNum, _ -> new byte[BLOCK_SIZE]);
}
/**
@@ -188,6 +188,16 @@ public class SemisparseByteArray {
return result;
}
+ /**
+ * {@return the full set of defined ranges}
+ *
+ * Use of the returned span set is not thread safe. The client must not attempt to mutate the
+ * set, or else there may be undefined behavior.
+ */
+ public ULongSpanSet getInitialized() {
+ return defined;
+ }
+
/**
* Check if a range is completely initialized
*
@@ -262,7 +272,7 @@ public class SemisparseByteArray {
// Write out portion of first block (could be full block)
long blockNum = Long.divideUnsigned(loc, BLOCK_SIZE);
int blockOffset = (int) Long.remainderUnsigned(loc, BLOCK_SIZE);
- byte[] block = blocks.computeIfAbsent(blockNum, n -> new byte[BLOCK_SIZE]);
+ byte[] block = blocks.computeIfAbsent(blockNum, _ -> new byte[BLOCK_SIZE]);
int amt = Math.min(length, BLOCK_SIZE - blockOffset);
System.arraycopy(data, offset, block, blockOffset, amt);
@@ -273,7 +283,7 @@ public class SemisparseByteArray {
if (blockNum == 0) {
throw new BufferOverflowException();
}
- block = blocks.computeIfAbsent(blockNum, n -> new byte[BLOCK_SIZE]);
+ block = blocks.computeIfAbsent(blockNum, _ -> new byte[BLOCK_SIZE]);
amt = Math.min(length - cur, BLOCK_SIZE);
System.arraycopy(data, cur + offset, block, 0, amt);
cur += amt;
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.java
index 88cb52b59d..98d91ad899 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
@@ -22,6 +22,7 @@ import ghidra.app.emulator.Emulator;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.app.plugin.processors.sleigh.SleighParserContext;
import ghidra.app.util.PseudoInstruction;
+import ghidra.pcode.emu.jit.decode.CanDecode;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
@@ -36,13 +37,11 @@ import ghidra.util.Msg;
/**
* The default implementation of {@link PcodeThread} suitable for most applications
- *
* <p>
* When emulating on concrete state, consider using {@link ModifiedPcodeThread}, so that state
* modifiers from the older {@link Emulator} are incorporated. In either case, it may be worthwhile
* to examine existing state modifiers to ensure they are appropriately represented in any abstract
* state. It may be necessary to port them.
- *
* <p>
* 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
@@ -54,7 +53,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* A userop library exporting some methods for emulated thread control
- *
* <p>
* TODO: Since p-code userops can now receive the executor, it may be better to receive it, cast
* it, and obtain the thread, rather than binding a library to each thread.
@@ -75,7 +73,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Execute the actual machine instruction at the current program counter
- *
* <p>
* Because "injects" override the machine instruction, injects which need to defer to the
* machine instruction must invoke this userop.
@@ -98,7 +95,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Advance the program counter beyond the current machine instruction
- *
* <p>
* Because "injects" override the machine instruction, they must specify the effect on the
* program counter, lest the thread become caught in an infinite loop on the inject. To
@@ -117,21 +113,19 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Interrupt execution
- *
* <p>
* This immediately throws an {@link InterruptPcodeExecutionException}. To implement
* out-of-band breakpoints, inject an invocation of this userop at the desired address.
*
* @see PcodeMachine#addBreakpoint(Address, String)
*/
- @PcodeUserop(functional = true)
+ @PcodeUserop(functional = true, canInterrupt = true)
public void emu_swi() {
thread.swi();
}
/**
* Notify the client of a failed Sleigh inject compilation.
- *
* <p>
* To avoid pestering the client during emulator set-up, a service may effectively defer
* notifying the user of Sleigh compilation errors by replacing the erroneous injects with
@@ -139,21 +133,20 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
* the client be notified.
*/
@PcodeUserop(functional = true)
- public void emu_injection_err() {
+ public static void emu_injection_err() {
throw new InjectionErrorPcodeExecutionException(null, null);
}
}
/**
* An executor for the p-code thread
- *
* <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> {
+ public static class PcodeThreadExecutor<T> extends PcodeExecutor<T> implements CanDecode {
volatile boolean suspended = false;
protected final DefaultPcodeThread<T> thread;
@@ -234,6 +227,11 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
public DefaultPcodeThread<T> getThread() {
return thread;
}
+
+ @Override
+ public PseudoInstruction decodeInstruction() {
+ return thread.decoder.decodeInstruction(thread.counter, thread.context);
+ }
}
private final String name;
@@ -316,7 +314,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* A factory method to create the complete userop library for this thread
- *
* <p>
* The returned library must compose the containing machine's shared userop library. See
* {@link PcodeUseropLibrary#compose(PcodeUseropLibrary)}.
@@ -607,7 +604,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Extension point: Extra behavior before executing an instruction
- *
* <p>
* This is currently used for incorporating state modifiers from the older {@link Emulator}
* framework. There is likely utility here when porting those to this framework.
@@ -617,7 +613,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Extension point: Extra behavior after executing an instruction
- *
* <p>
* This is currently used for incorporating state modifiers from the older {@link Emulator}
* framework. There is likely utility here when porting those to this framework.
@@ -724,7 +719,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Check for a p-code injection (override) at the given address
- *
* <p>
* This checks this thread's particular injects and then defers to the machine's injects.
*
@@ -762,7 +756,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Perform checks on a requested LOAD
- *
* <p>
* Throw an exception if the LOAD should cause an interrupt.
*
@@ -776,7 +769,6 @@ public class DefaultPcodeThread<T> implements PcodeThread<T> {
/**
* Perform checks on a requested STORE
- *
* <p>
* Throw an exception if the STORE should cause an interrupt.
*
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ModifiedPcodeThread.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/ModifiedPcodeThread.java
index 5e750d609d..184d05c818 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
@@ -132,6 +132,11 @@ public class ModifiedPcodeThread<T> extends DefaultPcodeThread<T> {
return false;
}
+ @Override
+ public boolean canInterrupt() {
+ return true;
+ }
+
@Override
public boolean hasSideEffects() {
return true;
@@ -147,6 +152,16 @@ public class ModifiedPcodeThread<T> extends DefaultPcodeThread<T> {
return false;
}
+ @Override
+ public boolean isOutSigned() {
+ return false;
+ }
+
+ @Override
+ public boolean isInSigned(int index) {
+ return false;
+ }
+
@Override
public Class<?> getOutputType() {
return void.class;
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.java
index b03fa6a114..cf7f19010a 100644
--- 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.java
@@ -23,6 +23,7 @@ import org.objectweb.asm.ClassWriter;
import ghidra.pcode.emu.jit.analysis.*;
import ghidra.pcode.emu.jit.decode.JitPassageDecoder;
+import ghidra.pcode.emu.jit.folding.FoldRevalidator;
import ghidra.pcode.emu.jit.gen.JitCodeGenerator;
import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;
import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassageClass;
@@ -30,14 +31,12 @@ 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
@@ -55,14 +54,14 @@ import ghidra.pcode.exec.PcodeExecutorState;
* 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>Decode: {@link JitPassageDecoder}</li>
* <li>Control Flow Analysis: {@link JitControlFlowModel}</li>
* <li>Data Flow Analysis: {@link JitDataFlowModel}</li>
+ * <li>Reachability Analysis: {@link JitReachabilityModel}</li>
* <li>Variable Scope Analysis: {@link JitVarScopeModel}</li>
* <li>Type Assignment: {@link JitTypeModel}</li>
* <li>Variable Allocation: {@link JitAllocationModel}</li>
@@ -70,11 +69,26 @@ import ghidra.pcode.exec.PcodeExecutorState;
* <li>Code Generation: {@link JitCodeGenerator}</li>
* </ol>
*
+ * <h2>Decode</h2>
+ * <p>
+ * Decoding is seeded at the emulator's current program counter. It takes each seed and decodes
+ * instructions linearly, until it encounters an instruction without fall through. This constitutes
+ * a stride. As it encounters control transfer instructions, it queues up additional branch targets
+ * as seeds. Once it runs out of seeds, or expends a passage-size allowance, it produces the final
+ * passage. See {@link JitPassageDecoder}.
+ * <p>
+ * The decoder also performs constant folding as it goes, which necessitates some interpretation of
+ * the p-code it decodes. This allows it to follow direct branches that may otherwise present as
+ * indirect, e.g., the target address is loaded from a table, or has to be loaded by two or more
+ * instructions. Some of these constants can be invalidated after decode if alternative pathways are
+ * found. Those that remain valid are included with the passage for further optimization downstream.
+ * See {@link FoldRevalidator}.
+ *
* <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
+ * each stride down into basic blocks at the p-code level. Note that a single instruction's p-code
* (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.
@@ -87,7 +101,19 @@ import ghidra.pcode.exec.PcodeExecutorState;
* 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}.
+ * model those effects. This phase also applies folded constants to the use-def graph. Ops with
+ * folded outputs are re-written to copies. Ops with folded inputs are re-written as if they took
+ * literal constants. Conditional branches with a folded predicate are re-written as unconditional
+ * branches or nops, etc. See {@link JitDataFlowModel}.
+ *
+ * <h2>Reachability Analysis</h2>
+ * <p>
+ * Generally, the passage decoder would not decode instructions that are not reachable, since it
+ * follows the targets of control transfer instructions. However, it is possible 1) That a userop or
+ * injection includes unreachable p-code blocks, or 2) After folding constants and re-writing
+ * branches, some blocks are now known to be unreachable, at least from the decode seed.
+ * Reachability analysis walks the new control-flow graph and marks only those blocks and edges that
+ * are reachable. Downstream analysis will ignore unreachable blocks and edges.
*
* <h2>Variable Scope Analysis</h2>
* <p>
@@ -161,6 +187,8 @@ public class JitCompiler {
PRINT_CFM,
/** Print the ops of each basic block in SSA (sort of) form */
PRINT_DFM,
+ /** Print the list of reachable basic blocks */
+ PRINT_RM,
/** Print the list of live variables for each basic block */
PRINT_VSM,
/** Print each synthetic operation, e.g., catenation, subpiece, phi */
@@ -169,22 +197,25 @@ public class JitCompiler {
PRINT_OUM,
/** Enable ASM's trace for each generated classfile */
TRACE_CLASS,
+ /** Enable per-op outline of bytecode generation */
+ DEEP_TRACE,
/** 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);
+ public static final EnumSet<Diag> ENABLE_DIAGNOSTICS =
+ EnumSet.noneOf(Diag.class);
+ //EnumSet.of(Diag.PRINT_PASSAGE, Diag.DUMP_CLASS, Diag.PRINT_OUM);
+ //EnumSet.of(Diag.PRINT_PASSAGE, Diag.DEEP_TRACE);
/**
* 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
@@ -192,7 +223,6 @@ public class JitCompiler {
* 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 /
@@ -213,7 +243,6 @@ public class JitCompiler {
/**
* Construct a p-code to bytecode translator.
- *
* <p>
* In general, this should only be used by the JIT emulator and its test suite.
*
@@ -248,22 +277,26 @@ public class JitCompiler {
if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_DFM)) {
dfm.dumpResult();
}
- JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm);
+ JitReachabilityModel rm = new JitReachabilityModel(context, cfm, dfm);
+ if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_RM)) {
+ rm.dumpResult();
+ }
+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm, rm);
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);
+ JitOpUseModel oum = new JitOpUseModel(context, cfm, dfm, rm, vsm);
if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_SYNTH)) {
dfm.dumpSynth();
}
if (ENABLE_DIAGNOSTICS.contains(Diag.PRINT_OUM)) {
oum.dumpResult();
}
+ JitTypeModel tm = new JitTypeModel(dfm, oum);
+ JitAllocationModel am = new JitAllocationModel(context, dfm, vsm, oum, tm);
JitCodeGenerator<?> gen =
- new JitCodeGenerator<>(lookup, context, cfm, dfm, vsm, tm, am, oum);
+ new JitCodeGenerator<>(lookup, context, cfm, dfm, rm, vsm, tm, am, oum);
return gen.load();
}
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.java
index 1b38236d08..d7ec845b26 100644
--- 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.java
@@ -15,8 +15,11 @@
*/
package ghidra.pcode.emu.jit;
+import java.util.EnumSet;
import java.util.Set;
+import ghidra.pcode.emu.jit.op.JitCopyOp;
+
/**
* The configuration for a JIT-accelerated emulator.
*
@@ -32,6 +35,8 @@ import java.util.Set;
* 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 foldConstants See {@link Opt#FOLD_CONSTANTS}
+ * @param removeUnreachableBlocks See {@link Opt#REMOVE_UNREACHABLE_BLOCKS}
* @param removeUnusedOperations See {@link Opt#REMOVE_UNUSED_OPERATIONS}
* @param emitCounters See {@link Opt#EMIT_COUNTERS}
* @param logStackTraces See {@link Opt#LOG_STACK_TRACES}
@@ -40,6 +45,8 @@ public record JitConfiguration(
int maxPassageInstructions,
int maxPassageOps,
int maxPassageStrides,
+ boolean foldConstants,
+ boolean removeUnreachableBlocks,
boolean removeUnusedOperations,
boolean emitCounters,
boolean logStackTraces) {
@@ -48,6 +55,20 @@ public record JitConfiguration(
* Fluent specifiers for the boolean options of {@link JitConfiguration}
*/
public enum Opt {
+ /**
+ * Attempt to fold constants. This will re-write ops that output a folded constant as a
+ * {@link JitCopyOp copy}, and any op that takes a folded constant input as taking that
+ * const directly. To see benefits, this should be used with
+ * {@link #REMOVE_UNUSED_OPERATIONS}.
+ */
+ FOLD_CONSTANTS,
+ /**
+ * Remove p-code basic blocks that cannot be reached. The ASM library or classfile API may
+ * remove unreachable blocks on its own, regardless of this option. If this option is
+ * enabled, the JIT compiler will remove unreachable blocks, <em>before</em> analyzing for
+ * unused operations, permitting more code removal.
+ */
+ REMOVE_UNREACHABLE_BLOCKS,
/**
* 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
@@ -69,7 +90,7 @@ public record JitConfiguration(
* Construct a default configuration
*/
public JitConfiguration() {
- this(1000, 5000, 10, true, true, false);
+ this(1000, 5000, 10, true, true, true, true, false);
}
/**
@@ -79,6 +100,8 @@ public record JitConfiguration(
*/
public JitConfiguration(Set<Opt> opts) {
this(1000, 5000, 10,
+ opts.contains(Opt.FOLD_CONSTANTS),
+ opts.contains(Opt.REMOVE_UNREACHABLE_BLOCKS),
opts.contains(Opt.REMOVE_UNUSED_OPERATIONS),
opts.contains(Opt.EMIT_COUNTERS),
opts.contains(Opt.LOG_STACK_TRACES));
@@ -92,4 +115,33 @@ public record JitConfiguration(
public JitConfiguration(Opt... opts) {
this(Set.of(opts));
}
+
+ public Set<Opt> opts() {
+ Set<Opt> opts = EnumSet.noneOf(Opt.class);
+ if (foldConstants) {
+ opts.add(Opt.FOLD_CONSTANTS);
+ }
+ if (removeUnusedOperations) {
+ opts.add(Opt.REMOVE_UNUSED_OPERATIONS);
+ }
+ if (emitCounters) {
+ opts.add(Opt.EMIT_COUNTERS);
+ }
+ if (logStackTraces) {
+ opts.add(Opt.LOG_STACK_TRACES);
+ }
+ return opts;
+ }
+
+ public JitConfiguration enable(Opt opt) {
+ Set<Opt> set = opts();
+ set.add(opt);
+ return new JitConfiguration(set);
+ }
+
+ public JitConfiguration disable(Opt opt) {
+ Set<Opt> set = opts();
+ set.remove(opt);
+ return new JitConfiguration(set);
+ }
}
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.java
index ba3088843f..ec8ef665c1 100644
--- 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.java
@@ -28,6 +28,7 @@ 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.folding.FoldedState;
import ghidra.pcode.emu.jit.gen.JitCodeGenerator;
import ghidra.pcode.emu.jit.gen.op.OpGen;
import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage;
@@ -45,7 +46,6 @@ 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)},
@@ -57,7 +57,6 @@ 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
@@ -86,7 +85,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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
@@ -229,7 +227,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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
@@ -256,7 +253,6 @@ public class JitPassage extends PcodeProgram {
/**
* A branch as analyzed within an instruction step
- *
* <p>
* After intra-instruction reachability is determined and this branch is to be added to the
* whole passage, it will be "upgraded" to a {@link PBranch}.
@@ -266,7 +262,6 @@ public class JitPassage extends PcodeProgram {
/**
* A branch as analyzed within a passage
- *
* <p>
* Many implement this via {@link RBranch}.
*/
@@ -282,26 +277,25 @@ public class JitPassage extends PcodeProgram {
*
* @return the reachability
*/
- Reachability reach();
+ CtxReach reach();
}
/**
* Describes the manner in which something is reachable, wrt. dynamic context changes <em>within
* an instruction step</em>.
- *
* <p>
* At the moment, the only way context can be changed dynamically is via a p-code userop. Such
* ops must have the {@link PcodeUserop#modifiesContext()} attribute set. If such an op is known
* to have been executed when finishing an instruction (either by branch or fall-through), we
* must exit the compiled passage.
*/
- public enum Reachability {
+ public enum CtxReach {
/**
* There is at least one path to reach it. None of them modify the context dynamically.
*/
WITHOUT_CTXMOD {
@Override
- public Reachability combine(Reachability that) {
+ public CtxReach combine(CtxReach that) {
return switch (that) {
case null -> this;
case WITHOUT_CTXMOD -> WITHOUT_CTXMOD;
@@ -321,7 +315,7 @@ public class JitPassage extends PcodeProgram {
*/
MAYBE_CTXMOD {
@Override
- public Reachability combine(Reachability that) {
+ public CtxReach combine(CtxReach that) {
return MAYBE_CTXMOD;
}
@@ -335,7 +329,7 @@ public class JitPassage extends PcodeProgram {
*/
WITH_CTXMOD {
@Override
- public Reachability combine(Reachability that) {
+ public CtxReach combine(CtxReach that) {
return switch (that) {
case null -> this;
case WITHOUT_CTXMOD -> MAYBE_CTXMOD;
@@ -356,7 +350,7 @@ public class JitPassage extends PcodeProgram {
* @param that the other reachability
* @return the "or" of both
*/
- public abstract Reachability combine(Reachability that);
+ public abstract CtxReach combine(CtxReach that);
/**
* Check if it is possible for this block to be reached without a context modification.
@@ -403,7 +397,7 @@ public class JitPassage extends PcodeProgram {
* @param reach see {@link RBranch#reach()}
* @return the branch
*/
- public RIntBranch withReach(Reachability reach) {
+ public RIntBranch withReach(CtxReach reach) {
return new RIntBranch(from, to, isFall, reach);
}
}
@@ -416,28 +410,44 @@ public class JitPassage extends PcodeProgram {
* @param isFall see {@link IntBranch#isFall()}
* @param reach see {@link RBranch#reach()}
*/
- public record RIntBranch(PcodeOp from, PcodeOp to, boolean isFall, Reachability reach)
- implements IntBranch, RBranch {}
+ public record RIntBranch(PcodeOp from, PcodeOp to, boolean isFall, CtxReach reach)
+ implements IntBranch, RBranch {
+
+ /**
+ * Convert this external branch into an indirect one
+ * <p>
+ * This is called whenever a once-folded branch is no longer foldable.
+ *
+ * @return the resulting indirect branch
+ */
+ public RIndBranch toIndBranch() {
+ if (!(to instanceof DecodedPcodeOp decTo)) {
+ throw new AssertionError();
+ }
+ return new RIndBranch(from, decTo.at.rvCtx, reach);
+ }
+ }
/**
* 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.
- *
* <p>
* 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.
*/
public interface ExtBranch extends Branch {
/**
- * The target address-context pair
- *
- * @return the target
+ * {@return the target address-context pair}
*/
AddrCtx to();
+
+ /**
+ * {@return the constant-folding state at the branch}
+ */
+ FoldedState state();
}
/**
@@ -445,16 +455,18 @@ public class JitPassage extends PcodeProgram {
*
* @param from see {@link ExtBranch#from()}
* @param to see {@link ExtBranch#to()}
+ * @param state the constant-folding state at the branch
*/
- public record SExtBranch(PcodeOp from, AddrCtx to) implements ExtBranch, SBranch {
+ public record SExtBranch(PcodeOp from, AddrCtx to, FoldedState state)
+ implements ExtBranch, SBranch {
/**
* Upgrade this branch to an {@link RExtBranch} for inclusion in the passage.
*
* @param reach see {@link RBranch#reach()}
* @return the branch
*/
- public RExtBranch withReach(Reachability reach) {
- return new RExtBranch(from, to, reach);
+ public RExtBranch withReach(CtxReach reach) {
+ return new RExtBranch(from, to, state, reach);
}
}
@@ -463,13 +475,13 @@ public class JitPassage extends PcodeProgram {
*
* @param from see {@link ExtBranch#from()}
* @param to see {@link ExtBranch#to()}
+ * @param state the constant-folding state at the branch
* @param reach see {@link RBranch#reach()}
*/
- public record RExtBranch(PcodeOp from, AddrCtx to, Reachability reach)
+ public record RExtBranch(PcodeOp from, AddrCtx to, FoldedState state, CtxReach reach)
implements ExtBranch, RBranch {
/**
* Convert this external branch into an internal one
- *
* <p>
* This is called whenever it becomes the case that an external target is decoded an added
* to the passage, making it an internal branch. Notably, this happens when selecting a seed
@@ -482,16 +494,25 @@ public class JitPassage extends PcodeProgram {
public RIntBranch toIntBranch(PcodeOp to) {
return new RIntBranch(from, to, false, reach);
}
+
+ /**
+ * Convert this external branch into an indirect one
+ * <p>
+ * This is called whenever a once-folded branch is no longer foldable.
+ *
+ * @return the resulting indirect branch
+ */
+ public RIndBranch toIndBranch() {
+ return new RIndBranch(from, to.rvCtx, reach);
+ }
}
/**
* 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
@@ -519,7 +540,7 @@ public class JitPassage extends PcodeProgram {
* @param reach see {@link RBranch#reach()}
* @return the branch
*/
- public RIndBranch withReach(Reachability reach) {
+ public RIndBranch withReach(CtxReach reach) {
return new RIndBranch(from, flowCtx, reach);
}
}
@@ -531,28 +552,24 @@ public class JitPassage extends PcodeProgram {
* @param flowCtx see {@link IndBranch#flowCtx()}
* @param reach see {@link RBranch#reach()}
*/
- public record RIndBranch(PcodeOp from, RegisterValue flowCtx, Reachability reach)
+ public record RIndBranch(PcodeOp from, RegisterValue flowCtx, CtxReach reach)
implements IndBranch, RBranch {}
/**
* 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 &mdash; 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.
@@ -638,7 +655,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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()}.
@@ -660,19 +676,16 @@ public class JitPassage extends PcodeProgram {
/**
* 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
@@ -680,14 +693,12 @@ public class JitPassage extends PcodeProgram {
* 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 {
/**
@@ -720,7 +731,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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
@@ -740,13 +750,11 @@ public class JitPassage extends PcodeProgram {
/**
* 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
@@ -779,7 +787,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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.
@@ -949,11 +956,18 @@ public class JitPassage extends PcodeProgram {
}
}
+ /**
+ * @param op the p-code op
+ * @param idx the operand index, -1 being output, inputs indexed 0-up
+ */
+ public record Operand(PcodeOp op, int idx) {}
+
private final List<Instruction> instructions;
private final AddrCtx entry;
- private final PcodeUseropLibrary<Object> decodeLibrary;
+ private final PcodeUseropLibrary<?> decodeLibrary;
private final Map<PcodeOp, PBranch> branches;
private final Map<PcodeOp, AddrCtx> entries;
+ private final Map<Operand, byte[]> folded;
private final Register contextreg;
private final ProgramContextImpl defaultContext;
@@ -971,16 +985,19 @@ public class JitPassage extends PcodeProgram {
* @param instructions see {@link #getInstructions()}
* @param branches see {@link #getBranches()}
* @param entries see {@link #getOpEntry(PcodeOp)}
+ * @param folded see {@link #getFoldedOperand(PcodeOp, int)}
*/
public JitPassage(SleighLanguage language, AddrCtx entry, List<PcodeOp> code,
- PcodeUseropLibrary<Object> decodeLibrary, List<Instruction> instructions,
- Map<PcodeOp, PBranch> branches, Map<PcodeOp, AddrCtx> entries) {
+ PcodeUseropLibrary<?> decodeLibrary, List<Instruction> instructions,
+ Map<PcodeOp, PBranch> branches, Map<PcodeOp, AddrCtx> entries,
+ Map<Operand, byte[]> folded) {
super(language, code, decodeLibrary.getSymbols(language));
this.entry = entry;
this.decodeLibrary = decodeLibrary;
this.instructions = instructions;
this.branches = branches;
this.entries = entries;
+ this.folded = folded;
this.contextreg = language.getContextBaseRegister();
@@ -995,7 +1012,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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.
@@ -1008,7 +1024,6 @@ public class JitPassage extends PcodeProgram {
/**
* {@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
@@ -1024,7 +1039,6 @@ public class JitPassage extends PcodeProgram {
/**
* Get the initial seed of this passage.
- *
* <p>
* This is informational only. It should be used in naming things and/or in diagnostics.
*
@@ -1036,7 +1050,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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
@@ -1044,7 +1057,7 @@ public class JitPassage extends PcodeProgram {
*
* @return the library
*/
- public PcodeUseropLibrary<Object> getDecodeLibrary() {
+ public PcodeUseropLibrary<?> getDecodeLibrary() {
return decodeLibrary;
}
@@ -1087,7 +1100,6 @@ public class JitPassage extends PcodeProgram {
/**
* 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
@@ -1101,6 +1113,24 @@ public class JitPassage extends PcodeProgram {
return entries.get(op);
}
+ /**
+ * Check if a given p-code op's operand was folded to a constant
+ *
+ * @param op the p-code op
+ * @param opIdx the operand idx, inputs indexed 0-up, -1 to indicate output
+ * @return non-null constant value, if it was folded
+ */
+ public byte[] getFoldedOperand(PcodeOp op, int opIdx) {
+ return folded.get(new Operand(op, opIdx));
+ }
+
+ /**
+ * {@return the map of all folded operands (TESTING ONLY)}
+ */
+ public Map<Operand, byte[]> allFoldedOperands() {
+ return folded;
+ }
+
/**
* If the given p-code op is known to cause an error, e.g., an unimplemented instruction, get
* the error message.
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.java
index 41a66e4264..78f83fa10a 100644
--- 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.java
@@ -44,14 +44,12 @@ 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}, you can simply
- * replace {@code new PcodeEmulator()} with {@code new JitPcodeEmulator(...)}.
+ * 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
@@ -60,7 +58,6 @@ import ghidra.util.Msg;
* 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:
@@ -155,14 +152,12 @@ public class JitPcodeEmulator extends PcodeEmulator {
/**
* 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>
@@ -235,13 +230,11 @@ public class JitPcodeEmulator extends PcodeEmulator {
/**
* {@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
@@ -259,7 +252,6 @@ public class JitPcodeEmulator extends PcodeEmulator {
/**
* 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
@@ -286,7 +278,6 @@ public class JitPcodeEmulator extends PcodeEmulator {
/**
* 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
@@ -327,7 +318,6 @@ public class JitPcodeEmulator extends PcodeEmulator {
/**
* 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
@@ -335,7 +325,6 @@ public class JitPcodeEmulator extends PcodeEmulator {
* 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
@@ -416,7 +405,6 @@ public class JitPcodeEmulator extends PcodeEmulator {
/**
* {@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
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.java
index 1767980c5e..6af97d8e50 100644
--- 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.java
@@ -32,13 +32,11 @@ 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
@@ -84,11 +82,9 @@ public class JitPcodeThread extends BytesPcodeThread {
/**
* 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)
@@ -98,7 +94,6 @@ public class JitPcodeThread extends BytesPcodeThread {
/**
* Create a thread
- *
* <p>
* This should only be called by the emulator and its test suites.
*
@@ -119,7 +114,6 @@ public class JitPcodeThread extends BytesPcodeThread {
/**
* Create the passage decoder
- *
* <p>
* This is an extension point in case the decoder needs to be replaced with a further extension.
*
@@ -184,7 +178,6 @@ public class JitPcodeThread extends BytesPcodeThread {
/**
* 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
@@ -200,12 +193,10 @@ public class JitPcodeThread extends BytesPcodeThread {
/**
* 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
@@ -226,7 +217,6 @@ public class JitPcodeThread extends BytesPcodeThread {
/**
* {@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
@@ -258,7 +248,6 @@ public class JitPcodeThread extends BytesPcodeThread {
/**
* 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
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.java
index 73bf855af1..ed170a7a72 100644
--- 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.java
@@ -38,7 +38,6 @@ 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
@@ -52,10 +51,8 @@ import ghidra.program.model.pcode.Varnode;
* 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>
@@ -76,11 +73,9 @@ import ghidra.program.model.pcode.Varnode;
* 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:
- *
* <table border="1">
* <tr>
* <th>SSA Var</th>
@@ -123,7 +118,7 @@ import ghidra.program.model.pcode.Varnode;
* <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
@@ -173,7 +168,6 @@ public class JitAllocationModel {
/**
* The descriptor of a p-code variable
- *
* <p>
* This is just a logical grouping of a varnode and its assigned p-code type.
*/
@@ -219,6 +213,7 @@ public class JitAllocationModel {
private final JitDataFlowModel dfm;
private final JitVarScopeModel vsm;
+ private final JitOpUseModel oum;
private final JitTypeModel tm;
private final SleighLanguage language;
@@ -234,12 +229,14 @@ public class JitAllocationModel {
* @param context the analysis context
* @param dfm the data flow model
* @param vsm the variable scope model
+ * @param oum the p-code op use model
* @param tm the type model
*/
public JitAllocationModel(JitAnalysisContext context, JitDataFlowModel dfm,
- JitVarScopeModel vsm, JitTypeModel tm) {
+ JitVarScopeModel vsm, JitOpUseModel oum, JitTypeModel tm) {
this.dfm = dfm;
this.vsm = vsm;
+ this.oum = oum;
this.tm = tm;
this.endian = context.getEndian();
@@ -287,7 +284,6 @@ public class JitAllocationModel {
/**
* 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.
@@ -310,7 +306,7 @@ public class JitAllocationModel {
* @param type the type
*/
public void vote(JitType type) {
- map.compute(type.ext(), (t, v) -> v == null ? 1 : v + 1);
+ map.compute(type.ext(), (_, v) -> v == null ? 1 : v + 1);
}
/**
@@ -474,11 +470,11 @@ public class JitAllocationModel {
private void analyze() {
for (JitVal v : dfm.allValues()) {
- if (v instanceof JitVarnodeVar vv && !(v instanceof JitMemoryVar)) {
+ if (oum.isUsed(v) && v instanceof JitVarnodeVar vv && !(v instanceof JitMemoryVar)) {
Varnode vn = vv.varnode();
Varnode coalesced = vsm.getCoalesced(vn);
TypeContest tc =
- typeContests.computeIfAbsent(coalesced, __ -> new TypeContest());
+ typeContests.computeIfAbsent(coalesced, _ -> new TypeContest());
if (vn.equals(coalesced)) {
tc.vote(tm.typeOf(v));
}
@@ -525,7 +521,9 @@ public class JitAllocationModel {
* keying the handlers some by an alternative (e.g., varnode when available), but that's
* for later exploration.
*/
- handlers.put(v, createHandler(v));
+ if (oum.isUsed(v)) {
+ handlers.put(v, createHandler(v));
+ }
}
}
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.java
index 8ff97b932b..7e9d336027 100644
--- 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.java
@@ -16,6 +16,7 @@
package ghidra.pcode.emu.jit.analysis;
import java.util.*;
+import java.util.function.Predicate;
import ghidra.pcode.emu.jit.*;
import ghidra.pcode.emu.jit.JitCompiler.Diag;
@@ -23,13 +24,14 @@ 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.emu.util.CountsPcodeOps;
+import ghidra.pcode.emu.util.PcodeOpCounter;
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 &mdash; note the {@link BlockSplitter} is exported
@@ -39,7 +41,6 @@ import ghidra.program.model.pcode.SequenceNumber;
* 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
@@ -50,12 +51,10 @@ import ghidra.program.model.pcode.SequenceNumber;
* 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
@@ -66,7 +65,6 @@ 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
@@ -89,12 +87,10 @@ public class JitControlFlowModel {
/**
* 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
@@ -121,14 +117,13 @@ public class JitControlFlowModel {
/**
* 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 {
+ public static class JitBlock extends PcodeProgram implements CountsPcodeOps {
private Map<IntBranch, BlockFlow> flowsFrom = new HashMap<>();
private Map<IntBranch, BlockFlow> flowsTo = new HashMap<>();
private List<IntBranch> branchesFrom = new ArrayList<>();
@@ -147,19 +142,14 @@ public class JitControlFlowModel {
public JitBlock(PcodeProgram program, List<PcodeOp> code) {
super(program, List.copyOf(code));
- int instructions = 0;
- int trailingOps = 0;
+ PcodeOpCounter counter = new PcodeOpCounter();
for (PcodeOp op : code) {
- if (op instanceof DecodedPcodeOp dec && dec.isInstructionStart()) {
- instructions++;
- trailingOps = 0;
- }
- else if (op instanceof DecodedPcodeOp) {
- trailingOps++;
+ if (op instanceof DecodedPcodeOp dec) {
+ counter.countOp(dec.isInstructionStart());
}
}
- this.instructions = instructions;
- this.trailingOps = trailingOps;
+ this.instructions = counter.instructionCount();
+ this.trailingOps = counter.trailingOpCount();
}
@Override
@@ -183,7 +173,6 @@ public class JitControlFlowModel {
/**
* Get the sequence number of the first op
- *
* <p>
* This is used for display and testing purposes only.
*
@@ -195,7 +184,6 @@ public class JitControlFlowModel {
/**
* Get the sequence number of the last op
- *
* <p>
* This is used for display and testing purposes only.
*
@@ -266,26 +254,25 @@ public class JitControlFlowModel {
*
* @return the block, or {@code null}
*/
- public JitBlock getFallFrom() {
+ public BlockFlow 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.
*
+ * @param predicate additional predicate to test the flow
* @return true if this block is targeted by a branch
*/
- public boolean hasJumpTo() {
- return flowsTo.values().stream().anyMatch(f -> !f.branch.isFall());
+ public boolean hasJumpTo(Predicate<BlockFlow> predicate) {
+ return flowsTo.values().stream().anyMatch(f -> !f.branch.isFall() && predicate.test(f));
}
/**
@@ -299,8 +286,7 @@ public class JitControlFlowModel {
}
/**
- * Get the number of instructions represented in this block
- *
+ * {@inheritDoc}
* <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
@@ -309,23 +295,13 @@ public class JitControlFlowModel {
*
* @see JitCompiledPassage#count(int, int)
* @see JitPcodeThread#count(int, int)
- * @return the instruction count
*/
+ @Override
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
- */
+ @Override
public int trailingOpCount() {
return trailingOps;
}
@@ -333,7 +309,6 @@ public class JitControlFlowModel {
/**
* 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
@@ -344,7 +319,6 @@ public class JitControlFlowModel {
* 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
@@ -362,7 +336,6 @@ public class JitControlFlowModel {
/**
* 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()}.
@@ -377,7 +350,6 @@ public class JitControlFlowModel {
/**
* Notify the splitter of the given branches before analysis
- *
* <p>
* The splitter immediately indexes the given branches by source and target op.
*
@@ -522,7 +494,6 @@ public class JitControlFlowModel {
/**
* Construct the control flow model.
- *
* <p>
* Analysis is performed as part of constructing the model.
*
@@ -543,7 +514,7 @@ public class JitControlFlowModel {
@Override
protected IntBranch newFallthroughIntBranch(PcodeOp from, PcodeOp to) {
// Decoder should already have inserted fall-through protectors
- return new RIntBranch(from, to, true, Reachability.WITHOUT_CTXMOD);
+ return new RIntBranch(from, to, true, CtxReach.WITHOUT_CTXMOD);
}
};
splitter.addBranches(passage.getBranches().values());
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.java
index dc3c705a5e..5d7807c648 100644
--- 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.java
@@ -34,20 +34,17 @@ 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.
*/
@@ -92,7 +89,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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
@@ -122,7 +118,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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
@@ -177,13 +172,12 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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.
- *
+ * <p>
* 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
@@ -221,7 +215,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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
@@ -265,7 +258,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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.
*
@@ -279,7 +271,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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.
*
@@ -293,7 +284,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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
@@ -303,7 +293,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
* 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}
@@ -329,7 +318,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* 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:
@@ -339,7 +327,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
* 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
@@ -377,7 +364,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* {@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
@@ -397,7 +383,6 @@ public class JitDataFlowArithmetic implements PcodeArithmetic<JitVal> {
/**
* {@inheritDoc}
- *
* <p>
* We override this to record the {@link JitLoadOp load} op into the use-def graph. For our
* {@code inValue}, the {@link JitDataFlowState state} will have just returned the
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.java
index 7165f713ca..ffbb99f205 100644
--- 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.java
@@ -30,7 +30,6 @@ 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
@@ -63,7 +62,6 @@ public class JitDataFlowBlockAnalyzer {
/**
* 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.
@@ -75,7 +73,6 @@ public class JitDataFlowBlockAnalyzer {
/**
* 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
@@ -93,7 +90,6 @@ public class JitDataFlowBlockAnalyzer {
/**
* 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
@@ -114,7 +110,6 @@ public class JitDataFlowBlockAnalyzer {
/**
* 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
@@ -204,7 +199,6 @@ public class JitDataFlowBlockAnalyzer {
/**
* Get the latest definition of the given varnode, synthesizing ops is required.
- *
* <p>
* NOTE: May produce phi nodes that need additional inter-block analysis
*
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.java
index 4db95aa010..7c15dab570 100644
--- 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.java
@@ -15,26 +15,29 @@
*/
package ghidra.pcode.emu.jit.analysis;
+import java.math.BigInteger;
import java.util.Map;
import java.util.Objects;
+import ghidra.pcode.emu.jit.JitPassage;
import ghidra.pcode.emu.jit.JitPassage.*;
import ghidra.pcode.emu.jit.op.*;
-import ghidra.pcode.emu.jit.var.JitFailVal;
-import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.emu.jit.var.*;
import ghidra.pcode.exec.*;
+import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.opbehavior.BinaryOpBehavior;
+import ghidra.pcode.opbehavior.UnaryOpBehavior;
+import ghidra.program.model.address.AddressSpace;
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.
@@ -44,7 +47,6 @@ import ghidra.program.model.pcode.Varnode;
* 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
@@ -52,10 +54,18 @@ import ghidra.program.model.pcode.Varnode;
* 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.
+ * <p>
+ * Much of the "re-writes" from constant folding occurs here. Instead of actually replacing the
+ * p-code ops, we wrap them in a different {@link JitOp} than usual. For outputs that get folded, we
+ * re-write to a {@link JitCopy}. For an folded inputs, we keep the op but replace those inputs with
+ * constants, as if they had been literals. The result breaks the use-def graph apart, which will
+ * permit op-use analysis to remove the actual folded computations, among other unneeded things.
*/
class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
private final JitDataFlowModel dfm;
+ private final JitPassage passage;
private final Map<PcodeOp, PBranch> branches;
+ private final BytesPcodeArithmetic bytes;
/**
* Construct an executor from the given context
@@ -69,12 +79,13 @@ class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
PcodeExecutorState<JitVal> state) {
super(context.getLanguage(), dfm.getArithmetic(), state, Reason.EXECUTE_READ);
this.dfm = dfm;
- this.branches = context.getPassage().getBranches();
+ this.passage = context.getPassage();
+ this.branches = passage.getBranches();
+ this.bytes = BytesPcodeArithmetic.forLanguage(state.getLanguage());
}
/**
* 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
@@ -91,7 +102,6 @@ class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
/**
* 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
@@ -101,7 +111,6 @@ class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
*/
protected void recordConditionalBranch(PcodeOp op) {
RBranch branch = (RBranch) Objects.requireNonNull(branches.get(op));
-
final JitVal cond;
if (op instanceof ExitPcodeOp) {
cond = JitFailVal.INSTANCE;
@@ -111,12 +120,21 @@ class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
cond = state.getVar(condVar, reason);
}
- dfm.notifyOp(new JitCBranchOp(op, branch, cond));
+ if (cond instanceof JitConstVal cc) {
+ if (cc.value().equals(BigInteger.ZERO)) {
+ dfm.notifyOp(new JitNopOp(op));
+ }
+ else {
+ dfm.notifyOp(new JitBranchOp(op, branch));
+ }
+ }
+ else {
+ 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.
@@ -126,8 +144,13 @@ class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
protected void recordIndirectBranch(PcodeOp op) {
Varnode offVar = getIndirectBranchTarget(op);
JitVal offset = state.getVar(offVar, reason);
- RIndBranch branch = (RIndBranch) Objects.requireNonNull(branches.get(op));
- dfm.notifyOp(new JitBranchIndOp(op, offset, branch));
+ RBranch branch = (RBranch) Objects.requireNonNull(branches.get(op));
+ if (offset instanceof JitConstVal) {
+ dfm.notifyOp(new JitBranchOp(op, branch));
+ }
+ else {
+ dfm.notifyOp(new JitBranchIndOp(op, offset, branch));
+ }
}
@Override
@@ -137,12 +160,27 @@ class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
@Override
public void executeConditionalBranch(PcodeOp op, PcodeFrame frame) {
- recordConditionalBranch(op);
+ byte[] foldedCond = passage.getFoldedOperand(op, OPIDX_CBRANCH_PRED);
+ if (foldedCond == null) {
+ recordConditionalBranch(op);
+ }
+ else if (bytes.isTrue(foldedCond, Purpose.CONDITION)) {
+ recordBranch(op);
+ }
+ else {
+ dfm.notifyOp(new JitNopOp(op));
+ }
}
@Override
- public void executeIndirectBranch(PcodeOp op, PcodeFrame frame) {
- recordIndirectBranch(op);
+ protected void doExecuteIndirectBranch(PcodeOp op, PcodeFrame frame) {
+ byte[] foldedTarget = passage.getFoldedOperand(op, OPIDX_BRANCH_TARGET);
+ if (foldedTarget == null) {
+ recordIndirectBranch(op);
+ }
+ else {
+ recordBranch(op);
+ }
}
@Override
@@ -150,14 +188,112 @@ class JitDataFlowExecutor extends PcodeExecutor<JitVal> {
recordBranch(op);
}
+ /**
+ * We examine and apply folding here so that re-written ops are entered into the use-def graph
+ * for further analysis.
+ * <p>
+ * Were we to instead apply this during code generation, we'd miss the opportunity to remove
+ * unnecessary ops.
+ *
+ * @param op the p-code op whose output to examine
+ * @return true if the output can be folded
+ */
+ boolean tryNotifyFoldedOutput(PcodeOp op) {
+ Varnode outVar = op.getOutput();
+ byte[] foldedOut = passage.getFoldedOperand(op, -1);
+ if (foldedOut != null) {
+ JitOutVar out = dfm.generateOutVar(op.getOutput());
+ JitVal outConst = arithmetic.fromConst(foldedOut);
+ dfm.notifyOp(new JitCopyOp(op, out, outConst));
+ /**
+ * Don't just put the const into the state. Put the re-written copy's output. Otherwise,
+ * the copy op will not get marked as "used" by block retirement, intervening
+ * callothers, etc. Ops that use the result as input will have those inputs re-written,
+ * anyway. This re-written op may still be removed if that output is never actually
+ * used.
+ */
+ state.setVar(outVar, out);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * We examine and apply input folding here so that computed outputs resulting in folded
+ * constants no longer appear "used," permitting their removal by later analysis.
+ * <p>
+ * Were we to instead apply this during code generation, we'd miss the opportunity to remove the
+ * ops computing the folded constant.
+ *
+ * @param op the p-code op
+ * @param index the input operand index (0-up)
+ * @return true if the input can be folded
+ */
+ JitVal getFoldedOrVarInput(PcodeOp op, int index) {
+ byte[] folded = passage.getFoldedOperand(op, index);
+ if (folded != null) {
+ return arithmetic.fromConst(folded);
+ }
+ return state.getVar(op.getInput(index), reason);
+ }
+
@Override
- public void executeIndirectCall(PcodeOp op, PcodeFrame frame) {
- recordIndirectBranch(op);
+ public void executeUnaryOp(PcodeOp op, UnaryOpBehavior b) {
+ if (tryNotifyFoldedOutput(op)) {
+ return;
+ }
+ JitVal in1 = getFoldedOrVarInput(op, 0);
+ JitVal out = arithmetic.unaryOp(op, in1);
+ Varnode outVar = op.getOutput();
+ state.setVar(outVar, out);
+ }
+
+ @Override
+ public void executeBinaryOp(PcodeOp op, BinaryOpBehavior b) {
+ if (tryNotifyFoldedOutput(op)) {
+ return;
+ }
+ JitVal in1 = getFoldedOrVarInput(op, 0);
+ JitVal in2 = getFoldedOrVarInput(op, 1);
+ JitVal out = arithmetic.binaryOp(op, in1, in2);
+ Varnode outVar = op.getOutput();
+ state.setVar(outVar, out);
}
+ // Callother is handled in JitDataFlowUseropLibrary.WrappedUseropDefinition
+
@Override
- public void executeReturn(PcodeOp op, PcodeFrame frame) {
- recordIndirectBranch(op);
+ public void executeLoad(PcodeOp op) {
+ /**
+ * LATER: Try folding LOAD, but only on addresses that are near this instruction. That is a
+ * heuristic for likely constant memory, e.g., a constant pool in ARM. That loaded range
+ * would need to be considered for invalidation in the same manner as any range in the
+ * decoded passage.
+ */
+ AddressSpace space = getLoadStoreSpace(op);
+ // If folded, both breaks up the use-def graph and permits gen to use direct access.
+ JitVal offset = getFoldedOrVarInput(op, OPIDX_DEREF_OFFSET);
+ Varnode outVar = op.getOutput();
+ beforeLoad(op, space, offset, outVar.getSize());
+
+ JitVal out = state.getVar(space, offset, outVar.getSize(), true, reason);
+ JitVal mod = arithmetic.modAfterLoad(op, space, offset, out);
+ state.setVar(outVar, mod);
+ afterLoad(op, space, offset, outVar.getSize(), mod);
+ }
+
+ @Override
+ public void executeStore(PcodeOp op) {
+ AddressSpace space = getLoadStoreSpace(op);
+ JitVal offset = getFoldedOrVarInput(op, OPIDX_DEREF_OFFSET);
+ // If folded, just breaks up the use-def graph
+ Varnode valVar = getStoreValue(op); // for size
+ JitVal val = getFoldedOrVarInput(op, OPIDX_STORE_VALUE);
+ JitVal mod = arithmetic.modBeforeStore(op, space, offset, val);
+ beforeStore(op, space, offset, valVar.getSize(), mod);
+
+ state.setVar(space, offset, valVar.getSize(), true, mod);
+ afterStore(op, space, offset, valVar.getSize(), mod);
}
@Override
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.java
index 08eadd8167..c8ee1a48fe 100644
--- 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.java
@@ -17,6 +17,7 @@ package ghidra.pcode.emu.jit.analysis;
import java.io.*;
import java.util.*;
+import java.util.stream.Stream;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.lifecycle.Internal;
@@ -38,7 +39,6 @@ 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
@@ -55,7 +55,6 @@ import ghidra.program.model.pcode.Varnode;
* 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},
@@ -67,7 +66,6 @@ import ghidra.program.model.pcode.Varnode;
* 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
@@ -83,7 +81,6 @@ import ghidra.program.model.pcode.Varnode;
* 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
@@ -111,7 +108,6 @@ import ghidra.program.model.pcode.Varnode;
* 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
@@ -124,16 +120,6 @@ import ghidra.program.model.pcode.Varnode;
*/
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;
@@ -153,7 +139,6 @@ public class JitDataFlowModel {
/**
* Construct the data flow model.
- *
* <p>
* Analysis is performed as part of constructing the model.
*
@@ -292,7 +277,6 @@ public class JitDataFlowModel {
/**
* 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
@@ -307,16 +291,14 @@ public class JitDataFlowModel {
}
/**
- * Get all the op nodes, whether from a p-code op or synthesized.
+ * {@return 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;
+ Stream<JitOp> allOps() {
+ return Stream.concat(
+ ops.values().stream(),
+ synthNodes.stream());
}
/**
@@ -327,8 +309,8 @@ public class JitDataFlowModel {
*/
protected class ValCollector extends HashSet<JitVal> implements JitOpUpwardVisitor {
public ValCollector() {
- for (PcodeOp op : passage.getCode()) {
- JitOp jitOp = getJitOp(op);
+ // Don't just use passage ops, because we need synthetic (phi) outputs, too.
+ for (JitOp jitOp : (Iterable<JitOp>) allOps()::iterator) {
visitOp(jitOp);
if (jitOp instanceof JitDefOp defOp) {
visitVal(defOp.out());
@@ -390,29 +372,25 @@ public class JitDataFlowModel {
/**
* Construct the use-def graph
+ *
+ * @implNote Just visit the blocks in any order. Use input placeholders and glue them together
+ * afterward.
+ * <p>
+ * 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.
*/
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.
*
@@ -474,7 +452,6 @@ public class JitDataFlowModel {
/**
* 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.
@@ -634,7 +611,6 @@ public class JitDataFlowModel {
/**
* 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.
*
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.java
index 2976a4a286..17043bb0d2 100644
--- 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.java
@@ -35,7 +35,6 @@ 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
@@ -48,7 +47,6 @@ import ghidra.util.Msg;
* 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
@@ -97,7 +95,6 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
/**
* 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
@@ -194,7 +191,6 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
/**
* 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
@@ -275,12 +271,10 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
/**
* 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
@@ -348,7 +342,6 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
/**
* Get the value of the given varnode
- *
* <p>
* This is the implementation of
* {@link JitDataFlowState#getVar(AddressSpace, JitVal, int, boolean, Reason)}, but only for
@@ -417,7 +410,6 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
/**
* {@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
@@ -427,23 +419,29 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
* 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.
+ *
+ * @implNote 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,
+ * with a pre-load of register values and a try-finally to write them, we optimize
+ * register access, too. Turns out registers and uniques get the same treatment, at
+ * least for now, partly for debugging purposes, but also because with crossbuilds,
+ * uniques must outlive their generating instruction. LATER: Can we examine an
+ * instruction's named blocks to determine which uniques need saving? LATER: It might
+ * also be possible (with significant changes to the strategy in
+ * {@link JitVarScopeModel}) to be more selective in which variables become live and
+ * are retired. But we must avoid the situation where we might "save" a variable that
+ * was never restored or written. That would effectively erase a variable that should
+ * have been left unmodified.
+ * <p>
+ * Memory must be written. Unless we can determine for sure the memory is
+ * non-volatile, we must presume volatile, so no bypassing is allowed. LATER: 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.
*/
@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;
@@ -499,7 +497,6 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
/**
* {@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
@@ -584,7 +581,6 @@ public class JitDataFlowState implements PcodeExecutorState<JitVal> {
/**
* 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
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.java
index d6e42cbe6b..c60f5f1177 100644
--- 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.java
@@ -19,7 +19,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.stream.IntStream;
import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;
import ghidra.pcode.emu.jit.decode.DecoderUseropLibrary;
@@ -34,7 +34,6 @@ 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
@@ -44,10 +43,8 @@ import ghidra.program.model.pcode.Varnode;
* 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}
@@ -65,7 +62,6 @@ import ghidra.program.model.pcode.Varnode;
* 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
@@ -84,9 +80,9 @@ public class JitDataFlowUseropLibrary implements PcodeUseropLibrary<JitVal> {
* The wrapper of a specific userop definition
*/
protected class WrappedUseropDefinition implements PcodeUseropDefinition<JitVal> {
- private final PcodeUseropDefinition<Object> decOp;
+ private final PcodeUseropDefinition<?> decOp;
- public WrappedUseropDefinition(PcodeUseropDefinition<Object> decOp) {
+ public WrappedUseropDefinition(PcodeUseropDefinition<?> decOp) {
this.decOp = decOp;
}
@@ -107,33 +103,59 @@ public class JitDataFlowUseropLibrary implements PcodeUseropLibrary<JitVal> {
}
/**
+ * The output and input types of a userop, defined using a Java callback
+ *
+ * @param out the type behavior of the userop's output, or null if it returns {@code void}.
+ * @param ins the type behavior or each input argument
+ */
+ record InOutTypes(JitTypeBehavior out, List<JitTypeBehavior> ins) {
+ /**
+ * Indicates that the userop's type behaviors aren't known
+ * <p>
+ * Perhaps they are partially-known, but some property of the method prevents direct
+ * invocation, and so we indicate unknown to ensure a more conservative strategy is
+ * applied.
+ *
+ * @param hasOutput true if the return type is not {@code void}
+ * @param inputCount the number of input arguments the userop can accept
+ * @return the fallback types, i.e., everything is {@link JitTypeBehavior#ANY}, unless
+ * the method returns {@code void}, in which case the output type is
+ * {@code null}.
+ */
+ static InOutTypes fallback(boolean hasOutput, int inputCount) {
+ return new InOutTypes(hasOutput ? JitTypeBehavior.ANY : null,
+ IntStream.range(0, inputCount).mapToObj(_ -> JitTypeBehavior.ANY).toList());
+ }
+ }
+
+ /**
+ * Get the input and output types for this userop.
+ * <p>
* 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.
+ * type or the output 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) {
+ private InOutTypes getInOutTypes(boolean hasOutput, List<JitVal> inVals) {
int inputCount = getInputCount();
if (inputCount != inVals.size()) { // includes inputCount == -1 (variadic)
- return JitDataFlowModel.allAny(inVals);
+ return InOutTypes.fallback(hasOutput, inVals.size());
}
Method method = decOp.getJavaMethod();
if (method == null) {
- return JitDataFlowModel.allAny(inVals);
+ return InOutTypes.fallback(hasOutput, inVals.size());
}
List<JitTypeBehavior> result = new ArrayList<>();
Parameter[] parameters = method.getParameters();
@@ -141,29 +163,23 @@ public class JitDataFlowUseropLibrary implements PcodeUseropLibrary<JitVal> {
Parameter p = parameters[i];
JitTypeBehavior type = JitTypeBehavior.forJavaType(p.getType());
if (type == null) {
- return JitDataFlowModel.allAny(inVals);
+ return InOutTypes.fallback(hasOutput, inVals.size());
}
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 output type is not supported, this
- * return {@link JitTypeBehavior#ANY}.
- *
- * @return the type behavior
- */
- private JitTypeBehavior getOutputTypeBehavior() {
- return JitTypeBehavior.forJavaType(getOutputType());
+ Class<?> outCls = getOutputType();
+ if (outCls == null) {
+ return InOutTypes.fallback(hasOutput, inVals.size());
+ }
+ JitTypeBehavior outType = JitTypeBehavior.forJavaType(outCls);
+ if (outType == null && hasOutput) {
+ return InOutTypes.fallback(hasOutput, inVals.size());
+ }
+ return new InOutTypes(outType, Collections.unmodifiableList(result));
}
/**
* {@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
@@ -194,20 +210,29 @@ public class JitDataFlowUseropLibrary implements PcodeUseropLibrary<JitVal> {
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);
+ JitDataFlowExecutor exec = (JitDataFlowExecutor) executor;
+
+ if (exec.tryNotifyFoldedOutput(op)) {
+ // A folded constant would not be present were the userop not suitable for removal
+ return;
+ }
+
+ JitDataFlowState state = (JitDataFlowState) exec.getState();
+ List<JitVal> inVals = new ArrayList<>();
+ int n = op.getNumInputs();
+ for (int i = 1; i < n; i++) {
+ inVals.add(exec.getFoldedOrVarInput(op, i));
+ }
Varnode outVn = op.getOutput();
+ InOutTypes types = getInOutTypes(outVn != null, inVals);
if (outVn == null) {
- dfm.notifyOp(new JitCallOtherOp(op, decOp, inVals, inTypes, state.captureState()));
+ dfm.notifyOp(
+ new JitCallOtherOp(op, decOp, inVals, types.ins, state.captureState()));
}
else {
JitOutVar out = dfm.generateOutVar(outVn);
- dfm.notifyOp(new JitCallOtherDefOp(op, out, getOutputTypeBehavior(), decOp, inVals,
- inTypes, state.captureState()));
+ dfm.notifyOp(new JitCallOtherDefOp(op, out, types.out, decOp, inVals, types.ins,
+ state.captureState()));
state.setVar(outVn, out);
}
}
@@ -217,6 +242,11 @@ public class JitDataFlowUseropLibrary implements PcodeUseropLibrary<JitVal> {
return decOp.isFunctional();
}
+ @Override
+ public boolean canInterrupt() {
+ return decOp.canInterrupt();
+ }
+
@Override
public boolean hasSideEffects() {
return decOp.hasSideEffects();
@@ -232,6 +262,16 @@ public class JitDataFlowUseropLibrary implements PcodeUseropLibrary<JitVal> {
return decOp.canInlinePcode();
}
+ @Override
+ public boolean isOutSigned() {
+ return decOp.isOutSigned();
+ }
+
+ @Override
+ public boolean isInSigned(int index) {
+ return decOp.isInSigned(index);
+ }
+
@Override
public Class<?> getOutputType() {
return decOp.getOutputType();
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.java
index f11abe025d..3c15a187a1 100644
--- 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.java
@@ -16,6 +16,7 @@
package ghidra.pcode.emu.jit.analysis;
import java.util.*;
+import java.util.Map.Entry;
import ghidra.pcode.emu.jit.JitCompiler;
import ghidra.pcode.emu.jit.JitCompiler.Diag;
@@ -26,21 +27,21 @@ 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.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
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.
- *
+ * downstream op. This includes all "sink" ops and all ops on which they depend. We also collect the
+ * set of {@link JitVal values} used.
* <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>
@@ -51,11 +52,9 @@ import ghidra.program.model.pcode.Varnode;
* <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
@@ -68,14 +67,12 @@ import ghidra.program.model.pcode.Varnode;
* 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.
@@ -89,9 +86,11 @@ public class JitOpUseModel {
private final JitAnalysisContext context;
private final JitControlFlowModel cfm;
private final JitDataFlowModel dfm;
+ private final JitReachabilityModel rm;
private final JitVarScopeModel vsm;
- private final Set<JitOp> used = new HashSet<>();
+ private final Set<JitOp> usedOps = new HashSet<>();
+ private final Set<JitVal> usedVals = new HashSet<>();
/**
* Construct the operator use model
@@ -99,13 +98,15 @@ public class JitOpUseModel {
* @param context the analysis context
* @param cfm the control flow model
* @param dfm the data flow model
+ * @param rm the reachability model
* @param vsm the variable scope model
*/
public JitOpUseModel(JitAnalysisContext context, JitControlFlowModel cfm,
- JitDataFlowModel dfm, JitVarScopeModel vsm) {
+ JitDataFlowModel dfm, JitReachabilityModel rm, JitVarScopeModel vsm) {
this.context = context;
this.cfm = cfm;
this.dfm = dfm;
+ this.rm = rm;
this.vsm = vsm;
if (context.getConfiguration().removeUnusedOperations()) {
@@ -115,11 +116,11 @@ public class JitOpUseModel {
/**
* 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}.
+ * {@link #visitVal(JitVal)}, etc., all used ops are collected into
+ * {@link JitOpUseModel#usedOps}.
*/
class OpUseCollector implements JitOpUpwardVisitor {
final JitBlock block;
@@ -137,12 +138,29 @@ public class JitOpUseModel {
@Override
public void visitOp(JitOp op) {
- if (!used.add(op)) {
+ if (!usedOps.add(op)) {
return;
}
JitOpUpwardVisitor.super.visitOp(op);
}
+ @Override
+ public void visitVal(JitVal v) {
+ if (!usedVals.add(v)) {
+ return;
+ }
+ JitOpUpwardVisitor.super.visitVal(v);
+ }
+
+ @Override
+ public void visitPhiOp(JitPhiOp op) {
+ for (Entry<BlockFlow, JitVal> entry : op.options().entrySet()) {
+ if (rm.isTakeable(entry.getKey())) {
+ visitVal(entry.getValue());
+ }
+ }
+ }
+
@Override
public void visitMissingVar(JitMissingVar missingVar) {
throw new AssertionError("missing: " + missingVar);
@@ -150,7 +168,6 @@ public class JitOpUseModel {
/**
* 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.
@@ -165,7 +182,6 @@ public class JitOpUseModel {
/**
* Visit a varnode that will be retired before calling a userop
- *
* <p>
* This applies only when the userop is invoked using the Standard strategy.
*
@@ -186,10 +202,21 @@ public class JitOpUseModel {
* @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.
+ * @implNote in general, we must retire all varnodes before invoking a callother, so that its
+ * implementation can confidently retrieve up-to-date values from the machine state,
+ * including registers and uniques. If a userop attests to being functional, i.e., it
+ * neither reads to writes state outside what's given by its operands, then we can
+ * neglect to retire the state. However, we must also consider that a functional
+ * userop could interrupt execution, in which case, we must ensure the values get
+ * retired. In the op-use model, this method just served to indicate the varnodes are
+ * "used." At generation, this should ensure that the varnode retirement that happens
+ * in the exception handler includes the actual values, because none of the writes
+ * into the allocated locals should be elided.
*/
private Set<Varnode> getCallOtherRetireVarnodes(JitBlock block, JitCallOtherOpIf op) {
// Should not see inline-replaced ops here
- if (op.userop().isFunctional()) {
+ PcodeUseropDefinition<?> userop = op.userop();
+ if (userop.isFunctional() && !userop.canInterrupt()) {
return Set.of();
}
return vsm.getLiveVars(block);
@@ -197,7 +224,6 @@ public class JitOpUseModel {
/**
* 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
@@ -216,14 +242,24 @@ public class JitOpUseModel {
if (!block.branchesOut().isEmpty()) {
return vsm.getLiveVars(block);
}
- if (block.flowsFrom().isEmpty()) {
+
+ List<BlockFlow> reachableFlowsFrom =
+ block.flowsFrom().values().stream().filter(rm::isTakeable).toList();
+
+ if (reachableFlowsFrom.isEmpty()) {
+ /**
+ * Reachable flows from should only be smaller than all flows from in the event a
+ * CBRANCH was folded to a BRANCH, so 2 becomes 1. Thus, there should still always be at
+ * least one reachable flow from (or a branch out).
+ */
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()));
+
+ Iterator<BlockFlow> it = reachableFlowsFrom.iterator();
+ Set<Varnode> aliveAfterAnyFlow = new HashSet<>(vsm.getLiveVars(it.next().to()));
+ while (it.hasNext()) {
+ aliveAfterAnyFlow.retainAll(vsm.getLiveVars(it.next().to()));
}
Set<Varnode> result = new HashSet<>(vsm.getLiveVars(block));
result.removeAll(aliveAfterAnyFlow);
@@ -232,7 +268,6 @@ public class JitOpUseModel {
/**
* 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
@@ -249,7 +284,9 @@ public class JitOpUseModel {
Set<JitPhiOp> phisBefore = Set.copyOf(dfm.phiNodes());
for (JitBlock block : cfm.getBlocks()) {
-
+ if (!rm.isReachable(block)) {
+ continue;
+ }
for (PcodeOp op : block.getCode()) {
if (dfm.getJitOp(op) instanceof JitCallOtherOpIf callother) {
for (Varnode vn : getCallOtherRetireVarnodes(block, callother)) {
@@ -269,6 +306,9 @@ public class JitOpUseModel {
dfm.analyzeInterblock(extraPhis);
for (JitBlock block : cfm.getBlocks()) {
+ if (!rm.isReachable(block)) {
+ continue;
+ }
OpUseCollector collector = new OpUseCollector(block);
// Locate memory outputs, stores, branches, callothers
@@ -294,39 +334,68 @@ public class JitOpUseModel {
/**
* 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 usedOps.contains(op);
+ }
+ return true;
+ }
+
+ /**
+ * Check whether the given value node is used.
+ *
+ * @param val the value to check
+ * @return true if used, i.e., non-removable
+ */
+ public boolean isUsed(JitVal val) {
+ if (context.getConfiguration().removeUnusedOperations()) {
+ return usedVals.contains(val);
}
return true;
}
+ /**
+ * For diagnostics: A visual hint as to whether the op or its output are removable.
+ *
+ * @param op the op to check
+ * @return DEL, OUT, or blank to indicate op deletion, output removal, or keep.
+ */
+ public String prefixFor(JitOp op) {
+ if (!isUsed(op)) {
+ return "[DEL]";
+ }
+ if (op instanceof JitDefOp defOp && !isUsed(defOp.out())) {
+ return "[OUT]";
+ }
+ return "[ ]";
+ }
+
/**
* For diagnostics: Dump the analysis result to stderr
*
* @see Diag#PRINT_OUM
*/
public void dumpResult() {
+ PcodeUseropSymbolMap symbols = dfm.getLibrary().getSymbols(context.getLanguage());
System.err.println("STAGE: OpUse");
for (JitBlock block : cfm.getBlocks()) {
+ if (!rm.isReachable(block)) {
+ continue;
+ }
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);
+ System.err.println(" Could retire: " + val.toString(context.getLanguage()));
}
}
for (PcodeOp op : block.getCode()) {
JitOp jitOp = dfm.getJitOp(op);
- if (!isUsed(jitOp)) {
- System.err.println(" Removed: %s: %s".formatted(op.getSeqnum(), jitOp));
- }
+ System.err.println(" %s %s: %s".formatted(prefixFor(jitOp), op.getSeqnum(),
+ jitOp.toString(symbols)));
}
}
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitReachabilityModel.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitReachabilityModel.java
new file mode 100644
index 0000000000..dd0ce2590f
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/analysis/JitReachabilityModel.java
@@ -0,0 +1,164 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.pcode.emu.jit.analysis;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import ghidra.pcode.emu.jit.JitCompiler;
+import ghidra.pcode.emu.jit.JitCompiler.Diag;
+import ghidra.pcode.emu.jit.JitPassage.IntBranch;
+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;
+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;
+import ghidra.pcode.emu.jit.op.*;
+
+/**
+ * The p-code block reachability analysis for JIT-accelerated emulation.
+ * <p>
+ * The implements the Reachability phase of the {@link JitCompiler} using a simple graph traversal.
+ * The result is the set of {@linkplain JitBlock basic blocks} and {@linkplain BlockFlow edges} that
+ * are actually reachable from a passage's entries.
+ * <p>
+ * The traversal is seeded with each of the passage's entry points, and then each outbound flow is
+ * considered. Consider a conditional branch. The control-flow graph will have two outbound flows,
+ * one for the branch case, and one for the fall-through case. It's possible the data-flow phase
+ * detected its condition was constant, and so it would be re-written as an unconditional branch or
+ * nop, so we must examine the actual {@link JitOp} presented, not just the original p-code op, when
+ * determining which flows can be taken. We perform this traversal in the downstream direction only.
+ */
+public class JitReachabilityModel {
+ private final JitAnalysisContext context;
+ private final JitControlFlowModel cfm;
+ private final JitDataFlowModel dfm;
+
+ private final Set<JitBlock> reachable = new HashSet<>();
+ private final Set<BlockFlow> takeable = new HashSet<>();
+
+ /**
+ * Create the reachability model
+ *
+ * @param context the analysis context
+ * @param cfm the control-flow model
+ * @param dfm the data-flow model.
+ * @implNote We're being a bit lazy here requiring the DFM, because we use the re-written JitOps
+ * so that reachability heeds folded indirect and conditional branches. If we don't
+ * want this dependency, we could inspect the folded constants for the ops ourselves.
+ */
+ public JitReachabilityModel(JitAnalysisContext context, JitControlFlowModel cfm,
+ JitDataFlowModel dfm) {
+ this.context = context;
+ this.cfm = cfm;
+ this.dfm = dfm;
+
+ if (context.getConfiguration().removeUnreachableBlocks()) {
+ analyze();
+ }
+ }
+
+ private void visitBlock(JitBlock block) {
+ if (!reachable.add(block)) {
+ return;
+ }
+ for (BlockFlow flow : block.flowsFrom().values()) {
+ IntBranch br = flow.branch();
+ // Use DFM JitOp instead of PcodeOp opcodes, for folding re-writes
+ JitOp op = dfm.getJitOp(br.from());
+ switch (op) {
+ case JitCBranchOp _ -> {
+ // Add both fall-through and branch target
+ visitFlow(flow);
+ }
+ case JitBranchOp _ -> {
+ // Possibly re-written from CBRANCH. Either way, only include target
+ if (!br.isFall()) {
+ visitFlow(flow);
+ }
+ }
+ case JitBranchIndOp _ -> {
+ // Reverted from re-written BRANCH. Still, folded target is reachable
+ assert !br.isFall();
+ visitFlow(flow);
+ }
+ case JitNopOp _ -> {
+ // Re-written CBRANCH, or just next op is target of another branch.
+ // In case a CBRANCH, only include fall-through
+ if (br.isFall()) {
+ visitFlow(flow);
+ }
+ }
+ default -> {
+ // Next op is target of another branch. There is only fall-through.
+ assert br.isFall();
+ visitFlow(flow);
+ }
+ }
+ }
+ }
+
+ private void visitFlow(BlockFlow flow) {
+ takeable.add(flow);
+ visitBlock(flow.to());
+ }
+
+ private void analyze() {
+ /**
+ * See the set with every block that is an entry point
+ */
+ for (JitBlock block : cfm.getBlocks()) {
+ if (context.getOpEntry(block.first()) != null) {
+ visitBlock(block);
+ }
+ }
+ }
+
+ /**
+ * Check whether the given block can be reached
+ *
+ * @param block the block to check
+ * @return true if reachable, i.e., non-removable
+ */
+ public boolean isReachable(JitBlock block) {
+ if (context.getConfiguration().removeUnreachableBlocks()) {
+ return reachable.contains(block);
+ }
+ return true;
+ }
+
+ /**
+ * Check whether the given flow can be taken
+ *
+ * @param flow the flow to check
+ * @return true if it can be taken, i.e., analysis must consider this edge.
+ */
+ public boolean isTakeable(BlockFlow flow) {
+ if (context.getConfiguration().removeUnreachableBlocks()) {
+ return takeable.contains(flow);
+ }
+ return true;
+ }
+
+ /**
+ * For diagnostics: Dump the analysis result to stder
+ *
+ * @see Diag#PRINT_RM
+ */
+ public void dumpResult() {
+ System.err.println("STAGE: Reachability");
+ for (JitBlock block : reachable) {
+ System.err.println(" Reachable: " + block);
+ }
+ }
+}
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.java
index a695179eb2..c3d11cf332 100644
--- 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.java
@@ -31,7 +31,6 @@ 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
@@ -57,9 +56,9 @@ import ghidra.program.model.pcode.PcodeOp;
* 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}.
+ * {@linkplain 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>
@@ -77,14 +76,15 @@ import ghidra.program.model.pcode.PcodeOp;
* 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.
+ * unsigned (except unsigned right shifts). 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 a
+ * 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>
@@ -96,7 +96,6 @@ import ghidra.program.model.pcode.PcodeOp;
* $U00:4 = FLOAT_ADD r0, r1
* r2 = INT_2COMP $U00:4
* </pre>
- *
* <p>
* The native translation to bytecode:
*
@@ -110,7 +109,6 @@ import ghidra.program.model.pcode.PcodeOp;
* 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}
@@ -121,7 +119,6 @@ import ghidra.program.model.pcode.PcodeOp;
* 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
@@ -131,7 +128,6 @@ import ghidra.program.model.pcode.PcodeOp;
* 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
@@ -141,7 +137,6 @@ import ghidra.program.model.pcode.PcodeOp;
* 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
@@ -154,25 +149,22 @@ import ghidra.program.model.pcode.PcodeOp;
* 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
+ * as specified by the p-code opcode; and the size of the input varnode, specified by the actual
* 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
+ * This becomes 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
@@ -188,7 +180,6 @@ import ghidra.program.model.pcode.PcodeOp;
* 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
@@ -225,7 +216,7 @@ public class JitTypeModel {
if (candidate == JitTypeBehavior.ANY || candidate == JitTypeBehavior.COPY) {
return;
}
- counts.compute(candidate, (k, v) -> v == null ? c : v + c);
+ counts.compute(candidate, (_, v) -> v == null ? c : v + c);
}
/**
@@ -239,7 +230,6 @@ public class JitTypeModel {
/**
* 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.
@@ -280,6 +270,7 @@ public class JitTypeModel {
}
private final JitDataFlowModel dfm;
+ private final JitOpUseModel oum;
private final SequencedSet<JitVal> queue = new LinkedHashSet<>();
private final Map<JitVal, JitTypeBehavior> assignments = new HashMap<>();
@@ -288,16 +279,17 @@ public class JitTypeModel {
* Construct the type model
*
* @param dfm the data flow model whose use-def graph to process
+ * @param oum the p-code op use model
*/
- public JitTypeModel(JitDataFlowModel dfm) {
+ public JitTypeModel(JitDataFlowModel dfm, JitOpUseModel oum) {
this.dfm = dfm;
+ this.oum = oum;
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.
@@ -309,27 +301,33 @@ public class JitTypeModel {
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);
+ if (oum.isUsed(use.op())) {
+ JitTypeBehavior type = use.type();
+ if (type == JitTypeBehavior.COPY && use.op() instanceof JitDefOp def) {
+ JitVal downstream = def.out();
+ type = assignments.get(downstream);
+ }
+ contest.vote(type);
}
- 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));
+ if (oum.isUsed(def)) {
+ JitTypeBehavior defType = JitTypeBehavior.ANY;
+ defType = def.type();
+ if (defType == JitTypeBehavior.COPY) {
+ Contest subContest = new Contest();
+ for (JitVal upstream : def.inputs()) {
+ if (oum.isUsed(upstream)) {
+ subContest.vote(assignments.get(upstream));
+ }
+ }
+ defType = subContest.winner();
}
- defType = subContest.winner();
+ contest.vote(defType);
}
- contest.vote(defType);
}
return contest.winner();
@@ -337,7 +335,6 @@ public class JitTypeModel {
/**
* 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}
* &mdash; or any op with an operand requiring {@link JitTypeBehavior#COPY} if additional ones
@@ -365,7 +362,6 @@ public class JitTypeModel {
/**
* 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
@@ -376,11 +372,17 @@ public class JitTypeModel {
Set<JitVal> vals = dfm.allValues();
queue.addAll(vals);
for (JitVal v : vals) {
- assignments.put(v, JitTypeBehavior.ANY);
+ if (oum.isUsed(v)) {
+ assignments.put(v, JitTypeBehavior.ANY);
+ }
}
while (!queue.isEmpty()) {
JitVal v = queue.removeFirst();
+ if (!oum.isUsed(v)) {
+ // Filter here rather than in queueNeighbors
+ continue;
+ }
JitTypeBehavior type = computeNewAssignment(v);
JitTypeBehavior old = assignments.put(v, type);
if (old != type) {
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.java
index 19e459a629..1d16650e58 100644
--- 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.java
@@ -30,7 +30,6 @@ 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
@@ -45,7 +44,6 @@ import ghidra.util.MathUtilities;
* 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},
@@ -54,7 +52,6 @@ import ghidra.util.MathUtilities;
* 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
@@ -68,7 +65,6 @@ import ghidra.util.MathUtilities;
* 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
@@ -83,7 +79,6 @@ import ghidra.util.MathUtilities;
* 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:
@@ -105,7 +100,6 @@ import ghidra.util.MathUtilities;
* 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.
@@ -129,12 +123,10 @@ import ghidra.util.MathUtilities;
* | 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:
- *
* <table border="1">
* <tr>
* <th>Block</th>
@@ -157,7 +149,7 @@ import ghidra.util.MathUtilities;
* <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
@@ -173,7 +165,6 @@ import ghidra.util.MathUtilities;
* above. The algorithm considers it alive in blocks 4&ndash;7 and 8, despite the fact neither
* actually accesses it. Nevertheless, we'd rather generate one birth upon entering block 1&ndash;3,
* keep it alive in the body, and then generate one retirement upon leaving block 9&ndash;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
@@ -202,8 +193,13 @@ public class JitVarScopeModel {
*/
UP {
@Override
- Collection<JitBlock> getFlows(ScopeInfo info) {
- return info.block.flowsTo().values().stream().map(BlockFlow::from).toList();
+ Collection<JitBlock> getFlows(ScopeInfo info, JitReachabilityModel rm) {
+ return info.block.flowsTo()
+ .values()
+ .stream()
+ .filter(rm::isTakeable)
+ .map(BlockFlow::from)
+ .toList();
}
@Override
@@ -221,8 +217,13 @@ public class JitVarScopeModel {
*/
DOWN {
@Override
- Collection<JitBlock> getFlows(ScopeInfo info) {
- return info.block.flowsFrom().values().stream().map(BlockFlow::to).toList();
+ Collection<JitBlock> getFlows(ScopeInfo info, JitReachabilityModel rm) {
+ return info.block.flowsFrom()
+ .values()
+ .stream()
+ .filter(rm::isTakeable)
+ .map(BlockFlow::to)
+ .toList();
}
@Override
@@ -240,9 +241,10 @@ public class JitVarScopeModel {
* 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
+ * @param rm the reachability model, as only "taken" flows will be followed
* @return the blocks into which our set will be unioned
*/
- abstract Collection<JitBlock> getFlows(ScopeInfo info);
+ abstract Collection<JitBlock> getFlows(ScopeInfo info, JitReachabilityModel rm);
/**
* Get the current set for the given block
@@ -300,7 +302,6 @@ public class JitVarScopeModel {
/**
* 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.
@@ -312,7 +313,7 @@ public class JitVarScopeModel {
if (queued.isEmpty()) {
return;
}
- for (JitBlock block : which.getFlows(this)) {
+ for (JitBlock block : which.getFlows(this, rm)) {
ScopeInfo that = infos.get(block);
Set<Varnode> toQueueThat = new HashSet<>(queued);
toQueueThat.removeAll(which.getLive(that));
@@ -326,7 +327,6 @@ public class JitVarScopeModel {
/**
* 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
@@ -342,6 +342,7 @@ public class JitVarScopeModel {
private final JitControlFlowModel cfm;
private final JitDataFlowModel dfm;
+ private final JitReachabilityModel rm;
private final NavigableMap<Address, Varnode> coalesced = new TreeMap<>();
@@ -353,10 +354,13 @@ public class JitVarScopeModel {
*
* @param cfm the control flow model
* @param dfm the data flow model
+ * @param rm the reachability model
*/
- public JitVarScopeModel(JitControlFlowModel cfm, JitDataFlowModel dfm) {
+ public JitVarScopeModel(JitControlFlowModel cfm, JitDataFlowModel dfm,
+ JitReachabilityModel rm) {
this.cfm = cfm;
this.dfm = dfm;
+ this.rm = rm;
analyze();
}
@@ -407,6 +411,9 @@ public class JitVarScopeModel {
private void coalesceVarnodes() {
Set<Varnode> allVarnodes = new HashSet<>();
for (JitBlock block : cfm.getBlocks()) {
+ if (!rm.isReachable(block)) {
+ continue;
+ }
allVarnodes.addAll(dfm.getAnalyzer(block).getVarnodesRead());
allVarnodes.addAll(dfm.getAnalyzer(block).getVarnodesWritten());
}
@@ -455,7 +462,6 @@ public class JitVarScopeModel {
/**
* 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,
@@ -465,6 +471,9 @@ public class JitVarScopeModel {
private void analyze() {
coalesceVarnodes();
for (JitBlock block : cfm.getBlocks()) {
+ if (!rm.isReachable(block)) {
+ continue;
+ }
ScopeInfo info = new ScopeInfo(block);
infos.put(block, info);
blockQueue.add(info);
@@ -497,6 +506,9 @@ public class JitVarScopeModel {
* @return the live varnodes
*/
public Set<Varnode> getLiveVars(JitBlock block) {
+ if (!rm.isReachable(block)) {
+ return Set.of();
+ }
return infos.get(block).liveVarsImm;
}
@@ -509,6 +521,9 @@ public class JitVarScopeModel {
System.err.println("STAGE: VarLiveness");
for (JitBlock block : cfm.getBlocks()) {
System.err.println(" Block: " + block);
+ if (!rm.isReachable(block)) {
+ continue;
+ }
Set<String> liveNames = new TreeSet<>();
for (Varnode vn : infos.get(block).liveVarsImm) {
Register register = block.getLanguage().getRegister(vn.getAddress(), vn.getSize());
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/CanDecode.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/CanDecode.java
new file mode 100644
index 0000000000..59119f4b7d
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/CanDecode.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.decode;
+
+import ghidra.app.util.PseudoInstruction;
+import ghidra.pcode.exec.PcodeExecutor;
+import ghidra.program.model.listing.Instruction;
+
+/**
+ * An interface on {@link PcodeExecutor} when that executor can decode and interpret an
+ * {@link Instruction}
+ */
+public interface CanDecode {
+ /**
+ * {@return the current instruction, decoding it if needed}
+ */
+ PseudoInstruction decodeInstruction();
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/CollectExecutor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/CollectExecutor.java
new file mode 100644
index 0000000000..81c36e5907
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/decode/CollectExecutor.java
@@ -0,0 +1,78 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.plugin.processors.sleigh.SleighLanguage;
+import ghidra.app.util.PseudoInstruction;
+import ghidra.lifecycle.Internal;
+import ghidra.pcode.emu.jit.folding.*;
+import ghidra.pcode.exec.*;
+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.program.model.pcode.PcodeOp;
+
+/**
+ * An executor that simply records the ops that would be executed
+ * <p>
+ * This decodes instructions by delegating to another given executor
+ */
+@Internal
+public class CollectExecutor extends PcodeExecutor<MaskedBytes> implements CanDecode {
+ /**
+ * The collected ops
+ */
+ public final List<PcodeOp> ops = new ArrayList<>();
+ private final CanDecode delegate;
+
+ /**
+ * Construct a collecting executor
+ *
+ * @param language the language
+ * @param state the constant-folding state
+ * @param reason the reason for reading variables
+ * @param delegate the decoding delegate
+ */
+ public CollectExecutor(SleighLanguage language, FoldedState state, Reason reason,
+ CanDecode delegate) {
+ super(language, FoldedArithmetic.forLanguage(language), state, reason);
+ this.delegate = delegate;
+ }
+
+ /**
+ * Construct a collecting executor, based on a given executor
+ *
+ * @param <T> the type of executor
+ * @param executor the executor
+ */
+ public <T extends FoldingExecutor & CanDecode> CollectExecutor(T executor) {
+ FoldedState state = executor.getState();
+ this(executor.getLanguage(), state == null ? null : state.fork(), executor.getReason(),
+ executor);
+ }
+
+ @Override
+ public void stepOp(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<MaskedBytes> library) {
+ ops.add(op);
+ }
+
+ @Override
+ public PseudoInstruction decodeInstruction() {
+ return delegate.decodeInstruction();
+ }
+}
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.java
index d1d069eb24..f41fc475cc 100644
--- 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.java
@@ -17,6 +17,7 @@ package ghidra.pcode.emu.jit.decode;
import java.util.List;
+import ghidra.lifecycle.Internal;
import ghidra.pcode.emu.jit.JitPassage.AddrCtx;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.pcode.PcodeOp;
@@ -29,4 +30,5 @@ import ghidra.program.model.pcode.PcodeOp;
* @param ops the ops in the order decoded and emitted
* @see JitPassageDecoder
*/
-record DecodedStride(AddrCtx start, List<Instruction> instructions, List<PcodeOp> ops) {}
+@Internal
+public 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.java
index b9ecbd6734..bf4602ad61 100644
--- 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.java
@@ -25,9 +25,11 @@ 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.folding.*;
import ghidra.pcode.emu.jit.op.JitNopOp;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.disassemble.Disassembler;
import ghidra.program.model.address.Address;
import ghidra.program.model.lang.*;
@@ -39,18 +41,28 @@ 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}.
+ * <p>
+ * Some ops requiring special attention:
+ * <ul>
+ * <li>{@link PcodeOp#CALLOTHER callother} - in case we'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.</li>
+ * <li>{@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.</li>
+ * </ul>
*
* @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
@@ -66,10 +78,8 @@ import ghidra.util.Msg;
* @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 {
+class DecoderExecutor extends FoldingExecutor implements DisassemblerContextAdapter, CanDecode {
private final DecoderForOneStride stride;
final AddrCtx at;
@@ -82,25 +92,24 @@ class DecoderExecutor extends PcodeExecutor<Object>
final List<PcodeOp> opsForThisStep = new ArrayList<>();
private final List<SBranch> 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 state the constant-folding state
* @param instruction the instruction, or {@code null}
*/
- DecoderExecutor(DecoderForOneStride stride, AddrCtx at, PseudoInstruction instruction) {
- super(stride.decoder.thread.getLanguage(), null, null, null);
+ DecoderExecutor(DecoderForOneStride stride, AddrCtx at, FoldedState state,
+ PseudoInstruction instruction) {
this.stride = stride;
this.at = at;
+ super(stride.passage, state);
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)
@@ -109,23 +118,22 @@ class DecoderExecutor extends PcodeExecutor<Object>
*
* @param stride the stride being decoded
* @param at the address and contextreg value of the instruction
+ * @param state the constant-folding state
*/
- DecoderExecutor(DecoderForOneStride stride, AddrCtx at) {
- this(stride, at, null);
+ DecoderExecutor(DecoderForOneStride stride, AddrCtx at, FoldedState state) {
+ this(stride, at, state, 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) {
+ DecodedPcodeOp rewriteOp(PcodeOp op) {
if (op instanceof DecodedPcodeOp dec) {
assert dec.getAt().equals(at);
return dec;
@@ -134,24 +142,17 @@ class DecoderExecutor extends PcodeExecutor<Object>
}
/**
- * 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.
+ * Apply {@link #rewriteOp(PcodeOp)} over a list
*
- * @param op the op to re-write
- * @return the equivalent op, re-written
+ * @param ops the ops
+ * @return the equivalent ops, re-written
*/
- DecodedPcodeOp rewrite(PcodeOp op) {
- return rewrites.computeIfAbsent(op, o -> rewriteOp(at, o));
+ List<PcodeOp> rewriteOps(List<PcodeOp> ops) {
+ return ops.stream().<PcodeOp> map(this::rewriteOp).toList();
}
/**
* 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
@@ -179,15 +180,15 @@ class DecoderExecutor extends PcodeExecutor<Object>
/**
* 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)}.
+ * be invoked by {@link DecoderUseropLibrary#emu_exec_decoded} or
+ * {@link DecoderUseropLibrary#emu_skip_decoded}.
*
* @return the decoded instruction, which may be a {@link DecodeErrorInstruction}
*/
- PseudoInstruction decodeInstruction() {
+ @Override
+ public PseudoInstruction decodeInstruction() {
PseudoInstruction instruction = stride.decoder.decodeInstruction(at.address, at.rvCtx);
setInstruction(instruction);
return instruction;
@@ -204,13 +205,9 @@ class DecoderExecutor extends PcodeExecutor<Object>
}
}
- /**
- * 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());
+ @Override
+ public PcodeFrame begin(List<PcodeOp> code, PcodeUseropSymbolMap userops) {
+ return super.begin(rewriteOps(code), userops);
}
/**
@@ -223,7 +220,7 @@ class DecoderExecutor extends PcodeExecutor<Object>
* proper, we have to add that nop.
*/
@Override
- public void finish(PcodeFrame frame, PcodeUseropLibrary<Object> library) {
+ public void finish(PcodeFrame frame, PcodeUseropLibrary<MaskedBytes> library) {
super.finish(frame, library);
NopPcodeOp termNop = termNopsPerFrame.remove(frame);
if (termNop != null) {
@@ -233,49 +230,23 @@ class DecoderExecutor extends PcodeExecutor<Object>
/**
* {@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.
+ * We interpret all the ops here, as we hope to fold constants for simplification purposes, esp.
+ * for re-writing {@link PcodeOp#BRANCHIND} and {@link PcodeOp#CALLIND} ops.
*/
@Override
- public void stepOp(PcodeOp op, PcodeFrame frame, PcodeUseropLibrary<Object> library) {
+ public void stepOp(PcodeOp op, PcodeFrame frame, PcodeUseropLibrary<MaskedBytes> 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);
- }
- }
+ opsForThisStep.add(op);
+ super.stepOp(op, frame, library);
}
/**
* {@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.
@@ -283,11 +254,11 @@ class DecoderExecutor extends PcodeExecutor<Object>
@Override
public void executeConditionalBranch(PcodeOp op, PcodeFrame frame) {
doExecuteBranch(op, frame);
+ super.executeConditionalBranch(op, frame); // Try to fold the predicate
}
/**
* {@inheritDoc}
- *
* <p>
* We override this to prevent an attempt to write PC to the {@link #getState() state}, which is
* {@code null}.
@@ -297,13 +268,12 @@ class DecoderExecutor extends PcodeExecutor<Object>
}
@Override
- protected void branchToOffset(PcodeOp op, Object offset, PcodeFrame frame) {
+ protected void branchToOffset(PcodeOp op, MaskedBytes 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,
@@ -313,12 +283,12 @@ class DecoderExecutor extends PcodeExecutor<Object>
*/
@Override
protected void branchToAddress(PcodeOp op, Address target) {
- branchesForThisStep.add(new SExtBranch(op, takeTargetContext(target)));
+ branchesForThisStep.add(
+ new SExtBranch(op, takeTargetContext(target), state == null ? null : state.fork()));
}
/**
* {@inheritDoc}
- *
* <p>
* This creates 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,
@@ -331,22 +301,22 @@ class DecoderExecutor extends PcodeExecutor<Object>
int tgtSeq = op.getSeqnum().getTime() + relative;
if (tgtSeq == frame.getCode().size()) {
NopPcodeOp termNop =
- termNopsPerFrame.computeIfAbsent(frame, f -> new NopPcodeOp(at, tgtSeq));
+ termNopsPerFrame.computeIfAbsent(frame, _ -> new NopPcodeOp(at, tgtSeq));
branchesForThisStep.add(new SIntBranch(op, termNop, false));
}
else {
PcodeOp to = frame.getCode().get(op.getSeqnum().getTime() + relative);
- branchesForThisStep.add(new SIntBranch(op, rewrite(to), false));
+ branchesForThisStep.add(new SIntBranch(op, 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.
+ * This creates 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 for later passage-wide control flow analysis. The superclass only
+ * delegates here if it wasn't able to fold the indirect branch to a direct one.
*
* @see #checkFallthroughAndAccumulate(PcodeProgram)
*/
@@ -357,7 +327,6 @@ class DecoderExecutor extends PcodeExecutor<Object>
/**
* {@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
@@ -382,7 +351,6 @@ class DecoderExecutor extends PcodeExecutor<Object>
/**
* {@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
@@ -392,7 +360,7 @@ class DecoderExecutor extends PcodeExecutor<Object>
*/
@Override
protected void onMissingUseropDef(PcodeOp op, PcodeFrame frame, String opName,
- PcodeUseropLibrary<Object> library) {
+ PcodeUseropLibrary<MaskedBytes> library) {
branchesForThisStep.add(
new ErrBranch(op, "Sleigh userop '%s' is not in the library".formatted(opName)));
}
@@ -402,12 +370,11 @@ class DecoderExecutor extends PcodeExecutor<Object>
if (!value.getRegister().isProcessorContext()) {
return;
}
- futCtx.compute(address, (a, v) -> v == null ? value : v.combineValues(value));
+ futCtx.compute(address, (_, 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
@@ -431,7 +398,6 @@ class DecoderExecutor extends PcodeExecutor<Object>
/**
* 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
@@ -439,7 +405,6 @@ class DecoderExecutor extends PcodeExecutor<Object>
* 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
@@ -453,14 +418,14 @@ class DecoderExecutor extends PcodeExecutor<Object>
* @param from the instruction's or inject's p-code
* @return the reachability of the fall-through flow
*/
- public Reachability checkFallthroughAndAccumulate(PcodeProgram from) {
+ public CtxReach checkFallthroughAndAccumulate(PcodeProgram from) {
if (opsForThisStep.isEmpty()) {
- return Reachability.WITHOUT_CTXMOD;
+ return CtxReach.WITHOUT_CTXMOD;
}
ExitPcodeOp probeOp = ExitPcodeOp.exit(AddrCtx.NOWHERE);
opsForThisStep.add(probeOp);
- SExtBranch probeBranch = new SExtBranch(probeOp, AddrCtx.NOWHERE);
+ SExtBranch probeBranch = new SExtBranch(probeOp, AddrCtx.NOWHERE, null);
branchesForThisStep.add(probeBranch);
PcodeProgram program = new PcodeProgram(from, opsForThisStep);
@@ -475,11 +440,11 @@ class DecoderExecutor extends PcodeExecutor<Object>
JitBlock entry = blocks.firstEntry().getValue();
JitBlock exit = blocks.lastEntry().getValue();
- Map<JitBlock, Reachability> reachable = new HashMap<>();
- collectReachable(reachable, entry, Reachability.WITHOUT_CTXMOD);
+ Map<JitBlock, CtxReach> reachable = new HashMap<>();
+ collectCtxReach(reachable, entry, CtxReach.WITHOUT_CTXMOD);
for (JitBlock block : blocks.values()) {
- Reachability reach = reachable.get(block);
+ CtxReach reach = reachable.get(block);
if (reach == null) {
continue;
}
@@ -522,7 +487,7 @@ class DecoderExecutor extends PcodeExecutor<Object>
if (name == null) {
continue;
}
- PcodeUseropDefinition<Object> userop = stride.passage.library().getUserops().get(name);
+ PcodeUseropDefinition<?> userop = stride.passage.library().getUserops().get(name);
if (userop == null) {
continue;
}
@@ -535,38 +500,36 @@ class DecoderExecutor extends PcodeExecutor<Object>
/**
* The reachability test mentioned in {@link #checkFallthroughAndAccumulate(PcodeProgram)}
- *
* <p>
* Collects the reachability of blocks reachable from {@code cur} into the given mutable map.
* The value indicates whether or not context modifications can occur along the paths to the
* block (key). If a block is not in the map, it is not reachable.
+ * <p>
+ * Context-modifying userops are all considered hazards, but we shouldn't abort until after the
+ * instruction. If the exit is reachable without passing through a context modification, then
+ * we're good to proceed. Otherwise, no. Additionally, we're going to check all branches, direct
+ * or indirect, to see if they are reachable without context modification. If they are, then we
+ * treat them as usual. If not, then they will be treated as indirect, and we'll neglect to
+ * "retire" the context, because presumably, the userop will already have caused that retirement
+ * and modified it in place.
+ * <p>
+ * If one branch is reachable by multiple paths where some require context modification and some
+ * do not, we'll keep a local variable at runtime to track whether a context-modifying userop
+ * has actually been executed. We'll generate code to check this variable at the branch site and
+ * treat it as a hazard if it is set.
*
* @param into a mutable map for collecting reachable blocks
* @param cur the source block, or an intermediate during recursion
- * @param the computed reachability of the source block. Use {@link Reachability#WITHOUT_CTXMOD}
- * for the seed.
+ * @param the computed reachability of the source block. Use {@link CtxReach#WITHOUT_CTXMOD} for
+ * the seed.
*/
- private void collectReachable(Map<JitBlock, Reachability> into, JitBlock cur,
- Reachability how) {
- Reachability curHow = into.get(cur);
+ private void collectCtxReach(Map<JitBlock, CtxReach> into, JitBlock cur,
+ CtxReach how) {
+ CtxReach curHow = into.get(cur);
- /**
- * Context-modifying userops are all considered hazards, but we shouldn't abort until after
- * the instruction. If the exit is reachable without passing through a context modification,
- * then we're good to proceed. Otherwise, no. Additionally, we're going to check all
- * branches, direct or indirect, to see if they are reachable without context modification.
- * If they are, then we treat them as usual. If not, then they will be treated as indirect,
- * and we'll neglect to "retire" the context, because presumably, the userop will already
- * have caused that retirement and modified it in place.
- *
- * If one branch is reachable by multiple paths where some require context modification and
- * some do not, we'll keep a local variable at runtime to track whether a context-modifying
- * userop has actually been executed. We'll generate code to check this variable at the
- * branch site and treat it as a hazard if it is set.
- */
if (blockModifiesContext(cur)) {
// Not combine. If we're MAYBE here, we still become WITH_CTX.
- how = Reachability.WITH_CTXMOD;
+ how = CtxReach.WITH_CTXMOD;
}
else {
how = how.combine(curHow);
@@ -578,13 +541,12 @@ class DecoderExecutor extends PcodeExecutor<Object>
into.put(cur, how);
for (BlockFlow flow : cur.flowsFrom().values()) {
- collectReachable(into, flow.to(), how);
+ collectCtxReach(into, flow.to(), how);
}
}
/**
* 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.
@@ -607,7 +569,6 @@ class DecoderExecutor extends PcodeExecutor<Object>
/**
* 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
@@ -618,4 +579,14 @@ class DecoderExecutor extends PcodeExecutor<Object>
void addInstruction(PseudoInstruction instruction) {
stride.instructions.add(instruction);
}
+
+ /**
+ * Notify the passage of an inlined userop
+ *
+ * @param op the {@link PcodeOp#CALLOTHER} op
+ * @param replacement the replacement ops
+ */
+ void recordInline(PcodeOp op, List<PcodeOp> replacement) {
+ stride.passage.inlines.put(op, replacement);
+ }
}
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.java
index de44fe132a..7587827eb5 100644
--- 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.java
@@ -16,42 +16,80 @@
package ghidra.pcode.emu.jit.decode;
import java.util.*;
-import java.util.Map.Entry;
+import java.util.stream.Stream;
import org.apache.commons.collections4.MapUtils;
+import ghidra.lifecycle.Internal;
import ghidra.pcode.emu.jit.JitConfiguration;
import ghidra.pcode.emu.jit.JitPassage;
import ghidra.pcode.emu.jit.JitPassage.*;
+import ghidra.pcode.emu.jit.folding.*;
import ghidra.pcode.exec.PcodeUseropLibrary;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.pcode.PcodeOp;
+import ghidra.program.model.pcode.Varnode;
/**
* 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}.
+ * decoded. Once complete, this provides an immutable decoded {@link JitPassage}.
*/
-class DecoderForOnePassage {
- private final JitPassageDecoder decoder;
+@Internal
+public class DecoderForOnePassage {
+ public final JitPassageDecoder decoder;
private final AddrCtx seed;
private final int maxOps;
private final int maxInstrs;
private final int maxStrides;
- final Map<PcodeOp, RIntBranch> internalBranches = new HashMap<>();
+ public final Map<PcodeOp, RIntBranch> internalBranches = new HashMap<>();
// Sequenced, because this is also the seed queue
- final SequencedMap<PcodeOp, RExtBranch> externalBranches = new LinkedHashMap<>();
+ final TieredBranchQueue externalBranches = new TieredBranchQueue();
final Map<PcodeOp, PBranch> otherBranches = new HashMap<>();
- final Map<AddrCtx, PcodeOp> firstOps = new HashMap<>();
- final List<DecodedStride> strides = new ArrayList<>();
+ public final Map<AddrCtx, PcodeOp> firstOps = new HashMap<>();
+ public final List<DecodedStride> strides = new ArrayList<>();
+ public final Map<Operand, byte[]> folded = new HashMap<>();
+ final Map<PcodeOp, List<PcodeOp>> inlines = new HashMap<>();
private int opCount = 0;
private int instructionCount = 0;
+ static class TieredBranchQueue {
+ final SequencedMap<PcodeOp, RExtBranch> direct = new LinkedHashMap<>();
+ final SequencedMap<PcodeOp, RExtBranch> folded = new LinkedHashMap<>();
+
+ void put(PcodeOp op, RExtBranch branch) {
+ var which = switch (op.getOpcode()) {
+ case PcodeOp.BRANCHIND, PcodeOp.CALLIND -> folded;
+ default -> direct;
+ };
+ which.put(op, branch);
+ }
+
+ RExtBranch next() {
+ var first = direct.pollFirstEntry();
+ if (first != null) {
+ return first.getValue();
+ }
+ first = folded.pollFirstEntry();
+ if (first != null) {
+ return first.getValue();
+ }
+ return null;
+ }
+
+ Collection<RExtBranch> remaining() {
+ return Stream.concat(direct.values().stream(), folded.values().stream()).toList();
+ }
+
+ void clear() {
+ direct.clear();
+ folded.clear();
+ }
+ }
+
/**
* Construct the decoder
*
@@ -67,7 +105,9 @@ class DecoderForOnePassage {
this.maxInstrs = config.maxPassageInstructions();
this.maxStrides = config.maxPassageStrides();
EntryPcodeOp entryOp = new EntryPcodeOp(seed);
- externalBranches.put(entryOp, new RExtBranch(entryOp, seed, Reachability.WITHOUT_CTXMOD));
+ externalBranches.put(entryOp, new RExtBranch(entryOp, seed,
+ config.foldConstants() ? new FoldedState(decoder.thread.getLanguage()) : null,
+ CtxReach.WITHOUT_CTXMOD));
}
/**
@@ -76,11 +116,10 @@ class DecoderForOnePassage {
void decodePassage() {
while (opCount < maxOps && instructionCount < maxInstrs &&
strides.size() < maxStrides) {
- Entry<PcodeOp, RExtBranch> nextEnt = externalBranches.pollFirstEntry();
- if (nextEnt == null) {
+ RExtBranch next = externalBranches.next();
+ if (next == null) {
break;
}
- RExtBranch next = nextEnt.getValue();
AddrCtx start = next.to();
if (decoder.thread.hasEntry(start)) {
@@ -90,7 +129,7 @@ class DecoderForOnePassage {
otherBranches.put(next.from(), next);
}
else {
- decodeStride(start);
+ decodeStride(start, next.state());
PcodeOp to = Objects.requireNonNull(firstOps.get(start));
internalBranches.put(next.from(), next.toIntBranch(to));
}
@@ -99,17 +138,15 @@ class DecoderForOnePassage {
/**
* 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
+ * Otherwise, we queue up the {@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
+ * @param eb the tentatively-external branch whose flow we may follow
*/
void flowTo(RExtBranch eb) {
if (!eb.reach().canReachWithoutCtxMod()) {
@@ -128,17 +165,23 @@ class DecoderForOnePassage {
* Decode a stride starting at the given address.
*
* @param start the starting address and context
+ * @param state the constant-folding state at the given start
*/
- private void decodeStride(AddrCtx start) {
- DecodedStride stride = new DecoderForOneStride(decoder, this, start).decode();
+ private void decodeStride(AddrCtx start, FoldedState state) {
+ DecodedStride stride = new DecoderForOneStride(decoder, this, start, state).decode();
opCount += stride.ops().size();
instructionCount += stride.instructions().size();
strides.add(stride);
}
+ void revalidateFolded() {
+ if (decoder.thread.getMachine().getConfiguration().foldConstants()) {
+ new FoldRevalidator(this).revalidate();
+ }
+ }
+
/**
* 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
@@ -154,7 +197,7 @@ class DecoderForOnePassage {
strides.stream().flatMap(b -> b.instructions().stream()).toList();
Map<PcodeOp, PBranch> branches = otherBranches;
branches.putAll(internalBranches);
- for (RExtBranch eb : externalBranches.values()) {
+ for (RExtBranch eb : externalBranches.remaining()) {
if (!eb.reach().canReachWithoutCtxMod()) {
branches.put(eb.from(), eb);
}
@@ -167,7 +210,7 @@ class DecoderForOnePassage {
}
}
return new JitPassage(decoder.thread.getLanguage(), seed, code, decoder.library,
- instructions, branches, MapUtils.invertMap(firstOps));
+ instructions, branches, MapUtils.invertMap(firstOps), folded);
}
/**
@@ -175,7 +218,78 @@ class DecoderForOnePassage {
*
* @return the library
*/
- PcodeUseropLibrary<Object> library() {
+ public PcodeUseropLibrary<MaskedBytes> library() {
return decoder.library;
}
+
+ static boolean vnArrsEquivalent(Varnode[] a, Varnode[] b) {
+ int n = a.length;
+ if (n != b.length) {
+ return false;
+ }
+ for (int i = 0; i < n; i++) {
+ if (!vnsEquivalent(a[i], b[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static boolean vnsEquivalent(Varnode a, Varnode b) {
+ if ((a == null) != (b == null)) {
+ return false;
+ }
+ if (a == null) {
+ return true;
+ }
+ return a.getOffset() == b.getOffset() && a.getSize() == b.getSize() &&
+ a.getSpace() == b.getSpace();
+ }
+
+ /**
+ * Because {@link PcodeOp} does not override {@link Object#equals}, we define one here for our
+ * specific purposes.
+ *
+ * @param a the first op
+ * @param b the second op
+ * @return true if the ops have the same opcode, output, and inputs
+ */
+ static boolean opsEquivalent(PcodeOp a, PcodeOp b) {
+ if ((a instanceof NopPcodeOp) != (b instanceof NopPcodeOp)) {
+ return false;
+ }
+ if (a.getOpcode() != b.getOpcode()) {
+ return false;
+ }
+ if (!vnsEquivalent(a.getOutput(), b.getOutput())) {
+ return false;
+ }
+ if (!vnArrsEquivalent(a.getInputs(), b.getInputs())) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Check if the given op was replaced with the same program as before
+ *
+ * @param op the inlined op
+ * @param revalidated the newly-observed replacement
+ * @return true if the replacement observed during decode is the same as the one given
+ */
+ public boolean checkSameInline(PcodeOp op, List<PcodeOp> revalidated) {
+ List<PcodeOp> original = inlines.get(op);
+ int n = original.size();
+ if (n != revalidated.size()) {
+ return false;
+ }
+ for (int i = 0; i < n; i++) {
+ PcodeOp oOp = original.get(i);
+ PcodeOp rOp = revalidated.get(i);
+ if (!opsEquivalent(oOp, rOp)) {
+ return false;
+ }
+ }
+ return true;
+ }
}
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.java
index 46c360686d..2305a024e8 100644
--- 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.java
@@ -20,13 +20,13 @@ import java.util.List;
import ghidra.app.util.PseudoInstruction;
import ghidra.pcode.emu.jit.JitPassage.*;
+import ghidra.pcode.emu.jit.folding.FoldedState;
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.
@@ -37,7 +37,6 @@ public class DecoderForOneStride {
/**
* The result of decoding an instruction
- *
* <p>
* This may also represent an error encountered while trying to decode an instruction.
*
@@ -53,13 +52,12 @@ public class DecoderForOneStride {
* @return the reachability of the fall-through flow
* @see DecoderExecutor#checkFallthroughAndAccumulate(PcodeProgram)
*/
- Reachability checkFallthroughAndAccumulate() {
+ CtxReach 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
@@ -75,6 +73,7 @@ public class DecoderForOneStride {
final JitPassageDecoder decoder;
final DecoderForOnePassage passage;
private final AddrCtx start;
+ private final FoldedState state;
final List<Instruction> instructions = new ArrayList<>();
final List<PcodeOp> opsForStride = new ArrayList<>();
@@ -85,12 +84,14 @@ public class DecoderForOneStride {
* @param decoder the thread's passage decoder
* @param passage the decoder for this specific passage
* @param start the seed to start this stride
+ * @param state the constant-folding state
*/
public DecoderForOneStride(JitPassageDecoder decoder, DecoderForOnePassage passage,
- AddrCtx start) {
+ AddrCtx start, FoldedState state) {
this.decoder = decoder;
this.passage = passage;
this.start = start;
+ this.state = state;
}
/**
@@ -104,7 +105,6 @@ public class DecoderForOneStride {
/**
* "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
@@ -126,11 +126,11 @@ public class DecoderForOneStride {
ExitPcodeOp exitOp = ExitPcodeOp.exit(at);
opsForStride.add(exitOp);
passage.otherBranches.put(exitOp,
- new RExtBranch(exitOp, at, Reachability.WITHOUT_CTXMOD));
+ new RExtBranch(exitOp, at, null, CtxReach.WITHOUT_CTXMOD));
return null;
}
- DecoderExecutor executor = new DecoderExecutor(this, at);
+ DecoderExecutor executor = new DecoderExecutor(this, at, state);
PcodeProgram program = decoder.thread.getInject(at.address);
if (program == null) {
PseudoInstruction instruction = executor.decodeInstruction();
@@ -168,7 +168,7 @@ public class DecoderForOneStride {
return toStride();
}
- Reachability reach = result.checkFallthroughAndAccumulate();
+ CtxReach reach = result.checkFallthroughAndAccumulate();
if (reach == null) {
return toStride();
}
@@ -178,7 +178,7 @@ public class DecoderForOneStride {
// Would happen because of inject without control flow
ExitPcodeOp exitOp = ExitPcodeOp.exit(at);
opsForStride.add(exitOp);
- passage.otherBranches.put(exitOp, new RExtBranch(exitOp, at, reach));
+ passage.otherBranches.put(exitOp, new RExtBranch(exitOp, at, null, reach));
return toStride();
}
at = next;
@@ -191,13 +191,13 @@ public class DecoderForOneStride {
// Looks like the without-control-flow case, but at has advanced
ExitPcodeOp exitOp = ExitPcodeOp.exit(at);
opsForStride.add(exitOp);
- passage.otherBranches.put(exitOp, new RExtBranch(exitOp, at, reach));
+ passage.otherBranches.put(exitOp, new RExtBranch(exitOp, at, null, reach));
return toStride();
}
case MAYBE_CTXMOD -> {
ExitPcodeOp exitOp = ExitPcodeOp.cond(at);
opsForStride.add(exitOp);
- passage.otherBranches.put(exitOp, new RExtBranch(exitOp, at, reach));
+ passage.otherBranches.put(exitOp, new RExtBranch(exitOp, at, null, reach));
continue;
}
}
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.java
index 9b52b8dd9e..d4bd533bf5 100644
--- 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.java
@@ -20,6 +20,7 @@ import java.util.List;
import ghidra.app.util.PseudoInstruction;
import ghidra.pcode.emu.DefaultPcodeThread.PcodeEmulationLibrary;
+import ghidra.pcode.emu.jit.folding.MaskedBytes;
import ghidra.pcode.emu.jit.op.JitNopOp;
import ghidra.pcode.exec.*;
import ghidra.program.model.pcode.PcodeOp;
@@ -27,20 +28,17 @@ 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.
- *
+ * that {@linkplain 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
@@ -50,12 +48,12 @@ import ghidra.program.model.pcode.Varnode;
* {@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> {
+public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<MaskedBytes> {
/**
* The wrapper around one of the emulator's userops
*/
- protected class WrappedUseropDefinition implements PcodeUseropDefinition<Object> {
+ protected class WrappedUseropDefinition implements PcodeUseropDefinition<MaskedBytes> {
private final PcodeUseropDefinition<byte[]> rtOp;
/**
@@ -78,8 +76,9 @@ public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<Object> {
}
@Override
- public void execute(PcodeExecutor<Object> executor, PcodeUseropLibrary<Object> library,
- PcodeOp op, Varnode outVar, List<Varnode> inVars) {
+ public void execute(PcodeExecutor<MaskedBytes> executor,
+ PcodeUseropLibrary<MaskedBytes> library, PcodeOp op, Varnode outVar,
+ List<Varnode> inVars) {
throw new AssertionError();
}
@@ -94,13 +93,29 @@ public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<Object> {
*/
@Override
@SuppressWarnings("unchecked")
- public void execute(PcodeExecutor<Object> executor, PcodeUseropLibrary<Object> library,
- PcodeOp op) {
+ public void execute(PcodeExecutor<MaskedBytes> executor,
+ PcodeUseropLibrary<MaskedBytes> library, PcodeOp op) {
+ @SuppressWarnings("rawtypes")
+ PcodeExecutor rawExec = executor;
+ @SuppressWarnings("rawtypes")
+ PcodeUseropLibrary rawLib = library;
if (rtOp.canInlinePcode()) {
- @SuppressWarnings("rawtypes")
- PcodeExecutor rawExec = executor;
- @SuppressWarnings("rawtypes")
- PcodeUseropLibrary rawLib = library;
+ if (executor instanceof DecoderExecutor decEx) {
+ CollectExecutor collect = new CollectExecutor(decEx);
+ @SuppressWarnings("rawtypes")
+ PcodeExecutor rawColl = collect;
+ rtOp.execute(rawColl, rawLib, op);
+ List<PcodeOp> code = decEx.rewriteOps(collect.ops);
+ decEx.recordInline(op, code);
+ executor.execute(code, library);
+ }
+ else {
+ // likely the FoldRevalidator's executor, let it capture inlined ops
+ rtOp.execute(rawExec, rawLib, op);
+ }
+ }
+ else if (rtOp.isFunctional() && !rtOp.hasSideEffects() && !rtOp.modifiesContext()) {
+ // FoldingExecutor might like to try folding it
rtOp.execute(rawExec, rawLib, op);
}
else {
@@ -113,6 +128,11 @@ public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<Object> {
return rtOp.isFunctional();
}
+ @Override
+ public boolean canInterrupt() {
+ return rtOp.canInterrupt();
+ }
+
@Override
public boolean hasSideEffects() {
return rtOp.hasSideEffects();
@@ -128,6 +148,16 @@ public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<Object> {
return rtOp.canInlinePcode();
}
+ @Override
+ public boolean isOutSigned() {
+ return rtOp.isOutSigned();
+ }
+
+ @Override
+ public boolean isInSigned(int index) {
+ return rtOp.isInSigned(index);
+ }
+
@Override
public Class<?> getOutputType() {
return rtOp.getOutputType();
@@ -161,32 +191,44 @@ public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<Object> {
/**
* 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
+ * @param library the decoder's library
+ * @param op the op being executed
*/
@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);
+ public void emu_exec_decoded(@OpExecutor PcodeExecutor<MaskedBytes> executor,
+ @OpLibrary PcodeUseropLibrary<MaskedBytes> library, @OpOp PcodeOp op) {
+ if (executor instanceof DecoderExecutor de) {
+ // This is not wrapped, so it must collect and record the inline itself
+ PseudoInstruction instruction = de.decodeInstruction();
+ de.addInstruction(instruction);
+ PcodeProgram program = PcodeProgram.fromInstruction(instruction, false);
+ program = new PcodeProgram(program, de.rewriteOps(program.getCode()));
+ de.recordInline(op, program.getCode());
+ executor.execute(program, library);
+ }
+ else if (executor instanceof CanDecode cd) {
+ PseudoInstruction instruction = cd.decodeInstruction();
+ PcodeProgram program = PcodeProgram.fromInstruction(instruction, false);
+ executor.execute(program, library);
+ }
+ else {
+ throw new AssertionError();
+ }
}
/**
* 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
@@ -197,16 +239,20 @@ public class DecoderUseropLibrary extends AnnotatedPcodeUseropLibrary<Object> {
* 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
+ * @param op the op being executed
*/
@PcodeUserop(canInline = true)
- public void emu_skip_decoded(@OpExecutor PcodeExecutor<Object> executor) {
- DecoderExecutor de = (DecoderExecutor) executor;
- de.decodeInstruction();
+ public void emu_skip_decoded(@OpExecutor PcodeExecutor<MaskedBytes> executor,
+ @OpOp PcodeOp op) {
+ if (executor instanceof DecoderExecutor de) {
+ de.decodeInstruction();
+ // This is not wrapped, so it must record the "inline" itself
+ de.recordInline(op, List.of());
+ }
}
}
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.java
index 5ea92286bf..93f2846bc0 100644
--- 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.java
@@ -16,6 +16,7 @@
package ghidra.pcode.emu.jit.decode;
import ghidra.app.util.PseudoInstruction;
+import ghidra.lifecycle.Internal;
import ghidra.pcode.emu.InstructionDecoder;
import ghidra.pcode.emu.jit.*;
import ghidra.pcode.emu.jit.JitPassage.*;
@@ -31,7 +32,6 @@ 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
@@ -58,7 +58,6 @@ import ghidra.program.model.pcode.PcodeOp;
* 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
@@ -71,7 +70,6 @@ import ghidra.program.model.pcode.PcodeOp;
* 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}
@@ -89,13 +87,14 @@ import ghidra.program.model.pcode.PcodeOp;
* This class just keeps the configuration and some other trappings, and instantiates an
* actual decoder upon requesting a seed.
*/
+@Internal
public class JitPassageDecoder {
- final JitPcodeThread thread;
+ public final JitPcodeThread thread;
final InstructionDecoder decoder;
final ProgramContext defaultContext;
final Register contextreg;
- final DecoderUseropLibrary library;
+ public final DecoderUseropLibrary library;
/**
* Construct a passage decoder
@@ -127,7 +126,6 @@ public class JitPassageDecoder {
/**
* 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
@@ -146,6 +144,7 @@ public class JitPassageDecoder {
public JitPassage decodePassage(AddrCtx seed, int maxOps) {
DecoderForOnePassage forOne = new DecoderForOnePassage(this, seed, maxOps);
forOne.decodePassage();
+ forOne.revalidateFolded();
return forOne.finish();
}
@@ -156,9 +155,11 @@ public class JitPassageDecoder {
* @param ctx the input decode context
* @return the decoded instruction, or a {@link DecodeErrorInstruction}.
*/
- PseudoInstruction decodeInstruction(Address address, RegisterValue ctx) {
+ @Internal
+ public PseudoInstruction decodeInstruction(Address address, RegisterValue ctx) {
try {
- return decoder.decodeInstruction(address, ctx);
+ PseudoInstruction instruction = decoder.decodeInstruction(address, ctx);
+ return instruction;
}
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/folding/FoldRevalidator.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldRevalidator.java
new file mode 100644
index 0000000000..8bdf8ec268
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldRevalidator.java
@@ -0,0 +1,263 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.folding;
+
+import java.util.*;
+
+import ghidra.app.plugin.processors.sleigh.SleighLanguage;
+import ghidra.lifecycle.Internal;
+import ghidra.lifecycle.Unfinished;
+import ghidra.pcode.emu.jit.JitPassage.*;
+import ghidra.pcode.emu.jit.decode.CollectExecutor;
+import ghidra.pcode.emu.jit.decode.DecoderForOnePassage;
+import ghidra.pcode.exec.*;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.program.model.pcode.PcodeOp;
+
+/**
+ * A mechanism for re-validating the folded constants discovered during decode
+ * <p>
+ * Because alternative flows into a block can be discovered during decode, after that block's
+ * computations were already examined for folded constants, blocks must generally be re-examined
+ * with all discovered flows considered. We also have to consider that a block that becomes an entry
+ * point into the passage may have <em>no</em> incoming folded constants.
+ * <p>
+ * The algorithm is basically a forward traversal of block flows until we reach convergence. We
+ * haven't performed full control-flow analysis at this point, so we just follow branches and merge
+ * as we go. If the target is also an entry point, we erase all the folded constants in the "merged"
+ * state. Otherwise, we merge with the state at the target and re-queue it for interpretation.
+ * Merging consists of taking only those constants common to both states, and where those constants
+ * have the same value. If merging produces the same state as was already there, that target is
+ * <em>not</em> re-queued. Convergence occurs when the queue is empty. LATER: Prove it?
+ */
+@Internal
+public class FoldRevalidator {
+ final DecoderForOnePassage passage;
+ final List<PcodeOp> code;
+
+ final Map<PcodeOp, Integer> where = new HashMap<>(); // ick
+ final Map<PcodeOp, RIntBranch> invertedBranches = new HashMap<>();
+ final Map<PcodeOp, FoldedState> stateMap = new HashMap<>();
+ final Deque<PcodeOp> queue = new LinkedList<>();
+
+ /**
+ * Begin re-validating a decoded passage
+ *
+ * @param passage the (mutable) decoded passage
+ */
+ public FoldRevalidator(DecoderForOnePassage passage) {
+ this.passage = passage;
+ this.code = passage.strides.stream().flatMap(b -> b.ops().stream()).toList();
+
+ PcodeOp entry = passage.strides.getFirst().ops().getFirst();
+ this.stateMap.put(entry, new FoldedState(passage.decoder.thread.getLanguage()));
+ this.queue.add(entry);
+
+ for (int i = 0; i < code.size(); i++) {
+ where.put(code.get(i), i);
+ }
+
+ for (RIntBranch br : passage.internalBranches.values()) {
+ invertedBranches.put(br.to(), br);
+ }
+ }
+
+ /**
+ * The interpreter for re-validation
+ */
+ protected class RevalidateExecutor extends FoldingExecutor {
+ private final PcodeOp next;
+
+ protected RevalidateExecutor(DecoderForOnePassage passage, PcodeOp next) {
+ super(passage, stateMap.get(next).fork());
+ this.next = next;
+ }
+
+ void mergeAndQueue(PcodeOp to) {
+ FoldedState exists = stateMap.get(to);
+ if (exists == null) {
+ FoldedState choice = isEntry(to) ? new FoldedState(language) : state.fork();
+ stateMap.put(to, choice);
+ queue.add(to);
+ return;
+ }
+ /**
+ * Don't use .clear(). 1) It doesn't provide feedback as to whether or not the state
+ * changed. 2) We'd need logic to assure clearing out 00-masked bytes does not count as
+ * "changed." Intersecting with empty gets what we need, though at mildly greater cost.
+ */
+ FoldedState choice = isEntry(to) ? new FoldedState(language) : state;
+ if (exists.intersectInPlace(choice)) {
+ queue.add(to);
+ }
+ }
+
+ @Override
+ public void stepOp(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<MaskedBytes> library) {
+ if (op != next) {
+ RIntBranch br = invertedBranches.get(op);
+ if (br != null) {
+ mergeAndQueue(op);
+ frame.finishAsBranch();
+ return;
+ }
+ }
+ if (op.getOpcode() == PcodeOp.UNIMPLEMENTED) {
+ // Ignore these
+ // Don't just override badOp, because any unrecognized op goes there.
+ return;
+ }
+ super.stepOp(op, frame, library);
+ }
+
+ @Override
+ protected void doExecuteBranch(PcodeOp op, PcodeFrame frame) {
+ RIntBranch branch = passage.internalBranches.get(op);
+ if (branch == null) {
+ // An external or other branch
+ return;
+ }
+ PcodeOp to = branch.to();
+ mergeAndQueue(to);
+ }
+
+ @Override
+ public void executeBranch(PcodeOp op, PcodeFrame frame) {
+ doExecuteBranch(op, frame);
+ frame.finishAsBranch();
+ }
+
+ @Override
+ public void executeCall(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<MaskedBytes> library) {
+ doExecuteBranch(op, frame);
+ frame.finishAsBranch();
+ }
+
+ @Override
+ public void executeConditionalBranch(PcodeOp op, PcodeFrame frame) {
+ super.executeConditionalBranch(op, frame);
+ doExecuteBranch(op, frame);
+ int fallIndex = frame.index();
+ // Could be fall to external. Ensure the op is actually in the program
+ if (fallIndex < frame.getCode().size()) {
+ PcodeOp to = frame.getCode().get(fallIndex);
+ mergeAndQueue(to);
+ }
+ frame.finishAsBranch();
+ }
+
+ @Override
+ protected void doExecuteIndirectBranch(PcodeOp op, PcodeFrame frame) {
+ // Don't worry whether the target is still a valid constant at this point.
+ // Ensure the speculative block is still covered.
+ // We could encode a conditional branch to it, if the actual target matches.
+ doExecuteBranch(op, frame);
+ frame.finishAsBranch();
+ }
+
+ @Override
+ public void executeCallother(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<MaskedBytes> library) {
+ PcodeUseropDefinition<?> opDef = getUserop(op, frame, library);
+ if (opDef != null && opDef.canInlinePcode()) {
+ CollectExecutor collect = new CollectExecutor(language, state, reason, () -> {
+ DecodedPcodeOp decOp = (DecodedPcodeOp) op;
+ AddrCtx at = decOp.getAt();
+ return passage.decoder.decodeInstruction(at.address, at.rvCtx);
+ });
+ collect.executeCallother(op, frame, library);
+
+ if (!passage.checkSameInline(op, collect.ops)) {
+ throw new Unfinished.TODOException();
+ /**
+ * TODO: We'll need to remove old and insert new, which may involve re-executing
+ * and re-recording the same and possible additional inlines. This will also
+ * involve removing branches to or from the inlined ops.
+ *
+ * TODO: Some attention to the branches. My inclination is to make all branches,
+ * internal or not, behave like an exit. Library authors ought never to insert
+ * new instruction branches if folding fails, no?
+ *
+ * Another option is to just not inline it....
+ */
+ }
+ /**
+ * The inlined ops are already queued up, so don't actually "execute" the userop
+ * again.
+ */
+ return;
+ }
+ super.executeCallother(op, frame, library);
+ }
+
+ @Override
+ protected void onMissingUseropDef(PcodeOp op, PcodeFrame frame, String opName,
+ PcodeUseropLibrary<MaskedBytes> library) {
+ // The decoder has already created an ErrBranch for it.
+ }
+ }
+
+ /**
+ * A portion of a p-code program
+ * <p>
+ * Because we are "extracting" from a given start to the next branch, we generally don't need to
+ * specify the end, as the interpreter will naturally end at that branch.
+ */
+ class SubProgram extends PcodeProgram {
+ /**
+ * Construct a sub-program
+ *
+ * @param full the full program
+ * @param start which op to start on
+ */
+ SubProgram(List<PcodeOp> full, PcodeOp start) {
+ SleighLanguage language = passage.decoder.thread.getLanguage();
+ super(language, full.subList(where.get(start), full.size()),
+ passage.decoder.library.getSymbols(language));
+ }
+ }
+
+ /**
+ * Check if a given p-code op is a passage entry
+ *
+ * @param op the op
+ * @return true if it is an entry
+ */
+ boolean isEntry(PcodeOp op) {
+ if (!(op instanceof DecodedPcodeOp dec)) {
+ return false;
+ }
+ return passage.firstOps.get(dec.getAt()) == dec;
+ }
+
+ /**
+ * Re-validate folded constants
+ * <p>
+ * I had worried this algorithm could get expensive with loops with a counter. I thought perhaps
+ * with bit-level tricks in INT_ADD/SUB, the varnode would get invalidated one bit per
+ * re-interpretation of the loop. However, INT_ADD would invalidate all higher order bits of an
+ * unknown bit all at once.
+ */
+ public void revalidate() {
+ while (!queue.isEmpty()) {
+ PcodeOp next = queue.pollFirst();
+ FoldingExecutor exec = new RevalidateExecutor(passage, next);
+ exec.execute(new SubProgram(code, next));
+ }
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldedArithmetic.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldedArithmetic.java
new file mode 100644
index 0000000000..e552b4e2bd
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldedArithmetic.java
@@ -0,0 +1,238 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.folding;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+
+import ghidra.pcode.exec.*;
+import ghidra.program.model.address.AddressSpace;
+import ghidra.program.model.lang.Endian;
+import ghidra.program.model.lang.Language;
+import ghidra.program.model.pcode.PcodeOp;
+
+/**
+ * The arithmetic for computing folded constants
+ * <p>
+ * For the most part, the result of any operation is only known if all inputs are known. In that
+ * case, the result is equivalent to applying {@link BytesPcodeArithmetic}. Otherwise, the result is
+ * completely unknown. Special treatment is given to bitwise boolean operators, extension operators,
+ * and shift operators. We also give some special treatment for operators that only modify the sign
+ * bit, e.g., {@link PcodeOp#FLOAT_ABS}.
+ */
+public enum FoldedArithmetic implements PcodeArithmetic<MaskedBytes> {
+ /** The big-endian instance */
+ BE(Endian.BIG),
+ /** The little-endian instance */
+ LE(Endian.LITTLE);
+
+ /**
+ * {@return the instance for the given endian}
+ *
+ * @param endian the endian
+ */
+ public static FoldedArithmetic forEndian(Endian endian) {
+ return switch (endian) {
+ case BIG -> BE;
+ case LITTLE -> LE;
+ };
+ }
+
+ /**
+ * {@return the instance for the given language}
+ *
+ * @param language the language
+ */
+ public static FoldedArithmetic forLanguage(Language language) {
+ return language.isBigEndian() ? BE : LE;
+ }
+
+ private final Endian endian;
+ private final BytesPcodeArithmetic bytes;
+
+ FoldedArithmetic(Endian endian) {
+ this.endian = endian;
+ this.bytes = BytesPcodeArithmetic.forEndian(endian.isBigEndian());
+ }
+
+ @Override
+ public Class<MaskedBytes> getDomain() {
+ return MaskedBytes.class;
+ }
+
+ @Override
+ public Endian getEndian() {
+ return endian;
+ }
+
+ MaskedBytes unaryAllOrTop(int opcode, int sizeout, int sizein1, MaskedBytes in1) {
+ byte[] value1 = concreteOrNull(in1);
+ if (value1 == null) {
+ return MaskedBytes.ofUnknown(sizeout);
+ }
+ byte[] out = bytes.unaryOp(opcode, sizeout, sizein1, value1);
+ return MaskedBytes.ofKnown(out);
+ }
+
+ @Override
+ public MaskedBytes unaryOp(int opcode, int sizeout, int sizein1, MaskedBytes in1) {
+ // 2COMP, ADD, SUB (in case higher bits are TOP)?
+ // LZCOUNT (in case a high 1 appears, can disregard lower TOP)?
+ return switch (opcode) {
+ case PcodeOp.COPY -> in1;
+ case PcodeOp.BOOL_NEGATE, PcodeOp.INT_NEGATE -> in1.negate();
+ case PcodeOp.FLOAT_ABS -> in1.floatAbs(endian);
+ case PcodeOp.FLOAT_NEG -> in1.floatNeg(endian);
+ case PcodeOp.INT_SEXT -> in1.sext(sizeout, endian);
+ case PcodeOp.INT_ZEXT -> in1.zext(sizeout, endian);
+ default -> unaryAllOrTop(opcode, sizeout, sizein1, in1);
+ };
+ }
+
+ MaskedBytes left(MaskedBytes value, MaskedBytes shift) {
+ byte[] shiftC = concreteOrNull(shift);
+ if (shiftC == null) {
+ return MaskedBytes.ofUnknown(value.val.length);
+ }
+ int s = (int) bytes.toLong(shiftC, Purpose.OTHER);
+ BigInteger m = value.bigMask(endian)
+ .shiftLeft(s)
+ .or(BigInteger.ONE.shiftLeft(s).subtract(BigInteger.ONE));
+ BigInteger v = value.bigValue(endian).shiftLeft(s);
+ return MaskedBytes.of(v, m, value.val.length, endian);
+ }
+
+ MaskedBytes right(MaskedBytes value, MaskedBytes shift) {
+ byte[] shiftC = concreteOrNull(shift);
+ if (shiftC == null) {
+ return MaskedBytes.ofUnknown(value.val.length);
+ }
+ int s = (int) bytes.toLong(shiftC, Purpose.OTHER);
+ BigInteger m = value.bigMask(endian)
+ .shiftRight(s)
+ .or(BigInteger.ONE.shiftLeft(s)
+ .subtract(BigInteger.ONE)
+ .shiftLeft(value.val.length * 8 - s));
+ BigInteger v = value.bigValue(endian).shiftRight(s);
+ return MaskedBytes.of(v, m, value.val.length, endian);
+ }
+
+ MaskedBytes sright(MaskedBytes value, MaskedBytes shift) {
+ byte[] shiftC = concreteOrNull(shift);
+ if (shiftC == null) {
+ return MaskedBytes.ofUnknown(value.val.length);
+ }
+ int s = (int) bytes.toLong(shiftC, Purpose.OTHER);
+ BigInteger m = value.bigMaskSigned(endian) // Let the mask's sign bit be extended
+ .shiftRight(s);
+ BigInteger v = value.bigValueSigned(endian) // Let the sign bit be extended
+ .shiftRight(s);
+ return MaskedBytes.of(v, m, value.val.length, endian);
+ }
+
+ MaskedBytes subpiece(MaskedBytes value, MaskedBytes offset, int sizeout) {
+ byte[] offsetC = concreteOrNull(offset);
+ if (offsetC == null) {
+ // Should this be an assertion failure instead?
+ return MaskedBytes.ofUnknown(value.val.length);
+ }
+ int off = (int) bytes.toLong(offsetC, Purpose.OTHER);
+ BigInteger trunc = BigInteger.ONE.shiftLeft(sizeout * 8).subtract(BigInteger.ONE);
+ int over = sizeout - value.val.length + off;
+ BigInteger fill = over > 0
+ ? BigInteger.ONE.shiftLeft(over * 8)
+ .subtract(BigInteger.ONE)
+ .shiftLeft((value.val.length - off) * 8)
+ : BigInteger.ZERO;
+
+ BigInteger m = value.bigMask(endian)
+ .shiftRight(off * 8)
+ .or(fill)
+ .and(trunc);
+ BigInteger v = value.bigValue(endian)
+ .shiftRight(off * 8);
+ return MaskedBytes.of(v, m, sizeout, endian);
+ }
+
+ MaskedBytes binaryAllOrTop(int opcode, int sizeout, int sizein1, MaskedBytes in1,
+ int sizein2, MaskedBytes in2) {
+ byte[] value1 = concreteOrNull(in1);
+ if (value1 == null) {
+ return MaskedBytes.ofUnknown(sizeout);
+ }
+ byte[] value2 = concreteOrNull(in2);
+ if (value2 == null) {
+ return MaskedBytes.ofUnknown(sizeout);
+ }
+ byte[] out = bytes.binaryOp(opcode, sizeout, sizein1, value1, sizein2, value2);
+ return MaskedBytes.ofKnown(out);
+ }
+
+ @Override
+ public MaskedBytes binaryOp(int opcode, int sizeout, int sizein1, MaskedBytes in1,
+ int sizein2, MaskedBytes in2) {
+ // EQUAL, NOTEQUAL, because any known disagreement?
+ // SLESS,LESS(EQUAL), because can short circuit at high bits?
+ return switch (opcode) {
+ case PcodeOp.BOOL_AND, PcodeOp.INT_AND -> in1.and(in2);
+ case PcodeOp.BOOL_OR, PcodeOp.INT_OR -> in1.or(in2);
+ case PcodeOp.BOOL_XOR, PcodeOp.INT_XOR -> in1.xor(in2);
+ case PcodeOp.INT_LEFT -> left(in1, in2);
+ case PcodeOp.INT_RIGHT -> right(in1, in2);
+ case PcodeOp.INT_SRIGHT -> sright(in1, in2);
+ case PcodeOp.SUBPIECE -> subpiece(in1, in2, sizeout);
+ default -> binaryAllOrTop(opcode, sizeout, sizein1, in1, sizein2, in2);
+ };
+ }
+
+ @Override
+ public MaskedBytes modBeforeStore(int sizeinOffset, AddressSpace space, MaskedBytes inOffset,
+ int sizeinValue, MaskedBytes inValue) {
+ return inValue;
+ }
+
+ @Override
+ public MaskedBytes modAfterLoad(int sizeinOffset, AddressSpace space, MaskedBytes inOffset,
+ int sizeinValue, MaskedBytes inValue) {
+ return inValue;
+ }
+
+ @Override
+ public MaskedBytes fromConst(byte[] value) {
+ return MaskedBytes.ofKnown(value);
+ }
+
+ static byte[] concreteOrNull(MaskedBytes value) {
+ if (value.isMasked()) {
+ return null;
+ }
+ return value.val;
+ }
+
+ @Override
+ public byte[] toConcrete(MaskedBytes value, Purpose purpose) {
+ byte[] result = concreteOrNull(value);
+ if (result == null) {
+ throw new ConcretionError("Part of the value is masked", purpose);
+ }
+ return Arrays.copyOf(result, result.length);
+ }
+
+ @Override
+ public long sizeOf(MaskedBytes value) {
+ return value.val.length;
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldedState.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldedState.java
new file mode 100644
index 0000000000..4ca30df8d3
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldedState.java
@@ -0,0 +1,245 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.folding;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.stream.Stream;
+
+import generic.ULongSpan;
+import generic.ULongSpan.DefaultULongSpanSet;
+import generic.ULongSpan.MutableULongSpanSet;
+import ghidra.generic.util.datastruct.SemisparseByteArray;
+import ghidra.pcode.exec.*;
+import ghidra.pcode.exec.PcodeArithmetic.Purpose;
+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.util.Msg;
+
+/**
+ * A p-code executor state on {@link MaskedBytes}.
+ * <p>
+ * This is used as the state for interpretation when computing folded constants. Because the JIT
+ * only elides passage through registers and uniques, those are the only spaces we actually store
+ * here. Otherwise, this is roughly equivalent to {@link BytesPcodeExecutorState}, but we store both
+ * the values and masks of the {@link MaskedBytes} into the backing byte arrays.
+ */
+public class FoldedState implements PcodeExecutorState<MaskedBytes> {
+
+ private final Language language;
+ private final FoldedArithmetic arithmetic;
+
+ private final FoldedSpace uniqSpace = new FoldedSpace();
+ private final FoldedSpace regSpace = new FoldedSpace();
+
+ private class FoldedSpace {
+ SemisparseByteArray values = new SemisparseByteArray();
+ SemisparseByteArray masks = new SemisparseByteArray();
+
+ void setVar(long off, MaskedBytes value) {
+ values.putData(off, value.val);
+ masks.putData(off, value.msk);
+ }
+
+ MaskedBytes getVar(long off, int size) {
+ byte[] values = new byte[size];
+ byte[] masks = new byte[size];
+ this.values.getData(off, values);
+ this.masks.getData(off, masks);
+ return new MaskedBytes(values, masks);
+ }
+
+ void clear() {
+ values.clear();
+ masks.clear();
+ }
+
+ void addAll(FoldedSpace that) {
+ this.values.putAll(that.values);
+ this.masks.putAll(that.masks);
+ }
+
+ boolean intersect(FoldedSpace that) {
+ boolean changed = false;
+ MutableULongSpanSet union = new DefaultULongSpanSet();
+ union.addAll(this.values.getInitialized());
+ union.addAll(that.values.getInitialized());
+ byte[] thisVal = new byte[1];
+ byte[] thatVal = new byte[1];
+ byte[] thisMsk = new byte[1];
+ byte[] thatMsk = new byte[1];
+ for (ULongSpan span : union.spans()) {
+ for (long i = span.min(); Long.compareUnsigned(i, span.max()) <= 0; i++) {
+ if (this.values.isInitialized(i)) {
+ this.values.getData(i, thisVal);
+ Arrays.fill(thatVal, (byte) 0);
+ that.values.getData(i, thatVal);
+ this.masks.getData(i, thisMsk);
+ Arrays.fill(thatMsk, (byte) 0);
+ that.masks.getData(i, thatMsk);
+
+ int origMsk = thisMsk[0];
+
+ thisMsk[0] &= thatMsk[0];
+ int diffs = thisVal[0] ^ thatVal[0];
+ thisMsk[0] &= ~diffs;
+ thisVal[0] &= thisMsk[0];
+
+ changed |= (origMsk != thisMsk[0]);
+
+ this.values.putData(i, thisVal);
+ this.masks.putData(i, thisMsk);
+ }
+ }
+ }
+ return changed;
+ }
+ }
+
+ /**
+ * Construct a constant-folding state for the given language
+ *
+ * @param language the language
+ */
+ public FoldedState(Language language) {
+ this.language = language;
+ this.arithmetic = language.isBigEndian() ? FoldedArithmetic.BE : FoldedArithmetic.LE;
+ }
+
+ @Override
+ public Language getLanguage() {
+ return language;
+ }
+
+ @Override
+ public FoldedArithmetic getArithmetic() {
+ return arithmetic;
+ }
+
+ @Override
+ public Stream<PcodeExecutorStatePiece<?, ?>> streamPieces() {
+ return Stream.of(this);
+ }
+
+ @Override
+ public void setVar(AddressSpace space, MaskedBytes offset, int size, boolean quantize,
+ MaskedBytes val) {
+ setVarInternal(space, offset, size, val);
+ }
+
+ @Override
+ public void setVarInternal(AddressSpace space, MaskedBytes offset, int size,
+ MaskedBytes val) {
+ try {
+ if (space.isUniqueSpace()) {
+ long off = arithmetic.toLong(offset, Purpose.STORE);
+ uniqSpace.setVar(off, val);
+ }
+ else if (space.isRegisterSpace()) {
+ long off = arithmetic.toLong(offset, Purpose.STORE);
+ regSpace.setVar(off, val);
+ }
+ }
+ catch (ConcretionError e) {
+ Msg.warn(this, "Should not get unknown offsets in unique or register space");
+ }
+ }
+
+ @Override
+ public MaskedBytes getVar(AddressSpace space, MaskedBytes offset, int size, boolean quantize,
+ Reason reason) {
+ return getVarInternal(space, offset, size, reason);
+ }
+
+ @Override
+ public MaskedBytes getVarInternal(AddressSpace space, MaskedBytes offset, int size,
+ Reason reason) {
+ try {
+ if (space.isConstantSpace()) {
+ return offset.zext(size, arithmetic.getEndian());
+ }
+ else if (space.isUniqueSpace()) {
+ long off = arithmetic.toLong(offset, Purpose.LOAD);
+ return uniqSpace.getVar(off, size);
+ }
+ else if (space.isRegisterSpace()) {
+ long off = arithmetic.toLong(offset, Purpose.LOAD);
+ return regSpace.getVar(off, size);
+ }
+ }
+ catch (ConcretionError e) {
+ Msg.warn(this, "Should not get unknown offsets in unique or register space");
+ }
+ return MaskedBytes.ofUnknown(size);
+ }
+
+ @Override
+ public Map<Register, MaskedBytes> getRegisterValues() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public MemBuffer getConcreteBuffer(Address address, Purpose purpose) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void clear() {
+ uniqSpace.clear();
+ regSpace.clear();
+ }
+
+ /**
+ * Fork this state, without callbacks, because they're not supported here.
+ *
+ * @return the copy
+ */
+ public FoldedState fork() {
+ return fork(null);
+ }
+
+ @Override
+ public FoldedState fork(PcodeStateCallbacks cb) {
+ if (cb != null) {
+ throw new UnsupportedOperationException("callbacks");
+ }
+ FoldedState newState = new FoldedState(language);
+ newState.uniqSpace.addAll(this.uniqSpace);
+ newState.regSpace.addAll(this.regSpace);
+ return newState;
+ }
+
+ /**
+ * Merge the given state into this one, modifying this state in place
+ * <p>
+ * This is the merging operation used by {@link FoldRevalidator}. Where we have known values
+ * (1-bits in the mask) the other must also have known values, or else we erase our mask (and
+ * value) bits. If the other also has known values at the same offset, the values must match, or
+ * else we erase. These checks and erasures are applied with bit-level granularity. Any erasure
+ * results in a return of {@code true} (without short circuiting).
+ *
+ * @param that the other state
+ * @return true if this state changed as a result of this intersection
+ */
+ public boolean intersectInPlace(FoldedState that) {
+ boolean uniqChanged = this.uniqSpace.intersect(that.uniqSpace);
+ boolean regChanged = this.regSpace.intersect(that.regSpace);
+ return uniqChanged | regChanged;
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldingExecutor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldingExecutor.java
new file mode 100644
index 0000000000..f29a07c92d
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/FoldingExecutor.java
@@ -0,0 +1,252 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.folding;
+
+import ghidra.lifecycle.Internal;
+import ghidra.pcode.emu.jit.JitPassage.ExitPcodeOp;
+import ghidra.pcode.emu.jit.JitPassage.Operand;
+import ghidra.pcode.emu.jit.decode.DecoderForOnePassage;
+import ghidra.pcode.exec.*;
+import ghidra.pcode.exec.PcodeArithmetic.Purpose;
+import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.pcode.opbehavior.BinaryOpBehavior;
+import ghidra.pcode.opbehavior.UnaryOpBehavior;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.address.AddressSpace;
+import ghidra.program.model.pcode.PcodeOp;
+import ghidra.program.model.pcode.Varnode;
+
+/**
+ * An executor that records and/or removes folded constants into a passage decoder.
+ */
+@Internal
+public class FoldingExecutor extends PcodeExecutor<MaskedBytes> {
+ final DecoderForOnePassage passage;
+ protected final FoldedState state; // My own copy of more specific type
+
+ public FoldingExecutor(DecoderForOnePassage passage, FoldedState state) {
+ this.passage = passage;
+ this.state = state;
+ super(passage.decoder.thread.getLanguage(), state == null ? null : state.getArithmetic(),
+ state, Reason.EXECUTE_READ);
+ }
+
+ @Override
+ public FoldedState getState() {
+ return state;
+ }
+
+ /**
+ * 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, passage.library());
+ }
+
+ /**
+ * Record (or remove) a folded constant from the passage
+ * <p>
+ * If the value is not <em>completely</em> known, we do not record it. We may invalidate it,
+ * actually. (It remains in the state, but we don't record this specific operand instance as
+ * foldable.)
+ *
+ * @param op the op whose operand is being considered
+ * @param index the position of the operand, -1 for output, otherwise the input operand index
+ * @param value the value observed
+ * @return
+ */
+ MaskedBytes recordFolded(PcodeOp op, int index, MaskedBytes value) {
+ // No sense in recording the degenerate case
+ Varnode operand = index == -1 ? op.getOutput() : op.getInput(index);
+ if (operand.isConstant()) {
+ return value;
+ }
+
+ byte[] c = FoldedArithmetic.concreteOrNull(value);
+ Operand key = new Operand(op, index);
+ if (c != null) {
+ passage.folded.put(key, c);
+ }
+ else {
+ passage.folded.remove(key);
+ }
+ return value;
+ }
+
+ @Override
+ public void executeUnaryOp(PcodeOp op, UnaryOpBehavior b) {
+ if (state == null) {
+ return;
+ }
+ Varnode in1Var = op.getInput(0);
+ Varnode outVar = op.getOutput();
+ MaskedBytes in1 = recordFolded(op, 0, state.getVar(in1Var, reason));
+ MaskedBytes out = recordFolded(op, -1, arithmetic.unaryOp(op, in1));
+ state.setVar(outVar, out);
+ }
+
+ @Override
+ public void executeBinaryOp(PcodeOp op, BinaryOpBehavior b) {
+ if (state == null) {
+ return;
+ }
+ Varnode in1Var = op.getInput(0);
+ Varnode in2Var = op.getInput(1);
+ Varnode outVar = op.getOutput();
+ MaskedBytes in1 = recordFolded(op, 0, state.getVar(in1Var, reason));
+ MaskedBytes in2 = recordFolded(op, 1, state.getVar(in2Var, reason));
+ MaskedBytes out = recordFolded(op, -1, arithmetic.binaryOp(op, in1, in2));
+ state.setVar(outVar, out);
+ }
+
+ @Override
+ public void executeLoad(PcodeOp op) {
+ if (state == null) {
+ return;
+ }
+ super.executeLoad(op);
+ }
+
+ @Override
+ protected void afterLoad(PcodeOp op, AddressSpace space, MaskedBytes offset, int size,
+ MaskedBytes value) {
+ recordFolded(op, 1, offset);
+ // LATER: Treat near loads as constant?
+ // LATER: If so, would need to add to ranges causing translation cache invalidation
+ }
+
+ @Override
+ public void executeStore(PcodeOp op) {
+ if (state == null) {
+ return;
+ }
+ super.executeStore(op);
+ }
+
+ @Override
+ protected void afterStore(PcodeOp op, AddressSpace space, MaskedBytes offset, int size,
+ MaskedBytes value) {
+ recordFolded(op, 1, offset);
+ }
+
+ @Override
+ public void executeConditionalBranch(PcodeOp op, PcodeFrame frame) {
+ if (state == null) {
+ return;
+ }
+ if (op instanceof ExitPcodeOp) {
+ return;
+ }
+ Varnode condVar = getConditionalBranchPredicate(op);
+ recordFolded(op, OPIDX_CBRANCH_PRED, state.getVar(condVar, reason));
+ }
+
+ /**
+ * This attempts to resolve a folded constant address. If it succeeds, it delegates to
+ * {@link #branchToAddress(PcodeOp, Address)}. Otherwise, it delegates to
+ * {@link #doExecuteIndirectBranch(PcodeOp, PcodeFrame)}.
+ *
+ * @param op the p-code op
+ * @param frame the frame
+ */
+ protected void doFoldIndirectBranch(PcodeOp op, PcodeFrame frame) {
+ if (state == null) {
+ doExecuteIndirectBranch(op, frame);
+ return;
+ }
+ MaskedBytes offset = recordFolded(op, OPIDX_BRANCH_TARGET,
+ state.getVar(getIndirectBranchTarget(op), reason));
+ // Don't call branchToOffset
+ try {
+ long concrete = arithmetic.toLong(offset, Purpose.BRANCH);
+ Address target = op.getSeqnum().getTarget().getNewAddress(concrete, true);
+ branchToAddress(op, checkInjectedTarget(target));
+ }
+ catch (ConcretionError e) {
+ doExecuteIndirectBranch(op, frame);
+ }
+ }
+
+ @Override
+ public void executeIndirectBranch(PcodeOp op, PcodeFrame frame) {
+ doFoldIndirectBranch(op, frame);
+ }
+
+ @Override
+ public void executeIndirectCall(PcodeOp op, PcodeFrame frame) {
+ doFoldIndirectBranch(op, frame);
+ }
+
+ @Override
+ public void executeReturn(PcodeOp op, PcodeFrame frame) {
+ doFoldIndirectBranch(op, frame);
+ }
+
+ protected PcodeUseropDefinition<?> getUserop(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<?> library) {
+ int opNo = getCallotherOpNumber(op);
+ String opName = getUseropName(opNo, frame);
+ if (opName == null) {
+ return null;
+ }
+ return library.getUserops().get(opName);
+ }
+
+ @Override
+ public void executeCallother(PcodeOp op, PcodeFrame frame,
+ PcodeUseropLibrary<MaskedBytes> library) {
+ if (state == null) {
+ super.executeCallother(op, frame, library);
+ return;
+ }
+
+ PcodeUseropDefinition<?> opDef = getUserop(op, frame, library);
+ if (opDef == null || opDef.canInlinePcode()) {
+ // null case: Let super handle the error
+ // inline case: Let the constant analysis examine the inlined ops
+ super.executeCallother(op, frame, library);
+ return;
+ }
+
+ // We can still use folded inputs, even if the userop is not itself foldable
+ int n = op.getNumInputs();
+ boolean tryFoldOutput = true;
+ for (int i = 0; i < n; i++) {
+ MaskedBytes in = recordFolded(op, i, state.getVar(op.getInput(i), reason));
+ if (FoldedArithmetic.concreteOrNull(in) == null) {
+ tryFoldOutput = false;
+ }
+ }
+ if (!opDef.isFunctional()) {
+ // Userop has carte blanche, so erase all assumptions about constants :(
+ state.clear();
+ return;
+ }
+ Varnode outVar = op.getOutput();
+ if (outVar != null) {
+ if (tryFoldOutput && !opDef.hasSideEffects() && !opDef.modifiesContext()) {
+ super.executeCallother(op, frame, library);
+ recordFolded(op, -1, state.getVar(outVar, Reason.INSPECT));
+ }
+ // It has an output that we didn't even try to fold
+ state.setVar(outVar, MaskedBytes.ofUnknown(outVar.getSize()));
+ passage.folded.remove(new Operand(op, -1));
+ }
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/MaskedBytes.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/MaskedBytes.java
new file mode 100644
index 0000000000..ac0b70e1ab
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/folding/MaskedBytes.java
@@ -0,0 +1,473 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.folding;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+
+import ghidra.pcode.utils.Utils;
+import ghidra.program.model.lang.Endian;
+
+/**
+ * A masked array of bytes.
+ * <p>
+ * This consists of a pair of byte arrays. One that represents the values, if known, and another
+ * that indicates which bits of the values array are actually known.
+ */
+public final class MaskedBytes {
+ final byte[] val;
+ final byte[] msk;
+
+ /**
+ * Construct from arrays
+ * <p>
+ * The given arrays are copied, and the mask is applied so that all unknown bits have 0s in the
+ * values array.
+ *
+ * @param val the value array
+ * @param msk the mask array
+ * @return the masked bytes
+ */
+ public static MaskedBytes of(byte[] val, byte[] msk) {
+ final int l = val.length;
+ if (val.length != l) {
+ throw new IllegalArgumentException("Lengths must match");
+ }
+ byte[] mval = new byte[l];
+ for (int i = 0; i < l; i++) {
+ mval[i] = (byte) (val[i] & msk[i]);
+ }
+ return new MaskedBytes(mval, Arrays.copyOf(msk, l));
+ }
+
+ /**
+ * Construct from big integers
+ *
+ * @param val the value
+ * @param msk the bits of the value that are known
+ * @param length the size of the value in bytes
+ * @param endian the endianness of the bytes
+ * @return the masked bytes
+ */
+ public static MaskedBytes of(BigInteger val, BigInteger msk, int length, Endian endian) {
+ byte[] bVal = Utils.bigIntegerToBytes(val, length, endian.isBigEndian());
+ byte[] bMsk = Utils.bigIntegerToBytes(msk, length, endian.isBigEndian());
+ return of(bVal, bMsk);
+ }
+
+ /**
+ * Construct from longs
+ *
+ * @param val the value
+ * @param msk the bits of the value that are known
+ * @param length the size of the value in bytes
+ * @param endian the endianness of the bytes
+ * @return the masked bytes
+ */
+ public static MaskedBytes of(long val, long msk, int length, Endian endian) {
+ byte[] bVal = Utils.longToBytes(val, length, endian.isBigEndian());
+ byte[] bMsk = Utils.longToBytes(msk, length, endian.isBigEndian());
+ return of(bVal, bMsk);
+ }
+
+ /**
+ * Construct from known bytes
+ * <p>
+ * The resulting mask is all 1s.
+ *
+ * @param val the known values
+ * @return the masked bytes
+ */
+ public static MaskedBytes ofKnown(byte[] val) {
+ final int l = val.length;
+ byte[] msk = new byte[l];
+ Arrays.fill(msk, (byte) -1);
+ return new MaskedBytes(Arrays.copyOf(val, l), msk);
+ }
+
+ /**
+ * Construct completely unknown
+ * <p>
+ * The contents of both arrays (value and mask) are all 0s
+ *
+ * @param length the number of bytes
+ * @return the masked bytes
+ */
+ public static MaskedBytes ofUnknown(int length) {
+ return new MaskedBytes(new byte[length], new byte[length]);
+ }
+
+ MaskedBytes(byte[] val, byte[] msk) {
+ assert val.length == msk.length;
+ this.val = val;
+ this.msk = msk;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof MaskedBytes that)) {
+ return false;
+ }
+ return Arrays.equals(this.val, that.val) && Arrays.equals(this.msk, that.msk);
+ }
+
+ private void byteToString(StringBuilder sb, int i) {
+ byte v = val[i];
+ byte m = msk[i];
+ if (m == -1) {
+ sb.append("%02x".formatted(v));
+ return;
+ }
+ for (int j = 0; j < 2; j++) {
+ if ((m & 0xf0) == 0xf0) {
+ sb.append("%1x".formatted(Byte.toUnsignedInt(v) >>> 4));
+ m <<= 4;
+ v <<= 4;
+ }
+ else if ((m & 0xf0) == 0) {
+ sb.append("X");
+ m <<= 4;
+ v <<= 4;
+ }
+ else {
+ sb.append("[");
+ for (int k = 0; k < 4; k++) {
+ if ((m & 0x80) == 0x80) {
+ sb.append("%1x".formatted(Byte.toUnsignedInt(v) >>> 7));
+ }
+ else {
+ sb.append("x");
+ }
+ m <<= 1;
+ v <<= 1;
+ }
+ sb.append("]");
+ }
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < val.length; i++) {
+ byteToString(sb, i);
+ sb.append(":");
+ }
+ return sb.substring(0, sb.length() - 1);
+ }
+
+ /**
+ * {@return true if <em>any</em> portion, even a single bit, of the value is unknown}
+ */
+ public boolean isMasked() {
+ for (int i = 0; i < msk.length; i++) {
+ if (msk[i] != -1) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * {@return the value as an unsigned big integer}
+ *
+ * @param endian the endianness of the bytes
+ */
+ public BigInteger bigValue(Endian endian) {
+ return Utils.bytesToBigInteger(val, val.length, endian.isBigEndian(), false);
+ }
+
+ /**
+ * {@return the value as a signed big integer}
+ *
+ * @param endian the endianness of the bytes
+ */
+ public BigInteger bigValueSigned(Endian endian) {
+ return Utils.bytesToBigInteger(val, val.length, endian.isBigEndian(), true);
+ }
+
+ /**
+ * {@return the mask as an unsigned big integer}
+ *
+ * @param endian the endianness of the bytes
+ */
+ public BigInteger bigMask(Endian endian) {
+ return Utils.bytesToBigInteger(msk, msk.length, endian.isBigEndian(), false);
+ }
+
+ /**
+ * {@return the mask as a signed big integer}
+ *
+ * @param endian the endianness of the bytes
+ */
+ public BigInteger bigMaskSigned(Endian endian) {
+ return Utils.bytesToBigInteger(msk, msk.length, endian.isBigEndian(), true);
+ }
+
+ /**
+ * Invert the known bits
+ *
+ * @return the new masked bytes
+ */
+ public MaskedBytes negate() {
+ byte[] neg = new byte[val.length];
+ for (int i = 0; i < val.length; i++) {
+ neg[i] = (byte) (~val[i] & msk[i]);
+ }
+ return new MaskedBytes(neg, msk);
+ }
+
+ /**
+ * Perform a bitwise and
+ * <p>
+ * Note that known 0s in either operand cause known 0s in the result, even if the same bit of
+ * the other operand was unknown.
+ *
+ * @param that the other operand
+ * @return the result
+ */
+ public MaskedBytes and(MaskedBytes that) {
+ final int n = Math.min(this.val.length, that.val.length);
+ final int l = Math.max(this.val.length, that.val.length);
+ byte[] val = new byte[l];
+ byte[] msk = new byte[l];
+ for (int i = 0; i < n; i++) {
+ val[i] = (byte) (this.val[i] & that.val[i]);
+ int thisKnown0 = this.msk[i] & ~this.val[i];
+ int thatKnown0 = that.msk[i] & ~that.val[i];
+ msk[i] = (byte) (this.msk[i] & that.msk[i] | thisKnown0 | thatKnown0);
+ }
+ for (int i = n; i < l; i++) {
+ // val[i] already 0
+ msk[i] = -1;
+ }
+ return new MaskedBytes(val, msk);
+ }
+
+ /**
+ * Perform a bitwise or
+ * <p>
+ * Note that known 1s in either operand cause known ss in the result, even if the same bit of
+ * the other operand was unknown.
+ *
+ * @param that the other operand
+ * @return the result
+ */
+ public MaskedBytes or(MaskedBytes that) {
+ final int n = Math.min(this.val.length, that.val.length);
+ final int l = Math.max(this.val.length, that.val.length);
+ byte[] val = new byte[l];
+ byte[] msk = new byte[l];
+ for (int i = 0; i < n; i++) {
+ val[i] = (byte) (this.val[i] | that.val[i]);
+ int thisKnown1 = this.msk[i] & this.val[i];
+ int thatKnown1 = that.msk[i] & that.val[i];
+ msk[i] = (byte) (this.msk[i] & that.msk[i] | thisKnown1 | thatKnown1);
+ }
+ byte[] v = this.val.length == n ? that.val : this.val;
+ byte[] m = this.val.length == n ? that.msk : this.msk;
+ for (int i = n; i < l; i++) {
+ val[i] = v[i];
+ msk[i] = m[i];
+ }
+ return new MaskedBytes(val, msk);
+ }
+
+ /**
+ * Perform a bitwise xor
+ *
+ * @param that the other operand
+ * @return the result
+ */
+ public MaskedBytes xor(MaskedBytes that) {
+ final int n = Math.min(this.val.length, that.val.length);
+ final int l = Math.max(this.val.length, that.val.length);
+ byte[] val = new byte[l];
+ byte[] msk = new byte[l];
+ for (int i = 0; i < n; i++) {
+ msk[i] = (byte) (this.msk[i] & that.msk[i]);
+ val[i] = (byte) ((this.val[i] ^ that.val[i]) & msk[i]);
+ }
+ byte[] v = this.val.length == n ? that.val : this.val;
+ byte[] m = this.val.length == n ? that.msk : this.msk;
+ for (int i = n; i < l; i++) {
+ val[i] = v[i];
+ msk[i] = m[i];
+ }
+ return new MaskedBytes(val, msk);
+ }
+
+ /**
+ * Zero out the first bit
+ * <p>
+ * The first bit becomes a known 0 in the result, even if it was unknown.
+ *
+ * @param endian the endianness of the bytes
+ * @return the result
+ */
+ public MaskedBytes floatAbs(Endian endian) {
+ final int l = this.val.length;
+ int idxMsb = switch (endian) {
+ case BIG -> 0;
+ case LITTLE -> l - 1;
+ };
+ if ((this.msk[idxMsb] & 0x80) == 0x80 && (this.val[idxMsb] & 0x80) == 0) {
+ return this;
+ }
+ final byte[] val;
+ final byte[] msk;
+ if ((this.val[idxMsb] & 0x80) == 0) {
+ val = this.val;
+ }
+ else {
+ val = Arrays.copyOf(this.val, l);
+ val[idxMsb] &= 0x7f;
+ }
+ if ((this.msk[idxMsb] & 0x80) == 0x80) {
+ msk = this.msk;
+ }
+ else {
+ msk = Arrays.copyOf(this.msk, l);
+ msk[idxMsb] |= 0x80;
+ }
+ return new MaskedBytes(val, msk);
+ }
+
+ /**
+ * Invert the first bit, if it is known
+ *
+ * @param endian the endianness of the bytes
+ * @return the result
+ */
+ public MaskedBytes floatNeg(Endian endian) {
+ final int l = this.val.length;
+ int idxMsb = switch (endian) {
+ case BIG -> 0;
+ case LITTLE -> l - 1;
+ };
+ if ((this.msk[idxMsb] & 0x80) == 0) {
+ return this;
+ }
+ final byte[] val = Arrays.copyOf(this.val, l);
+ val[idxMsb] ^= 0x80;
+ return new MaskedBytes(val, msk);
+ }
+
+ private static void copy(MaskedBytes from, int fromOffset, MaskedBytes into, int intoOffset,
+ int length) {
+ System.arraycopy(from.val, fromOffset, into.val, intoOffset, length);
+ System.arraycopy(from.msk, fromOffset, into.msk, intoOffset, length);
+ }
+
+ /**
+ * Copy a range of the masked bytes
+ *
+ * @param start the first byte to include
+ * @param stop the last byte, exclusive
+ * @return the copy
+ */
+ public MaskedBytes copyOfRange(int start, int stop) {
+ return new MaskedBytes(
+ Arrays.copyOfRange(val, start, stop),
+ Arrays.copyOfRange(msk, start, stop));
+ }
+
+ private MaskedBytes shrink(MaskedBytes into, Endian endian) {
+ final int l = into.val.length;
+ int off = switch (endian) {
+ case BIG -> this.val.length - l;
+ case LITTLE -> 0;
+ };
+ copy(this, off, into, 0, l);
+ return into;
+ }
+
+ private MaskedBytes grow(MaskedBytes into, byte signVal, byte signMsk, Endian endian) {
+ final int lInfo = into.val.length;
+ final int lThis = this.val.length;
+ int copyOff;
+ int slackStart;
+ int slackEnd;
+ switch (endian) {
+ case BIG -> {
+ copyOff = lInfo - lThis;
+ slackStart = 0;
+ slackEnd = copyOff;
+ }
+ case LITTLE -> {
+ copyOff = 0;
+ slackStart = lThis;
+ slackEnd = lInfo;
+ }
+ default -> throw new AssertionError();
+ }
+
+ copy(this, 0, into, copyOff, lThis);
+ for (int i = slackStart; i < slackEnd; i++) {
+ into.val[i] = signVal;
+ into.msk[i] = signMsk;
+ }
+ return into;
+ }
+
+ private byte sign(byte val) {
+ return (byte) (val >> 7);
+ }
+
+ /**
+ * Perform sign extension
+ * <p>
+ * The sign bit (known 0, known 1, or unknown) is extended to fill the requested size.
+ *
+ * @param size the size in bytes of the result
+ * @param endian the endianness of the bytes
+ * @return the extended masked bytes
+ */
+ public MaskedBytes sext(int size, Endian endian) {
+ if (size == val.length) {
+ return this;
+ }
+ MaskedBytes result = MaskedBytes.ofUnknown(size);
+ if (size < val.length) {
+ return shrink(result, endian);
+ }
+ int idxMsb = switch (endian) {
+ case BIG -> 0;
+ case LITTLE -> val.length - 1;
+ };
+ return grow(result, sign(val[idxMsb]), sign(msk[idxMsb]), endian);
+ }
+
+ /**
+ * Perform zero/unsigned extension
+ * <p>
+ * Known 0s fill to the requested size
+ *
+ * @param size the size in bytes of the result
+ * @param endian the endianness of the bytes
+ * @return the extended masked bytes
+ */
+ public MaskedBytes zext(int size, Endian endian) {
+ if (size == val.length) {
+ return this;
+ }
+ MaskedBytes result = MaskedBytes.ofUnknown(size);
+ if (size < val.length) {
+ return shrink(result, endian);
+ }
+ return grow(result, (byte) 0, (byte) -1, endian);
+ }
+}
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.java
index 59a6334074..de0a80f39e 100644
--- 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.java
@@ -27,13 +27,11 @@ 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
@@ -62,11 +60,14 @@ public record ExceptionHandler(PcodeOp op, JitBlock block, Lbl<Ent<Bot, TRef<Thr
* @param em the dead emitter
* @param localThis a handle to the local holding the {@code this} reference
* @param gen the code generator
+ * @param linenumber the "line number" of the exception handler
* @return the dead emitter
*/
public <THIS extends JitCompiledPassage> Emitter<Dead> genRun(Emitter<Dead> em,
- Local<TRef<THIS>> localThis, JitCodeGenerator<THIS> gen) {
- var emLive = em.emit(Lbl::placeDead, lbl);
+ Local<TRef<THIS>> localThis, JitCodeGenerator<THIS> gen, int linenumber) {
+ var emLive = em
+ .emit(Lbl::placeDead, lbl)
+ .emit(Misc::lineNumber, linenumber);
if (gen.context.getConfiguration().logStackTraces()) {
emLive = emLive
.emit(Op::dup)
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.java
index cba6e6dfa0..3ce88005a3 100644
--- 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.java
@@ -31,7 +31,6 @@ 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
@@ -48,14 +47,12 @@ public record FieldForSpaceIndirect(AddressSpace space)
/**
* {@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:
*
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.java
index fa80c0fdfb..235ab9736c 100644
--- 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.java
@@ -32,14 +32,13 @@ 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<byte[]> userop)
+public record FieldForUserop(PcodeUseropDefinition<?> userop)
implements InstanceFieldReq<TRef<PcodeUseropDefinition<byte[]>>> {
@Override
public String name() {
@@ -48,14 +47,12 @@ public record FieldForUserop(PcodeUseropDefinition<byte[]> userop)
/**
* {@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:
*
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.java
index cbc9f550c8..0290e4f421 100644
--- 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.java
@@ -35,6 +35,7 @@ import ghidra.pcode.emu.jit.JitPassage.AddrCtx;
import ghidra.pcode.emu.jit.JitPassage.DecodedPcodeOp;
import ghidra.pcode.emu.jit.alloc.JvmLocal;
import ghidra.pcode.emu.jit.analysis.*;
+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;
import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;
import ghidra.pcode.emu.jit.analysis.JitType.*;
import ghidra.pcode.emu.jit.gen.op.IntMultOpGen;
@@ -57,7 +58,10 @@ 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.emu.util.CountsPcodeOps;
+import ghidra.pcode.emu.util.PcodeOpCounter;
import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.pcode.exec.SleighPcodeUseropDefinition;
import ghidra.program.model.address.*;
import ghidra.program.model.lang.*;
@@ -67,7 +71,6 @@ 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
@@ -81,7 +84,6 @@ import ghidra.util.Msg;
* {@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>
@@ -153,7 +155,7 @@ import ghidra.util.Msg;
* </ol>
*
* <p>
- * This first ensure that a valid entry point was given in {@code blockId}. If not, we jump to the
+ * This first ensures 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
@@ -173,7 +175,6 @@ import ghidra.util.Msg;
* 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
@@ -188,6 +189,8 @@ import ghidra.util.Msg;
* @param <THIS> the type of the generated passage
*/
public class JitCodeGenerator<THIS extends JitCompiledPassage> {
+ static final boolean DEEP_TRACE = JitCompiler.ENABLE_DIAGNOSTICS.contains(Diag.DEEP_TRACE);
+
/**
* The key for a varnode, to ensure we control the definition of {@link Object#equals(Object)
* equality}.
@@ -223,6 +226,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
final JitAnalysisContext context;
final JitControlFlowModel cfm;
final JitDataFlowModel dfm;
+ final JitReachabilityModel rm;
final JitVarScopeModel vsm;
final JitTypeModel tm;
final JitAllocationModel am;
@@ -248,7 +252,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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
@@ -260,18 +263,20 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @param context the analysis context for the passage
* @param cfm the control flow model
* @param dfm the data flow model
+ * @param rm the reachability 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) {
+ JitDataFlowModel dfm, JitReachabilityModel rm, JitVarScopeModel vsm, JitTypeModel tm,
+ JitAllocationModel am, JitOpUseModel oum) {
this.lookup = lookup;
this.context = context;
this.cfm = cfm;
this.dfm = dfm;
+ this.rm = rm;
this.vsm = vsm;
this.tm = tm;
this.am = am;
@@ -326,41 +331,40 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
}
/**
- * Get the analysis context
- *
- * @return the context
+ * {@return the analysis context}
*/
public JitAnalysisContext getAnalysisContext() {
return context;
}
/**
- * Get the variable scope model
- *
- * @return the model
+ * {@return the variable scope model}
*/
public JitVarScopeModel getVariableScopeModel() {
return vsm;
}
/**
- * Get the type model
- *
- * @return the model
+ * {@return the type model}
*/
public JitTypeModel getTypeModel() {
return tm;
}
/**
- * Get the allocation model
- *
- * @return the model
+ * {@return the allocation model}
*/
public JitAllocationModel getAllocationModel() {
return am;
}
+ /**
+ * {@return the op use model}
+ */
+ public JitOpUseModel getOpUseModel() {
+ return oum;
+ }
+
/**
* Emit the first bytecodes for the static initializer
*
@@ -437,7 +441,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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
@@ -452,6 +455,9 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
*/
protected <N extends Next> Emitter<Ent<N, TRef<JitBytesPcodeExecutorStateSpace>>>
genLoadJitStateSpace(Emitter<N> em, Local<TRef<THIS>> localThis, AddressSpace space) {
+ if (DEEP_TRACE) {
+ System.err.println(" // space=%s".formatted(space));
+ }
return em
/**
* return
@@ -506,7 +512,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @return the field request
*/
protected FieldForContext requestStaticFieldForContext(RegisterValue ctx) {
- return fieldsForContext.computeIfAbsent(ctx, c -> {
+ return fieldsForContext.computeIfAbsent(ctx, _ -> {
FieldForContext f = new FieldForContext(ctx);
return f;
});
@@ -519,7 +525,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @return the field request
*/
public FieldForVarnode requestStaticFieldForVarnode(Varnode vn) {
- return fieldsForVarnode.computeIfAbsent(new VarnodeKey(vn), vk -> {
+ return fieldsForVarnode.computeIfAbsent(new VarnodeKey(vn), _ -> {
FieldForVarnode f = new FieldForVarnode(vn);
return f;
});
@@ -534,7 +540,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @return the field request
*/
public FieldForPcodeOp requestStaticFieldForOp(PcodeOp op) {
- return fieldsForOp.computeIfAbsent(new PcodeOpKey(op), ok -> new FieldForPcodeOp(this, op));
+ return fieldsForOp.computeIfAbsent(new PcodeOpKey(op), _ -> new FieldForPcodeOp(this, op));
}
/**
@@ -543,8 +549,8 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @param userop the userop
* @return the field request
*/
- public FieldForUserop requestFieldForUserop(PcodeUseropDefinition<byte[]> userop) {
- return fieldsForUserop.computeIfAbsent(userop.getName(), n -> {
+ public FieldForUserop requestFieldForUserop(PcodeUseropDefinition<?> userop) {
+ return fieldsForUserop.computeIfAbsent(userop.getName(), _ -> {
FieldForUserop f = new FieldForUserop(userop);
return f;
});
@@ -570,7 +576,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @return the label
*/
public Lbl<Bot> labelForBlock(JitBlock block) {
- return blockLabels.computeIfAbsent(block, b -> Lbl.create());
+ return blockLabels.computeIfAbsent(block, _ -> Lbl.create());
}
/**
@@ -660,7 +666,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* counter-intuitive for a user to receive a single varnode in several parameters. The
* annotation system to sort that all out would also be atrocious and not easily made compatible
* with non-JIT emulation. Instead, mp-int arguments are received via {@code int[]} parameters.
- *
+ * <p>
* The second case is for more complicated p-code ops. One notable example is
* {@link IntMultOpGen int_mult}. Theoretically, yes, we could emit all of the operations to
* compute the product using long multiplication inline; however, for large operands, that would
@@ -774,12 +780,10 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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
@@ -800,6 +804,11 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
protected OpResult genOp(Emitter<Bot> em, Local<TRef<THIS>> localThis, Local<TInt> localCtxmod,
RetReq<TRef<EntryPoint>> retReq, PcodeOp op, JitBlock block, int opIdx) {
JitOp jitOp = dfm.getJitOp(op);
+ if (DEEP_TRACE) {
+ PcodeUseropSymbolMap symbols = dfm.getLibrary().getSymbols(context.getLanguage());
+ System.err.println(" op: %s %s %s".formatted(oum.prefixFor(jitOp), op.getSeqnum(),
+ jitOp.toString(symbols)));
+ }
if (!oum.isUsed(jitOp)) {
return new LiveOpResult(em);
}
@@ -813,7 +822,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* Emit the bytecode translation for the ops in the given p-code block
- *
* <p>
* This simply invokes {@link #genOp(Emitter, Local, Local, RetReq, PcodeOp, JitBlock, int)} on
* each op in the block and counts up the indices. Other per-block instrumentation is not
@@ -838,7 +846,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
result = genOp(live.em(), localThis, localCtxmod, retReq, op, block, opIdx);
opIdx++;
}
- return new GenBlockResult(opIdx, result);
+ return GenBlockResult.normal(opIdx, result);
}
/**
@@ -847,12 +855,89 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @param opIdx the index of the <em>next</em> op
* @param opResult the result of op generation, indicating whether or not control flow can fall
* through
+ * @param wasEmpty indicates the block had no used ops
+ * @param instructions see {@link CountsPcodeOps#instructionCount}
+ * @param trailingOps see {@link CountsPcodeOps#trailingOpCount}
*/
- record GenBlockResult(int opIdx, OpResult opResult) {}
+ record GenBlockResult(int opIdx, OpResult opResult, boolean wasEmpty, int instructionCount,
+ int trailingOpCount) implements CountsPcodeOps {
+ /**
+ * The block contained some (used) p-code ops
+ *
+ * @param opIdx the updated op index (including unused ops)
+ * @param opResult the result of op generation, indicating whether or not control flow can
+ * fall through
+ * @return the result
+ */
+ static GenBlockResult normal(int opIdx, OpResult opResult) {
+ return new GenBlockResult(opIdx, opResult, false, 0, 0);
+ }
+
+ /**
+ * The block contained no (used) p-code ops and had only fall-through flow from.
+ * Additionally, that fall-through flow is the <em>only</em> flow into the next block.
+ * <p>
+ * The first block in a coalesced chain <em>may</em> have a branching flow into it, in which
+ * case, the label for that block must still be generated, even if no ops and no counter are
+ * emitted. If a block has a branch out, or the following block has a branch in, this block
+ * must emit a counter, even if no ops are emitted, so that the instruction/op counts are
+ * correctly computed for the actual execution path. If counts are disabled
+ * ({@link JitConfiguration.Opt#EMIT_COUNTERS}), then this rule should still produce optimal
+ * results.
+ *
+ * @param opIdx the update op index (including unused ops)
+ * @param opResult the result of op generation, indicating whether or not control flow can
+ * fall through
+ * @param instructions see {@link CountsPcodeOps#instructionCount}
+ * @param trailingOps see {@link CountsPcodeOps#trailingOpCount}
+ * @return the result
+ */
+ static GenBlockResult empty(int opIdx, OpResult opResult, int instructions,
+ int trailingOps) {
+ return new GenBlockResult(opIdx, opResult, true, instructions, trailingOps);
+ }
+
+ /**
+ * Produce a normal result with opIdx incremented the given amount, having not actually
+ * generated any code
+ *
+ * @param ops the number of ops (used or not) in the block
+ * @return the result
+ */
+ public GenBlockResult incremented(int ops) {
+ return GenBlockResult.normal(opIdx + ops, opResult);
+ }
+
+ /**
+ * Produce an empty result with opIdx incremented the given total and the given counts
+ *
+ * @param totalOps the total number of ops (used or not) in the block, used to increment
+ * opIdx
+ * @param opCounts the total number of instructions and trailing ops to defer to the next
+ * block
+ * @return the result
+ */
+ public GenBlockResult emptyIncremented(int totalOps, CountsPcodeOps opCounts) {
+ PcodeOpCounter counter = new PcodeOpCounter();
+ counter.count(this);
+ counter.count(opCounts);
+ return GenBlockResult.empty(opIdx + totalOps, opResult, counter.instructionCount(),
+ counter.trailingOpCount());
+ }
+
+ /**
+ * Produce a result after auxiliary code generation
+ *
+ * @param em the live emitter
+ * @return the result
+ */
+ public GenBlockResult aux(Emitter<Bot> em) {
+ return GenBlockResult.normal(opIdx, new LiveOpResult(em));
+ }
+ }
/**
* 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,
@@ -863,24 +948,57 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* @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 GenBlockResult genBlock(OpResult prev, Local<TRef<THIS>> localThis,
- Local<TInt> localCtxmod, RetReq<TRef<EntryPoint>> retReq, JitBlock block, int opIdx) {
+ protected GenBlockResult genBlock(GenBlockResult prev, Local<TRef<THIS>> localThis,
+ Local<TInt> localCtxmod, RetReq<TRef<EntryPoint>> retReq, JitBlock block) {
+ final boolean hasBranchInto;
LiveOpResult live;
- if (block.hasJumpTo() || getOpEntry(block.first()) != null) {
- live = new LiveOpResult(switch (prev) {
+ if (block.hasJumpTo(rm::isTakeable) || getOpEntry(block.first()) != null) {
+ if (DEEP_TRACE) {
+ System.err.println(" gen: has branch into");
+ }
+ hasBranchInto = true;
+ live = new LiveOpResult(switch (prev.opResult) {
case DeadOpResult r -> r.em().emit(Lbl::placeDead, labelForBlock(block));
case LiveOpResult r -> r.em().emit(Lbl::place, labelForBlock(block));
});
}
- else if (prev instanceof LiveOpResult r) {
+ else if (prev.opResult instanceof LiveOpResult r) {
+ if (DEEP_TRACE) {
+ System.err.println(" gen: no branch into");
+ }
+ hasBranchInto = false;
live = r;
}
else {
Msg.warn(this, "No control flow into block " + block.start());
- return new GenBlockResult(opIdx, prev);
+ return prev.incremented(block.getCode().size());
//throw new AssertionError("No control flow into a block");
}
+ BlockFlow fall = block.getFallFrom();
+ final boolean isFallOnlyWayToNext = fall != null && rm.isTakeable(fall) && fall.to()
+ .flowsTo()
+ .values()
+ .stream()
+ .filter(rm::isTakeable)
+ .toList()
+ .equals(List.of(fall));
+ final boolean hasUsedOps =
+ block.getCode().stream().anyMatch(op -> oum.isUsed(dfm.getJitOp(op)));
+ if (DEEP_TRACE) {
+ System.err.println(" gen: isFallOnlyWayToNext=%s".formatted(isFallOnlyWayToNext));
+ System.err.println(" gen: hasUsedOps=%s".formatted(hasUsedOps));
+ }
+ if (!(hasBranchInto && prev.wasEmpty) && isFallOnlyWayToNext && !hasUsedOps) {
+ System.err.println(
+ " gen: coalescing to next block (ops=%d)".formatted(block.getCode().size()));
+ return prev.emptyIncremented(block.getCode().size(), block);
+ }
+
+ PcodeOpCounter counter = new PcodeOpCounter();
+ counter.count(prev);
+ counter.count(block);
+
Emitter<Bot> em;
if (block.first() instanceof DecodedPcodeOp first &&
context.getConfiguration().emitCounters()) {
@@ -889,8 +1007,8 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
var tryCatch = Misc.tryCatch(live.em(), Lbl.create(), handler.lbl(), T_THROWABLE);
em = tryCatch.em()
.emit(Op::aload, localThis)
- .emit(Op::ldc__i, block.instructionCount())
- .emit(Op::ldc__i, block.trailingOpCount())
+ .emit(Op::ldc__i, counter.instructionCount())
+ .emit(Op::ldc__i, counter.trailingOpCount())
.emit(Op::invokeinterface, T_JIT_COMPILED_PASSAGE, "count",
MDESC_JIT_COMPILED_PASSAGE__COUNT)
.step(Inv::takeArg)
@@ -902,12 +1020,11 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
else {
em = live.em();
}
- return genBlockOps(em, localThis, localCtxmod, retReq, block, opIdx);
+ return genBlockOps(em, localThis, localCtxmod, retReq, block, prev.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.
*
@@ -918,6 +1035,9 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
*/
protected <N extends Next> Emitter<Ent<N, TRef<Address>>> genAddress(Emitter<N> em,
Address address) {
+ if (DEEP_TRACE) {
+ System.err.println(" // space=%s".formatted(address.getAddressSpace()));
+ }
if (address == Address.NO_ADDRESS) {
return em
.emit(Op::getstatic, T_ADDRESS, "NO_ADDRESS", T_ADDRESS);
@@ -941,7 +1061,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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:
*
@@ -951,11 +1070,12 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* ADDRESS_FACTORY.getAddressSpace(ramId).getAddress(0x400000), CTX_80000000));
* }
* </pre>
- *
* <p>
* Note this method will request the appropriate {@code CTX_...} field.
*
+ * @param em the emitter
* @param entry the entry point to add
+ * @return the same emitter
*/
protected Emitter<Bot> genStaticEntry(Emitter<Bot> em, AddrCtx entry) {
FieldForContext ctxField = requestStaticFieldForContext(entry.rvCtx);
@@ -979,11 +1099,13 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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.
+ *
+ * @param em the emitter
+ * @return the same emitter
*/
protected Emitter<Bot> genStaticEntries(Emitter<Bot> em) {
em = em
@@ -1011,7 +1133,7 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* requests are not known until the run-method generator has finished.
*
* @param em the emitter
- * @return the emitter
+ * @return the same emitter
*/
protected Emitter<Bot> genClInitMethod(Emitter<Bot> em) {
for (FieldForContext fCtx : fieldsForContext.values()) {
@@ -1039,6 +1161,10 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* 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.
+ *
+ * @param em the emitter
+ * @param localThis a handle to the local holding the {@code this} reference
+ * @return the same emitter
*/
protected Emitter<Bot> genInitMethod(Emitter<Bot> em, Local<TRef<THIS>> localThis) {
// NOTE: Ops don't need init. They'll invoke field requests as needed.
@@ -1069,7 +1195,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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
@@ -1084,9 +1209,15 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
* live, and then jump to the translation. Then, we emit the translation for each block using
* {@link #genBlock(OpResult, Local, Local, RetReq, JitBlock, int)}, placing transitions between
* those connected by fall through using
- * {@link VarGen#computeBlockTransition(Local, JitCodeGenerator, JitBlock, JitBlock)}. Finally,
- * we emit each requested exception handler using
+ * {@link VarGen#computeBlockTransition(Local, JitCodeGenerator, BlockFlow)}. Finally, we emit
+ * each requested exception handler using
* {@link ExceptionHandler#genRun(Emitter, Local, JitCodeGenerator)}.
+ *
+ * @param em the emitter
+ * @param localThis a handle to the local holding the {@code this} reference
+ * @param localBlockId a handle to the local holding {@code blockId}
+ * @param retReq the required return type
+ * @return the dead emitter
*/
protected Emitter<Dead> genRunMethod(Emitter<Bot> em, Local<TRef<THIS>> localThis,
Local<TInt> localBlockId, RetReq<TRef<EntryPoint>> retReq) {
@@ -1113,12 +1244,18 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
for (Map.Entry<JitBlock, Lbl<Bot>> ent : entries.entrySet()) {
JitBlock block = ent.getKey();
+ if (DEEP_TRACE) {
+ System.err.println(" gen: entry to %s".formatted(block.start()));
+ }
dead = dead
.emit(Lbl::placeDead, ent.getValue())
.emit(VarGen.computeBlockTransition(localThis, this, null, block)::genFwd)
.emit(Op::goto_, labelForBlock(block));
}
+ if (DEEP_TRACE) {
+ System.err.println(" gen: bad entry");
+ }
dead = dead
.emit(Lbl::placeDead, lblBadEntry)
.emit(Op::new_, T_ILLEGAL_ARGUMENT_EXCEPTION)
@@ -1134,45 +1271,78 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* NB. opIdx starts at 1, because JVM will ignore "Line number 0"
*/
- int opIdx = 1;
-
- OpResult opResult = new DeadOpResult(dead);
+ GenBlockResult prevResult = GenBlockResult.normal(1, new DeadOpResult(dead));
for (JitBlock block : cfm.getBlocks()) {
- var blockResult = genBlock(opResult, localThis, localCtxmod, retReq, block, opIdx);
- opIdx = blockResult.opIdx;
- JitBlock fall = block.getFallFrom();
+ if (DEEP_TRACE) {
+ System.err.println(" gen: block %s".formatted(block.start()));
+ System.err.println(" flows to:");
+ for (BlockFlow ft : block.flowsTo().values()) {
+ System.err
+ .println(" [%s] %s".formatted(rm.isTakeable(ft) ? "->" : "XX", ft));
+ }
+ AddrCtx entry = getOpEntry(block.first());
+ if (entry != null) {
+ System.err.println(" [en] %s".formatted(entry));
+ }
+ }
+ if (!rm.isReachable(block)) {
+ if (DEEP_TRACE) {
+ System.err
+ .println(" unreachable (ops=%d)".formatted(block.getCode().size()));
+ }
+ prevResult = prevResult.incremented(block.getCode().size());
+ continue;
+ }
+ var thisResult = genBlock(prevResult, localThis, localCtxmod, retReq, block);
+ BlockFlow fall = block.getFallFrom();
+
+ if (DEEP_TRACE) {
+ System.err.println(" flows from:");
+ for (BlockFlow ff : block.flowsFrom().values()) {
+ System.err
+ .println(" [%s] %s".formatted(rm.isTakeable(ff) ? "<-" : "XX", ff));
+ }
+ }
- if (fall == null) {
- if (!(blockResult.opResult instanceof DeadOpResult r)) {
+ if (fall == null || !rm.isTakeable(fall)) {
+ if (!(thisResult.opResult instanceof DeadOpResult)) {
throw new AssertionError("No fall-through, but control flow is live");
}
- opResult = r;
+ prevResult = thisResult;
+ }
+ else if (thisResult.wasEmpty) {
+ prevResult = thisResult;
}
else {
- opResult = switch (blockResult.opResult) {
- case LiveOpResult r -> new LiveOpResult(r.em()
- .emit(VarGen.computeBlockTransition(localThis, this, block,
- fall)::genFwd));
- case DeadOpResult r -> {
+ prevResult = switch (thisResult.opResult) {
+ case LiveOpResult r -> thisResult.aux(r.em()
+ .emit(VarGen.computeBlockTransition(localThis, this, fall)::genFwd));
+ case DeadOpResult _ -> {
/**
* This can happen, e.g., if an undefined userop is invoked. LATER: Perhaps
* have the control-flow analyzer consider this dead instead of
* fall-through?
+ *
+ * This can also happen now when a CBRANCH is re-written to a folded BRANCH.
*/
Msg.warn(this, "Fall-through block resulted in dead control flow.");
- yield r;
+ yield thisResult;
}
};
}
}
- if (!(opResult instanceof DeadOpResult r)) {
+ if (!(prevResult.opResult instanceof DeadOpResult r)) {
throw new AssertionError("Final block left live control flow");
}
dead = r.em();
+ int opIdx = prevResult.opIdx + 100; // Make a clear gap to indicate exception handlers
for (ExceptionHandler handler : excHandlers.values()) {
- dead = dead
- .emit(handler::genRun, localThis, this);
+ if (DEEP_TRACE) {
+ System.err.println(" gen: exceptiona handler %s".formatted(handler));
+ }
+ dead = dead.emit(handler::genRun, localThis, this, opIdx);
+ opIdx++;
}
return dead;
}
@@ -1209,7 +1379,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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
@@ -1228,6 +1397,9 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
Local<TRef<THIS>> this_;
Local<TInt> blockId;
};
+ if (DEEP_TRACE) {
+ System.err.println("Generate: run() {");
+ }
var retRun = Emitter.start(typeThis, cv, ACC_PUBLIC, "run",
MthDesc.returns(T_ENTRY_POINT).param(Types.T_INT).build())
.param(Def::param, Types.T_INT, "blockId", l -> paramsRun.blockId = l)
@@ -1235,6 +1407,9 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
retRun.em()
.emit(this::genRunMethod, paramsRun.this_, paramsRun.blockId, retRun.ret())
.emit(Misc::finish);
+ if (DEEP_TRACE) {
+ System.err.println("} // end run()");
+ }
// Run may make requests of Init and ClInit
var paramsInit = new Object() {
@@ -1282,7 +1457,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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.
@@ -1359,6 +1533,29 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
};
}
+ /**
+ * Create a generator that loads the program counter from a temporary local
+ * <p>
+ * This is used to verify a re-written indirect branch whose target constant became
+ * invalidated. In that case, the actual run-time target is loaded using {@link #loadTarget}
+ * and then stored into a temporary local. That target is compared to the now-invalidated
+ * constant target. If it matches, the direct internal branch is taken. Otherwise, we exit.
+ * LATER: If it happens that the target {@link JitVal} is allocated in a local, anyway, the
+ * temporary local is a bit redundant. It might be nice to avoid that.
+ *
+ * @param <THIS> the type of the generated passage
+ * @param local the local holding the program counter
+ * @return the generator
+ */
+ public static <THIS extends JitCompiledPassage> PcGen loadLocal(Local<TLong> local) {
+ return new PcGen() {
+ @Override
+ public <N extends Next> Emitter<Ent<N, TLong>> gen(Emitter<N> em) {
+ return em.emit(Op::lload, local);
+ }
+ };
+ }
+
/**
* Emit bytecode to load a program counter
*
@@ -1371,7 +1568,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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
@@ -1409,7 +1605,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* Emit code to exit the passage
- *
* <p>
* This retires all the variables of the current block as well as the program counter and decode
* context. It does not generate the actual {@link Opcodes#ARETURN areturn} or
@@ -1443,7 +1638,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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.
@@ -1460,7 +1654,6 @@ public class JitCodeGenerator<THIS extends JitCompiledPassage> {
/**
* 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.
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.java
index 4bb225858b..354a33b7eb 100644
--- 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.java
@@ -15,8 +15,9 @@
*/
package ghidra.pcode.emu.jit.gen.op;
-import ghidra.pcode.emu.jit.JitPassage.RIndBranch;
+import ghidra.pcode.emu.jit.JitPassage.*;
import ghidra.pcode.emu.jit.JitPcodeThread;
+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;
import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;
import ghidra.pcode.emu.jit.gen.GenConsts;
import ghidra.pcode.emu.jit.gen.JitCodeGenerator;
@@ -28,15 +29,14 @@ import ghidra.pcode.emu.jit.gen.util.*;
import ghidra.pcode.emu.jit.gen.util.Emitter.Bot;
import ghidra.pcode.emu.jit.gen.util.Emitter.Dead;
import ghidra.pcode.emu.jit.gen.util.Methods.RetReq;
-import ghidra.pcode.emu.jit.gen.util.Types.TInt;
-import ghidra.pcode.emu.jit.gen.util.Types.TRef;
+import ghidra.pcode.emu.jit.gen.util.Types.*;
+import ghidra.pcode.emu.jit.gen.var.VarGen;
import ghidra.pcode.emu.jit.op.JitBranchIndOp;
import ghidra.program.model.address.Address;
import ghidra.program.model.lang.RegisterValue;
/**
* 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
@@ -94,11 +94,90 @@ public enum BranchIndOpGen implements OpGen<JitBranchIndOp> {
}
}
+ /**
+ * A branch code generator for indirect branches which may be an internal branch
+ * <p>
+ * These occur when an indirect branch is folded to a direct branch during decode but later
+ * invalidated. The direct branch is preserved, but only taken when the run-time target happens
+ * to match the folded target.
+ */
+ static class MaybeIntBranchGen extends UBranchGen<RIntBranch, JitBranchIndOp> {
+ static final MaybeIntBranchGen MAYBE = new MaybeIntBranchGen();
+
+ @Override
+ Address exit(JitCodeGenerator<?> gen, RIntBranch branch) {
+ return IndBranchGen.IND.exit(gen, branch.toIndBranch());
+ }
+
+ @Override
+ <THIS extends JitCompiledPassage> Emitter<Dead> genRunWithoutCtxmod(Emitter<Bot> em,
+ Local<TRef<THIS>> localThis, RetReq<TRef<EntryPoint>> retReq,
+ JitCodeGenerator<THIS> gen, JitBranchIndOp op, RIntBranch branch, JitBlock block) {
+ RIndBranch indBranch = branch.toIndBranch();
+ Address intTarget = branch.to().getSeqnum().getTarget();
+ PcGen targetGen = PcGen.loadTarget(localThis, gen, op.target());
+ try (SubScope ss = em.rootScope().sub()) {
+ Local<TLong> localTarget = ss.decl(Types.T_LONG, "target");
+ PcGen missGen = PcGen.loadLocal(localTarget);
+ BlockFlow flow = block.flowsFrom().get(branch);
+ Lbl<Bot> intTargetLabel = gen.labelForBlock(flow.to());
+ var lblHit = em
+ .emit(targetGen::gen)
+ .emit(Op::lstore, localTarget)
+ .emit(Op::lload, localTarget)
+ .emit(Op::ldc__l, intTarget.getOffset())
+ .emit(Op::lcmp)
+ .emit(Op::ifeq);
+ return lblHit.em()
+ .emit(gen::genExit, localThis, block, missGen, indBranch.flowCtx())
+ .emit(Op::aconst_null, GenConsts.T_ENTRY_POINT)
+ .emit(Op::areturn, retReq)
+ .emit(Lbl::placeDead, lblHit.lbl())
+ .emit(VarGen.computeBlockTransition(localThis, gen, flow)::genFwd)
+ .emit(Op::goto_, intTargetLabel);
+ }
+ }
+
+ @Override
+ <THIS extends JitCompiledPassage> Emitter<Dead> genRunWithCtxmod(Emitter<Bot> em,
+ Local<TRef<THIS>> localThis, Local<TInt> localCtxmod,
+ RetReq<TRef<EntryPoint>> retReq, JitCodeGenerator<THIS> gen, JitBranchIndOp op,
+ Address exit, JitBlock block) {
+ return genExit(em, localThis, retReq, gen, op, null, block);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @implNote No need to check for folded target. DataFlow already did, and it would have
+ * substituted this {@link JitBranchIndOp} with something else. So, we know there's no
+ * folded target here.
+ * <p>
+ * As for Indirect-or-External branches, there's little or no benefit to encoding the
+ * run-time condition:
+ * <ol>
+ * <li>No internal block resulted from folding it. It remained in the queue of
+ * externals.</li>
+ * <li>The pseudo code is something like:
+ * <code> t = getTarget(); if (t == folded) goto folded; else goto t;</code></li>
+ * <li>While we might benefit from compile-time lookup of the exit slot, the run-time
+ * conditional check is still little or no improvement over the run-time hash-map
+ * lookup.</li>
+ * </ul>
+ */
@Override
public <THIS extends JitCompiledPassage> OpResult genRun(Emitter<Bot> em,
Local<TRef<THIS>> localThis, Local<TInt> localCtxmod, RetReq<TRef<EntryPoint>> retReq,
JitCodeGenerator<THIS> gen, JitBranchIndOp op, JitBlock block, Scope scope) {
- return new DeadOpResult(IndBranchGen.IND.genRun(
- em, localThis, localCtxmod, retReq, gen, op, op.branch(), block));
+ return new DeadOpResult(switch (op.branch()) {
+ case RIndBranch br -> IndBranchGen.IND.genRun(em, localThis, localCtxmod, retReq, gen,
+ op, br, block);
+ case RIntBranch br -> MaybeIntBranchGen.MAYBE.genRun(em, localThis, localCtxmod, retReq,
+ gen, op, br, block);
+ case RExtBranch br -> IndBranchGen.IND.genRun(em, localThis, localCtxmod, retReq, gen,
+ op, br.toIndBranch(), block);
+ default -> throw new AssertionError();
+ });
}
}
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.java
index a58202737c..dff9e76322 100644
--- 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.java
@@ -17,6 +17,7 @@ package ghidra.pcode.emu.jit.gen.op;
import ghidra.pcode.emu.jit.JitPassage.*;
import ghidra.pcode.emu.jit.JitPcodeThread;
+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;
import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;
import ghidra.pcode.emu.jit.gen.*;
import ghidra.pcode.emu.jit.gen.JitCodeGenerator.PcGen;
@@ -38,11 +39,9 @@ import ghidra.program.model.lang.RegisterValue;
/**
* 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 Op#goto_(Emitter) 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
@@ -70,7 +69,6 @@ public enum BranchOpGen implements OpGen<JitBranchOp> {
/**
* Generate code to retire the variables, write a given pc value, and return from the passage.
- *
* <p>
* This will not write any decode context.
*
@@ -108,7 +106,6 @@ public enum BranchOpGen implements OpGen<JitBranchOp> {
/**
* Generate code for the branch in the case a context modification has not occurred.
- *
* <p>
* This means <em>no</em> context-modifying userop has been invoked.
*
@@ -124,7 +121,6 @@ public enum BranchOpGen implements OpGen<JitBranchOp> {
/**
* Generate code for the branch in the case a context modification may have occurred.
- *
* <p>
* This means a context-modifying userop has <em>certainly</em> been invoked, but not
* necessarily that the context has actually changed.
@@ -217,10 +213,10 @@ public enum BranchOpGen implements OpGen<JitBranchOp> {
<THIS extends JitCompiledPassage> Emitter<Dead> genRunWithoutCtxmod(Emitter<Bot> em,
Local<TRef<THIS>> localThis, RetReq<TRef<EntryPoint>> retReq,
JitCodeGenerator<THIS> gen, JitOp op, RIntBranch branch, JitBlock block) {
- JitBlock target = block.getTargetBlock(branch);
- Lbl<Bot> label = gen.labelForBlock(target);
+ BlockFlow flow = block.flowsFrom().get(branch);
+ Lbl<Bot> label = gen.labelForBlock(flow.to());
return em
- .emit(VarGen.computeBlockTransition(localThis, gen, block, target)::genFwd)
+ .emit(VarGen.computeBlockTransition(localThis, gen, flow)::genFwd)
.emit(Op::goto_, label);
}
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.java
index a9aa4caf42..9e712f9834 100644
--- 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.java
@@ -16,6 +16,7 @@
package ghidra.pcode.emu.jit.gen.op;
import ghidra.pcode.emu.jit.JitPassage.*;
+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;
import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;
import ghidra.pcode.emu.jit.analysis.JitDataFlowModel;
import ghidra.pcode.emu.jit.gen.JitCodeGenerator;
@@ -37,17 +38,14 @@ import ghidra.program.model.pcode.PcodeOp;
/**
* 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 Op#ifeq(Emitter) ifeq} with the
* transition and {@link Op#goto_(Emitter) goto} it guards. The {@code ifeq} skips to the
* fall-through case. If a transition is not necessary, it simply emits an {@link Op#ifne(Emitter)
* ifne} to the target label.
- *
* <p>
* With an {@link ExtBranch} record, this does the same as {@link BranchOpGen} but guarded by an
* {@link Op#ifeq(Emitter) ifeq} that skips to the fall-through case.
@@ -62,13 +60,13 @@ public enum CBranchOpGen implements OpGen<JitCBranchOp> {
* @param <TB> the type of branch
* @param <TO> the type of op
*/
- abstract static class CBranchGen<TB extends RBranch, TO extends JitCBranchOp>
- extends BranchGen<Bot, Ent<Bot, TInt>, TB, TO> {
+ abstract static class CBranchGen<TB extends RBranch>
+ extends BranchGen<Bot, Ent<Bot, TInt>, TB, JitCBranchOp> {
@Override
<THIS extends JitCompiledPassage> Emitter<Bot> genRun(Emitter<Ent<Bot, TInt>> em,
Local<TRef<THIS>> localThis, Local<TInt> localCtxmod,
- RetReq<TRef<EntryPoint>> retReq, JitCodeGenerator<THIS> gen, TO op, TB branch,
- JitBlock block) {
+ RetReq<TRef<EntryPoint>> retReq, JitCodeGenerator<THIS> gen, JitCBranchOp op,
+ TB branch, JitBlock block) {
return switch (branch.reach()) {
case WITH_CTXMOD -> genRunWithCtxmod(em, localThis, localCtxmod, retReq, gen, op,
exit(gen, branch), block);
@@ -94,7 +92,7 @@ public enum CBranchOpGen implements OpGen<JitCBranchOp> {
/**
* A branch code generator for internal conditional branches
*/
- static class IntCBranchGen extends CBranchGen<RIntBranch, JitCBranchOp> {
+ static class IntCBranchGen extends CBranchGen<RIntBranch> {
/** Singleton */
static final IntCBranchGen C_INT = new IntCBranchGen();
@@ -108,10 +106,9 @@ public enum CBranchOpGen implements OpGen<JitCBranchOp> {
Emitter<Ent<Bot, TInt>> em, Local<TRef<THIS>> localThis,
RetReq<TRef<EntryPoint>> retReq, JitCodeGenerator<THIS> gen, JitCBranchOp op,
RIntBranch branch, JitBlock block) {
- JitBlock target = block.getTargetBlock(branch);
- Lbl<Bot> label = gen.labelForBlock(target);
- BlockTransition<THIS> transition =
- VarGen.computeBlockTransition(localThis, gen, block, target);
+ BlockFlow flow = block.flowsFrom().get(branch);
+ Lbl<Bot> label = gen.labelForBlock(flow.to());
+ BlockTransition<THIS> transition = VarGen.computeBlockTransition(localThis, gen, flow);
if (!transition.needed()) {
return em
@@ -142,7 +139,7 @@ public enum CBranchOpGen implements OpGen<JitCBranchOp> {
/**
* A branch code generator for external conditional branches
*/
- static class ExtCBranchGen extends CBranchGen<RExtBranch, JitCBranchOp> {
+ static class ExtCBranchGen extends CBranchGen<RExtBranch> {
/** Singleton */
static final ExtCBranchGen C_EXT = new ExtCBranchGen();
@@ -194,13 +191,16 @@ public enum CBranchOpGen implements OpGen<JitCBranchOp> {
* {@link JitDataFlowModel} recognizes this and uses {@link JitFailVal} for
* {@link JitCBranchOp#cond()}. The "fail" value asserts that it never gets generated,
* which will ensure we apply special handling here.
+ * @implNote No need to check for folded predicate. DataFlow already did, and it would have
+ * substituted this {@link JitCBranchOp} with something else. So, we know there's no
+ * folded predicate here.
*/
@Override
public <THIS extends JitCompiledPassage> LiveOpResult genRun(Emitter<Bot> em,
Local<TRef<THIS>> localThis, Local<TInt> localCtxmod, RetReq<TRef<EntryPoint>> retReq,
JitCodeGenerator<THIS> gen, JitCBranchOp op, JitBlock block, Scope scope) {
if (op.op() instanceof ExitPcodeOp && op.branch() instanceof RExtBranch eb) {
- assert eb.reach() == Reachability.MAYBE_CTXMOD;
+ assert eb.reach() == CtxReach.MAYBE_CTXMOD;
var lblFall = em
.emit(Op::iload, localCtxmod)
.emit(Op::ifeq);
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.java
index fc629cf6fb..d47c677b1e 100644
--- 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.java
@@ -43,6 +43,7 @@ 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.AnnotatedPcodeUseropLibrary.OpInput;
import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.OpOutput;
import ghidra.pcode.exec.PcodeUseropLibrary;
import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
@@ -101,8 +102,8 @@ public enum CallOtherOpGen implements OpGen<JitCallOtherOpIf> {
* @return the result of emitting the userop's bytecode
*/
public static <THIS extends JitCompiledPassage> OpResult genRunRetirementStrategy(
- Emitter<Bot> em, Local<TRef<THIS>> localThis, JitCodeGenerator<THIS> gen,
- PcodeOp op, JitBlock block, PcodeUseropDefinition<?> userop) {
+ Emitter<Bot> em, Local<TRef<THIS>> localThis, JitCodeGenerator<THIS> gen, PcodeOp op,
+ JitBlock block, PcodeUseropDefinition<?> userop) {
/**
* This is about the simplest (laziest) approach we could take, but it should suffice when
* we cannot invoke directly. We immediately retire all variables, then invoke the userop as
@@ -113,8 +114,7 @@ public enum CallOtherOpGen implements OpGen<JitCallOtherOpIf> {
* 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.
*/
- @SuppressWarnings({ "rawtypes", "unchecked" })
- FieldForUserop useropField = gen.requestFieldForUserop((PcodeUseropDefinition) userop);
+ FieldForUserop useropField = gen.requestFieldForUserop(userop);
FieldForPcodeOp opField = gen.requestStaticFieldForOp(op);
BlockTransition<THIS> transition =
@@ -183,16 +183,15 @@ public enum CallOtherOpGen implements OpGen<JitCallOtherOpIf> {
public static <THIS extends JitCompiledPassage, LIB extends PcodeUseropLibrary<?>> OpResult
genRunDirectStrategy(Emitter<Bot> em, Local<TRef<THIS>> localThis,
JitCodeGenerator<THIS> gen, JitCallOtherOpIf op, JitBlock block, Scope scope) {
- @SuppressWarnings({ "rawtypes", "unchecked" })
- FieldForUserop useropField = gen.requestFieldForUserop((PcodeUseropDefinition) op.userop());
+ PcodeUseropDefinition<?> userop = op.userop();
+ FieldForUserop useropField = gen.requestFieldForUserop(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.
*/
- Method method = op.userop().getJavaMethod();
+ Method method = userop.getJavaMethod();
Parameter[] parameters = method.getParameters();
Parameter outputParameter = findOutputParameter(parameters, method);
@@ -232,19 +231,22 @@ public enum CallOtherOpGen implements OpGen<JitCallOtherOpIf> {
var rec = new Object() {
<N extends Next> Emitter<? extends Ent<N, ?>> doReadArg(Emitter<N> em, JitVal arg,
Parameter param) {
+ OpInput annotation = param.getAnnotation(OpInput.class);
if (param.getType() == boolean.class) {
return gen.genReadToBool(em, localThis, arg);
}
if (param.getType() == int[].class) {
MpIntJitType t = MpIntJitType.forSize(arg.size());
- // TODO: Annotation/attribute to specify slack?
- return gen.genReadToArray(em, localThis, arg, t, Ext.ZERO, scope, 0);
+ int slack = annotation == null ? OpInput.DEFAULT_SLACK : annotation.slack();
+ return gen.genReadToArray(em, localThis, arg, t, Ext.ZERO, scope, slack);
}
+ boolean signed = annotation == null ? OpInput.DEFAULT_SIGNED : annotation.signed();
+ Ext ext = Ext.forSigned(signed);
return switch (JitType.forJavaType(param.getType())) {
- case IntJitType t -> gen.genReadToStack(em, localThis, arg, t, Ext.ZERO);
- case LongJitType t -> gen.genReadToStack(em, localThis, arg, t, Ext.ZERO);
- case FloatJitType t -> gen.genReadToStack(em, localThis, arg, t, Ext.ZERO);
- case DoubleJitType t -> gen.genReadToStack(em, localThis, arg, t, Ext.ZERO);
+ case IntJitType t -> gen.genReadToStack(em, localThis, arg, t, ext);
+ case LongJitType t -> gen.genReadToStack(em, localThis, arg, t, ext);
+ case FloatJitType t -> gen.genReadToStack(em, localThis, arg, t, ext);
+ case DoubleJitType t -> gen.genReadToStack(em, localThis, arg, t, ext);
default -> throw new AssertionError();
};
}
@@ -323,21 +325,20 @@ public enum CallOtherOpGen implements OpGen<JitCallOtherOpIf> {
em = inv
.step(Inv::retQVoid)
.emit(Op::aload, localOut)
- .emit(gen::genWriteFromArray, localThis, defOp.out(), outMpType, Ext.ZERO,
- scope);
+ .emit(gen::genWriteFromArray, localThis, defOp.out(), outMpType,
+ Ext.forSigned(userop.isOutSigned()), scope);
}
// Else there's either no @OpOutput or the output operand is absent
}
- else if (op instanceof JitCallOtherDefOp defOp) {
- // TODO: Can annotation specify signedness of return value?
+ else if (op instanceof JitCallOtherDefOp defOp && gen.getOpUseModel().isUsed(defOp.out())) {
var write = new Object() {
public <T extends BPrim<?>, JT extends SimpleJitType<T, JT>> Emitter<Bot> doWrite(
Inv<?, Bot, ?> inv, Class<?> returnType) {
JT type = SimpleJitType.forJavaType(returnType);
return inv
.step(Inv::retQ, type.bType())
- .emit(gen::genWriteFromStack, localThis, defOp.out(), type, Ext.ZERO,
- scope);
+ .emit(gen::genWriteFromStack, localThis, defOp.out(), type,
+ Ext.forSigned(userop.isOutSigned()), scope);
}
};
em = inv.step(write::doWrite, method.getReturnType());
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.java
index 8b55704931..1ed567ab30 100644
--- 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.java
@@ -39,7 +39,6 @@ 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
@@ -110,7 +109,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -126,7 +124,6 @@ public interface JitCompiledPassage {
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}.
@@ -140,7 +137,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -168,7 +164,6 @@ public interface JitCompiledPassage {
/**
* Get the entry point for this target
- *
* <p>
* This may cause the emulator to translate a new passage.
*
@@ -192,13 +187,11 @@ public interface JitCompiledPassage {
/**
* 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
@@ -214,7 +207,6 @@ public interface JitCompiledPassage {
/**
* Read an {@link IntJitType#I1 int1} from the given array at the given offset
- *
* <p>
* This is invoked by dynamically generated code.
*
@@ -228,7 +220,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -243,7 +234,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -259,7 +249,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -276,7 +265,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -291,7 +279,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -307,7 +294,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -324,7 +310,6 @@ public interface JitCompiledPassage {
/**
* Write an {@link IntJitType#I1 int1} into the given array at the given offset
- *
* <p>
* This is invoked by dynamically generated code.
*
@@ -338,7 +323,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -353,7 +337,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -369,7 +352,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -386,7 +368,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -401,7 +382,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -417,7 +397,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -434,7 +413,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -450,7 +428,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -467,7 +444,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -485,7 +461,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -504,7 +479,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -522,7 +496,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -541,7 +514,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -561,7 +533,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -582,7 +553,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -599,7 +569,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -617,7 +586,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -637,7 +605,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -656,7 +623,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -676,7 +642,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -697,7 +662,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -718,7 +682,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -734,7 +697,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -751,7 +713,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -769,7 +730,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -788,7 +748,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -806,7 +765,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -825,7 +783,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -845,7 +802,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -867,7 +823,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -885,7 +840,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -904,7 +858,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -924,7 +877,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -943,7 +895,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -963,7 +914,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -984,7 +934,6 @@ public interface JitCompiledPassage {
/**
* 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.
*
@@ -1005,7 +954,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -1021,7 +969,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1041,7 +988,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1090,7 +1036,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1110,7 +1055,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1231,7 +1175,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_LEFT int_left} on multi-precision 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.
@@ -1258,7 +1201,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_LEFT int_left} on an mp-int with a JVM long shift
* amount.
- *
* <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.
@@ -1279,7 +1221,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_LEFT int_left} on an mp-int with a JVM int shift
* amount.
- *
* <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.
@@ -1300,7 +1241,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_LEFT int_left} on a JVM long with an mp-int shift
* amount.
- *
* <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.
@@ -1323,7 +1263,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1341,7 +1280,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1360,7 +1298,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_LEFT int_left} on a JVM int with an mp-int shift
* amount.
- *
* <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.
@@ -1383,7 +1320,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1401,7 +1337,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1419,7 +1354,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_RIGHT int_right} on multi-precision 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.
@@ -1446,7 +1380,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_RIGHT int_right} on an mp-int with a JVM long shift
* amount.
- *
* <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.
@@ -1467,7 +1400,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_RIGHT int_right} on an mp-int with a JVM int shift
* amount.
- *
* <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.
@@ -1488,7 +1420,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_RIGHT int_right} on a JVM long with an mp-int shift
* amount.
- *
* <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.
@@ -1511,7 +1442,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1529,7 +1459,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1548,7 +1477,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_RIGHT int_right} on a JVM int with an mp-int shift
* amount.
- *
* <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.
@@ -1571,7 +1499,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1589,7 +1516,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -1607,7 +1533,6 @@ public interface JitCompiledPassage {
/**
* The implementation of {@link PcodeOp#INT_RIGHT int_sright} on multi-precision 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
@@ -1635,7 +1560,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -1654,7 +1578,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -1673,7 +1596,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -1692,7 +1614,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -2032,7 +1953,6 @@ public interface JitCompiledPassage {
/**
* Get the language for the given string language ID
- *
* <p>
* This is called by generated static initializers.
*
@@ -2046,7 +1966,6 @@ public interface JitCompiledPassage {
/**
* Construct a contextreg value from the given language and hex value
- *
* <p>
* This is called by generated static initializers to pre-construct context values.
*
@@ -2061,7 +1980,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -2092,7 +2010,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -2103,7 +2020,6 @@ public interface JitCompiledPassage {
/**
* Set the bound thread's program counter and decode context.
- *
* <p>
* This is called during retirement, i.e., upon exiting a passage. This just converts things to
* the right type and invokes
@@ -2121,7 +2037,6 @@ public interface JitCompiledPassage {
/**
* Set the bound thread's program counter and decode context, without writing it to the machine
* state.
- *
* <p>
* This is called during retirement upon entering a hazard. This just converts things to the
* right type and invokes {@link JitPcodeThread#setCounterAndContext(Address, RegisterValue)}.
@@ -2137,13 +2052,12 @@ public interface JitCompiledPassage {
/**
* 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, PcodeOp)}, or its
- * method and instance may be extracted and saved for Direct invocation later.
+ * later used with {@link #invokeUserop(PcodeUseropDefinition, PcodeOp)}, 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}
@@ -2155,7 +2069,6 @@ public interface JitCompiledPassage {
/**
* 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.
@@ -2171,7 +2084,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -2189,7 +2101,6 @@ public interface JitCompiledPassage {
/**
* 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
@@ -2205,7 +2116,6 @@ public interface JitCompiledPassage {
/**
* 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
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.java
index b5f7ed89f7..64fd9d0989 100644
--- 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.java
@@ -27,7 +27,6 @@ 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
@@ -35,7 +34,6 @@ import ghidra.pcode.emu.jit.gen.tgt.JitCompiledPassage.EntryPointPrototype;
* 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
@@ -57,7 +55,6 @@ public record JitCompiledPassageClass(Lookup lookup, Class<? extends JitCompiled
/**
* 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
@@ -99,7 +96,6 @@ public record JitCompiledPassageClass(Lookup lookup, Class<? extends JitCompiled
/**
* 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
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Lbl.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Lbl.java
index c196a218e9..4503c7051c 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Lbl.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Lbl.java
@@ -17,6 +17,7 @@ package ghidra.pcode.emu.jit.gen.util;
import org.objectweb.asm.Label;
+import ghidra.pcode.emu.jit.JitCompiler.Diag;
import ghidra.pcode.emu.jit.gen.util.Emitter.Dead;
import ghidra.pcode.emu.jit.gen.util.Emitter.Next;
import ghidra.pcode.emu.jit.gen.util.Methods.RetReq;
@@ -102,9 +103,23 @@ import ghidra.pcode.emu.jit.gen.util.Methods.RetReq;
* not currently have a solution to that complaint.
*
* @param <N> the stack contents where the label is placed (or must be placed)
+ * @param id if {@link Diag#DEEP_TRACE} is enabled, a globally-unique 0-up counter, or -1
* @param label the wrapped ASM label
*/
-public record Lbl<N extends Next>(Label label) {
+public record Lbl<N extends Next>(int id, Label label) {
+ static int nextId = 0; // for diagnostics only
+
+ public Lbl(Label label) {
+ final int id;
+ if (Op.DEEP_TRACE) {
+ id = nextId++;
+ }
+ else {
+ id = -1;
+ }
+ this(id, label);
+ }
+
/**
* A tuple providing both a (new) label and a resulting emitter
*
@@ -143,6 +158,9 @@ public record Lbl<N extends Next>(Label label) {
*/
public static <N extends Next> LblEm<N, N> place(Emitter<N> em) {
Lbl<N> lbl = create();
+ if (Op.DEEP_TRACE) {
+ System.err.println(" jvm<%s>".formatted(lbl));
+ }
em.mv.visitLabel(lbl.label);
return new LblEm<>(lbl, em);
}
@@ -159,6 +177,9 @@ public record Lbl<N extends Next>(Label label) {
* @return the same emitter
*/
public static <N extends Next> Emitter<N> place(Emitter<N> em, Lbl<N> lbl) {
+ if (Op.DEEP_TRACE) {
+ System.err.println(" jvm<%s>".formatted(lbl));
+ }
em.mv.visitLabel(lbl.label);
return em;
}
@@ -180,6 +201,9 @@ public record Lbl<N extends Next>(Label label) {
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <N extends Next> Emitter<N> placeDead(Emitter<Dead> em, Lbl<N> lbl) {
+ if (Op.DEEP_TRACE) {
+ System.err.println(" jvm<%s>".formatted(lbl));
+ }
em.mv.visitLabel(lbl.label);
return (Emitter) em;
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Misc.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Misc.java
index 495bc07c8a..1b5685e63f 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Misc.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Misc.java
@@ -88,6 +88,10 @@ public interface Misc {
Lbl<N> end, Lbl<Ent<N, TRef<T>>> handler, TRef<T> type) {
Lbl<N> start = Lbl.create();
em = em.emit(Lbl::place, start);
+ if (Op.DEEP_TRACE) {
+ System.err.println(
+ " jvm<try-catch> %s handler=%s, end=%s".formatted(type, handler, end));
+ }
em.mv.visitTryCatchBlock(start.label(), end.label(), handler.label(),
type.internalName());
return new TryCatchBlock<>(end, handler, em);
@@ -103,6 +107,9 @@ public interface Misc {
*/
static <N extends Next> Emitter<N> lineNumber(Emitter<N> em, int number) {
Label label = new Label();
+ if (Op.DEEP_TRACE) {
+ System.err.println(" jvm<Line %d>".formatted(number));
+ }
em.mv.visitLabel(label);
em.mv.visitLineNumber(number, label);
return em;
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Op.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Op.java
index 33e0ce74f2..608376e688 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Op.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/gen/util/Op.java
@@ -17,10 +17,13 @@ package ghidra.pcode.emu.jit.gen.util;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.function.Function;
import org.objectweb.asm.*;
+import ghidra.pcode.emu.jit.JitCompiler;
+import ghidra.pcode.emu.jit.JitCompiler.Diag;
import ghidra.pcode.emu.jit.gen.util.Emitter.*;
import ghidra.pcode.emu.jit.gen.util.Lbl.LblEm;
import ghidra.pcode.emu.jit.gen.util.Methods.*;
@@ -51,6 +54,7 @@ import ghidra.pcode.emu.jit.gen.util.Types.*;
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public interface Op {
+ boolean DEEP_TRACE = JitCompiler.ENABLE_DIAGNOSTICS.contains(Diag.DEEP_TRACE);
/**
* Emit an {@code aaload} instruction
@@ -67,7 +71,10 @@ public interface Op {
N1 extends Ent<N2, TRef<ET[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TRef<ET>>> aaload(Emitter<N0> em) {
- em.mv.visitInsn(Opcodes.AASTORE);
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: aaload");
+ }
+ em.mv.visitInsn(Opcodes.AALOAD);
return (Emitter) em;
}
@@ -88,6 +95,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, ? extends TRef<? extends ET>>>
Emitter<N3> aastore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: aastore");
+ }
em.mv.visitInsn(Opcodes.AASTORE);
return (Emitter) em;
}
@@ -104,6 +114,9 @@ public interface Op {
static <T extends TRef<?>,
N extends Next>
Emitter<Ent<N, T>> aconst_null(Emitter<N> em, T type) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: aconst_null %s".formatted(type));
+ }
em.mv.visitInsn(Opcodes.ACONST_NULL);
return (Emitter) em;
}
@@ -120,6 +133,9 @@ public interface Op {
static <T extends TRef<?>,
N extends Next>
Emitter<Ent<N, T>> aload(Emitter<N> em, Local<T> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: aload %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.ALOAD, local.index());
return (Emitter) em;
}
@@ -138,6 +154,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TRef<ET[]>>> anewarray(Emitter<N0> em, TRef<ET> elemType) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: anewarray %s".formatted(elemType));
+ }
em.mv.visitTypeInsn(Opcodes.ANEWARRAY, elemType.internalName());
return (Emitter) em;
}
@@ -157,6 +176,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, ? extends TRef<TR>>>
Emitter<Dead> areturn(Emitter<N0> em, RetReq<? extends TRef<TL>> retReq) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: areturn %s".formatted(retReq));
+ }
em.mv.visitInsn(Opcodes.ARETURN);
return (Emitter) em;
}
@@ -175,6 +197,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TRef<AT>>>
Emitter<Ent<N1, TInt>> arraylength__prim(Emitter<N0> em, ET elemType) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: arraylength %s".formatted(elemType));
+ }
em.mv.visitInsn(Opcodes.ARRAYLENGTH);
return (Emitter) em;
}
@@ -192,6 +217,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TRef<ET[]>>>
Emitter<Ent<N1, TInt>> arraylength__ref(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: arraylength");
+ }
em.mv.visitInsn(Opcodes.ARRAYLENGTH);
return (Emitter) em;
}
@@ -211,6 +239,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, ? extends TRef<TR>>>
Emitter<N1> astore(Emitter<N0> em, Local<? extends TRef<TL>> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: astore %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.ASTORE, local.index());
return (Emitter) em;
}
@@ -228,6 +259,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, T1>>
Emitter<Dead> athrow(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: athrow");
+ }
em.mv.visitInsn(Opcodes.ATHROW);
return (Emitter) em;
}
@@ -246,6 +280,9 @@ public interface Op {
N1 extends Ent<N2, TRef<boolean[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> baload__boolean(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: baload");
+ }
em.mv.visitInsn(Opcodes.BALOAD);
return (Emitter) em;
}
@@ -264,6 +301,9 @@ public interface Op {
N1 extends Ent<N2, TRef<byte[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> baload(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: baload");
+ }
em.mv.visitInsn(Opcodes.BALOAD);
return (Emitter) em;
}
@@ -284,6 +324,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N3> bastore__boolean(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: bastore");
+ }
em.mv.visitInsn(Opcodes.BASTORE);
return (Emitter) em;
}
@@ -304,6 +347,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N3> bastore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: bastore");
+ }
em.mv.visitInsn(Opcodes.BASTORE);
return (Emitter) em;
}
@@ -322,6 +368,9 @@ public interface Op {
N1 extends Ent<N2, TRef<char[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> caload(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: caload");
+ }
em.mv.visitInsn(Opcodes.CALOAD);
return (Emitter) em;
}
@@ -342,6 +391,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N3> castore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: castore");
+ }
em.mv.visitInsn(Opcodes.CASTORE);
return (Emitter) em;
}
@@ -362,6 +414,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, T1>>
Emitter<Ent<N1, TRef<CT>>> checkcast(Emitter<N0> em, TRef<CT> type) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: checkcast %s".formatted(type));
+ }
em.mv.visitTypeInsn(Opcodes.CHECKCAST, type.internalName());
return (Emitter) em;
}
@@ -378,6 +433,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N1, TFloat>> d2f(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: d2f");
+ }
em.mv.visitInsn(Opcodes.D2F);
return (Emitter) em;
}
@@ -394,6 +452,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N1, TInt>> d2i(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: d2i");
+ }
em.mv.visitInsn(Opcodes.D2I);
return (Emitter) em;
}
@@ -410,6 +471,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N1, TLong>> d2l(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: d2l");
+ }
em.mv.visitInsn(Opcodes.D2L);
return (Emitter) em;
}
@@ -428,6 +492,9 @@ public interface Op {
N1 extends Ent<N2, TDouble>,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N2, TDouble>> dadd(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dadd");
+ }
em.mv.visitInsn(Opcodes.DADD);
return (Emitter) em;
}
@@ -446,6 +513,9 @@ public interface Op {
N1 extends Ent<N2, TRef<double[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TDouble>> daload(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: daload");
+ }
em.mv.visitInsn(Opcodes.DALOAD);
return (Emitter) em;
}
@@ -466,6 +536,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TDouble>>
Emitter<N3> dastore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dastore");
+ }
em.mv.visitInsn(Opcodes.DASTORE);
return (Emitter) em;
}
@@ -484,6 +557,9 @@ public interface Op {
N1 extends Ent<N2, TDouble>,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N2, TInt>> dcmpg(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dcmpg");
+ }
em.mv.visitInsn(Opcodes.DCMPG);
return (Emitter) em;
}
@@ -502,6 +578,9 @@ public interface Op {
N1 extends Ent<N2, TDouble>,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N2, TInt>> dcmpl(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dcmpl");
+ }
em.mv.visitInsn(Opcodes.DCMPL);
return (Emitter) em;
}
@@ -520,6 +599,9 @@ public interface Op {
N1 extends Ent<N2, TDouble>,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N2, TDouble>> ddiv(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ddiv");
+ }
em.mv.visitInsn(Opcodes.DDIV);
return (Emitter) em;
}
@@ -534,6 +616,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TDouble>> dload(Emitter<N> em, Local<TDouble> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dload %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.DLOAD, local.index());
return (Emitter) em;
}
@@ -552,6 +637,9 @@ public interface Op {
N1 extends Ent<N2, TDouble>,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N2, TDouble>> dmul(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dmul");
+ }
em.mv.visitInsn(Opcodes.DMUL);
return (Emitter) em;
}
@@ -568,6 +656,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N1, TDouble>> dneg(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dneg");
+ }
em.mv.visitInsn(Opcodes.DNEG);
return (Emitter) em;
}
@@ -586,6 +677,9 @@ public interface Op {
N1 extends Ent<N2, TDouble>,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N2, TDouble>> drem(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: drem");
+ }
em.mv.visitInsn(Opcodes.DREM);
return (Emitter) em;
}
@@ -603,6 +697,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TDouble>>
Emitter<Dead> dreturn(Emitter<N0> em, RetReq<TDouble> retReq) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dreturn %s".formatted(retReq));
+ }
em.mv.visitInsn(Opcodes.DRETURN);
return (Emitter) em;
}
@@ -620,6 +717,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TDouble>>
Emitter<N1> dstore(Emitter<N0> em, Local<TDouble> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dstore %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.DSTORE, local.index());
return (Emitter) em;
}
@@ -638,6 +738,9 @@ public interface Op {
N1 extends Ent<N2, TDouble>,
N0 extends Ent<N1, TDouble>>
Emitter<Ent<N2, TDouble>> dsub(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dsub");
+ }
em.mv.visitInsn(Opcodes.DSUB);
return (Emitter) em;
}
@@ -655,6 +758,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, V1>>
Emitter<Ent<N0, V1>> dup(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup");
+ }
em.mv.visitInsn(Opcodes.DUP);
return (Emitter) em;
}
@@ -675,6 +781,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<N2, V1>, V2>, V1>> dup_x1(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup_x1");
+ }
em.mv.visitInsn(Opcodes.DUP_X1);
return (Emitter) em;
}
@@ -698,6 +807,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<Ent<N3, V1>, V3>, V2>, V1>> dup_x2__111(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup_x2 (111)");
+ }
em.mv.visitInsn(Opcodes.DUP_X2);
return (Emitter) em;
}
@@ -718,6 +830,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<N2, V1>, V2>, V1>> dup_x2__21(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup_x2 (21)");
+ }
em.mv.visitInsn(Opcodes.DUP_X2);
return (Emitter) em;
}
@@ -738,6 +853,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<N0, V2>, V1>> dup2__11(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2 (11)");
+ }
em.mv.visitInsn(Opcodes.DUP2);
return (Emitter) em;
}
@@ -755,6 +873,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, V1>>
Emitter<Ent<N0, V1>> dup2__2(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2 (2)");
+ }
em.mv.visitInsn(Opcodes.DUP2);
return (Emitter) em;
}
@@ -779,6 +900,9 @@ public interface Op {
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<Ent<Ent<N3, V2>, V1>, V3>, V2>, V1>> dup2_x1__111(Emitter<N0> em) {
em.mv.visitInsn(Opcodes.DUP2_X1);
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2_x1 (111)");
+ }
return (Emitter) em;
}
@@ -798,6 +922,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<N2, V1>, V2>, V1>> dup2_x1__12(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2_x1 (12)");
+ }
em.mv.visitInsn(Opcodes.DUP2_X1);
return (Emitter) em;
}
@@ -826,6 +953,9 @@ public interface Op {
Emitter<Ent<Ent<Ent<Ent<Ent<Ent<N4, V2>, V1>, V4>, V3>, V2>, V1>>
dup2_x2_1111(Emitter<N0> em) {
em.mv.visitInsn(Opcodes.DUP2_X2);
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2_x2 (1111)");
+ }
return (Emitter) em;
}
@@ -848,6 +978,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<Ent<N3, V1>, V3>, V2>, V1>> dup2_x2_112(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2_x2 (112)");
+ }
em.mv.visitInsn(Opcodes.DUP2_X2);
return (Emitter) em;
}
@@ -871,6 +1004,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<Ent<Ent<N3, V2>, V1>, V3>, V2>, V1>> dup2_x2_211(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2_x2 (211)");
+ }
em.mv.visitInsn(Opcodes.DUP2_X2);
return (Emitter) em;
}
@@ -891,6 +1027,9 @@ public interface Op {
N1 extends Ent<N2, V2>,
N0 extends Ent<N1, V1>>
Emitter<Ent<Ent<Ent<N2, V1>, V2>, V1>> dup2_x2_22(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: dup2_x2 (22)");
+ }
em.mv.visitInsn(Opcodes.DUP2_X2);
return (Emitter) em;
}
@@ -907,6 +1046,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N1, TDouble>> f2d(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: f2d");
+ }
em.mv.visitInsn(Opcodes.F2D);
return (Emitter) em;
}
@@ -923,6 +1065,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N1, TInt>> f2i(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: f2i");
+ }
em.mv.visitInsn(Opcodes.F2I);
return (Emitter) em;
}
@@ -939,6 +1084,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N1, TLong>> f2l(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: f2l");
+ }
em.mv.visitInsn(Opcodes.F2L);
return (Emitter) em;
}
@@ -957,6 +1105,9 @@ public interface Op {
N1 extends Ent<N2, TFloat>,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N2, TFloat>> fadd(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fadd");
+ }
em.mv.visitInsn(Opcodes.FADD);
return (Emitter) em;
}
@@ -975,6 +1126,9 @@ public interface Op {
N1 extends Ent<N2, TRef<float[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TFloat>> faload(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: faload");
+ }
em.mv.visitInsn(Opcodes.FALOAD);
return (Emitter) em;
}
@@ -995,6 +1149,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TFloat>>
Emitter<N3> fastore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fastore");
+ }
em.mv.visitInsn(Opcodes.FASTORE);
return (Emitter) em;
}
@@ -1013,6 +1170,9 @@ public interface Op {
N1 extends Ent<N2, TFloat>,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N2, TInt>> fcmpg(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fcmpg");
+ }
em.mv.visitInsn(Opcodes.FCMPG);
return (Emitter) em;
}
@@ -1031,6 +1191,9 @@ public interface Op {
N1 extends Ent<N2, TFloat>,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N2, TInt>> fcmpl(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fcmpl");
+ }
em.mv.visitInsn(Opcodes.FCMPL);
return (Emitter) em;
}
@@ -1049,6 +1212,9 @@ public interface Op {
N1 extends Ent<N2, TFloat>,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N2, TFloat>> fdiv(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fdiv");
+ }
em.mv.visitInsn(Opcodes.FDIV);
return (Emitter) em;
}
@@ -1063,6 +1229,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TFloat>> fload(Emitter<N> em, Local<TFloat> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fload %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.FLOAD, local.index());
return (Emitter) em;
}
@@ -1081,6 +1250,9 @@ public interface Op {
N1 extends Ent<N2, TFloat>,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N2, TFloat>> fmul(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fmul");
+ }
em.mv.visitInsn(Opcodes.FMUL);
return (Emitter) em;
}
@@ -1097,6 +1269,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N1, TFloat>> fneg(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fneg");
+ }
em.mv.visitInsn(Opcodes.FNEG);
return (Emitter) em;
}
@@ -1115,6 +1290,9 @@ public interface Op {
N1 extends Ent<N2, TFloat>,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N2, TFloat>> frem(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: frem");
+ }
em.mv.visitInsn(Opcodes.FREM);
return (Emitter) em;
}
@@ -1132,6 +1310,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TFloat>>
Emitter<Dead> freturn(Emitter<N0> em, RetReq<TFloat> retReq) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: freturn %s".formatted(retReq));
+ }
em.mv.visitInsn(Opcodes.FRETURN);
return (Emitter) em;
}
@@ -1149,6 +1330,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TFloat>>
Emitter<N1> fstore(Emitter<N0> em, Local<TFloat> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fstore %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.FSTORE, local.index());
return (Emitter) em;
}
@@ -1167,6 +1351,9 @@ public interface Op {
N1 extends Ent<N2, TFloat>,
N0 extends Ent<N1, TFloat>>
Emitter<Ent<N2, TFloat>> fsub(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: fsub");
+ }
em.mv.visitInsn(Opcodes.FSUB);
return (Emitter) em;
}
@@ -1193,6 +1380,12 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, T1>>
Emitter<Ent<N1, FT>> getfield(Emitter<N0> em, TRef<OT> owner, String name, FT type) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: getfield %s %s
+ .%s""".formatted(type, owner, name));
+ }
em.mv.visitFieldInsn(Opcodes.GETFIELD, owner.type().getInternalName(), name,
type.type().getDescriptor());
return (Emitter) em;
@@ -1214,6 +1407,12 @@ public interface Op {
static <FT extends BNonVoid,
N extends Next>
Emitter<Ent<N, FT>> getstatic(Emitter<N> em, TRef<?> owner, String name, FT type) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: getstatic %s %s
+ .%s""".formatted(type, owner, name));
+ }
em.mv.visitFieldInsn(Opcodes.GETSTATIC, owner.type().getInternalName(), name,
type.type().getDescriptor());
return (Emitter) em;
@@ -1229,6 +1428,9 @@ public interface Op {
static <N extends Next>
LblEm<N, Dead> goto_(Emitter<N> em) {
Lbl<N> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: goto %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.GOTO, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1243,6 +1445,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Dead> goto_(Emitter<N> em, Lbl<N> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: goto %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.GOTO, target.label());
return (Emitter) em;
}
@@ -1259,6 +1464,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TInt>> i2b(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: i2b");
+ }
em.mv.visitInsn(Opcodes.I2B);
return (Emitter) em;
}
@@ -1275,6 +1483,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TInt>> i2c(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: i2c");
+ }
em.mv.visitInsn(Opcodes.I2C);
return (Emitter) em;
}
@@ -1291,6 +1502,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TDouble>> i2d(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: i2d");
+ }
em.mv.visitInsn(Opcodes.I2D);
return (Emitter) em;
}
@@ -1307,6 +1521,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TFloat>> i2f(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: i2f");
+ }
em.mv.visitInsn(Opcodes.I2F);
return (Emitter) em;
}
@@ -1323,6 +1540,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TLong>> i2l(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: i2l");
+ }
em.mv.visitInsn(Opcodes.I2L);
return (Emitter) em;
}
@@ -1339,6 +1559,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TInt>> i2s(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: i2s");
+ }
em.mv.visitInsn(Opcodes.I2S);
return (Emitter) em;
}
@@ -1357,6 +1580,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> iadd(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iadd");
+ }
em.mv.visitInsn(Opcodes.IADD);
return (Emitter) em;
}
@@ -1375,6 +1601,9 @@ public interface Op {
N1 extends Ent<N2, TRef<int[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> iaload(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iaload");
+ }
em.mv.visitInsn(Opcodes.IALOAD);
return (Emitter) em;
}
@@ -1393,6 +1622,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> iand(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iand");
+ }
em.mv.visitInsn(Opcodes.IAND);
return (Emitter) em;
}
@@ -1413,6 +1645,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N3> iastore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iastore");
+ }
em.mv.visitInsn(Opcodes.IASTORE);
return (Emitter) em;
}
@@ -1431,6 +1666,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> idiv(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: idiv");
+ }
em.mv.visitInsn(Opcodes.IDIV);
return (Emitter) em;
}
@@ -1450,6 +1688,9 @@ public interface Op {
N0 extends Ent<N1, TRef<?>>>
LblEm<N2, N2> if_acmpeq(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_acmpeq %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ACMPEQ, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1469,6 +1710,9 @@ public interface Op {
N1 extends Ent<N2, TRef<?>>,
N0 extends Ent<N1, TRef<?>>>
Emitter<N2> if_acmpeq(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_acmpeq %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ACMPEQ, target.label());
return (Emitter) em;
}
@@ -1488,6 +1732,9 @@ public interface Op {
N0 extends Ent<N1, TRef<?>>>
LblEm<N2, N2> if_acmpne(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_acmpne %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ACMPNE, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1507,6 +1754,9 @@ public interface Op {
N1 extends Ent<N2, TRef<?>>,
N0 extends Ent<N1, TRef<?>>>
Emitter<N2> if_acmpne(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_acmpne %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ACMPNE, target.label());
return (Emitter) em;
}
@@ -1526,6 +1776,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N2, N2> if_icmpeq(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpeq %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPEQ, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1545,6 +1798,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N2> if_icmpeq(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpeq %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPEQ, target.label());
return (Emitter) em;
}
@@ -1564,6 +1820,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N2, N2> if_icmpge(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpge %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPGE, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1583,6 +1842,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N2> if_icmpge(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpge %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPGE, target.label());
return (Emitter) em;
}
@@ -1602,6 +1864,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N2, N2> if_icmpgt(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpgt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPGT, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1621,6 +1886,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N2> if_icmpgt(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpgt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPGT, target.label());
return (Emitter) em;
}
@@ -1640,6 +1908,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N2, N2> if_icmple(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmple %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPLE, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1659,6 +1930,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N2> if_icmple(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmple %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPLE, target.label());
return (Emitter) em;
}
@@ -1678,6 +1952,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N2, N2> if_icmplt(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmplt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPLT, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1697,6 +1974,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N2> if_icmplt(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmplt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPLT, target.label());
return (Emitter) em;
}
@@ -1716,6 +1996,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N2, N2> if_icmpne(Emitter<N0> em) {
Lbl<N2> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpne %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPNE, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1735,6 +2018,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N2> if_icmpne(Emitter<N0> em, Lbl<N2> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: if_icmpne %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IF_ICMPNE, target.label());
return (Emitter) em;
}
@@ -1752,6 +2038,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N1, N1> ifeq(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifeq %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFEQ, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1769,6 +2058,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<N1> ifeq(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifeq %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFEQ, target.label());
return (Emitter) em;
}
@@ -1786,6 +2078,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N1, N1> ifge(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifge %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFGE, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1803,6 +2098,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<N1> ifge(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifge %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFGE, target.label());
return (Emitter) em;
}
@@ -1820,6 +2118,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N1, N1> ifgt(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifgt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFGT, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1837,6 +2138,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<N1> ifgt(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifgt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFGT, target.label());
return (Emitter) em;
}
@@ -1854,6 +2158,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N1, N1> ifle(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifle %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFLE, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1871,6 +2178,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<N1> ifle(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifle %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFLE, target.label());
return (Emitter) em;
}
@@ -1888,6 +2198,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N1, N1> iflt(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iflt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFLT, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1905,6 +2218,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<N1> iflt(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iflt %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFLT, target.label());
return (Emitter) em;
}
@@ -1922,6 +2238,9 @@ public interface Op {
N0 extends Ent<N1, TInt>>
LblEm<N1, N1> ifne(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifne %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFNE, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1939,6 +2258,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<N1> ifne(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifne %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFNE, target.label());
return (Emitter) em;
}
@@ -1956,6 +2278,9 @@ public interface Op {
N0 extends Ent<N1, TRef<?>>>
LblEm<N1, N1> ifnonnull(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifnonnull %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFNONNULL, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -1973,6 +2298,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TRef<?>>>
Emitter<N1> ifnonnull(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifnonnull %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFNONNULL, target.label());
return (Emitter) em;
}
@@ -1990,6 +2318,9 @@ public interface Op {
N0 extends Ent<N1, TRef<?>>>
LblEm<N1, N1> ifnull(Emitter<N0> em) {
Lbl<N1> target = Lbl.create();
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifnull %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFNULL, target.label());
return new LblEm<>(target, (Emitter) em);
}
@@ -2007,6 +2338,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TRef<?>>>
Emitter<N1> ifnull(Emitter<N0> em, Lbl<N1> target) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ifnull %s".formatted(target));
+ }
em.mv.visitJumpInsn(Opcodes.IFNULL, target.label());
return (Emitter) em;
}
@@ -2022,6 +2356,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<N> iinc(Emitter<N> em, Local<TInt> local, int increment) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iinc %s %d".formatted(local, increment));
+ }
em.mv.visitIincInsn(local.index(), increment);
return em;
}
@@ -2036,6 +2373,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TInt>> iload(Emitter<N> em, Local<TInt> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iload %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.ILOAD, local.index());
return (Emitter) em;
}
@@ -2054,6 +2394,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> imul(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: imul");
+ }
em.mv.visitInsn(Opcodes.IMUL);
return (Emitter) em;
}
@@ -2070,6 +2413,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TInt>> ineg(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ineg");
+ }
em.mv.visitInsn(Opcodes.INEG);
return (Emitter) em;
}
@@ -2087,6 +2433,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TRef<?>>>
Emitter<Ent<N1, TInt>> instanceof_(Emitter<N0> em, TRef<?> type) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: instanceof %s".formatted(type));
+ }
em.mv.visitTypeInsn(Opcodes.INSTANCEOF, type.internalName());
return (Emitter) em;
}
@@ -2119,6 +2468,12 @@ public interface Op {
Inv<MR, SN, MN> invokedynamic__unsupported(Emitter<SN> em, String name,
MthDesc<MR, MN> desc, Handle bootstrapMethodHandle,
Object... bootstrapMethodArguments) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: invokedynamic %s %s %s %s""".formatted(name, desc,
+ bootstrapMethodHandle, bootstrapMethodArguments));
+ }
em.mv.visitInvokeDynamicInsn(name, desc.desc(), bootstrapMethodHandle,
bootstrapMethodArguments);
return new Inv<>(em);
@@ -2143,6 +2498,12 @@ public interface Op {
MR extends BType>
ObjInv<MR, OT, SN, MN>
invokeinterface(Emitter<SN> em, TRef<OT> ownerType, String name, MthDesc<MR, MN> desc) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: invokeinterface %s
+ .%s %s""".formatted(ownerType, name, desc));
+ }
em.mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, ownerType.internalName(),
name,
desc.desc(), true);
@@ -2169,6 +2530,13 @@ public interface Op {
MR extends BType>
ObjInv<MR, OT, SN, MN> invokespecial(Emitter<SN> em, TRef<OT> ownerType, String name,
MthDesc<MR, MN> desc, boolean isInterface) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: invokespecial %s
+ .%s %s (%s)""".formatted(ownerType, name, desc,
+ isInterface ? "interface" : "class"));
+ }
em.mv.visitMethodInsn(Opcodes.INVOKESPECIAL, ownerType.internalName(), name,
desc.desc(), isInterface);
return new ObjInv<>(em);
@@ -2193,6 +2561,13 @@ public interface Op {
MR extends BType>
Inv<MR, SN, MN> invokestatic(Emitter<SN> em, TRef<?> ownerType, String name,
MthDesc<MR, MN> desc, boolean isInterface) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: invokestatic %s
+ .%s %s (%s)""".formatted(ownerType, name, desc,
+ isInterface ? "interface" : "class"));
+ }
em.mv.visitMethodInsn(Opcodes.INVOKESTATIC, ownerType.internalName(), name,
desc.desc(), isInterface);
return new Inv<>(em);
@@ -2218,6 +2593,13 @@ public interface Op {
MR extends BType>
ObjInv<MR, OT, SN, MN> invokevirtual(Emitter<SN> em, TRef<OT> ownerType, String name,
MthDesc<MR, MN> desc, boolean isInterface) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: invokevirtual %s
+ .%s %s (%s)""".formatted(ownerType, name, desc,
+ isInterface ? "interface" : "class"));
+ }
em.mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, ownerType.internalName(), name,
desc.desc(), isInterface);
return new ObjInv<>(em);
@@ -2237,6 +2619,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> ior(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ior");
+ }
em.mv.visitInsn(Opcodes.IOR);
return (Emitter) em;
}
@@ -2255,6 +2640,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> irem(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: irem");
+ }
em.mv.visitInsn(Opcodes.IREM);
return (Emitter) em;
}
@@ -2272,6 +2660,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Dead> ireturn(Emitter<N0> em, RetReq<TInt> retReq) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ireturn %s".formatted(retReq));
+ }
em.mv.visitInsn(Opcodes.IRETURN);
return (Emitter) em;
}
@@ -2290,6 +2681,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> ishl(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ishl");
+ }
em.mv.visitInsn(Opcodes.ISHL);
return (Emitter) em;
}
@@ -2308,6 +2702,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> ishr(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ishr");
+ }
em.mv.visitInsn(Opcodes.ISHR);
return (Emitter) em;
}
@@ -2325,6 +2722,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<N1> istore(Emitter<N0> em, Local<TInt> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: istore %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.ISTORE, local.index());
return (Emitter) em;
}
@@ -2343,6 +2743,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> isub(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: isub");
+ }
em.mv.visitInsn(Opcodes.ISUB);
return (Emitter) em;
}
@@ -2361,6 +2764,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> iushr(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: iushr");
+ }
em.mv.visitInsn(Opcodes.IUSHR);
return (Emitter) em;
}
@@ -2379,6 +2785,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> ixor(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ixor");
+ }
em.mv.visitInsn(Opcodes.IXOR);
return (Emitter) em;
}
@@ -2414,6 +2823,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N1, TDouble>> l2d(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: l2d");
+ }
em.mv.visitInsn(Opcodes.L2D);
return (Emitter) em;
}
@@ -2430,6 +2842,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N1, TFloat>> l2f(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: l2f");
+ }
em.mv.visitInsn(Opcodes.L2F);
return (Emitter) em;
}
@@ -2446,6 +2861,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N1, TInt>> l2i(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: l2i");
+ }
em.mv.visitInsn(Opcodes.L2I);
return (Emitter) em;
}
@@ -2464,6 +2882,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> ladd(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ladd");
+ }
em.mv.visitInsn(Opcodes.LADD);
return (Emitter) em;
}
@@ -2482,6 +2903,9 @@ public interface Op {
N1 extends Ent<N2, TRef<long[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TLong>> laload(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: laload");
+ }
em.mv.visitInsn(Opcodes.LALOAD);
return (Emitter) em;
}
@@ -2500,6 +2924,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> land(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: land");
+ }
em.mv.visitInsn(Opcodes.LAND);
return (Emitter) em;
}
@@ -2520,6 +2947,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TLong>>
Emitter<N3> lastore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lastore");
+ }
em.mv.visitInsn(Opcodes.LASTORE);
return (Emitter) em;
}
@@ -2538,6 +2968,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TInt>> lcmp(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lcmp");
+ }
em.mv.visitInsn(Opcodes.LCMP);
return (Emitter) em;
}
@@ -2554,6 +2987,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TInt>> ldc__i(Emitter<N> em, int value) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ldc (int) 0x%x %d".formatted(value, value));
+ }
em.mv.visitLdcInsn(value);
return (Emitter) em;
}
@@ -2570,6 +3006,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TLong>> ldc__l(Emitter<N> em, long value) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ldc (long) 0x%x %d".formatted(value, value));
+ }
em.mv.visitLdcInsn(value);
return (Emitter) em;
}
@@ -2586,6 +3025,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TFloat>> ldc__f(Emitter<N> em, float value) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ldc (float) %s".formatted(value));
+ }
em.mv.visitLdcInsn(value);
return (Emitter) em;
}
@@ -2602,6 +3044,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TDouble>> ldc__d(Emitter<N> em, double value) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ldc (double) %s".formatted(value));
+ }
em.mv.visitLdcInsn(value);
return (Emitter) em;
}
@@ -2621,6 +3066,10 @@ public interface Op {
static <T,
N extends Next>
Emitter<Ent<N, TRef<T>>> ldc__a(Emitter<N> em, T value) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ldc (%s) %s"
+ .formatted(value.getClass().getSimpleName(), value));
+ }
em.mv.visitLdcInsn(value);
return (Emitter) em;
}
@@ -2639,6 +3088,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> ldiv(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: ldiv");
+ }
em.mv.visitInsn(Opcodes.LDIV);
return (Emitter) em;
}
@@ -2653,6 +3105,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Ent<N, TLong>> lload(Emitter<N> em, Local<TLong> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lload %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.LLOAD, local.index());
return (Emitter) em;
}
@@ -2671,6 +3126,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> lmul(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lmul");
+ }
em.mv.visitInsn(Opcodes.LMUL);
return (Emitter) em;
}
@@ -2687,6 +3145,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N1, TLong>> lneg(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lneg");
+ }
em.mv.visitInsn(Opcodes.LNEG);
return (Emitter) em;
}
@@ -2705,6 +3166,13 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Dead> lookupswitch(Emitter<N0> em, Lbl<N1> dflt, Map<Integer, Lbl<N1>> cases) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lookupswitch default=%s, cases={".formatted(dflt));
+ for (Entry<Integer, Lbl<N1>> ent : cases.entrySet()) {
+ System.err.println(" %d: %s".formatted(ent.getKey(), ent.getValue()));
+ }
+ System.err.println(" }");
+ }
em.mv.visitLookupSwitchInsn(dflt.label(),
cases.keySet().stream().mapToInt(k -> k).toArray(),
cases.values().stream().map(Lbl::label).toArray(Label[]::new));
@@ -2725,6 +3193,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> lor(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lor");
+ }
em.mv.visitInsn(Opcodes.LOR);
return (Emitter) em;
}
@@ -2743,6 +3214,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> lrem(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lrem");
+ }
em.mv.visitInsn(Opcodes.LREM);
return (Emitter) em;
}
@@ -2760,6 +3234,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Dead> lreturn(Emitter<N0> em, RetReq<TInt> retReq) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lreturn %s".formatted(retReq));
+ }
em.mv.visitInsn(Opcodes.LRETURN);
return (Emitter) em;
}
@@ -2778,6 +3255,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TLong>> lshl(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lshl");
+ }
em.mv.visitInsn(Opcodes.LSHL);
return (Emitter) em;
}
@@ -2796,6 +3276,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TLong>> lshr(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lshr");
+ }
em.mv.visitInsn(Opcodes.LSHR);
return (Emitter) em;
}
@@ -2813,6 +3296,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TLong>>
Emitter<N1> lstore(Emitter<N0> em, Local<TLong> local) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lstore %s".formatted(local));
+ }
em.mv.visitVarInsn(Opcodes.LSTORE, local.index());
return (Emitter) em;
}
@@ -2831,6 +3317,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> lsub(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lsub");
+ }
em.mv.visitInsn(Opcodes.LSUB);
return (Emitter) em;
}
@@ -2849,6 +3338,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TLong>> lushr(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lushr");
+ }
em.mv.visitInsn(Opcodes.LUSHR);
return (Emitter) em;
}
@@ -2867,6 +3359,9 @@ public interface Op {
N1 extends Ent<N2, TLong>,
N0 extends Ent<N1, TLong>>
Emitter<Ent<N2, TLong>> lxor(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: lxor");
+ }
em.mv.visitInsn(Opcodes.LXOR);
return (Emitter) em;
}
@@ -2883,6 +3378,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TRef<?>>>
Emitter<N1> monitorenter(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: monitorenter");
+ }
em.mv.visitInsn(Opcodes.MONITORENTER);
return (Emitter) em;
}
@@ -2899,6 +3397,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TRef<?>>>
Emitter<N1> monitorexit(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: monitorexit");
+ }
em.mv.visitInsn(Opcodes.MONITOREXIT);
return (Emitter) em;
}
@@ -2917,6 +3418,9 @@ public interface Op {
* @return the emitter with unknown stack
*/
static Emitter<?> multianewarray__unsupported(Emitter<?> em, TRef<?> type, int dimensions) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: multianewarray %s %s".formatted(type, dimensions));
+ }
em.mv.visitMultiANewArrayInsn(type.internalName(), dimensions);
return em;
}
@@ -2937,6 +3441,9 @@ public interface Op {
static <T extends TRef<?>,
N extends Next>
Emitter<Ent<N, T>> new_(Emitter<N> em, T type) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: new %s".formatted(type));
+ }
em.mv.visitTypeInsn(Opcodes.NEW, type.internalName());
return (Emitter) em;
}
@@ -2956,6 +3463,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N1, TRef<AT>>> newarray(Emitter<N0> em, ET elemType) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: newarray %s".formatted(elemType));
+ }
em.mv.visitIntInsn(Opcodes.NEWARRAY, elemType.t());
return (Emitter) em;
}
@@ -2969,6 +3479,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<N> nop(Emitter<N> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: nop");
+ }
em.mv.visitInsn(Opcodes.NOP);
return em;
}
@@ -2985,6 +3498,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, ? extends TCat1>>
Emitter<N1> pop(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: pop");
+ }
em.mv.visitInsn(Opcodes.POP);
return (Emitter) em;
}
@@ -3003,6 +3519,9 @@ public interface Op {
N1 extends Ent<N2, ? extends TCat1>,
N0 extends Ent<N1, ? extends TCat1>>
Emitter<N2> pop2__11(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: pop2 (11)");
+ }
em.mv.visitInsn(Opcodes.POP2);
return (Emitter) em;
}
@@ -3019,6 +3538,9 @@ public interface Op {
N1 extends Next,
N0 extends Ent<N1, ? extends TCat2>>
Emitter<N1> pop2__2(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: pop2 (2)");
+ }
em.mv.visitInsn(Opcodes.POP2);
return (Emitter) em;
}
@@ -3042,8 +3564,13 @@ public interface Op {
N2 extends Next,
N1 extends Ent<N2, T2>,
N0 extends Ent<N1, ? extends FT>>
- Emitter<N2> putfield(Emitter<N0> em, TRef<OT> owner, String name,
- FT type) {
+ Emitter<N2> putfield(Emitter<N0> em, TRef<OT> owner, String name, FT type) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: putfield %s %s
+ .%s""".formatted(type, owner, name));
+ }
em.mv.visitFieldInsn(Opcodes.PUTFIELD, owner.internalName(), name,
type.type().getDescriptor());
return (Emitter) em;
@@ -3064,8 +3591,13 @@ public interface Op {
static <FT extends BNonVoid,
N1 extends Next,
N0 extends Ent<N1, ? extends FT>>
- Emitter<N1> putstatic(Emitter<N0> em, TRef<?> owner, String name,
- FT type) {
+ Emitter<N1> putstatic(Emitter<N0> em, TRef<?> owner, String name, FT type) {
+ if (DEEP_TRACE) {
+ System.err.println("""
+ \
+ jvm: putstatic %s %s
+ .%s""".formatted(type, owner, name));
+ }
em.mv.visitFieldInsn(Opcodes.PUTSTATIC, owner.internalName(), name,
type.type().getDescriptor());
return (Emitter) em;
@@ -3101,6 +3633,9 @@ public interface Op {
*/
static <N extends Next>
Emitter<Dead> return_(Emitter<N> em, RetReq<TVoid> retReq) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: return %s".formatted(retReq));
+ }
em.mv.visitInsn(Opcodes.RETURN);
return (Emitter) em;
}
@@ -3119,6 +3654,9 @@ public interface Op {
N1 extends Ent<N2, TRef<short[]>>,
N0 extends Ent<N1, TInt>>
Emitter<Ent<N2, TInt>> saload(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: saload");
+ }
em.mv.visitInsn(Opcodes.SALOAD);
return (Emitter) em;
}
@@ -3139,6 +3677,9 @@ public interface Op {
N1 extends Ent<N2, TInt>,
N0 extends Ent<N1, TInt>>
Emitter<N3> sastore(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: sastore");
+ }
em.mv.visitInsn(Opcodes.SASTORE);
return (Emitter) em;
}
@@ -3158,6 +3699,9 @@ public interface Op {
N2 extends Next, N1 extends Ent<N2, T2>,
N0 extends Ent<N1, T1>>
Emitter<Ent<Ent<N2, T1>, T2>> swap(Emitter<N0> em) {
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: swap");
+ }
em.mv.visitInsn(Opcodes.SWAP);
return (Emitter) em;
}
@@ -3178,6 +3722,13 @@ public interface Op {
N0 extends Ent<N1, TInt>>
Emitter<Dead> tableswitch(Emitter<N0> em, int low, Lbl<N1> dflt, List<Lbl<N1>> cases) {
int high = low + cases.size() - 1; // inclusive
+ if (DEEP_TRACE) {
+ System.err.println(" jvm: tableswitch default=%s cases=[".formatted(dflt));
+ for (int i = 0; i < cases.size(); i++) {
+ System.err.println(" %d: %s".formatted(i, cases.get(i)));
+ }
+ System.err.println(" ]");
+ }
em.mv.visitTableSwitchInsn(low, high, dflt.label(),
cases.stream().map(Lbl::label).toArray(Label[]::new));
return (Emitter) em;
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.java
index 3ec404c149..daf35ffc0b 100644
--- 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.java
@@ -22,6 +22,7 @@ import java.util.Set;
import ghidra.pcode.emu.jit.JitBytesPcodeExecutorState;
import ghidra.pcode.emu.jit.alloc.JvmLocal;
+import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;
import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.JitBlock;
import ghidra.pcode.emu.jit.analysis.JitType.MpIntJitType;
import ghidra.pcode.emu.jit.analysis.JitType.SimpleJitType;
@@ -65,12 +66,12 @@ public interface VarGen<V extends JitVar> extends ValGen<V> {
@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 -> WholeDirectMemoryVarGen.GEN;
- case JitInputVar iv -> WholeInputVarGen.GEN;
- case JitMissingVar mv -> MissingVarGen.GEN;
- case JitMemoryOutVar mov -> WholeMemoryOutVarGen.GEN;
- case JitLocalOutVar lov -> WholeLocalOutVarGen.GEN;
+ case JitIndirectMemoryVar _ -> throw new AssertionError();
+ case JitDirectMemoryVar _ -> WholeDirectMemoryVarGen.GEN;
+ case JitInputVar _ -> WholeInputVarGen.GEN;
+ case JitMissingVar _ -> MissingVarGen.GEN;
+ case JitMemoryOutVar _ -> WholeMemoryOutVarGen.GEN;
+ case JitLocalOutVar _ -> WholeLocalOutVarGen.GEN;
default -> throw new AssertionError();
};
}
@@ -302,7 +303,6 @@ public interface VarGen<V extends JitVar> extends ValGen<V> {
/**
* 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.
@@ -330,6 +330,20 @@ public interface VarGen<V extends JitVar> extends ValGen<V> {
return result;
}
+ /**
+ * Compute the retired and birthed varnodes for a transition along a given flow.
+ *
+ * @param <THIS> the type of the generated class
+ * @param localThis a handle to {@code this}
+ * @param gen the code generator
+ * @param flow the flow
+ * @return the means of generating bytecode at the transition
+ */
+ static <THIS extends JitCompiledPassage> BlockTransition<THIS> computeBlockTransition(
+ Local<TRef<THIS>> localThis, JitCodeGenerator<THIS> gen, BlockFlow flow) {
+ return computeBlockTransition(localThis, gen, flow.from(), flow.to());
+ }
+
/**
* Write a value from a stack operand into the given variable
*
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.java
index 283f19dd78..b205c18208 100644
--- 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.java
@@ -19,11 +19,22 @@ import java.util.List;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
/**
* A p-code operator use-def node with two inputs and one output.
*/
public interface JitBinOp extends JitDefOp {
+ @Override
+ default String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, out=%s, l=%s, r=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op(), symbols),
+ out().toString(symbols.language()),
+ l().toString(symbols.language()),
+ r().toString(symbols.language()));
+ }
+
/**
* The use-def node for the left input operand
*
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.java
index f4fba64db7..ceee2fc144 100644
--- 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.java
@@ -17,9 +17,10 @@ package ghidra.pcode.emu.jit.op;
import java.util.List;
-import ghidra.pcode.emu.jit.JitPassage.RIndBranch;
+import ghidra.pcode.emu.jit.JitPassage.RBranch;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -29,7 +30,15 @@ import ghidra.program.model.pcode.PcodeOp;
* @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, RIndBranch branch) implements JitOp {
+public record JitBranchIndOp(PcodeOp op, JitVal target, RBranch branch) implements JitOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, target=%s, branch=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ target.toString(symbols.language()),
+ branch);
+ }
@Override
public boolean canBeRemoved() {
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.java
index 14175631f5..1598103ee7 100644
--- 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.java
@@ -20,6 +20,7 @@ import java.util.List;
import ghidra.pcode.emu.jit.JitPassage.RBranch;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -29,6 +30,13 @@ import ghidra.program.model.pcode.PcodeOp;
* @param branch the branch record created for the p-code op
*/
public record JitBranchOp(PcodeOp op, RBranch branch) implements JitOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, branch=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ branch);
+ }
@Override
public boolean canBeRemoved() {
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.java
index 4055133672..9537682ffc 100644
--- 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.java
@@ -20,6 +20,7 @@ import java.util.List;
import ghidra.pcode.emu.jit.JitPassage.RBranch;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -29,8 +30,15 @@ import ghidra.program.model.pcode.PcodeOp;
* @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, RBranch branch, JitVal cond)
- implements JitOp {
+public record JitCBranchOp(PcodeOp op, RBranch branch, JitVal cond) implements JitOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, branch=%s, cond=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ branch,
+ cond.toString(symbols.language()));
+ }
@Override
public boolean canBeRemoved() {
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.java
index a58af8eca9..b3a895396f 100644
--- 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.java
@@ -17,12 +17,14 @@ package ghidra.pcode.emu.jit.op;
import java.util.List;
import java.util.Objects;
+import java.util.stream.Collectors;
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.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -37,8 +39,23 @@ import ghidra.program.model.pcode.PcodeOp;
* @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,
+ PcodeUseropDefinition<?> userop, List<JitVal> args, List<JitTypeBehavior> inputTypes,
MiniDFState dfState) implements JitCallOtherOpIf, JitDefOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, out=%s, type=%s, userop=%s, args=(%s), inputTypes=%s, dfState=%s]"
+ .formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ out.toString(symbols.language()),
+ type,
+ userop,
+ args.stream()
+ .map(a -> a.toString(symbols.language()))
+ .collect(Collectors.joining(",")),
+ inputTypes,
+ dfState);
+ }
public JitCallOtherDefOp {
Objects.requireNonNull(type);
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.java
index 689e6b64cb..d8ff691985 100644
--- 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.java
@@ -19,6 +19,7 @@ import java.util.List;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -28,6 +29,14 @@ import ghidra.program.model.pcode.PcodeOp;
* @param opName the name of the missing userop
*/
public record JitCallOtherMissingOp(PcodeOp op, String opName) implements JitOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, opName=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ opName);
+ }
+
@Override
public boolean canBeRemoved() {
return false;
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.java
index 8a8687ddcb..f378ab9710 100644
--- 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.java
@@ -16,11 +16,13 @@
package ghidra.pcode.emu.jit.op;
import java.util.List;
+import java.util.stream.Collectors;
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.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -32,5 +34,19 @@ import ghidra.program.model.pcode.PcodeOp;
* @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 {}
+public record JitCallOtherOp(PcodeOp op, PcodeUseropDefinition<?> userop, List<JitVal> args,
+ List<JitTypeBehavior> inputTypes, MiniDFState dfState) implements JitCallOtherOpIf {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, userop=%s, args=(%s), inputTypes=%s, dfState=%s]"
+ .formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ userop,
+ args.stream()
+ .map(a -> a.toString(symbols.language()))
+ .collect(Collectors.joining(",")),
+ inputTypes,
+ dfState);
+ }
+}
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.java
index 6b1db488da..83edc71ee9 100644
--- 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.java
@@ -25,29 +25,22 @@ 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 {
@@ -57,7 +50,7 @@ public interface JitCallOtherOpIf extends JitOp {
*
* @return the definition from the library
*/
- PcodeUseropDefinition<Object> userop();
+ PcodeUseropDefinition<?> userop();
/**
* The arguments to the userop.
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.java
index 0ae239d90a..b09bb4edb8 100644
--- 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.java
@@ -16,16 +16,17 @@
package ghidra.pcode.emu.jit.op;
import java.util.List;
+import java.util.stream.Collectors;
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;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
/**
* 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
@@ -47,6 +48,15 @@ public record JitCatenateOp(JitOutVar out, List<JitVal> parts) implements JitDef
}
}
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[out=%s, parts=%s]".formatted(
+ out.toString(symbols.language()),
+ parts.stream()
+ .map(p -> p.toString(symbols.language()))
+ .collect(Collectors.joining(",")));
+ }
+
@Override
public void link() {
JitDefOp.super.link();
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.java
index 3772d9dced..6e5e611d72 100644
--- 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.java
@@ -20,6 +20,7 @@ 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.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.pcode.PcodeOp;
@@ -33,6 +34,15 @@ import ghidra.program.model.pcode.PcodeOp;
*/
public record JitLoadOp(PcodeOp op, JitOutVar out, AddressSpace space, JitVal offset)
implements JitDefOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, out=%s, space=%s, offset=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ out.toString(symbols.language()),
+ space,
+ offset.toString(symbols.language()));
+ }
@Override
public void link() {
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.java
index 51187a4bd2..b410482c9a 100644
--- 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.java
@@ -20,11 +20,11 @@ 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.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
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.
@@ -32,6 +32,12 @@ import ghidra.program.model.pcode.PcodeOp;
* @param op the p-code op
*/
public record JitNopOp(PcodeOp op) implements JitOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols));
+ }
@Override
public boolean canBeRemoved() {
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.java
index a780cbf56d..3aa2f6bb04 100644
--- 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.java
@@ -16,20 +16,46 @@
package ghidra.pcode.emu.jit.op;
import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
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.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
+import ghidra.program.model.pcode.Varnode;
/**
* 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 {
+
+ static String toString(PcodeOp op, PcodeUseropSymbolMap symbols) {
+ Varnode out = op.getOutput();
+ if (op.getOpcode() == PcodeOp.CALLOTHER) {
+ Varnode opIndex = op.getInput(0);
+ String opName = symbols.getUseropName((int) opIndex.getOffset());
+ return "%s = %s '%s' %s".formatted(
+ out == null ? " --- " : out.toString(symbols.language()),
+ op.getMnemonic(),
+ opName == null ? "<unk>" : opName,
+ Stream.of(op.getInputs())
+ .skip(1)
+ .map(in -> in.toString(symbols.language()))
+ .collect(Collectors.joining(", ")));
+ }
+ return "%s = %s %s".formatted(
+ out == null ? " --- " : out.toString(symbols.language()),
+ op.getMnemonic(),
+ Stream.of(op.getInputs())
+ .map(in -> in.toString(symbols.language()))
+ .collect(Collectors.joining(", ")));
+ }
+
/**
* Create a use-def node for a nop or unimplemented op.
*
@@ -142,6 +168,14 @@ public interface JitOp {
};
}
+ /**
+ * Render this op using symbols for varnodes and userop names
+ *
+ * @param symbols the userop symbols and language
+ * @return the string
+ */
+ String toString(PcodeUseropSymbolMap symbols);
+
/**
* The p-code op represented by this use-def node
*
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.java
index ada7279a14..6d6be3e60c 100644
--- 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.java
@@ -16,6 +16,7 @@
package ghidra.pcode.emu.jit.op;
import java.util.List;
+import java.util.stream.Collectors;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
@@ -24,6 +25,7 @@ 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.*;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
/**
* The synthetic use-def node for phi nodes.
@@ -44,6 +46,18 @@ public record JitPhiOp(JitBlock block, JitOutVar out, BidiMap<BlockFlow, JitVal>
this(block, out, new DualHashBidiMap<>());
}
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[block=%s, out=%s, options={%s}]".formatted(
+ block,
+ out.toString(symbols.language()),
+ options.entrySet()
+ .stream()
+ .map(e -> "%s=%s".formatted(e.getKey(),
+ e.getValue().toString(symbols.language())))
+ .collect(Collectors.joining(",")));
+ }
+
/**
* Add an option assuming the given flow is taken
*
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.java
index 37e4d19282..1ae7f7a39f 100644
--- 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.java
@@ -19,6 +19,7 @@ import java.util.List;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.pcode.PcodeOp;
@@ -32,6 +33,15 @@ import ghidra.program.model.pcode.PcodeOp;
*/
public record JitStoreOp(PcodeOp op, AddressSpace space, JitVal offset, JitVal value)
implements JitOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, space=%s, offset=%s, value=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols),
+ space,
+ offset.toString(symbols.language()),
+ value.toString(symbols.language()));
+ }
@Override
public boolean canBeRemoved() {
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.java
index 70bee82ca8..3e487036a1 100644
--- 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.java
@@ -20,18 +20,17 @@ 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.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
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
@@ -59,6 +58,14 @@ public record JitSynthSubPieceOp(JitOutVar out, int offset, JitVal v)
}
}
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[out=%s, offset=%d, v=%s]".formatted(
+ out.toString(symbols.language()),
+ offset,
+ v.toString(symbols.language()));
+ }
+
@Override
public void link() {
JitDefOp.super.link();
@@ -100,7 +107,6 @@ public record JitSynthSubPieceOp(JitOutVar out, int offset, JitVal v)
/**
* 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:
@@ -108,16 +114,14 @@ public record JitSynthSubPieceOp(JitOutVar out, int offset, JitVal v)
* <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
*
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.java
index 40991e0021..53f22e578e 100644
--- 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.java
@@ -19,11 +19,21 @@ import java.util.List;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
/**
* A p-code operator use-def node with one input and one output.
*/
public interface JitUnOp extends JitDefOp {
+ @Override
+ default String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s, out=%s, u=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op(), symbols),
+ out().toString(symbols.language()),
+ u().toString(symbols.language()));
+ }
+
/**
* The use-def node for the input operand
*
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.java
index cdddb80fd9..f976010313 100644
--- 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.java
@@ -19,6 +19,7 @@ import java.util.List;
import ghidra.pcode.emu.jit.analysis.JitTypeBehavior;
import ghidra.pcode.emu.jit.var.JitVal;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -27,6 +28,12 @@ import ghidra.program.model.pcode.PcodeOp;
* @param op the p-code op
*/
public record JitUnimplementedOp(PcodeOp op) implements JitOp {
+ @Override
+ public String toString(PcodeUseropSymbolMap symbols) {
+ return "%s[op=%s]".formatted(
+ getClass().getSimpleName(),
+ JitOp.toString(op, symbols));
+ }
@Override
public boolean canBeRemoved() {
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.java
index d72dc2fd07..bf5ea2648c 100644
--- 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.java
@@ -36,9 +36,4 @@ public abstract class AbstractJitVar extends AbstractJitVal implements JitVar {
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.java
index b585468caa..e749f3fe8f 100644
--- 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.java
@@ -16,6 +16,7 @@
package ghidra.pcode.emu.jit.var;
import ghidra.program.model.address.AddressSpace;
+import ghidra.program.model.lang.Language;
import ghidra.program.model.pcode.Varnode;
/**
@@ -52,4 +53,10 @@ public abstract class AbstractJitVarnodeVar extends AbstractJitVar implements Ji
public String toString() {
return "%s[id=%d,varnode=%s]".formatted(getClass().getSimpleName(), id, varnode);
}
+
+ @Override
+ public String toString(Language language) {
+ return "%s[id=%s, varnode=%s]".formatted(getClass().getSimpleName(), id,
+ varnode.toString(language));
+ }
}
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.java
index 1d9ead7fc4..b4dbf1da38 100644
--- 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.java
@@ -17,6 +17,8 @@ package ghidra.pcode.emu.jit.var;
import java.math.BigInteger;
+import ghidra.program.model.lang.Language;
+
/**
* A p-code constant use-def node.
*/
@@ -25,7 +27,6 @@ public class JitConstVal extends AbstractJitVal {
/**
* Construct a constant.
- *
* <p>
* Use {@link JitVal#constant(int, BigInteger)} instead.
*
@@ -42,6 +43,11 @@ public class JitConstVal extends AbstractJitVal {
return "%s[value=%s]".formatted(getClass().getSimpleName(), value);
}
+ @Override
+ public String toString(Language language) {
+ return toString();
+ }
+
/**
* The value of this constant.
*
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitFailVal.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitFailVal.java
index 6cc78f7a74..8d12525e18 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitFailVal.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/jit/var/JitFailVal.java
@@ -18,6 +18,7 @@ package ghidra.pcode.emu.jit.var;
import java.util.List;
import ghidra.pcode.emu.jit.op.JitOp;
+import ghidra.program.model.lang.Language;
/**
* A value that is forbidden from being translated
@@ -43,4 +44,9 @@ public enum JitFailVal implements JitVal {
@Override
public void removeUse(JitOp op, int position) {
}
+
+ @Override
+ public String toString(Language language) {
+ return "<FAIL>";
+ }
}
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.java
index 6865d3f379..cd79f3dff5 100644
--- 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.java
@@ -22,11 +22,11 @@ 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.lang.Language;
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
@@ -68,4 +68,9 @@ public enum JitIndirectMemoryVar implements JitMemoryVar {
public AddressSpace space() {
return null;
}
+
+ @Override
+ public String toString(Language language) {
+ return "<INDIRECT>";
+ }
}
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.java
index f11a6a9d9d..f98ca08ea6 100644
--- 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.java
@@ -23,6 +23,7 @@ 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;
+import ghidra.program.model.lang.Language;
/**
* A p-code value use-def node.
@@ -54,6 +55,14 @@ public interface JitVal {
return new JitConstVal(size, value);
}
+ /**
+ * Render this value using symbols for varnodes
+ *
+ * @param language the language
+ * @return the string
+ */
+ String toString(Language language);
+
/**
* The size in bytes.
*
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/util/CountsPcodeOps.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/util/CountsPcodeOps.java
new file mode 100644
index 0000000000..67eeb44ee6
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/util/CountsPcodeOps.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.util;
+
+/**
+ * An interface for things that count instructions and p-code ops
+ */
+public interface CountsPcodeOps {
+ /**
+ * {@return the number of instructions counted}
+ */
+ int instructionCount();
+
+ /**
+ * {@return the number of trailing p-code ops counted}
+ * <p>
+ * This represents partial execution of an instruction. Though {@link #instructionCount()}
+ * <em>does</em> count the partial instruction, this indicates how much of that instruction was
+ * counted. This should provide enough information to replay an execution to exactly the same
+ * p-code op step.
+ */
+ int trailingOpCount();
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/util/PcodeOpCounter.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/util/PcodeOpCounter.java
new file mode 100644
index 0000000000..b6d5666a1b
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emu/util/PcodeOpCounter.java
@@ -0,0 +1,80 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.pcode.emu.util;
+
+/**
+ * The most basic implementation of {@link CountsPcodeOps}
+ */
+public class PcodeOpCounter implements CountsPcodeOps {
+ private int instructions;
+ private int trailingOps;
+
+ /**
+ * Count one additional op
+ *
+ * @param startsInstruction true if this op is the beginning of a new instruction
+ */
+ public void countOp(boolean startsInstruction) {
+ if (startsInstruction) {
+ instructions++;
+ trailingOps = 1;
+ }
+ else {
+ trailingOps++;
+ }
+ }
+
+ /**
+ * Count some number of additional instructions and ops
+ * <p>
+ * If there are no new instructions, then the trailing ops are added to those already counted.
+ * If there is 1 or more new instructions, those are added to those already counted, but
+ * trailing ops is reset to only count those given.
+ *
+ * @param instructions the number of instructions
+ * @param trailingOps the number of trailing ops
+ */
+ public void count(int instructions, int trailingOps) {
+ if (instructions != 0) {
+ this.instructions += instructions;
+ this.trailingOps = trailingOps;
+ }
+ else {
+ this.trailingOps += trailingOps;
+ }
+ }
+
+ /**
+ * Count some number of additional instructions and ops
+ * <p>
+ * This works as in {@link #count(int, int)} but the counts are taken from another counter
+ *
+ * @param counter the other counter
+ */
+ public void count(CountsPcodeOps counter) {
+ count(counter.instructionCount(), counter.trailingOpCount());
+ }
+
+ @Override
+ public int instructionCount() {
+ return instructions;
+ }
+
+ @Override
+ public int trailingOpCount() {
+ return trailingOps;
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emulate/Emulate.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emulate/Emulate.java
index c0ef5fca99..4a325b0cec 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emulate/Emulate.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/emulate/Emulate.java
@@ -38,10 +38,10 @@ import ghidra.util.task.TaskMonitor;
/**
* A SLEIGH based implementation of the Emulate interface
* <p>
- * This implementation uses a Translate object to translate machine instructions into
- * pcode and caches pcode ops for later use by the emulator. The pcode is cached as soon
- * as the execution address is set, either explicitly, or via branches and fallthrus. There
- * are additional methods for inspecting the pcode ops in the current instruction as a sequence.
+ * This implementation uses a Translate object to translate machine instructions into pcode and
+ * caches pcode ops for later use by the emulator. The pcode is cached as soon as the execution
+ * address is set, either explicitly, or via branches and fallthrus. There are additional methods
+ * for inspecting the pcode ops in the current instruction as a sequence.
*/
@Deprecated(since = "12.1", forRemoval = true)
public class Emulate {
@@ -134,10 +134,11 @@ public class Emulate {
}
/**
- * Since the emulator can single step through individual pcode operations, the machine state
- * may be halted in the middle of a single machine instruction, unlike conventional debuggers.
- * This routine can be used to determine if execution is actually at the beginning of a machine
+ * Since the emulator can single step through individual pcode operations, the machine state may
+ * be halted in the middle of a single machine instruction, unlike conventional debuggers. This
+ * routine can be used to determine if execution is actually at the beginning of a machine
* instruction.
+ *
* @return true if the next pcode operation is at the start of the instruction translation
*/
public boolean isInstructionStart() {
@@ -171,8 +172,9 @@ public class Emulate {
}
/**
- * Get length of instruction including any delay-slotted instructions.
- * Must be called by emitPcode with lastPseudoInstructionBlock properly set.
+ * Get length of instruction including any delay-slotted instructions. Must be called by
+ * emitPcode with lastPseudoInstructionBlock properly set.
+ *
* @param instr
* @return length of instruction in bytes for use in computing fall-through location
*/
@@ -239,14 +241,12 @@ public class Emulate {
}
/**
- * Returns the current context register value. The context value returned reflects
- * its state when the previously executed instruction was
- * parsed/executed. The context value returned will feed into the next
- * instruction to be parsed with its non-flowing bits cleared and
- * any future context state merged in. If no instruction has been executed,
- * the explicitly set context will be returned. A null value is returned
- * if no context register is defined by the language or initial context has
- * not been set.
+ * Returns the current context register value. The context value returned reflects its state
+ * when the previously executed instruction was parsed/executed. The context value returned will
+ * feed into the next instruction to be parsed with its non-flowing bits cleared and any future
+ * context state merged in. If no instruction has been executed, the explicitly set context will
+ * be returned. A null value is returned if no context register is defined by the language or
+ * initial context has not been set.
*/
public RegisterValue getContextRegisterValue() {
Register contextReg = language.getContextBaseRegister();
@@ -260,14 +260,12 @@ public class Emulate {
}
/**
- * Sets the context register value at the current execute address.
- * The Emulator should not be running when this method is invoked.
- * Only flowing context bits should be set, as non-flowing bits
- * will be cleared prior to parsing on instruction. In addition,
- * any future context state set by the pcode emitter will
- * take precedence over context set using this method. This method
- * is primarily intended to be used to establish the initial
- * context state.
+ * Sets the context register value at the current execute address. The Emulator should not be
+ * running when this method is invoked. Only flowing context bits should be set, as non-flowing
+ * bits will be cleared prior to parsing on instruction. In addition, any future context state
+ * set by the pcode emitter will take precedence over context set using this method. This method
+ * is primarily intended to be used to establish the initial context state.
+ *
* @param regValue
*/
public void setContextRegisterValue(RegisterValue regValue) {
@@ -297,8 +295,8 @@ public class Emulate {
}
/**
- * Update the iterator into the current pcode cache, and if necessary, generate
- * the pcode for the fallthru instruction and reset the iterator.
+ * Update the iterator into the current pcode cache, and if necessary, generate the pcode for
+ * the fallthru instruction and reset the iterator.
*/
public void fallthruOp() {
current_op += 1;
@@ -349,9 +347,9 @@ public class Emulate {
}
/**
- * Give instuctionStateModifier first shot at executing custom pcodeop,
- * if not supported look for a breakpoint for the given user-defined op and invoke it.
- * If it doesn't exist, or doesn't replace the action, throw an exception
+ * Give instuctionStateModifier first shot at executing custom pcodeop, if not supported look
+ * for a breakpoint for the given user-defined op and invoke it. If it doesn't exist, or doesn't
+ * replace the action, throw an exception
*
* @param op is the particular user-defined op being executed
* @throws UnimplementedCallOtherException
@@ -389,15 +387,16 @@ public class Emulate {
/**
* This routine executes an entire machine instruction at once, as a conventional debugger step
- * function would do. If execution is at the start of an instruction, the breakpoints are checked
- * and invoked as needed for the current address. If this routine is invoked while execution is
- * in the middle of a machine instruction, execution is continued until the current instruction
- * completes.
- * @param stopAtBreakpoint
- * @param monitor
- * @throws CancelledException
- * @throws LowlevelError
- * @throws InstructionDecodeException
+ * function would do. If execution is at the start of an instruction, the breakpoints are
+ * checked and invoked as needed for the current address. If this routine is invoked while
+ * execution is in the middle of a machine instruction, execution is continued until the current
+ * instruction completes.
+ *
+ * @param stopAtBreakpoint
+ * @param monitor
+ * @throws CancelledException
+ * @throws LowlevelError
+ * @throws InstructionDecodeException
*/
public void executeInstruction(boolean stopAtBreakpoint, TaskMonitor monitor)
throws CancelledException, LowlevelError, InstructionDecodeException {
@@ -451,7 +450,7 @@ public class Emulate {
throw e;
}
}
-
+
/**
* {@return the memory state object which this emulator uses}
*/
@@ -525,7 +524,7 @@ public class Emulate {
fallthruOp(); // All binary ops are fallthrus
}
else {
- switch (behave.getOpCode()) {
+ switch (behave.opcode()) {
case PcodeOp.LOAD:
executeLoad(raw);
fallthruOp();
@@ -564,13 +563,14 @@ public class Emulate {
fallthruOp();
break;
default:
- throw new LowlevelError("Unsupported op (opcode=" + behave.getOpCode() + ")");
+ throw new LowlevelError("Unsupported op (opcode=" + behave.opcode() + ")");
}
}
}
/**
* This routine performs a standard pcode load operation on the memory state
+ *
* @param op is the particular load op being executed
*/
public void executeLoad(PcodeOpRaw op) {
@@ -596,6 +596,7 @@ public class Emulate {
/**
* This routine performs a standard pcode store operation on the memory state
+ *
* @param op is the particular store op being executed
*/
public void executeStore(PcodeOpRaw op) {
@@ -620,6 +621,7 @@ public class Emulate {
/**
* This routine performs a standard pcode branch indirect operation on the memory state
+ *
* @param op is the particular branchind op being executed
*/
public void executeBranchind(PcodeOpRaw op) {
@@ -630,6 +632,7 @@ public class Emulate {
/**
* This routine performs a standard pcode call operation on the memory state
+ *
* @param op is the particular call op being executed
*/
public void executeCall(PcodeOpRaw op) {
@@ -638,15 +641,17 @@ public class Emulate {
/**
* This routine performs a standard pcode call indirect operation on the memory state
- * @param op is the particular callind op being executed
+ *
+ * @param op is the particular callind op being executed
*/
public void executeCallind(PcodeOpRaw op) {
executeBranchind(op); // same behavior as branch indirect
}
/**
- * This kind of pcode op should not come up in ordinary emulation, so this routine
- * throws an exception.
+ * This kind of pcode op should not come up in ordinary emulation, so this routine throws an
+ * exception.
+ *
* @param op is the particular multiequal op being executed
*/
public void executeMultiequal(PcodeOpRaw op) {
@@ -654,8 +659,9 @@ public class Emulate {
}
/**
- * This kind of pcode op should not come up in ordinary emulation, so this routine
- * throws an exception.
+ * This kind of pcode op should not come up in ordinary emulation, so this routine throws an
+ * exception.
+ *
* @param op is the particular indirect op being executed
*/
public void executeIndirect(PcodeOpRaw op) {
@@ -663,154 +669,129 @@ public class Emulate {
}
}
-/** \page sleighAPIemulate The SLEIGH Emulator
-
- \section emu_overview Overview
-
- \b SLEIGH provides a framework for emulating the processors which have a specification written
- for them. The key classes in this framework are:
-
- \b Key \b Classes
- - \ref MemoryState
- - \ref MemoryBank
- - \ref BreakTable
- - \ref BreakCallBack
- - \ref Emulate
- - \ref EmulatePcodeCache
-
- The MemoryState object holds the representation of registers and memory during emulation. It
- understands the address spaces defined in the \b SLEIGH specification and how data is encoded
- in these spaces. It also knows any register names defined by the specification, so these
- can be used to set or query the state of these registers naturally.
-
- The emulation framework can be tailored to a particular environment by creating \b breakpoint
- objects, which derive off the BreakCallBack interface. These can be used to create callbacks
- during emulation that have full access to the memory state and the emulator, so any action
- can be accomplished. The breakpoint callbacks can be designed to either augment or replace
- the instruction at a particular address, or the callback can be used to implement the action
- of a user-defined pcode op. The BreakCallBack objects are managed by the BreakTable object,
- which takes care of invoking the callback at the appropriate time.
-
- The Emulate object serves as a basic execution engine. Its main method is
- Emulate::executeCurrentOp() which executes a single pcode operation on the memory state.
- Methods exist for querying and setting the current execution address and examining the pcode
- op being executed.
-
- The main implementation of the Emulate interface is the EmulatePcodeCache object. It uses
- SLEIGH to translate machine instructions as they are executed. The currently executing instruction
- is translated into a cached sequence of pcode operations. Additional methods allow this entire
- sequence to be inspected, and there is another stepping function which allows the emulator
- to be stepped through an entire machine instruction at a time. The single pcode stepping methods
- are of course still available and the two methods can be used together without conflict.
-
- \section emu_membuild Building a Memory State
-
- Assuming the SLEIGH Translate object and the LoadImage object have already been built
- (see \ref sleighAPIbasic), the only required step left before instantiating an emulator
- is to create a MemoryState object. The MemoryState object can be instantiated simply by
- passing the constructor the Translate object, but before it will work properly, you need
- to register individual MemoryBank objects with it, for each address space that might
- get used by the emulator.
-
- A MemoryBank is a representation of data stored in a single address space
- There are some choices for the type of MemoryBank associated with an address space.
- A MemoryImage is a read-only memory bank that gets its data from a LoadImage. In order
- to make this writeable, or to create a writeable memory bank which starts with its bytes
- initialized to zero, you can use a MemoryPageOverlay.
-
- A MemoryPageOverlay overlays another memory bank as well. But it implements writes to the bank
- by caching memory \e pages. Any write creates an aligned page to hold the new data. The class
- takes care of loading and filling in pages as needed.
-
- The Emulate constructor always adds a unique space memory bank using the UniqueMemoryBank,
- the user needs not add this space.
-
- All the memory bank constructors need a page size, which is most relevant to the page implementation. The
- null pointers passed in, in place of a real memory bank, indicate that the memory bank has no initial
- memory image. Once the memory banks are instantiated, they are registered with the memory state
- via the MemoryState::setMemoryBank() method.
-
- \section emu_breakpoints Breakpoints
-
- In order to provide behavior within the emulator beyond just what the core instruction emulation
- provides, the framework supports \b breakpoint classes. A breakpoint is created by deriving a
- class from the BreakCallBack class and overriding either BreakCallBack::addressCallback() or
- BreakCallBack::pcodeCallback(). Here is an example of a breakpoint that implements a
- standard C library \e puts call an the x86 architecture. When the breakpoint is invoked,
- a call to \e puts has just been made, so the stack pointer is pointing to the return address
- and the next 4 bytes on the stack are a pointer to the string being passed in.
-
- \code
- class PutsCallBack : public BreakCallBack {
- public:
- virtual bool addressCallback(const Address &addr);
- };
-
- bool PutsCallBack::addressCallback(const Address &addr)
-
- {
- MemoryState *mem = emulate->getMemoryState();
- uint1 buffer[256];
- uint4 esp = mem->getValue("ESP");
- AddrSpace *ram = mem->getTranslate()->getSpaceByName("ram");
-
- uint4 param1 = mem->getValue(ram,esp+4,4);
- mem->getChunk(buffer,ram,param1,255);
-
- cout << (char *)&buffer << endl;
-
- uint4 returnaddr = mem->getValue(ram,esp,4);
- mem->setValue("ESP",esp+8);
- emulate->setExecuteAddress(Address(ram,returnaddr));
-
- return true; // This replaces the indicated instruction
- }
-
- \endcode
-
- Notice that the callback retrieves the value of the stack pointer by name. Using this
- value, the string pointer is retrieved, then the data for the actual string is retrieved.
- After dumping the string to standard out, the return address is recovered and the \e return
- instruction is emulated by explicitly setting the next execution address to be the return value.
-
- \section emu_finalsetup Running the Emulator
- Here is an example of instantiating an EmulatePcodeCache object. A breakpoint is also instantiated
- and registered with the BreakTable.
-
- \code
- ...
- Sleigh trans(&loader,&context); // Instantiate the translator
- ...
- MemoryState memstate(&trans); // Instantiate the memory state
- ...
- BreakTableCallBack breaktable(&trans); // Instantiate a breakpoint table
- EmulatePcodeCache emulator(&trans,&memstate,&breaktable); // Instantiate the emulator
-
- // Set up the initial stack pointer
- memstate.setValue("ESP",0xbffffffc);
- emulator.setExecuteAddress(Address(trans.getDefaultSpace(),0x1D00114)); // Initial execution address
-
- PutsCallBack putscallback;
- breaktable.registerAddressCallback(Address(trans.getDefaultSpace(),0x1D00130),&putscallback);
-
- AssemblyRaw assememit;
- for(;;) {
- Address addr = emulator.getExecuteAddress();
- trans.printAssembly(assememit,addr);
- emulator.executeInstruction();
- }
-
- \endcode
-
- Notice how the initial stack pointer and initial execute address is set up. The breakpoint
- is registered with the BreakTable, giving it a specific address. The executeInstruction method
- is called inside the loop, to actually run the emulator. Notice that a disassembly of each
- instruction is printed after each step of the emulator.
-
- Other information can be examined from within this execution loop or in other tailored breakpoints.
- In particular, the Emulate::getCurrentOp() method can be used to retrieve the an instance
- of the currently executing pcode operation. From this starting point, you can examine the
- low-level objects:
- - PcodeOpRaw and
- - VarnodeData
+/**
+ * \page sleighAPIemulate The SLEIGH Emulator
+ *
+ * \section emu_overview Overview
+ *
+ * \b SLEIGH provides a framework for emulating the processors which have a specification written
+ * for them. The key classes in this framework are:
+ *
+ * \b Key \b Classes - \ref MemoryState - \ref MemoryBank - \ref BreakTable - \ref BreakCallBack -
+ * \ref Emulate - \ref EmulatePcodeCache
+ *
+ * The MemoryState object holds the representation of registers and memory during emulation. It
+ * understands the address spaces defined in the \b SLEIGH specification and how data is encoded in
+ * these spaces. It also knows any register names defined by the specification, so these can be used
+ * to set or query the state of these registers naturally.
+ *
+ * The emulation framework can be tailored to a particular environment by creating \b breakpoint
+ * objects, which derive off the BreakCallBack interface. These can be used to create callbacks
+ * during emulation that have full access to the memory state and the emulator, so any action can be
+ * accomplished. The breakpoint callbacks can be designed to either augment or replace the
+ * instruction at a particular address, or the callback can be used to implement the action of a
+ * user-defined pcode op. The BreakCallBack objects are managed by the BreakTable object, which
+ * takes care of invoking the callback at the appropriate time.
+ *
+ * The Emulate object serves as a basic execution engine. Its main method is
+ * Emulate::executeCurrentOp() which executes a single pcode operation on the memory state. Methods
+ * exist for querying and setting the current execution address and examining the pcode op being
+ * executed.
+ *
+ * The main implementation of the Emulate interface is the EmulatePcodeCache object. It uses SLEIGH
+ * to translate machine instructions as they are executed. The currently executing instruction is
+ * translated into a cached sequence of pcode operations. Additional methods allow this entire
+ * sequence to be inspected, and there is another stepping function which allows the emulator to be
+ * stepped through an entire machine instruction at a time. The single pcode stepping methods are of
+ * course still available and the two methods can be used together without conflict.
+ *
+ * \section emu_membuild Building a Memory State
+ *
+ * Assuming the SLEIGH Translate object and the LoadImage object have already been built (see \ref
+ * sleighAPIbasic), the only required step left before instantiating an emulator is to create a
+ * MemoryState object. The MemoryState object can be instantiated simply by passing the constructor
+ * the Translate object, but before it will work properly, you need to register individual
+ * MemoryBank objects with it, for each address space that might get used by the emulator.
+ *
+ * A MemoryBank is a representation of data stored in a single address space There are some choices
+ * for the type of MemoryBank associated with an address space. A MemoryImage is a read-only memory
+ * bank that gets its data from a LoadImage. In order to make this writeable, or to create a
+ * writeable memory bank which starts with its bytes initialized to zero, you can use a
+ * MemoryPageOverlay.
+ *
+ * A MemoryPageOverlay overlays another memory bank as well. But it implements writes to the bank by
+ * caching memory \e pages. Any write creates an aligned page to hold the new data. The class takes
+ * care of loading and filling in pages as needed.
+ *
+ * The Emulate constructor always adds a unique space memory bank using the UniqueMemoryBank, the
+ * user needs not add this space.
+ *
+ * All the memory bank constructors need a page size, which is most relevant to the page
+ * implementation. The null pointers passed in, in place of a real memory bank, indicate that the
+ * memory bank has no initial memory image. Once the memory banks are instantiated, they are
+ * registered with the memory state via the MemoryState::setMemoryBank() method.
+ *
+ * \section emu_breakpoints Breakpoints
+ *
+ * In order to provide behavior within the emulator beyond just what the core instruction emulation
+ * provides, the framework supports \b breakpoint classes. A breakpoint is created by deriving a
+ * class from the BreakCallBack class and overriding either BreakCallBack::addressCallback() or
+ * BreakCallBack::pcodeCallback(). Here is an example of a breakpoint that implements a standard C
+ * library \e puts call an the x86 architecture. When the breakpoint is invoked, a call to \e puts
+ * has just been made, so the stack pointer is pointing to the return address and the next 4 bytes
+ * on the stack are a pointer to the string being passed in.
+ *
+ * \code class PutsCallBack : public BreakCallBack { public: virtual bool addressCallback(const
+ * Address &addr); };
+ *
+ * bool PutsCallBack::addressCallback(const Address &addr)
+ *
+ * { MemoryState *mem = emulate->getMemoryState(); uint1 buffer[256]; uint4 esp =
+ * mem->getValue("ESP"); AddrSpace *ram = mem->getTranslate()->getSpaceByName("ram");
+ *
+ * uint4 param1 = mem->getValue(ram,esp+4,4); mem->getChunk(buffer,ram,param1,255);
+ *
+ * cout << (char *)&buffer << endl;
+ *
+ * uint4 returnaddr = mem->getValue(ram,esp,4); mem->setValue("ESP",esp+8);
+ * emulate->setExecuteAddress(Address(ram,returnaddr));
+ *
+ * return true; // This replaces the indicated instruction }
+ *
+ * \endcode
+ *
+ * Notice that the callback retrieves the value of the stack pointer by name. Using this value, the
+ * string pointer is retrieved, then the data for the actual string is retrieved. After dumping the
+ * string to standard out, the return address is recovered and the \e return instruction is emulated
+ * by explicitly setting the next execution address to be the return value.
+ *
+ * \section emu_finalsetup Running the Emulator Here is an example of instantiating an
+ * EmulatePcodeCache object. A breakpoint is also instantiated and registered with the BreakTable.
+ *
+ * \code ... Sleigh trans(&loader,&context); // Instantiate the translator ... MemoryState
+ * memstate(&trans); // Instantiate the memory state ... BreakTableCallBack breaktable(&trans); //
+ * Instantiate a breakpoint table EmulatePcodeCache emulator(&trans,&memstate,&breaktable); //
+ * Instantiate the emulator
+ *
+ * // Set up the initial stack pointer memstate.setValue("ESP",0xbffffffc);
+ * emulator.setExecuteAddress(Address(trans.getDefaultSpace(),0x1D00114)); // Initial execution
+ * address
+ *
+ * PutsCallBack putscallback;
+ * breaktable.registerAddressCallback(Address(trans.getDefaultSpace(),0x1D00130),&putscallback);
+ *
+ * AssemblyRaw assememit; for(;;) { Address addr = emulator.getExecuteAddress();
+ * trans.printAssembly(assememit,addr); emulator.executeInstruction(); }
+ *
+ * \endcode
+ *
+ * Notice how the initial stack pointer and initial execute address is set up. The breakpoint is
+ * registered with the BreakTable, giving it a specific address. The executeInstruction method is
+ * called inside the loop, to actually run the emulator. Notice that a disassembly of each
+ * instruction is printed after each step of the emulator.
+ *
+ * Other information can be examined from within this execution loop or in other tailored
+ * breakpoints. In particular, the Emulate::getCurrentOp() method can be used to retrieve the an
+ * instance of the currently executing pcode operation. From this starting point, you can examine
+ * the low-level objects: - PcodeOpRaw and - VarnodeData
*/
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AbstractSleighPcodeUseropDefinition.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AbstractSleighPcodeUseropDefinition.java
index 2802759613..ff3611dd53 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AbstractSleighPcodeUseropDefinition.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AbstractSleighPcodeUseropDefinition.java
@@ -18,17 +18,13 @@ package ghidra.pcode.exec;
import java.lang.reflect.Method;
import java.util.*;
-import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.Varnode;
/**
* A abstract Sleigh userop definition
- *
- * @param <T> no type in particular, except to match any executor
*/
-public abstract class AbstractSleighPcodeUseropDefinition<T>
- implements SleighPcodeUseropDefinition<T> {
+public abstract class AbstractSleighPcodeUseropDefinition implements SleighPcodeUseropDefinition {
/**
* A builder for a particular userop
@@ -36,14 +32,12 @@ public abstract class AbstractSleighPcodeUseropDefinition<T>
* @see SleighPcodeUseropDefinition.Factory
*/
public static class Builder implements BuilderStage1 {
- private final Factory factory;
private final String name;
private final Map<Integer, SignatureDef> definitions = new HashMap<>();
private final List<String> params = new ArrayList<>();
private final List<BodyFunc> body = new ArrayList<>();
- protected Builder(Factory factory, String name) {
- this.factory = factory;
+ protected Builder(String name) {
this.name = name;
params(OUT_SYMBOL_NAME);
@@ -78,34 +72,29 @@ public abstract class AbstractSleighPcodeUseropDefinition<T>
/**
* Build the actual definition
- *
* <p>
* NOTE: Compilation of the sleigh source is delayed until the first invocation, since the
* compiler must know about the varnodes used as parameters. TODO: There may be some way to
* template it at the p-code level instead of the Sleigh source level.
*
- * @param <T> no particular type, except to match the executor
* @return the definition
*/
@Override
- public <T> SleighPcodeUseropDefinition<T> build() {
+ public SleighPcodeUseropDefinition build() {
overload();
if (definitions.size() == 1) {
- return new FixedSleighPcodeUseropDefinition<T>(factory.language, name,
+ return new FixedSleighPcodeUseropDefinition(name,
definitions.values().iterator().next());
}
- return new OverloadedSleighPcodeUseropDefinition<>(factory.language, name,
- Map.copyOf(definitions));
+ return new OverloadedSleighPcodeUseropDefinition(name, Map.copyOf(definitions));
}
}
- protected final SleighLanguage language;
protected final String name;
protected final Map<List<Varnode>, PcodeProgram> cacheByArgs = new HashMap<>();
- protected AbstractSleighPcodeUseropDefinition(SleighLanguage language, String name) {
- this.language = language;
+ protected AbstractSleighPcodeUseropDefinition(String name) {
this.name = name;
}
@@ -119,6 +108,11 @@ public abstract class AbstractSleighPcodeUseropDefinition<T>
return false;
}
+ @Override
+ public boolean canInterrupt() {
+ return false;
+ }
+
@Override
public boolean hasSideEffects() {
return true;
@@ -142,23 +136,38 @@ public abstract class AbstractSleighPcodeUseropDefinition<T>
return true;
}
+ @Override
+ public boolean isOutSigned() {
+ return false;
+ }
+
+ @Override
+ public boolean isInSigned(int index) {
+ return false;
+ }
+
+ @Override
+ public Class<?> getOutputType() {
+ return null;
+ }
+
@Override
public Method getJavaMethod() {
return null;
}
@Override
- public PcodeUseropLibrary<T> getDefiningLibrary() {
+ public PcodeUseropLibrary<?> getDefiningLibrary() {
return null;
}
@Override
- public void execute(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library, PcodeOp op,
- Varnode outArg, List<Varnode> inArgs) {
+ public void execute(PcodeExecutor<Object> executor, PcodeUseropLibrary<Object> library,
+ PcodeOp op, Varnode outArg, List<Varnode> inArgs) {
List<Varnode> args = new ArrayList<>(inArgs.size() + 1);
args.add(outArg);
args.addAll(inArgs);
- PcodeProgram program = programFor(args, library);
+ PcodeProgram program = programFor(executor.language, args, library);
executor.execute(program, library);
}
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibrary.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibrary.java
index 073656deae..6d5d3e83b1 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
@@ -27,15 +27,16 @@ import java.util.stream.Stream;
import org.apache.commons.lang3.reflect.TypeUtils;
+import ghidra.lifecycle.Experimental;
import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.Varnode;
import utilities.util.AnnotationUtilities;
/**
* A userop library wherein Java methods are exported via a special annotation
- *
* <p>
* See {@code StandAloneEmuExampleScript} for an example of implementing a userop library.
*
@@ -212,13 +213,35 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
*/
protected static abstract class AnnotatedPcodeUseropDefinition<T>
implements PcodeUseropDefinition<T> {
+ static final Class<?>[] REQUIRED_SLEIGH_DEF_PARAMS = new Class<?>[] {
+ SleighPcodeUseropDefinition.BuilderStage1.class };
protected static boolean isPrimitive(Type type) {
return type instanceof Class<?> cls && cls.isPrimitive();
}
- protected static <T> AnnotatedPcodeUseropDefinition<T> create(PcodeUserop annot,
+ protected static <T> PcodeUseropDefinition<T> create(PcodeUserop annot,
AnnotatedPcodeUseropLibrary<T> library, Type opType, Lookup lookup, Method method) {
+ Class<?> returnType = method.getReturnType();
+ if (SleighPcodeUseropDefinition.class.isAssignableFrom(returnType)) {
+ if (!Arrays.equals(REQUIRED_SLEIGH_DEF_PARAMS, method.getParameterTypes())) {
+ throw new IllegalArgumentException("""
+ Method %s with @%s annotation returning a %s must only accept these \
+ parameters: %s""".formatted(method.getName(),
+ PcodeUserop.class.getSimpleName(),
+ SleighPcodeUseropDefinition.class.getSimpleName(),
+ List.of(REQUIRED_SLEIGH_DEF_PARAMS)));
+ }
+ try {
+ SleighPcodeUseropDefinition def =
+ (SleighPcodeUseropDefinition) method.invoke(library,
+ SleighPcodeUseropDefinition.FACTORY.define(method.getName()));
+ return def.cast();
+ }
+ catch (IllegalAccessException | InvocationTargetException e) {
+ throw new RuntimeException(e);
+ }
+ }
if (annot.variadic()) {
return new VariadicAnnotatedPcodeUseropDefinition<>(library, opType, lookup,
method, annot);
@@ -228,14 +251,22 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
}
@SuppressWarnings("unchecked")
- protected static <T> T fromPrimitive(Object value, int size,
+ protected static <T> T fromPrimitive(Object value, int size, boolean signed,
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 Byte v -> signed
+ ? arithmetic.fromConstSigned(v, size)
+ : arithmetic.fromConst(v, size);
+ case Short v -> signed
+ ? arithmetic.fromConstSigned(v, size)
+ : arithmetic.fromConst(v, size);
+ case Integer v -> signed
+ ? arithmetic.fromConstSigned(v, size)
+ : arithmetic.fromConst(v, size);
+ case Long v -> signed
+ ? arithmetic.fromConstSigned(v, size)
+ : 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);
@@ -246,9 +277,11 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
protected final Method method;
private final AnnotatedPcodeUseropLibrary<T> library;
private final boolean isFunctional;
+ private final boolean canInterrupt;
private final boolean hasSideEffects;
private final boolean modifiesContext;
private final boolean canInline;
+ private final boolean signed;
private final MethodHandle handle;
private int posExecutor = -1;
@@ -297,9 +330,11 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
}
initFinished();
this.isFunctional = annot.functional();
+ this.canInterrupt = annot.canInterrupt();
this.hasSideEffects = annot.hasSideEffects();
this.modifiesContext = annot.modifiesContext();
this.canInline = annot.canInline();
+ this.signed = annot.signed();
}
@Override
@@ -308,8 +343,8 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
}
@Override
- public void execute(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library,
- PcodeOp op, Varnode outVar, List<Varnode> inVars) {
+ public void execute(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library, PcodeOp op,
+ Varnode outVar, List<Varnode> inVars) {
validateInputs(inVars);
PcodeExecutorStatePiece<T, T> state = executor.getState();
@@ -336,7 +371,7 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
Object result = handle.invokeWithArguments(args);
if (result != null && outVar != null) {
state.setVar(outVar,
- fromPrimitive(result, outVar.getSize(), executor.getArithmetic()));
+ fromPrimitive(result, outVar.getSize(), signed, executor.getArithmetic()));
}
}
catch (PcodeExecutionException e) {
@@ -352,6 +387,11 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
return isFunctional;
}
+ @Override
+ public boolean canInterrupt() {
+ return canInterrupt;
+ }
+
@Override
public boolean hasSideEffects() {
return hasSideEffects;
@@ -367,6 +407,11 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
return canInline;
}
+ @Override
+ public boolean isOutSigned() {
+ return signed;
+ }
+
@Override
public Class<?> getOutputType() {
if (posOut == -1) {
@@ -415,6 +460,10 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
interface UseropInputParam {
int position();
+ default boolean signed() {
+ return false;
+ }
+
<T> Object convert(Varnode vn, PcodeExecutor<T> executor);
}
@@ -433,42 +482,51 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
}
}
- record ByteUseropInputParam(int position) implements UseropInputParam {
+ record ByteUseropInputParam(int position, boolean signed) 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);
+ T t = state.getVar(vn, executor.getReason());
+ return (byte) (signed
+ ? arithmetic.toLongSigned(t, Purpose.OTHER)
+ : arithmetic.toLong(t, Purpose.OTHER));
}
}
- record ShortUseropInputParam(int position) implements UseropInputParam {
+ record ShortUseropInputParam(int position, boolean signed) 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);
+ T t = state.getVar(vn, executor.getReason());
+ return (short) (signed
+ ? arithmetic.toLongSigned(t, Purpose.OTHER)
+ : arithmetic.toLong(t, Purpose.OTHER));
}
}
- record IntUseropInputParam(int position) implements UseropInputParam {
+ record IntUseropInputParam(int position, boolean signed) 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);
+ T t = state.getVar(vn, executor.getReason());
+ return (int) (signed
+ ? arithmetic.toLongSigned(t, Purpose.OTHER)
+ : arithmetic.toLong(t, Purpose.OTHER));
}
}
- record LongUseropInputParam(int position) implements UseropInputParam {
+ record LongUseropInputParam(int position, boolean signed) 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);
+ T t = state.getVar(vn, executor.getReason());
+ return signed
+ ? arithmetic.toLongSigned(t, Purpose.OTHER)
+ : arithmetic.toLong(t, Purpose.OTHER);
}
}
@@ -531,6 +589,8 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
@Override
protected void processNonAnnotatedParameter(Type declClsOpType, Type opType, int i,
Parameter p) {
+ OpInput annotation = p.getAnnotation(OpInput.class);
+ boolean signed = annotation == null ? OpInput.DEFAULT_SIGNED : annotation.signed();
Type pType = p.getParameterizedType();
if (TypeUtils.isAssignable(Varnode.class, pType)) {
paramsIn.add(new VarnodeUseropInputParam(i));
@@ -539,16 +599,16 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
paramsIn.add(new TValUseropInputParam(i));
}
else if (pType == byte.class) {
- paramsIn.add(new ByteUseropInputParam(i));
+ paramsIn.add(new ByteUseropInputParam(i, signed));
}
else if (pType == short.class) {
- paramsIn.add(new ShortUseropInputParam(i));
+ paramsIn.add(new ShortUseropInputParam(i, signed));
}
else if (pType == int.class) {
- paramsIn.add(new IntUseropInputParam(i));
+ paramsIn.add(new IntUseropInputParam(i, signed));
}
else if (pType == long.class) {
- paramsIn.add(new LongUseropInputParam(i));
+ paramsIn.add(new LongUseropInputParam(i, signed));
}
else if (pType == int[].class) {
paramsIn.add(new IntArrayUseropInputParam(i));
@@ -596,6 +656,11 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
public int getInputCount() {
return paramsIn.size();
}
+
+ @Override
+ public boolean isInSigned(int index) {
+ return paramsIn.get(index).signed();
+ }
}
/**
@@ -680,29 +745,35 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
public int getInputCount() {
return -1;
}
+
+ @Override
+ public boolean isInSigned(int index) {
+ return false;
+ }
}
/**
* An annotation to export a Java method as a userop in the library.
- *
* <p>
- * Ordinarily, each parameter receives an input to the userop. Each parameter may be annotated
- * with at most one of {@link OpExecutor}, {@link OpState}, {@link OpLibrary}, or
- * {@link OpOutput} to change what it receives. If {@link #variadic()} is false, non-annotated
- * parameters receive the inputs to the userop in matching order. Conventionally, annotated
- * parameters should be placed first or last. Parameters accepting inputs must have type either
- * {@link Varnode} or assignable from {@code T}. A parameter of type {@link Varnode} will
- * receive the input {@link Varnode}. A parameter that is assignable from {@code T} will receive
- * the input value. If it so happens that {@code T} is assignable from {@link Varnode}, the
- * parameter will receive the {@link Varnode}, not the value. <b>NOTE:</b> Receiving a value
- * instead of a variable may lose its size. Depending on the type of the value, that size may or
- * may not be recoverable.
- *
+ * This can annotate a Java callback userop or a Sleigh-defined userop.
+ * <p>
+ * For a Java callback, each parameter ordinarily receives an input to the userop. Each
+ * parameter may be annotated with at most one of {@link OpExecutor}, {@link OpState},
+ * {@link OpLibrary}, or {@link OpOutput} to change what it receives. If {@link #variadic()} is
+ * false, non-annotated parameters receive the inputs to the userop in matching order.
+ * Conventionally, annotated parameters should be placed first or last. Parameters accepting
+ * inputs must have type {@link Varnode}, a type assignable from {@code T}, or a primitive type,
+ * and may be annotated with {@link OpInput}. A parameter of type {@link Varnode} will receive
+ * the input {@link Varnode}. A parameter that is of primitive type or assignable from {@code T}
+ * will receive the input value. If it so happens that {@code T} is assignable from
+ * {@link Varnode}, the parameter will receive the {@link Varnode}, not the value. <b>NOTE:</b>
+ * Receiving a value instead of a variable may lose its size. Depending on the type of the
+ * value, that size may or may not be recoverable. Values passed as primitives imply an attempt
+ * to concretize the value.
* <p>
* If {@link #variadic()} is true, then a single non-annotated parameter receives all inputs in
* order. This parameter must have a type {@link Varnode}{@code []} to receive variables or have
* type assignable from {@code T[]} to receive values.
- *
* <p>
* Note that there is no annotation to receive the "thread," because threads are not a concept
* known to the p-code executor or userop libraries, in general. In most cases, receiving the
@@ -711,6 +782,13 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
* specific thread. That strategy should preserve compile-time type safety. Alternatively, you
* can receive the executor or state, cast it to your specific type, and use an accessor to get
* its thread.
+ * <p>
+ * For a Sleigh-defined userop, the method must return {@link SleighPcodeUseropDefinition} and
+ * accept a single parameter of type {@link BuilderStage1}. The method is invoked once at
+ * library construction. The method can use the builder to create the userop definition. The
+ * various attributes and attestations accepted by this annotation are currently ignored for
+ * Sleigh-defined userops. The various {@code Op}-prefixed annotations, e.g., {@link OpExecutor}
+ * have no effect on the single parameter and should not be applied.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@@ -722,7 +800,6 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
/**
* Set to true to attest that the userop is a pure function.
- *
* <p>
* An incorrect attestation can lead to erroneous execution results.
*
@@ -731,8 +808,21 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
boolean functional() default false;
/**
- * Set to false to attest the userop has no side effects.
+ * Set to false to attest that the userop will not interrupt execution.
+ * <p>
+ * This defaults to false, even though it seems unsafe to attest to no interrupts.
+ * Generally, this is about <em>expected</em> interruptions, not exceptions that occur
+ * because of buggy userop implementations. In general, userops that interrupt on purpose
+ * are uncommon. Userop authors may, at their discretion, adjust this attribute to ease
+ * debugging. If this userop can throw an exception and the emulator is meant to resume
+ * execution after handling it, this <em>must</em> be set to true.
*
+ * @see PcodeUseropLibrary.PcodeUseropDefinition#canInterrupt()
+ */
+ boolean canInterrupt() default false;
+
+ /**
+ * Set to false to attest the userop has no side effects.
* <p>
* An incorrect attestation can lead to erroneous execution results.
*
@@ -742,7 +832,6 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
/**
* Set to true to indicate the userop can modify the decode context.
- *
* <p>
* Failure to indicate context modifications can lead to erroneous decodes and thus
* incorrect execution results.
@@ -757,11 +846,17 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
* @see PcodeUseropLibrary.PcodeUseropDefinition#canInlinePcode()
*/
boolean canInline() default false;
+
+ /**
+ * Set true to indicate sign extension of the output.
+ *
+ * @see PcodeUseropLibrary.PcodeUseropDefinition#isOutSigned()
+ */
+ boolean signed() default true;
}
/**
* An annotation to receive the executor itself into a parameter
- *
* <p>
* The annotated parameter must have type {@link PcodeExecutor} with the same {@code <T>} as the
* class declaring the method.
@@ -773,7 +868,6 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
/**
* An annotation to receive the executor's state into a parameter
- *
* <p>
* The annotated parameter must have type {@link PcodeExecutorState} with the same {@code <T>}
* as the class declaring the method.
@@ -785,14 +879,12 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
/**
* An annotation to receive the complete library into a parameter
- *
* <p>
* Because the library defining the userop may be composed with other libraries, it is not
* sufficient to use the "{@code this}" reference to obtain the library. If the library being
* used for execution needs to be passed to a dependent component of execution, it must be the
* complete library, not just the one defining the userop. This annotation allows a userop
* definition to receive the complete library.
- *
* <p>
* The annotated parameter must have type {@link PcodeUseropLibrary} with the same {@code <T>}
* as the class declaring the method.
@@ -804,7 +896,6 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
/**
* An annotation to receive the output varnode into a parameter
- *
* <p>
* The annotated parameter must have type {@link Varnode} (or {@code int[]} for direct
* invocation when the output is a multi-precision integer}).
@@ -814,11 +905,45 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
public @interface OpOutput {
}
+ /**
+ * An annotation to receive an input into a parameter
+ * <p>
+ * Parameters without other annotations are assumed inputs, but this annotation permits further
+ * defining the behavior of that input. This is experimental. We need the feature, but we're not
+ * settled on how to indicate signedness of inputs.
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.PARAMETER)
+ @Experimental
+ public @interface OpInput {
+ boolean DEFAULT_SIGNED = false;
+ int DEFAULT_SLACK = 0;
+
+ /**
+ * Indicates the signedness of the input
+ *
+ * @see PcodeUseropLibrary.PcodeUseropDefinition#isInSigned(int)
+ */
+ boolean signed() default DEFAULT_SIGNED;
+
+ /**
+ * For parameters taking {@code int[]}, usually in a JIT-accelerated emulator, the number of
+ * slack elements to add.
+ * <p>
+ * {@code int[]} values have the elements in little-endian order. That is, the
+ * less-significant legs are in the lower indices. Slack legs are added at the
+ * most-significant end, i.e., at the upper indices. This is useful for algorithms that
+ * benefit from such extension.
+ *
+ * @return the number of slack elements
+ */
+ int slack() default DEFAULT_SLACK;
+ }
+
/**
* An annotation to receive the CALLOTHER p-code op into a parameter
- *
* <p>
- * The annotated parameter must have type {@link PcodeOp}).
+ * The annotated parameter must have type {@link PcodeOp}.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@@ -835,7 +960,7 @@ public abstract class AnnotatedPcodeUseropLibrary<T> extends DefaultPcodeUseropL
Class<? extends AnnotatedPcodeUseropLibrary<T>> cls = (Class) this.getClass();
Set<Method> methods;
synchronized (CACHE_BY_CLASS) {
- methods = CACHE_BY_CLASS.computeIfAbsent(cls, __ -> collectDefinitions(cls));
+ methods = CACHE_BY_CLASS.computeIfAbsent(cls, _ -> collectDefinitions(cls));
}
for (Method m : methods) {
ops.put(m.getName(), AnnotatedPcodeUseropDefinition
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/FixedSleighPcodeUseropDefinition.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/FixedSleighPcodeUseropDefinition.java
index 078af40d15..4106ff9bad 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/FixedSleighPcodeUseropDefinition.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/FixedSleighPcodeUseropDefinition.java
@@ -22,15 +22,12 @@ import ghidra.program.model.pcode.Varnode;
/**
* A Sleigh userop definition with one signature
- *
- * @param <T> no type in particular, except to match any executor
*/
-public class FixedSleighPcodeUseropDefinition<T> extends AbstractSleighPcodeUseropDefinition<T> {
+public class FixedSleighPcodeUseropDefinition extends AbstractSleighPcodeUseropDefinition {
protected final SignatureDef definition;
- protected FixedSleighPcodeUseropDefinition(SleighLanguage language, String name,
- SignatureDef definition) {
- super(language, name);
+ protected FixedSleighPcodeUseropDefinition(String name, SignatureDef definition) {
+ super(name);
this.definition = definition;
}
@@ -54,14 +51,10 @@ public class FixedSleighPcodeUseropDefinition<T> extends AbstractSleighPcodeUser
}
@Override
- public PcodeProgram programFor(List<Varnode> args, PcodeUseropLibrary<?> library) {
+ public PcodeProgram programFor(SleighLanguage language, List<Varnode> args,
+ PcodeUseropLibrary<?> library) {
return cacheByArgs.computeIfAbsent(args,
a -> SleighProgramCompiler.compileUserop(language, name, definition.signature(),
definition.generateBody(a), library, a));
}
-
- @Override
- public Class<?> getOutputType() {
- return null;
- }
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/OverloadedSleighPcodeUseropDefinition.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/OverloadedSleighPcodeUseropDefinition.java
index 63442b2fc1..c17609e0db 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/OverloadedSleighPcodeUseropDefinition.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/OverloadedSleighPcodeUseropDefinition.java
@@ -22,16 +22,13 @@ import ghidra.program.model.pcode.Varnode;
/**
* A Sleigh userop definition with multiple signatures
- *
- * @param <T> no type in particular, except to match any executor
*/
-public class OverloadedSleighPcodeUseropDefinition<T>
- extends AbstractSleighPcodeUseropDefinition<T> {
+public class OverloadedSleighPcodeUseropDefinition extends AbstractSleighPcodeUseropDefinition {
protected final Map<Integer, SignatureDef> definitions;
- protected OverloadedSleighPcodeUseropDefinition(SleighLanguage language, String name,
+ protected OverloadedSleighPcodeUseropDefinition(String name,
Map<Integer, SignatureDef> definitions) {
- super(language, name);
+ super(name);
this.definitions = definitions;
}
@@ -74,16 +71,12 @@ public class OverloadedSleighPcodeUseropDefinition<T>
}
@Override
- public PcodeProgram programFor(List<Varnode> args, PcodeUseropLibrary<?> library) {
+ public PcodeProgram programFor(SleighLanguage language, List<Varnode> args,
+ PcodeUseropLibrary<?> library) {
return cacheByArgs.computeIfAbsent(args, a -> {
SignatureDef definition = requireSignatureDef(a);
return SleighProgramCompiler.compileUserop(language, name, definition.signature(),
definition.generateBody(a), library, a);
});
}
-
- @Override
- public Class<?> getOutputType() {
- return null;
- }
}
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.java
index a29910e88a..add499216f 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
@@ -27,7 +27,6 @@ import ghidra.program.model.pcode.PcodeOp;
/**
* An interface that defines arithmetic p-code operations on values of type {@code T}.
- *
* <p>
* See {@link BytesPcodeArithmetic} for the typical pattern when implementing an arithmetic. There
* are generally two cases: 1) Where endianness matters, 2) Where endianness does not matter. The
@@ -90,13 +89,11 @@ public interface PcodeArithmetic<T> {
/**
* Get the endianness of this arithmetic
- *
* <p>
* Often T is a byte array, or at least represents one abstractly. Ideally, it is an array where
* each element is an abstraction of a byte. If that is the case, then the arithmetic likely has
* to interpret those bytes as integral values according to an endianness. This should return
* that endianness.
- *
* <p>
* If the abstraction has no notion of endianness, return null. In that case, the both
* {@link #fromConst(BigInteger, int, boolean)} and {@link #fromConst(long, int)} must be
@@ -110,7 +107,6 @@ public interface PcodeArithmetic<T> {
/**
* Apply a unary operator to the given input
- *
* <p>
* Note the sizes of variables are given, because values don't necessarily have an intrinsic
* size. For example, a {@link BigInteger} may have a minimum encoding size, but that does not
@@ -129,7 +125,6 @@ public interface PcodeArithmetic<T> {
/**
* Apply a unary operator to the given input
- *
* <p>
* This provides the full p-code op, allowing deeper inspection of the code. For example, an
* arithmetic may wish to distinguish immediate (constant) values from variables. By default,
@@ -148,7 +143,6 @@ public interface PcodeArithmetic<T> {
/**
* Apply a binary operator to the given inputs
- *
* <p>
* Note the sizes of variables are given, because values don't necessarily have an intrinsic
* size. For example, a {@link BigInteger} may have a minimum encoding size, but that does not
@@ -169,7 +163,6 @@ public interface PcodeArithmetic<T> {
/**
* Apply a binary operator to the given input
- *
* <p>
* This provides the full p-code op, allowing deeper inspection of the code. For example, an
* arithmetic may wish to distinguish immediate (constant) values from variables. By default,
@@ -190,7 +183,6 @@ public interface PcodeArithmetic<T> {
/**
* Apply the {@link PcodeOp#PTRADD} operator to the given inputs
- *
* <p>
* The "pointer add" op takes three operands: base, index, size; and is used as a more compact
* representation of array index address computation. The {@code size} operand must be constant.
@@ -198,7 +190,6 @@ public interface PcodeArithmetic<T> {
* of its first element is {@code base}. The decompiler would likely render the
* {@link PcodeOp#PTRADD} op as {@code &arr[index]}. An equivalent SLEIGH expression is
* {@code base + index*size}.
- *
* <p>
* NOTE: This op is always a result of decompiler simplification, not low p-code generation, and
* so are not ordinarily used by a {@link PcodeExecutor}.
@@ -221,7 +212,6 @@ public interface PcodeArithmetic<T> {
/**
* Apply the {@link PcodeOp#PTRSUB} operator to the given inputs
- *
* <p>
* The "pointer subfield" op takes two operands: base, offset; and is used as a more specific
* representation of structure field address computation. Its behavior is exactly equivalent to
@@ -229,7 +219,6 @@ public interface PcodeArithmetic<T> {
* located {@code inOffset} bytes into the structure, and {@code st} has the value {@code base}.
* The decompiler would likely render the {@link PcodeOp#PTRSUB} op as {@code &st->f}. An
* equivalent SLEIGH expression is {@code base + offset}.
- *
* <p>
* NOTE: This op is always a result of decompiler simplification, not low p-code generation, and
* so are not ordinarily used by a {@link PcodeExecutor}.
@@ -247,7 +236,6 @@ public interface PcodeArithmetic<T> {
/**
* Apply any modifications before a value is stored
- *
* <p>
* This implements any abstractions associated with {@link PcodeOp#STORE}. This is called on the
* offset and the value before the value is actually stored into the state. <b>NOTE:</b> STORE
@@ -264,7 +252,6 @@ public interface PcodeArithmetic<T> {
/**
* 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.
@@ -282,7 +269,6 @@ public interface PcodeArithmetic<T> {
/**
* 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. <b>NOTE:</b>
@@ -299,7 +285,6 @@ public interface PcodeArithmetic<T> {
/**
* 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.
@@ -334,6 +319,17 @@ public interface PcodeArithmetic<T> {
return fromConst(Byte.toUnsignedLong(value), size);
}
+ /**
+ * Convert a {@code byte} to {@code T}, with signed extension
+ *
+ * @param value the constant value
+ * @param size the size in bytes
+ * @return the value
+ */
+ default T fromConstSigned(byte value, int size) {
+ return fromConstSigned((long) value, size);
+ }
+
/**
* Convert a {@code short} to {@code T}, with unsigned extension
*
@@ -345,6 +341,17 @@ public interface PcodeArithmetic<T> {
return fromConst(Short.toUnsignedLong(value), size);
}
+ /**
+ * Convert a {@code short} to {@code T}, with signed extension
+ *
+ * @param value the constant value
+ * @param size the size in bytes
+ * @return the value
+ */
+ default T fromConstSigned(short value, int size) {
+ return fromConst((long) value, size);
+ }
+
/**
* Convert an {@code int} to {@code T}, with unsigned extension
*
@@ -357,8 +364,19 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert the given constant concrete value to type {@code T} having the given size.
+ * Convert an {@code int} to {@code T}, with signed extension
*
+ * @param value the constant value
+ * @param size the size in bytes
+ * @return the value
+ */
+ default T fromConstSigned(int value, int size) {
+ return fromConst((long) value, size);
+ }
+
+ /**
+ * Convert the given constant concrete value to type {@code T} having the given size, with
+ * unsigned extension.
* <p>
* Note that the size may not be applicable to {@code T}. It is given to ensure the value can be
* held in a variable of that size when passed to downstream operators or stored in the executor
@@ -373,10 +391,28 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert a {@code float} to {@code T}
+ * Convert the given constant concrete value to type {@code T} having the given size, with
+ * signed extension.
+ * <p>
+ * Note that the size may not be applicable to {@code T}. It is given to ensure the value can be
+ * held in a variable of that size when passed to downstream operators or stored in the executor
+ * state.
*
+ * @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 fromConstSigned(long value, int size) {
+ byte[] arr8 = Utils.longToBytes(value, Long.BYTES, getEndian().isBigEndian());
+ byte[] arrFull = BytesPcodeArithmetic.forEndian(getEndian().isBigEndian())
+ .unaryOp(PcodeOp.INT_SEXT, size, Long.BYTES, arr8);
+ return fromConst(arrFull);
+ }
+
+ /**
+ * Convert a {@code float} to {@code T}
* <p>
- * If size is not {@value Float#BYTES}, bytes are truncated or passed with 0s, according to
+ * If size is not {@value Float#BYTES}, bytes are truncated or padded with 0s, according to
* machine endianness.
*
* @param value the constant value
@@ -389,9 +425,8 @@ public interface PcodeArithmetic<T> {
/**
* Convert a {@code double} to {@code T}
- *
* <p>
- * If size is not {@value Double#BYTES}, bytes are truncated or passed with 0s, according to
+ * If size is not {@value Double#BYTES}, bytes are truncated or padded with 0s, according to
* machine endianness.
*
* @param value the constant value
@@ -404,9 +439,8 @@ public interface PcodeArithmetic<T> {
/**
* Convert a {@code boolean} to {@code T}
- *
* <p>
- * {@code true} is represented as 1, and {@code false} as 0, padded to the given size.
+ * {@code true} is represented as 1, and {@code false} as 0, zero extended to the given size.
*
* @param value the constant value
* @param size the size in bytes
@@ -417,8 +451,8 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert the given constant concrete value to type {@code T} having the given size.
- *
+ * Convert the given constant concrete value to type {@code T} having the given size, using
+ * signed extension.
* <p>
* Note that the size may not be applicable to {@code T}. It is given to ensure the value can be
* held in a variable of that size when passed to downstream operators or stored in the executor
@@ -437,7 +471,8 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert the given constant concrete register value to type {@code T}
+ * Convert the given constant concrete register value to type {@code T}, using unsigned
+ * extension
*
* @param value the register value
* @return the value as a {@code T}
@@ -448,8 +483,8 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert the given constant concrete value to type {@code T} having the given size.
- *
+ * Convert the given constant concrete value to type {@code T} having the given size, using
+ * signed extension.
* <p>
* The value is assumed <em>not</em> to be for the disassembly context register.
*
@@ -463,8 +498,7 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert the given concrete address to type {@code T}.
- *
+ * Convert the given concrete address to type {@code T}, using unsigned extension.
* <p>
* The value will have the pointer size of the address' space. Other than deriving that size,
* the returned value has nothing to do with the address space.
@@ -521,7 +555,6 @@ public interface PcodeArithmetic<T> {
/**
* Convert, if possible, the given abstract value to a concrete big integer
- *
* <p>
* If the conversion is not possible, throw an exception.
*
@@ -537,8 +570,7 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert, if possible, the given abstract value to a concrete long
- *
+ * Convert, if possible, the given abstract value to a concrete long, using unsigned extension.
* <p>
* If the conversion is not possible, throw an exception.
*
@@ -554,8 +586,28 @@ public interface PcodeArithmetic<T> {
}
/**
- * Convert, if possible, the given abstract value to a concrete float
+ * Convert, if possible, the given abstract value to a concrete long, using signed extension.
+ * <p>
+ * If the conversion is not possible, throw an exception.
*
+ * @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 long toLongSigned(T value, Purpose purpose) {
+ byte[] concrete = toConcrete(value, purpose);
+ long u = Utils.bytesToLong(concrete, concrete.length,
+ purpose == Purpose.CONTEXT || getEndian().isBigEndian());
+ int shamt = (Long.BYTES - concrete.length) * 8;
+ if (shamt <= 0) {
+ return u;
+ }
+ return (u << shamt) >> shamt;
+ }
+
+ /**
+ * 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.
@@ -571,7 +623,6 @@ public interface PcodeArithmetic<T> {
/**
* 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.
@@ -599,7 +650,6 @@ public interface PcodeArithmetic<T> {
/**
* Get the size in bytes, if possible, of the given abstract value
- *
* <p>
* If the abstract value does not conceptually have a size, throw an exception.
*
@@ -610,7 +660,6 @@ public interface PcodeArithmetic<T> {
/**
* Get the size in bytes, if possible, of the given abstract value, as an abstract value
- *
* <p>
* The returned size should have a size of {@link #SIZEOF_SIZEOF}.
*
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.java
index e9496896d0..d244c8db33 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
@@ -16,7 +16,6 @@
package ghidra.pcode.exec;
import java.util.List;
-import java.util.Map;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.emu.PcodeEmulator;
@@ -24,6 +23,7 @@ import ghidra.pcode.error.LowlevelError;
import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.pcode.opbehavior.*;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressSpace;
@@ -33,7 +33,6 @@ import ghidra.program.model.pcode.Varnode;
/**
* An executor of p-code programs
- *
* <p>
* This is the kernel of Sleigh expression evaluation and p-code emulation. For a complete example
* of a p-code emulator, see {@link PcodeEmulator}.
@@ -41,6 +40,13 @@ import ghidra.program.model.pcode.Varnode;
* @param <T> the type of values processed by the executor
*/
public class PcodeExecutor<T> {
+ public static final int OPIDX_BRANCH_TARGET = 0;
+ public static final int OPIDX_CBRANCH_PRED = 1;
+ public static final int OPIDX_DEFEF_SPACE = 0;
+ public static final int OPIDX_DEREF_OFFSET = 1;
+ public static final int OPIDX_STORE_VALUE = 2;
+ public static final int OPIDX_CALLOTHER_OP_NUMBER = 0;
+
protected final SleighLanguage language;
protected final PcodeArithmetic<T> arithmetic;
protected final PcodeExecutorState<T> state;
@@ -131,7 +137,7 @@ public class PcodeExecutor<T> {
* @return the frame
*/
public PcodeFrame begin(PcodeProgram program) {
- return begin(program.code, program.useropNames);
+ return begin(program.code, program.userops);
}
/**
@@ -142,38 +148,35 @@ public class PcodeExecutor<T> {
* @return the frame
*/
public PcodeFrame execute(PcodeProgram program, PcodeUseropLibrary<T> library) {
- return execute(program.code, program.useropNames, library);
+ return execute(program.code, library);
}
/**
* Begin execution of a list of p-code ops
*
* @param code the ops
- * @param useropNames the map of userop numbers to names
+ * @param userops the map of userop symbols
* @return the frame
*/
- public PcodeFrame begin(List<PcodeOp> code, Map<Integer, String> useropNames) {
- return new PcodeFrame(language, code, useropNames);
+ public PcodeFrame begin(List<PcodeOp> code, PcodeUseropSymbolMap userops) {
+ return new PcodeFrame(language, code, userops);
}
/**
* Execute a list of p-code ops
*
* @param code the ops
- * @param useropNames the map of userop numbers to names
* @param library the library of userops
* @return the frame
*/
- public PcodeFrame execute(List<PcodeOp> code, Map<Integer, String> useropNames,
- PcodeUseropLibrary<T> library) {
- PcodeFrame frame = begin(code, useropNames);
+ public PcodeFrame execute(List<PcodeOp> code, PcodeUseropLibrary<T> library) {
+ PcodeFrame frame = begin(code, library.getSymbols(language));
finish(frame, library);
return frame;
}
/**
* Finish execution of a frame
- *
* <p>
* TODO: This is not really sufficient for continuation after a break, esp. if that break occurs
* within a nested call back into the executor. This would likely become common when using pCode
@@ -272,7 +275,6 @@ public class PcodeExecutor<T> {
/**
* Assert that a varnode is constant and get its value as an integer.
- *
* <p>
* Here "constant" means a literal or immediate value. It does not read from the state.
*
@@ -344,7 +346,7 @@ public class PcodeExecutor<T> {
* @return the address space (derived from const input 0)
*/
protected AddressSpace getLoadStoreSpace(PcodeOp op) {
- int spaceID = getIntConst(op.getInput(0));
+ int spaceID = getIntConst(op.getInput(OPIDX_DEFEF_SPACE));
return language.getAddressFactory().getAddressSpace(spaceID);
}
@@ -355,7 +357,7 @@ public class PcodeExecutor<T> {
* @return the offset varnode (input 1)
*/
protected Varnode getLoadStoreOffset(PcodeOp op) {
- return op.getInput(1);
+ return op.getInput(OPIDX_DEREF_OFFSET);
}
/**
@@ -406,7 +408,7 @@ public class PcodeExecutor<T> {
* @return the value varnode (input 2)
*/
protected Varnode getStoreValue(PcodeOp op) {
- return op.getInput(2);
+ return op.getInput(OPIDX_STORE_VALUE);
}
/**
@@ -429,7 +431,6 @@ public class PcodeExecutor<T> {
/**
* Extension point: Called when execution branches to a target address
- *
* <p>
* NOTE: This is <em>not</em> called for the fall-through case
*
@@ -441,7 +442,6 @@ public class PcodeExecutor<T> {
/**
* 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.
@@ -456,7 +456,6 @@ public class PcodeExecutor<T> {
/**
* Set the state's pc to the given offset and finish the frame
- *
* <p>
* This implements only part of the p-code control flow semantics. An emulator must also
* override {@link #branchToAddress(PcodeOp, Address)}, so that it can update its internal
@@ -492,12 +491,11 @@ public class PcodeExecutor<T> {
* @return the target address (input 0's address)
*/
protected Address getBranchTarget(PcodeOp op) {
- return op.getInput(0).getAddress();
+ return op.getInput(OPIDX_BRANCH_TARGET).getAddress();
}
/**
* Perform the actual logic of a branch p-code op
- *
* <p>
* This is a separate method, so that overriding {@link #executeBranch(PcodeOp, PcodeFrame)}
* does not implicitly modify {@link #executeConditionalBranch(PcodeOp, PcodeFrame)}.
@@ -518,7 +516,6 @@ public class PcodeExecutor<T> {
/**
* Execute a branch
- *
* <p>
* This merely defers to {@link #doExecuteBranch(PcodeOp, PcodeFrame)}. To instrument the
* operation, override this. To modify or instrument branching in general, override
@@ -540,7 +537,7 @@ public class PcodeExecutor<T> {
* @return the predicate varnode (input 1)
*/
protected Varnode getConditionalBranchPredicate(PcodeOp op) {
- return op.getInput(1);
+ return op.getInput(OPIDX_CBRANCH_PRED);
}
/**
@@ -565,12 +562,11 @@ public class PcodeExecutor<T> {
* @return the target varnode (input 0)
*/
protected Varnode getIndirectBranchTarget(PcodeOp op) {
- return op.getInput(0);
+ return op.getInput(OPIDX_BRANCH_TARGET);
}
/**
* Check and correct the given target address, if it resides in "NO ADDRESS" space.
- *
* <p>
* At some point, we made a change to set the "target address" of compiled p-code userops to
* {@link Address#NO_ADDRESS} instead of pretending its at {@code ram:00000000}. This is
@@ -592,7 +588,6 @@ public class PcodeExecutor<T> {
/**
* Perform the actual logic of an indirect branch p-code op
- *
* <p>
* This is a separate method, so that overriding
* {@link #executeIndirectBranch(PcodeOp, PcodeFrame)} does not implicitly modify
@@ -613,7 +608,6 @@ public class PcodeExecutor<T> {
/**
* Execute an indirect branch
- *
* <p>
* This merely defers to {@link #doExecuteIndirectBranch(PcodeOp, PcodeFrame)}. To instrument
* the operation, override this. To modify or instrument indirect branching in general, override
@@ -670,7 +664,7 @@ public class PcodeExecutor<T> {
* @return the userop number (const input 0)
*/
protected int getCallotherOpNumber(PcodeOp op) {
- return getIntConst(op.getInput(0));
+ return getIntConst(op.getInput(OPIDX_CALLOTHER_OP_NUMBER));
}
/**
@@ -696,7 +690,6 @@ public class PcodeExecutor<T> {
/**
* Extension point: Behavior when a userop definition was not found in the library
- *
* <p>
* The default behavior is to throw a {@link SleighLinkException}.
*
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutorStatePiece.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutorStatePiece.java
index ccc8095514..f5577b171d 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutorStatePiece.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExecutorStatePiece.java
@@ -366,7 +366,6 @@ public interface PcodeExecutorStatePiece<A, T> {
/**
* Erase the entire state or piece
- *
* <p>
* This is generally only useful when the state is itself a cache to another object. This will
* ensure the state is reading from that object rather than a stale cache. If this is not a
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExpression.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExpression.java
index 9d9a3e7971..cec82bfd5a 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExpression.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/PcodeExpression.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,10 +16,9 @@
package ghidra.pcode.exec;
import java.util.List;
-import java.util.Map;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
-import ghidra.pcodeCPort.slghsymbol.UserOpSymbol;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.pcode.PcodeOp;
/**
@@ -55,11 +54,11 @@ public class PcodeExpression extends PcodeProgram {
*
* @param language the language that generated the p-code
* @param code the list of p-code ops
- * @param useropSymbols a map of expected userop symbols
+ * @param userops a map of expected userop symbols
*/
protected PcodeExpression(SleighLanguage language, List<PcodeOp> code,
- Map<Integer, UserOpSymbol> useropSymbols) {
- super(language, code, useropSymbols);
+ PcodeUseropSymbolMap userops) {
+ super(language, code, userops);
}
// TODO: One that can take a library, and compose the result into it
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.java
index ac486a9cb9..1fe4e10205 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
@@ -16,26 +16,25 @@
package ghidra.pcode.exec;
import java.util.List;
-import java.util.Map;
import ghidra.app.plugin.processors.sleigh.template.OpTpl;
import ghidra.app.util.pcode.AbstractAppender;
import ghidra.app.util.pcode.AbstractPcodeFormatter;
import ghidra.pcode.emulate.EmulateInstructionStateModifier;
import ghidra.pcode.error.LowlevelError;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.lang.Language;
import ghidra.program.model.pcode.PcodeOp;
+import ghidra.program.model.pcode.SequenceNumber;
/**
* The executor's internal counter
- *
* <p>
* To distinguish the program counter of a p-code program from the program counter of the machine it
* models, we address p-code ops by "index." When derived from an instruction, the address and index
- * together form the "sequence number." Because the executor care's not about the derivation of a
+ * together form the "sequence number." Because the executor cares not about the derivation of a
* p-code program, it counts through indices. The frame carries with it the p-code ops comprising
* its current p-code program.
- *
* <p>
* A p-code emulator feeds p-code to an executor by decoding one instruction at a time. Thus, the
* "current p-code program" comprises only those ops generated by a single instruction. Or else, it
@@ -43,6 +42,11 @@ import ghidra.program.model.pcode.PcodeOp;
* program by falling-through, i.e., stepping past the final op, or by branching externally, i.e.,
* to a different machine instruction. The emulator must then update its program counter accordingly
* and proceed to the next instruction.
+ * <p>
+ * Methods receiving a frame should use it only for the userop names, usually to fabricate a sub
+ * frame. Other than the executor, things should generally not access its code. If a {@link PcodeOp}
+ * is provided to the same method, generally that is the only op this frame is guaranteed to
+ * contain. The execution engine <em>is not</em> required to provide the surrounding ops.
*/
public class PcodeFrame {
protected class MyAppender extends AbstractAppender<String> {
@@ -83,6 +87,8 @@ public class PcodeFrame {
else {
buf.append(" ");
}
+ SequenceNumber seq = code.get(i).getSeqnum();
+ buf.append(seq.getTarget()).append(".").append(seq.getTime()).append(": ");
}
protected void endLine() {
@@ -98,7 +104,7 @@ public class PcodeFrame {
if (name != null) {
return name;
}
- return useropNames.get(id);
+ return userops.getUseropName(id);
}
@Override
@@ -128,7 +134,7 @@ public class PcodeFrame {
private final Language language;
private final List<PcodeOp> code;
- private final Map<Integer, String> useropNames;
+ private final PcodeUseropSymbolMap userops;
private int count = 0;
private int index = 0;
@@ -136,7 +142,6 @@ public class PcodeFrame {
/**
* Construct a frame of p-code execution
- *
* <p>
* The passed in code should be an immutable list. It is returned directly by
* {@link #getCode()}, which would otherwise allow mutation. The frame does not create its own
@@ -145,12 +150,12 @@ public class PcodeFrame {
*
* @param language the language to which the program applies
* @param code the program's p-code
- * @param useropNames a map of additional sleigh/p-code userops linked to the program
+ * @param userops a map of additional sleigh/p-code userops linked to the program
*/
- public PcodeFrame(Language language, List<PcodeOp> code, Map<Integer, String> useropNames) {
+ public PcodeFrame(Language language, List<PcodeOp> code, PcodeUseropSymbolMap userops) {
this.language = language;
this.code = code;
- this.useropNames = useropNames;
+ this.userops = userops;
}
@Override
@@ -160,7 +165,6 @@ public class PcodeFrame {
/**
* Get and reset the number of p-code ops executed
- *
* <p>
* Contrast this to {@link #index()}, which marks the next op to be executed. This counts the
* number of ops executed, which will differ from index when an internal branch is taken.
@@ -175,7 +179,6 @@ public class PcodeFrame {
/**
* The index of the <em>next</em> p-code op to be executed
- *
* <p>
* If the last p-code op resulted in a branch, this will instead return -1.
*
@@ -190,7 +193,6 @@ public class PcodeFrame {
/**
* Get the op at the current index, and then advance that index
- *
* <p>
* This is used in the execution loop to retrieve each op to execute
*
@@ -227,21 +229,18 @@ public class PcodeFrame {
* @return the name of the userop, as expressed in the Sleigh source
*/
public String getUseropName(int userop) {
- return useropNames.get(userop);
+ return userops.getUseropName(userop);
}
/**
- * Get the map of userop numbers to names
- *
- * @return the map
+ * {@return the map of userop symbols}
*/
- public Map<Integer, String> getUseropNames() {
- return useropNames;
+ public PcodeUseropSymbolMap getUserops() {
+ return userops;
}
/**
* Check if the index has advanced past the end of the p-code program
- *
* <p>
* If the index has advanced beyond the program, it implies the program has finished executing.
* In the case of instruction emulation, no branch was encountered. The machine should advance
@@ -257,7 +256,6 @@ public class PcodeFrame {
/**
* Check if the p-code program has executed a branch
- *
* <p>
* Branches can be internal, i.e., within the current program, or external, i.e., to another
* machine instructions. This refers strictly to the latter.
@@ -283,7 +281,6 @@ public class PcodeFrame {
/**
* Perform an internal branch, relative to the <em>current op</em>.
- *
* <p>
* Because index advances before execution of each op, the index is adjusted by an extra -1.
*
@@ -324,7 +321,6 @@ public class PcodeFrame {
/**
* Get the index of the last (branch) op executed
- *
* <p>
* The behavior here is a bit strange for compatibility with
* {@link EmulateInstructionStateModifier}. If the p-code program (likely derived from a machine
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.java
index 9ef11c988b..04c62bf1ba 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
@@ -16,14 +16,13 @@
package ghidra.pcode.exec;
import java.io.IOException;
-import java.util.*;
-import java.util.Map.Entry;
+import java.util.List;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.app.plugin.processors.sleigh.template.OpTpl;
import ghidra.app.util.pcode.AbstractAppender;
import ghidra.app.util.pcode.AbstractPcodeFormatter;
-import ghidra.pcodeCPort.slghsymbol.UserOpSymbol;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.program.model.lang.*;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.Program;
@@ -68,7 +67,7 @@ public class PcodeProgram {
if (name != null) {
return name;
}
- return program.useropNames.get(id);
+ return program.getUseropName(id);
}
@Override
@@ -141,7 +140,7 @@ public class PcodeProgram {
throw new IllegalArgumentException("Instruction must be parsed using Sleigh");
}
PcodeOp[] pcode = instruction.getPcode(includeOverrides);
- return new PcodeProgram(slang, List.of(pcode), Map.of());
+ return new PcodeProgram(slang, List.of(pcode), PcodeUseropSymbolMap.EMPTY);
}
/**
@@ -163,35 +162,26 @@ public class PcodeProgram {
InjectContext ctx = library.buildInjectContext();
InjectPayload payload = library.getPayload(type, name);
PcodeOp[] pcode = payload.getPcode(program, ctx);
- return new PcodeProgram((SleighLanguage) program.getLanguage(), List.of(pcode), Map.of());
+ return new PcodeProgram((SleighLanguage) program.getLanguage(), List.of(pcode),
+ PcodeUseropSymbolMap.EMPTY);
}
protected final SleighLanguage language;
protected final List<PcodeOp> code;
- protected final Map<Integer, String> useropNames;
+ protected final PcodeUseropSymbolMap userops;
/**
* Construct a p-code program with the given bindings
*
* @param language the language that generated the p-code
* @param code the list of p-code ops
- * @param useropSymbols a map of expected userop symbols
+ * @param userops a map of expected userop symbols
*/
protected PcodeProgram(SleighLanguage language, List<PcodeOp> code,
- Map<Integer, UserOpSymbol> useropSymbols) {
+ PcodeUseropSymbolMap userops) {
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();
- if (index < langOpCount) {
- useropNames.put(index, language.getUserDefinedOpName(index));
- }
- else {
- useropNames.put(index, ent.getValue().getName());
- }
- }
+ this.userops = userops;
}
/**
@@ -204,7 +194,7 @@ public class PcodeProgram {
assert !code.isEmpty();
this.language = program.language;
this.code = code;
- this.useropNames = program.useropNames;
+ this.userops = program.userops;
}
/**
@@ -216,6 +206,9 @@ public class PcodeProgram {
return language;
}
+ /**
+ * {@return the p-code ops of this program}
+ */
public List<PcodeOp> getCode() {
return code;
}
@@ -245,40 +238,42 @@ public class PcodeProgram {
return format();
}
+ /**
+ * For display purposes, list the code
+ *
+ * @param numberOps true to include op numbers
+ * @return the formatted listing
+ */
public String format(boolean numberOps) {
return new MyFormatter(this, numberOps).formatOps(language, code);
}
+ /**
+ * For display purposes, list the code without op numbers
+ *
+ * @return the formatted listing
+ */
public String format() {
return format(false);
}
+ /**
+ * Get the name of a userop by number
+ *
+ * @param opNo the userop number
+ * @return the name
+ */
public String getUseropName(int opNo) {
- if (opNo < language.getNumberOfUserDefinedOpNames()) {
- return language.getUserDefinedOpName(opNo);
- }
- return useropNames.get(opNo);
+ return userops.getUseropName(opNo);
}
/**
- * For testing/debug only: Get the userop number for a given name
+ * Get the userop index for a given name
*
- * @implNote There is no index by name, so this exhaustively searches the language- and
- * library-defined userops.
* @param name the name
- * @return the number, or -1 if not found
+ * @return the index, or -1 if not found
*/
public int getUseropNumber(String name) {
- for (int i = 0; i < language.getNumberOfUserDefinedOpNames(); i++) {
- if (name.equals(language.getUserDefinedOpName(i))) {
- return i;
- }
- }
- for (Entry<Integer, String> ent : useropNames.entrySet()) {
- if (name.equals(ent.getValue())) {
- return ent.getKey();
- }
- }
- return -1;
+ return userops.getUseropIndex(name);
}
}
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.java
index 7dfc73c216..3aa121d21b 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
@@ -17,20 +17,22 @@ package ghidra.pcode.exec;
import java.lang.reflect.*;
import java.util.*;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.reflect.TypeUtils;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
+import ghidra.app.plugin.processors.sleigh.symbol.UseropSymbol;
+import ghidra.lifecycle.Internal;
import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.OpOutput;
import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary.PcodeUserop;
import ghidra.pcodeCPort.slghsymbol.UserOpSymbol;
+import ghidra.program.model.lang.PcodeParser;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.Varnode;
-import ghidra.sleigh.grammar.Location;
/**
* A "library" of p-code userops available to a p-code executor
- *
* <p>
* The library can provide definitions of p-code userops already declared by the executor's language
* as well as completely new userops accessible to Sleigh/p-code later compiled for the executor.
@@ -39,6 +41,99 @@ import ghidra.sleigh.grammar.Location;
* @param <T> the type of values accepted by the p-code userops.
*/
public interface PcodeUseropLibrary<T> {
+
+ /**
+ * A store of userop symbols, retrievable by index or name
+ *
+ * @param language the language whose symbols are incorporated into retrieval
+ * @param byIndex the symbols by index, excluding those in the language already
+ * @param byName the symbols by name, excluding those in the language already
+ */
+ record PcodeUseropSymbolMap(SleighLanguage language, Map<Integer, UserOpSymbol> byIndex,
+ Map<String, UserOpSymbol> byName) {
+ public PcodeUseropSymbolMap {
+ if (!byIndex.isEmpty() || !byName.isEmpty()) {
+ Objects.requireNonNull(language);
+ }
+ }
+
+ /**
+ * The empty set of symbols
+ */
+ public static final PcodeUseropSymbolMap EMPTY =
+ new PcodeUseropSymbolMap(null, Map.of(), Map.of());
+
+ private static Map<String, UserOpSymbol> byName(Map<Integer, UserOpSymbol> byIndex) {
+ return byIndex.values()
+ .stream()
+ .collect(Collectors.toMap(s -> s.getName(), s -> s));
+ }
+
+ /**
+ * Construct a store from the language and symbols by index
+ * <p>
+ * This constructor re-indexes by name as well to create the full store
+ *
+ * @param language the language whose symbols are incorporated into retrieval
+ * @param byIndex the symbols by index, excluding those in the language already
+ */
+ public PcodeUseropSymbolMap(SleighLanguage language, Map<Integer, UserOpSymbol> byIndex) {
+ this(language, byIndex, byName(byIndex));
+ }
+
+ /**
+ * Get the name of a userop by its index, whether from the language or library
+ *
+ * @param index the index
+ * @return the name, or null
+ */
+ public String getUseropName(int index) {
+ if (language == null) {
+ return null;
+ }
+ if (index < language.getNumberOfUserDefinedOpNames()) {
+ return language.getUserDefinedOpName(index);
+ }
+ UserOpSymbol symbol = byIndex.get(index);
+ return symbol == null ? null : symbol.getName();
+ }
+
+ /**
+ * Get the index of a userop by its name, whether from the language or library
+ *
+ * @param name the name
+ * @return the index, or -1
+ */
+ public int getUseropIndex(String name) {
+ if (language == null) {
+ return -1;
+ }
+ // Oof. UseropSymbol and UserOpSymbol in the same source file!
+ if (language.getSymbolTable().findSymbol(name) instanceof UseropSymbol userop) {
+ return userop.getIndex();
+ }
+ UserOpSymbol symbol = byName.get(name);
+ return symbol == null ? -1 : symbol.getIndex();
+ }
+
+ /**
+ * Add the library symbols to a given parser
+ *
+ * @param parser the parser whose table to populate
+ */
+ public void addToParser(PcodeParser parser) {
+ for (UserOpSymbol sym : byIndex.values()) {
+ parser.addSymbol(sym);
+ }
+ }
+ }
+
+ /**
+ * A cache of symbols per library
+ */
+ @Internal
+ Map<PcodeUseropLibrary<?>, SymbolsCache> SYMBOL_CACHE = new WeakHashMap<>();
+
/**
* The class of the empty userop library.
*
@@ -58,7 +153,6 @@ public interface PcodeUseropLibrary<T> {
/**
* Get the type {@code T} for the given class
- *
* <p>
* If the class does not implement {@link PcodeUseropLibrary}, this returns null. If it does,
* but no arguments are given (i.e., it implements the raw type), this return {@link Object}.
@@ -80,7 +174,6 @@ public interface PcodeUseropLibrary<T> {
/**
* The empty userop library.
- *
* <p>
* Executors cannot accept {@code null} libraries. Instead, give it this empty library. To
* satisfy Java's type checker, you may use {@link #nil()} instead.
@@ -106,7 +199,6 @@ public interface PcodeUseropLibrary<T> {
interface PcodeUseropDefinition<T> {
/**
* Get the name of the userop.
- *
* <p>
* This is the symbol assigned to the userop when compiling new Sleigh code. It cannot
* conflict with existing userops (except those declared, but not defined, by the executor's
@@ -142,7 +234,6 @@ public interface PcodeUseropLibrary<T> {
/**
* 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.
@@ -159,9 +250,8 @@ public interface PcodeUseropLibrary<T> {
/**
* 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
+ * 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
@@ -169,7 +259,6 @@ public interface PcodeUseropLibrary<T> {
* 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
@@ -182,12 +271,39 @@ public interface PcodeUseropLibrary<T> {
boolean isFunctional();
/**
- * Indicates whether this userop may have side effects.
+ * Indicates whether this userop can interrupt execution.
+ * <p>
+ * Optimized execution engines seeks to remove unnecessary variable assignments,
+ * computations, etc. If the userop is {@linkplain #isFunctional() functional}, then the
+ * engine can confidently assume only its operands need to be visible at the time of its
+ * invocation. If a userop can interrupt execution, then the engine must assure that, once
+ * the client has handled the exception, the machine state reflects the state at the time of
+ * the interruption. (This is especially critical for user breakpoints.)
+ * <p>
+ * NOTE: We're not settled on the case of "unexpected" interrupts, e.g., a null pointer
+ * exception in a user's userop library. In a sense, this is undefined behavior, so who's to
+ * say the machine had better have a consistent state? On the other hand, for userops that
+ * intend to throw exceptions as a means of interrupting execution for client inspection and
+ * possible resumption, this attribute must be set. Here's the rule for now: <blockquote>If
+ * the intent is to permit the client to resume execution after the interrupt, the machine
+ * state must be consistent, and so this attribute must be true.</blockquote> Otherwise, the
+ * value is set at the userop developer's discretion, but false should be preferred to
+ * facilitate better performance.
*
+ * @return true if the userop can be expected to interrupt execution by throwing an
+ * exception
+ * @see PcodeUserop#canInterrupt()
+ */
+ boolean canInterrupt();
+
+ /**
+ * 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.
+ * effects, e.g., updating a field in a library or printing to the screen. This <em>does
+ * not</em> permit a functional userop to modify the emulated machine state, but only
+ * "out-of-band" state.
*
* @return true if it has side effects.
* @see PcodeUserop#hasSideEffects()
@@ -196,7 +312,6 @@ public interface PcodeUseropLibrary<T> {
/**
* Indicates that this userop may modify the decode context.
- *
* <p>
* This means that the userop may set a field in {@code contextreg}, which could thus affect
* how subsequent instructions are decoded. Executors which decode ahead will have to
@@ -210,7 +325,6 @@ public interface PcodeUseropLibrary<T> {
/**
* 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
@@ -227,8 +341,44 @@ public interface PcodeUseropLibrary<T> {
boolean canInlinePcode();
/**
- * If this userop is defined as a java callback, get the type of the output
+ * Indicates whether the output should be sign or zero extended to match the output varnode
+ * size.
+ * <p>
+ * This only applies when the userop is implemented as a Java function returning a primitive
+ * type. Otherwise, the userop should examine the output varnode and behave accordingly, or
+ * just inline use of that output varnode. When returning, e.g., an {@code int}, it could
+ * happen that the output varnode size 8. Because it's larger, we need to know whether or
+ * not the output is meant to be signed. Contrary to Java conventions, but inline with
+ * Sleigh conventions, we default to <em>false</em>.
+ *
+ * @return true for signed extension
+ */
+ boolean isOutSigned();
+
+ /**
+ * Indicates whether a given input 0-up should be sign or zero extended to match a Java
+ * primitive parameter size.
+ * <p>
+ * This only applies when the userop is implemented as a Java function and this input is
+ * taken as a primitive type. Otherwise, the userop should examine the input varnode and
+ * behave accordingly, or just inline use of that input varnode. When accepting, e.g., a
+ * {@code long}, it could happen the input varnode is size 2. Because it's smaller, we need
+ * to know whether or not that input is meant to be signed. Contrary to Java conventions,
+ * but inline with Sleigh conventions, we default to <em>false</em>.
+ * <p>
+ * <b>WARNING:</b> Constant varnodes can behave weirdly when interpreted as signed. A userop
+ * declaring a signed input must be prepared to deal with this case. Consider the constant
+ * 0x80. Sleigh will encode this as the varnode {@code (const, 0x80, 1)}, i.e., the constant
+ * with value 0x80 having size 1. If you mark an {@code int} input as signed, and it
+ * receives this constant, Java will see it as -128.
*
+ * @param index the position of the input argument, 0 is leftmost.
+ * @return true for signed extension
+ */
+ boolean isInSigned(int index);
+
+ /**
+ * If this userop is defined as a java callback, get the type of the output
* <p>
* If the method has a {@code @}{@link OpOutput} annotation, this is the type of the output
* parameter. Otherwise, this is the method's return type.
@@ -246,12 +396,10 @@ public interface PcodeUseropLibrary<T> {
/**
* 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
@@ -299,30 +447,13 @@ public interface PcodeUseropLibrary<T> {
*
* @param language the language whose existing symbols to consider
* @return a map of new userop indices to extra userop symbols
+ * @implNote implementors would be wise to cache these by language
*/
- default Map<Integer, UserOpSymbol> getSymbols(SleighLanguage language) {
- //Set<String> langDefedNames = new HashSet<>();
- Map<Integer, UserOpSymbol> symbols = new HashMap<>();
- Set<String> allNames = new HashSet<>();
- int langOpCount = language.getNumberOfUserDefinedOpNames();
- for (int i = 0; i < langOpCount; i++) {
- String name = language.getUserDefinedOpName(i);
- allNames.add(name);
- }
- int nextOpNo = langOpCount;
- for (PcodeUseropDefinition<?> uop : new TreeMap<>(getUserops()).values()) {
- String opName = uop.getName();
- if (!allNames.add(opName)) {
- // Real duplicates will cause a warning during execution
- continue;
- }
-
- int opNo = nextOpNo++;
- Location loc = new Location(getClass().getName() + ":" + opName, 0);
- UserOpSymbol sym = new UserOpSymbol(loc, opName);
- sym.setIndex(opNo);
- symbols.put(opNo, sym);
+ default PcodeUseropSymbolMap getSymbols(SleighLanguage language) {
+ SymbolsCache cache;
+ synchronized (SYMBOL_CACHE) {
+ cache = SYMBOL_CACHE.computeIfAbsent(this, SymbolsCache::new);
}
- return symbols;
+ return cache.getSymbols(language);
}
}
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.java
index a355484ff1..6212714753 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
@@ -24,28 +24,21 @@ import ghidra.program.model.pcode.Varnode;
/**
* A p-code userop defined using Sleigh source
- *
- * @param <T> no type in particular, except to match any executor
*/
-public interface SleighPcodeUseropDefinition<T> extends PcodeUseropDefinition<T> {
+public interface SleighPcodeUseropDefinition extends PcodeUseropDefinition<Object> {
+ /** The factory for defining userops with Sleigh */
+ Factory FACTORY = Factory.INSTANCE;
/** The name of the output symbol */
String OUT_SYMBOL_NAME = "__op_output";
+ /** The varnode list containing only one null */
List<Varnode> EMPTY_ARGS = Collections.unmodifiableList(Arrays.asList(new Varnode[] { null }));
/**
* A factory for building {@link SleighPcodeUseropDefinition}s.
*/
- public static class Factory {
- final SleighLanguage language;
-
- /**
- * Construct a factory for the given language
- *
- * @param language the language
- */
- public Factory(SleighLanguage language) {
- this.language = language;
- }
+ public enum Factory {
+ /** The factory */
+ INSTANCE;
/**
* Begin building the definition for a userop with the given name
@@ -54,7 +47,7 @@ public interface SleighPcodeUseropDefinition<T> extends PcodeUseropDefinition<T>
* @return a builder for the userop
*/
public BuilderStage1 define(String name) {
- return new AbstractSleighPcodeUseropDefinition.Builder(this, name);
+ return new AbstractSleighPcodeUseropDefinition.Builder(name);
}
}
@@ -64,7 +57,6 @@ public interface SleighPcodeUseropDefinition<T> extends PcodeUseropDefinition<T>
public interface BodyFunc {
/**
* Generate the body, given the arguments
- *
* <p>
* In general, to refer to an argument, the source can use the corresponding parameter by
* name. Ideally, this is always the case, and the generated source does not depend on the
@@ -99,16 +91,14 @@ public interface SleighPcodeUseropDefinition<T> extends PcodeUseropDefinition<T>
/**
* Build the actual definition
- *
* <p>
* NOTE: Compilation of the sleigh source is delayed until the first invocation, since the
* compiler must know about the varnodes used as parameters. TODO: There may be some way to
* template it at the p-code level instead of the Sleigh source level.
*
- * @param <T> no particular type, except to match the executor
* @return the definition
*/
- <T> SleighPcodeUseropDefinition<T> build();
+ SleighPcodeUseropDefinition build();
}
/**
@@ -163,7 +153,6 @@ public interface SleighPcodeUseropDefinition<T> extends PcodeUseropDefinition<T>
/**
* Get the Sleigh source that defines this userop
- *
* <p>
* The body may or may not actually depend on the arguments. Ideally, it does not, but sometimes
* the body may vary depending on the <em>sizes</em> of the arguments. In cases where it is
@@ -189,14 +178,40 @@ public interface SleighPcodeUseropDefinition<T> extends PcodeUseropDefinition<T>
/**
* Get the p-code program implementing this userop for the given arguments and library.
- *
* <p>
* This will compile and cache a program for each new combination of arguments seen.
*
+ * @param language the language of the executor
* @param args the operands, output at index 0, and inputs following
* @param library the complete userop library
* @return the p-code program to be fed to the same executor as invoked this userop, but in a
* new frame
*/
- PcodeProgram programFor(List<Varnode> args, PcodeUseropLibrary<?> library);
+ PcodeProgram programFor(SleighLanguage language, List<Varnode> args,
+ PcodeUseropLibrary<?> library);
+
+ /**
+ * Cast this Sleigh p-code userop definition to one of the required type
+ *
+ * @param <T> the executor's, library's, etc. type
+ * @return this same definition
+ */
+ @SuppressWarnings("unchecked")
+ default <T> PcodeUseropDefinition<T> cast() {
+ return (PcodeUseropDefinition<T>) this;
+ }
+
+ /**
+ * Cast a userop definition to a Sleigh-defined one
+ * <p>
+ * For some reason, the usual syntax in Java is forbidden, probably because it's of {@code <T>}
+ * and not {@code <?>}....
+ *
+ * @param def the userop definition
+ * @return the userop definition, if it is a Sleigh-defined one
+ * @throws ClassCastException if def is not a Sleigh-defined userop
+ */
+ static SleighPcodeUseropDefinition cast(PcodeUseropDefinition<?> def) {
+ return (SleighPcodeUseropDefinition) def;
+ }
}
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.java
index 5483fd4061..ebb2d5ef64 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
@@ -16,16 +16,19 @@
package ghidra.pcode.exec;
import java.io.IOException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
import java.util.stream.Collectors;
import ghidra.app.plugin.processors.sleigh.*;
import ghidra.app.plugin.processors.sleigh.template.ConstructTpl;
import ghidra.app.plugin.processors.sleigh.template.OpTpl;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
import ghidra.pcode.utils.MessageFormattingUtils;
import ghidra.pcodeCPort.pcoderaw.VarnodeData;
import ghidra.pcodeCPort.sleighbase.SleighBase;
-import ghidra.pcodeCPort.slghsymbol.*;
+import ghidra.pcodeCPort.slghsymbol.SleighSymbol;
+import ghidra.pcodeCPort.slghsymbol.VarnodeSymbol;
import ghidra.pcodeCPort.space.AddrSpace;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressSpace;
@@ -38,7 +41,6 @@ import ghidra.util.Msg;
/**
* Methods for compiling p-code programs for various purposes
- *
* <p>
* Depending on the purpose, special provisions may be necessary around the execution of the
* resulting program. Many utility methods are declared public here because they, well, they have
@@ -179,24 +181,8 @@ public enum SleighProgramCompiler {
return List.of(emit.getPcodeOp());
}
- /**
- * Add extra user-op symbols to the parser's table
- *
- * <p>
- * The map cannot contain symbols whose user-op indices are already defined by the language.
- *
- * @param parser the parser to modify
- * @param symbols the map of extra symbols
- */
- protected static void addParserSymbols(PcodeParser parser, Map<Integer, UserOpSymbol> symbols) {
- for (UserOpSymbol sym : symbols.values()) {
- parser.addSymbol(sym);
- }
- }
-
/**
* Add a symbol for unwanted result
- *
* <p>
* This is basically a hack to avoid NPEs when no output varnode is given.
*
@@ -226,7 +212,7 @@ public enum SleighProgramCompiler {
* @param <T> the type of program to build
*/
public interface PcodeProgramConstructor<T extends PcodeProgram> {
- T construct(SleighLanguage language, List<PcodeOp> ops, Map<Integer, UserOpSymbol> symbols);
+ T construct(SleighLanguage language, List<PcodeOp> ops, PcodeUseropSymbolMap symbols);
}
/**
@@ -240,7 +226,7 @@ public enum SleighProgramCompiler {
* @return the p-code program
*/
public static <T extends PcodeProgram> T constructProgram(PcodeProgramConstructor<T> ctor,
- SleighLanguage language, ConstructTpl template, Map<Integer, UserOpSymbol> libSyms) {
+ SleighLanguage language, ConstructTpl template, PcodeUseropSymbolMap libSyms) {
try {
return ctor.construct(language, SleighProgramCompiler.buildOps(language, template),
libSyms);
@@ -252,7 +238,6 @@ public enum SleighProgramCompiler {
/**
* Compile the given Sleigh source into a simple p-code program with the given parser
- *
* <p>
* This is suitable for modifying program state using Sleigh statements. Most likely, in
* scripting, or perhaps in a Sleigh repl. The library given during compilation must match the
@@ -267,8 +252,8 @@ public enum SleighProgramCompiler {
*/
public static PcodeProgram compileProgram(PcodeParser parser, SleighLanguage language,
String sourceName, String source, PcodeUseropLibrary<?> library) {
- Map<Integer, UserOpSymbol> symbols = library.getSymbols(language);
- addParserSymbols(parser, symbols);
+ PcodeUseropSymbolMap symbols = library.getSymbols(language);
+ symbols.addToParser(parser);
ConstructTpl template = compileTemplate(language, parser, sourceName, source);
return constructProgram(PcodeProgram::new, language, template, symbols);
@@ -287,7 +272,6 @@ public enum SleighProgramCompiler {
/**
* Compile the given Sleigh expression into a p-code program that can evaluate it, using the
* given parser
- *
* <p>
* TODO: Currently, expressions cannot be compiled for a user-supplied userop library. The
* evaluator p-code program uses its own library as a means of capturing the result; however,
@@ -301,8 +285,8 @@ public enum SleighProgramCompiler {
*/
public static PcodeExpression compileExpression(PcodeParser parser, SleighLanguage language,
String expression) {
- Map<Integer, UserOpSymbol> symbols = PcodeExpression.CAPTURING.getSymbols(language);
- addParserSymbols(parser, symbols);
+ PcodeUseropSymbolMap symbols = PcodeExpression.CAPTURING.getSymbols(language);
+ symbols.addToParser(parser);
ConstructTpl template = compileTemplate(language, parser, EXPRESSION_SOURCE_NAME,
PcodeExpression.RESULT_NAME + "(" + expression + ");");
@@ -339,7 +323,6 @@ public enum SleighProgramCompiler {
/**
* Compile the definition of a p-code userop from Sleigh source into a p-code program
- *
* <p>
* TODO: Defining a userop from Sleigh source is currently a bit of a hack. It would be nice if
* there were a formalization of Sleigh/p-code subroutines. At the moment, the control flow for
@@ -371,8 +354,8 @@ public enum SleighProgramCompiler {
List<String> params, String source, PcodeUseropLibrary<?> library,
List<Varnode> args) {
PcodeParser parser = createParser(language);
- Map<Integer, UserOpSymbol> symbols = library.getSymbols(language);
- addParserSymbols(parser, symbols);
+ PcodeUseropSymbolMap symbols = library.getSymbols(language);
+ symbols.addToParser(parser);
SleighBase sleigh = parser.getSleigh();
int count = params.size();
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SymbolsCache.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SymbolsCache.java
new file mode 100644
index 0000000000..5f88aad86b
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/exec/SymbolsCache.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.exec;
+
+import java.util.*;
+
+import ghidra.app.plugin.processors.sleigh.SleighLanguage;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropDefinition;
+import ghidra.pcode.exec.PcodeUseropLibrary.PcodeUseropSymbolMap;
+import ghidra.pcodeCPort.slghsymbol.UserOpSymbol;
+import ghidra.sleigh.grammar.Location;
+
+class SymbolsCache {
+ private final PcodeUseropLibrary<?> library;
+ private final Map<SleighLanguage, PcodeUseropSymbolMap> cache = new HashMap<>();
+
+ public SymbolsCache(PcodeUseropLibrary<?> library) {
+ this.library = library;
+ }
+
+ PcodeUseropSymbolMap computeSymbols(SleighLanguage language) {
+ Map<Integer, UserOpSymbol> symbols = new HashMap<>();
+ Set<String> allNames = new HashSet<>();
+ int langOpCount = language.getNumberOfUserDefinedOpNames();
+ for (int i = 0; i < langOpCount; i++) {
+ String name = language.getUserDefinedOpName(i);
+ allNames.add(name);
+ }
+ int nextOpNo = langOpCount;
+ for (PcodeUseropDefinition<?> uop : new TreeMap<>(library.getUserops()).values()) {
+ String opName = uop.getName();
+ if (!allNames.add(opName)) {
+ // Real duplicates will cause a warning during execution
+ continue;
+ }
+
+ int opNo = nextOpNo++;
+ Location loc = new Location(getClass().getName() + ":" + opName, 0);
+ UserOpSymbol sym = new UserOpSymbol(loc, opName);
+ sym.setIndex(opNo);
+ symbols.put(opNo, sym);
+ }
+ return new PcodeUseropSymbolMap(language, Collections.unmodifiableMap(symbols));
+ }
+
+ PcodeUseropSymbolMap getSymbols(SleighLanguage language) {
+ synchronized (cache) {
+ return cache.computeIfAbsent(language, this::computeSymbols);
+ }
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/BinaryOpBehavior.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/BinaryOpBehavior.java
index bde80af11b..6f6b7751b8 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/BinaryOpBehavior.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/BinaryOpBehavior.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,48 +15,49 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.pcode.utils.Utils;
-
import java.math.BigInteger;
-public abstract class BinaryOpBehavior extends OpBehavior {
-
- BinaryOpBehavior(int opcode) {
- super(opcode);
- }
+import ghidra.pcode.utils.Utils;
+/**
+ * The implementation of a binary (2 input args, 1 output) p-code operator
+ */
+public interface BinaryOpBehavior extends OpBehavior {
/**
- * Evaluate the binary (2 input args) operation using long data
+ * Evaluate the binary operation using long data
+ * <p>
+ * NOTE: if the operation overflows bits may be set beyond the specified sizeout. Even though
+ * results should be treated as unsigned it may be returned as a signed long value. It is
+ * expected that the returned result always be properly truncated by the caller since the
+ * evaluation may not - this is done to conserve emulation cycles.
+ *
* @param sizeout intended output size (bytes)
* @param sizein in1 size (bytes)
* @param unsignedIn1 unsigned input 1
* @param unsignedIn2 unsigned input 2
- * @return operation result. NOTE: if the operation overflows bits may be
- * set beyond the specified sizeout. Even though results should be treated
- * as unsigned it may be returned as a signed long value. It is expected that the
- * returned result always be properly truncated by the caller since the evaluation
- * may not - this is done to conserve emulation cycles.
+ * @return operation result.
* @see Utils#longToBytes(long, int, boolean)
* @see Utils#bytesToLong(byte[], int, boolean)
*/
-
- public abstract long evaluateBinary(int sizeout, int sizein, long unsignedIn1, long unsignedIn2);
+ public abstract long evaluateBinary(int sizeout, int sizein, long unsignedIn1,
+ long unsignedIn2);
/**
- * Evaluate the binary (2 input args) operation using BigInteger data
+ * Evaluate the binary operation using BigInteger data
+ * <p>
+ * NOTE: if the operation overflows bits may be set beyond the specified sizeout. Even though
+ * results should be treated as unsigned it may be returned as a signed value. It is expected
+ * that the returned result always be properly truncated by the caller since the evaluation may
+ * not - this is done to conserve emulation cycles.
+ *
* @param sizeout intended output size (bytes)
* @param sizein in1 size (bytes)
* @param unsignedIn1 unsigned input 1
* @param unsignedIn2 unsigned input 2
- * @return operation result. NOTE: if the operation overflows bits may be
- * set beyond the specified sizeout. Even though results should be treated
- * as unsigned it may be returned as a signed value. It is expected that the
- * returned result always be properly truncated by the caller since the evaluation
- * may not - this is done to conserve emulation cycles.
+ * @return operation result.
* @see Utils#bigIntegerToBytes(BigInteger, int, boolean)
- * @see Utils#bytesToBigInteger(byte[], int, boolean, boolean)
+ * @see Utils#bytesToBigInteger(byte[], int, boolean, boolean)
*/
public abstract BigInteger evaluateBinary(int sizeout, int sizein, BigInteger unsignedIn1,
BigInteger unsignedIn2);
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehavior.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehavior.java
index bbef77583c..7bc9e07058 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehavior.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehavior.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,93 @@
*/
package ghidra.pcode.opbehavior;
-public class OpBehavior {
+/**
+ * The implementation of a p-code opcode
+ */
+public interface OpBehavior {
+ OpBehaviorCopy COPY = OpBehaviorCopy.OP_COPY;
+ SpecialOpBehavior LOAD = SpecialOpBehavior.OP_LOAD;
+ SpecialOpBehavior STORE = SpecialOpBehavior.OP_STORE;
+ SpecialOpBehavior BRANCH = SpecialOpBehavior.OP_BRANCH;
+ SpecialOpBehavior CBRANCH = SpecialOpBehavior.OP_CBRANCH;
+ SpecialOpBehavior BRANCHIND = SpecialOpBehavior.OP_BRANCHIND;
+ SpecialOpBehavior CALL = SpecialOpBehavior.OP_CALL;
+ SpecialOpBehavior CALLIND = SpecialOpBehavior.OP_CALLIND;
+ SpecialOpBehavior CALLOTHER = SpecialOpBehavior.OP_CALLOTHER;
+ SpecialOpBehavior RETURN = SpecialOpBehavior.OP_RETURN;
+
+ SpecialOpBehavior MULTIEQUAL = SpecialOpBehavior.OP_BRANCH;
+ SpecialOpBehavior INDIRECT = SpecialOpBehavior.OP_BRANCH;
+
+ OpBehaviorPiece PIECE = OpBehaviorPiece.OP_PIECE;
+ OpBehaviorSubpiece SUBPIECE = OpBehaviorSubpiece.OP_SUBPIECE;
+ OpBehaviorEqual INT_EQUAL = OpBehaviorEqual.OP_INT_EQUAL;
+ OpBehaviorNotEqual INT_NOTEQUAL = OpBehaviorNotEqual.OP_INT_NOTEQUAL;
+ OpBehaviorIntLess INT_LESS = OpBehaviorIntLess.OP_INT_LESS;
+ OpBehaviorIntLessEqual INT_LESSEQUAL = OpBehaviorIntLessEqual.OP_INT_LESSEQUAL;
+ OpBehaviorIntSless INT_SLESS = OpBehaviorIntSless.OP_INT_SLESS;
+ OpBehaviorIntSlessEqual INT_SLESSEQUAL = OpBehaviorIntSlessEqual.OP_INT_SLESSEQUAL;
+ OpBehaviorIntZext INT_ZEXT = OpBehaviorIntZext.OP_INT_ZEXT;
+ OpBehaviorIntSext INT_SEXT = OpBehaviorIntSext.OP_INT_SEXT;
+ OpBehaviorIntAdd INT_ADD = OpBehaviorIntAdd.OP_INT_ADD;
+ OpBehaviorIntSub INT_SUB = OpBehaviorIntSub.OP_INT_SUB;
+ OpBehaviorIntCarry INT_CARRY = OpBehaviorIntCarry.OP_INT_CARRY;
+ OpBehaviorIntScarry INT_SCARRY = OpBehaviorIntScarry.OP_INT_SCARRY;
+ OpBehaviorIntSborrow INT_SBORROW = OpBehaviorIntSborrow.OP_INT_SBORROW;
+ OpBehaviorInt2Comp INT_2COMP = OpBehaviorInt2Comp.OP_INT_2COMP;
+ OpBehaviorIntNegate INT_NEGATE = OpBehaviorIntNegate.OP_INT_NEGATE;
+ OpBehaviorIntXor INT_XOR = OpBehaviorIntXor.OP_INT_XOR;
+ OpBehaviorIntAnd INT_AND = OpBehaviorIntAnd.OP_INT_AND;
+ OpBehaviorIntOr INT_OR = OpBehaviorIntOr.OP_INT_OR;
+ OpBehaviorIntLeft INT_LEFT = OpBehaviorIntLeft.OP_INT_LEFT;
+ OpBehaviorIntRight INT_RIGHT = OpBehaviorIntRight.OP_INT_RIGHT;
+ OpBehaviorIntSright INT_SRIGHT = OpBehaviorIntSright.OP_INT_SRIGHT;
+ OpBehaviorIntMult INT_MULT = OpBehaviorIntMult.OP_INT_MULT;
+ OpBehaviorIntDiv INT_DIV = OpBehaviorIntDiv.OP_INT_DEV;
+ OpBehaviorIntSdiv INT_SDIV = OpBehaviorIntSdiv.OP_INT_SDIV;
+ OpBehaviorIntRem INT_REM = OpBehaviorIntRem.OP_INT_REM;
+ OpBehaviorIntSrem INT_SREM = OpBehaviorIntSrem.OP_INT_SREM;
+
+ OpBehaviorBoolNegate BOOL_NEGATE = OpBehaviorBoolNegate.OP_BOOL_NEGATE;
+ OpBehaviorBoolXor BOOL_XOR = OpBehaviorBoolXor.OP_BOOL_XOR;
+ OpBehaviorBoolAnd BOOL_AND = OpBehaviorBoolAnd.OP_BOOL_AND;
+ OpBehaviorBoolOr BOOL_OR = OpBehaviorBoolOr.OP_BOOL_OR;
+
+ SpecialOpBehavior CAST = SpecialOpBehavior.OP_CAST;
+ SpecialOpBehavior PTRADD = SpecialOpBehavior.OP_PTRADD;
+ SpecialOpBehavior PTRSUB = SpecialOpBehavior.OP_PTRSUB;
+
+ OpBehaviorFloatEqual FLOAT_EQUAL = OpBehaviorFloatEqual.OP_FLOAT_EQUAL;
+ OpBehaviorFloatNotEqual FLOAT_NOTEQUAL = OpBehaviorFloatNotEqual.OP_FLOAT_NOTEQUAL;
+ OpBehaviorFloatLess FLOAT_LESS = OpBehaviorFloatLess.OP_FLOAT_LESS;
+ OpBehaviorFloatLessEqual FLOAT_LESSEQUAL = OpBehaviorFloatLessEqual.OP_FLOAT_LESSEQUAL;
+ OpBehaviorFloatNan FLOAT_NAN = OpBehaviorFloatNan.OP_FLOAT_NAN;
+
+ OpBehaviorFloatAdd FLOAT_ADD = OpBehaviorFloatAdd.OP_FLOAT_ADD;
+ OpBehaviorFloatDiv FLOAT_DIV = OpBehaviorFloatDiv.OP_FLOAT_DIV;
+ OpBehaviorFloatMult FLOAT_MULT = OpBehaviorFloatMult.OP_FLOAT_MULT;
+ OpBehaviorFloatSub FLOAT_SUB = OpBehaviorFloatSub.OP_FLOAT_SUB;
+ OpBehaviorFloatNeg FLOAT_NEG = OpBehaviorFloatNeg.OP_FLOAT_NEG;
+ OpBehaviorFloatAbs FLOAT_ABS = OpBehaviorFloatAbs.OP_FLOAT_ABS;
+ OpBehaviorFloatSqrt FLOAT_SQRT = OpBehaviorFloatSqrt.OP_FLOAT_SQRT;
- final int opcode;
+ OpBehaviorFloatInt2Float FLOAT_INT2FLOAT = OpBehaviorFloatInt2Float.OP_FLOAT_INT2FLOAT;
+ OpBehaviorFloatFloat2Float FLOAT_FLOAT2FLOAT = OpBehaviorFloatFloat2Float.OP_FLOAT_FLOAT2FLOAT;
+ OpBehaviorFloatTrunc FLOAT_TRUNC = OpBehaviorFloatTrunc.OP_FLOAT_TRUNC;
+ OpBehaviorFloatCeil FLOAT_CEIL = OpBehaviorFloatCeil.OP_FLOAT_CEIL;
+ OpBehaviorFloatFloor FLOAT_FLOOR = OpBehaviorFloatFloor.OP_FLOAT_FLOOR;
+ OpBehaviorFloatRound FLOAT_ROUND = OpBehaviorFloatRound.OP_FLOAT_ROUND;
- OpBehavior(int opcode) {
- this.opcode = opcode;
- }
+ OpBehaviorLzcount LZCOUNT = OpBehaviorLzcount.OP_LZCOUNT;
+ OpBehaviorPopcount POPCOUNT = OpBehaviorPopcount.OP_POPCOUNT;
- public int getOpCode() {
- return opcode;
- }
+ SpecialOpBehavior SEGMENTOP = SpecialOpBehavior.OP_SEGMENTOP;
+ SpecialOpBehavior CPOOLREF = SpecialOpBehavior.OP_CPOOLREF;
+ SpecialOpBehavior NEW = SpecialOpBehavior.OP_NEW;
+ SpecialOpBehavior INSERT = SpecialOpBehavior.OP_INSERT;
+ SpecialOpBehavior ZPULL = SpecialOpBehavior.OP_ZPULL;
+ SpecialOpBehavior SPULL = SpecialOpBehavior.OP_SPULL;
+ /** {@return the opcode implemented} */
+ int opcode();
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolAnd.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolAnd.java
index fab69dbdf0..1ec716b166 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolAnd.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolAnd.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorBoolAnd extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorBoolAnd implements BinaryOpBehavior {
+ OP_BOOL_AND;
- public OpBehaviorBoolAnd() {
- super(PcodeOp.BOOL_AND);
+ @Override
+ public int opcode() {
+ return PcodeOp.BOOL_AND;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegate.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegate.java
index 03506eefcc..aaa123550f 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegate.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegate.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorBoolNegate extends UnaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorBoolNegate implements UnaryOpBehavior {
+ OP_BOOL_NEGATE;
- public OpBehaviorBoolNegate() {
- super(PcodeOp.BOOL_NEGATE);
+ @Override
+ public int opcode() {
+ return PcodeOp.BOOL_NEGATE;
}
@Override
@@ -37,5 +38,4 @@ public class OpBehaviorBoolNegate extends UnaryOpBehavior {
BigInteger res = in1.xor(BigInteger.ONE);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolOr.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolOr.java
index 272a2f0f7c..2e912e0026 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolOr.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolOr.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorBoolOr extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorBoolOr implements BinaryOpBehavior {
+ OP_BOOL_OR;
- public OpBehaviorBoolOr() {
- super(PcodeOp.BOOL_OR);
+ @Override
+ public int opcode() {
+ return PcodeOp.BOOL_OR;
}
@Override
@@ -37,5 +38,4 @@ public class OpBehaviorBoolOr extends BinaryOpBehavior {
BigInteger res = in1.or(in2);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolXor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolXor.java
index a42ea01846..da7cfbc08d 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolXor.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorBoolXor.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorBoolXor extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorBoolXor implements BinaryOpBehavior {
+ OP_BOOL_XOR;
- public OpBehaviorBoolXor() {
- super(PcodeOp.BOOL_XOR);
+ @Override
+ public int opcode() {
+ return PcodeOp.BOOL_XOR;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorCopy.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorCopy.java
index 18b217de26..271132e9cd 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorCopy.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorCopy.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorCopy extends UnaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorCopy implements UnaryOpBehavior {
+ OP_COPY;
- public OpBehaviorCopy() {
- super(PcodeOp.COPY);
+ @Override
+ public int opcode() {
+ return PcodeOp.COPY;
}
@Override
@@ -35,9 +36,4 @@ public class OpBehaviorCopy extends UnaryOpBehavior {
public BigInteger evaluateUnary(int sizeout, int sizein, BigInteger in1) {
return in1;
}
-
-// @Override
-// public long recoverInputUnary( int sizeout, long out, int sizein ) {
-// return out;
-// }
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorEqual.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorEqual.java
index b5cfc6389b..c88edc3a31 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorEqual.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorEqual.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorEqual extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorEqual implements BinaryOpBehavior {
+ OP_INT_EQUAL;
- public OpBehaviorEqual() {
- super(PcodeOp.INT_EQUAL);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_EQUAL;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFactory.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFactory.java
index 5d638d5d7d..7117bf7132 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFactory.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFactory.java
@@ -15,104 +15,95 @@
*/
package ghidra.pcode.opbehavior;
-import java.util.HashMap;
-import java.util.Map;
-
import ghidra.program.model.pcode.PcodeOp;
public class OpBehaviorFactory {
- private static Map<Integer, OpBehavior> opBehaviorMap = new HashMap<Integer, OpBehavior>();
- static {
- // TODO: should pass float format factory
-
- opBehaviorMap.put(PcodeOp.COPY, new OpBehaviorCopy());
- opBehaviorMap.put(PcodeOp.LOAD, new SpecialOpBehavior(PcodeOp.LOAD));
- opBehaviorMap.put(PcodeOp.STORE, new SpecialOpBehavior(PcodeOp.STORE));
- opBehaviorMap.put(PcodeOp.BRANCH, new SpecialOpBehavior(PcodeOp.BRANCH));
- opBehaviorMap.put(PcodeOp.CBRANCH, new SpecialOpBehavior(PcodeOp.CBRANCH));
- opBehaviorMap.put(PcodeOp.BRANCHIND, new SpecialOpBehavior(PcodeOp.BRANCHIND));
- opBehaviorMap.put(PcodeOp.CALL, new SpecialOpBehavior(PcodeOp.CALL));
- opBehaviorMap.put(PcodeOp.CALLIND, new SpecialOpBehavior(PcodeOp.CALLIND));
- opBehaviorMap.put(PcodeOp.CALLOTHER, new SpecialOpBehavior(PcodeOp.CALLOTHER));
- opBehaviorMap.put(PcodeOp.RETURN, new SpecialOpBehavior(PcodeOp.RETURN));
-
- opBehaviorMap.put(PcodeOp.MULTIEQUAL, new SpecialOpBehavior(PcodeOp.MULTIEQUAL));
- opBehaviorMap.put(PcodeOp.INDIRECT, new SpecialOpBehavior(PcodeOp.INDIRECT));
+ public static OpBehavior getOpBehavior(int opcode) {
+ // TODO: should pass float format factory?
+ return switch (opcode) {
+ case PcodeOp.COPY -> OpBehavior.COPY;
+ case PcodeOp.LOAD -> OpBehavior.LOAD;
+ case PcodeOp.STORE -> OpBehavior.STORE;
+ case PcodeOp.BRANCH -> OpBehavior.BRANCH;
+ case PcodeOp.CBRANCH -> OpBehavior.CBRANCH;
+ case PcodeOp.BRANCHIND -> OpBehavior.BRANCHIND;
+ case PcodeOp.CALL -> OpBehavior.CALL;
+ case PcodeOp.CALLIND -> OpBehavior.CALLIND;
+ case PcodeOp.CALLOTHER -> OpBehavior.CALLOTHER;
+ case PcodeOp.RETURN -> OpBehavior.RETURN;
- opBehaviorMap.put(PcodeOp.PIECE, new OpBehaviorPiece());
- opBehaviorMap.put(PcodeOp.SUBPIECE, new OpBehaviorSubpiece());
- opBehaviorMap.put(PcodeOp.INT_EQUAL, new OpBehaviorEqual());
- opBehaviorMap.put(PcodeOp.INT_NOTEQUAL, new OpBehaviorNotEqual());
- opBehaviorMap.put(PcodeOp.INT_SLESS, new OpBehaviorIntSless());
- opBehaviorMap.put(PcodeOp.INT_SLESSEQUAL, new OpBehaviorIntSlessEqual());
- opBehaviorMap.put(PcodeOp.INT_LESS, new OpBehaviorIntLess());
- opBehaviorMap.put(PcodeOp.INT_LESSEQUAL, new OpBehaviorIntLessEqual());
- opBehaviorMap.put(PcodeOp.INT_ZEXT, new OpBehaviorIntZext());
- opBehaviorMap.put(PcodeOp.INT_SEXT, new OpBehaviorIntSext());
- opBehaviorMap.put(PcodeOp.INT_ADD, new OpBehaviorIntAdd());
- opBehaviorMap.put(PcodeOp.INT_SUB, new OpBehaviorIntSub());
- opBehaviorMap.put(PcodeOp.INT_CARRY, new OpBehaviorIntCarry());
- opBehaviorMap.put(PcodeOp.INT_SCARRY, new OpBehaviorIntScarry());
- opBehaviorMap.put(PcodeOp.INT_SBORROW, new OpBehaviorIntSborrow());
- opBehaviorMap.put(PcodeOp.INT_2COMP, new OpBehaviorInt2Comp());
- opBehaviorMap.put(PcodeOp.INT_NEGATE, new OpBehaviorIntNegate());
- opBehaviorMap.put(PcodeOp.INT_XOR, new OpBehaviorIntXor());
- opBehaviorMap.put(PcodeOp.INT_AND, new OpBehaviorIntAnd());
- opBehaviorMap.put(PcodeOp.INT_OR, new OpBehaviorIntOr());
- opBehaviorMap.put(PcodeOp.INT_LEFT, new OpBehaviorIntLeft());
- opBehaviorMap.put(PcodeOp.INT_RIGHT, new OpBehaviorIntRight());
- opBehaviorMap.put(PcodeOp.INT_SRIGHT, new OpBehaviorIntSright());
- opBehaviorMap.put(PcodeOp.INT_MULT, new OpBehaviorIntMult());
- opBehaviorMap.put(PcodeOp.INT_DIV, new OpBehaviorIntDiv());
- opBehaviorMap.put(PcodeOp.INT_SDIV, new OpBehaviorIntSdiv());
- opBehaviorMap.put(PcodeOp.INT_REM, new OpBehaviorIntRem());
- opBehaviorMap.put(PcodeOp.INT_SREM, new OpBehaviorIntSrem());
+ case PcodeOp.MULTIEQUAL -> OpBehavior.MULTIEQUAL;
+ case PcodeOp.INDIRECT -> OpBehavior.INDIRECT;
- opBehaviorMap.put(PcodeOp.BOOL_NEGATE, new OpBehaviorBoolNegate());
- opBehaviorMap.put(PcodeOp.BOOL_XOR, new OpBehaviorBoolXor());
- opBehaviorMap.put(PcodeOp.BOOL_AND, new OpBehaviorBoolAnd());
- opBehaviorMap.put(PcodeOp.BOOL_OR, new OpBehaviorBoolOr());
+ case PcodeOp.PIECE -> OpBehavior.PIECE;
+ case PcodeOp.SUBPIECE -> OpBehavior.SUBPIECE;
+ case PcodeOp.INT_EQUAL -> OpBehavior.INT_EQUAL;
+ case PcodeOp.INT_NOTEQUAL -> OpBehavior.INT_NOTEQUAL;
+ case PcodeOp.INT_SLESS -> OpBehavior.INT_SLESS;
+ case PcodeOp.INT_SLESSEQUAL -> OpBehavior.INT_SLESSEQUAL;
+ case PcodeOp.INT_LESS -> OpBehavior.INT_LESS;
+ case PcodeOp.INT_LESSEQUAL -> OpBehavior.INT_LESSEQUAL;
+ case PcodeOp.INT_ZEXT -> OpBehavior.INT_ZEXT;
+ case PcodeOp.INT_SEXT -> OpBehavior.INT_SEXT;
+ case PcodeOp.INT_ADD -> OpBehavior.INT_ADD;
+ case PcodeOp.INT_SUB -> OpBehavior.INT_SUB;
+ case PcodeOp.INT_CARRY -> OpBehavior.INT_CARRY;
+ case PcodeOp.INT_SCARRY -> OpBehavior.INT_SCARRY;
+ case PcodeOp.INT_SBORROW -> OpBehavior.INT_SBORROW;
+ case PcodeOp.INT_2COMP -> OpBehavior.INT_2COMP;
+ case PcodeOp.INT_NEGATE -> OpBehavior.INT_NEGATE;
+ case PcodeOp.INT_XOR -> OpBehavior.INT_XOR;
+ case PcodeOp.INT_AND -> OpBehavior.INT_AND;
+ case PcodeOp.INT_OR -> OpBehavior.INT_OR;
+ case PcodeOp.INT_LEFT -> OpBehavior.INT_LEFT;
+ case PcodeOp.INT_RIGHT -> OpBehavior.INT_RIGHT;
+ case PcodeOp.INT_SRIGHT -> OpBehavior.INT_SRIGHT;
+ case PcodeOp.INT_MULT -> OpBehavior.INT_MULT;
+ case PcodeOp.INT_DIV -> OpBehavior.INT_DIV;
+ case PcodeOp.INT_SDIV -> OpBehavior.INT_SDIV;
+ case PcodeOp.INT_REM -> OpBehavior.INT_REM;
+ case PcodeOp.INT_SREM -> OpBehavior.INT_SREM;
- opBehaviorMap.put(PcodeOp.CAST, new SpecialOpBehavior(PcodeOp.CAST));
- opBehaviorMap.put(PcodeOp.PTRADD, new SpecialOpBehavior(PcodeOp.PTRADD));
- opBehaviorMap.put(PcodeOp.PTRSUB, new SpecialOpBehavior(PcodeOp.PTRSUB));
+ case PcodeOp.BOOL_NEGATE -> OpBehavior.BOOL_NEGATE;
+ case PcodeOp.BOOL_XOR -> OpBehavior.BOOL_XOR;
+ case PcodeOp.BOOL_AND -> OpBehavior.BOOL_AND;
+ case PcodeOp.BOOL_OR -> OpBehavior.BOOL_OR;
- opBehaviorMap.put(PcodeOp.FLOAT_EQUAL, new OpBehaviorFloatEqual());
- opBehaviorMap.put(PcodeOp.FLOAT_NOTEQUAL, new OpBehaviorFloatNotEqual());
- opBehaviorMap.put(PcodeOp.FLOAT_LESS, new OpBehaviorFloatLess());
- opBehaviorMap.put(PcodeOp.FLOAT_LESSEQUAL, new OpBehaviorFloatLessEqual());
- opBehaviorMap.put(PcodeOp.FLOAT_NAN, new OpBehaviorFloatNan());
+ case PcodeOp.CAST -> OpBehavior.CAST;
+ case PcodeOp.PTRADD -> OpBehavior.PTRADD;
+ case PcodeOp.PTRSUB -> OpBehavior.PTRSUB;
- opBehaviorMap.put(PcodeOp.FLOAT_ADD, new OpBehaviorFloatAdd());
- opBehaviorMap.put(PcodeOp.FLOAT_DIV, new OpBehaviorFloatDiv());
- opBehaviorMap.put(PcodeOp.FLOAT_MULT, new OpBehaviorFloatMult());
- opBehaviorMap.put(PcodeOp.FLOAT_SUB, new OpBehaviorFloatSub());
- opBehaviorMap.put(PcodeOp.FLOAT_NEG, new OpBehaviorFloatNeg());
- opBehaviorMap.put(PcodeOp.FLOAT_ABS, new OpBehaviorFloatAbs());
- opBehaviorMap.put(PcodeOp.FLOAT_SQRT, new OpBehaviorFloatSqrt());
+ case PcodeOp.FLOAT_EQUAL -> OpBehavior.FLOAT_EQUAL;
+ case PcodeOp.FLOAT_NOTEQUAL -> OpBehavior.FLOAT_NOTEQUAL;
+ case PcodeOp.FLOAT_LESS -> OpBehavior.FLOAT_LESS;
+ case PcodeOp.FLOAT_LESSEQUAL -> OpBehavior.FLOAT_LESSEQUAL;
+ case PcodeOp.FLOAT_NAN -> OpBehavior.FLOAT_NAN;
- opBehaviorMap.put(PcodeOp.FLOAT_INT2FLOAT, new OpBehaviorFloatInt2Float());
- opBehaviorMap.put(PcodeOp.FLOAT_FLOAT2FLOAT, new OpBehaviorFloatFloat2Float());
- opBehaviorMap.put(PcodeOp.FLOAT_TRUNC, new OpBehaviorFloatTrunc());
- opBehaviorMap.put(PcodeOp.FLOAT_CEIL, new OpBehaviorFloatCeil());
- opBehaviorMap.put(PcodeOp.FLOAT_FLOOR, new OpBehaviorFloatFloor());
- opBehaviorMap.put(PcodeOp.FLOAT_ROUND, new OpBehaviorFloatRound());
- opBehaviorMap.put(PcodeOp.SEGMENTOP, new SpecialOpBehavior(PcodeOp.SEGMENTOP));
- opBehaviorMap.put(PcodeOp.CPOOLREF, new SpecialOpBehavior(PcodeOp.CPOOLREF));
- opBehaviorMap.put(PcodeOp.NEW, new SpecialOpBehavior(PcodeOp.NEW));
- opBehaviorMap.put(PcodeOp.INSERT, new SpecialOpBehavior(PcodeOp.INSERT));
- opBehaviorMap.put(PcodeOp.ZPULL, new SpecialOpBehavior(PcodeOp.ZPULL));
- opBehaviorMap.put(PcodeOp.POPCOUNT, new OpBehaviorPopcount());
- opBehaviorMap.put(PcodeOp.LZCOUNT, new OpBehaviorLzcount());
- opBehaviorMap.put(PcodeOp.SPULL, new SpecialOpBehavior(PcodeOp.SPULL));
- }
+ case PcodeOp.FLOAT_ADD -> OpBehavior.FLOAT_ADD;
+ case PcodeOp.FLOAT_DIV -> OpBehavior.FLOAT_DIV;
+ case PcodeOp.FLOAT_MULT -> OpBehavior.FLOAT_MULT;
+ case PcodeOp.FLOAT_SUB -> OpBehavior.FLOAT_SUB;
+ case PcodeOp.FLOAT_NEG -> OpBehavior.FLOAT_NEG;
+ case PcodeOp.FLOAT_ABS -> OpBehavior.FLOAT_ABS;
+ case PcodeOp.FLOAT_SQRT -> OpBehavior.FLOAT_SQRT;
- private OpBehaviorFactory() {
- }
+ case PcodeOp.FLOAT_INT2FLOAT -> OpBehavior.FLOAT_INT2FLOAT;
+ case PcodeOp.FLOAT_FLOAT2FLOAT -> OpBehavior.FLOAT_FLOAT2FLOAT;
+ case PcodeOp.FLOAT_TRUNC -> OpBehavior.FLOAT_TRUNC;
+ case PcodeOp.FLOAT_CEIL -> OpBehavior.FLOAT_CEIL;
+ case PcodeOp.FLOAT_FLOOR -> OpBehavior.FLOAT_FLOOR;
+ case PcodeOp.FLOAT_ROUND -> OpBehavior.FLOAT_ROUND;
+ case PcodeOp.SEGMENTOP -> OpBehavior.SEGMENTOP;
+ case PcodeOp.CPOOLREF -> OpBehavior.CPOOLREF;
+ case PcodeOp.NEW -> OpBehavior.NEW;
+ case PcodeOp.INSERT -> OpBehavior.INSERT;
+ case PcodeOp.ZPULL -> OpBehavior.ZPULL;
+ case PcodeOp.POPCOUNT -> OpBehavior.POPCOUNT;
+ case PcodeOp.LZCOUNT -> OpBehavior.LZCOUNT;
+ case PcodeOp.SPULL -> OpBehavior.SPULL;
- public static OpBehavior getOpBehavior(int opcode) {
- return opBehaviorMap.get(opcode);
+ default -> null;
+ };
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbs.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbs.java
index d41d2d30bd..5a5bbbd6f3 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbs.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbs.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatAbs extends UnaryOpBehavior {
+public enum OpBehaviorFloatAbs implements UnaryOpBehavior {
+ OP_FLOAT_ABS;
- public OpBehaviorFloatAbs() {
- super(PcodeOp.FLOAT_ABS);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_ABS;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatAbs extends UnaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opAbs(in1);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAdd.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAdd.java
index 326ea9d282..373350b96e 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAdd.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatAdd.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatAdd extends BinaryOpBehavior {
+public enum OpBehaviorFloatAdd implements BinaryOpBehavior {
+ OP_FLOAT_ADD;
- public OpBehaviorFloatAdd() {
- super(PcodeOp.FLOAT_ADD);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_ADD;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeil.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeil.java
index 62daf683c7..ccb1b12665 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeil.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeil.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatCeil extends UnaryOpBehavior {
+public enum OpBehaviorFloatCeil implements UnaryOpBehavior {
+ OP_FLOAT_CEIL;
- public OpBehaviorFloatCeil() {
- super(PcodeOp.FLOAT_CEIL);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_CEIL;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatCeil extends UnaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opCeil(in1);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatDiv.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatDiv.java
index 4695c85154..9ebfa38b6b 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatDiv.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatDiv.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatDiv extends BinaryOpBehavior {
+public enum OpBehaviorFloatDiv implements BinaryOpBehavior {
+ OP_FLOAT_DIV;
- public OpBehaviorFloatDiv() {
- super(PcodeOp.FLOAT_DIV);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_DIV;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqual.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqual.java
index 1aa9d05da9..79ae1fd2d6 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqual.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqual.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatEqual extends BinaryOpBehavior {
+public enum OpBehaviorFloatEqual implements BinaryOpBehavior {
+ OP_FLOAT_EQUAL;
- public OpBehaviorFloatEqual() {
- super(PcodeOp.FLOAT_EQUAL);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_EQUAL;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatEqual extends BinaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opEqual(in1, in2);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2Float.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2Float.java
index d6d719faa4..df65bc3845 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2Float.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2Float.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatFloat2Float extends UnaryOpBehavior {
+public enum OpBehaviorFloatFloat2Float implements UnaryOpBehavior {
+ OP_FLOAT_FLOAT2FLOAT;
- public OpBehaviorFloatFloat2Float() {
- super(PcodeOp.FLOAT_FLOAT2FLOAT);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_FLOAT2FLOAT;
}
@Override
@@ -41,5 +42,4 @@ public class OpBehaviorFloatFloat2Float extends UnaryOpBehavior {
FloatFormat formatin = FloatFormatFactory.getFloatFormat(sizein);
return formatin.opFloat2Float(in1, formatout);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloor.java
index e2d376fea2..2bc584d995 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloor.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloor.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatFloor extends UnaryOpBehavior {
+public enum OpBehaviorFloatFloor implements UnaryOpBehavior {
+ OP_FLOAT_FLOOR;
- public OpBehaviorFloatFloor() {
- super(PcodeOp.FLOAT_FLOOR);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_FLOOR;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatFloor extends UnaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opFloor(in1);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2Float.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2Float.java
index 838ee1d875..6683eb8e4c 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2Float.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2Float.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatInt2Float extends UnaryOpBehavior {
+public enum OpBehaviorFloatInt2Float implements UnaryOpBehavior {
+ OP_FLOAT_INT2FLOAT;
- public OpBehaviorFloatInt2Float() {
- super(PcodeOp.FLOAT_INT2FLOAT);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_INT2FLOAT;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatInt2Float extends UnaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizeout);
return format.opInt2Float(in1, sizein, true);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLess.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLess.java
index 7e6bff6c6d..f289f4b355 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLess.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLess.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatLess extends BinaryOpBehavior {
+public enum OpBehaviorFloatLess implements BinaryOpBehavior {
+ OP_FLOAT_LESS;
- public OpBehaviorFloatLess() {
- super(PcodeOp.FLOAT_LESS);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_LESS;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqual.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqual.java
index 8982a56064..9a5bd6e81d 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqual.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqual.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatLessEqual extends BinaryOpBehavior {
+public enum OpBehaviorFloatLessEqual implements BinaryOpBehavior {
+ OP_FLOAT_LESSEQUAL;
- public OpBehaviorFloatLessEqual() {
- super(PcodeOp.FLOAT_LESSEQUAL);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_LESSEQUAL;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatLessEqual extends BinaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opLessEqual(in1, in2);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatMult.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatMult.java
index 6eb43f6939..8c1b1d1612 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatMult.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatMult.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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatMult extends BinaryOpBehavior {
+public enum OpBehaviorFloatMult implements BinaryOpBehavior {
+ OP_FLOAT_MULT;
- public OpBehaviorFloatMult() {
- super(PcodeOp.FLOAT_MULT);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_MULT;
}
@Override
@@ -38,5 +40,4 @@ public class OpBehaviorFloatMult extends BinaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opMult(in1, in2);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNan.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNan.java
index 3d6c3dfef0..42b8e734b5 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNan.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNan.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatNan extends UnaryOpBehavior {
+public enum OpBehaviorFloatNan implements UnaryOpBehavior {
+ OP_FLOAT_NAN;
- public OpBehaviorFloatNan() {
- super(PcodeOp.FLOAT_NAN);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_NAN;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNeg.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNeg.java
index d0a83465a3..e14615be6f 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNeg.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNeg.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatNeg extends UnaryOpBehavior {
+public enum OpBehaviorFloatNeg implements UnaryOpBehavior {
+ OP_FLOAT_NEG;
- public OpBehaviorFloatNeg() {
- super(PcodeOp.FLOAT_NEG);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_NEG;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatNeg extends UnaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opNeg(in1);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqual.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqual.java
index b559c02589..146185b8a5 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqual.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqual.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatNotEqual extends BinaryOpBehavior {
+public enum OpBehaviorFloatNotEqual implements BinaryOpBehavior {
+ OP_FLOAT_NOTEQUAL;
- public OpBehaviorFloatNotEqual() {
- super(PcodeOp.FLOAT_NOTEQUAL);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_NOTEQUAL;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatNotEqual extends BinaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opNotEqual(in1, in2);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatRound.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatRound.java
index 602e26290d..045944f04b 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatRound.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatRound.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatRound extends UnaryOpBehavior {
+public enum OpBehaviorFloatRound implements UnaryOpBehavior {
+ OP_FLOAT_ROUND;
- public OpBehaviorFloatRound() {
- super(PcodeOp.FLOAT_ROUND);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_ROUND;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatRound extends UnaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opRound(in1);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrt.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrt.java
index df023f709c..7f73c7adf5 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrt.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrt.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatSqrt extends UnaryOpBehavior {
+public enum OpBehaviorFloatSqrt implements UnaryOpBehavior {
+ OP_FLOAT_SQRT;
- public OpBehaviorFloatSqrt() {
- super(PcodeOp.FLOAT_SQRT);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_SQRT;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatSqrt extends UnaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opSqrt(in1);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSub.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSub.java
index 1ebb509342..f5c9fc209b 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSub.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatSub.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatSub extends BinaryOpBehavior {
+public enum OpBehaviorFloatSub implements BinaryOpBehavior {
+ OP_FLOAT_SUB;
- public OpBehaviorFloatSub() {
- super(PcodeOp.FLOAT_SUB);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_SUB;
}
@Override
@@ -39,5 +40,4 @@ public class OpBehaviorFloatSub extends BinaryOpBehavior {
FloatFormat format = FloatFormatFactory.getFloatFormat(sizein);
return format.opSub(in1, in2);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatTrunc.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatTrunc.java
index 125f36dac4..24d7a943c6 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatTrunc.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorFloatTrunc.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.floatformat.FloatFormat;
import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorFloatTrunc extends UnaryOpBehavior {
+public enum OpBehaviorFloatTrunc implements UnaryOpBehavior {
+ OP_FLOAT_TRUNC;
- public OpBehaviorFloatTrunc() {
- super(PcodeOp.FLOAT_TRUNC);
+ @Override
+ public int opcode() {
+ return PcodeOp.FLOAT_TRUNC;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorInt2Comp.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorInt2Comp.java
index 8ccf4505fb..74875a6a17 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorInt2Comp.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorInt2Comp.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.util.exception.AssertException;
-import java.math.BigInteger;
-
-public class OpBehaviorInt2Comp extends UnaryOpBehavior {
+public enum OpBehaviorInt2Comp implements UnaryOpBehavior {
+ OP_INT_2COMP;
- public OpBehaviorInt2Comp() {
- super(PcodeOp.INT_2COMP);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_2COMP;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAdd.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAdd.java
index b3c57fdfd2..3abd5764f4 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAdd.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAdd.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntAdd extends BinaryOpBehavior {
+public enum OpBehaviorIntAdd implements BinaryOpBehavior {
+ OP_INT_ADD;
- public OpBehaviorIntAdd() {
- super(PcodeOp.INT_ADD);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_ADD;
}
@Override
@@ -38,5 +39,4 @@ public class OpBehaviorIntAdd extends BinaryOpBehavior {
BigInteger res = in1.add(in2);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAnd.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAnd.java
index 8cfdb9a1ee..88ee8dd532 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAnd.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntAnd.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorIntAnd extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorIntAnd implements BinaryOpBehavior {
+ OP_INT_AND;
- public OpBehaviorIntAnd() {
- super(PcodeOp.INT_AND);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_AND;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntCarry.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntCarry.java
index c78d2d474f..34af1cb4a9 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntCarry.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntCarry.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.
@@ -21,10 +21,12 @@ import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.util.exception.AssertException;
-public class OpBehaviorIntCarry extends BinaryOpBehavior {
+public enum OpBehaviorIntCarry implements BinaryOpBehavior {
+ OP_INT_CARRY;
- public OpBehaviorIntCarry() {
- super(PcodeOp.INT_CARRY);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_CARRY;
}
@Override
@@ -42,5 +44,4 @@ public class OpBehaviorIntCarry extends BinaryOpBehavior {
: BigInteger.ZERO;
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntDiv.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntDiv.java
index 92c8478b6b..8147711f5a 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntDiv.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntDiv.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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntDiv extends BinaryOpBehavior {
+public enum OpBehaviorIntDiv implements BinaryOpBehavior {
+ OP_INT_DEV;
- public OpBehaviorIntDiv() {
- super(PcodeOp.INT_DIV);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_DIV;
}
@Override
@@ -33,7 +35,7 @@ public class OpBehaviorIntDiv extends BinaryOpBehavior {
if (in1 == in2)
return 1;
if (sizein == 8) {
- long mask = (0x1<<63);
+ long mask = (0x1 << 63);
long bit1 = in1 & mask; // Get the sign bits
long bit2 = in2 & mask;
if (bit1 != 0 || bit2 != 0) {
@@ -65,5 +67,4 @@ public class OpBehaviorIntDiv extends BinaryOpBehavior {
BigInteger res = in1.divide(in2);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLeft.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLeft.java
index 1fcc627442..df0ae4100b 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLeft.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLeft.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.util.exception.AssertException;
-import java.math.BigInteger;
-
-public class OpBehaviorIntLeft extends BinaryOpBehavior {
+public enum OpBehaviorIntLeft implements BinaryOpBehavior {
+ OP_INT_LEFT;
- public OpBehaviorIntLeft() {
- super(PcodeOp.INT_LEFT);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_LEFT;
}
@Override
@@ -47,5 +48,4 @@ public class OpBehaviorIntLeft extends BinaryOpBehavior {
}
return in1.shiftLeft(in2.intValue());
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLess.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLess.java
index 9bcaabbdda..56fb91b515 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLess.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLess.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntLess extends BinaryOpBehavior {
+public enum OpBehaviorIntLess implements BinaryOpBehavior {
+ OP_INT_LESS;
- public OpBehaviorIntLess() {
- super(PcodeOp.INT_LESS);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_LESS;
}
@Override
@@ -62,5 +63,4 @@ public class OpBehaviorIntLess extends BinaryOpBehavior {
BigInteger res = (in1.compareTo(in2) < 0) ? BigInteger.ONE : BigInteger.ZERO;
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqual.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqual.java
index 131a7f8cd2..0822185161 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqual.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqual.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntLessEqual extends BinaryOpBehavior {
+public enum OpBehaviorIntLessEqual implements BinaryOpBehavior {
+ OP_INT_LESSEQUAL;
- public OpBehaviorIntLessEqual() {
- super(PcodeOp.INT_LESSEQUAL);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_LESSEQUAL;
}
@Override
@@ -62,5 +63,4 @@ public class OpBehaviorIntLessEqual extends BinaryOpBehavior {
BigInteger res = (in1.compareTo(in2) <= 0) ? BigInteger.ONE : BigInteger.ZERO;
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntMult.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntMult.java
index 0274b135be..85b5abd74e 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntMult.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntMult.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntMult extends BinaryOpBehavior {
+public enum OpBehaviorIntMult implements BinaryOpBehavior {
+ OP_INT_MULT;
- public OpBehaviorIntMult() {
- super(PcodeOp.INT_MULT);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_MULT;
}
@Override
@@ -38,5 +39,4 @@ public class OpBehaviorIntMult extends BinaryOpBehavior {
BigInteger res = in1.multiply(in2);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntNegate.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntNegate.java
index e2da8fe184..2b4537b6ab 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntNegate.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntNegate.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.util.exception.AssertException;
-import java.math.BigInteger;
-
-public class OpBehaviorIntNegate extends UnaryOpBehavior {
+public enum OpBehaviorIntNegate implements UnaryOpBehavior {
+ OP_INT_NEGATE;
- public OpBehaviorIntNegate() {
- super(PcodeOp.INT_NEGATE);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_NEGATE;
}
@Override
@@ -41,5 +42,4 @@ public class OpBehaviorIntNegate extends UnaryOpBehavior {
}
return in1.not();
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntOr.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntOr.java
index 52eafdaad0..c4e5ca39a4 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntOr.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntOr.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorIntOr extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorIntOr implements BinaryOpBehavior {
+ OP_INT_OR;
- public OpBehaviorIntOr() {
- super(PcodeOp.INT_OR);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_OR;
}
@Override
@@ -37,5 +38,4 @@ public class OpBehaviorIntOr extends BinaryOpBehavior {
BigInteger res = in1.or(in2);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRem.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRem.java
index 97535b67ce..142d26b846 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRem.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRem.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,10 +20,12 @@ import java.math.BigInteger;
import ghidra.pcode.error.LowlevelError;
import ghidra.program.model.pcode.PcodeOp;
-public class OpBehaviorIntRem extends BinaryOpBehavior {
+public enum OpBehaviorIntRem implements BinaryOpBehavior {
+ OP_INT_REM;
- public OpBehaviorIntRem() {
- super(PcodeOp.INT_REM);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_REM;
}
@Override
@@ -42,5 +44,4 @@ public class OpBehaviorIntRem extends BinaryOpBehavior {
BigInteger res = in1.remainder(in2);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRight.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRight.java
index 65f451a238..024417b67f 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRight.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntRight.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.util.exception.AssertException;
-import java.math.BigInteger;
-
-public class OpBehaviorIntRight extends BinaryOpBehavior {
+public enum OpBehaviorIntRight implements BinaryOpBehavior {
+ OP_INT_RIGHT;
- public OpBehaviorIntRight() {
- super(PcodeOp.INT_RIGHT);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_RIGHT;
}
@Override
@@ -48,5 +49,4 @@ public class OpBehaviorIntRight extends BinaryOpBehavior {
}
return in1.shiftRight(in2.intValue());
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSborrow.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSborrow.java
index e404782eca..9116631052 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSborrow.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSborrow.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorIntSborrow extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorIntSborrow implements BinaryOpBehavior {
+ OP_INT_SBORROW;
- public OpBehaviorIntSborrow() {
- super(PcodeOp.INT_SBORROW);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SBORROW;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntScarry.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntScarry.java
index e8037b486b..7b97fa40e7 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntScarry.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntScarry.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorIntScarry extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorIntScarry implements BinaryOpBehavior {
+ OP_INT_SCARRY;
- public OpBehaviorIntScarry() {
- super(PcodeOp.INT_SCARRY);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SCARRY;
}
@Override
@@ -55,5 +56,4 @@ public class OpBehaviorIntScarry extends BinaryOpBehavior {
r &= a;
return r ? BigInteger.ONE : BigInteger.ZERO;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSdiv.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSdiv.java
index f71f73d84f..63b9d6954e 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSdiv.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSdiv.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.error.LowlevelError;
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntSdiv extends BinaryOpBehavior {
+public enum OpBehaviorIntSdiv implements BinaryOpBehavior {
+ OP_INT_SDIV;
- public OpBehaviorIntSdiv() {
- super(PcodeOp.INT_SDIV);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SDIV;
}
@Override
@@ -51,5 +52,4 @@ public class OpBehaviorIntSdiv extends BinaryOpBehavior {
in2 = Utils.convertToSignedValue(in2, sizein);
return in1.divide(in2);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSext.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSext.java
index 3c9040c5ab..49684d200a 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSext.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSext.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntSext extends UnaryOpBehavior {
+public enum OpBehaviorIntSext implements UnaryOpBehavior {
+ OP_INT_SEXT;
- public OpBehaviorIntSext() {
- super(PcodeOp.INT_SEXT);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SEXT;
}
@Override
@@ -37,21 +38,4 @@ public class OpBehaviorIntSext extends UnaryOpBehavior {
public BigInteger evaluateUnary(int sizeout, int sizein, BigInteger in1) {
return Utils.convertToSignedValue(in1, sizein);
}
-
-// @Override
-// public long recoverInputUnary(int sizeout, long out, int sizein) {
-// long masklong = Utils.calc_mask(sizeout);
-// long maskshort = Utils.calc_mask(sizein);
-//
-// if ((out & (maskshort ^ (maskshort >>> 1))) == 0) { // Positive input
-// if ((out & maskshort) != out)
-// throw new LowlevelError(
-// "Output is not in range of sext operation");
-// } else { // Negative input
-// if ((out & (masklong ^ maskshort)) != (masklong ^ maskshort))
-// throw new LowlevelError(
-// "Output is not in range of sext operation");
-// }
-// return (out & maskshort);
-// }
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSless.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSless.java
index a8ac7c25ee..f39de6b1b2 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSless.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSless.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntSless extends BinaryOpBehavior {
+public enum OpBehaviorIntSless implements BinaryOpBehavior {
+ OP_INT_SLESS;
- public OpBehaviorIntSless() {
- super(PcodeOp.INT_SLESS);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SLESS;
}
@Override
@@ -55,5 +56,4 @@ public class OpBehaviorIntSless extends BinaryOpBehavior {
in2 = Utils.convertToSignedValue(in2, sizein);
return (in1.compareTo(in2) < 0) ? BigInteger.ONE : BigInteger.ZERO;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSlessEqual.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSlessEqual.java
index 5e2a17af0a..095af79e3e 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSlessEqual.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSlessEqual.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntSlessEqual extends BinaryOpBehavior {
+public enum OpBehaviorIntSlessEqual implements BinaryOpBehavior {
+ OP_INT_SLESSEQUAL;
- public OpBehaviorIntSlessEqual() {
- super(PcodeOp.INT_SLESSEQUAL);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SLESSEQUAL;
}
@Override
@@ -55,5 +56,4 @@ public class OpBehaviorIntSlessEqual extends BinaryOpBehavior {
in2 = Utils.convertToSignedValue(in2, sizein);
return (in1.compareTo(in2) <= 0) ? BigInteger.ONE : BigInteger.ZERO;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSrem.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSrem.java
index 3645e10a8d..f4c294512d 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSrem.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSrem.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.error.LowlevelError;
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntSrem extends BinaryOpBehavior {
+public enum OpBehaviorIntSrem implements BinaryOpBehavior {
+ OP_INT_SREM;
- public OpBehaviorIntSrem() {
- super(PcodeOp.INT_SREM);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SREM;
}
@Override
@@ -53,5 +54,4 @@ public class OpBehaviorIntSrem extends BinaryOpBehavior {
in2 = Utils.convertToSignedValue(in2, sizein);
return in1.remainder(in2);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSright.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSright.java
index dc0105c62a..087589d29f 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSright.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSright.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,16 +15,18 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.util.exception.AssertException;
-import java.math.BigInteger;
-
-public class OpBehaviorIntSright extends BinaryOpBehavior {
+public enum OpBehaviorIntSright implements BinaryOpBehavior {
+ OP_INT_SRIGHT;
- public OpBehaviorIntSright() {
- super(PcodeOp.INT_SRIGHT);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SRIGHT;
}
@Override
@@ -65,5 +66,4 @@ public class OpBehaviorIntSright extends BinaryOpBehavior {
}
return in1.shiftRight(in2.intValue());
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSub.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSub.java
index 76cd781774..56844dad57 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSub.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntSub.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorIntSub extends BinaryOpBehavior {
+public enum OpBehaviorIntSub implements BinaryOpBehavior {
+ OP_INT_SUB;
- public OpBehaviorIntSub() {
- super(PcodeOp.INT_SUB);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_SUB;
}
@Override
@@ -38,5 +39,4 @@ public class OpBehaviorIntSub extends BinaryOpBehavior {
BigInteger res = in1.subtract(in2);
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntXor.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntXor.java
index 270c262983..4ef28199c9 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntXor.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntXor.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorIntXor extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorIntXor implements BinaryOpBehavior {
+ OP_INT_XOR;
- public OpBehaviorIntXor() {
- super(PcodeOp.INT_XOR);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_XOR;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntZext.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntZext.java
index 7a0329063e..1111260532 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntZext.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorIntZext.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorIntZext extends UnaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorIntZext implements UnaryOpBehavior {
+ OP_INT_ZEXT;
- public OpBehaviorIntZext() {
- super(PcodeOp.INT_ZEXT);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_ZEXT;
}
@Override
@@ -35,12 +36,4 @@ public class OpBehaviorIntZext extends UnaryOpBehavior {
public BigInteger evaluateUnary(int sizeout, int sizein, BigInteger in1) {
return in1;
}
-
-// @Override
-// public long recoverInputUnary(int sizeout, long out, int sizein) {
-// long mask = Utils.calc_mask(sizein);
-// if ((mask & out) != out)
-// throw new LowlevelError("Output is not in range of zext operation");
-// return out;
-// }
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorLzcount.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorLzcount.java
index 0b55c50537..6cdf9e2781 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorLzcount.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorLzcount.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,10 +19,12 @@ import java.math.BigInteger;
import ghidra.program.model.pcode.PcodeOp;
-public class OpBehaviorLzcount extends UnaryOpBehavior {
+public enum OpBehaviorLzcount implements UnaryOpBehavior {
+ OP_LZCOUNT;
- public OpBehaviorLzcount() {
- super(PcodeOp.LZCOUNT);
+ @Override
+ public int opcode() {
+ return PcodeOp.LZCOUNT;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorNotEqual.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorNotEqual.java
index 255b6fb38d..fb8cdf4d86 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorNotEqual.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorNotEqual.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorNotEqual extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorNotEqual implements BinaryOpBehavior {
+ OP_INT_NOTEQUAL;
- public OpBehaviorNotEqual() {
- super(PcodeOp.INT_NOTEQUAL);
+ @Override
+ public int opcode() {
+ return PcodeOp.INT_NOTEQUAL;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPiece.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPiece.java
index ceab930748..1f68b260c3 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPiece.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPiece.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,14 +15,16 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.program.model.pcode.PcodeOp;
-
import java.math.BigInteger;
-public class OpBehaviorPiece extends BinaryOpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum OpBehaviorPiece implements BinaryOpBehavior {
+ OP_PIECE;
- public OpBehaviorPiece() {
- super(PcodeOp.PIECE);
+ @Override
+ public int opcode() {
+ return PcodeOp.PIECE;
}
@Override
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPopcount.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPopcount.java
index fe44999160..03eda02096 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPopcount.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorPopcount.java
@@ -19,10 +19,12 @@ import java.math.BigInteger;
import ghidra.program.model.pcode.PcodeOp;
-public class OpBehaviorPopcount extends UnaryOpBehavior {
+public enum OpBehaviorPopcount implements UnaryOpBehavior {
+ OP_POPCOUNT;
- public OpBehaviorPopcount() {
- super(PcodeOp.POPCOUNT);
+ @Override
+ public int opcode() {
+ return PcodeOp.POPCOUNT;
}
@Override
@@ -34,5 +36,4 @@ public class OpBehaviorPopcount extends UnaryOpBehavior {
public BigInteger evaluateUnary(int sizeout, int sizein, BigInteger unsignedIn1) {
return BigInteger.valueOf(unsignedIn1.bitCount());
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorSubpiece.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorSubpiece.java
index 02325b11fe..76929780f3 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorSubpiece.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/OpBehaviorSubpiece.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,15 +15,17 @@
*/
package ghidra.pcode.opbehavior;
+import java.math.BigInteger;
+
import ghidra.pcode.utils.Utils;
import ghidra.program.model.pcode.PcodeOp;
-import java.math.BigInteger;
-
-public class OpBehaviorSubpiece extends BinaryOpBehavior {
+public enum OpBehaviorSubpiece implements BinaryOpBehavior {
+ OP_SUBPIECE;
- public OpBehaviorSubpiece() {
- super(PcodeOp.SUBPIECE);
+ @Override
+ public int opcode() {
+ return PcodeOp.SUBPIECE;
}
@Override
@@ -51,5 +52,4 @@ public class OpBehaviorSubpiece extends BinaryOpBehavior {
}
return res;
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/SpecialOpBehavior.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/SpecialOpBehavior.java
index 252f229d15..3d3d460f10 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/SpecialOpBehavior.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/SpecialOpBehavior.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,10 +15,41 @@
*/
package ghidra.pcode.opbehavior;
-public class SpecialOpBehavior extends OpBehavior {
+import ghidra.program.model.pcode.PcodeOp;
+
+public enum SpecialOpBehavior implements OpBehavior {
+ OP_LOAD(PcodeOp.LOAD),
+ OP_STORE(PcodeOp.STORE),
+ OP_BRANCH(PcodeOp.BRANCH),
+ OP_CBRANCH(PcodeOp.CBRANCH),
+ OP_BRANCHIND(PcodeOp.BRANCHIND),
+ OP_CALL(PcodeOp.CALL),
+ OP_CALLIND(PcodeOp.CALLIND),
+ OP_CALLOTHER(PcodeOp.CALLOTHER),
+ OP_RETURN(PcodeOp.RETURN),
+
+ OP_MULTIEQUAL(PcodeOp.MULTIEQUAL),
+ OP_INDIRECT(PcodeOp.INDIRECT),
+
+ OP_CAST(PcodeOp.CAST),
+ OP_PTRADD(PcodeOp.PTRADD),
+ OP_PTRSUB(PcodeOp.PTRSUB),
+
+ OP_SEGMENTOP(PcodeOp.SEGMENTOP),
+ OP_CPOOLREF(PcodeOp.CPOOLREF),
+ OP_NEW(PcodeOp.NEW),
+ OP_INSERT(PcodeOp.INSERT),
+ OP_ZPULL(PcodeOp.ZPULL),
+ OP_SPULL(PcodeOp.SPULL);
+
+ private final int opcode;
SpecialOpBehavior(int opcode) {
- super(opcode);
+ this.opcode = opcode;
}
+ @Override
+ public int opcode() {
+ return opcode;
+ }
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/UnaryOpBehavior.java b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/UnaryOpBehavior.java
index 201244b8bd..91b59075e3 100644
--- a/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/UnaryOpBehavior.java
+++ b/Ghidra/Framework/Emulation/src/main/java/ghidra/pcode/opbehavior/UnaryOpBehavior.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in 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,26 +15,26 @@
*/
package ghidra.pcode.opbehavior;
-import ghidra.pcode.utils.Utils;
-
import java.math.BigInteger;
-public abstract class UnaryOpBehavior extends OpBehavior {
-
- UnaryOpBehavior(int opcode) {
- super(opcode);
- }
+import ghidra.pcode.utils.Utils;
+/**
+ * The implementation of a unary (1 input arg, 1 output) p-code operator
+ */
+public interface UnaryOpBehavior extends OpBehavior {
/**
* Evaluate the unary operation using long data
+ * <p>
+ * NOTE: if the operation overflows bits may be set beyond the specified sizeout. Even though
+ * results should be treated as unsigned it may be returned as a signed long value. It is
+ * expected that the returned result always be properly truncated by the caller since the
+ * evaluation may not - this is done to conserve emulation cycles.
+ *
* @param sizeout intended output size (bytes)
* @param sizein in1 size (bytes)
* @param unsignedIn1 unsigned input 1
- * @return operation result. NOTE: if the operation overflows bits may be
- * set beyond the specified sizeout. Even though results should be treated
- * as unsigned it may be returned as a signed long value. It is expected that the
- * returned result always be properly truncated by the caller since the evaluation
- * may not - this is done to conserve emulation cycles.
+ * @return operation result.
* @see Utils#longToBytes(long, int, boolean)
* @see Utils#bytesToLong(byte[], int, boolean)
*/
@@ -43,16 +42,18 @@ public abstract class UnaryOpBehavior extends OpBehavior {
/**
* Evaluate the unary operation using BigInteger data
+ * <p>
+ * NOTE: if the operation overflows bits may be set beyond the specified sizeout. Even though
+ * results should be treated as unsigned it may be returned as a signed value. It is expected
+ * that the returned result always be properly truncated by the caller since the evaluation may
+ * not - this is done to conserve emulation cycles.
+ *
* @param sizeout intended output size (bytes)
* @param sizein in1 size (bytes)
* @param unsignedIn1 unsigned input 1
- * @return operation result. NOTE: if the operation overflows bits may be
- * set beyond the specified sizeout. Even though results should be treated
- * as unsigned it may be returned as a signed value. It is expected that the
- * returned result always be properly truncated by the caller since the evaluation
- * may not - this is done to conserve emulation cycles.
+ * @return operation result.
* @see Utils#bigIntegerToBytes(BigInteger, int, boolean)
- * @see Utils#bytesToBigInteger(byte[], int, boolean, boolean)
+ * @see Utils#bytesToBigInteger(byte[], int, boolean, boolean)
*/
public abstract BigInteger evaluateUnary(int sizeout, int sizein, BigInteger unsignedIn1);
}
diff --git a/Ghidra/Framework/Emulation/src/main/java/utilities/util/AnnotationUtilities.java b/Ghidra/Framework/Emulation/src/main/java/utilities/util/AnnotationUtilities.java
index 56daee83ba..4cb99fc3cc 100644
--- a/Ghidra/Framework/Emulation/src/main/java/utilities/util/AnnotationUtilities.java
+++ b/Ghidra/Framework/Emulation/src/main/java/utilities/util/AnnotationUtilities.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.
@@ -42,8 +42,7 @@ public enum AnnotationUtilities {
}
private static void collectAnnotatedMethods(Class<? extends Annotation> annotCls, Class<?> cls,
- Set<Method> defs,
- Set<Class<?>> visited) {
+ Set<Method> defs, Set<Class<?>> visited) {
if (!visited.add(cls)) {
return;
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/AbstractFoldedArithmeticTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/AbstractFoldedArithmeticTest.java
new file mode 100644
index 0000000000..688285784f
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/AbstractFoldedArithmeticTest.java
@@ -0,0 +1,258 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.folding;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import ghidra.program.model.lang.Endian;
+import ghidra.program.model.pcode.PcodeOp;
+
+public abstract class AbstractFoldedArithmeticTest {
+ abstract Endian getEndian();
+
+ final Endian endian = getEndian();
+ final FoldedArithmetic arithmetic = FoldedArithmetic.forEndian(endian);
+
+ MaskedBytes ofFloat(float f) {
+ return MaskedBytes.of(Float.floatToRawIntBits(f), -1, 4, endian);
+ }
+
+ MaskedBytes ofFloatMasked(float f, int msk) {
+ return MaskedBytes.of(Float.floatToRawIntBits(f), msk, 4, endian);
+ }
+
+ @Test
+ public void testCopy() {
+ MaskedBytes mb = MaskedBytes.of(0x1234, -1, 2, endian);
+ assertEquals(mb, arithmetic.unaryOp(PcodeOp.COPY, 2, 2, mb));
+ }
+
+ @Test
+ public void testNegate() {
+ assertEquals(MaskedBytes.of(~0x1234, -1, 2, endian),
+ arithmetic.unaryOp(PcodeOp.INT_NEGATE, 2, 2,
+ MaskedBytes.of(0x1234, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(~0x1234, 0x7fff, 2, endian),
+ arithmetic.unaryOp(PcodeOp.INT_NEGATE, 2, 2,
+ MaskedBytes.of(0x1234, 0x7fff, 2, endian)));
+ }
+
+ @Test
+ public void testFloatAbs() {
+ assertEquals(ofFloat(0.5f), arithmetic.unaryOp(PcodeOp.FLOAT_ABS, 4, 4, ofFloat(0.5f)));
+ assertEquals(ofFloat(0.5f), arithmetic.unaryOp(PcodeOp.FLOAT_ABS, 4, 4, ofFloat(-0.5f)));
+ assertEquals(ofFloat(0.5f),
+ arithmetic.unaryOp(PcodeOp.FLOAT_ABS, 4, 4, ofFloatMasked(0.5f, 0x7fffffff)));
+ assertEquals(ofFloatMasked(0.5f, 0xbfffffff),
+ arithmetic.unaryOp(PcodeOp.FLOAT_ABS, 4, 4, ofFloatMasked(0.5f, 0x3fffffff)));
+ }
+
+ @Test
+ public void testFloatNeg() {
+ assertEquals(ofFloat(-0.5f), arithmetic.unaryOp(PcodeOp.FLOAT_NEG, 4, 4, ofFloat(0.5f)));
+ assertEquals(ofFloat(0.5f), arithmetic.unaryOp(PcodeOp.FLOAT_NEG, 4, 4, ofFloat(-0.5f)));
+ assertEquals(ofFloatMasked(0.5f, 0x7fffffff),
+ arithmetic.unaryOp(PcodeOp.FLOAT_NEG, 4, 4, ofFloatMasked(0.5f, 0x7fffffff)));
+ assertEquals(ofFloatMasked(-0.5f, 0xbfffffff),
+ arithmetic.unaryOp(PcodeOp.FLOAT_NEG, 4, 4, ofFloatMasked(0.5f, 0xbfffffff)));
+ assertEquals(ofFloatMasked(0.5f, 0xbfffffff),
+ arithmetic.unaryOp(PcodeOp.FLOAT_NEG, 4, 4, ofFloatMasked(-0.5f, 0xbfffffff)));
+ }
+
+ @Test
+ public void testIntSExt() {
+ assertEquals(MaskedBytes.of(-1, -1, 4, endian),
+ arithmetic.unaryOp(PcodeOp.INT_SEXT, 4, 2, MaskedBytes.of(-1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(1, -1, 4, endian),
+ arithmetic.unaryOp(PcodeOp.INT_SEXT, 4, 2, MaskedBytes.of(1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0xffff8000, -1, 4, endian),
+ arithmetic.unaryOp(PcodeOp.INT_SEXT, 4, 2, MaskedBytes.of(0x8000, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0, 0, 4, endian),
+ arithmetic.unaryOp(PcodeOp.INT_SEXT, 4, 2, MaskedBytes.of(0, 0, 2, endian)));
+ }
+
+ @Test
+ public void testIntZExt() {
+ assertEquals(MaskedBytes.of(0xffff, -1, 4, endian),
+ arithmetic.unaryOp(PcodeOp.INT_ZEXT, 4, 2, MaskedBytes.of(-1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(1, -1, 4, endian),
+ arithmetic.unaryOp(PcodeOp.INT_ZEXT, 4, 2, MaskedBytes.of(1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0x00008000, -1, 4, endian),
+ arithmetic.unaryOp(PcodeOp.INT_ZEXT, 4, 2, MaskedBytes.of(0x8000, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0, 0xffff0000, 4, endian), // Upper bits become known 0s
+ arithmetic.unaryOp(PcodeOp.INT_ZEXT, 4, 2, MaskedBytes.of(0, 0, 2, endian)));
+ }
+
+ @Test
+ public void testUnaryMisc() {
+ assertEquals(ofFloat((float) Math.sqrt(0.5f)),
+ arithmetic.unaryOp(PcodeOp.FLOAT_SQRT, 4, 4, ofFloat(0.5f)));
+ assertEquals(MaskedBytes.ofUnknown(4),
+ arithmetic.unaryOp(PcodeOp.FLOAT_SQRT, 4, 4, ofFloatMasked(0.5f, 0xffff7fff)));
+ }
+
+ @Test
+ public void testIntAnd() {
+ // 01x01x01x
+ // & 000111xxx
+ // -----------
+ // 00001x0xx
+ assertEquals(MaskedBytes.of(0b000010000, 0b111110100, 4, endian),
+ arithmetic.binaryOp(PcodeOp.INT_AND, 4,
+ 4, MaskedBytes.of(0b010010010, 0b110110110, 4, endian),
+ 4, MaskedBytes.of(0b000111000, 0b111111000, 4, endian)));
+ }
+
+ @Test
+ public void testIntOr() {
+ // 01x01x01x
+ // | 000111xxx
+ // -----------
+ // 01x111x1x
+ assertEquals(MaskedBytes.of(0b010111010, 0b110111010, 4, endian),
+ arithmetic.binaryOp(PcodeOp.INT_OR, 4,
+ 4, MaskedBytes.of(0b010010010, 0b110110110, 4, endian),
+ 4, MaskedBytes.of(0b000111000, 0b111111000, 4, endian)));
+ }
+
+ @Test
+ public void testIntXor() {
+ // 01x01x01x
+ // ^ 000111xxx
+ // -----------
+ // 01x10xxxx
+ assertEquals(MaskedBytes.of(0b010100000, 0b110110000, 4, endian),
+ arithmetic.binaryOp(PcodeOp.INT_XOR, 4,
+ 4, MaskedBytes.of(0b010010010, 0b110110110, 4, endian),
+ 4, MaskedBytes.of(0b000111000, 0b111111000, 4, endian)));
+ }
+
+ @Test
+ public void testLeft() {
+ // Right is filled with known 0s
+ assertEquals(MaskedBytes.of(0x0460, 0x1fe1, 4, endian),
+ arithmetic.binaryOp(PcodeOp.INT_LEFT, 4,
+ 4, MaskedBytes.of(0x0230, 0x0ff0, 4, endian),
+ 4, MaskedBytes.of(1, -1, 4, endian)));
+ assertEquals(MaskedBytes.ofUnknown(4),
+ arithmetic.binaryOp(PcodeOp.INT_LEFT, 4,
+ 4, MaskedBytes.of(0x0230, 0x0ff0, 4, endian),
+ 4, MaskedBytes.of(1, 0xfffffffb, 4, endian)));
+
+ // What if value is all known 0s? Shift amount wouldn't matter.
+ }
+
+ @Test
+ public void testRight() {
+ // Left is filled with known 0s
+ assertEquals(MaskedBytes.of(0x0118, 0x87f8, 2, endian),
+ arithmetic.binaryOp(PcodeOp.INT_RIGHT, 2,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 2, MaskedBytes.of(1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0x0118, 0xfff8, 2, endian),
+ arithmetic.binaryOp(PcodeOp.INT_RIGHT, 2,
+ 2, MaskedBytes.of(0x0230, 0xfff0, 2, endian),
+ 2, MaskedBytes.of(1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0x4118, 0xfff8, 2, endian),
+ arithmetic.binaryOp(PcodeOp.INT_RIGHT, 2,
+ 2, MaskedBytes.of(0x8230, 0xfff0, 2, endian),
+ 2, MaskedBytes.of(1, -1, 2, endian)));
+
+ assertEquals(MaskedBytes.ofUnknown(2),
+ arithmetic.binaryOp(PcodeOp.INT_RIGHT, 2,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 2, MaskedBytes.of(1, 0xfffffffb, 2, endian)));
+
+ // What if value is all known 0s? Shift amount wouldn't matter.
+ }
+
+ @Test
+ public void testSRight() {
+ // Left is filled with sign bit
+ assertEquals(MaskedBytes.of(0x0118, 0x07f8, 2, endian),
+ arithmetic.binaryOp(PcodeOp.INT_SRIGHT, 2,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 2, MaskedBytes.of(1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0x0118, 0xfff8, 2, endian),
+ arithmetic.binaryOp(PcodeOp.INT_SRIGHT, 2,
+ 2, MaskedBytes.of(0x0230, 0xfff0, 2, endian),
+ 2, MaskedBytes.of(1, -1, 2, endian)));
+ assertEquals(MaskedBytes.of(0xc118, 0xfff8, 2, endian),
+ arithmetic.binaryOp(PcodeOp.INT_SRIGHT, 2,
+ 2, MaskedBytes.of(0x8230, 0xfff0, 2, endian),
+ 2, MaskedBytes.of(1, -1, 2, endian)));
+
+ assertEquals(MaskedBytes.ofUnknown(2),
+ arithmetic.binaryOp(PcodeOp.INT_SRIGHT, 2,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 2, MaskedBytes.of(1, 0xfffffffb, 2, endian)));
+
+ // What if value is all known 0s? Shift amount wouldn't matter.
+ }
+
+ @Test
+ public void testSubPiece() {
+ // Left is filled with known 0s, if needed
+ // Identity
+ assertEquals(MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ arithmetic.binaryOp(PcodeOp.SUBPIECE, 2,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 1, MaskedBytes.of(0, -1, 1, endian)));
+ // LSB
+ assertEquals(MaskedBytes.of(0x30, 0xf0, 1, endian),
+ arithmetic.binaryOp(PcodeOp.SUBPIECE, 1,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 1, MaskedBytes.of(0, -1, 1, endian)));
+ // MSB
+ assertEquals(MaskedBytes.of(0x02, 0x0f, 1, endian),
+ arithmetic.binaryOp(PcodeOp.SUBPIECE, 1,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 1, MaskedBytes.of(1, -1, 1, endian)));
+ // OOB
+ assertEquals(MaskedBytes.of(0x00, 0xff, 1, endian),
+ arithmetic.binaryOp(PcodeOp.SUBPIECE, 1,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 1, MaskedBytes.of(2, -1, 1, endian)));
+ // ZEXT
+ assertEquals(MaskedBytes.of(0x000230, 0xff0ff0, 3, endian),
+ arithmetic.binaryOp(PcodeOp.SUBPIECE, 3,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 1, MaskedBytes.of(0, -1, 1, endian)));
+ // ZEXT(1)
+ assertEquals(MaskedBytes.of(0x000002, 0xffff0f, 3, endian),
+ arithmetic.binaryOp(PcodeOp.SUBPIECE, 3,
+ 2, MaskedBytes.of(0x0230, 0x0ff0, 2, endian),
+ 1, MaskedBytes.of(1, -1, 1, endian)));
+ }
+
+ @Test
+ public void testBinaryMisc() {
+ assertEquals(MaskedBytes.of(6, -1, 4, endian),
+ arithmetic.binaryOp(PcodeOp.INT_MULT, 4,
+ 4, MaskedBytes.of(2, -1, 4, endian),
+ 4, MaskedBytes.of(3, -1, 4, endian)));
+ assertEquals(MaskedBytes.ofUnknown(4),
+ arithmetic.binaryOp(PcodeOp.INT_MULT, 4,
+ 4, MaskedBytes.of(2, -1, 4, endian),
+ 4, MaskedBytes.of(3, 0xffff7fff, 4, endian)));
+ assertEquals(MaskedBytes.ofUnknown(4),
+ arithmetic.binaryOp(PcodeOp.INT_MULT, 4,
+ 4, MaskedBytes.of(2, 0xffff7fff, 4, endian),
+ 4, MaskedBytes.of(3, -1, 4, endian)));
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/BEFoldedArithmeticTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/BEFoldedArithmeticTest.java
new file mode 100644
index 0000000000..b2a4faf0ec
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/BEFoldedArithmeticTest.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.folding;
+
+import ghidra.program.model.lang.Endian;
+
+public class BEFoldedArithmeticTest extends AbstractFoldedArithmeticTest {
+ @Override
+ Endian getEndian() {
+ return Endian.BIG;
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/LEFoldedArithmeticTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/LEFoldedArithmeticTest.java
new file mode 100644
index 0000000000..c92fb7a003
--- /dev/null
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/emu/jit/folding/LEFoldedArithmeticTest.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.folding;
+
+import ghidra.program.model.lang.Endian;
+
+public class LEFoldedArithmeticTest extends AbstractFoldedArithmeticTest {
+ @Override
+ Endian getEndian() {
+ return Endian.LITTLE;
+ }
+}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/PcodeFrameTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/PcodeFrameTest.java
index 8e61bb1189..844c6cd3d5 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/PcodeFrameTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/exec/PcodeFrameTest.java
@@ -15,7 +15,7 @@
*/
package ghidra.pcode.exec;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import java.io.File;
@@ -84,7 +84,7 @@ public class PcodeFrameTest extends AbstractGTest {
private PcodeFrame frame(String sample) {
PcodeProgram program = compile(sample);
- return new PcodeFrame(language, program.code, program.useropNames);
+ return new PcodeFrame(language, program.code, program.userops);
}
@Test
@@ -169,14 +169,14 @@ public class PcodeFrameTest extends AbstractGTest {
PcodeFrame frame = frame(SAMPLE_ADD);
assertEquals("""
<p-code frame: index=0 {
- -> r0 = INT_ADD r0, r1
+ -> NO ADDRESS.0: r0 = INT_ADD r0, r1
}>""",
frame.toString());
frame.advance();
assertEquals("""
<p-code frame: index=1 {
- r0 = INT_ADD r0, r1
+ NO ADDRESS.0: r0 = INT_ADD r0, r1
*> fall-through
}>""",
frame.toString());
@@ -187,9 +187,9 @@ public class PcodeFrameTest extends AbstractGTest {
PcodeFrame frame = frame(SAMPLE_IF);
assertEquals("""
<p-code frame: index=0 {
- -> $U200:1 = INT_EQUAL r0, r1
- CBRANCH <0>, $U200:1
- r2 = INT_ADD r2, 1:8
+ -> NO ADDRESS.0: $U200:1 = INT_EQUAL r0, r1
+ NO ADDRESS.1: CBRANCH <0>, $U200:1
+ NO ADDRESS.2: r2 = INT_ADD r2, 1:8
<0>
}>""",
frame.toString());
@@ -199,9 +199,9 @@ public class PcodeFrameTest extends AbstractGTest {
frame.advance();
assertEquals("""
<p-code frame: index=3 {
- $U200:1 = INT_EQUAL r0, r1
- CBRANCH <0>, $U200:1
- r2 = INT_ADD r2, 1:8
+ NO ADDRESS.0: $U200:1 = INT_EQUAL r0, r1
+ NO ADDRESS.1: CBRANCH <0>, $U200:1
+ NO ADDRESS.2: r2 = INT_ADD r2, 1:8
<0>
*> fall-through
}>""",
@@ -214,9 +214,9 @@ public class PcodeFrameTest extends AbstractGTest {
assertEquals("""
<p-code frame: index=0 {
<0>
- -> r0 = INT_ADD r0, 1:8
- $U300:1 = INT_EQUAL r0, r1
- CBRANCH <0>, $U300:1
+ -> NO ADDRESS.0: r0 = INT_ADD r0, 1:8
+ NO ADDRESS.1: $U300:1 = INT_EQUAL r0, r1
+ NO ADDRESS.2: CBRANCH <0>, $U300:1
}>""",
frame.toString());
}
@@ -226,7 +226,7 @@ public class PcodeFrameTest extends AbstractGTest {
PcodeFrame frame = frame(SAMPLE_BRANCH);
assertEquals("""
<p-code frame: index=0 {
- -> BRANCH *[NO ADDRESS]0x1234
+ -> NO ADDRESS.0: BRANCH *[NO ADDRESS]0x1234
}>""",
frame.toString());
@@ -234,7 +234,7 @@ public class PcodeFrameTest extends AbstractGTest {
frame.finishAsBranch();
assertEquals("""
<p-code frame: index=-1 branched=0 {
- *> BRANCH *[NO ADDRESS]0x1234
+ *> NO ADDRESS.0: BRANCH *[NO ADDRESS]0x1234
}>""",
frame.toString());
}
@@ -244,7 +244,7 @@ public class PcodeFrameTest extends AbstractGTest {
PcodeFrame frame = frame(SAMPLE_LANG_USEROP);
assertEquals("""
<p-code frame: index=0 {
- -> CALLOTHER "pcodeop_one", r0
+ -> NO ADDRESS.0: CALLOTHER "pcodeop_one", r0
}>""",
frame.toString());
}
@@ -254,7 +254,7 @@ public class PcodeFrameTest extends AbstractGTest {
PcodeFrame frame = frame(SAMPLE_LIB_USEROP);
assertEquals("""
<p-code frame: index=0 {
- -> CALLOTHER "__lib_userop", r0
+ -> NO ADDRESS.0: CALLOTHER "__lib_userop", r0
}>""",
frame.toString());
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/AbstractOpBehaviorTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/AbstractOpBehaviorTest.java
index 4a50293a4e..4988ff1243 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/AbstractOpBehaviorTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/AbstractOpBehaviorTest.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,10 +18,24 @@ package ghidra.pcode.opbehavior;
import java.math.BigInteger;
import generic.test.AbstractGenericTest;
+import ghidra.pcode.floatformat.FloatFormat;
+import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.pcode.utils.Utils;
import ghidra.util.StringUtilities;
public abstract class AbstractOpBehaviorTest extends AbstractGenericTest {
+ static final FloatFormat FF4 = FloatFormatFactory.getFloatFormat(4);
+ static final FloatFormat FF8 = FloatFormatFactory.getFloatFormat(8);
+
+ static final BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
+ static final BigInteger NEGATIVE_TWO = Utils.convertToUnsignedValue(BigInteger.valueOf(-2), 16);
+ static final BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
+ static final BigInteger BIG_NEGATIVE =
+ Utils.convertToUnsignedValue(new BigInteger("80000000000000000000000000000000", 16), 16);
+
+ static final BigInteger NEG_ONE = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
+ static final BigInteger MIN_NUM = new BigInteger("80000000000000000000000000000000", 16);
+ static final BigInteger MAX_NUM = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
public AbstractOpBehaviorTest() {
super();
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolAndTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolAndTest.java
index 2793026724..63dbc6c406 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolAndTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolAndTest.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.
@@ -21,34 +21,25 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorBoolAndTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorBoolAndTest() {
- super();
- }
+ static final OpBehaviorBoolAnd OP = OpBehavior.BOOL_AND;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorBoolOr op = new OpBehaviorBoolOr();
-
- Assert.assertEquals(0, op.evaluateBinary(1, 1, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 0, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 1, 1));
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(1, 1, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 1, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 1, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 1, 1, 1));
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorBoolOr op = new OpBehaviorBoolOr();
-
+ public void testEvaluateBinaryBigInteger() {
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ZERO));
+ OP.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ZERO));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ONE));
+ OP.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ONE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegateTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegateTest.java
index 13adc6905b..83dd5be23f 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegateTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolNegateTest.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.
@@ -21,26 +21,17 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorBoolNegateTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorBoolNegate OP = OpBehavior.BOOL_NEGATE;
- public OpBehaviorBoolNegateTest() {
- super();
- }
-
-@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorBoolNegate op = new OpBehaviorBoolNegate();
-
- Assert.assertEquals(1, op.evaluateUnary(1, 1, 0));
- Assert.assertEquals(0, op.evaluateUnary(1, 1, 1));
+ @Test
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(1, OP.evaluateUnary(1, 1, 0));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 1, 1));
}
-@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorBoolNegate op = new OpBehaviorBoolNegate();
-
- Assert.assertEquals(BigInteger.ONE, op.evaluateUnary(1, 1, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateUnary(1, 1, BigInteger.ONE));
+ @Test
+ public void testEvaluateBinaryBigInteger() {
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateUnary(1, 1, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateUnary(1, 1, BigInteger.ONE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolOrTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolOrTest.java
index 1a9cd7cb46..14b32ac9f4 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolOrTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolOrTest.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.
@@ -21,30 +21,25 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorBoolOrTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorBoolOrTest() {
- super();
+ static final OpBehaviorBoolOr OP = OpBehavior.BOOL_OR;
+
+ @Test
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(1, 1, 0, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 1, 0, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 1, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 1, 1, 1));
}
-@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorBoolOr op = new OpBehaviorBoolOr();
-
- Assert.assertEquals(0, op.evaluateBinary(1, 1, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 0, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 1, 1));
- }
-
-@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorBoolOr op = new OpBehaviorBoolOr();
-
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ONE));
+ @Test
+ public void testEvaluateBinaryBigInteger() {
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ONE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolXorTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolXorTest.java
index 36d99365dd..d1f489de7b 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolXorTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorBoolXorTest.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.
@@ -21,30 +21,25 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorBoolXorTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorBoolXorTest() {
- super();
+ static final OpBehaviorBoolXor OP = OpBehavior.BOOL_XOR;
+
+ @Test
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(1, 1, 0, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 1, 0, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 1, 1, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 1, 1, 1));
}
-@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorBoolXor op = new OpBehaviorBoolXor();
-
- Assert.assertEquals(0, op.evaluateBinary(1, 1, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 0, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 1, 1, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 1, 1, 1));
- }
-
-@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorBoolXor op = new OpBehaviorBoolXor();
-
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ONE));
+ @Test
+ public void testEvaluateBinaryBigInteger() {
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 1, BigInteger.ZERO, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 1, BigInteger.ONE, BigInteger.ONE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbsTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbsTest.java
index b3f32c9623..a36d8914a5 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbsTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAbsTest.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,69 +20,52 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatAbsTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatAbsTest() {
- super();
- }
+ static final OpBehaviorFloatAbs OP = OpBehavior.FLOAT_ABS;
@Test
public void testEvaluateBinaryLong() {
+ long a = FF8.getEncoding(2.5);
+ long result = OP.evaluateUnary(8, 8, FF8.opAbs(a));
+ Assert.assertEquals(2.5, FF8.decodeHostFloat(result), 0);
- OpBehaviorFloatAbs op = new OpBehaviorFloatAbs();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(-2.5);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(2.5, FF8.decodeHostFloat(result), 0);
- long a = ff.getEncoding(2.5);
- long result = op.evaluateUnary(8, 8, ff.opAbs(a));
- Assert.assertEquals(2.5, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.5);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(2.5, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NaN);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(2.5d));
+ BigInteger result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(2.5d), FF8.decodeBigFloat(result));
- OpBehaviorFloatAbs op = new OpBehaviorFloatAbs();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(FF8.getBigFloat(-2.5d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(2.5d), FF8.decodeBigFloat(result));
- BigInteger a = ff.getEncoding(ff.getBigFloat(2.5d));
- BigInteger result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(2.5d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.5d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(2.5d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
- a = ff.getBigInfinityEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigNaNEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ a = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAddTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAddTest.java
index 6daa0bfbd5..6575af210b 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAddTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatAddTest.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,89 +20,72 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatAddTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatAddTest() {
- super();
- }
+ static final OpBehaviorFloatAdd OP = OpBehavior.FLOAT_ADD;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatAdd op = new OpBehaviorFloatAdd();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- long a = ff.getEncoding(1.234);
- long b = ff.getEncoding(1.123);
- long result = op.evaluateBinary(8, 8, a, b);// 1.234 + 1.123
- Assert.assertEquals(2.357, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(-1.123);
- result = op.evaluateBinary(8, 8, a, b);// -1.123 + 1.123
- Assert.assertEquals(0d, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// +INFINITY + 1.123
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY + 1.123
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY + -INFINITY
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY + +INFINITY
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NaN);
- b = ff.getEncoding(1.123);
- result = op.evaluateBinary(8, 8, a, b);// NaN + 1.123
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ long a = FF8.getEncoding(1.234);
+ long b = FF8.getEncoding(1.123);
+ long result = OP.evaluateBinary(8, 8, a, b);// 1.234 + 1.123
+ Assert.assertEquals(2.357, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(-1.123);
+ result = OP.evaluateBinary(8, 8, a, b);// -1.123 + 1.123
+ Assert.assertEquals(0d, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// +INFINITY + 1.123
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY + 1.123
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY + -INFINITY
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY + +INFINITY
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(Double.NaN);
+ b = FF8.getEncoding(1.123);
+ result = OP.evaluateBinary(8, 8, a, b);// NaN + 1.123
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatAdd op = new OpBehaviorFloatAdd();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigInteger a = ff.getEncoding(ff.getBigFloat(1.234d));
- BigInteger b = ff.getEncoding(ff.getBigFloat(1.123d));
- BigInteger result = op.evaluateBinary(8, 8, a, b);// 1.234 + 1.123
- Assert.assertEquals(ff.getBigFloat(2.357), ff.decodeBigFloat(result));
-
- a = ff.getEncoding(ff.getBigFloat(-1.123d));
- result = op.evaluateBinary(8, 8, a, b);// -1.123 + 1.123
- Assert.assertEquals(ff.getBigZero(false), ff.decodeBigFloat(result));
-
- a = ff.getEncoding(ff.getBigInfinity(false));
- result = op.evaluateBinary(8, 8, a, b);// +INFINITY + 1.123
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY + 1.123
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- b = ff.getBigInfinityEncoding(true);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY + -INFINITY
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- b = ff.getEncoding(ff.getBigInfinity(false));
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY + +INFINITY
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
-
- a = ff.getBigNaNEncoding(false);
- b = ff.getEncoding(ff.getBigFloat(1.123d));
- result = op.evaluateBinary(8, 8, a, b);// NaN + 1.123
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(1.234d));
+ BigInteger b = FF8.getEncoding(FF8.getBigFloat(1.123d));
+ BigInteger result = OP.evaluateBinary(8, 8, a, b);// 1.234 + 1.123
+ Assert.assertEquals(FF8.getBigFloat(2.357), FF8.decodeBigFloat(result));
+
+ a = FF8.getEncoding(FF8.getBigFloat(-1.123d));
+ result = OP.evaluateBinary(8, 8, a, b);// -1.123 + 1.123
+ Assert.assertEquals(FF8.getBigZero(false), FF8.decodeBigFloat(result));
+
+ a = FF8.getEncoding(FF8.getBigInfinity(false));
+ result = OP.evaluateBinary(8, 8, a, b);// +INFINITY + 1.123
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
+
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY + 1.123
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
+
+ b = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY + -INFINITY
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
+
+ b = FF8.getEncoding(FF8.getBigInfinity(false));
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY + +INFINITY
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
+
+ a = FF8.getBigNaNEncoding(false);
+ b = FF8.getEncoding(FF8.getBigFloat(1.123d));
+ result = OP.evaluateBinary(8, 8, a, b);// NaN + 1.123
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeilTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeilTest.java
index 29cd37cc61..120cb9ea69 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeilTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatCeilTest.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,69 +20,52 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatCeilTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatCeilTest() {
- super();
- }
+ static final OpBehaviorFloatCeil OP = OpBehavior.FLOAT_CEIL;
@Test
public void testEvaluateBinaryLong() {
+ long a = FF8.getEncoding(2.5);
+ long result = FF8.opCeil(a);
+ Assert.assertEquals(3.0, FF8.decodeHostFloat(result), 0);
- OpBehaviorFloatCeil op = new OpBehaviorFloatCeil();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(-2.5);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(-2.0, FF8.decodeHostFloat(result), 0);
- long a = ff.getEncoding(2.5);
- long result = ff.opCeil(a);
- Assert.assertEquals(3.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.5);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(-2.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NaN);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(2.5d));
+ BigInteger result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(3.0d), FF8.decodeBigFloat(result));
- OpBehaviorFloatCeil op = new OpBehaviorFloatCeil();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(FF8.getBigFloat(-2.5d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(-2.0d), FF8.decodeBigFloat(result));
- BigInteger a = ff.getEncoding(ff.getBigFloat(2.5d));
- BigInteger result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(3.0d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.5d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(-2.0d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
- a = ff.getBigInfinityEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- a = ff.getBigNaNEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ a = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatDivTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatDivTest.java
index 85649639e4..246fd71e66 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatDivTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatDivTest.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,63 +20,46 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatDivTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatDivTest() {
- super();
- }
+ static final OpBehaviorFloatDiv OP = OpBehavior.FLOAT_DIV;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatDiv op = new OpBehaviorFloatDiv();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- long a = ff.getEncoding(3.75);
- long b = ff.getEncoding(1.5);
- long result = ff.opDiv(a, b);
- Assert.assertEquals(2.5, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(0);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(-3.75);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(Double.NaN);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ long a = FF8.getEncoding(3.75);
+ long b = FF8.getEncoding(1.5);
+ long result = FF8.opDiv(a, b);
+ Assert.assertEquals(2.5, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(0);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(-3.75);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatDiv op = new OpBehaviorFloatDiv();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigInteger a = ff.getEncoding(ff.getBigFloat(3.75d));
- BigInteger b = ff.getEncoding(ff.getBigFloat(1.5d));
- BigInteger result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigFloat(2.5d), ff.decodeBigFloat(result));
-
- b = ff.getBigZeroEncoding(false);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getEncoding(ff.getBigFloat(-3.75d));
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- b = ff.getBigNaNEncoding(false);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(3.75d));
+ BigInteger b = FF8.getEncoding(FF8.getBigFloat(1.5d));
+ BigInteger result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigFloat(2.5d), FF8.decodeBigFloat(result));
+
+ b = FF8.getBigZeroEncoding(false);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
+
+ a = FF8.getEncoding(FF8.getBigFloat(-3.75d));
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
+
+ b = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqualTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqualTest.java
index 040d867b35..b815491980 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqualTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatEqualTest.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,62 +20,48 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.*;
+import ghidra.pcode.floatformat.BigFloat;
public class OpBehaviorFloatEqualTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatEqualTest() {
- super();
- }
+ static final OpBehaviorFloatEqual OP = OpBehavior.FLOAT_EQUAL;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatEqual op = new OpBehaviorFloatEqual();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
Assert.assertEquals(1,
- op.evaluateBinary(8, 8, ff.getEncoding(1.234), ff.getEncoding(1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(1.234), FF8.getEncoding(1.234)));
Assert.assertEquals(1,
- op.evaluateBinary(8, 8, ff.getEncoding(-1.234), ff.getEncoding(-1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(-1.234), FF8.getEncoding(-1.234)));
Assert.assertEquals(0,
- op.evaluateBinary(8, 8, ff.getEncoding(-1.234), ff.getEncoding(1.234)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.NEGATIVE_INFINITY)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(Double.NEGATIVE_INFINITY),
- ff.getEncoding(Double.NEGATIVE_INFINITY)));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.NaN)));
-
+ OP.evaluateBinary(8, 8, FF8.getEncoding(-1.234), FF8.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.NEGATIVE_INFINITY)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.NEGATIVE_INFINITY),
+ FF8.getEncoding(Double.NEGATIVE_INFINITY)));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.NaN)));
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatEqual op = new OpBehaviorFloatEqual();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigFloat a = ff.getBigFloat(1.234d);
- BigFloat b = ff.getBigFloat(-1.234d);
+ BigFloat a = FF8.getBigFloat(1.234d);
+ BigFloat b = FF8.getBigFloat(-1.234d);
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(b), ff.getEncoding(b)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(b), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getEncoding(b), ff.getEncoding(a)));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(8, 8,
- ff.getBigInfinityEncoding(false), ff.getBigInfinityEncoding(false)));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(8, 8,
- ff.getBigInfinityEncoding(false), ff.getBigInfinityEncoding(true)));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(true),
- ff.getBigInfinityEncoding(true)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(b), FF8.getEncoding(a)));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(8, 8,
+ FF8.getBigInfinityEncoding(false), FF8.getBigInfinityEncoding(false)));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(8, 8,
+ FF8.getBigInfinityEncoding(false), FF8.getBigInfinityEncoding(true)));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(true),
+ FF8.getBigInfinityEncoding(true)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(false), ff.getBigNaNEncoding(false)));
-
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(false),
+ FF8.getBigNaNEncoding(false)));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2FloatTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2FloatTest.java
index 1ecd39a17d..457e8266c2 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2FloatTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloat2FloatTest.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,71 +20,52 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatFloat2FloatTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatFloat2FloatTest() {
- super();
- }
+ static final OpBehaviorFloatFloat2Float OP = OpBehavior.FLOAT_FLOAT2FLOAT;
@Test
public void testEvaluateBinaryLong() {
+ long a = FF4.getEncoding(1.75);
+ long result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(1.75, FF8.decodeHostFloat(result), 0);
- OpBehaviorFloatFloat2Float op = new OpBehaviorFloatFloat2Float();
-
- FloatFormat ff8 = FloatFormatFactory.getFloatFormat(8);
- FloatFormat ff4 = FloatFormatFactory.getFloatFormat(4);
+ a = FF4.getEncoding(-1.75);
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(-1.75, FF8.decodeHostFloat(result), 0);
- long a = ff4.getEncoding(1.75);
- long result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(1.75, ff8.decodeHostFloat(result), 0);
+ a = FF4.getEncoding(Float.POSITIVE_INFINITY);
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff4.getEncoding(-1.75);
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(-1.75, ff8.decodeHostFloat(result), 0);
+ a = FF4.getEncoding(Float.NEGATIVE_INFINITY);
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff4.getEncoding(Float.POSITIVE_INFINITY);
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff8.decodeHostFloat(result), 0);
-
- a = ff4.getEncoding(Float.NEGATIVE_INFINITY);
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff8.decodeHostFloat(result), 0);
-
- a = ff4.getEncoding(Float.NaN);
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(Double.NaN, ff8.decodeHostFloat(result), 0);
+ a = FF4.getEncoding(Float.NaN);
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
+ BigInteger a = FF4.getEncoding(FF4.getBigFloat(1.75d));
+ BigInteger result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(FF8.getBigFloat(1.75d), FF8.decodeBigFloat(result));
- OpBehaviorFloatFloat2Float op = new OpBehaviorFloatFloat2Float();
-
- FloatFormat ff8 = FloatFormatFactory.getFloatFormat(8);
- FloatFormat ff4 = FloatFormatFactory.getFloatFormat(4);
+ a = FF4.getEncoding(FF4.getBigFloat(-1.75d));
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(FF8.getBigFloat(-1.75d), FF8.decodeBigFloat(result));
- BigInteger a = ff4.getEncoding(ff4.getBigFloat(1.75d));
- BigInteger result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(ff8.getBigFloat(1.75d), ff8.decodeBigFloat(result));
+ a = FF4.getEncoding(FF4.getBigInfinity(false));
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
- a = ff4.getEncoding(ff4.getBigFloat(-1.75d));
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(ff8.getBigFloat(-1.75d), ff8.decodeBigFloat(result));
+ a = FF4.getEncoding(FF4.getBigInfinity(true));
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
- a = ff4.getEncoding(ff4.getBigInfinity(false));
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(ff8.getBigInfinity(false), ff8.decodeBigFloat(result));
-
- a = ff4.getEncoding(ff4.getBigInfinity(true));
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(ff8.getBigInfinity(true), ff8.decodeBigFloat(result));
-
- a = ff4.getEncoding(ff4.getBigNaN(false));
- result = op.evaluateUnary(8, 4, a);
- Assert.assertEquals(ff8.getBigNaN(false), ff8.decodeBigFloat(result));
+ a = FF4.getEncoding(FF4.getBigNaN(false));
+ result = OP.evaluateUnary(8, 4, a);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloorTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloorTest.java
index 1d13db78d0..58b5d75348 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloorTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatFloorTest.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,77 +20,60 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatFloorTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatFloorTest() {
- super();
- }
+ static final OpBehaviorFloatFloor OP = OpBehavior.FLOAT_FLOOR;
@Test
public void testEvaluateBinaryLong() {
+ long a = FF8.getEncoding(2.5);
+ long result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(2.0, FF8.decodeHostFloat(result), 0);
- OpBehaviorFloatFloor op = new OpBehaviorFloatFloor();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(-2.0);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(-2.0, FF8.decodeHostFloat(result), 0);
- long a = ff.getEncoding(2.5);
- long result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(2.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(-2.5);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(-3.0, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.0);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(-2.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.5);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(-3.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NaN);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(2.5d));
+ BigInteger result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(2.0d), FF8.decodeBigFloat(result));
- OpBehaviorFloatFloor op = new OpBehaviorFloatFloor();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(FF8.getBigFloat(-2.0d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(-2.0d), FF8.decodeBigFloat(result));
- BigInteger a = ff.getEncoding(ff.getBigFloat(2.5d));
- BigInteger result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(2.0d), ff.decodeBigFloat(result));
+ a = FF8.getEncoding(FF8.getBigFloat(-2.5d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(-3.0d), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.0d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(-2.0d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.5d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(-3.0d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
- a = ff.getBigInfinityEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- a = ff.getBigNaNEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ a = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2FloatTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2FloatTest.java
index 3d506b61f6..eae2c47a0b 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2FloatTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatInt2FloatTest.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,73 +15,56 @@
*/
package ghidra.pcode.opbehavior;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
import ghidra.pcode.utils.Utils;
public class OpBehaviorFloatInt2FloatTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatInt2FloatTest() {
- super();
- }
+ static final OpBehaviorFloatInt2Float OP = OpBehavior.FLOAT_INT2FLOAT;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatInt2Float op = new OpBehaviorFloatInt2Float();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(4);
-
- long result = op.evaluateUnary(4, 4, 2);
+ long result = OP.evaluateUnary(4, 4, 2);
Assert.assertEquals(0, result & 0xffffffff00000000L);// verify that only 4-bytes are used
- Assert.assertEquals(2.0d, ff.decodeHostFloat(result), 0);
+ Assert.assertEquals(2.0d, FF4.decodeHostFloat(result), 0);
- result = op.evaluateUnary(4, 4, -2);
+ result = OP.evaluateUnary(4, 4, -2);
Assert.assertEquals(0, result & 0xffffffff00000000L);// verify that only 4-bytes are used
- Assert.assertEquals(-2.0d, ff.decodeHostFloat(result), 0);
+ Assert.assertEquals(-2.0d, FF4.decodeHostFloat(result), 0);
- result = op.evaluateUnary(4, 4, 0);
+ result = OP.evaluateUnary(4, 4, 0);
Assert.assertEquals(0, result & 0xffffffff00000000L);// verify that only 4-bytes are used
- Assert.assertEquals(0d, ff.decodeHostFloat(result), 0);
+ Assert.assertEquals(0d, FF4.decodeHostFloat(result), 0);
- result = op.evaluateUnary(4, 4, 0x0ffffffffL);
+ result = OP.evaluateUnary(4, 4, 0x0ffffffffL);
Assert.assertEquals(0, result & 0xffffffff00000000L);// verify that only 4-bytes are used
- Assert.assertEquals(-1.0d, ff.decodeHostFloat(result), 0);
+ Assert.assertEquals(-1.0d, FF4.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatInt2Float op = new OpBehaviorFloatInt2Float();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(4);
-
BigInteger limit = BigInteger.ONE.shiftLeft(32);
- BigInteger result = op.evaluateUnary(4, 4, BigInteger.valueOf(2));
+ BigInteger result = OP.evaluateUnary(4, 4, BigInteger.valueOf(2));
assertTrue(result.compareTo(limit) < 0);// verify that only 4-bytes are used
- Assert.assertEquals(ff.getBigFloat(2.0d), ff.decodeBigFloat(result));
+ Assert.assertEquals(FF4.getBigFloat(2.0d), FF4.decodeBigFloat(result));
- result = op.evaluateUnary(4, 4, BigInteger.valueOf(-2));
+ result = OP.evaluateUnary(4, 4, BigInteger.valueOf(-2));
assertTrue(result.compareTo(limit) < 0);// verify that only 4-bytes are used
- Assert.assertEquals(ff.getBigFloat(-2.0d), ff.decodeBigFloat(result));
+ Assert.assertEquals(FF4.getBigFloat(-2.0d), FF4.decodeBigFloat(result));
- result = op.evaluateUnary(4, 4, BigInteger.ZERO);
+ result = OP.evaluateUnary(4, 4, BigInteger.ZERO);
assertTrue(result.compareTo(limit) < 0);// verify that only 4-bytes are used
- Assert.assertEquals(ff.getBigZero(false), ff.decodeBigFloat(result));
+ Assert.assertEquals(FF4.getBigZero(false), FF4.decodeBigFloat(result));
BigInteger NEG_ONE = Utils.bytesToBigInteger(
new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }, 4, false, false);
- result = op.evaluateUnary(4, 4, NEG_ONE);
- Assert.assertEquals(ff.getBigFloat(-1.0d), ff.decodeBigFloat(result));
-
+ result = OP.evaluateUnary(4, 4, NEG_ONE);
+ Assert.assertEquals(FF4.getBigFloat(-1.0d), FF4.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqualTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqualTest.java
index 2c6de5cf57..97a6979cf6 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqualTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessEqualTest.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,89 +20,75 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.*;
+import ghidra.pcode.floatformat.BigFloat;
public class OpBehaviorFloatLessEqualTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatLessEqualTest() {
- super();
- }
+ static final OpBehaviorFloatLessEqual OP = OpBehavior.FLOAT_LESSEQUAL;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatLessEqual op = new OpBehaviorFloatLessEqual();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
Assert.assertEquals(1,
- op.evaluateBinary(8, 8, ff.getEncoding(1.234), ff.getEncoding(1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(1.234), FF8.getEncoding(1.234)));
Assert.assertEquals(1,
- op.evaluateBinary(8, 8, ff.getEncoding(-1.234), ff.getEncoding(-1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(-1.234), FF8.getEncoding(-1.234)));
Assert.assertEquals(0,
- op.evaluateBinary(8, 8, ff.getEncoding(1.234), ff.getEncoding(-1.234)));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(0), ff.getEncoding(-1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(1.234), FF8.getEncoding(-1.234)));
+ Assert.assertEquals(0,
+ OP.evaluateBinary(8, 8, FF8.getEncoding(0), FF8.getEncoding(-1.234)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(0), ff.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(0), FF8.getEncoding(1.234)));
Assert.assertEquals(1,
- op.evaluateBinary(8, 8, ff.getEncoding(-1.234), ff.getEncoding(1.234)));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(1.234)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(Double.NEGATIVE_INFINITY),
- ff.getEncoding(1.234)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(1.234),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(1.234),
- ff.getEncoding(Double.NEGATIVE_INFINITY)));
-
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(Double.NEGATIVE_INFINITY),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
-
+ OP.evaluateBinary(8, 8, FF8.getEncoding(-1.234), FF8.getEncoding(1.234)));
+
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.NEGATIVE_INFINITY),
+ FF8.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(1.234),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, FF8.getEncoding(1.234),
+ FF8.getEncoding(Double.NEGATIVE_INFINITY)));
+
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.NEGATIVE_INFINITY),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatLessEqual op = new OpBehaviorFloatLessEqual();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigFloat a = ff.getBigFloat(1.234d);
- BigFloat b = ff.getBigFloat(-1.234d);
+ BigFloat a = FF8.getBigFloat(1.234d);
+ BigFloat b = FF8.getBigFloat(-1.234d);
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(b), ff.getEncoding(b)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(b), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getEncoding(b)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getBigZeroEncoding(false), ff.getEncoding(b)));
+ OP.evaluateBinary(8, 8, FF8.getBigZeroEncoding(false), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getBigZeroEncoding(false), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getBigZeroEncoding(false), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(b), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(b), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(false), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(false), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(true), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(true), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getBigInfinityEncoding(false)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getBigInfinityEncoding(false)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getBigInfinityEncoding(true)));
-
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(8, 8,
- ff.getBigInfinityEncoding(false), ff.getBigInfinityEncoding(false)));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(true),
- ff.getBigInfinityEncoding(false)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getBigInfinityEncoding(true)));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(8, 8,
+ FF8.getBigInfinityEncoding(false), FF8.getBigInfinityEncoding(false)));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(true),
+ FF8.getBigInfinityEncoding(false)));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessTest.java
index a8651ba59e..b57d7681a7 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatLessTest.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,86 +20,73 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.*;
+import ghidra.pcode.floatformat.BigFloat;
public class OpBehaviorFloatLessTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatLessTest() {
- super();
- }
+ static final OpBehaviorFloatLess OP = OpBehavior.FLOAT_LESS;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatLess op = new OpBehaviorFloatLess();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
Assert.assertEquals(0,
- op.evaluateBinary(8, 8, ff.getEncoding(1.234), ff.getEncoding(1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(1.234), FF8.getEncoding(1.234)));
+ Assert.assertEquals(0,
+ OP.evaluateBinary(8, 8, FF8.getEncoding(-1.234), FF8.getEncoding(-1.234)));
Assert.assertEquals(0,
- op.evaluateBinary(8, 8, ff.getEncoding(-1.234), ff.getEncoding(-1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(1.234), FF8.getEncoding(-1.234)));
Assert.assertEquals(0,
- op.evaluateBinary(8, 8, ff.getEncoding(1.234), ff.getEncoding(-1.234)));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(0), ff.getEncoding(-1.234)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(0), FF8.getEncoding(-1.234)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(0), ff.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(0), FF8.getEncoding(1.234)));
Assert.assertEquals(1,
- op.evaluateBinary(8, 8, ff.getEncoding(-1.234), ff.getEncoding(1.234)));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(1.234)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(Double.NEGATIVE_INFINITY),
- ff.getEncoding(1.234)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(1.234),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(1.234),
- ff.getEncoding(Double.NEGATIVE_INFINITY)));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, ff.getEncoding(Double.NEGATIVE_INFINITY),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(-1.234), FF8.getEncoding(1.234)));
+
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.NEGATIVE_INFINITY),
+ FF8.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(1.234),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, FF8.getEncoding(1.234),
+ FF8.getEncoding(Double.NEGATIVE_INFINITY)));
+
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, FF8.getEncoding(Double.NEGATIVE_INFINITY),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatLess op = new OpBehaviorFloatLess();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigFloat a = ff.getBigFloat(1.234d);
- BigFloat b = ff.getBigFloat(-1.234d);
+ BigFloat a = FF8.getBigFloat(1.234d);
+ BigFloat b = FF8.getBigFloat(-1.234d);
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getEncoding(b), ff.getEncoding(b)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(b), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getEncoding(b)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getBigZeroEncoding(false), ff.getEncoding(b)));
+ OP.evaluateBinary(8, 8, FF8.getBigZeroEncoding(false), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getBigZeroEncoding(false), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getBigZeroEncoding(false), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(b), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(b), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(false), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(false), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(true), ff.getEncoding(a)));
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(true), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getBigInfinityEncoding(false)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getBigInfinityEncoding(false)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, ff.getEncoding(a), ff.getBigInfinityEncoding(true)));
-
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(8, 8,
- ff.getBigInfinityEncoding(false), ff.getBigInfinityEncoding(false)));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(8, 8, ff.getBigInfinityEncoding(true),
- ff.getBigInfinityEncoding(false)));
+ OP.evaluateBinary(8, 8, FF8.getEncoding(a), FF8.getBigInfinityEncoding(true)));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(8, 8,
+ FF8.getBigInfinityEncoding(false), FF8.getBigInfinityEncoding(false)));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(8, 8, FF8.getBigInfinityEncoding(true),
+ FF8.getBigInfinityEncoding(false)));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatMultTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatMultTest.java
index 3d7a4f3022..a0174dcf72 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatMultTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatMultTest.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,63 +20,46 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatMultTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatMultTest() {
- super();
- }
+ static final OpBehaviorFloatMult OP = OpBehavior.FLOAT_MULT;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatMult op = new OpBehaviorFloatMult();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- long a = ff.getEncoding(2.5);
- long b = ff.getEncoding(1.5);
- long result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(3.75, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(Double.NaN);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ long a = FF8.getEncoding(2.5);
+ long b = FF8.getEncoding(1.5);
+ long result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(3.75, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatMult op = new OpBehaviorFloatMult();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigInteger a = ff.getEncoding(ff.getBigFloat(2.5d));
- BigInteger b = ff.getEncoding(ff.getBigFloat(1.5d));
- BigInteger result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigFloat(3.75d), ff.decodeBigFloat(result));
-
- b = ff.getBigInfinityEncoding(false);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- b = ff.getBigNaNEncoding(false);
- result = op.evaluateBinary(8, 8, a, b);
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(2.5d));
+ BigInteger b = FF8.getEncoding(FF8.getBigFloat(1.5d));
+ BigInteger result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigFloat(3.75d), FF8.decodeBigFloat(result));
+
+ b = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
+
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
+
+ b = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateBinary(8, 8, a, b);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNanTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNanTest.java
index 1d38903d63..75bc7f7cf3 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNanTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNanTest.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,39 +20,21 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatNanTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatNanTest() {
- super();
- }
+ static final OpBehaviorFloatNan OP = OpBehavior.FLOAT_NAN;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatNan op = new OpBehaviorFloatNan();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- Assert.assertEquals(1, op.evaluateUnary(1, 8, ff.getEncoding(Double.NaN)));
- Assert.assertEquals(0, op.evaluateUnary(1, 8, ff.getEncoding(0)));
- Assert.assertEquals(0, op.evaluateUnary(1, 8, ff.getEncoding(1.234)));
+ Assert.assertEquals(1, OP.evaluateUnary(1, 8, FF8.getEncoding(Double.NaN)));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 8, FF8.getEncoding(0)));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 8, FF8.getEncoding(1.234)));
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatNan op = new OpBehaviorFloatNan();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- Assert.assertEquals(BigInteger.ONE, op.evaluateUnary(1, 8, ff.getBigNaNEncoding(false)));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateUnary(1, 8, ff.getBigZeroEncoding(false)));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateUnary(1, 8, FF8.getBigNaNEncoding(false)));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateUnary(1, 8, FF8.getBigZeroEncoding(false)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateUnary(1, 8, ff.getEncoding(ff.getBigFloat(1.234d))));
-
+ OP.evaluateUnary(1, 8, FF8.getEncoding(FF8.getBigFloat(1.234d))));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNegTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNegTest.java
index c2143f7dde..61b46059c2 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNegTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNegTest.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,69 +20,52 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatNegTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatNegTest() {
- super();
- }
+ static final OpBehaviorFloatNeg OP = OpBehavior.FLOAT_NEG;
@Test
public void testEvaluateBinaryLong() {
+ long a = FF8.getEncoding(2.5);
+ long result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(-2.5, FF8.decodeHostFloat(result), 0);
- OpBehaviorFloatNeg op = new OpBehaviorFloatNeg();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(-2.5);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(2.5, FF8.decodeHostFloat(result), 0);
- long a = ff.getEncoding(2.5);
- long result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(-2.5, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.5);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(2.5, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NaN);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(2.5d));
+ BigInteger result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(-2.5d), FF8.decodeBigFloat(result));
- OpBehaviorFloatNeg op = new OpBehaviorFloatNeg();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
+ a = FF8.getEncoding(FF8.getBigFloat(-2.5d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(2.5d), FF8.decodeBigFloat(result));
- BigInteger a = ff.getEncoding(ff.getBigFloat(2.5d));
- BigInteger result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(-2.5d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.5d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(2.5d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
- a = ff.getBigInfinityEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigNaNEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ a = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqualTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqualTest.java
index acd9626214..a8dce68099 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqualTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatNotEqualTest.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,62 +20,48 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.*;
+import ghidra.pcode.floatformat.BigFloat;
public class OpBehaviorFloatNotEqualTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatNotEqualTest() {
- super();
- }
+ static final OpBehaviorFloatNotEqual OP = OpBehavior.FLOAT_NOTEQUAL;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatNotEqual op = new OpBehaviorFloatNotEqual();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
Assert.assertEquals(0,
- op.evaluateBinary(1, 8, ff.getEncoding(1.234), ff.getEncoding(1.234)));
+ OP.evaluateBinary(1, 8, FF8.getEncoding(1.234), FF8.getEncoding(1.234)));
Assert.assertEquals(0,
- op.evaluateBinary(1, 8, ff.getEncoding(-1.234), ff.getEncoding(-1.234)));
+ OP.evaluateBinary(1, 8, FF8.getEncoding(-1.234), FF8.getEncoding(-1.234)));
Assert.assertEquals(1,
- op.evaluateBinary(1, 8, ff.getEncoding(-1.234), ff.getEncoding(1.234)));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.POSITIVE_INFINITY)));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.NEGATIVE_INFINITY)));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, ff.getEncoding(Double.NEGATIVE_INFINITY),
- ff.getEncoding(Double.NEGATIVE_INFINITY)));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, ff.getEncoding(Double.POSITIVE_INFINITY),
- ff.getEncoding(Double.NaN)));
+ OP.evaluateBinary(1, 8, FF8.getEncoding(-1.234), FF8.getEncoding(1.234)));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.POSITIVE_INFINITY)));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.NEGATIVE_INFINITY)));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, FF8.getEncoding(Double.NEGATIVE_INFINITY),
+ FF8.getEncoding(Double.NEGATIVE_INFINITY)));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, FF8.getEncoding(Double.POSITIVE_INFINITY),
+ FF8.getEncoding(Double.NaN)));
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatNotEqual op = new OpBehaviorFloatNotEqual();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigFloat a = ff.getBigFloat(1.234d);
- BigFloat b = ff.getBigFloat(-1.234d);
+ BigFloat a = FF8.getBigFloat(1.234d);
+ BigFloat b = FF8.getBigFloat(-1.234d);
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(1, 8, ff.getEncoding(a), ff.getEncoding(a)));
+ OP.evaluateBinary(1, 8, FF8.getEncoding(a), FF8.getEncoding(a)));
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(1, 8, ff.getEncoding(b), ff.getEncoding(b)));
+ OP.evaluateBinary(1, 8, FF8.getEncoding(b), FF8.getEncoding(b)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(1, 8, ff.getEncoding(b), ff.getEncoding(a)));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 8,
- ff.getBigInfinityEncoding(false), ff.getBigInfinityEncoding(false)));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 8,
- ff.getBigInfinityEncoding(false), ff.getBigInfinityEncoding(true)));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 8,
- ff.getBigInfinityEncoding(true), ff.getBigInfinityEncoding(true)));
+ OP.evaluateBinary(1, 8, FF8.getEncoding(b), FF8.getEncoding(a)));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 8,
+ FF8.getBigInfinityEncoding(false), FF8.getBigInfinityEncoding(false)));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 8,
+ FF8.getBigInfinityEncoding(false), FF8.getBigInfinityEncoding(true)));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 8,
+ FF8.getBigInfinityEncoding(true), FF8.getBigInfinityEncoding(true)));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(1, 8, ff.getBigInfinityEncoding(false), ff.getBigNaNEncoding(false)));
-
+ OP.evaluateBinary(1, 8, FF8.getBigInfinityEncoding(false),
+ FF8.getBigNaNEncoding(false)));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatRoundTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatRoundTest.java
index 90ef4cdfbd..c2287689d3 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatRoundTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatRoundTest.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,102 +20,84 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatRoundTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatRoundTest() {
- super();
- }
+ static final OpBehaviorFloatRound OP = OpBehavior.FLOAT_ROUND;
@Test
public void testEvaluateBinaryLong() {
+ long a = FF8.getEncoding(2.5);
+ long result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(3.0, FF8.decodeHostFloat(result), 0);
- OpBehaviorFloatRound op = new OpBehaviorFloatRound();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- long a = ff.getEncoding(2.5);
- long result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(3.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(2.25);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(2.0, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(2.25);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(2.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(2.75);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(3.0, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(2.75);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(3.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(-2.5);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(-2.0, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.5);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(-2.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(-2.25);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(-2.0, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.25);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(-2.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(-2.75);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(-3.0, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(-2.75);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(-3.0, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NaN);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ a = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(2.5d));
+ BigInteger result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(3.0d), FF8.decodeBigFloat(result));
- OpBehaviorFloatRound op = new OpBehaviorFloatRound();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigInteger a = ff.getEncoding(ff.getBigFloat(2.5d));
- BigInteger result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(3.0d), ff.decodeBigFloat(result));
+ a = FF8.getEncoding(FF8.getBigFloat(2.25d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(2.0d), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(2.25d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(2.0d), ff.decodeBigFloat(result));
+ a = FF8.getEncoding(FF8.getBigFloat(2.75d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(3.0d), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(2.75d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(3.0d), ff.decodeBigFloat(result));
+ a = FF8.getEncoding(FF8.getBigFloat(-2.5d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(-2.0d), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.5d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(-2.0d), ff.decodeBigFloat(result));
+ a = FF8.getEncoding(FF8.getBigFloat(-2.25d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(-2.0d), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.25d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(-2.0d), ff.decodeBigFloat(result));
+ a = FF8.getEncoding(FF8.getBigFloat(-2.75d));
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigFloat(-3.0d), FF8.decodeBigFloat(result));
- a = ff.getEncoding(ff.getBigFloat(-2.75d));
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigFloat(-3.0d), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
- a = ff.getBigInfinityEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- a = ff.getBigNaNEncoding(false);
- result = op.evaluateUnary(8, 8, a);
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
+ a = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrtTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrtTest.java
index d30c91ef47..6af808e71a 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrtTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSqrtTest.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.
@@ -23,37 +23,22 @@ import org.junit.Test;
import ghidra.pcode.floatformat.*;
public class OpBehaviorFloatSqrtTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatSqrtTest() {
- super();
- }
+ static final OpBehaviorFloatSqrt OP = OpBehavior.FLOAT_SQRT;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatSqrt op = new OpBehaviorFloatSqrt();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- long longbits = ff.getEncoding(2.0);
- longbits = op.evaluateUnary(8, 8, longbits);
- double d = ff.decodeHostFloat(longbits);
+ long longbits = FF8.getEncoding(2.0);
+ longbits = OP.evaluateUnary(8, 8, longbits);
+ double d = FF8.decodeHostFloat(longbits);
Assert.assertEquals("1.414213562373095", Double.toString(d).substring(0, 17));
-
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatSqrt op = new OpBehaviorFloatSqrt();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigFloat big = ff.getBigFloat(2.0);
- BigInteger encoding = ff.getEncoding(big);
- encoding = op.evaluateUnary(8, 8, encoding);
- BigFloat result = ff.decodeBigFloat(encoding);
- Assert.assertEquals("1.414213562373095", ff.round(result).toString());
+ BigFloat big = FF8.getBigFloat(2.0);
+ BigInteger encoding = FF8.getEncoding(big);
+ encoding = OP.evaluateUnary(8, 8, encoding);
+ BigFloat result = FF8.decodeBigFloat(encoding);
+ Assert.assertEquals("1.414213562373095", FF8.round(result).toString());
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSubTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSubTest.java
index b9dee62599..e836a17088 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSubTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatSubTest.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,90 +20,72 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatSubTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatSubTest() {
- super();
- }
+ static final OpBehaviorFloatSub OP = OpBehavior.FLOAT_SUB;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatSub op = new OpBehaviorFloatSub();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- long a = ff.getEncoding(1.5);
- long b = ff.getEncoding(1.25);
- long result = op.evaluateBinary(8, 8, a, b);// 1.5 - 1.25
- Assert.assertEquals(0.25, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(-1.25);
- result = op.evaluateBinary(8, 8, a, b);// -1.25 - 1.25
- Assert.assertEquals(-2.5, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// +INFINITY - 1.25
- Assert.assertEquals(Double.POSITIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY - 1.25
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY - -INFINITY
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
-
- b = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY - +INFINITY
- Assert.assertEquals(Double.NEGATIVE_INFINITY, ff.decodeHostFloat(result), 0);
-
- a = ff.getEncoding(Double.NaN);
- b = ff.getEncoding(1.25);
- result = op.evaluateBinary(8, 8, a, b);// NaN - 1.25
- Assert.assertEquals(Double.NaN, ff.decodeHostFloat(result), 0);
+ long a = FF8.getEncoding(1.5);
+ long b = FF8.getEncoding(1.25);
+ long result = OP.evaluateBinary(8, 8, a, b);// 1.5 - 1.25
+ Assert.assertEquals(0.25, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(-1.25);
+ result = OP.evaluateBinary(8, 8, a, b);// -1.25 - 1.25
+ Assert.assertEquals(-2.5, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// +INFINITY - 1.25
+ Assert.assertEquals(Double.POSITIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY - 1.25
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY - -INFINITY
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
+
+ b = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY - +INFINITY
+ Assert.assertEquals(Double.NEGATIVE_INFINITY, FF8.decodeHostFloat(result), 0);
+
+ a = FF8.getEncoding(Double.NaN);
+ b = FF8.getEncoding(1.25);
+ result = OP.evaluateBinary(8, 8, a, b);// NaN - 1.25
+ Assert.assertEquals(Double.NaN, FF8.decodeHostFloat(result), 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatSub op = new OpBehaviorFloatSub();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigInteger a = ff.getEncoding(ff.getBigFloat(1.5d));
- BigInteger b = ff.getEncoding(ff.getBigFloat(1.25d));
- BigInteger result = op.evaluateBinary(8, 8, a, b);// 1.5 - 1.25
- Assert.assertEquals(ff.getBigFloat(0.25d), ff.decodeBigFloat(result));
-
- a = ff.getEncoding(ff.getBigFloat(-1.25d));
- result = op.evaluateBinary(8, 8, a, b);// -1.25 - 1.25
- Assert.assertEquals(ff.getBigFloat(-2.5d), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(false);
- result = op.evaluateBinary(8, 8, a, b);// +INFINITY - 1.25
- Assert.assertEquals(ff.getBigInfinity(false), ff.decodeBigFloat(result));
-
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY - 1.25
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- b = ff.getBigInfinityEncoding(true);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY - -INFINITY
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
-
- b = ff.getBigInfinityEncoding(false);
- result = op.evaluateBinary(8, 8, a, b);// -INFINITY - +INFINITY
- Assert.assertEquals(ff.getBigInfinity(true), ff.decodeBigFloat(result));
-
- a = ff.getBigNaNEncoding(false);
- b = ff.getEncoding(ff.getBigFloat(1.25d));
- result = op.evaluateBinary(8, 8, a, b);// NaN - 1.25
- Assert.assertEquals(ff.getBigNaN(false), ff.decodeBigFloat(result));
-
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(1.5d));
+ BigInteger b = FF8.getEncoding(FF8.getBigFloat(1.25d));
+ BigInteger result = OP.evaluateBinary(8, 8, a, b);// 1.5 - 1.25
+ Assert.assertEquals(FF8.getBigFloat(0.25d), FF8.decodeBigFloat(result));
+
+ a = FF8.getEncoding(FF8.getBigFloat(-1.25d));
+ result = OP.evaluateBinary(8, 8, a, b);// -1.25 - 1.25
+ Assert.assertEquals(FF8.getBigFloat(-2.5d), FF8.decodeBigFloat(result));
+
+ a = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateBinary(8, 8, a, b);// +INFINITY - 1.25
+ Assert.assertEquals(FF8.getBigInfinity(false), FF8.decodeBigFloat(result));
+
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY - 1.25
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
+
+ b = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY - -INFINITY
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
+
+ b = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateBinary(8, 8, a, b);// -INFINITY - +INFINITY
+ Assert.assertEquals(FF8.getBigInfinity(true), FF8.decodeBigFloat(result));
+
+ a = FF8.getBigNaNEncoding(false);
+ b = FF8.getEncoding(FF8.getBigFloat(1.25d));
+ result = OP.evaluateBinary(8, 8, a, b);// NaN - 1.25
+ Assert.assertEquals(FF8.getBigNaN(false), FF8.decodeBigFloat(result));
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatTruncTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatTruncTest.java
index e8037af847..405c453dc4 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatTruncTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorFloatTruncTest.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,71 +20,54 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.floatformat.FloatFormat;
-import ghidra.pcode.floatformat.FloatFormatFactory;
-
public class OpBehaviorFloatTruncTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorFloatTruncTest() {
- super();
- }
+ static final OpBehaviorFloatTrunc OP = OpBehavior.FLOAT_TRUNC;
@Test
public void testEvaluateBinaryLong() {
-
- OpBehaviorFloatTrunc op = new OpBehaviorFloatTrunc();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- long a = ff.getEncoding(2.5);
- long result = op.evaluateUnary(8, 8, a);
+ long a = FF8.getEncoding(2.5);
+ long result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(2, result);
- a = ff.getEncoding(-2.5);
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getEncoding(-2.5);
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(-2, result);
- a = ff.getEncoding(Double.POSITIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getEncoding(Double.POSITIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(Long.MAX_VALUE, result);
- a = ff.getEncoding(Double.NEGATIVE_INFINITY);
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getEncoding(Double.NEGATIVE_INFINITY);
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(Long.MIN_VALUE, result);
// TODO: What should the correct result be?
- a = ff.getEncoding(Double.NaN);
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getEncoding(Double.NaN);
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(0, result);
}
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorFloatTrunc op = new OpBehaviorFloatTrunc();
-
- FloatFormat ff = FloatFormatFactory.getFloatFormat(8);
-
- BigInteger a = ff.getEncoding(ff.getBigFloat(2.5d));
- BigInteger result = op.evaluateUnary(8, 8, a);
+ BigInteger a = FF8.getEncoding(FF8.getBigFloat(2.5d));
+ BigInteger result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(BigInteger.valueOf(2), result);
- a = ff.getEncoding(ff.getBigFloat(-2.5d));
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getEncoding(FF8.getBigFloat(-2.5d));
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(BigInteger.valueOf(-2), result);
- a = ff.getBigInfinityEncoding(false);
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getBigInfinityEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(BigInteger.valueOf(Long.MAX_VALUE), result);
- a = ff.getBigInfinityEncoding(true);
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getBigInfinityEncoding(true);
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(BigInteger.valueOf(Long.MIN_VALUE), result);
// TODO: What should the correct result be?
- a = ff.getBigNaNEncoding(false);
- result = op.evaluateUnary(8, 8, a);
+ a = FF8.getBigNaNEncoding(false);
+ result = OP.evaluateUnary(8, 8, a);
Assert.assertEquals(BigInteger.ZERO, result);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorInt2CompTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorInt2CompTest.java
index 9a27347d53..c285fcb1f6 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorInt2CompTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorInt2CompTest.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.
@@ -21,44 +21,29 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorInt2CompTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorInt2CompTest() {
- super();
- }
+ static final OpBehaviorInt2Comp OP = OpBehavior.INT_2COMP;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorInt2Comp op = new OpBehaviorInt2Comp();
-
- Assert.assertEquals(0, op.evaluateUnary(4, 4, 0));
- Assert.assertEquals(1, op.evaluateUnary(4, 4, 0xffffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateUnary(4, 4, 1));
- Assert.assertEquals(0x80000001L, op.evaluateUnary(4, 4, 0x7fffffffL));
- Assert.assertEquals(0x80000000L, op.evaluateUnary(4, 4, 0x80000000L));// overflow
-
- Assert.assertEquals(0, op.evaluateUnary(8, 8, 0));
- Assert.assertEquals(1, op.evaluateUnary(8, 8, -1));
- Assert.assertEquals(-1, op.evaluateUnary(8, 8, 1));
- Assert.assertEquals(Long.MIN_VALUE + 1, op.evaluateUnary(8, 8, Long.MAX_VALUE));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateUnary(8, 8, Long.MIN_VALUE));// overflow
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateUnary(4, 4, 0));
+ Assert.assertEquals(1, OP.evaluateUnary(4, 4, 0xffffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateUnary(4, 4, 1));
+ Assert.assertEquals(0x80000001L, OP.evaluateUnary(4, 4, 0x7fffffffL));
+ Assert.assertEquals(0x80000000L, OP.evaluateUnary(4, 4, 0x80000000L));// overflow
+
+ Assert.assertEquals(0, OP.evaluateUnary(8, 8, 0));
+ Assert.assertEquals(1, OP.evaluateUnary(8, 8, -1));
+ Assert.assertEquals(-1, OP.evaluateUnary(8, 8, 1));
+ Assert.assertEquals(Long.MIN_VALUE + 1, OP.evaluateUnary(8, 8, Long.MAX_VALUE));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateUnary(8, 8, Long.MIN_VALUE));// overflow
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorInt2Comp op = new OpBehaviorInt2Comp();
-
- BigInteger negOne = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger minNum = new BigInteger("80000000000000000000000000000000", 16);
- BigInteger maxNum = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
-
- assertEquals(BigInteger.ZERO, op.evaluateUnary(8, 8, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ONE, op.evaluateUnary(8, 8, negOne), 16);
- assertEquals(negOne, op.evaluateUnary(8, 8, BigInteger.ONE), 16);
- assertEquals(minNum.add(BigInteger.ONE), op.evaluateUnary(8, 8, maxNum), 16);
- assertEquals(minNum, op.evaluateUnary(8, 8, minNum), 16);// overflow
-
+ public void testEvaluateBinaryBigInteger() {
+ assertEquals(BigInteger.ZERO, OP.evaluateUnary(8, 8, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateUnary(8, 8, NEG_ONE), 16);
+ assertEquals(NEG_ONE, OP.evaluateUnary(8, 8, BigInteger.ONE), 16);
+ assertEquals(MIN_NUM.add(BigInteger.ONE), OP.evaluateUnary(8, 8, MAX_NUM), 16);
+ assertEquals(MIN_NUM, OP.evaluateUnary(8, 8, MIN_NUM), 16);// overflow
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAddTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAddTest.java
index 5a8c1f0856..a789f83a3c 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAddTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAddTest.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,88 +20,70 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntAddTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntAddTest() {
- super();
- }
+ static final OpBehaviorIntAdd OP = OpBehavior.INT_ADD;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntAdd op = new OpBehaviorIntAdd();
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0, 1));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0xffffffffL, 0));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0xffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 0xffffffffL));
+ Assert.assertEquals(0xfffffffeL, OP.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x80000000L, 0));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0, 0x80000000L));
+ Assert.assertEquals(0x80000001L, OP.evaluateBinary(4, 4, 0x80000000L, 1));
+ Assert.assertEquals(0x80000001L, OP.evaluateBinary(4, 4, 1, 0x80000000L));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));// overflow
+ Assert.assertEquals(0xfffffffeL, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));// overflow
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0, 1));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0xffffffffL, 0));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0xffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 0xffffffffL));
- Assert.assertEquals(0xfffffffeL, op.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x80000000L, 0));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0, 0x80000000L));
- Assert.assertEquals(0x80000001L, op.evaluateBinary(4, 4, 0x80000000L, 1));
- Assert.assertEquals(0x80000001L, op.evaluateBinary(4, 4, 1, 0x80000000L));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));// overflow
- Assert.assertEquals(0xfffffffeL, op.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));// overflow
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 0, 1));
- Assert.assertEquals(0xffffffffffffffffL, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 0));
- Assert.assertEquals(0xffffffffffffffffL, op.evaluateBinary(8, 8, 0, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 0, 1));
+ Assert.assertEquals(0xffffffffffffffffL, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 0));
+ Assert.assertEquals(0xffffffffffffffffL, OP.evaluateBinary(8, 8, 0, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, 0xffffffffffffffffL));
Assert.assertEquals(0xfffffffffffffffeL,
- op.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(Long.MIN_VALUE + 1, op.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(Long.MIN_VALUE + 1, op.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
+ OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(Long.MIN_VALUE + 1, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(Long.MIN_VALUE + 1, OP.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
Assert.assertEquals(0xffffffffffffffffL,
- op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
Assert.assertEquals(0xffffffffffffffffL,
- op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));// overflow
+ OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));// overflow
Assert.assertEquals(0xfffffffffffffffeL,
- op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));// overflow
+ OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));// overflow
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntAdd op = new OpBehaviorIntAdd();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger NEGATIVE_TWO = Utils.convertToUnsignedValue(BigInteger.valueOf(-2), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = Utils.convertToUnsignedValue(
- new BigInteger("80000000000000000000000000000000", 16), 16);
-
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
+ public void testEvaluateBinaryBigInteger() {
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
- assertEquals(NEGATIVE_TWO, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
+ assertEquals(NEGATIVE_TWO, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
assertEquals(BIG_NEGATIVE.add(BigInteger.ONE),
- op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
assertEquals(BIG_NEGATIVE.add(BigInteger.ONE),
- op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
- assertEquals(NEGATIVE_TWO, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
-
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
+ assertEquals(NEGATIVE_TWO, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAndTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAndTest.java
index e40cf5e093..4fc4bcb41e 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAndTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntAndTest.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,86 +20,73 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntAndTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorIntAnd OP = OpBehavior.INT_AND;
public OpBehaviorIntAndTest() {
super();
}
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntAnd op = new OpBehaviorIntAnd();
-
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0xffffffffL, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0xffffffffL, 1));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 1, 0xffffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));// overflow
- Assert.assertEquals(0x7fffffffL, op.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));// overflow
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0xffffffffL, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0xffffffffL, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 1, 0xffffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));// overflow
+ Assert.assertEquals(0x7fffffffL, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));// overflow
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 1));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 1, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 1, 0xffffffffffffffffL));
Assert.assertEquals(0xffffffffffffffffL,
- op.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
Assert.assertEquals(Long.MIN_VALUE,
- op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));// overflow
+ OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));// overflow
Assert.assertEquals(Long.MAX_VALUE,
- op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));// overflow
+ OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));// overflow
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntAnd op = new OpBehaviorIntAnd();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = Utils.convertToUnsignedValue(
- new BigInteger("80000000000000000000000000000000", 16), 16);
-
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
+ public void testEvaluateBinaryBigInteger() {
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO),
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO),
16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE),
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE),
16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
- assertEquals(BIG_POSITIVE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
-
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
+ assertEquals(BIG_POSITIVE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntCarryTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntCarryTest.java
index 069d55e4b0..3be6a09f96 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntCarryTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntCarryTest.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.
@@ -21,6 +21,7 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorIntCarryTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorIntCarry OP = OpBehavior.INT_CARRY;
public OpBehaviorIntCarryTest() {
super();
@@ -28,47 +29,41 @@ public class OpBehaviorIntCarryTest extends AbstractOpBehaviorTest {
@Test
public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 1, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0xffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x80000001L));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0x80000001L, 0x7fffffffL));
- OpBehaviorIntCarry op = new OpBehaviorIntCarry();
-
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 1, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0xffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0x7fffffffL, 0x80000001L));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0x80000001L, 0x7fffffffL));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE + 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, Long.MIN_VALUE + 1, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0x7fffffffffffffffL, 1L));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1L, 0x7fffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 1L));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 1L, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE + 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, Long.MIN_VALUE + 1, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0x7fffffffffffffffL, 1L));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1L, 0x7fffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 1L));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 1L, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
}
+ static final BigInteger NEGATIVE_ONE = new BigInteger("FFFFFFFFFFFFFFFF", 16);
+ static final BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFF", 16);
+ static final BigInteger BIG_NEGATIVE = new BigInteger("8000000000000000", 16);
+
@Test
public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntCarry op = new OpBehaviorIntCarry();
-
- BigInteger NEGATIVE_ONE = new BigInteger("FFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = new BigInteger("8000000000000000", 16);
-
Assert.assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(8, 8, BigInteger.ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(8, 8, NEGATIVE_ONE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(8, 8, BIG_POSITIVE, BIG_NEGATIVE));
+ OP.evaluateBinary(8, 8, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(8, 8, BigInteger.ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(8, 8, NEGATIVE_ONE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(8, 8, BIG_POSITIVE, BIG_NEGATIVE));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, BIG_POSITIVE, BIG_NEGATIVE.add(BigInteger.ONE)));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(8, 8, BIG_NEGATIVE, BIG_POSITIVE));
+ OP.evaluateBinary(8, 8, BIG_POSITIVE, BIG_NEGATIVE.add(BigInteger.ONE)));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(8, 8, BIG_NEGATIVE, BIG_POSITIVE));
Assert.assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, BIG_NEGATIVE.add(BigInteger.ONE), BIG_POSITIVE));
+ OP.evaluateBinary(8, 8, BIG_NEGATIVE.add(BigInteger.ONE), BIG_POSITIVE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntDivTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntDivTest.java
index a117e77692..71dac36314 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntDivTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntDivTest.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,83 +20,66 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntDivTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntDivTest() {
- super();
- }
+ static final OpBehaviorIntDiv OP = OpBehavior.INT_DIV;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntDiv op = new OpBehaviorIntDiv();
-
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 0));// divide by zero
-
- Assert.assertEquals(13, op.evaluateBinary(4, 4, 65, 5));
-
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0xffffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0xffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0x80000000L));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x80000000L, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, 0));// divide by zero
-
- Assert.assertEquals(0x3E0708EEL, op.evaluateBinary(8, 8, 0x2512345678L, 0x99));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 0xffffffffffffffffL));
- Assert.assertEquals(0xffffffffffffffffL, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 0));// divide by zero
+
+ Assert.assertEquals(13, OP.evaluateBinary(4, 4, 65, 5));
+
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0xffffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0xffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0x80000000L));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x80000000L, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));
+
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, 0));// divide by zero
+
+ Assert.assertEquals(0x3E0708EEL, OP.evaluateBinary(8, 8, 0x2512345678L, 0x99));
+
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 0xffffffffffffffffL));
+ Assert.assertEquals(0xffffffffffffffffL, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntDiv op = new OpBehaviorIntDiv();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = Utils.convertToUnsignedValue(
- new BigInteger("80000000000000000000000000000000", 16), 16);
-
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO),
+ public void testEvaluateBinaryBigInteger() {
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO),
16);
Assert.assertEquals(BigInteger.valueOf(0x3E0708EEL),
- op.evaluateBinary(8, 8, BigInteger.valueOf(0x2512345678L), BigInteger.valueOf(0x99)));
+ OP.evaluateBinary(8, 8, BigInteger.valueOf(0x2512345678L), BigInteger.valueOf(0x99)));
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE),
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE),
16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
-
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLeftTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLeftTest.java
index d31275c545..1d2d17ca8b 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLeftTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLeftTest.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.
@@ -21,66 +21,55 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorIntLeftTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntLeftTest() {
- super();
- }
+ static final OpBehaviorIntLeft OP = OpBehavior.INT_LEFT;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntLeft op = new OpBehaviorIntLeft();
-
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 8));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, -1));
- Assert.assertEquals(0x100, op.evaluateBinary(4, 4, 1, 8));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 1, 31));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 32));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 33));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 8));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, -1));
- Assert.assertEquals(0x100L, op.evaluateBinary(8, 8, 1, 8));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, 1, 63));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, 64));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, 65));
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, -1));
+ Assert.assertEquals(0x100, OP.evaluateBinary(4, 4, 1, 8));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 1, 31));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 32));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 33));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, -1));
+ Assert.assertEquals(0x100L, OP.evaluateBinary(8, 8, 1, 8));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, 1, 63));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, 64));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, 65));
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntLeft op = new OpBehaviorIntLeft();
-
+ public void testEvaluateBinaryBigInteger() {
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(8)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(8)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(-1)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(-1)), 4);
assertEquals(getUnsignedBigInt(0x100L),
- op.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(8)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(8)), 4);
assertEquals(getUnsignedBigInt(0x80000000L),
- op.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(31)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(31)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(32)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(32)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(33)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ONE, getUnsignedBigInt(33)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), BigInteger.ONE), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), BigInteger.ONE), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(8)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(8)), 8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(-1)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(-1)), 8);
assertEquals(getUnsignedBigInt(0x100L),
- op.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(8)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(8)), 8);
assertEquals(getUnsignedBigInt(Long.MIN_VALUE),
- op.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(63)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(63)), 8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(64)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(64)), 8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(65)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ONE, getUnsignedBigInt(65)), 8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, getUnsignedBigInt(Long.MIN_VALUE), BigInteger.ONE), 4);
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(Long.MIN_VALUE), BigInteger.ONE), 4);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqualTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqualTest.java
index 5897040ddf..93350a977b 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqualTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessEqualTest.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,85 +20,77 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntLessEqualTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorIntLessEqual OP = OpBehavior.INT_LESSEQUAL;
- public OpBehaviorIntLessEqualTest() {
- super();
- }
-
-@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntLessEqual op = new OpBehaviorIntLessEqual();
+ @Test
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 1, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 1, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 1, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 1, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
-
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
}
-@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntLessEqual op = new OpBehaviorIntLessEqual();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE =
- Utils.convertToUnsignedValue(new BigInteger("80000000000000000000000000000000", 16), 16);
-
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
-
+ @Test
+ public void testEvaluateBinaryBigInteger() {
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessTest.java
index 01f6d77d58..7bda07bcb6 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntLessTest.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,84 +20,76 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntLessTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorIntLess OP = OpBehavior.INT_LESS;
- public OpBehaviorIntLessTest() {
- super();
- }
-
-@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntLess op = new OpBehaviorIntLess();
+ @Test
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 1, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 1, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 1, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 1, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
-
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
}
-@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntLess op = new OpBehaviorIntLess();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE =
- Utils.convertToUnsignedValue(new BigInteger("80000000000000000000000000000000", 16), 16);
-
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
-
+ @Test
+ public void testEvaluateBinaryBigInteger() {
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntMultTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntMultTest.java
index 4318e8a311..9eff9a84ac 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntMultTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntMultTest.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,90 +20,74 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntMultTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntMultTest() {
- super();
- }
+ static final OpBehaviorIntMult OP = OpBehavior.INT_MULT;
@Test
- public void testEvaluateBinaryLong() {
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 1, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0xffffffffL, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0xffffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0xffffffffL, 1));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 1, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0x80000000L));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x80000000L, 1));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 1, 0x80000000L));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL), 4);
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));
+ Assert.assertEquals(0x71c71c72, OP.evaluateBinary(4, 4, 0x55555555L, 0xaaaaaaaaL));
- OpBehaviorIntMult op = new OpBehaviorIntMult();
-
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 1, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0xffffffffL, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0xffffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0xffffffffL, 1));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 1, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 0));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0x80000000L));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x80000000L, 1));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 1, 0x80000000L));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL), 4);
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));
- Assert.assertEquals(0x71c71c72, op.evaluateBinary(4, 4, 0x55555555L, 0xaaaaaaaaL));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 1, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, -1, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, -1));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, -1, 1));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, 1, -1));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, -1, -1));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 1, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, -1, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, -1));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, -1, 1));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, 1, -1));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, -1, -1));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
Assert.assertEquals(Long.MIN_VALUE,
- op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
Assert.assertEquals(Long.MIN_VALUE,
- op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));
+ OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));
Assert.assertEquals(0x1c71c71c71c71c72L,
- op.evaluateBinary(8, 8, 0x5555555555555555L, 0xaaaaaaaaaaaaaaaaL), 8);
+ OP.evaluateBinary(8, 8, 0x5555555555555555L, 0xaaaaaaaaaaaaaaaaL), 8);
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntMult op = new OpBehaviorIntMult();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = Utils.convertToUnsignedValue(
- new BigInteger("80000000000000000000000000000000", 16), 16);
-
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
+ public void testEvaluateBinaryBigInteger() {
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO),
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO),
16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE),
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE),
16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);
assertEquals(new BigInteger("71c71c71c71c71c71c71c71c71c71c72", 16),
- op.evaluateBinary(8, 8, new BigInteger("55555555555555555555555555555555", 16),
+ OP.evaluateBinary(8, 8, new BigInteger("55555555555555555555555555555555", 16),
new BigInteger("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 16)),
16);
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntNegateTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntNegateTest.java
index f2c0fb88f7..d21f22c725 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntNegateTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntNegateTest.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.
@@ -21,52 +21,38 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorIntNegateTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntNegateTest() {
- super();
- }
+ static final OpBehaviorIntNegate OP = OpBehavior.INT_NEGATE;
@Test
- public void testevaluateUnaryLong() {
-
- OpBehaviorIntNegate op = new OpBehaviorIntNegate();
-
- Assert.assertEquals(0xffffffffL, op.evaluateUnary(4, 4, 0));
- Assert.assertEquals(0, op.evaluateUnary(4, 4, 0xffffffffL));
- Assert.assertEquals(0xfffffffdL, op.evaluateUnary(4, 4, 2));
- Assert.assertEquals(2, op.evaluateUnary(4, 4, 0xfffffffdL));
- Assert.assertEquals(0x80000000L, op.evaluateUnary(4, 4, 0x7fffffffL));
- Assert.assertEquals(0x7fffffffL, op.evaluateUnary(4, 4, 0x80000000L));
- Assert.assertEquals(1, op.evaluateUnary(4, 4, 0xfffffffeL));
- Assert.assertEquals(0xfffffffeL, op.evaluateUnary(4, 4, 1));
-
- Assert.assertEquals(0, op.evaluateUnary(8, 8, -1));
- Assert.assertEquals(-1, op.evaluateUnary(8, 8, 0));
- Assert.assertEquals(-3, op.evaluateUnary(8, 8, 2));
- Assert.assertEquals(2, op.evaluateUnary(8, 8, -3));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateUnary(8, 8, Long.MAX_VALUE));
- Assert.assertEquals(Long.MAX_VALUE, op.evaluateUnary(8, 8, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateUnary(8, 8, -2));
- Assert.assertEquals(-2, op.evaluateUnary(8, 8, 1));
-
+ public void testevaluateUnaryLong() {
+ Assert.assertEquals(0xffffffffL, OP.evaluateUnary(4, 4, 0));
+ Assert.assertEquals(0, OP.evaluateUnary(4, 4, 0xffffffffL));
+ Assert.assertEquals(0xfffffffdL, OP.evaluateUnary(4, 4, 2));
+ Assert.assertEquals(2, OP.evaluateUnary(4, 4, 0xfffffffdL));
+ Assert.assertEquals(0x80000000L, OP.evaluateUnary(4, 4, 0x7fffffffL));
+ Assert.assertEquals(0x7fffffffL, OP.evaluateUnary(4, 4, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateUnary(4, 4, 0xfffffffeL));
+ Assert.assertEquals(0xfffffffeL, OP.evaluateUnary(4, 4, 1));
+
+ Assert.assertEquals(0, OP.evaluateUnary(8, 8, -1));
+ Assert.assertEquals(-1, OP.evaluateUnary(8, 8, 0));
+ Assert.assertEquals(-3, OP.evaluateUnary(8, 8, 2));
+ Assert.assertEquals(2, OP.evaluateUnary(8, 8, -3));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateUnary(8, 8, Long.MAX_VALUE));
+ Assert.assertEquals(Long.MAX_VALUE, OP.evaluateUnary(8, 8, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateUnary(8, 8, -2));
+ Assert.assertEquals(-2, OP.evaluateUnary(8, 8, 1));
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntNegate op = new OpBehaviorIntNegate();
-
- BigInteger negOne = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger minNum = new BigInteger("80000000000000000000000000000000", 16);
- BigInteger maxNum = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
-
- assertEquals(negOne, op.evaluateUnary(8, 8, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ZERO, op.evaluateUnary(8, 8, negOne), 16);
- assertEquals(getUnsignedBigInt(-3, 16), op.evaluateUnary(8, 8, getUnsignedBigInt(2)), 16);
- assertEquals(getUnsignedBigInt(2), op.evaluateUnary(8, 8, getUnsignedBigInt(-3, 16)), 16);
- assertEquals(minNum, op.evaluateUnary(8, 8, maxNum), 16);
- assertEquals(maxNum, op.evaluateUnary(8, 8, minNum), 16);
- assertEquals(BigInteger.ONE, op.evaluateUnary(8, 8, getUnsignedBigInt(-2, 16)), 16);
- assertEquals(getUnsignedBigInt(-2, 16), op.evaluateUnary(8, 8, BigInteger.ONE), 16);
+ public void testEvaluateBinaryBigInteger() {
+ assertEquals(NEG_ONE, OP.evaluateUnary(8, 8, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateUnary(8, 8, NEG_ONE), 16);
+ assertEquals(getUnsignedBigInt(-3, 16), OP.evaluateUnary(8, 8, getUnsignedBigInt(2)), 16);
+ assertEquals(getUnsignedBigInt(2), OP.evaluateUnary(8, 8, getUnsignedBigInt(-3, 16)), 16);
+ assertEquals(MIN_NUM, OP.evaluateUnary(8, 8, MAX_NUM), 16);
+ assertEquals(MAX_NUM, OP.evaluateUnary(8, 8, MIN_NUM), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateUnary(8, 8, getUnsignedBigInt(-2, 16)), 16);
+ assertEquals(getUnsignedBigInt(-2, 16), OP.evaluateUnary(8, 8, BigInteger.ONE), 16);
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntOrTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntOrTest.java
index 8a94bb3c73..2fbd3d3a39 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntOrTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntOrTest.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,85 +20,68 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntOrTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntOrTest() {
- super();
- }
+ static final OpBehaviorIntOr OP = OpBehavior.INT_OR;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntOr op = new OpBehaviorIntOr();
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0, 1));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0xffffffffL, 0));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0, 0xffffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0xffffffffL, 1));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 1, 0xffffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x80000000L, 0));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0, 0x80000000L));
+ Assert.assertEquals(0x80000001L, OP.evaluateBinary(4, 4, 0x80000000L, 1));
+ Assert.assertEquals(0x80000001L, OP.evaluateBinary(4, 4, 1, 0x80000000L));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(0xffffffffL, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(0x80000000L, OP.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));// overflow
+ Assert.assertEquals(0x7fffffffL, OP.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));// overflow
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0, 1));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0xffffffffL, 0));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0, 0xffffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0xffffffffL, 1));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 1, 0xffffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x80000000L, 0));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0, 0x80000000L));
- Assert.assertEquals(0x80000001L, op.evaluateBinary(4, 4, 0x80000000L, 1));
- Assert.assertEquals(0x80000001L, op.evaluateBinary(4, 4, 1, 0x80000000L));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(0xffffffffL, op.evaluateBinary(4, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(0x80000000L, op.evaluateBinary(4, 4, 0x80000000L, 0x80000000L));// overflow
- Assert.assertEquals(0x7fffffffL, op.evaluateBinary(4, 4, 0x7fffffffL, 0x7fffffffL));// overflow
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 0));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 0, 1));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, -1, 0));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, 0, -1));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, -1, 1));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, 1, -1));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, -1, -1));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(Long.MIN_VALUE, op.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(Long.MIN_VALUE + 1, op.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(Long.MIN_VALUE + 1, op.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 0, 1));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, -1, 0));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, 0, -1));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, -1, 1));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, 1, -1));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, -1, -1));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(Long.MIN_VALUE, OP.evaluateBinary(8, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(Long.MIN_VALUE + 1, OP.evaluateBinary(8, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(Long.MIN_VALUE + 1, OP.evaluateBinary(8, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MIN_VALUE));
Assert.assertEquals(Long.MIN_VALUE,
- op.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));// overflow
+ OP.evaluateBinary(8, 8, Long.MIN_VALUE, Long.MIN_VALUE));// overflow
Assert.assertEquals(Long.MAX_VALUE,
- op.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));// overflow
+ OP.evaluateBinary(8, 8, Long.MAX_VALUE, Long.MAX_VALUE));// overflow
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntOr op = new OpBehaviorIntOr();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = Utils.convertToUnsignedValue(
- new BigInteger("80000000000000000000000000000000", 16), 16);
-
- assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
+ public void testEvaluateBinaryBigInteger() {
+ assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO),
16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE), 16);
assertEquals(BIG_NEGATIVE.add(BigInteger.ONE),
- op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE), 16);
assertEquals(BIG_NEGATIVE.add(BigInteger.ONE),
- op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
- assertEquals(NEGATIVE_ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
- assertEquals(BIG_NEGATIVE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
- assertEquals(BIG_POSITIVE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
-
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE), 16);
+ assertEquals(NEGATIVE_ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE), 16);
+ assertEquals(BIG_NEGATIVE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE), 16);// overflow
+ assertEquals(BIG_POSITIVE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE), 16);// overflow
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRemTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRemTest.java
index d447e3bf80..9a2f39592f 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRemTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRemTest.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.
@@ -23,38 +23,30 @@ import org.junit.Test;
import ghidra.pcode.error.LowlevelError;
public class OpBehaviorIntRemTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntRemTest() {
- super();
- }
+ static final OpBehaviorIntRem OP = OpBehavior.INT_REM;
@Test
public void testEvaluateBinaryLong() {
- OpBehaviorIntRem op = new OpBehaviorIntRem();
- Assert.assertEquals(0L, op.evaluateBinary(4, 4, 16, 2));
- Assert.assertEquals(1L, op.evaluateBinary(4, 4, 17, 2));
- Assert.assertEquals(1L, op.evaluateBinary(8, 8, 0xffffffffffffffffL, 2L));
+ Assert.assertEquals(0L, OP.evaluateBinary(4, 4, 16, 2));
+ Assert.assertEquals(1L, OP.evaluateBinary(4, 4, 17, 2));
+ Assert.assertEquals(1L, OP.evaluateBinary(8, 8, 0xffffffffffffffffL, 2L));
}
@Test(expected = LowlevelError.class)
public void testDivideByZeroLong() {
- OpBehaviorIntRem op = new OpBehaviorIntRem();
- op.evaluateBinary(4, 4, 1, 0);
+ OP.evaluateBinary(4, 4, 1, 0);
}
@Test
public void testEvaluateBinaryBigInteger() {
- OpBehaviorIntRem op = new OpBehaviorIntRem();
Assert.assertEquals(BigInteger.TWO,
- op.evaluateBinary(16, 16, new BigInteger("fffffffffffffffffffffffffffffff2", 16),
+ OP.evaluateBinary(16, 16, new BigInteger("fffffffffffffffffffffffffffffff2", 16),
BigInteger.TWO.add(BigInteger.TWO)));
}
@Test(expected = LowlevelError.class)
public void testDivideByZeroBigInteger() {
- OpBehaviorIntRem op = new OpBehaviorIntRem();
- op.evaluateBinary(16, 16, BigInteger.ONE, BigInteger.ZERO);
+ OP.evaluateBinary(16, 16, BigInteger.ONE, BigInteger.ZERO);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRightTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRightTest.java
index 5ef1d10d3c..ec6c0cf3f0 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRightTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntRightTest.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.
@@ -21,67 +21,55 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorIntRightTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntRightTest() {
- super();
- }
+ static final OpBehaviorIntRight OP = OpBehavior.INT_RIGHT;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntRight op = new OpBehaviorIntRight();
-
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 8));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, -1));
- Assert.assertEquals(0x800000L, op.evaluateBinary(4, 4, 0x80000000L, 8));
- Assert.assertEquals(1, op.evaluateBinary(4, 4, 0x80000000L, 31));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 32));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x80000000L, 33));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 8));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, -1));
- Assert.assertEquals(0x80000000000000L, op.evaluateBinary(8, 8, 0x8000000000000000L, 8));
- Assert.assertEquals(1, op.evaluateBinary(8, 8, 0x8000000000000000L, 63));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0x8000000000000000L, 64));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0x8000000000000000L, 65));
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, -1));
+ Assert.assertEquals(0x800000L, OP.evaluateBinary(4, 4, 0x80000000L, 8));
+ Assert.assertEquals(1, OP.evaluateBinary(4, 4, 0x80000000L, 31));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 32));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x80000000L, 33));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, -1));
+ Assert.assertEquals(0x80000000000000L, OP.evaluateBinary(8, 8, 0x8000000000000000L, 8));
+ Assert.assertEquals(1, OP.evaluateBinary(8, 8, 0x8000000000000000L, 63));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0x8000000000000000L, 64));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0x8000000000000000L, 65));
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntRight op = new OpBehaviorIntRight();
-
+ public void testEvaluateBinaryBigInteger() {
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(8)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(8)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(-1)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(-1)), 4);
assertEquals(getUnsignedBigInt(0x800000L),
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(8)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(8)), 4);
assertEquals(BigInteger.ONE,
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(31)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(31)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(32)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(32)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(33)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(33)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(8)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(8)), 8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(-1)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(-1)), 8);
assertEquals(getUnsignedBigInt(0x80000000000000L),
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(8)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(8)),
8);
assertEquals(BigInteger.ONE,
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(63)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(63)),
8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(64)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(64)),
8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(65)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(65)),
8);
-
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessEqualTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessEqualTest.java
index 3b19edf9e4..0f840e482e 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessEqualTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessEqualTest.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,85 +20,76 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntSLessEqualTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorIntSless OP = OpBehavior.INT_SLESS;
- public OpBehaviorIntSLessEqualTest() {
- super();
- }
-
-@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntSless op = new OpBehaviorIntSless();
-
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0xffffffffL, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0xffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
-
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
+ @Test
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0xffffffffL, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0xffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
}
-@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntSless op = new OpBehaviorIntSless();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE =
- Utils.convertToUnsignedValue(new BigInteger("80000000000000000000000000000000", 16), 16);
-
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
-
+ @Test
+ public void testEvaluateBinaryBigInteger() {
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessTest.java
index 781b00d772..67766d2ed6 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSLessTest.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,85 +20,76 @@ import java.math.BigInteger;
import org.junit.Assert;
import org.junit.Test;
-import ghidra.pcode.utils.Utils;
-
public class OpBehaviorIntSLessTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorIntSlessEqual OP = OpBehavior.INT_SLESSEQUAL;
- public OpBehaviorIntSLessTest() {
- super();
- }
-
-@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntSlessEqual op = new OpBehaviorIntSlessEqual();
-
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0xffffffffL, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0xffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 1, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
- Assert.assertEquals(0, op.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
-
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, 0));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0, 1));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
- Assert.assertEquals(0, op.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
- Assert.assertEquals(1, op.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
+ @Test
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0xffffffffL, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0xffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0xffffffffL, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 1, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x7fffffffL, 0x7fffffffL));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 4, 0xffffffffL, 0x80000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 4, 0x80000000L, 0xffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, 0));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0, 1));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0xffffffffffffffffL));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 0));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, 1));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 1, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MIN_VALUE, Long.MIN_VALUE));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, Long.MAX_VALUE, Long.MAX_VALUE));
+ Assert.assertEquals(0, OP.evaluateBinary(1, 8, 0xffffffffffffffffL, 0x8000000000000000L));
+ Assert.assertEquals(1, OP.evaluateBinary(1, 8, 0x8000000000000000L, 0xffffffffffffffffL));
}
-@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntSlessEqual op = new OpBehaviorIntSlessEqual();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE =
- Utils.convertToUnsignedValue(new BigInteger("80000000000000000000000000000000", 16), 16);
-
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
- Assert.assertEquals(BigInteger.ZERO, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
- Assert.assertEquals(BigInteger.ONE, op.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
-
+ @Test
+ public void testEvaluateBinaryBigInteger() {
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, NEGATIVE_ONE, NEGATIVE_ONE));
+ Assert.assertEquals(BigInteger.ONE,
+ OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ZERO));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ZERO, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BigInteger.ONE));
+ Assert.assertEquals(BigInteger.ZERO,
+ OP.evaluateBinary(1, 16, BigInteger.ONE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_POSITIVE));
+ Assert.assertEquals(BigInteger.ZERO, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_NEGATIVE, BIG_NEGATIVE));
+ Assert.assertEquals(BigInteger.ONE, OP.evaluateBinary(1, 16, BIG_POSITIVE, BIG_POSITIVE));
}
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSRightTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSRightTest.java
index 4ccbecdc13..dd74364d5d 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSRightTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorIntSRightTest.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.
@@ -21,95 +21,84 @@ import org.junit.Assert;
import org.junit.Test;
public class OpBehaviorIntSRightTest extends AbstractOpBehaviorTest {
-
- public OpBehaviorIntSRightTest() {
- super();
- }
+ static final OpBehaviorIntSright OP = OpBehavior.INT_SRIGHT;
@Test
- public void testEvaluateBinaryLong() {
-
- OpBehaviorIntSright op = new OpBehaviorIntSright();
+ public void testEvaluateBinaryLong() {
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0, -1));
+ Assert.assertEquals(0xFF800000L, OP.evaluateBinary(4, 4, 0x80000000L, 8));
+ Assert.assertEquals(0xFFFFFFFFL, OP.evaluateBinary(4, 4, 0x80000000L, 31));
+ Assert.assertEquals(0xFFFFFFFFL, OP.evaluateBinary(4, 4, 0x80000000L, 32));
+ Assert.assertEquals(0xFFFFFFFFL, OP.evaluateBinary(4, 4, 0x80000000L, 33));
+ Assert.assertEquals(0x400000L, OP.evaluateBinary(4, 4, 0x40000000L, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x40000000L, 31));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x40000000L, 32));
+ Assert.assertEquals(0, OP.evaluateBinary(4, 4, 0x40000000L, 33));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, 8));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0, -1));
- Assert.assertEquals(0xFF800000L, op.evaluateBinary(4, 4, 0x80000000L, 8));
- Assert.assertEquals(0xFFFFFFFFL, op.evaluateBinary(4, 4, 0x80000000L, 31));
- Assert.assertEquals(0xFFFFFFFFL, op.evaluateBinary(4, 4, 0x80000000L, 32));
- Assert.assertEquals(0xFFFFFFFFL, op.evaluateBinary(4, 4, 0x80000000L, 33));
- Assert.assertEquals(0x400000L, op.evaluateBinary(4, 4, 0x40000000L, 8));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x40000000L, 31));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x40000000L, 32));
- Assert.assertEquals(0, op.evaluateBinary(4, 4, 0x40000000L, 33));
-
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, 8));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0, -1));
- Assert.assertEquals(0xFF80000000000000L, op.evaluateBinary(8, 8, 0x8000000000000000L, 8));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, 0x8000000000000000L, 63));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, 0x8000000000000000L, 64));
- Assert.assertEquals(-1, op.evaluateBinary(8, 8, 0x8000000000000000L, 65));
- Assert.assertEquals(0x40000000000000L, op.evaluateBinary(8, 8, 0x4000000000000000L, 8));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0x4000000000000000L, 63));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0x4000000000000000L, 64));
- Assert.assertEquals(0, op.evaluateBinary(8, 8, 0x4000000000000000L, 65));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0, -1));
+ Assert.assertEquals(0xFF80000000000000L, OP.evaluateBinary(8, 8, 0x8000000000000000L, 8));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, 0x8000000000000000L, 63));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, 0x8000000000000000L, 64));
+ Assert.assertEquals(-1, OP.evaluateBinary(8, 8, 0x8000000000000000L, 65));
+ Assert.assertEquals(0x40000000000000L, OP.evaluateBinary(8, 8, 0x4000000000000000L, 8));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0x4000000000000000L, 63));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0x4000000000000000L, 64));
+ Assert.assertEquals(0, OP.evaluateBinary(8, 8, 0x4000000000000000L, 65));
}
@Test
- public void testEvaluateBinaryBigInteger() {
-
- OpBehaviorIntSright op = new OpBehaviorIntSright();
-
+ public void testEvaluateBinaryBigInteger() {
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(8)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(8)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(-1)), 4);
+ OP.evaluateBinary(4, 4, BigInteger.ZERO, getUnsignedBigInt(-1)), 4);
assertEquals(getUnsignedBigInt(0xFF800000L),
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(8)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(8)), 4);
assertEquals(getUnsignedBigInt(0xFFFFFFFFL),
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(31)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(31)), 4);
assertEquals(getUnsignedBigInt(0xFFFFFFFFL),
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(32)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(32)), 4);
assertEquals(getUnsignedBigInt(0xFFFFFFFFL),
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(33)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x80000000L), getUnsignedBigInt(33)), 4);
assertEquals(getUnsignedBigInt(0x400000L),
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(8)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(8)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(31)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(31)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(32)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(32)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(33)), 4);
+ OP.evaluateBinary(4, 4, getUnsignedBigInt(0x40000000L), getUnsignedBigInt(33)), 4);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(8)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(8)), 8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(-1)), 8);
+ OP.evaluateBinary(8, 8, BigInteger.ZERO, getUnsignedBigInt(-1)), 8);
assertEquals(getUnsignedBigInt(0xFF80000000000000L),
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(8)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(8)),
8);
assertEquals(getUnsignedBigInt(-1L),
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(63)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(63)),
8);
assertEquals(getUnsignedBigInt(-1L),
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(64)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(64)),
8);
assertEquals(getUnsignedBigInt(-1L),
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(65)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x8000000000000000L), getUnsignedBigInt(65)),
8);
assertEquals(getUnsignedBigInt(0x40000000000000L),
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(8)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(8)),
8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(63)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(63)),
8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(64)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(64)),
8);
assertEquals(BigInteger.ZERO,
- op.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(65)),
+ OP.evaluateBinary(8, 8, getUnsignedBigInt(0x4000000000000000L), getUnsignedBigInt(65)),
8);
-
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorLzcountTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorLzcountTest.java
index c8a696d9ac..d99b4c2aec 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorLzcountTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorLzcountTest.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.
@@ -23,61 +23,52 @@ import org.junit.Test;
import ghidra.pcode.utils.Utils;
public class OpBehaviorLzcountTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorLzcount OP = OpBehavior.LZCOUNT;
+
@Test
public void testEvaluateUnaryLong() {
-
- OpBehaviorLzcount op = new OpBehaviorLzcount();
-
- Assert.assertEquals(8, op.evaluateUnary(1, 1, 0L));
- Assert.assertEquals(16, op.evaluateUnary(1, 2, 0L));
- Assert.assertEquals(32, op.evaluateUnary(1, 4, 0L));
- Assert.assertEquals(64, op.evaluateUnary(1, 8, 0L));
-
- Assert.assertEquals(0, op.evaluateUnary(1, 1, 0xffL));
- Assert.assertEquals(0, op.evaluateUnary(1, 2, 0xffffL));
- Assert.assertEquals(0, op.evaluateUnary(1, 4, 0xffffffffL));
- Assert.assertEquals(0, op.evaluateUnary(1, 8, 0xffffffffffffffffL));
-
- Assert.assertEquals(0, op.evaluateUnary(1, 1, 0x96L));
- Assert.assertEquals(0, op.evaluateUnary(1, 2, 0xdbf4L));
- Assert.assertEquals(1, op.evaluateUnary(1, 4, 0x460f457bL));
- Assert.assertEquals(3, op.evaluateUnary(1, 8, 0x1fae97efca7d5759L));
-
- Assert.assertEquals(4, op.evaluateUnary(1, 1, 0xaL));
- Assert.assertEquals(6, op.evaluateUnary(1, 2, 0x2a5L));
- Assert.assertEquals(9, op.evaluateUnary(1, 4, 0x60dfffL));
- Assert.assertEquals(13, op.evaluateUnary(1, 8, 0x635017adefe4eL));
-
- Assert.assertEquals(3, op.evaluateUnary(1, 1, 0x17L));
- Assert.assertEquals(8, op.evaluateUnary(1, 2, 0xd1L));
- Assert.assertEquals(22, op.evaluateUnary(1, 4, 0x39eL));
- Assert.assertEquals(27, op.evaluateUnary(1, 8, 0x189c178d6aL));
-
- Assert.assertEquals(4, op.evaluateUnary(1, 1, 0xfL));
- Assert.assertEquals(4, op.evaluateUnary(1, 2, 0xff0L));
- Assert.assertEquals(0, op.evaluateUnary(1, 4, 0xffff0000L));
- Assert.assertEquals(24, op.evaluateUnary(1, 8, 0xff00ff00ffL));
-
+ Assert.assertEquals(8, OP.evaluateUnary(1, 1, 0L));
+ Assert.assertEquals(16, OP.evaluateUnary(1, 2, 0L));
+ Assert.assertEquals(32, OP.evaluateUnary(1, 4, 0L));
+ Assert.assertEquals(64, OP.evaluateUnary(1, 8, 0L));
+
+ Assert.assertEquals(0, OP.evaluateUnary(1, 1, 0xffL));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 2, 0xffffL));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 4, 0xffffffffL));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 8, 0xffffffffffffffffL));
+
+ Assert.assertEquals(0, OP.evaluateUnary(1, 1, 0x96L));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 2, 0xdbf4L));
+ Assert.assertEquals(1, OP.evaluateUnary(1, 4, 0x460f457bL));
+ Assert.assertEquals(3, OP.evaluateUnary(1, 8, 0x1fae97efca7d5759L));
+
+ Assert.assertEquals(4, OP.evaluateUnary(1, 1, 0xaL));
+ Assert.assertEquals(6, OP.evaluateUnary(1, 2, 0x2a5L));
+ Assert.assertEquals(9, OP.evaluateUnary(1, 4, 0x60dfffL));
+ Assert.assertEquals(13, OP.evaluateUnary(1, 8, 0x635017adefe4eL));
+
+ Assert.assertEquals(3, OP.evaluateUnary(1, 1, 0x17L));
+ Assert.assertEquals(8, OP.evaluateUnary(1, 2, 0xd1L));
+ Assert.assertEquals(22, OP.evaluateUnary(1, 4, 0x39eL));
+ Assert.assertEquals(27, OP.evaluateUnary(1, 8, 0x189c178d6aL));
+
+ Assert.assertEquals(4, OP.evaluateUnary(1, 1, 0xfL));
+ Assert.assertEquals(4, OP.evaluateUnary(1, 2, 0xff0L));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 4, 0xffff0000L));
+ Assert.assertEquals(24, OP.evaluateUnary(1, 8, 0xff00ff00ffL));
}
@Test
public void testEvaluateUnaryBigInteger() {
- OpBehaviorLzcount op = new OpBehaviorLzcount();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = Utils
- .convertToUnsignedValue(new BigInteger("80000000000000000000000000000000", 16), 16);
-
- assertEquals(BigInteger.valueOf(128), op.evaluateUnary(1, 16, BigInteger.ZERO), 16);
- assertEquals(BigInteger.ZERO, op.evaluateUnary(1, 16, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.ONE, op.evaluateUnary(1, 16, BIG_POSITIVE), 16);
- assertEquals(BigInteger.ZERO, op.evaluateUnary(1, 16, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.valueOf(128), OP.evaluateUnary(1, 16, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateUnary(1, 16, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateUnary(1, 16, BIG_POSITIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateUnary(1, 16, BIG_NEGATIVE), 16);
BigInteger val = BigInteger.valueOf(0x35017adefe4eL);
val = val.shiftLeft(64);
val = val.or(Utils.convertToUnsignedValue(BigInteger.valueOf(0xd46223189c178d6aL), 8));
- assertEquals(BigInteger.valueOf(18), op.evaluateUnary(1, 16, val), 16);
+ assertEquals(BigInteger.valueOf(18), OP.evaluateUnary(1, 16, val), 16);
BigInteger FF = BigInteger.valueOf(0xff);
val = BigInteger.ZERO;
@@ -85,7 +76,6 @@ public class OpBehaviorLzcountTest extends AbstractOpBehaviorTest {
val = val.shiftLeft(16);
val = val.add(FF);
}
- assertEquals(BigInteger.valueOf(8), op.evaluateUnary(1, 40, val), 40);
+ assertEquals(BigInteger.valueOf(8), OP.evaluateUnary(1, 40, val), 40);
}
-
}
diff --git a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorPopcountTest.java b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorPopcountTest.java
index 777001ee2e..dc4ee8b35b 100644
--- a/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorPopcountTest.java
+++ b/Ghidra/Framework/Emulation/src/test/java/ghidra/pcode/opbehavior/OpBehaviorPopcountTest.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.
@@ -23,61 +23,52 @@ import org.junit.Test;
import ghidra.pcode.utils.Utils;
public class OpBehaviorPopcountTest extends AbstractOpBehaviorTest {
+ static final OpBehaviorPopcount OP = OpBehavior.POPCOUNT;
+
@Test
public void testEvaluateUnaryLong() {
-
- OpBehaviorPopcount op = new OpBehaviorPopcount();
-
- Assert.assertEquals(0, op.evaluateUnary(1, 1, 0L));
- Assert.assertEquals(0, op.evaluateUnary(1, 2, 0L));
- Assert.assertEquals(0, op.evaluateUnary(1, 4, 0L));
- Assert.assertEquals(0, op.evaluateUnary(1, 8, 0L));
-
- Assert.assertEquals(8, op.evaluateUnary(1, 1, 0xffL));
- Assert.assertEquals(16, op.evaluateUnary(1, 2, 0xffffL));
- Assert.assertEquals(32, op.evaluateUnary(1, 4, 0xffffffffL));
- Assert.assertEquals(64, op.evaluateUnary(1, 8, 0xffffffffffffffffL));
-
- Assert.assertEquals(4, op.evaluateUnary(1, 1, 0x96L));
- Assert.assertEquals(11, op.evaluateUnary(1, 2, 0xdbf4L));
- Assert.assertEquals(16, op.evaluateUnary(1, 4, 0x460f457bL));
- Assert.assertEquals(41, op.evaluateUnary(1, 8, 0x1fae97efca7d5759L));
-
- Assert.assertEquals(5, op.evaluateUnary(1, 1, 0x7aL));
- Assert.assertEquals(10, op.evaluateUnary(1, 2, 0xfca5L));
- Assert.assertEquals(20, op.evaluateUnary(1, 4, 0x2660dfffL));
- Assert.assertEquals(38, op.evaluateUnary(1, 8, 0x79f635017adefe4eL));
-
- Assert.assertEquals(4, op.evaluateUnary(1, 1, 0x17L));
- Assert.assertEquals(10, op.evaluateUnary(1, 2, 0x77d1L));
- Assert.assertEquals(15, op.evaluateUnary(1, 4, 0x5758039eL));
- Assert.assertEquals(28, op.evaluateUnary(1, 8, 0xd46223189c178d6aL));
-
- Assert.assertEquals(7, op.evaluateUnary(1, 1, 0xbfL));
- Assert.assertEquals(12, op.evaluateUnary(1, 2, 0xe3efL));
- Assert.assertEquals(17, op.evaluateUnary(1, 4, 0xb2d7e134L));
- Assert.assertEquals(34, op.evaluateUnary(1, 8, 0x69f7a0fa6eeda6L));
-
+ Assert.assertEquals(0, OP.evaluateUnary(1, 1, 0L));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 2, 0L));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 4, 0L));
+ Assert.assertEquals(0, OP.evaluateUnary(1, 8, 0L));
+
+ Assert.assertEquals(8, OP.evaluateUnary(1, 1, 0xffL));
+ Assert.assertEquals(16, OP.evaluateUnary(1, 2, 0xffffL));
+ Assert.assertEquals(32, OP.evaluateUnary(1, 4, 0xffffffffL));
+ Assert.assertEquals(64, OP.evaluateUnary(1, 8, 0xffffffffffffffffL));
+
+ Assert.assertEquals(4, OP.evaluateUnary(1, 1, 0x96L));
+ Assert.assertEquals(11, OP.evaluateUnary(1, 2, 0xdbf4L));
+ Assert.assertEquals(16, OP.evaluateUnary(1, 4, 0x460f457bL));
+ Assert.assertEquals(41, OP.evaluateUnary(1, 8, 0x1fae97efca7d5759L));
+
+ Assert.assertEquals(5, OP.evaluateUnary(1, 1, 0x7aL));
+ Assert.assertEquals(10, OP.evaluateUnary(1, 2, 0xfca5L));
+ Assert.assertEquals(20, OP.evaluateUnary(1, 4, 0x2660dfffL));
+ Assert.assertEquals(38, OP.evaluateUnary(1, 8, 0x79f635017adefe4eL));
+
+ Assert.assertEquals(4, OP.evaluateUnary(1, 1, 0x17L));
+ Assert.assertEquals(10, OP.evaluateUnary(1, 2, 0x77d1L));
+ Assert.assertEquals(15, OP.evaluateUnary(1, 4, 0x5758039eL));
+ Assert.assertEquals(28, OP.evaluateUnary(1, 8, 0xd46223189c178d6aL));
+
+ Assert.assertEquals(7, OP.evaluateUnary(1, 1, 0xbfL));
+ Assert.assertEquals(12, OP.evaluateUnary(1, 2, 0xe3efL));
+ Assert.assertEquals(17, OP.evaluateUnary(1, 4, 0xb2d7e134L));
+ Assert.assertEquals(34, OP.evaluateUnary(1, 8, 0x69f7a0fa6eeda6L));
}
@Test
public void testEvaluateUnaryBigInteger() {
- OpBehaviorPopcount op = new OpBehaviorPopcount();
-
- BigInteger NEGATIVE_ONE = Utils.convertToUnsignedValue(BigInteger.valueOf(-1), 16);
- BigInteger BIG_POSITIVE = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);
- BigInteger BIG_NEGATIVE = Utils
- .convertToUnsignedValue(new BigInteger("80000000000000000000000000000000", 16), 16);
-
- assertEquals(BigInteger.ZERO, op.evaluateUnary(1, 16, BigInteger.ZERO), 16);
- assertEquals(BigInteger.valueOf(128), op.evaluateUnary(1, 16, NEGATIVE_ONE), 16);
- assertEquals(BigInteger.valueOf(127), op.evaluateUnary(1, 16, BIG_POSITIVE), 16);
- assertEquals(BigInteger.ONE, op.evaluateUnary(1, 16, BIG_NEGATIVE), 16);
+ assertEquals(BigInteger.ZERO, OP.evaluateUnary(1, 16, BigInteger.ZERO), 16);
+ assertEquals(BigInteger.valueOf(128), OP.evaluateUnary(1, 16, NEGATIVE_ONE), 16);
+ assertEquals(BigInteger.valueOf(127), OP.evaluateUnary(1, 16, BIG_POSITIVE), 16);
+ assertEquals(BigInteger.ONE, OP.evaluateUnary(1, 16, BIG_NEGATIVE), 16);
BigInteger val = BigInteger.valueOf(0x79f635017adefe4eL);
val = val.shiftLeft(64);
val = val.or(Utils.convertToUnsignedValue(BigInteger.valueOf(0xd46223189c178d6aL), 8));
- assertEquals(BigInteger.valueOf(66), op.evaluateUnary(1, 16, val), 16);
+ assertEquals(BigInteger.valueOf(66), OP.evaluateUnary(1, 16, val), 16);
BigInteger FF = BigInteger.valueOf(0xff);
val = BigInteger.ZERO;
@@ -85,6 +76,6 @@ public class OpBehaviorPopcountTest extends AbstractOpBehaviorTest {
val = val.shiftLeft(16);
val = val.add(FF);
}
- assertEquals(BigInteger.valueOf(160), op.evaluateUnary(1, 40, val), 40);
+ assertEquals(BigInteger.valueOf(160), OP.evaluateUnary(1, 40, val), 40);
}
}
diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/Appender.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/Appender.java
index ed0ad1cb7a..13c681fdd3 100644
--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/Appender.java
+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/pcode/Appender.java
@@ -21,7 +21,6 @@ import ghidra.program.model.lang.Register;
/**
* An appender to receive formatted p-code ops.
- *
* <p>
* Using {@link AbstractAppender} is highly recommended, as it makes available methods for
* displaying elements according to established Ghidra conventions.
@@ -30,9 +29,7 @@ import ghidra.program.model.lang.Register;
*/
interface Appender<T> {
/**
- * Get the language of the p-code being formatted
- *
- * @return
+ * {@return the language of the p-code being formatted}
*/
Language getLanguage();
@@ -85,7 +82,6 @@ interface Appender<T> {
/**
* Append a character
- *
* <p>
* <b>NOTE:</b> if extra spacing is desired, esp., surrounding the equals sign, it must be
* appended manually.
diff --git a/Ghidra/Processors/AARCH64/src/main/java/ghidra/program/emulation/Aarch64PcodeUseropLibraryFactory.java b/Ghidra/Processors/AARCH64/src/main/java/ghidra/program/emulation/Aarch64PcodeUseropLibraryFactory.java
index 582ea9a189..7e8c857bd8 100644
--- a/Ghidra/Processors/AARCH64/src/main/java/ghidra/program/emulation/Aarch64PcodeUseropLibraryFactory.java
+++ b/Ghidra/Processors/AARCH64/src/main/java/ghidra/program/emulation/Aarch64PcodeUseropLibraryFactory.java
@@ -18,6 +18,7 @@ package ghidra.program.emulation;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibraryFactory.UseropLibrary;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.program.model.pcode.Varnode;
/**
@@ -31,38 +32,10 @@ public class Aarch64PcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
@Override
public <T> PcodeUseropLibrary<T> create(SleighLanguage language,
PcodeArithmetic<T> arithmetic) {
- return new Aarch64PcodeUseropLibrary<>(language);
+ return new Aarch64PcodeUseropLibrary<>();
}
public static class Aarch64PcodeUseropLibrary<T> extends AnnotatedPcodeUseropLibrary<T> {
- public Aarch64PcodeUseropLibrary(SleighLanguage language) {
- SleighPcodeUseropDefinition.Factory factory =
- new SleighPcodeUseropDefinition.Factory(language);
-
- putOp(factory.define("MP_INT_ABS").params("n").body(args -> """
- if (n >= 0) goto <pos>;
- __op_output = -n;
- goto <done>;
- <pos>
- __op_output = n;
- <done>
- """).build());
-
- putOp(factory.define("SIMD_PIECE").params("simdBytes", "offset").body(args -> """
- __op_output = simdBytes(%d*offset);
- """.formatted(args.get(1).getSize())).build());
-
- putOp(factory.define("a64_TBL").params("init", "n1", "m").body(args -> {
- return genA64_TBL(args.get(0), "n1");
- }).overload().params("init", "n1", "n2", "m").body(args -> {
- return genA64_TBL(args.get(0), "n1", "n2");
- }).overload().params("init", "n1", "n2", "n3", "m").body(args -> {
- return genA64_TBL(args.get(0), "n1", "n2", "n3");
- }).overload().params("init", "n1", "n2", "n3", "n4", "m").body(args -> {
- return genA64_TBL(args.get(0), "n1", "n2", "n3", "n4");
- }).build());
- }
-
protected String genA64_TBL(Varnode out, String... regs) {
int size = out.getSize();
String body = genBuildTable(regs) + genIndex(size, regs.length);
@@ -104,6 +77,38 @@ public class Aarch64PcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
return buf.toString();
}
+ @PcodeUserop
+ public SleighPcodeUseropDefinition MP_INT_ABS(BuilderStage1 builder) {
+ return builder.params("n").body(_ -> """
+ if (n >= 0) goto <pos>;
+ __op_output = -n;
+ goto <done>;
+ <pos>
+ __op_output = n;
+ <done>
+ """).build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition SIMD_PIECE(BuilderStage1 builder) {
+ return builder.params("simdBytes", "offset").body(args -> """
+ __op_output = simdBytes(%d*offset);
+ """.formatted(args.get(1).getSize())).build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition a64_TBL(BuilderStage1 builder) {
+ return builder.params("init", "n1", "m").body(args -> {
+ return genA64_TBL(args.get(0), "n1");
+ }).overload().params("init", "n1", "n2", "m").body(args -> {
+ return genA64_TBL(args.get(0), "n1", "n2");
+ }).overload().params("init", "n1", "n2", "n3", "m").body(args -> {
+ return genA64_TBL(args.get(0), "n1", "n2", "n3");
+ }).overload().params("init", "n1", "n2", "n3", "n4", "m").body(args -> {
+ return genA64_TBL(args.get(0), "n1", "n2", "n3", "n4");
+ }).build();
+ }
+
@PcodeUserop(functional = true)
public void CallSecureMonitor(int imm16) {
}
diff --git a/Ghidra/Processors/AARCH64/src/test.slow/java/ghidra/program/emulation/Aarch64PcodeLibraryTest.java b/Ghidra/Processors/AARCH64/src/test.slow/java/ghidra/program/emulation/Aarch64PcodeLibraryTest.java
index b0fc43adc7..0feceafa2f 100644
--- a/Ghidra/Processors/AARCH64/src/test.slow/java/ghidra/program/emulation/Aarch64PcodeLibraryTest.java
+++ b/Ghidra/Processors/AARCH64/src/test.slow/java/ghidra/program/emulation/Aarch64PcodeLibraryTest.java
@@ -68,14 +68,14 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 8);
Varnode vnInit = vn(16, 8);
Varnode vnN1 = vn(32, 16);
Varnode vnM = vn(96, 8);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnM),
lib);
@@ -87,15 +87,15 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 8);
Varnode vnInit = vn(16, 8);
Varnode vnN1 = vn(32, 16);
Varnode vnN2 = vn(48, 16);
Varnode vnM = vn(96, 8);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnN2, vnM),
lib);
@@ -107,8 +107,8 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 8);
Varnode vnInit = vn(16, 8);
@@ -116,7 +116,7 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
Varnode vnN2 = vn(48, 16);
Varnode vnN3 = vn(64, 16);
Varnode vnM = vn(96, 8);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnN2, vnN3, vnM),
lib);
@@ -128,8 +128,8 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 8);
Varnode vnInit = vn(16, 8);
@@ -138,7 +138,7 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
Varnode vnN3 = vn(64, 16);
Varnode vnN4 = vn(80, 16);
Varnode vnM = vn(96, 8);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnN2, vnN3, vnN4, vnM),
lib);
@@ -150,14 +150,14 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 16);
Varnode vnInit = vn(16, 16);
Varnode vnN1 = vn(32, 16);
Varnode vnM = vn(96, 16);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnM),
lib);
@@ -169,15 +169,15 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 16);
Varnode vnInit = vn(16, 16);
Varnode vnN1 = vn(32, 16);
Varnode vnN2 = vn(48, 16);
Varnode vnM = vn(96, 16);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnN2, vnM),
lib);
@@ -189,8 +189,8 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 16);
Varnode vnInit = vn(16, 16);
@@ -198,7 +198,7 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
Varnode vnN2 = vn(48, 16);
Varnode vnN3 = vn(64, 16);
Varnode vnM = vn(96, 16);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnN2, vnN3, vnM),
lib);
@@ -210,8 +210,8 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
PcodeUseropLibrary<byte[]> lib = PcodeUseropLibraryFactory.createUseropLibraryFromId(
"aarch64", aarch64, BytesPcodeArithmetic.forLanguage(aarch64));
- SleighPcodeUseropDefinition<byte[]> tbl =
- (SleighPcodeUseropDefinition<byte[]>) lib.getUserops().get("a64_TBL");
+ SleighPcodeUseropDefinition tbl =
+ SleighPcodeUseropDefinition.cast(lib.getUserops().get("a64_TBL"));
Varnode vnDest = vn(0, 16);
Varnode vnInit = vn(16, 16);
@@ -220,7 +220,7 @@ public class Aarch64PcodeLibraryTest extends AbstractGhidraHeadlessIntegrationTe
Varnode vnN3 = vn(64, 16);
Varnode vnN4 = vn(80, 16);
Varnode vnM = vn(96, 16);
- PcodeProgram program = tbl.programFor(
+ PcodeProgram program = tbl.programFor(aarch64,
List.of(vnDest, vnInit, vnN1, vnN2, vnN3, vnN4, vnM),
lib);
diff --git a/Ghidra/Processors/ARM/src/main/java/ghidra/program/emulation/ArmPcodeUseropLibraryFactory.java b/Ghidra/Processors/ARM/src/main/java/ghidra/program/emulation/ArmPcodeUseropLibraryFactory.java
index e71d591753..a76a36487e 100644
--- a/Ghidra/Processors/ARM/src/main/java/ghidra/program/emulation/ArmPcodeUseropLibraryFactory.java
+++ b/Ghidra/Processors/ARM/src/main/java/ghidra/program/emulation/ArmPcodeUseropLibraryFactory.java
@@ -22,9 +22,9 @@ import ghidra.pcode.emu.DefaultPcodeThread.PcodeThreadExecutor;
import ghidra.pcode.error.LowlevelError;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibraryFactory.UseropLibrary;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.program.model.lang.Register;
import ghidra.program.model.lang.RegisterValue;
-import ghidra.program.model.pcode.Varnode;
import ghidra.util.Msg;
@UseropLibrary(id = "arm")
@@ -52,32 +52,27 @@ public class ArmPcodeUseropLibraryFactory implements PcodeUseropLibraryFactory {
tMode = null;
aMode = null;
}
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition VectorSignedToFloat(BuilderStage1 builder) {
+ return builder.params("s", "mode").body(args -> switch (args.get(0).getSize()) {
+ case 4 -> "__op_output = int2float(s);";
+ default -> throw new LowlevelError(
+ "VectorSignedToFloat: invalid dest size of " + args.get(0).getSize());
+ }).build();
+ }
- SleighPcodeUseropDefinition.Factory factory =
- new SleighPcodeUseropDefinition.Factory(language);
-
- putOp(factory.define("VectorSignedToFloat")
- .params("s", "mode")
- .body(args -> switch (args.get(0).getSize()) {
- case 4 -> "__op_output = int2float(s);";
- default -> throw new LowlevelError(
- "VectorSignedToFloat: invalid dest size of " + args.get(0).getSize());
- })
- .build());
- putOp(factory.define("VectorUnsignedToFloat")
- .params("s", "mode")
- .body(args -> switch (args.get(0).getSize()) {
- case 4 -> {
- Varnode s = args.get(1);
- yield """
- temp:%d = zext(s);
- __op_output = int2float(s);
- """.formatted(s.getSize() + 1);
- }
- default -> throw new LowlevelError(
- "VectorSignedToFloat: invalid dest size of " + args.get(0).getSize());
- })
- .build());
+ @PcodeUserop
+ public SleighPcodeUseropDefinition VectorUnsignedToFloat(BuilderStage1 builder) {
+ return builder.params("s", "mode").body(args -> switch (args.get(0).getSize()) {
+ case 4 -> """
+ temp:%d = zext(s);
+ __op_output = int2float(s);
+ """.formatted(args.get(1).getSize() + 1);
+ default -> throw new LowlevelError(
+ "VectorSignedToFloat: invalid dest size of " + args.get(0).getSize());
+ }).build();
}
@PcodeUserop(modifiesContext = true)
diff --git a/Ghidra/Processors/Hexagon/src/main/java/ghidra/program/emulation/HexagonPcodeUseropLibraryFactory.java b/Ghidra/Processors/Hexagon/src/main/java/ghidra/program/emulation/HexagonPcodeUseropLibraryFactory.java
index cfa6d1d82f..c1cb0cd244 100644
--- a/Ghidra/Processors/Hexagon/src/main/java/ghidra/program/emulation/HexagonPcodeUseropLibraryFactory.java
+++ b/Ghidra/Processors/Hexagon/src/main/java/ghidra/program/emulation/HexagonPcodeUseropLibraryFactory.java
@@ -21,6 +21,7 @@ import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.error.LowlevelError;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibraryFactory.UseropLibrary;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.program.model.pcode.Varnode;
@UseropLibrary(id = "hexagon")
@@ -28,7 +29,7 @@ public class HexagonPcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
@Override
public <T> PcodeUseropLibrary<T> create(SleighLanguage language,
PcodeArithmetic<T> arithmetic) {
- return new HexagonPcodeUseropLibrary<T>(language);
+ return new HexagonPcodeUseropLibrary<T>();
}
public static class HexagonPcodeUseropLibrary<T> extends AnnotatedPcodeUseropLibrary<T> {
@@ -38,75 +39,16 @@ public class HexagonPcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
private static final int FP_INFINITE_CLASS_MASK = 0x08;
private static final int FP_NAN_CLASS_MASK = 0x10;
- public HexagonPcodeUseropLibrary(SleighLanguage language) {
- SleighPcodeUseropDefinition.Factory factory =
- new SleighPcodeUseropDefinition.Factory(language);
-
- putOp(factory.define("min").params("a", "b").body(args -> """
+ @PcodeUserop
+ public SleighPcodeUseropDefinition min(BuilderStage1 builder) {
+ return builder.params("a", "b").body(_ -> """
if (a s<= b) goto <take_a>;
__op_output = b;
goto <done>;
<take_a>
__op_output = a;
<done>
- """).build());
-
- putOp(factory.define("vlslh")
- .params("source", "shift")
- .body(args -> genVecShift(args.get(0), 16, "<<", ">>"))
- .build());
- putOp(factory.define("vlsrh")
- .params("source", "shift")
- .body(args -> genVecShift(args.get(0), 16, ">>", "<<"))
- .build());
- putOp(factory.define("vlslw")
- .params("source", "shift")
- .body(args -> genVecShift(args.get(0), 32, "<<", ">>"))
- .build());
- putOp(factory.define("vlsrw")
- .params("source", "shift")
- .body(args -> genVecShift(args.get(0), 32, ">>", "<<"))
- .build());
-
- putOp(factory.define("vmux").params("sel", "a", "b").body(args -> """
- local s:1;
- local result:8;
- """ + genVec(0, 8, 1, i -> """
- s = ((sel >> %d) & 1) * 0xff;
- result[%d,8] = (a[%d,8] & s) | (b[%d,8] & ~s);
- """.formatted(i, 8 * i, 8 * i, 8 * i)) + """
- __op_output = result;
- """).build());
-
- putOp(factory.define("vabsh").params("n").body(args -> genVecAbs(16)).build());
- putOp(factory.define("vabsw").params("n").body(args -> genVecAbs(32)).build());
-
- putOp(factory.define("dfmpylh").params("rdd", "rss", "rtt").body(args -> """
- rss_lo:8 = rss & 0xffffffff;
- rtt_hi:8 = rtt >> 32;
- prod:8 = (rss_lo * (0x00100000 | (rtt_hi & 0xfffff))) << 1;
- __op_output = rdd + prod;
- """).build());
- putOp(factory.define("dfmpyll").params("rss", "rtt").body(args -> """
- rss_lo:8 = rss & 0xffffffff;
- rtt_lo:8 = rtt & 0xffffffff;
- prod:8 = rss_lo * rtt_lo;
- result:8 = (prod >> 32) << 1;
- if ((prod & 0xffffffff) == 0) goto <done>;
- result = result + 1;
- <done>
- __op_output = result;
- """).build());
-
- putOp(factory.define("isClassifiedFloat")
- .params("bits", "cls")
- .body(args -> switch (args.get(1).getSize()) {
- case 4 -> "__op_output = __isClassifiedFloat32(bits, cls);";
- case 8 -> "__op_output = __isClassifiedFloat64(bits, cls);";
- default -> throw new LowlevelError(
- "isClassifiedFloat: invalid float size of " + args.get(1).getSize());
- })
- .build());
+ """).build();
}
protected String genVec(int start, int stop, int step, Function<Integer, String> slot) {
@@ -134,6 +76,47 @@ public class HexagonPcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
""";
}
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vlslh(BuilderStage1 builder) {
+ return builder.params("source", "shift")
+ .body(args -> genVecShift(args.get(0), 16, "<<", ">>"))
+ .build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vlsrh(BuilderStage1 builder) {
+ return builder.params("source", "shift")
+ .body(args -> genVecShift(args.get(0), 16, ">>", "<<"))
+ .build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vlslw(BuilderStage1 builder) {
+ return builder.params("source", "shift")
+ .body(args -> genVecShift(args.get(0), 32, "<<", ">>"))
+ .build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vlsrw(BuilderStage1 builder) {
+ return builder.params("source", "shift")
+ .body(args -> genVecShift(args.get(0), 32, ">>", "<<"))
+ .build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vmux(BuilderStage1 builder) {
+ return builder.params("sel", "a", "b").body(_ -> """
+ local s:1;
+ local result:8;
+ """ + genVec(0, 8, 1, i -> """
+ s = ((sel >> %d) & 1) * 0xff;
+ result[%d,8] = (a[%d,8] & s) | (b[%d,8] & ~s);
+ """.formatted(i, 8 * i, 8 * i, 8 * i)) + """
+ __op_output = result;
+ """).build();
+ }
+
protected String genVecAbs(int slotSize) {
long signMask = Long.MIN_VALUE;
for (int i = 32; i >= slotSize; i >>>= 1) {
@@ -151,6 +134,52 @@ public class HexagonPcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
""".formatted(slot, slotSize, slot, slotSize, slot, slotSize));
}
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vabsh(BuilderStage1 builder) {
+ return builder.params("n").body(_ -> genVecAbs(16)).build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vabsw(BuilderStage1 builder) {
+ return builder.params("n").body(_ -> genVecAbs(32)).build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition dfmpylh(BuilderStage1 builder) {
+ return builder.params("rdd", "rss", "rtt").body(_ -> """
+ rss_lo:8 = rss & 0xffffffff;
+ rtt_hi:8 = rtt >> 32;
+ prod:8 = (rss_lo * (0x00100000 | (rtt_hi & 0xfffff))) << 1;
+ __op_output = rdd + prod;
+ """).build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition dfmpyll(BuilderStage1 builder) {
+ return builder.params("rss", "rtt").body(_ -> """
+ rss_lo:8 = rss & 0xffffffff;
+ rtt_lo:8 = rtt & 0xffffffff;
+ prod:8 = rss_lo * rtt_lo;
+ result:8 = (prod >> 32) << 1;
+ if ((prod & 0xffffffff) == 0) goto <done>;
+ result = result + 1;
+ <done>
+ __op_output = result;
+ """).build();
+ }
+
+ // LATER: Could/should this be done in Sleigh instead?
+ @PcodeUserop(functional = true)
+ public static long dfmpyfix(long rss, long rtt) {
+ return HexagonFp64.dfmpyfix(rss, rtt);
+ }
+
+ // LATER: Could/should this be done in Sleigh instead?
+ @PcodeUserop(functional = true)
+ public static long dfmpyhh(long rdd, long rss, long rtt) {
+ return HexagonFp64.dfmpyhh(rdd, rss, rtt);
+ }
+
@PcodeUserop(functional = true)
public static int __isClassifiedFloat32(int valueBits, int cls) {
int exp = HexagonFp32.maskFp32Exponent(valueBits);
@@ -195,16 +224,16 @@ public class HexagonPcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
return 0;
}
- // LATER: Could/should this be done in Sleigh instead?
- @PcodeUserop(functional = true)
- public static long dfmpyfix(long rss, long rtt) {
- return HexagonFp64.dfmpyfix(rss, rtt);
- }
-
- // LATER: Could/should this be done in Sleigh instead?
- @PcodeUserop(functional = true)
- public static long dfmpyhh(long rdd, long rss, long rtt) {
- return HexagonFp64.dfmpyhh(rdd, rss, rtt);
+ @PcodeUserop
+ public SleighPcodeUseropDefinition isClassifiedFloat(BuilderStage1 builder) {
+ return builder.params("bits", "cls")
+ .body(args -> switch (args.get(1).getSize()) {
+ case 4 -> "__op_output = __isClassifiedFloat32(bits, cls);";
+ case 8 -> "__op_output = __isClassifiedFloat64(bits, cls);";
+ default -> throw new LowlevelError(
+ "isClassifiedFloat: invalid float size of " + args.get(1).getSize());
+ })
+ .build();
}
}
}
diff --git a/Ghidra/Processors/PowerPC/src/main/java/ghidra/program/emulation/PpcPcodeUseropLibraryFactory.java b/Ghidra/Processors/PowerPC/src/main/java/ghidra/program/emulation/PpcPcodeUseropLibraryFactory.java
index b8f153f4c5..aae10ba5fc 100644
--- a/Ghidra/Processors/PowerPC/src/main/java/ghidra/program/emulation/PpcPcodeUseropLibraryFactory.java
+++ b/Ghidra/Processors/PowerPC/src/main/java/ghidra/program/emulation/PpcPcodeUseropLibraryFactory.java
@@ -18,29 +18,17 @@ package ghidra.program.emulation;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibraryFactory.UseropLibrary;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
@UseropLibrary(id = "ppc")
public class PpcPcodeUseropLibraryFactory implements PcodeUseropLibraryFactory {
@Override
public <T> PcodeUseropLibrary<T> create(SleighLanguage language,
PcodeArithmetic<T> arithmetic) {
- return new PpcPcodeUseropLibrary<>(language);
+ return new PpcPcodeUseropLibrary<>();
}
public static class PpcPcodeUseropLibrary<T> extends AnnotatedPcodeUseropLibrary<T> {
- public PpcPcodeUseropLibrary(SleighLanguage language) {
- SleighPcodeUseropDefinition.Factory factory =
- new SleighPcodeUseropDefinition.Factory(language);
-
- putOp(factory.define("vectorPermute").params("s1", "s2", "p").body(args -> """
- local table:32;
- local result:16;
- table[128,128] = s1;
- table[0,128] = s2;
- """ + genIndex() + """
- __op_output = result;
- """).build());
- }
protected String genIndex() {
StringBuilder buf = new StringBuilder();
@@ -51,5 +39,17 @@ public class PpcPcodeUseropLibraryFactory implements PcodeUseropLibraryFactory {
}
return buf.toString();
}
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition vectorPermute(BuilderStage1 builder) {
+ return builder.params("s1", "s2", "p").body(_ -> """
+ local table:32;
+ local result:16;
+ table[128,128] = s1;
+ table[0,128] = s2;
+ """ + genIndex() + """
+ __op_output = result;
+ """).build();
+ }
}
}
diff --git a/Ghidra/Processors/Xtensa/src/main/java/ghidra/program/emulation/XtensaPcodeUseropLibraryFactory.java b/Ghidra/Processors/Xtensa/src/main/java/ghidra/program/emulation/XtensaPcodeUseropLibraryFactory.java
index 77a3c0a336..8f2970a881 100644
--- a/Ghidra/Processors/Xtensa/src/main/java/ghidra/program/emulation/XtensaPcodeUseropLibraryFactory.java
+++ b/Ghidra/Processors/Xtensa/src/main/java/ghidra/program/emulation/XtensaPcodeUseropLibraryFactory.java
@@ -19,13 +19,14 @@ import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.error.LowlevelError;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibraryFactory.UseropLibrary;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
@UseropLibrary(id = "xtensa")
public class XtensaPcodeUseropLibraryFactory implements PcodeUseropLibraryFactory {
@Override
public <T> PcodeUseropLibrary<T> create(SleighLanguage language,
PcodeArithmetic<T> arithmetic) {
- return new XtensaPcodeUseropLibrary<>(language);
+ return new XtensaPcodeUseropLibrary<>();
}
public static class IntStack {
@@ -62,11 +63,21 @@ public class XtensaPcodeUseropLibraryFactory implements PcodeUseropLibraryFactor
private final IntStack stack = new IntStack();
- public XtensaPcodeUseropLibrary(SleighLanguage language) {
- SleighPcodeUseropDefinition.Factory factory =
- new SleighPcodeUseropDefinition.Factory(language);
+ protected String genPushN(int n) {
+ StringBuilder buf = new StringBuilder();
+ int i = 0;
+ for (; i < n; i++) {
+ buf.append(" __pushValue(a%d);\n".formatted(i));
+ }
+ for (; i < 16; i++) {
+ buf.append(" a%d = a%d;\n".formatted(i - n, i));
+ }
+ return buf.toString();
+ }
- putOp(factory.define("rotateRegWindow").params("callinc").body(args -> """
+ @PcodeUserop
+ public SleighPcodeUseropDefinition rotateRegWindow(BuilderStage1 builder) {
+ return builder.params("callinc").body(_ -> """
__pushCount(callinc);
if (callinc == 0) goto <done>;
if (callinc == 1) goto <push4>;
@@ -82,9 +93,24 @@ public class XtensaPcodeUseropLibraryFactory implements PcodeUseropLibraryFactor
<push12>
""" + genPushN(12) + """
<done>
- """).build());
+ """).build();
+ }
+
+ protected String genPopN(int n) {
+ StringBuilder buf = new StringBuilder();
+ int i = 15;
+ for (; i >= n; i--) {
+ buf.append(" a%d = a%d;\n".formatted(i, i - n));
+ }
+ for (; i >= 0; i--) {
+ buf.append(" a%d = __popValue();\n".formatted(i));
+ }
+ return buf.toString();
+ }
- putOp(factory.define("restoreRegWindow").body(args -> """
+ @PcodeUserop
+ public SleighPcodeUseropDefinition restoreRegWindow(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
callinc:4 = (a0 >> 30) & 0x3;
__popCount(callinc);
if (callinc == 0) goto <done>;
@@ -100,31 +126,7 @@ public class XtensaPcodeUseropLibraryFactory implements PcodeUseropLibraryFactor
<pop12>
""" + genPopN(12) + """
<done>
- """).build());
- }
-
- protected String genPushN(int n) {
- StringBuilder buf = new StringBuilder();
- int i = 0;
- for (; i < n; i++) {
- buf.append(" __pushValue(a%d);\n".formatted(i));
- }
- for (; i < 16; i++) {
- buf.append(" a%d = a%d;\n".formatted(i - n, i));
- }
- return buf.toString();
- }
-
- protected String genPopN(int n) {
- StringBuilder buf = new StringBuilder();
- int i = 15;
- for (; i >= n; i--) {
- buf.append(" a%d = a%d;\n".formatted(i, i - n));
- }
- for (; i >= 0; i--) {
- buf.append(" a%d = __popValue();\n".formatted(i));
- }
- return buf.toString();
+ """).build();
}
@PcodeUserop(functional = true, hasSideEffects = false)
diff --git a/Ghidra/Processors/tricore/src/main/java/ghidra/program/emulation/TricorePcodeUseropLibraryFactory.java b/Ghidra/Processors/tricore/src/main/java/ghidra/program/emulation/TricorePcodeUseropLibraryFactory.java
index 4409245160..ecc9efc944 100644
--- a/Ghidra/Processors/tricore/src/main/java/ghidra/program/emulation/TricorePcodeUseropLibraryFactory.java
+++ b/Ghidra/Processors/tricore/src/main/java/ghidra/program/emulation/TricorePcodeUseropLibraryFactory.java
@@ -18,23 +18,22 @@ package ghidra.program.emulation;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeUseropLibraryFactory.UseropLibrary;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
@UseropLibrary(id = "tricore")
public class TricorePcodeUseropLibraryFactory implements PcodeUseropLibraryFactory {
@Override
public <T> PcodeUseropLibrary<T> create(SleighLanguage language,
PcodeArithmetic<T> arithmetic) {
- return new TricorePcodeUseropLibrary<>(language);
+ return new TricorePcodeUseropLibrary<>();
}
public static class TricorePcodeUseropLibrary<T> extends AnnotatedPcodeUseropLibrary<T> {
- public TricorePcodeUseropLibrary(SleighLanguage language) {
- SleighPcodeUseropDefinition.Factory factory =
- new SleighPcodeUseropDefinition.Factory(language);
- putOp(factory.define("saveCallerState")
- .params("_fcx", "_lcx", "_pcxi")
- .body(args -> """
+ @PcodeUserop
+ public SleighPcodeUseropDefinition saveCallerState(BuilderStage1 builder) {
+ return builder.params("_fcx", "_lcx", "_pcxi")
+ .body(_ -> """
local ea:4 = ((FCX & 0xffff0000) << 12) | ((FCX & 0xffff) << 6);
local new_fcx:4 = * ea;
if (new_fcx != 0) goto <skip_init>;
@@ -59,10 +58,13 @@ public class TricorePcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
PCXI = (PCXI & 0xfff00000) | ( FCX & 0x000fffff);
FCX = (FCX & 0xfff00000) | (new_fcx & 0x000fffff);
""")
- .build());
- putOp(factory.define("restoreCallerState")
- .params("_fcx", "_lcx", "_pcxi")
- .body(args -> """
+ .build();
+ }
+
+ @PcodeUserop
+ public SleighPcodeUseropDefinition restoreCallerState(BuilderStage1 builder) {
+ return builder.params("_fcx", "_lcx", "_pcxi")
+ .body(_ -> """
local ea:4 = ((PCXI & 0xffff0000) << 12) | ((PCXI & 0x0000ffff) << 6);
local savePCXI = PCXI;
PCXI = * ea;
@@ -84,7 +86,7 @@ public class TricorePcodeUseropLibraryFactory implements PcodeUseropLibraryFacto
* ea = FCX;
FCX = (FCX & 0xfff00000) | (savePCXI & 0x000fffff);
""")
- .build());
+ .build();
}
}
}
diff --git a/Ghidra/Test/DebuggerIntegrationTest/build.gradle b/Ghidra/Test/DebuggerIntegrationTest/build.gradle
index 3ab091037d..6fd01c1f4a 100644
--- a/Ghidra/Test/DebuggerIntegrationTest/build.gradle
+++ b/Ghidra/Test/DebuggerIntegrationTest/build.gradle
@@ -61,6 +61,8 @@ dependencies {
testImplementation project(path: ':Framework-TraceModeling', configuration: 'testArtifacts')
testImplementation project(path: ':Debugger', configuration: 'testArtifacts')
testImplementation project(path: ':Debugger-rmi-trace', configuration: 'testArtifacts')
+
+ testImplementation project(path: ':GhidraDocs', configuration: 'ghidraClassArtifacts')
}
// For Java 9, we must explicitly export references to the internal classes we are using.
diff --git a/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/pcode/emu/demo/ModelingScriptTest.java b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/pcode/emu/demo/ModelingScriptTest.java
new file mode 100644
index 0000000000..08a56202d1
--- /dev/null
+++ b/Ghidra/Test/DebuggerIntegrationTest/src/test/java/ghidra/pcode/emu/demo/ModelingScriptTest.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.demo;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import generic.test.AbstractGenericTest;
+import ghidra.app.plugin.assembler.Assemblers;
+import ghidra.app.plugin.assembler.AssemblyBuffer;
+import ghidra.pcode.emu.PcodeEmulator;
+import ghidra.pcode.emu.PcodeThread;
+import ghidra.pcode.emu.jit.*;
+import ghidra.pcode.exec.DecodePcodeExecutionException;
+import ghidra.pcode.exec.PcodeUseropLibrary;
+import ghidra.program.model.address.Address;
+import ghidra.program.model.lang.*;
+import ghidra.program.util.DefaultLanguageService;
+
+public class ModelingScriptTest extends AbstractGenericTest {
+ static final LanguageID LANGID_X86_64 = new LanguageID("x86:LE:64:default");
+
+ Language language;
+
+ @Before
+ public void setUp() throws Exception {
+ language = DefaultLanguageService.getLanguageService().getLanguage(LANGID_X86_64);
+ }
+
+ protected void runTestOnEmulator(PcodeEmulator emu) throws Exception {
+ Address entry = language.getDefaultSpace().getAddress(0x00400000);
+ Address addrHw = language.getDefaultDataSpace().getAddress(0x00600000);
+ AssemblyBuffer asm = new AssemblyBuffer(Assemblers.getAssembler(language), entry);
+ asm.assemble("MOV RDI, 0x%x".formatted(addrHw.getOffset()));
+ asm.assemble("MOV RSI, 100");
+ Address call = asm.getNext();
+ asm.assemble("CALL 0");
+ asm.assemble("RET");
+ Address extStrnlen = asm.getNext();
+ asm.assemble("NOP");
+ // Back patches
+ asm.assemble(call, "CALL 0x%x".formatted(extStrnlen.getOffset()));
+
+ byte[] codeBytes = asm.getBytes();
+ emu.getSharedState().setVar(entry, codeBytes.length, false, codeBytes);
+ byte[] hwBytes = "Hello, World!\n\0".getBytes();
+ emu.getSharedState().setVar(addrHw, hwBytes.length, false, hwBytes);
+
+ PcodeThread<byte[]> thread = emu.newThread();
+ thread.setCounter(entry);
+ thread.overrideContextWithDefault();
+ thread.inject(extStrnlen, """
+ __libc_strnlen();
+ RIP = __x86_64_POP();
+ return [RIP];
+ """);
+
+ try {
+ thread.run();
+ }
+ catch (DecodePcodeExecutionException e) {
+ assertEquals(0, e.getProgramCounter().getOffset());
+ }
+ Register regRAX = language.getRegister("RAX");
+ assertEquals(14,
+ thread.getState().inspectRegisterValue(regRAX).getUnsignedValue().longValueExact());
+ }
+
+ <T> PcodeUseropLibrary<T> reflect(String name) {
+ Lookup lookup = MethodHandles.lookup();
+ try {
+ return (PcodeUseropLibrary<T>) lookup
+ .findConstructor(lookup.findClass(name),
+ MethodType.methodType(void.class))
+ .invoke();
+ }
+ catch (Throwable e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ <T> PcodeUseropLibrary<T> reflect(String name, Language language) {
+ Lookup lookup = MethodHandles.lookup();
+ try {
+ return (PcodeUseropLibrary<T>) lookup
+ .findConstructor(lookup.findClass(name),
+ MethodType.methodType(void.class, Language.class))
+ .invoke(language);
+ }
+ catch (Throwable e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ <T> PcodeUseropLibrary<T> reflect(String name, CompilerSpec cSpec) {
+ Lookup lookup = MethodHandles.lookup();
+ try {
+ return (PcodeUseropLibrary<T>) lookup
+ .findConstructor(lookup.findClass(name),
+ MethodType.methodType(void.class, CompilerSpec.class))
+ .invoke(cSpec);
+ }
+ catch (Throwable e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ @Test
+ public void testViaJavaCallbacks() throws Exception {
+ runTestOnEmulator(new PcodeEmulator(language) {
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ return reflect("ModelingScript$JavaStdLibPcodeUseropLibrary", language);
+ }
+ });
+ }
+
+ @Test
+ public void testViaSleighDefs() throws Exception {
+ runTestOnEmulator(new PcodeEmulator(language) {
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ return reflect("ModelingScript$SleighStdLibPcodeUseropLibrary");
+ }
+ });
+ }
+
+ @Test
+ public void testViaStructuredSleigh() throws Exception {
+ CompilerSpec gcc = language.getCompilerSpecByID(new CompilerSpecID("gcc"));
+ runTestOnEmulator(new PcodeEmulator(language) {
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ return reflect("ModelingScript$StructuredStdLibPcodeUseropLibrary", gcc);
+ }
+ });
+ }
+
+ static class TestJitPcodeEmulator extends JitPcodeEmulator {
+
+ public TestJitPcodeEmulator(Language language) {
+ super(language, new JitConfiguration(), MethodHandles.lookup());
+ }
+
+ @Override
+ protected JitPcodeThread createThread(String name) {
+ return new JitPcodeThread(name, this) {
+ int count = 0;
+
+ @Override
+ public void count(int instructions, int trailingOps) {
+ count += instructions + trailingOps;
+ if (count > 1000000) {
+ fail("Probably an infinite loop");
+ }
+ }
+ };
+ }
+ }
+
+ @Test
+ public void testViaJavaCallbacksJit() throws Exception {
+ runTestOnEmulator(new TestJitPcodeEmulator(language) {
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ return reflect("ModelingScript$JavaStdLibPcodeUseropLibrary", language);
+ }
+ });
+ }
+
+ @Test
+ public void testViaSleighDefsJit() throws Exception {
+ runTestOnEmulator(new TestJitPcodeEmulator(language) {
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ return reflect("ModelingScript$SleighStdLibPcodeUseropLibrary");
+ }
+ });
+ }
+
+ @Test
+ public void testViaStructuredSleighJit() throws Exception {
+ CompilerSpec gcc = language.getCompilerSpecByID(new CompilerSpecID("gcc"));
+ runTestOnEmulator(new TestJitPcodeEmulator(language) {
+ @Override
+ protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
+ return reflect("ModelingScript$StructuredStdLibPcodeUseropLibrary", gcc);
+ }
+ });
+ }
+}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/AbstractPcodeEmulatorTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/AbstractPcodeEmulatorTest.java
index 898f36cd8a..62f5abf696 100644
--- a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/AbstractPcodeEmulatorTest.java
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/AbstractPcodeEmulatorTest.java
@@ -15,9 +15,9 @@
*/
package ghidra.pcode.emu;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
-import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
@@ -25,11 +25,10 @@ import org.junit.Before;
import org.junit.Test;
import generic.test.AbstractGTest;
-import ghidra.GhidraTestApplicationLayout;
+import generic.test.AbstractGenericTest;
import ghidra.app.plugin.assembler.*;
import ghidra.app.plugin.assembler.sleigh.sem.AssemblyPatternBlock;
import ghidra.framework.Application;
-import ghidra.framework.ApplicationConfiguration;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
@@ -89,9 +88,11 @@ public abstract class AbstractPcodeEmulatorTest extends AbstractGTest {
@Before
public void setUp() throws IOException {
if (!Application.isInitialized()) {
- Application.initializeApplication(
- new GhidraTestApplicationLayout(new File(getTestDirectoryPath())),
- new ApplicationConfiguration());
+ /**
+ * Don't do it directly, or else extension of AbstractGenericTest will try again and
+ * fail.
+ */
+ new AbstractGenericTest() {};
}
}
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.java
index b52c4e68b8..69aa9782d9 100644
--- 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.java
@@ -29,18 +29,18 @@ 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 {
+ protected JitConfiguration createConfiguration() {
+ return new JitConfiguration();
+ }
+
public static PcodeOp assertOp(int opcode, PcodeOp op) {
assertEquals(opcode, op.getOpcode());
return op;
@@ -55,34 +55,6 @@ public class AbstractJitTest extends AbstractGTest {
}
}
- /**
- * 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;
@@ -113,6 +85,14 @@ public class AbstractJitTest extends AbstractGTest {
return makeContext(program, thread);
}
+ public static JitAnalysisContext makeContext(PcodeProgram program,
+ JitConfiguration config) {
+ JitPcodeEmulator emu =
+ new JitPcodeEmulator(program.getLanguage(), config, 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));
@@ -126,7 +106,7 @@ public class AbstractJitTest extends AbstractGTest {
public JitPassage decodePassage(AssemblyBuffer asm) {
JitPcodeEmulator emu = new JitPcodeEmulator(asm.getAssembler().getLanguage(),
- new JitConfiguration(), MethodHandles.lookup());
+ createConfiguration(), MethodHandles.lookup());
byte[] bytes = asm.getBytes();
emu.getSharedState().setVar(asm.getEntry(), bytes.length, false, bytes);
JitPcodeThread thread = emu.newThread();
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.java
index 1b8bf9a571..c3f8f20940 100644
--- 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.java
@@ -37,6 +37,27 @@ import ghidra.pcode.exec.*;
import junit.framework.AssertionFailedError;
public class JitAllocationModelTest extends AbstractJitTest {
+
+ static class Models {
+ final JitControlFlowModel cfm;
+ final JitDataFlowModel dfm;
+ final JitReachabilityModel rm;
+ final JitVarScopeModel vsm;
+ final JitOpUseModel oum;
+ final JitTypeModel tm;
+ final JitAllocationModel am;
+
+ public Models(JitAnalysisContext context) {
+ cfm = new JitControlFlowModel(context);
+ dfm = new JitDataFlowModel(context, cfm);
+ rm = new JitReachabilityModel(context, cfm, dfm);
+ vsm = new JitVarScopeModel(cfm, dfm, rm);
+ oum = new JitOpUseModel(context, cfm, dfm, rm, vsm);
+ tm = new JitTypeModel(dfm, oum);
+ am = new JitAllocationModel(context, dfm, vsm, oum, tm);
+ }
+ }
+
public static <T> Stream<T> filterByType(Stream<?> in, Class<T> cls) {
return in.<T> mapMulti((e, d) -> {
if (cls.isInstance(e)) {
@@ -59,20 +80,16 @@ public class JitAllocationModelTest extends AbstractJitTest {
""", 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);
+ Models m = new Models(context);
- JitVarnodeVar tempVar = Unique.assertOne(varnodeVars(dfm)
+ JitVarnodeVar tempVar = Unique.assertOne(varnodeVars(m.dfm)
.filter(v -> v.varnode().isUnique()));
ClassWriter cw = new ClassWriter(0);
Emitter<?> em = Emitter.start(cw.visitMethod(0, "none", "()V", null, null));
- am.allocate(em.rootScope());
+ m.am.allocate(em.rootScope());
- if (!(am.getHandler(tempVar) instanceof AlignedMpIntHandler handler)) {
+ if (!(m.am.getHandler(tempVar) instanceof AlignedMpIntHandler handler)) {
throw new AssertionFailedError();
}
@@ -95,20 +112,16 @@ public class JitAllocationModelTest extends AbstractJitTest {
""", 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);
+ Models m = new Models(context);
- List<JitVarnodeVar> r0Vars = varnodeVars(dfm)
+ List<JitVarnodeVar> r0Vars = varnodeVars(m.dfm)
.filter(v -> v.varnode().toString(language).equals("r0"))
.sorted(Comparator.comparing(JitVar::id))
.toList();
ClassWriter cw = new ClassWriter(0);
Emitter<?> em = Emitter.start(cw.visitMethod(0, "none", "()V", null, null));
- am.allocate(em.rootScope());
+ m.am.allocate(em.rootScope());
/**
* NOTE: Variables are coalesced by varnode, so all of these will receive the same handler,
@@ -116,6 +129,6 @@ public class JitAllocationModelTest extends AbstractJitTest {
* 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());
+ r0Vars.stream().map(v -> m.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.java
index 8330c1667a..e44648ea4f 100644
--- 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.java
@@ -48,12 +48,20 @@ public class JitControlFlowModelTest extends AbstractJitTest {
}
record ExpectedBlock(List<PcodeOp> ops) {
+ static ExpectedBlock of(PcodeOp... ops) {
+ return new ExpectedBlock(List.of(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)));
}
+
+ public static ExpectedBlock whole(PcodeProgram program) {
+ return new ExpectedBlock(program.getCode());
+ }
}
enum BrType {
@@ -64,7 +72,27 @@ public class JitControlFlowModelTest extends AbstractJitTest {
BR, FT
}
- record ExpectedBranch(PcodeOp from, PcodeOp to, BrType type, BrFlow flow, long addr) {}
+ record ExpectedBranch(PcodeOp from, PcodeOp to, BrType type, BrFlow flow, long addr) {
+ static ExpectedBranch fall(PcodeOp from, PcodeOp to) {
+ return new ExpectedBranch(from, to, BrType.INT, BrFlow.FT, 0);
+ }
+
+ static ExpectedBranch intern(PcodeOp from, PcodeOp to) {
+ return new ExpectedBranch(from, to, BrType.INT, BrFlow.BR, 0);
+ }
+
+ static ExpectedBranch error(PcodeOp from) {
+ return new ExpectedBranch(from, null, BrType.ERR, BrFlow.BR, 0);
+ }
+
+ static ExpectedBranch extern(PcodeOp from, long addr) {
+ return new ExpectedBranch(from, null, BrType.EXT, BrFlow.BR, addr);
+ }
+
+ static ExpectedBranch indirect(PcodeOp from) {
+ return new ExpectedBranch(from, null, BrType.IND, BrFlow.BR, 0);
+ }
+ }
record From(PcodeOp op, BrFlow flow) {
From {
@@ -122,11 +150,14 @@ public class JitControlFlowModelTest extends AbstractJitTest {
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);
+ eBranchesFrom.computeIfAbsent(aFromBlock, _ -> new HashSet<>())
+ .add(eBranch);
+ eBranchesTo.computeIfAbsent(aToBlock, _ -> new HashSet<>())
+ .add(eBranch);
}
else {
- eBranchesOut.computeIfAbsent(aFromBlock, fb -> new HashSet<>()).add(eBranch);
+ eBranchesOut.computeIfAbsent(aFromBlock, _ -> new HashSet<>())
+ .add(eBranch);
}
}
}
@@ -170,7 +201,8 @@ public class JitControlFlowModelTest extends AbstractJitTest {
.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));
+ 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);
@@ -191,7 +223,8 @@ public class JitControlFlowModelTest extends AbstractJitTest {
assertEquals(aOpToBlock.get(aFlow.branch().to()), aFlow.to());
}
- public void assertFlowsEquivalent(Set<ExpectedBranch> eBranches, Set<BlockFlow> aFlows) {
+ 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(),
@@ -257,9 +290,9 @@ public class JitControlFlowModelTest extends AbstractJitTest {
assertCfmExpectations(
List.of(
- new ExpectedBlock(List.of(opBranch))),
+ ExpectedBlock.of(opBranch)),
Set.of(
- new ExpectedBranch(opBranch, null, BrType.EXT, BrFlow.BR, 0x1234)),
+ ExpectedBranch.extern(opBranch, 0x1234)),
cfm);
}
@@ -279,12 +312,12 @@ public class JitControlFlowModelTest extends AbstractJitTest {
assertCfmExpectations(
List.of(
- new ExpectedBlock(List.of(opCBranch)),
- new ExpectedBlock(List.of(opBranch))),
+ ExpectedBlock.of(opCBranch),
+ ExpectedBlock.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)),
+ ExpectedBranch.extern(opCBranch, 0x5678),
+ ExpectedBranch.fall(opCBranch, opBranch),
+ ExpectedBranch.extern(opBranch, 0x1234)),
cfm);
}
@@ -303,9 +336,9 @@ public class JitControlFlowModelTest extends AbstractJitTest {
assertCfmExpectations(
List.of(
- new ExpectedBlock(List.of(opBranch))),
+ ExpectedBlock.of(opBranch)),
Set.of(
- new ExpectedBranch(opBranch, opBranch, BrType.INT, BrFlow.BR, 0)),
+ ExpectedBranch.intern(opBranch, opBranch)),
cfm);
}
@@ -326,12 +359,12 @@ public class JitControlFlowModelTest extends AbstractJitTest {
assertCfmExpectations(
List.of(
- new ExpectedBlock(List.of(opCBranch)),
- new ExpectedBlock(List.of(opBranch))),
+ ExpectedBlock.of(opCBranch),
+ ExpectedBlock.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)),
+ ExpectedBranch.intern(opCBranch, opCBranch),
+ ExpectedBranch.fall(opCBranch, opBranch),
+ ExpectedBranch.extern(opBranch, 0x1234)),
cfm);
}
@@ -352,12 +385,12 @@ public class JitControlFlowModelTest extends AbstractJitTest {
assertCfmExpectations(
List.of(
- new ExpectedBlock(List.of(opCBranch)),
- new ExpectedBlock(List.of(opBranch))),
+ ExpectedBlock.of(opCBranch),
+ ExpectedBlock.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)),
+ ExpectedBranch.intern(opCBranch, opBranch),
+ ExpectedBranch.fall(opCBranch, opBranch),
+ ExpectedBranch.extern(opBranch, 0x1234)),
cfm);
}
@@ -390,10 +423,10 @@ public class JitControlFlowModelTest extends AbstractJitTest {
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)),
+ ExpectedBranch.fall(opCBranch, opAfterCBranch),
+ ExpectedBranch.intern(opCBranch, opAtL1),
+ ExpectedBranch.fall(opBeforeL1, opAtL1),
+ ExpectedBranch.extern(opBranch, 0x1234)),
cfm);
}
@@ -415,9 +448,49 @@ public class JitControlFlowModelTest extends AbstractJitTest {
assertCfmExpectations(
List.of(
- new ExpectedBlock(passage.getCode())),
+ ExpectedBlock.whole(passage)),
Set.of(
- new ExpectedBranch(opLast, null, BrType.ERR, BrFlow.BR, 0x4)),
+ ExpectedBranch.error(opLast)),
+ cfm);
+ }
+
+ @Test
+ public void testConstBranchInd() 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, #6");
+ buf.assemble("br r0");
+ buf.assemble("imm r0, #8");
+ JitPassage passage = decodePassage(buf);
+ // This listing already has evidence of the BRANCHIND resolution to ram:6
+ assertEquals("""
+ <JitPassage:
+ 0,00000000.0: C = COPY 0:1
+ 1,00000000.1: V = COPY 0:1
+ 2,00000000.2: r0 = COPY 6:8
+ 3,00000000.3: N = INT_SLESS r0, 0:8
+ 4,00000000.4: Z = INT_EQUAL r0, 0:8
+ 5,00000002.0: BRANCHIND r0
+ 6,00000006.0: UNIMPLEMENTED
+ >""", passage.format(true));
+ PcodeOp opFirst = passage.getCode().getFirst();
+ PcodeOp opBranchInd = assertOp(PcodeOp.BRANCHIND, passage.getCode().get(5));
+ PcodeOp opLast = assertOp(PcodeOp.UNIMPLEMENTED, passage.getCode().getLast());
+
+ JitAnalysisContext context = makeContext(passage);
+ JitControlFlowModel cfm = new JitControlFlowModel(context);
+
+ assertCfmExpectations(
+ List.of(
+ ExpectedBlock.sub(passage, opFirst, opBranchInd),
+ ExpectedBlock.of(opLast)),
+ Set.of(
+ ExpectedBranch.intern(opBranchInd, opLast),
+ ExpectedBranch.error(opLast)),
cfm);
}
@@ -472,11 +545,49 @@ public class JitControlFlowModelTest extends AbstractJitTest {
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)),
+ ExpectedBranch.intern(opCBranch, opStartImm),
+ ExpectedBranch.fall(opCBranch, opBranch),
+ ExpectedBranch.intern(opBranch, opStartAdd),
+ ExpectedBranch.fall(opEndImm, opStartAdd),
+ ExpectedBranch.error(opLast)),
cfm);
}
+
+ @Test
+ public void testConstantFoldedInLoopBody() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+ BytesPcodeArithmetic bytes = BytesPcodeArithmetic.forLanguage(language);
+
+ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """
+ r0 = 0x600d;
+ <L1>
+ *:8 r0 = 0xbeef;
+ goto <L1>;
+ """, PcodeUseropLibrary.NIL);
+ JitAnalysisContext context = makeContext(program);
+ JitPassage passage = context.getPassage();
+
+ // Eh, this isn't really a control-flow test....
+ PcodeOp opStore = assertOp(PcodeOp.STORE, passage.getCode().get(1));
+ assertArrayEquals(bytes.fromConst(0x600d, 8), passage.getFoldedOperand(opStore, 1));
+ }
+
+ @Test
+ public void testCounterNotFoldedInLoopBody() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+
+ PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """
+ r0 = 0x600d;
+ <L1>
+ *:8 r0 = 0xbeef;
+ r0 = r0 + 1;
+ goto <L1>;
+ """, PcodeUseropLibrary.NIL);
+ JitAnalysisContext context = makeContext(program);
+ JitPassage passage = context.getPassage();
+
+ // Eh, this isn't really a control-flow test....
+ PcodeOp opStore = assertOp(PcodeOp.STORE, passage.getCode().get(1));
+ assertNull(passage.getFoldedOperand(opStore, 1));
+ }
}
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.java
index 583fb544af..65b88a8de1 100644
--- 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.java
@@ -30,6 +30,7 @@ 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.JitConfiguration.Opt;
import ghidra.pcode.emu.jit.analysis.JitControlFlowModel.BlockFlow;
import ghidra.pcode.emu.jit.op.*;
import ghidra.pcode.emu.jit.var.*;
@@ -167,8 +168,8 @@ public class JitDataFlowModelTest extends AbstractJitTest {
}
for (ExpectedEdge<?, ?> ee : eEdges) {
- edgesO2V.computeIfAbsent(ee.op, e -> new HashSet<>()).add(ee);
- edgesV2O.computeIfAbsent(ee.v, e -> new HashSet<>()).add(ee);
+ edgesO2V.computeIfAbsent(ee.op, _ -> new HashSet<>()).add(ee);
+ edgesV2O.computeIfAbsent(ee.v, _ -> new HashSet<>()).add(ee);
}
}
@@ -263,7 +264,7 @@ public class JitDataFlowModelTest extends AbstractJitTest {
public void assertEquivalence() {
processQueues();
- assertEquals(opsMap.keySet(), dfm.allOps());
+ assertEquals(opsMap.keySet(), dfm.allOps().collect(Collectors.toSet()));
assertEquals(valsMap.keySet(), dfm.allValues());
assertEquals("Not all expected ops were found.", Set.copyOf(eOps),
@@ -303,7 +304,7 @@ public class JitDataFlowModelTest extends AbstractJitTest {
eBranch),
Set.of(e5678, eR0),
Set.of(
- ExpectedEdge.in(eCopy, JitCopyOp::u, op -> true, e5678),
+ ExpectedEdge.in(eCopy, JitCopyOp::u, _ -> true, e5678),
ExpectedEdge.out(eR0, eCopy)),
context, dfm);
}
@@ -333,9 +334,9 @@ public class JitDataFlowModelTest extends AbstractJitTest {
ePhi),
Set.of(eR1In, eR1, eR0),
Set.of(
- ExpectedEdge.phi(ePhi, flow -> true, eR1In),
+ ExpectedEdge.phi(ePhi, _ -> true, eR1In),
ExpectedEdge.out(eR1, ePhi),
- ExpectedEdge.in(eCopy, JitCopyOp::u, op -> true, eR1),
+ ExpectedEdge.in(eCopy, JitCopyOp::u, _ -> true, eR1),
ExpectedEdge.out(eR0, eCopy)),
context, dfm);
}
@@ -349,7 +350,8 @@ public class JitDataFlowModelTest extends AbstractJitTest {
r0 = r1;
goto 0x1234;
""", PcodeUseropLibrary.NIL);
- JitAnalysisContext context = makeContext(program);
+ JitAnalysisContext context = makeContext(program, createConfiguration()
+ .disable(Opt.FOLD_CONSTANTS));
JitControlFlowModel cfm = new JitControlFlowModel(context);
JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
@@ -366,9 +368,9 @@ public class JitDataFlowModelTest extends AbstractJitTest {
eBranch),
Set.of(e5678, eR1, eR0),
Set.of(
- ExpectedEdge.in(eCopy1, JitCopyOp::u, op -> true, e5678),
+ ExpectedEdge.in(eCopy1, JitCopyOp::u, _ -> true, e5678),
ExpectedEdge.out(eR1, eCopy1),
- ExpectedEdge.in(eCopy2, JitCopyOp::u, op -> true, eR1),
+ ExpectedEdge.in(eCopy2, JitCopyOp::u, _ -> true, eR1),
ExpectedEdge.out(eR0, eCopy2)),
context, dfm);
}
@@ -382,7 +384,8 @@ public class JitDataFlowModelTest extends AbstractJitTest {
r0 = temp;
goto 0x1234;
""", PcodeUseropLibrary.NIL);
- JitAnalysisContext context = makeContext(program);
+ JitAnalysisContext context = makeContext(program, createConfiguration()
+ .disable(Opt.FOLD_CONSTANTS));
JitControlFlowModel cfm = new JitControlFlowModel(context);
JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
@@ -393,14 +396,15 @@ public class JitDataFlowModelTest extends AbstractJitTest {
ExpectedVal<JitOutVar> eTemp = new ExpectedVal<>(JitOutVar.class, "$U", 8);
ExpectedVal<JitOutVar> eR0 = new ExpectedVal<>(JitOutVar.class, "r0", 8);
assertDfmExpectations(
- List.of(eCopy1,
+ List.of(
+ eCopy1,
eCopy2,
eBranch),
Set.of(e5678, eTemp, eR0),
Set.of(
- ExpectedEdge.in(eCopy1, JitCopyOp::u, op -> true, e5678),
+ ExpectedEdge.in(eCopy1, JitCopyOp::u, _ -> true, e5678),
ExpectedEdge.out(eTemp, eCopy1),
- ExpectedEdge.in(eCopy2, JitCopyOp::u, op -> true, eTemp),
+ ExpectedEdge.in(eCopy2, JitCopyOp::u, _ -> true, eTemp),
ExpectedEdge.out(eR0, eCopy2)),
context, dfm);
}
@@ -449,7 +453,8 @@ public class JitDataFlowModelTest extends AbstractJitTest {
r0 = r1;
goto <loop>;
""", PcodeUseropLibrary.NIL);
- JitAnalysisContext context = makeContext(program);
+ JitAnalysisContext context = makeContext(program, createConfiguration()
+ .disable(Opt.FOLD_CONSTANTS));
JitControlFlowModel cfm = new JitControlFlowModel(context);
JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
@@ -545,6 +550,13 @@ public class JitDataFlowModelTest extends AbstractJitTest {
public long l_op1(long p1) {
return p1;
}
+
+ /**
+ * A userop that could have machine-state side effects
+ */
+ @PcodeUserop
+ public void opaque() {
+ }
}
public static final PcodeUseropLibrary<?> MY_LIB = new MyLibrary();
@@ -592,7 +604,7 @@ public class JitDataFlowModelTest extends AbstractJitTest {
ePhi),
Set.of(eR0In, eR0),
Set.of(
- ExpectedEdge.phi(ePhi, flow -> true, eR0In),
+ ExpectedEdge.phi(ePhi, _ -> true, eR0In),
ExpectedEdge.out(eR0, ePhi),
ExpectedEdge.in(eCallOther, otherArg(0), opType(JitCallOtherOp.class), eR0)),
context, dfm);
@@ -644,15 +656,102 @@ public class JitDataFlowModelTest extends AbstractJitTest {
ePhi),
Set.of(eR0In, eR0, eR1),
Set.of(
- ExpectedEdge.phi(ePhi, flow -> true, eR0In),
+ ExpectedEdge.phi(ePhi, _ -> true, eR0In),
ExpectedEdge.out(eR0, ePhi),
ExpectedEdge.in(eCallOther, otherArg(0), opType(JitCallOtherDefOp.class), eR0),
ExpectedEdge.out(eR1, eCallOther)),
context, dfm);
}
+ @Test
+ public void testConstantFoldingRewriteConstInput() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+
+ JitAnalysisContext context = makeContext(language, """
+ r1 = 0x10;
+ r0 = r0 + r1;
+ goto 0x1234;
+ """, MY_LIB);
+ JitControlFlowModel cfm = new JitControlFlowModel(context);
+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
+
+ ExpectedOp<JitCopyOp> eCopy = new ExpectedOp<>(JitCopyOp.class);
+ ExpectedOp<JitIntAddOp> eAdd = new ExpectedOp<>(JitIntAddOp.class);
+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);
+ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);
+ ExpectedVal<JitConstVal> e10_1 = new ExpectedVal<>(JitConstVal.class, "10", 8);
+ // Not great, but each getVar(const) has its own instance
+ ExpectedVal<JitConstVal> e10_2 = new ExpectedVal<>(JitConstVal.class, "10", 8);
+ ExpectedVal<JitOutVar> eR1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);
+ ExpectedVal<JitInputVar> eR0In = new ExpectedVal<>(JitInputVar.class, "r0", 8);
+ ExpectedVal<JitOutVar> eR0_1 = new ExpectedVal<>(JitOutVar.class, "r0", 8);
+ ExpectedVal<JitOutVar> eR0_2 = new ExpectedVal<>(JitOutVar.class, "r0", 8);
+ assertDfmExpectations(
+ List.of(
+ eCopy,
+ eAdd,
+ eBranch,
+ ePhi),
+ Set.of(e10_1, e10_2, eR1, eR0In, eR0_1, eR0_2),
+ Set.of(
+ ExpectedEdge.in(eCopy, JitCopyOp::u, opType(JitCopyOp.class), e10_1),
+ ExpectedEdge.out(eR1, eCopy),
+ ExpectedEdge.phi(ePhi, flow -> flow.from() == null, eR0In),
+ ExpectedEdge.out(eR0_1, ePhi),
+ ExpectedEdge.in(eAdd, JitIntAddOp::l, opType(JitIntAddOp.class), eR0_1),
+ ExpectedEdge.in(eAdd, JitIntAddOp::r, opType(JitIntAddOp.class), e10_2), // <--
+ ExpectedEdge.out(eR0_2, eAdd)),
+ context, dfm);
+ }
+
+ @Test
+ public void testConstantFoldingDontRewriteConstInputInterveningCallOther() throws Exception {
+ /**
+ * A non-functional userop could technically do whatever to the state, so nothing can be
+ * assumed constant after such a userop.
+ */
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+
+ JitAnalysisContext context = makeContext(language, """
+ r1 = 0x10;
+ opaque();
+ r0 = r0 + r1;
+ goto 0x1234;
+ """, MY_LIB);
+ JitControlFlowModel cfm = new JitControlFlowModel(context);
+ JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
+
+ ExpectedOp<JitCopyOp> eCopy = new ExpectedOp<>(JitCopyOp.class);
+ ExpectedOp<JitCallOtherOp> eCallOther = new ExpectedOp<>(JitCallOtherOp.class);
+ ExpectedOp<JitIntAddOp> eAdd = new ExpectedOp<>(JitIntAddOp.class);
+ ExpectedOp<JitBranchOp> eBranch = new ExpectedOp<>(JitBranchOp.class);
+ ExpectedOp<JitPhiOp> ePhi = new ExpectedOp<>(JitPhiOp.class);
+ ExpectedVal<JitConstVal> e10_1 = new ExpectedVal<>(JitConstVal.class, "10", 8);
+ ExpectedVal<JitOutVar> eR1 = new ExpectedVal<>(JitOutVar.class, "r1", 8);
+ ExpectedVal<JitInputVar> eR0In = new ExpectedVal<>(JitInputVar.class, "r0", 8);
+ ExpectedVal<JitOutVar> eR0_1 = new ExpectedVal<>(JitOutVar.class, "r0", 8);
+ ExpectedVal<JitOutVar> eR0_2 = new ExpectedVal<>(JitOutVar.class, "r0", 8);
+ assertDfmExpectations(
+ List.of(
+ eCopy,
+ eCallOther,
+ eAdd,
+ eBranch,
+ ePhi),
+ Set.of(e10_1, eR1, eR0In, eR0_1, eR0_2),
+ Set.of(
+ ExpectedEdge.in(eCopy, JitCopyOp::u, opType(JitCopyOp.class), e10_1),
+ ExpectedEdge.out(eR1, eCopy),
+ ExpectedEdge.phi(ePhi, flow -> flow.from() == null, eR0In),
+ ExpectedEdge.out(eR0_1, ePhi),
+ ExpectedEdge.in(eAdd, JitIntAddOp::l, opType(JitIntAddOp.class), eR0_1),
+ ExpectedEdge.in(eAdd, JitIntAddOp::r, opType(JitIntAddOp.class), eR1), // <--
+ ExpectedEdge.out(eR0_2, eAdd)),
+ context, dfm);
+ }
+
/**
- * NOTE: cat, subpiece, etc., do not currrently have much meaning except to indicate a
+ * NOTE: cat, subpiece, etc., do not currently 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.java
index 06d66a9167..6425267534 100644
--- 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.java
@@ -15,14 +15,18 @@
*/
package ghidra.pcode.emu.jit.analysis;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import org.hamcrest.Matchers;
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.op.JitCopyOp;
+import ghidra.pcode.emu.jit.op.JitOp;
import ghidra.pcode.exec.AnnotatedPcodeUseropLibrary;
import ghidra.pcode.exec.PcodeExecutorState;
import ghidra.program.model.pcode.PcodeOp;
@@ -30,6 +34,22 @@ import ghidra.program.model.pcode.Varnode;
public class JitOpUseModelTest extends AbstractJitTest {
+ static class Models {
+ final JitControlFlowModel cfm;
+ final JitDataFlowModel dfm;
+ final JitReachabilityModel rm;
+ final JitVarScopeModel vsm;
+ final JitOpUseModel oum;
+
+ public Models(JitAnalysisContext context) {
+ this.cfm = new JitControlFlowModel(context);
+ this.dfm = new JitDataFlowModel(context, cfm);
+ this.rm = new JitReachabilityModel(context, cfm, dfm);
+ this.vsm = new JitVarScopeModel(cfm, dfm, rm);
+ this.oum = new JitOpUseModel(context, cfm, dfm, rm, vsm);
+ }
+ }
+
public static class MyLib extends AnnotatedPcodeUseropLibrary<byte[]> {
@PcodeUserop
public void pcodeop_one(@OpState PcodeExecutorState<byte[]> state, @OpOutput Varnode out,
@@ -48,13 +68,13 @@ public class JitOpUseModelTest extends AbstractJitTest {
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);
+ Models m = new Models(context);
- PcodeOp copyOp = assertOp(PcodeOp.COPY, context.getPassage().getCode().getFirst());
- assertFalse(oum.isUsed(dfm.getJitOp(copyOp)));
+ PcodeOp copyOpR1 = assertOp(PcodeOp.COPY, context.getPassage().getCode().getFirst());
+ assertFalse(m.oum.isUsed(m.dfm.getJitOp(copyOpR1)));
+
+ PcodeOp copyOpR2 = assertOp(PcodeOp.COPY, context.getPassage().getCode().get(1));
+ assertTrue(m.oum.isUsed(m.dfm.getJitOp(copyOpR2)));
}
/**
@@ -72,12 +92,34 @@ public class JitOpUseModelTest extends AbstractJitTest {
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);
+ Models m = new Models(context);
+
+ PcodeOp copyOp = assertOp(PcodeOp.COPY, context.getPassage().getCode().getFirst());
+ assertTrue(m.oum.isUsed(m.dfm.getJitOp(copyOp)));
+
+ PcodeOp callotherOp = assertOp(PcodeOp.CALLOTHER, context.getPassage().getCode().get(1));
+ assertTrue(m.oum.isUsed(m.dfm.getJitOp(callotherOp)));
+ }
+
+ @Test
+ public void testConstantFoldingRewriteCopyConst() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+
+ JitAnalysisContext context = makeContext(language, """
+ r0 = 0x10;
+ r0 = r0 + r0;
+ goto 0x1234;
+ """, lib);
+ Models m = new Models(context);
PcodeOp copyOp = assertOp(PcodeOp.COPY, context.getPassage().getCode().getFirst());
- assertTrue(oum.isUsed(dfm.getJitOp(copyOp)));
+ JitOp jitCopyOp = m.dfm.getJitOp(copyOp);
+ assertThat(jitCopyOp, Matchers.instanceOf(JitCopyOp.class));
+ assertFalse(m.oum.isUsed(jitCopyOp));
+
+ PcodeOp addOp = assertOp(PcodeOp.INT_ADD, context.getPassage().getCode().get(1));
+ JitOp jitAddOp = m.dfm.getJitOp(addOp);
+ assertThat(jitAddOp, Matchers.instanceOf(JitCopyOp.class)); // re-written
+ assertTrue(m.oum.isUsed(jitAddOp));
}
}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitReachabilityModelTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitReachabilityModelTest.java
new file mode 100644
index 0000000000..a08d8b34be
--- /dev/null
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/analysis/JitReachabilityModelTest.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.analysis;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+
+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.exec.PcodeUseropLibrary;
+import ghidra.program.model.pcode.PcodeOp;
+
+public class JitReachabilityModelTest extends AbstractJitTest {
+
+ static class Models {
+ final JitControlFlowModel cfm;
+ final JitDataFlowModel dfm;
+ final JitReachabilityModel rm;
+
+ public Models(JitAnalysisContext context) {
+ this.cfm = new JitControlFlowModel(context);
+ this.dfm = new JitDataFlowModel(context, cfm);
+ dfm.dumpResult();
+ this.rm = new JitReachabilityModel(context, cfm, dfm);
+ rm.dumpResult();
+ }
+ }
+
+ @Test
+ public void testSingleBlock() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+
+ JitAnalysisContext context = makeContext(language, """
+ goto 0x1234;
+ """, PcodeUseropLibrary.nil());
+ Models m = new Models(context);
+
+ JitBlock block = Unique.assertOne(m.cfm.getBlocks());
+ assertTrue(m.rm.isReachable(block));
+ }
+
+ @Test
+ public void testCBranchNever() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+
+ JitAnalysisContext context = makeContext(language, """
+ if 0:1 goto <L1>;
+ r0 = 1;
+ <L1>
+ goto 0x1234;
+ """, PcodeUseropLibrary.nil());
+ Models m = new Models(context);
+
+ List<JitBlock> blocks = List.copyOf(m.cfm.getBlocks());
+ assertOp(PcodeOp.CBRANCH, blocks.get(0).first());
+ assertOp(PcodeOp.COPY, blocks.get(1).first());
+ assertOp(PcodeOp.BRANCH, blocks.get(2).first());
+
+ assertTrue(m.rm.isReachable(blocks.get(0)));
+ assertTrue(m.rm.isReachable(blocks.get(1)));
+ assertTrue(m.rm.isReachable(blocks.get(2)));
+
+ assertTrue(m.rm.isTakeable(blocks.get(0).getFallFrom()));
+ assertFalse(m.rm.isTakeable(blocks.get(0)
+ .flowsFrom()
+ .values()
+ .stream()
+ .filter(f -> !f.branch().isFall())
+ .findAny()
+ .orElseThrow()));
+ assertTrue(m.rm.isTakeable(blocks.get(1).getFallFrom()));
+ }
+
+ @Test
+ public void testCBranchAlways() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+
+ JitAnalysisContext context = makeContext(language, """
+ if 1:1 goto <L1>;
+ r0 = 1;
+ <L1>
+ goto 0x1234;
+ """, PcodeUseropLibrary.nil());
+ Models m = new Models(context);
+
+ List<JitBlock> blocks = List.copyOf(m.cfm.getBlocks());
+ assertOp(PcodeOp.CBRANCH, blocks.get(0).first());
+ assertOp(PcodeOp.COPY, blocks.get(1).first());
+ assertOp(PcodeOp.BRANCH, blocks.get(2).first());
+
+ assertTrue(m.rm.isReachable(blocks.get(0)));
+ assertFalse(m.rm.isReachable(blocks.get(1)));
+ assertTrue(m.rm.isReachable(blocks.get(2)));
+
+ assertFalse(m.rm.isTakeable(blocks.get(0).getFallFrom()));
+ assertTrue(m.rm.isTakeable(blocks.get(0)
+ .flowsFrom()
+ .values()
+ .stream()
+ .filter(f -> !f.branch().isFall())
+ .findAny()
+ .orElseThrow()));
+ assertFalse(m.rm.isTakeable(blocks.get(1).getFallFrom()));
+ }
+}
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.java
index 40b0d7ddbf..888bef1b7c 100644
--- 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.java
@@ -33,6 +33,25 @@ import ghidra.pcode.exec.*;
import ghidra.program.model.pcode.PcodeOp;
public class JitTypeModelTest extends AbstractJitTest {
+ static class Models {
+ final JitControlFlowModel cfm;
+ final JitDataFlowModel dfm;
+ final JitReachabilityModel rm;
+ final JitVarScopeModel vsm;
+ final JitOpUseModel oum;
+ final JitTypeModel tm;
+
+ public Models(JitAnalysisContext context) {
+ cfm = new JitControlFlowModel(context);
+ dfm = new JitDataFlowModel(context, cfm);
+ rm = new JitReachabilityModel(context, cfm, dfm);
+ vsm = new JitVarScopeModel(cfm, dfm, rm);
+ oum = new JitOpUseModel(context, cfm, dfm, rm, vsm);
+ oum.dumpResult();
+ tm = new JitTypeModel(dfm, oum);
+ }
+ }
+
@Test
public void testDefault() throws Exception {
SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
@@ -43,13 +62,11 @@ public class JitTypeModelTest extends AbstractJitTest {
""", PcodeUseropLibrary.NIL);
JitAnalysisContext context = makeContext(program);
- JitControlFlowModel cfm = new JitControlFlowModel(context);
- JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
- JitTypeModel tm = new JitTypeModel(dfm);
+ Models m = new Models(context);
- JitBlock block = Unique.assertOne(cfm.getBlocks());
- JitVal r0 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r0")));
- assertEquals(LongJitType.I8, tm.typeOf(r0));
+ JitBlock block = Unique.assertOne(m.cfm.getBlocks());
+ JitVal r0 = Unique.assertOne(m.dfm.getOutput(block, language.getRegister("r0")));
+ assertEquals(LongJitType.I8, m.tm.typeOf(r0));
}
@Test
@@ -63,13 +80,11 @@ public class JitTypeModelTest extends AbstractJitTest {
""", PcodeUseropLibrary.NIL);
JitAnalysisContext context = makeContext(program);
- JitControlFlowModel cfm = new JitControlFlowModel(context);
- JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
- JitTypeModel tm = new JitTypeModel(dfm);
+ Models m = new Models(context);
- JitBlock block = Unique.assertOne(cfm.getBlocks());
- JitVal r0 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r0")));
- assertEquals(DoubleJitType.F8, tm.typeOf(r0));
+ JitBlock block = Unique.assertOne(m.cfm.getBlocks());
+ JitVal r0 = Unique.assertOne(m.dfm.getOutput(block, language.getRegister("r0")));
+ assertEquals(DoubleJitType.F8, m.tm.typeOf(r0));
}
@Test
@@ -82,14 +97,12 @@ public class JitTypeModelTest extends AbstractJitTest {
""", PcodeUseropLibrary.NIL);
JitAnalysisContext context = makeContext(program);
- JitControlFlowModel cfm = new JitControlFlowModel(context);
- JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
- JitTypeModel tm = new JitTypeModel(dfm);
+ Models m = new Models(context);
PcodeOp op = assertOp(PcodeOp.FLOAT_ADD, context.getPassage().getCode().getFirst());
- JitFloatAddOp fAddOp = (JitFloatAddOp) dfm.getJitOp(op);
+ JitFloatAddOp fAddOp = (JitFloatAddOp) m.dfm.getJitOp(op);
JitConstVal c1234 = (JitConstVal) fAddOp.r();
- assertEquals(DoubleJitType.F8, tm.typeOf(c1234));
+ assertEquals(DoubleJitType.F8, m.tm.typeOf(c1234));
}
@Test
@@ -103,14 +116,12 @@ public class JitTypeModelTest extends AbstractJitTest {
""", PcodeUseropLibrary.NIL);
JitAnalysisContext context = makeContext(program);
- JitControlFlowModel cfm = new JitControlFlowModel(context);
- JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
- JitTypeModel tm = new JitTypeModel(dfm);
+ Models m = new Models(context);
PcodeOp op = assertOp(PcodeOp.CBRANCH, context.getPassage().getCode().getFirst());
- JitCBranchOp cbranch = (JitCBranchOp) dfm.getJitOp(op);
+ JitCBranchOp cbranch = (JitCBranchOp) m.dfm.getJitOp(op);
JitVal r0 = cbranch.cond();
- assertEquals(LongJitType.I8, tm.typeOf(r0));
+ assertEquals(LongJitType.I8, m.tm.typeOf(r0));
}
@Test
@@ -122,34 +133,36 @@ public class JitTypeModelTest extends AbstractJitTest {
""", PcodeUseropLibrary.NIL);
JitAnalysisContext context = makeContext(program);
- JitControlFlowModel cfm = new JitControlFlowModel(context);
- JitDataFlowModel dfm = new JitDataFlowModel(context, cfm);
- JitTypeModel tm = new JitTypeModel(dfm);
+ Models m = new Models(context);
PcodeOp op = Unique.assertOne(context.getPassage().getCode());
- JitBranchIndOp branchind = (JitBranchIndOp) dfm.getJitOp(op);
+ JitBranchIndOp branchind = (JitBranchIndOp) m.dfm.getJitOp(op);
JitVal r0 = branchind.target();
- assertEquals(LongJitType.I8, tm.typeOf(r0));
+ assertEquals(LongJitType.I8, m.tm.typeOf(r0));
}
@Test
public void testLoop() throws Exception {
SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+ /**
+ * Use conditional branch here otherwise, r0 appears unused and receives no type assignment.
+ *
+ * The condition cannot be r0, because it wants to assign INTEGER.
+ */
PcodeProgram program = SleighProgramCompiler.compileProgram(language, "test", """
<loop>
r0 = r0 f+ r1;
- goto <loop>;
+ if r1 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);
+ Models m = new Models(context);
- JitBlock block = Unique.assertOne(cfm.getBlocks());
- JitVal r0 = Unique.assertOne(dfm.getOutput(block, language.getRegister("r0")));
- assertEquals(DoubleJitType.F8, tm.typeOf(r0));
+ JitBlock block = m.cfm.getBlocks().iterator().next();
+ JitVal r0 = Unique.assertOne(m.dfm.getOutput(block, language.getRegister("r0")));
+ assertEquals(DoubleJitType.F8, m.tm.typeOf(r0));
}
@Test
@@ -163,14 +176,12 @@ public class JitTypeModelTest extends AbstractJitTest {
""", 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));
+ Models m = new Models(context);
+
+ JitBlock block = Unique.assertOne(m.cfm.getBlocks());
+ JitVal r0 = Unique.assertOne(m.dfm.getOutput(block, language.getRegister("r0")));
+ assertEquals(DoubleJitType.F8, m.tm.typeOf(r0));
+ JitVal r2 = Unique.assertOne(m.dfm.getOutput(block, language.getRegister("r2")));
+ assertEquals(DoubleJitType.F8, m.tm.typeOf(r2));
}
}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/decode/JitPassageDecoderTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/decode/JitPassageDecoderTest.java
new file mode 100644
index 0000000000..e3cf50ccd6
--- /dev/null
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/decode/JitPassageDecoderTest.java
@@ -0,0 +1,81 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.pcode.emu.jit.decode;
+
+import static org.junit.Assert.assertNull;
+
+import java.util.Map.Entry;
+
+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.JitPassage.Operand;
+import ghidra.pcode.emu.jit.analysis.JitAnalysisContext;
+import ghidra.pcode.emu.jit.op.JitOp;
+import ghidra.pcode.exec.PcodeUseropLibrary;
+import ghidra.pcode.utils.Utils;
+import ghidra.program.model.pcode.PcodeOp;
+
+public class JitPassageDecoderTest extends AbstractJitTest {
+ void dumpFolded(JitAnalysisContext context) {
+ SleighLanguage language = context.getLanguage();
+ for (Entry<Operand, byte[]> ent : context.getPassage().allFoldedOperands().entrySet()) {
+ byte[] v = ent.getValue();
+ Operand k = ent.getKey();
+ System.err.println("%s %s=0x%s".formatted(k.op().getSeqnum(), k,
+ Utils.bytesToBigInteger(v, v.length, language.isBigEndian(), false).toString(16)));
+ }
+ }
+
+ @Test
+ public void testRevalidationSimpleCBranch() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+ JitAnalysisContext context = makeContext(language, """
+ local base:8 = 0x6000;
+ local off:8 = 0;
+ <loop>
+ local addr:8 = base + off;
+ off = off + 1;
+ if off < 0x100 goto <loop>;
+ """, PcodeUseropLibrary.nil());
+
+ PcodeOp addOp = assertOp(PcodeOp.INT_ADD, context.getPassage().getCode().get(2));
+ byte[] constAddr = context.getPassage().getFoldedOperand(addOp, -1);
+ assertNull(constAddr);
+ }
+
+ @Test
+ public void testRevalidationCBranchOverBranch() throws Exception {
+ SleighLanguage language = SleighLanguageHelper.getMockBE64Language();
+ JitAnalysisContext context = makeContext(language, """
+ local base:8 = 0x6000;
+ local off:8 = 0;
+ <loop>
+ local addr:8 = base + off;
+ off = off + 1;
+ if off > 0x100 goto <exit>;
+ goto <loop>;
+ <exit>
+ """, PcodeUseropLibrary.nil());
+
+ PcodeOp addOp = assertOp(PcodeOp.INT_ADD, context.getPassage().getCode().get(2));
+ JitOp.toString(addOp, PcodeUseropLibrary.nil().getSymbols(language));
+ byte[] constAddr = context.getPassage().getFoldedOperand(addOp, -1);
+ assertNull(constAddr);
+ }
+}
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.java
index 46ff0a72fc..1d7718b43c 100644
--- 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.java
@@ -18,21 +18,28 @@ 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.emu.jit.folding.FoldedState;
import ghidra.pcode.exec.PcodeProgram;
public class JitPassageDecoderTestAccess {
public static JitPassage simulateFromPcode(PcodeProgram program, JitPcodeThread thread) {
+ boolean foldConstants = thread.getMachine().getConfiguration().foldConstants();
+
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()));
+ FoldedState state = foldConstants ? new FoldedState(program.getLanguage()) : null;
+ DecoderForOneStride d4stride =
+ new DecoderForOneStride(decoder, d4passage, AddrCtx.NOWHERE, state);
+ DecoderExecutor exec = new DecoderExecutor(d4stride, AddrCtx.NOWHERE, state);
+ program = new PcodeProgram(program, exec.rewriteOps(program.getCode()));
+ d4passage.firstOps.put(AddrCtx.NOWHERE, program.getCode().getFirst());
exec.execute(program);
exec.checkFallthroughAndAccumulate(program);
d4passage.strides.add(d4stride.toStride());
+ d4passage.revalidateFolded();
return d4passage.finish();
}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractJitCodeGeneratorTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractJitCodeGeneratorTest.java
index 309ea2a6b4..8a17d3dd7a 100644
--- a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractJitCodeGeneratorTest.java
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractJitCodeGeneratorTest.java
@@ -18,14 +18,19 @@ package ghidra.pcode.emu.jit.gen;
import static org.junit.Assert.*;
import java.io.*;
+import java.lang.classfile.*;
+import java.lang.classfile.instruction.*;
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.function.Predicate;
import java.util.stream.Collectors;
-import org.objectweb.asm.*;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.TraceClassVisitor;
@@ -67,7 +72,7 @@ public abstract class AbstractJitCodeGeneratorTest extends AbstractJitTest {
if (!DEBUG_ENABLED) {
return;
}
- Msg.debug(AbstractJitCodeGeneratorTest.class, program);
+ Msg.debug(AbstractJitCodeGeneratorTest.class, program.format(true));
}
public static void dumpClass(byte[] classbytes) throws Exception {
@@ -82,7 +87,7 @@ public abstract class AbstractJitCodeGeneratorTest extends AbstractJitTest {
}
record Translation(PcodeProgram program, MethodNode init, MethodNode run, JitPcodeThread thread,
- TestUseropLibrary library, JitBytesPcodeExecutorState state,
+ TestUseropLibrary library, JitBytesPcodeExecutorState state, byte[] classbytes,
JitCompiledPassageClass passageCls, JitCompiledPassage passage) {
public void runErr(Class<? extends Throwable> excType, String message) {
@@ -172,6 +177,36 @@ public abstract class AbstractJitCodeGeneratorTest extends AbstractJitTest {
int blockId) {
return Map.entry(new AddrCtx(ctx, addr), new EntryPointPrototype(passageCls, blockId));
}
+
+ public PcodeOp uniqueOp(Predicate<PcodeOp> predicate) {
+ return Unique.assertOne(program.getCode().stream().filter(predicate));
+ }
+
+ public PcodeOp uniqueOp(int opcode) {
+ return uniqueOp(op -> op.getOpcode() == opcode);
+ }
+
+ public PcodeOp uniqueCopyTo(String regname) {
+ return uniqueOp(op -> op.getOpcode() == PcodeOp.COPY &&
+ op.getOutput().toString(program.getLanguage()).equals(regname));
+ }
+
+ public List<CodeElement> codeForOp(ClassModel cm, PcodeOp op) {
+ int idx = program.getCode().indexOf(op);
+ if (idx == -1) {
+ throw new AssertionError("Op %s not part of program %s".formatted(op, program));
+ }
+ int lineno = idx + 1;
+ return cm.methods()
+ .stream()
+ .filter(m -> "run".equals(m.methodName().stringValue()))
+ .limit(1)
+ .flatMap(rm -> rm.code().stream())
+ .flatMap(code -> code.elementStream())
+ .dropWhile(ce -> !(ce instanceof LineNumber l) || l.line() != lineno)
+ .takeWhile(ce -> !(ce instanceof LineNumber l) || l.line() == lineno)
+ .toList();
+ }
}
public Translation translateProgram(PcodeProgram program, JitPcodeThread thread)
@@ -182,13 +217,14 @@ public abstract class AbstractJitCodeGeneratorTest extends AbstractJitTest {
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);
+ JitReachabilityModel rm = new JitReachabilityModel(context, cfm, dfm);
+ JitVarScopeModel vsm = new JitVarScopeModel(cfm, dfm, rm);
+ JitOpUseModel oum = new JitOpUseModel(context, cfm, dfm, rm, vsm);
+ JitTypeModel tm = new JitTypeModel(dfm, oum);
+ JitAllocationModel am = new JitAllocationModel(context, dfm, vsm, oum, tm);
JitCodeGenerator<?> gen =
- new JitCodeGenerator<>(MethodHandles.lookup(), context, cfm, dfm, vsm, tm, am, oum);
+ new JitCodeGenerator<>(MethodHandles.lookup(), context, cfm, dfm, rm, vsm, tm, am, oum);
byte[] classbytes = gen.generate();
@@ -214,7 +250,8 @@ public abstract class AbstractJitCodeGeneratorTest extends AbstractJitTest {
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);
+ (TestUseropLibrary) thread.getMachine().getUseropLibrary(), state, classbytes,
+ passageCls, passage);
}
public static class TestUseropLibrary extends AnnotatedPcodeUseropLibrary<byte[]> {
@@ -289,15 +326,30 @@ public abstract class AbstractJitCodeGeneratorTest extends AbstractJitTest {
}
}
- public static class TestJitPcodeEmulator extends JitPcodeEmulator {
+ record CountInvocation(String threadName, int instructions, int trailingOps) {}
+
+ protected final List<CountInvocation> countInvocations = new ArrayList<>();
+
+ public class TestJitPcodeEmulator extends JitPcodeEmulator {
public TestJitPcodeEmulator(Language language) {
- super(language, new JitConfiguration(), MethodHandles.lookup());
+ super(language, createConfiguration(), MethodHandles.lookup());
}
@Override
protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
return new TestUseropLibrary();
}
+
+ @Override
+ protected JitPcodeThread createThread(String name) {
+ return new JitPcodeThread(name, this) {
+ @Override
+ public void count(int instructions, int trailingOps) {
+ super.count(instructions, trailingOps);
+ countInvocations.add(new CountInvocation(name, instructions, trailingOps));
+ }
+ };
+ }
}
public static class TestPlainPcodeEmulator extends PcodeEmulator {
@@ -435,4 +487,15 @@ public abstract class AbstractJitCodeGeneratorTest extends AbstractJitTest {
}
return translateBuffer(buf, buf.getEntry(), injects);
}
+
+ public static Instruction firstControlFlowInstruction(List<CodeElement> code) {
+ return (Instruction) code.stream()
+ .filter(ce -> ce instanceof BranchInstruction ||
+ ce instanceof ReturnInstruction ||
+ ce instanceof ThrowInstruction ||
+ ce instanceof LookupSwitchInstruction ||
+ ce instanceof TableSwitchInstruction)
+ .findFirst()
+ .orElseThrow();
+ }
}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractToyJitCodeGeneratorTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractToyJitCodeGeneratorTest.java
index e39afb9736..771bac745a 100644
--- a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractToyJitCodeGeneratorTest.java
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/AbstractToyJitCodeGeneratorTest.java
@@ -3668,6 +3668,49 @@ public abstract class AbstractToyJitCodeGeneratorTest extends AbstractJitCodeGen
assertEquals(123 * 2 + 4, tr.getLongRegVal("r1"));
}
+ @Test
+ public void testEmuInjectionAtEntry() throws Exception {
+ Translation tr = translateLang(getLanguageID(), 0x00400000, """
+ imm r0,#123
+ add r0,#7
+ """, Map.ofEntries(
+ Map.entry(0x00400000L, """
+ r1 = 0xbeef;
+ emu_exec_decoded();
+ """)));
+
+ tr.runDecodeErr(0x00400004);
+ assertEquals(123 + 7, tr.getLongRegVal("r0"));
+ assertEquals(0xbeef, tr.getLongRegVal("r1"));
+ }
+
+ @Test
+ public void testEmuInjectionAtEntrySkip() throws Exception {
+ Translation tr = translateLang(getLanguageID(), 0x00400000, """
+ imm r0,#123
+ add r0,#7
+ """, Map.ofEntries(
+ Map.entry(0x00400000L, """
+ r1 = 0xbeef;
+ emu_skip_decoded();
+ """)));
+
+ tr.runDecodeErr(0x00400004);
+ assertEquals(7, tr.getLongRegVal("r0"));
+ assertEquals(0xbeef, tr.getLongRegVal("r1"));
+ }
+
+ @Test
+ public void testEmuInjectionAtEntryEmpty() throws Exception {
+ Translation tr = translateLang(getLanguageID(), 0x00400000, """
+ imm r0,#123
+ add r0,#7
+ """, Map.ofEntries(
+ Map.entry(0x00400000L, """
+ """)));
+ // Can't run, or else it loops. Just verify it doesn't crash.
+ }
+
@Test
public void testEmuInjectionCallEmuSkipDecoded() throws Exception {
Translation tr = translateLang(getLanguageID(), 0x00400000, """
@@ -3700,6 +3743,8 @@ public abstract class AbstractToyJitCodeGeneratorTest extends AbstractJitCodeGen
}
return "sCarryLongRaw".equals(mi.name);
}).count();
- assertEquals(1, countSCarrys);
+ long expected =
+ tr.thread().getMachine().getConfiguration().removeUnusedOperations() ? 1 : 2;
+ assertEquals(expected, countSCarrys);
}
}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/FoldingJitCodeGeneratorTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/FoldingJitCodeGeneratorTest.java
new file mode 100644
index 0000000000..4e57d70e2b
--- /dev/null
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/FoldingJitCodeGeneratorTest.java
@@ -0,0 +1,311 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR 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.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+import java.lang.classfile.*;
+import java.util.List;
+import java.util.Map;
+
+import org.hamcrest.Matchers;
+import org.junit.Test;
+
+import ghidra.app.plugin.processors.sleigh.SleighLanguage;
+import ghidra.pcode.emu.jit.analysis.JitTypeModel;
+import ghidra.pcode.emu.jit.analysis.JitVarScopeModel;
+import ghidra.pcode.exec.PcodeProgram;
+import ghidra.program.model.lang.Endian;
+import ghidra.program.model.lang.LanguageID;
+import ghidra.program.model.pcode.PcodeOp;
+
+public class FoldingJitCodeGeneratorTest extends AbstractJitCodeGeneratorTest {
+
+ protected static final LanguageID ID_TOYBE64 = new LanguageID("Toy:BE:64:default");
+ protected static final LanguageID ID_TOYLE64 = new LanguageID("Toy:LE:64:default");
+
+ protected Endian getEndian() {
+ return Endian.BIG;
+ }
+
+ @Override
+ protected LanguageID getLanguageID() {
+ return switch (getEndian()) {
+ case BIG -> ID_TOYBE64;
+ case LITTLE -> ID_TOYLE64;
+ };
+ }
+
+ @Test
+ public void testBranchIndRewriteToDirectInternal() throws Exception {
+ Translation tr = translateLang(getLanguageID(), 0x00400000, """
+ imm r0,#6
+ br r0
+ """, Map.of());
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opBranchInd = tr.uniqueOp(PcodeOp.BRANCHIND);
+ List<CodeElement> codeForBranch = tr.codeForOp(cm, opBranchInd);
+ Instruction firstCfi = firstControlFlowInstruction(codeForBranch);
+ // As if internal unconditional branch, which uses goto
+ assertEquals(Opcode.GOTO, firstCfi.opcode());
+ }
+
+ @Test
+ public void testBranchIndNotRewritten() throws Exception {
+ Translation tr = translateLang(getLanguageID(), 0x00400000, """
+ br r0
+ """, Map.of());
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opBranchInd = tr.uniqueOp(PcodeOp.BRANCHIND);
+ List<CodeElement> codeForBranch = tr.codeForOp(cm, opBranchInd);
+ Instruction firstCfi = firstControlFlowInstruction(codeForBranch);
+ // Indirect branch writes counter/context and returns null
+ assertEquals(Opcode.ARETURN, firstCfi.opcode());
+ }
+
+ @Test
+ public void testBranchIndRewrittenToConditionalDirectInternal() throws Exception {
+ Translation tr = translateLang(getLanguageID(), 0x00400000, """
+ imm r0, #0
+ imm r1, #1
+ imm r2, #6
+
+ add r0, r1
+ cmp r0, r2
+ brne 0x00400006
+
+ br r0
+ """, Map.of());
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opBranchInd = tr.uniqueOp(PcodeOp.BRANCHIND);
+ List<CodeElement> codeForBranch = tr.codeForOp(cm, opBranchInd);
+ Instruction firstCfi = firstControlFlowInstruction(codeForBranch);
+ assertThat(firstCfi.opcode(), Matchers.oneOf(Opcode.IFEQ, Opcode.IFNE));
+ }
+
+ @Test
+ public void testCBranchRewrittenToBranch() throws Exception {
+ // Two vars, because a==a could be optimized later, regardless of A's constness
+ Translation tr = translateSleigh(getLanguageID(), """
+ local a:4 = 0;
+ local b:4 = 0;
+ if a==b goto <L1>;
+ r0 = 1;
+ <L1>
+ """);
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opCBranch = tr.uniqueOp(PcodeOp.CBRANCH);
+ List<CodeElement> codeForBranch = tr.codeForOp(cm, opCBranch);
+ Instruction firstCfi = firstControlFlowInstruction(codeForBranch);
+ // Re-written as unconditional, so goto
+ assertEquals(Opcode.GOTO, firstCfi.opcode());
+
+ tr.runFallthrough();
+ assertEquals(0, tr.getLongRegVal("r0"));
+ }
+
+ @Test
+ public void testCBranchRewrittenToNop() throws Exception {
+ Translation tr = translateSleigh(getLanguageID(), """
+ local a:4 = 0;
+ local b:4 = 1;
+ if a==b goto <L1>;
+ r0 = 1;
+ <L1>
+ """);
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opCBranch = tr.uniqueOp(PcodeOp.CBRANCH);
+ List<CodeElement> codeForBranch = tr.codeForOp(cm, opCBranch);
+ // Re-written as nop
+ assertEquals(List.of(), codeForBranch);
+
+ tr.runFallthrough();
+ assertEquals(1, tr.getLongRegVal("r0"));
+ }
+
+ @Test
+ public void testCBranchNotRewritten() throws Exception {
+ Translation tr = translateSleigh(getLanguageID(), """
+ r0 = 0;
+ <L1>
+ r0 = r0 + 1;
+ if r0 != 6 goto <L1>;
+ """);
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opCBranch = tr.uniqueOp(PcodeOp.CBRANCH);
+ List<CodeElement> codeForBranch = tr.codeForOp(cm, opCBranch);
+ Instruction firstCfi = firstControlFlowInstruction(codeForBranch);
+ // Still conditional
+ assertThat(firstCfi.opcode(), Matchers.oneOf(Opcode.IFEQ, Opcode.IFNE));
+
+ // Emu initialized a and b to 0, but JIT doesn't know or care
+ tr.runFallthrough();
+ assertEquals(6, tr.getLongRegVal("r0"));
+ }
+
+ @Test
+ public void testCBranchRewrittenToBranchFallRemoved() throws Exception {
+ // Two vars, because a==a could be optimized later, regardless of A's constness
+ Translation tr = translateSleigh(getLanguageID(), """
+ local a:4 = 0;
+ local b:4 = 0;
+ if a==b goto <L1>;
+ r0 = 1;
+ goto <L2>;
+ <L1>
+ r1 = 1;
+ <L2>
+ """);
+ tr.runFallthrough();
+ assertEquals(0, tr.getLongRegVal("r0"));
+ assertEquals(1, tr.getLongRegVal("r1"));
+
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opR0Copy1 = tr.uniqueCopyTo("r0");
+ List<CodeElement> codeForCopyR0 = tr.codeForOp(cm, opR0Copy1);
+ assertEquals(List.of(), codeForCopyR0);
+ PcodeOp opR1Copy1 = tr.uniqueCopyTo("r1");
+ List<CodeElement> codeForCopyR1 = tr.codeForOp(cm, opR1Copy1);
+ assertNotEquals(List.of(), codeForCopyR1);
+ }
+
+ @Test
+ public void testCBranchRewrittenToNopJumpRemoved() throws Exception {
+ Translation tr = translateSleigh(getLanguageID(), """
+ local a:4 = 0;
+ local b:4 = 1;
+ if a==b goto <L1>;
+ r0 = 1;
+ goto <L2>;
+ <L1>
+ r1 = 1;
+ <L2>
+ """);
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeOp opR0Copy1 = tr.uniqueCopyTo("r0");
+ List<CodeElement> codeForCopyR0 = tr.codeForOp(cm, opR0Copy1);
+ assertNotEquals(List.of(), codeForCopyR0);
+ PcodeOp opR1Copy1 = tr.uniqueCopyTo("r1");
+ List<CodeElement> codeForCopyR1 = tr.codeForOp(cm, opR1Copy1);
+ assertEquals(List.of(), codeForCopyR1);
+
+ tr.runFallthrough();
+ assertEquals(1, tr.getLongRegVal("r0"));
+ assertEquals(0, tr.getLongRegVal("r1"));
+ }
+
+ static final List<Integer> CONSTS =
+ List.of(0x12, 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xfa, 0xce);
+
+ /**
+ * There's a lesson learned here when writing such chains e.g., in a syscall handler userop.
+ * Avoid allocation of disposable uniques. Use "local" to manually allocate and re-use uniques,
+ * but be careful to consider how the {@link JitTypeModel} will treat them.
+ * <p>
+ * LATER: Can we be more clever about which uniques actually need saving? Could be limited to
+ * those from a constructor offering a named block (for crossbuild elsewhere.) We have to
+ * consider whether it's possible for a unique to be retired and re-birthed within the same
+ * inject or instruction p-code. I <em>think</em> the current {@link JitVarScopeModel} prohibits
+ * this, but that could change.
+ *
+ * @throws Exception because
+ */
+ @Test
+ public void testCBranchChainCollapsed() throws Exception {
+ Translation tr = translateSleigh(getLanguageID(), """
+ r0 = 5;
+ local z:1;
+ z=r0==1; if z goto <L1>;
+ z=r0==2; if z goto <L2>;
+ z=r0==3; if z goto <L3>;
+ z=r0==4; if z goto <L4>;
+ z=r0==5; if z goto <L5>;
+ z=r0==6; if z goto <L6>;
+ z=r0==7; if z goto <L7>;
+ z=r0==8; if z goto <L8>;
+ r1 = 0x12; goto <exit>;
+ <L1> r1 = 0xde; goto <exit>;
+ <L2> r1 = 0xad; goto <exit>;
+ <L3> r1 = 0xbe; goto <exit>;
+ <L4> r1 = 0xef; goto <exit>;
+ <L5> r1 = 0xca; goto <exit>;
+ <L6> r1 = 0xfe; goto <exit>;
+ <L7> r1 = 0xfa; goto <exit>;
+ <L8> r1 = 0xce;
+ <exit>
+ """);
+ ClassModel cm = ClassFile.of().parse(tr.classbytes());
+ PcodeProgram program = tr.program();
+ SleighLanguage language = program.getLanguage();
+
+ for (int i = 1; i <= 8; i++) {
+ int idxIntEqual = i * 2 - 1;
+ int idxCBranch = i * 2;
+ PcodeOp opIntEqual = assertOp(PcodeOp.INT_EQUAL, program.getCode().get(idxIntEqual));
+ assertEquals("r0", opIntEqual.getInput(0).toString(language));
+ assertEquals("0x%x".formatted(i), opIntEqual.getInput(1).toString(language));
+ PcodeOp opCBranch = assertOp(PcodeOp.CBRANCH, program.getCode().get(idxCBranch));
+ if (i == 5) {
+ assertNotEquals(List.of(), tr.codeForOp(cm, opIntEqual));
+ /**
+ * No assertion on CBRANCH being a GOTO. If that GOTO is to the next bytecode, it
+ * ought to be removed.
+ */
+ }
+ else {
+ assertEquals(List.of(), tr.codeForOp(cm, opIntEqual));
+ assertEquals(List.of(), tr.codeForOp(cm, opCBranch));
+ }
+ }
+
+ for (int i = 0; i <= 8; i++) {
+ int idxCopy = i * 2 + 17;
+ int idxBranch = i * 2 + 18;
+ PcodeOp opCopy = assertOp(PcodeOp.COPY, program.getCode().get(idxCopy));
+ assertEquals("r1", opCopy.getOutput().toString(language));
+ assertEquals("0x%x".formatted(CONSTS.get(i)), opCopy.getInput(0).toString(language));
+ PcodeOp opBranch =
+ i == 8 ? null : assertOp(PcodeOp.BRANCH, program.getCode().get(idxBranch));
+ if (i == 5) {
+ assertNotEquals(List.of(), tr.codeForOp(cm, opCopy));
+ /**
+ * No assertion on BRANCH being a GOTO. If that GOTO is to the next bytecode, it
+ * ought to be removed.
+ */
+ }
+ else {
+ assertEquals(List.of(), tr.codeForOp(cm, opCopy));
+ if (i != 8) {
+ assertEquals(List.of(), tr.codeForOp(cm, opBranch));
+ }
+ }
+ }
+
+ tr.runFallthrough();
+ assertEquals(5, tr.getLongRegVal("r0"));
+ assertEquals(0xca, tr.getLongRegVal("r1"));
+
+ assertEquals(
+ List.of(
+ new CountInvocation("Thread 0", 1, 3), // r0 = 5 and first cmp/cbranch
+ new CountInvocation("Thread 0", 0, 8), // four collapsed cmp/cbranch blocks
+ new CountInvocation("Thread 0", 0, 2), // r1 = 0xca; goto <exit>
+ new CountInvocation("Thread 0", 0, 1)), // goto 0xdeadbeef
+ countInvocations);
+ }
+}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/KeepUnreachableBlocksRemoveUnusedOpsToyBEJitCodeGeneratorTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/KeepUnreachableBlocksRemoveUnusedOpsToyBEJitCodeGeneratorTest.java
new file mode 100644
index 0000000000..7369ddcc83
--- /dev/null
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/KeepUnreachableBlocksRemoveUnusedOpsToyBEJitCodeGeneratorTest.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.gen;
+
+import ghidra.pcode.emu.jit.JitConfiguration;
+import ghidra.pcode.emu.jit.JitConfiguration.Opt;
+
+public class KeepUnreachableBlocksRemoveUnusedOpsToyBEJitCodeGeneratorTest
+ extends ToyBEJitCodeGeneratorTest {
+ @Override
+ protected JitConfiguration createConfiguration() {
+ return new JitConfiguration()
+ .disable(Opt.REMOVE_UNREACHABLE_BLOCKS)
+ .enable(Opt.REMOVE_UNUSED_OPERATIONS);
+ }
+}
diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/RemoveUnreachableBlocksKeepUnusedOpsToyBEJitCodeGeneratorTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/RemoveUnreachableBlocksKeepUnusedOpsToyBEJitCodeGeneratorTest.java
new file mode 100644
index 0000000000..df448ab146
--- /dev/null
+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcode/emu/jit/gen/RemoveUnreachableBlocksKeepUnusedOpsToyBEJitCodeGeneratorTest.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.gen;
+
+import ghidra.pcode.emu.jit.JitConfiguration;
+import ghidra.pcode.emu.jit.JitConfiguration.Opt;
+
+public class RemoveUnreachableBlocksKeepUnusedOpsToyBEJitCodeGeneratorTest
+ extends ToyBEJitCodeGeneratorTest {
+ @Override
+ protected JitConfiguration createConfiguration() {
+ return new JitConfiguration()
+ .enable(Opt.REMOVE_UNREACHABLE_BLOCKS)
+ .disable(Opt.REMOVE_UNUSED_OPERATIONS);
+ }
+}
diff --git a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.html b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.html
index d2cd7ae433..9697b55362 100644
--- a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.html
+++ b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.html
@@ -207,7 +207,7 @@ a Sleigh breakpoint that invokes the appropriate userop.</p>
<p>A userop library is created by implementing the
<code>PcodeUseropLibrary</code> interface, most likely by extending
<code>AnnotatedPcodeUseropLibrary</code>. For example, to provide a stub
-for <code>strlen</code>:</p>
+for <code>strnlen</code>:</p>
<div class="sourceCode" id="cb1"><pre
class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb1-1"><a href="#cb1-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> JavaStdLibPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> <span class="kw">extends</span> AnnotatedPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> <span class="op">{</span></span>
<span id="cb1-2"><a href="#cb1-2"></a> <span class="kw">private</span> <span class="dt">final</span> AddressSpace space<span class="op">;</span></span>
@@ -216,7 +216,7 @@ class="sourceCode numberSource java numberLines"><code class="sourceCode java"><
<span id="cb1-5"><a href="#cb1-5"></a> <span class="kw">private</span> <span class="dt">final</span> Register regRDI<span class="op">;</span></span>
<span id="cb1-6"><a href="#cb1-6"></a> <span class="kw">private</span> <span class="dt">final</span> Register regRSI<span class="op">;</span></span>
<span id="cb1-7"><a href="#cb1-7"></a></span>
-<span id="cb1-8"><a href="#cb1-8"></a> <span class="kw">public</span> <span class="fu">JavaStdLibPcodeUseropLibrary</span><span class="op">(</span>SleighLanguage language<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb1-8"><a href="#cb1-8"></a> <span class="kw">public</span> <span class="fu">JavaStdLibPcodeUseropLibrary</span><span class="op">(</span>Language language<span class="op">)</span> <span class="op">{</span></span>
<span id="cb1-9"><a href="#cb1-9"></a> space <span class="op">=</span> language<span class="op">.</span><span class="fu">getDefaultSpace</span><span class="op">();</span></span>
<span id="cb1-10"><a href="#cb1-10"></a> regRSP <span class="op">=</span> language<span class="op">.</span><span class="fu">getRegister</span><span class="op">(</span><span class="st">&quot;RSP&quot;</span><span class="op">);</span></span>
<span id="cb1-11"><a href="#cb1-11"></a> regRAX <span class="op">=</span> language<span class="op">.</span><span class="fu">getRegister</span><span class="op">(</span><span class="st">&quot;RAX&quot;</span><span class="op">);</span></span>
@@ -225,44 +225,51 @@ class="sourceCode numberSource java numberLines"><code class="sourceCode java"><
<span id="cb1-14"><a href="#cb1-14"></a> <span class="op">}</span></span>
<span id="cb1-15"><a href="#cb1-15"></a></span>
<span id="cb1-16"><a href="#cb1-16"></a> <span class="at">@PcodeUserop</span></span>
-<span id="cb1-17"><a href="#cb1-17"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__x86_64_RET</span><span class="op">(</span></span>
-<span id="cb1-18"><a href="#cb1-18"></a> <span class="at">@OpExecutor</span> PcodeExecutor<span class="op">&lt;</span>T<span class="op">&gt;</span> executor<span class="op">,</span></span>
-<span id="cb1-19"><a href="#cb1-19"></a> <span class="at">@OpState</span> PcodeExecutorState<span class="op">&lt;</span>T<span class="op">&gt;</span> state<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb1-20"><a href="#cb1-20"></a> PcodeArithmetic<span class="op">&lt;</span>T<span class="op">&gt;</span> arithmetic <span class="op">=</span> state<span class="op">.</span><span class="fu">getArithmetic</span><span class="op">();</span></span>
-<span id="cb1-21"><a href="#cb1-21"></a> T tRSP <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>regRSP<span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
-<span id="cb1-22"><a href="#cb1-22"></a> <span class="dt">long</span> lRSP <span class="op">=</span> arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tRSP<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">OTHER</span><span class="op">);</span></span>
-<span id="cb1-23"><a href="#cb1-23"></a> T tReturn <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>space<span class="op">,</span> lRSP<span class="op">,</span> <span class="dv">8</span><span class="op">,</span> <span class="kw">true</span><span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
-<span id="cb1-24"><a href="#cb1-24"></a> <span class="dt">long</span> lReturn <span class="op">=</span> arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tReturn<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">BRANCH</span><span class="op">);</span></span>
-<span id="cb1-25"><a href="#cb1-25"></a> state<span class="op">.</span><span class="fu">setVar</span><span class="op">(</span>regRSP<span class="op">,</span> arithmetic<span class="op">.</span><span class="fu">fromConst</span><span class="op">(</span>lRSP <span class="op">+</span> <span class="dv">8</span><span class="op">,</span> <span class="dv">8</span><span class="op">));</span></span>
-<span id="cb1-26"><a href="#cb1-26"></a> <span class="op">((</span>PcodeThreadExecutor<span class="op">&lt;</span>T<span class="op">&gt;)</span> executor<span class="op">).</span><span class="fu">getThread</span><span class="op">()</span></span>
-<span id="cb1-27"><a href="#cb1-27"></a> <span class="op">.</span><span class="fu">overrideCounter</span><span class="op">(</span>space<span class="op">.</span><span class="fu">getAddress</span><span class="op">(</span>lReturn<span class="op">));</span></span>
-<span id="cb1-28"><a href="#cb1-28"></a> <span class="op">}</span></span>
-<span id="cb1-29"><a href="#cb1-29"></a></span>
-<span id="cb1-30"><a href="#cb1-30"></a> <span class="at">@PcodeUserop</span></span>
-<span id="cb1-31"><a href="#cb1-31"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__libc_strlen</span><span class="op">(</span><span class="at">@OpState</span> PcodeExecutorState<span class="op">&lt;</span>T<span class="op">&gt;</span> state<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb1-32"><a href="#cb1-32"></a> PcodeArithmetic<span class="op">&lt;</span>T<span class="op">&gt;</span> arithmetic <span class="op">=</span> state<span class="op">.</span><span class="fu">getArithmetic</span><span class="op">();</span></span>
-<span id="cb1-33"><a href="#cb1-33"></a> T tStr <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>regRDI<span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
-<span id="cb1-34"><a href="#cb1-34"></a> <span class="dt">long</span> lStr <span class="op">=</span> arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tStr<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">OTHER</span><span class="op">);</span></span>
-<span id="cb1-35"><a href="#cb1-35"></a> T tMaxlen <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>regRSI<span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
-<span id="cb1-36"><a href="#cb1-36"></a> <span class="dt">long</span> lMaxlen <span class="op">=</span> arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tMaxlen<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">OTHER</span><span class="op">);</span></span>
-<span id="cb1-37"><a href="#cb1-37"></a></span>
-<span id="cb1-38"><a href="#cb1-38"></a> <span class="cf">for</span> <span class="op">(</span><span class="dt">int</span> i <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> i <span class="op">&lt;</span> lMaxlen<span class="op">;</span> i<span class="op">++)</span> <span class="op">{</span></span>
-<span id="cb1-39"><a href="#cb1-39"></a> T tChar <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>space<span class="op">,</span> lStr <span class="op">+</span> i<span class="op">,</span> <span class="dv">1</span><span class="op">,</span> <span class="kw">false</span><span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
-<span id="cb1-40"><a href="#cb1-40"></a> <span class="cf">if</span> <span class="op">(</span>arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tChar<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">OTHER</span><span class="op">)</span> <span class="op">==</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb1-41"><a href="#cb1-41"></a> state<span class="op">.</span><span class="fu">setVar</span><span class="op">(</span>regRAX<span class="op">,</span> arithmetic<span class="op">.</span><span class="fu">fromConst</span><span class="op">(</span><span class="bu">Integer</span><span class="op">.</span><span class="fu">toUnsignedLong</span><span class="op">(</span>i<span class="op">),</span> <span class="dv">8</span><span class="op">));</span></span>
-<span id="cb1-42"><a href="#cb1-42"></a> <span class="cf">break</span><span class="op">;</span></span>
-<span id="cb1-43"><a href="#cb1-43"></a> <span class="op">}</span></span>
-<span id="cb1-44"><a href="#cb1-44"></a> <span class="op">}</span></span>
-<span id="cb1-45"><a href="#cb1-45"></a> <span class="op">}</span></span>
-<span id="cb1-46"><a href="#cb1-46"></a><span class="op">}</span></span></code></pre></div>
+<span id="cb1-17"><a href="#cb1-17"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__x86_64_POP</span><span class="op">(</span><span class="at">@OpExecutor</span> PcodeExecutor<span class="op">&lt;</span>T<span class="op">&gt;</span> executor<span class="op">,</span></span>
+<span id="cb1-18"><a href="#cb1-18"></a> <span class="at">@OpState</span> PcodeExecutorState<span class="op">&lt;</span>T<span class="op">&gt;</span> state<span class="op">,</span> <span class="at">@OpOutput</span> Varnode out<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb1-19"><a href="#cb1-19"></a> PcodeArithmetic<span class="op">&lt;</span>T<span class="op">&gt;</span> arithmetic <span class="op">=</span> state<span class="op">.</span><span class="fu">getArithmetic</span><span class="op">();</span></span>
+<span id="cb1-20"><a href="#cb1-20"></a> T tRSP <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>regRSP<span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
+<span id="cb1-21"><a href="#cb1-21"></a> <span class="dt">long</span> lRSP <span class="op">=</span> arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tRSP<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">LOAD</span><span class="op">);</span></span>
+<span id="cb1-22"><a href="#cb1-22"></a> T tReturn <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>space<span class="op">,</span> lRSP<span class="op">,</span> <span class="dv">8</span><span class="op">,</span> <span class="kw">true</span><span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
+<span id="cb1-23"><a href="#cb1-23"></a> state<span class="op">.</span><span class="fu">setVar</span><span class="op">(</span>regRSP<span class="op">,</span> arithmetic<span class="op">.</span><span class="fu">fromConst</span><span class="op">(</span>lRSP <span class="op">+</span> <span class="dv">8</span><span class="op">,</span> <span class="dv">8</span><span class="op">));</span></span>
+<span id="cb1-24"><a href="#cb1-24"></a> state<span class="op">.</span><span class="fu">setVar</span><span class="op">(</span>out<span class="op">,</span> tReturn<span class="op">);</span></span>
+<span id="cb1-25"><a href="#cb1-25"></a> <span class="op">}</span></span>
+<span id="cb1-26"><a href="#cb1-26"></a></span>
+<span id="cb1-27"><a href="#cb1-27"></a> <span class="at">@PcodeUserop</span></span>
+<span id="cb1-28"><a href="#cb1-28"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__libc_strnlen</span><span class="op">(</span><span class="at">@OpState</span> PcodeExecutorState<span class="op">&lt;</span>T<span class="op">&gt;</span> state<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb1-29"><a href="#cb1-29"></a> PcodeArithmetic<span class="op">&lt;</span>T<span class="op">&gt;</span> arithmetic <span class="op">=</span> state<span class="op">.</span><span class="fu">getArithmetic</span><span class="op">();</span></span>
+<span id="cb1-30"><a href="#cb1-30"></a> T tStr <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>regRDI<span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
+<span id="cb1-31"><a href="#cb1-31"></a> <span class="dt">long</span> lStr <span class="op">=</span> arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tStr<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">OTHER</span><span class="op">);</span></span>
+<span id="cb1-32"><a href="#cb1-32"></a> T tMaxlen <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>regRSI<span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
+<span id="cb1-33"><a href="#cb1-33"></a> <span class="dt">long</span> lMaxlen <span class="op">=</span> arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tMaxlen<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">OTHER</span><span class="op">);</span></span>
+<span id="cb1-34"><a href="#cb1-34"></a></span>
+<span id="cb1-35"><a href="#cb1-35"></a> <span class="cf">for</span> <span class="op">(</span><span class="dt">int</span> i <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> i <span class="op">&lt;</span> lMaxlen<span class="op">;</span> i<span class="op">++)</span> <span class="op">{</span></span>
+<span id="cb1-36"><a href="#cb1-36"></a> T tChar <span class="op">=</span> state<span class="op">.</span><span class="fu">getVar</span><span class="op">(</span>space<span class="op">,</span> lStr <span class="op">+</span> i<span class="op">,</span> <span class="dv">1</span><span class="op">,</span> <span class="kw">false</span><span class="op">,</span> Reason<span class="op">.</span><span class="fu">EXECUTE_READ</span><span class="op">);</span></span>
+<span id="cb1-37"><a href="#cb1-37"></a> <span class="cf">if</span> <span class="op">(</span>arithmetic<span class="op">.</span><span class="fu">toLong</span><span class="op">(</span>tChar<span class="op">,</span> Purpose<span class="op">.</span><span class="fu">OTHER</span><span class="op">)</span> <span class="op">==</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb1-38"><a href="#cb1-38"></a> state<span class="op">.</span><span class="fu">setVar</span><span class="op">(</span>regRAX<span class="op">,</span> arithmetic<span class="op">.</span><span class="fu">fromConst</span><span class="op">(</span><span class="bu">Integer</span><span class="op">.</span><span class="fu">toUnsignedLong</span><span class="op">(</span>i<span class="op">),</span> <span class="dv">8</span><span class="op">));</span></span>
+<span id="cb1-39"><a href="#cb1-39"></a> <span class="cf">break</span><span class="op">;</span></span>
+<span id="cb1-40"><a href="#cb1-40"></a> <span class="op">}</span></span>
+<span id="cb1-41"><a href="#cb1-41"></a> <span class="op">}</span></span>
+<span id="cb1-42"><a href="#cb1-42"></a> <span class="op">}</span></span>
+<span id="cb1-43"><a href="#cb1-43"></a><span class="op">}</span></span></code></pre></div>
<p>Here, we implement the stub using Java callbacks. This is more useful
when modeling things outside of Ghidra’s definition of machine state,
e.g., to simulate kernel objects in an underlying operating system.
Nevertheless, it can be used to model simple state changes as well. A
user would place a breakpoint at either the call site or the call
-target, have it invoke <code>__libc_strlen()</code>, and then invoke
-either <code>emu_skip_decoded()</code> or <code>__x86_64_RET()</code>
-depending on where the breakpoint was placed.</p>
+target, have it invoke <code>__libc_strnlen()</code>, and then invoke
+either <code>emu_skip_decoded()</code> or
+<code>RIP = __x86_64_POP(); return [RIP];</code> depending on where the
+breakpoint was placed. <strong>NOTE</strong>: Control transfers should
+rarely, if ever, be performed within a userop, except internal to that
+userop. This assures advanced execution engines can better process the
+control graph of the target. In particular, invoking
+<code>thread.overrideCounter()</code> from within a Java-callback userop
+is <em>not</em> recommended. It is better to place such control
+transfers in the injection, which is why we include
+<code>return [RIP];</code> rather than having an
+<code>__x86_64_RET()</code> userop that performs the control
+transfer.</p>
</section>
<section id="modeling-by-sleigh-semantics" class="level3">
<h3>Modeling by Sleigh Semantics</h3>
@@ -277,118 +284,170 @@ concrete, and then converting back to <code>T</code> using the
<code>arithmetic</code> object. However, if the emulator has been
augmented, as we will discuss below, the model may become confused,
because values computed by a careless userop will appear to the model a
-literal constant. To avoid this, you should keep everything a T and use
-the <code>arithmetic</code> object to perform any arithmetic operations.
-Alternatively, you can implement the userop using pre-compiled Sleigh
-code:</p>
+literal constant. To avoid this, you should keep everything a
+<code>T</code> and use the <code>arithmetic</code> object to perform any
+arithmetic operations. Alternatively, you can implement the userop using
+Sleigh code:</p>
<div class="sourceCode" id="cb2"><pre
class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb2-1"><a href="#cb2-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> SleighStdLibPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> <span class="kw">extends</span> AnnotatedPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb2-2"><a href="#cb2-2"></a> <span class="kw">private</span> <span class="dt">static</span> <span class="dt">final</span> <span class="bu">String</span> SRC_RET <span class="op">=</span> <span class="st">&quot;&quot;&quot;</span></span>
-<span id="cb2-3"><a href="#cb2-3"></a> RIP <span class="op">=</span> <span class="op">*:</span><span class="dv">8</span> RSP<span class="op">;</span></span>
-<span id="cb2-4"><a href="#cb2-4"></a> RSP <span class="op">=</span> RSP <span class="op">+</span> <span class="dv">8</span><span class="op">;</span></span>
-<span id="cb2-5"><a href="#cb2-5"></a> <span class="cf">return</span> <span class="op">[</span>RIP<span class="op">];</span></span>
-<span id="cb2-6"><a href="#cb2-6"></a> <span class="st">&quot;&quot;&quot;;</span></span>
-<span id="cb2-7"><a href="#cb2-7"></a> <span class="kw">private</span> <span class="dt">static</span> <span class="dt">final</span> <span class="bu">String</span> SRC_STRLEN <span class="op">=</span> <span class="st">&quot;&quot;&quot;</span></span>
-<span id="cb2-8"><a href="#cb2-8"></a> __result <span class="op">=</span> <span class="dv">0</span><span class="op">;</span></span>
-<span id="cb2-9"><a href="#cb2-9"></a> <span class="op">&lt;</span>loop<span class="op">&gt;</span></span>
-<span id="cb2-10"><a href="#cb2-10"></a> <span class="cf">if</span> <span class="op">(*:</span><span class="dv">1</span> <span class="op">(</span>str<span class="op">+</span>__result<span class="op">)</span> <span class="op">==</span> <span class="dv">0</span> <span class="op">||</span> __result <span class="op">&gt;=</span> maxlen<span class="op">)</span> <span class="cf">goto</span> <span class="op">&lt;</span>exit<span class="op">&gt;;</span></span>
-<span id="cb2-11"><a href="#cb2-11"></a> __result <span class="op">=</span> __result <span class="op">+</span> <span class="dv">1</span><span class="op">;</span></span>
-<span id="cb2-12"><a href="#cb2-12"></a> <span class="cf">goto</span> <span class="op">&lt;</span>loop<span class="op">&gt;;</span></span>
-<span id="cb2-13"><a href="#cb2-13"></a> <span class="op">&lt;</span>exit<span class="op">&gt;</span></span>
-<span id="cb2-14"><a href="#cb2-14"></a> <span class="st">&quot;&quot;&quot;;</span></span>
-<span id="cb2-15"><a href="#cb2-15"></a> <span class="kw">private</span> <span class="dt">final</span> Register regRAX<span class="op">;</span></span>
-<span id="cb2-16"><a href="#cb2-16"></a> <span class="kw">private</span> <span class="dt">final</span> Register regRDI<span class="op">;</span></span>
-<span id="cb2-17"><a href="#cb2-17"></a> <span class="kw">private</span> <span class="dt">final</span> Register regRSI<span class="op">;</span></span>
-<span id="cb2-18"><a href="#cb2-18"></a> <span class="kw">private</span> <span class="dt">final</span> Varnode vnRAX<span class="op">;</span></span>
-<span id="cb2-19"><a href="#cb2-19"></a> <span class="kw">private</span> <span class="dt">final</span> Varnode vnRDI<span class="op">;</span></span>
-<span id="cb2-20"><a href="#cb2-20"></a> <span class="kw">private</span> <span class="dt">final</span> Varnode vnRSI<span class="op">;</span></span>
-<span id="cb2-21"><a href="#cb2-21"></a></span>
-<span id="cb2-22"><a href="#cb2-22"></a> <span class="kw">private</span> PcodeProgram progRet<span class="op">;</span></span>
-<span id="cb2-23"><a href="#cb2-23"></a> <span class="kw">private</span> PcodeProgram progStrlen<span class="op">;</span></span>
-<span id="cb2-24"><a href="#cb2-24"></a></span>
-<span id="cb2-25"><a href="#cb2-25"></a> <span class="kw">public</span> <span class="fu">SleighStdLibPcodeUseropLibrary</span><span class="op">(</span>SleighLanguage language<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb2-26"><a href="#cb2-26"></a> regRAX <span class="op">=</span> language<span class="op">.</span><span class="fu">getRegister</span><span class="op">(</span><span class="st">&quot;RAX&quot;</span><span class="op">);</span></span>
-<span id="cb2-27"><a href="#cb2-27"></a> regRDI <span class="op">=</span> language<span class="op">.</span><span class="fu">getRegister</span><span class="op">(</span><span class="st">&quot;RDI&quot;</span><span class="op">);</span></span>
-<span id="cb2-28"><a href="#cb2-28"></a> regRSI <span class="op">=</span> language<span class="op">.</span><span class="fu">getRegister</span><span class="op">(</span><span class="st">&quot;RSI&quot;</span><span class="op">);</span></span>
-<span id="cb2-29"><a href="#cb2-29"></a> vnRAX <span class="op">=</span> <span class="kw">new</span> <span class="fu">Varnode</span><span class="op">(</span>regRAX<span class="op">.</span><span class="fu">getAddress</span><span class="op">(),</span> regRAX<span class="op">.</span><span class="fu">getMinimumByteSize</span><span class="op">());</span></span>
-<span id="cb2-30"><a href="#cb2-30"></a> vnRDI <span class="op">=</span> <span class="kw">new</span> <span class="fu">Varnode</span><span class="op">(</span>regRDI<span class="op">.</span><span class="fu">getAddress</span><span class="op">(),</span> regRDI<span class="op">.</span><span class="fu">getMinimumByteSize</span><span class="op">());</span></span>
-<span id="cb2-31"><a href="#cb2-31"></a> vnRSI <span class="op">=</span> <span class="kw">new</span> <span class="fu">Varnode</span><span class="op">(</span>regRSI<span class="op">.</span><span class="fu">getAddress</span><span class="op">(),</span> regRSI<span class="op">.</span><span class="fu">getMinimumByteSize</span><span class="op">());</span></span>
-<span id="cb2-32"><a href="#cb2-32"></a> <span class="op">}</span></span>
-<span id="cb2-33"><a href="#cb2-33"></a></span>
-<span id="cb2-34"><a href="#cb2-34"></a> <span class="at">@PcodeUserop</span></span>
-<span id="cb2-35"><a href="#cb2-35"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__x86_64_RET</span><span class="op">(</span><span class="at">@OpExecutor</span> PcodeExecutor<span class="op">&lt;</span>T<span class="op">&gt;</span> executor<span class="op">,</span></span>
-<span id="cb2-36"><a href="#cb2-36"></a> <span class="at">@OpLibrary</span> PcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> library<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb2-37"><a href="#cb2-37"></a> <span class="cf">if</span> <span class="op">(</span>progRet <span class="op">==</span> <span class="kw">null</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb2-38"><a href="#cb2-38"></a> progRet <span class="op">=</span> SleighProgramCompiler<span class="op">.</span><span class="fu">compileUserop</span><span class="op">(</span>executor<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span></span>
-<span id="cb2-39"><a href="#cb2-39"></a> <span class="st">&quot;__x86_64_RET&quot;</span><span class="op">,</span> <span class="bu">List</span><span class="op">.</span><span class="fu">of</span><span class="op">(),</span> SRC_RET<span class="op">,</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">(),</span> <span class="bu">List</span><span class="op">.</span><span class="fu">of</span><span class="op">());</span></span>
-<span id="cb2-40"><a href="#cb2-40"></a> <span class="op">}</span></span>
-<span id="cb2-41"><a href="#cb2-41"></a> progRet<span class="op">.</span><span class="fu">execute</span><span class="op">(</span>executor<span class="op">,</span> library<span class="op">);</span></span>
-<span id="cb2-42"><a href="#cb2-42"></a> <span class="op">}</span></span>
-<span id="cb2-43"><a href="#cb2-43"></a></span>
-<span id="cb2-44"><a href="#cb2-44"></a> <span class="at">@PcodeUserop</span></span>
-<span id="cb2-45"><a href="#cb2-45"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__libc_strlen</span><span class="op">(</span><span class="at">@OpExecutor</span> PcodeExecutor<span class="op">&lt;</span>T<span class="op">&gt;</span> executor<span class="op">,</span></span>
-<span id="cb2-46"><a href="#cb2-46"></a> <span class="at">@OpLibrary</span> PcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> library<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb2-47"><a href="#cb2-47"></a> <span class="cf">if</span> <span class="op">(</span>progStrlen <span class="op">==</span> <span class="kw">null</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb2-48"><a href="#cb2-48"></a> progStrlen <span class="op">=</span> SleighProgramCompiler<span class="op">.</span><span class="fu">compileUserop</span><span class="op">(</span>executor<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span></span>
-<span id="cb2-49"><a href="#cb2-49"></a> <span class="st">&quot;__libc_strlen&quot;</span><span class="op">,</span> <span class="bu">List</span><span class="op">.</span><span class="fu">of</span><span class="op">(</span><span class="st">&quot;__result&quot;</span><span class="op">,</span> <span class="st">&quot;str&quot;</span><span class="op">,</span> <span class="st">&quot;maxlen&quot;</span><span class="op">),</span></span>
-<span id="cb2-50"><a href="#cb2-50"></a> SRC_STRLEN<span class="op">,</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">(),</span> <span class="bu">List</span><span class="op">.</span><span class="fu">of</span><span class="op">(</span>vnRAX<span class="op">,</span> vnRDI<span class="op">,</span> vnRSI<span class="op">));</span></span>
-<span id="cb2-51"><a href="#cb2-51"></a> <span class="op">}</span></span>
-<span id="cb2-52"><a href="#cb2-52"></a> progStrlen<span class="op">.</span><span class="fu">execute</span><span class="op">(</span>executor<span class="op">,</span> library<span class="op">);</span></span>
-<span id="cb2-53"><a href="#cb2-53"></a> <span class="op">}</span></span>
-<span id="cb2-54"><a href="#cb2-54"></a><span class="op">}</span></span></code></pre></div>
-<p>At construction, we capture the varnodes we need to use. We could
-just use them directly in the source, but this demonstrates the ability
-to alias them, which makes the Sleigh source more re-usable across
-target architectures. We then lazily compile each userop upon its first
-invocation. These are technically still Java callbacks, but our
-implementation delegates to the executor, giving it the compiled p-code
-program.</p>
-<p>The advantage here is that the p-code will use the underlying
-arithmetic appropriately. However, for some models, that may actually
-not be desired. Some symbolic models might just like to see an abstract
-call to <code>strlen()</code>.</p>
+<span id="cb2-2"><a href="#cb2-2"></a> <span class="at">@PcodeUserop</span></span>
+<span id="cb2-3"><a href="#cb2-3"></a> <span class="kw">public</span> SleighPcodeUseropDefinition <span class="fu">__x86_64_POP</span><span class="op">(</span>BuilderStage1 builder<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb2-4"><a href="#cb2-4"></a> <span class="cf">return</span> builder<span class="op">.</span><span class="fu">params</span><span class="op">().</span><span class="fu">body</span><span class="op">(</span>_ <span class="op">-&gt;</span> <span class="st">&quot;&quot;&quot;</span></span>
+<span id="cb2-5"><a href="#cb2-5"></a> __op_output <span class="op">=</span> <span class="op">*:</span><span class="dv">8</span> RSP<span class="op">;</span></span>
+<span id="cb2-6"><a href="#cb2-6"></a> RSP <span class="op">=</span> RSP <span class="op">+</span> <span class="dv">8</span><span class="op">;</span></span>
+<span id="cb2-7"><a href="#cb2-7"></a> <span class="st">&quot;&quot;&quot;).build();</span></span>
+<span id="cb2-8"><a href="#cb2-8"></a> <span class="op">}</span></span>
+<span id="cb2-9"><a href="#cb2-9"></a></span>
+<span id="cb2-10"><a href="#cb2-10"></a> <span class="at">@PcodeUserop</span></span>
+<span id="cb2-11"><a href="#cb2-11"></a> <span class="kw">public</span> SleighPcodeUseropDefinition <span class="fu">__libc_strnlen</span><span class="op">(</span>BuilderStage1 builder<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb2-12"><a href="#cb2-12"></a> <span class="cf">return</span> builder<span class="op">.</span><span class="fu">params</span><span class="op">().</span><span class="fu">body</span><span class="op">(</span>_ <span class="op">-&gt;</span> <span class="st">&quot;&quot;&quot;</span></span>
+<span id="cb2-13"><a href="#cb2-13"></a> RAX <span class="op">=</span> <span class="fu">__libc_strnlen_generic</span><span class="op">(</span>RDI<span class="op">,</span> RSI<span class="op">);</span></span>
+<span id="cb2-14"><a href="#cb2-14"></a> <span class="st">&quot;&quot;&quot;).build();</span></span>
+<span id="cb2-15"><a href="#cb2-15"></a> <span class="op">}</span></span>
+<span id="cb2-16"><a href="#cb2-16"></a></span>
+<span id="cb2-17"><a href="#cb2-17"></a> <span class="at">@PcodeUserop</span></span>
+<span id="cb2-18"><a href="#cb2-18"></a> <span class="kw">public</span> SleighPcodeUseropDefinition <span class="fu">__libc_strnlen_generic</span><span class="op">(</span>BuilderStage1 builder<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb2-19"><a href="#cb2-19"></a> <span class="cf">return</span> builder<span class="op">.</span><span class="fu">params</span><span class="op">(</span><span class="st">&quot;str&quot;</span><span class="op">,</span> <span class="st">&quot;maxlen&quot;</span><span class="op">).</span><span class="fu">body</span><span class="op">(</span>_ <span class="op">-&gt;</span> <span class="st">&quot;&quot;&quot;</span></span>
+<span id="cb2-20"><a href="#cb2-20"></a> local result <span class="op">=</span> <span class="dv">0</span><span class="op">;</span></span>
+<span id="cb2-21"><a href="#cb2-21"></a> <span class="op">&lt;</span>loop<span class="op">&gt;</span></span>
+<span id="cb2-22"><a href="#cb2-22"></a> <span class="cf">if</span> <span class="op">(*:</span><span class="dv">1</span> <span class="op">(</span>str<span class="op">+</span>result<span class="op">)</span> <span class="op">==</span> <span class="dv">0</span> <span class="op">||</span> result <span class="op">&gt;=</span> maxlen<span class="op">)</span> <span class="cf">goto</span> <span class="op">&lt;</span>exit<span class="op">&gt;;</span></span>
+<span id="cb2-23"><a href="#cb2-23"></a> result <span class="op">=</span> result <span class="op">+</span> <span class="dv">1</span><span class="op">;</span></span>
+<span id="cb2-24"><a href="#cb2-24"></a> <span class="cf">goto</span> <span class="op">&lt;</span>loop<span class="op">&gt;;</span></span>
+<span id="cb2-25"><a href="#cb2-25"></a> <span class="op">&lt;</span>exit<span class="op">&gt;</span></span>
+<span id="cb2-26"><a href="#cb2-26"></a> __op_output <span class="op">=</span> result<span class="op">;</span></span>
+<span id="cb2-27"><a href="#cb2-27"></a> <span class="st">&quot;&quot;&quot;).build();</span></span>
+<span id="cb2-28"><a href="#cb2-28"></a> <span class="op">}</span></span>
+<span id="cb2-29"><a href="#cb2-29"></a><span class="op">}</span></span></code></pre></div>
+<p>Each userop implementation is still annotated with
+<code>@PcodeUserop</code>; however, the return type
+<code>SleighPcodeUseropDefinition</code> tells the framework the userop
+is not a run-time callback, but a factory method for Sleigh source code.
+The builder provides a fluent style for specifying the different forms,
+parameters, and bodies of the userop. The examples above are fairly
+simple.</p>
+<p>The <code>params(...)</code> call indicates the number and names of
+parameters. The <code>body(...)</code> call generates the Sleigh source
+for the userop, typically expressed using a lambda. The lambda takes
+<code>List&lt;Varnode&gt;</code> and returns a <code>String</code> of
+Sleigh source. Upon encountering a callother to this userop, the
+emulator invokes the lambda, giving the actual varnode arguments, and
+executes the generated Sleigh. The arguments are often ignored, because
+the Sleigh source can refer to them by the names given in
+<code>params(...)</code>. Finally, we call <code>build()</code> to
+create the userop definition and return it.</p>
+<p>Overloading is possible, but we discuss that later. The
+<code>__libc_strnlen</code> userop delegates to
+<code>__libc_strnlen_generic</code>, which in turn implements
+<code>strnlen</code> naively. It loops from 0 to maxlen until it finds a
+zero. Note that the generic userop does not refer to any x86-specific
+registers.</p>
+<p>Userops can refer to any other userop defined either by the
+language’s Sleigh spec file, by the userop library, or by any other
+userop library composed with it. Arguments (inputs) and the output
+varnodes are passed by reference. Technically, userops can read and
+write to any of them freely, but conventionally, they should read only
+from inputs and write only to the output. The output varnode is named
+<code>__op_output</code>. The input varnode names are specified in the
+call to <code>params()</code>. The compiled result is as if those
+varnodes were substituted for their arguments. Note that expressions are
+given intermediate unique varnodes. When used as a userop input
+argument, the expression is evaluated once, then that temporary varnode
+is passed. Thus, writing to an input risks undefined behavior.
+Conventionally, userops should write to <code>__op_output</code> exactly
+once, at or near the end of the userop.</p>
+<p>With is mind, we re-examine the definition of
+<code>__libc_strnlen</code>:</p>
+<div class="sourceCode" id="cb3"><pre
+class="sourceCode sleigh"><code class="sourceCode sleighsyntax"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>RAX = __libc_strnlen_generic(RDI, RSI);</span></code></pre></div>
+<p>It implements <code>strnlen</code> for the System V ABI by naming the
+appropriate register for each parameter and return value. (A more
+sophisticated implementation of this library could take a
+<code>CompilerSpec</code> and/or calling convention argument in its
+constructor to generate the appropriate register names.) Essentially,
+the generic parameter names (and <code>__op_output</code>) become
+aliased to the register names. The generated p-code will be exactly the
+same as if it had been defined:</p>
+<div class="sourceCode" id="cb4"><pre
+class="sourceCode sleigh"><code class="sourceCode sleighsyntax"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>local result = <span class="dv">0</span>;</span>
+<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>&lt;<span class="at">loop</span>&gt;</span>
+<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="cf">if</span> (*:<span class="dv">1</span> (RDI+result) == <span class="dv">0</span> || result &gt;= RSI) <span class="cf">goto</span> &lt;<span class="at">exit</span>&gt;;</span>
+<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a>result = result + <span class="dv">1</span>;</span>
+<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a><span class="cf">goto</span> &lt;<span class="at">loop</span>&gt;;</span>
+<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>&lt;<span class="at">exit</span>&gt;</span>
+<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a>RAX = result;</span></code></pre></div>
+<section id="overloading" class="level4">
+<h4>Overloading</h4>
+<p>Two kinds of overloading are possible:</p>
+<ol type="1">
+<li>The userop has multiple forms, each having a different number of
+parameters</li>
+<li>A single form’s implementation depends on the size of at least one
+varnode argument</li>
+</ol>
+<p>The first kind is handled using the <code>overload()</code> method on
+the builder and then repeating the <code>params().body()</code> sequence
+for each form. For example</p>
+<div class="sourceCode" id="cb5"><pre
+class="sourceCode java"><code class="sourceCode java"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="cf">return</span> builder<span class="op">.</span><span class="fu">params</span><span class="op">(</span><span class="st">&quot;a&quot;</span><span class="op">).</span><span class="fu">body</span><span class="op">(</span>args <span class="op">-&gt;</span> <span class="st">&quot;&quot;&quot;</span></span>
+<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">...</span></span>
+<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a> <span class="st">&quot;&quot;&quot;).overload().params(&quot;</span>a<span class="st">&quot;, &quot;</span>b<span class="st">&quot;).body(args -&gt; &quot;&quot;&quot;</span></span>
+<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">...</span></span>
+<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a> <span class="st">&quot;&quot;&quot;).build();</span></span></code></pre></div>
+<p>The second kind is handled by inspecting the actual argument list in
+the lambda expression. This can often be accomplished using a
+<code>switch</code> expression on the size of a varnode, e.g.:</p>
+<div class="sourceCode" id="cb6"><pre
+class="sourceCode java"><code class="sourceCode java"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="cf">return</span> builder<span class="op">.</span><span class="fu">params</span><span class="op">(</span><span class="st">&quot;n&quot;</span><span class="op">).</span><span class="fu">body</span><span class="op">(</span>a <span class="op">-&gt;</span> <span class="cf">switch</span><span class="op">(</span>a<span class="op">.</span><span class="fu">get</span><span class="op">(</span><span class="dv">0</span><span class="op">).</span><span class="fu">getSize</span><span class="op">())</span> <span class="op">{</span></span>
+<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a> <span class="cf">case</span> <span class="dv">4</span> <span class="op">-&gt;</span> <span class="st">&quot;__op_output = sin_float(n);&quot;</span><span class="op">;</span></span>
+<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a> <span class="cf">case</span> <span class="dv">8</span> <span class="op">-&gt;</span> <span class="st">&quot;__op_output = sin_double(n);&quot;</span><span class="op">;</span></span>
+<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="op">}).</span><span class="fu">build</span><span class="op">();</span></span></code></pre></div>
+<p>In this example, we select between a single-precision and
+double-precision <code>sin</code> operation, based on the size of the
+input varnode. This pattern of delegating to size-specific userops is
+common, and those userops can be Java callbacks. Both kinds of
+overloading may be applied to the same userop definition.</p>
+</section>
</section>
<section id="modeling-by-structured-sleigh" class="level3">
<h3>Modeling by Structured Sleigh</h3>
-<p>The disadvantage to pre-compiled p-code is all the boilerplate and
-manual handling of Sleigh compilation. Additionally, when stubbing C
-functions, you have to be mindful of the types, and things may get
-complicated enough that you pine for more C-like control structures. The
-same library can be implemented using an incubating feature we call
-<em>Structured Sleigh</em>:</p>
-<div class="sourceCode" id="cb3"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb3-1"><a href="#cb3-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> StructuredStdLibPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span></span>
-<span id="cb3-2"><a href="#cb3-2"></a> <span class="kw">extends</span> AnnotatedPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb3-3"><a href="#cb3-3"></a> <span class="kw">public</span> <span class="fu">StructuredStdLibPcodeUseropLibrary</span><span class="op">(</span>CompilerSpec cs<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb3-4"><a href="#cb3-4"></a> <span class="kw">new</span> <span class="fu">MyStructuredPart</span><span class="op">(</span>cs<span class="op">).</span><span class="fu">generate</span><span class="op">(</span>ops<span class="op">);</span></span>
-<span id="cb3-5"><a href="#cb3-5"></a> <span class="op">}</span></span>
-<span id="cb3-6"><a href="#cb3-6"></a></span>
-<span id="cb3-7"><a href="#cb3-7"></a> <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> MyStructuredPart <span class="kw">extends</span> StructuredSleigh <span class="op">{</span></span>
-<span id="cb3-8"><a href="#cb3-8"></a> <span class="kw">protected</span> <span class="fu">MyStructuredPart</span><span class="op">(</span>CompilerSpec cs<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb3-9"><a href="#cb3-9"></a> <span class="kw">super</span><span class="op">(</span>cs<span class="op">);</span></span>
-<span id="cb3-10"><a href="#cb3-10"></a> <span class="op">}</span></span>
-<span id="cb3-11"><a href="#cb3-11"></a></span>
-<span id="cb3-12"><a href="#cb3-12"></a> <span class="at">@StructuredUserop</span></span>
-<span id="cb3-13"><a href="#cb3-13"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__x86_64_RET</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb3-14"><a href="#cb3-14"></a> Var RSP <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RSP&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;void **&quot;</span><span class="op">));</span></span>
-<span id="cb3-15"><a href="#cb3-15"></a> Var RIP <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RIP&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;void *&quot;</span><span class="op">));</span></span>
-<span id="cb3-16"><a href="#cb3-16"></a> RIP<span class="op">.</span><span class="fu">set</span><span class="op">(</span>RSP<span class="op">.</span><span class="fu">deref</span><span class="op">());</span></span>
-<span id="cb3-17"><a href="#cb3-17"></a> RSP<span class="op">.</span><span class="fu">addiTo</span><span class="op">(</span><span class="dv">8</span><span class="op">);</span></span>
-<span id="cb3-18"><a href="#cb3-18"></a> <span class="fu">_return</span><span class="op">(</span>RIP<span class="op">);</span></span>
-<span id="cb3-19"><a href="#cb3-19"></a> <span class="op">}</span></span>
-<span id="cb3-20"><a href="#cb3-20"></a></span>
-<span id="cb3-21"><a href="#cb3-21"></a> <span class="at">@StructuredUserop</span></span>
-<span id="cb3-22"><a href="#cb3-22"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__libc_strlen</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb3-23"><a href="#cb3-23"></a> Var result <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RAX&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;long&quot;</span><span class="op">));</span></span>
-<span id="cb3-24"><a href="#cb3-24"></a> Var str <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RDI&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;char *&quot;</span><span class="op">));</span></span>
-<span id="cb3-25"><a href="#cb3-25"></a> Var maxlen <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RSI&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;long&quot;</span><span class="op">));</span></span>
-<span id="cb3-26"><a href="#cb3-26"></a></span>
-<span id="cb3-27"><a href="#cb3-27"></a> <span class="fu">_for</span><span class="op">(</span>result<span class="op">.</span><span class="fu">set</span><span class="op">(</span><span class="dv">0</span><span class="op">),</span> result<span class="op">.</span><span class="fu">ltiu</span><span class="op">(</span>maxlen<span class="op">).</span><span class="fu">andb</span><span class="op">(</span>str<span class="op">.</span><span class="fu">index</span><span class="op">(</span>result<span class="op">).</span><span class="fu">deref</span><span class="op">().</span><span class="fu">eq</span><span class="op">(</span><span class="dv">0</span><span class="op">)),</span></span>
-<span id="cb3-28"><a href="#cb3-28"></a> result<span class="op">.</span><span class="fu">inc</span><span class="op">(),</span> <span class="op">()</span> <span class="op">-&gt;</span> <span class="op">{</span></span>
-<span id="cb3-29"><a href="#cb3-29"></a> <span class="op">});</span></span>
-<span id="cb3-30"><a href="#cb3-30"></a> <span class="op">}</span></span>
-<span id="cb3-31"><a href="#cb3-31"></a> <span class="op">}</span></span>
-<span id="cb3-32"><a href="#cb3-32"></a><span class="op">}</span></span></code></pre></div>
+<p>When stubbing C functions, you have to be mindful of the types, and
+things may get complicated enough that you pine for more C-like control
+structures. The same library can be implemented using an incubating
+feature we call <em>Structured Sleigh</em>:</p>
+<div class="sourceCode" id="cb7"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb7-1"><a href="#cb7-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> StructuredStdLibPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span></span>
+<span id="cb7-2"><a href="#cb7-2"></a> <span class="kw">extends</span> AnnotatedPcodeUseropLibrary<span class="op">&lt;</span>T<span class="op">&gt;</span> <span class="op">{</span></span>
+<span id="cb7-3"><a href="#cb7-3"></a> <span class="kw">public</span> <span class="fu">StructuredStdLibPcodeUseropLibrary</span><span class="op">(</span>CompilerSpec cs<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb7-4"><a href="#cb7-4"></a> <span class="kw">new</span> <span class="fu">MyStructuredPart</span><span class="op">(</span>cs<span class="op">).</span><span class="fu">generate</span><span class="op">(</span>ops<span class="op">);</span></span>
+<span id="cb7-5"><a href="#cb7-5"></a> <span class="op">}</span></span>
+<span id="cb7-6"><a href="#cb7-6"></a></span>
+<span id="cb7-7"><a href="#cb7-7"></a> <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> MyStructuredPart <span class="kw">extends</span> StructuredSleigh <span class="op">{</span></span>
+<span id="cb7-8"><a href="#cb7-8"></a> <span class="kw">protected</span> <span class="fu">MyStructuredPart</span><span class="op">(</span>CompilerSpec cs<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb7-9"><a href="#cb7-9"></a> <span class="kw">super</span><span class="op">(</span>cs<span class="op">);</span></span>
+<span id="cb7-10"><a href="#cb7-10"></a> <span class="op">}</span></span>
+<span id="cb7-11"><a href="#cb7-11"></a></span>
+<span id="cb7-12"><a href="#cb7-12"></a> <span class="at">@StructuredUserop</span><span class="op">(</span>type <span class="op">=</span> <span class="st">&quot;undefined *&quot;</span><span class="op">)</span></span>
+<span id="cb7-13"><a href="#cb7-13"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__x86_64_POP</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb7-14"><a href="#cb7-14"></a> Var RSP <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RSP&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;undefined **&quot;</span><span class="op">));</span></span>
+<span id="cb7-15"><a href="#cb7-15"></a> Var result <span class="op">=</span> <span class="fu">temp</span><span class="op">(</span><span class="fu">type</span><span class="op">(</span><span class="st">&quot;undefined *&quot;</span><span class="op">));</span></span>
+<span id="cb7-16"><a href="#cb7-16"></a> result<span class="op">.</span><span class="fu">set</span><span class="op">(</span>RSP<span class="op">.</span><span class="fu">deref</span><span class="op">());</span></span>
+<span id="cb7-17"><a href="#cb7-17"></a> RSP<span class="op">.</span><span class="fu">addiTo</span><span class="op">(</span><span class="dv">8</span><span class="op">);</span></span>
+<span id="cb7-18"><a href="#cb7-18"></a> <span class="fu">_result</span><span class="op">(</span>result<span class="op">);</span></span>
+<span id="cb7-19"><a href="#cb7-19"></a> <span class="op">}</span></span>
+<span id="cb7-20"><a href="#cb7-20"></a></span>
+<span id="cb7-21"><a href="#cb7-21"></a> <span class="at">@StructuredUserop</span></span>
+<span id="cb7-22"><a href="#cb7-22"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">__libc_strnlen</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb7-23"><a href="#cb7-23"></a> Var result <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RAX&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;long&quot;</span><span class="op">));</span></span>
+<span id="cb7-24"><a href="#cb7-24"></a> Var str <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RDI&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;char *&quot;</span><span class="op">));</span></span>
+<span id="cb7-25"><a href="#cb7-25"></a> Var maxlen <span class="op">=</span> <span class="fu">lang</span><span class="op">(</span><span class="st">&quot;RSI&quot;</span><span class="op">,</span> <span class="fu">type</span><span class="op">(</span><span class="st">&quot;long&quot;</span><span class="op">));</span></span>
+<span id="cb7-26"><a href="#cb7-26"></a></span>
+<span id="cb7-27"><a href="#cb7-27"></a> RVal inBounds <span class="op">=</span> result<span class="op">.</span><span class="fu">ltiu</span><span class="op">(</span>maxlen<span class="op">);</span></span>
+<span id="cb7-28"><a href="#cb7-28"></a> RVal notTerm <span class="op">=</span> str<span class="op">.</span><span class="fu">index</span><span class="op">(</span>result<span class="op">).</span><span class="fu">deref</span><span class="op">().</span><span class="fu">neq</span><span class="op">(</span><span class="dv">0</span><span class="op">);</span></span>
+<span id="cb7-29"><a href="#cb7-29"></a> <span class="fu">_for</span><span class="op">(</span>result<span class="op">.</span><span class="fu">set</span><span class="op">(</span><span class="dv">0</span><span class="op">),</span> inBounds<span class="op">.</span><span class="fu">andb</span><span class="op">(</span>notTerm<span class="op">),</span> result<span class="op">.</span><span class="fu">inc</span><span class="op">(),</span> <span class="op">()</span> <span class="op">-&gt;</span> <span class="op">{</span></span>
+<span id="cb7-30"><a href="#cb7-30"></a> <span class="op">});</span></span>
+<span id="cb7-31"><a href="#cb7-31"></a> <span class="op">}</span></span>
+<span id="cb7-32"><a href="#cb7-32"></a> <span class="op">}</span></span>
+<span id="cb7-33"><a href="#cb7-33"></a><span class="op">}</span></span></code></pre></div>
<p>This is about as succinct as we can get specifying p-code behaviors
in Java. While these may appear like callbacks into Java methods that
use a special API for state manipulation, that is not entirely accurate.
@@ -400,12 +459,12 @@ sense, Structured Sleigh is a DSL hosted in Java….</p>
using method invocations. Another disadvantage is the dependence on a
compiler spec for type resolution. Structured Sleigh is not the best
suited for all circumstances, e.g., the implementation of
-<code>__x86_64_RET</code> is odd to express. Arguably, there is no real
+<code>__x86_64_POP</code> is odd to express. Arguably, there is no real
need to ascribe high-level types to <code>RSP</code> and
<code>RIP</code> when expressing low-level operations. Luckily, these
-implementation techniques can be mixed. A single library can implement
-the <code>RET</code> using pre-compiled Sleigh, but <code>strlen</code>
-using Structured Sleigh.</p>
+implementation techniques can be mixed. A single library could implement
+the <code>POP</code> using (raw) Sleigh, but <code>strnlen</code> using
+Structured Sleigh.</p>
</section>
<section id="modeling-system-calls" class="level3">
<h3>Modeling System Calls</h3>
@@ -429,76 +488,77 @@ to provide additional system calls.</p>
<h3>Using Custom Userop Libraries</h3>
<p>The use of a custom library in a stand-alone emulation script is
pretty straightforward:</p>
-<div class="sourceCode" id="cb4"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb4-1"><a href="#cb4-1"></a><span class="kw">public</span> <span class="kw">class</span> CustomLibraryScript <span class="kw">extends</span> GhidraScript <span class="op">{</span></span>
-<span id="cb4-2"><a href="#cb4-2"></a> <span class="at">@Override</span></span>
-<span id="cb4-3"><a href="#cb4-3"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
-<span id="cb4-4"><a href="#cb4-4"></a> PcodeEmulator emu <span class="op">=</span> <span class="kw">new</span> <span class="fu">PcodeEmulator</span><span class="op">(</span>currentProgram<span class="op">.</span><span class="fu">getLanguage</span><span class="op">())</span> <span class="op">{</span></span>
-<span id="cb4-5"><a href="#cb4-5"></a> <span class="at">@Override</span></span>
-<span id="cb4-6"><a href="#cb4-6"></a> <span class="kw">protected</span> PcodeUseropLibrary<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> <span class="fu">createUseropLibrary</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb4-7"><a href="#cb4-7"></a> <span class="cf">return</span> <span class="kw">super</span><span class="op">.</span><span class="fu">createUseropLibrary</span><span class="op">()</span></span>
-<span id="cb4-8"><a href="#cb4-8"></a> <span class="op">.</span><span class="fu">compose</span><span class="op">(</span><span class="kw">new</span> ModelingScript<span class="op">.</span><span class="fu">StructuredStdLibPcodeUseropLibrary</span><span class="op">&lt;&gt;(</span></span>
-<span id="cb4-9"><a href="#cb4-9"></a> currentProgram<span class="op">.</span><span class="fu">getCompilerSpec</span><span class="op">()));</span></span>
-<span id="cb4-10"><a href="#cb4-10"></a> <span class="op">}</span></span>
-<span id="cb4-11"><a href="#cb4-11"></a> <span class="op">};</span></span>
-<span id="cb4-12"><a href="#cb4-12"></a> emu<span class="op">.</span><span class="fu">inject</span><span class="op">(</span>currentAddress<span class="op">,</span> <span class="st">&quot;&quot;&quot;</span></span>
-<span id="cb4-13"><a href="#cb4-13"></a> <span class="fu">__libc_strlen</span><span class="op">();</span></span>
-<span id="cb4-14"><a href="#cb4-14"></a> <span class="fu">__X86_64_RET</span><span class="op">();</span></span>
-<span id="cb4-15"><a href="#cb4-15"></a> <span class="st">&quot;&quot;&quot;);</span></span>
-<span id="cb4-16"><a href="#cb4-16"></a></span>
-<span id="cb4-17"><a href="#cb4-17"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the emulator&#39;s memory from the current program</span></span>
-<span id="cb4-18"><a href="#cb4-18"></a></span>
-<span id="cb4-19"><a href="#cb4-19"></a> PcodeThread<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> thread <span class="op">=</span> emu<span class="op">.</span><span class="fu">newThread</span><span class="op">();</span></span>
-<span id="cb4-20"><a href="#cb4-20"></a></span>
-<span id="cb4-21"><a href="#cb4-21"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the thread&#39;s registers</span></span>
-<span id="cb4-22"><a href="#cb4-22"></a></span>
-<span id="cb4-23"><a href="#cb4-23"></a> <span class="cf">while</span> <span class="op">(</span><span class="kw">true</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb4-24"><a href="#cb4-24"></a> monitor<span class="op">.</span><span class="fu">checkCancelled</span><span class="op">();</span></span>
-<span id="cb4-25"><a href="#cb4-25"></a> thread<span class="op">.</span><span class="fu">stepInstruction</span><span class="op">(</span><span class="dv">100</span><span class="op">);</span></span>
-<span id="cb4-26"><a href="#cb4-26"></a> <span class="op">}</span></span>
-<span id="cb4-27"><a href="#cb4-27"></a> <span class="op">}</span></span>
-<span id="cb4-28"><a href="#cb4-28"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb8"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb8-1"><a href="#cb8-1"></a><span class="kw">public</span> <span class="kw">class</span> CustomLibraryScript <span class="kw">extends</span> GhidraScript <span class="op">{</span></span>
+<span id="cb8-2"><a href="#cb8-2"></a> <span class="at">@Override</span></span>
+<span id="cb8-3"><a href="#cb8-3"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
+<span id="cb8-4"><a href="#cb8-4"></a> PcodeEmulator emu <span class="op">=</span> <span class="kw">new</span> <span class="fu">PcodeEmulator</span><span class="op">(</span>currentProgram<span class="op">.</span><span class="fu">getLanguage</span><span class="op">())</span> <span class="op">{</span></span>
+<span id="cb8-5"><a href="#cb8-5"></a> <span class="at">@Override</span></span>
+<span id="cb8-6"><a href="#cb8-6"></a> <span class="kw">protected</span> PcodeUseropLibrary<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> <span class="fu">createUseropLibrary</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb8-7"><a href="#cb8-7"></a> <span class="cf">return</span> <span class="kw">super</span><span class="op">.</span><span class="fu">createUseropLibrary</span><span class="op">()</span></span>
+<span id="cb8-8"><a href="#cb8-8"></a> <span class="op">.</span><span class="fu">compose</span><span class="op">(</span><span class="kw">new</span> ModelingScript<span class="op">.</span><span class="fu">StructuredStdLibPcodeUseropLibrary</span><span class="op">&lt;&gt;(</span></span>
+<span id="cb8-9"><a href="#cb8-9"></a> currentProgram<span class="op">.</span><span class="fu">getCompilerSpec</span><span class="op">()));</span></span>
+<span id="cb8-10"><a href="#cb8-10"></a> <span class="op">}</span></span>
+<span id="cb8-11"><a href="#cb8-11"></a> <span class="op">};</span></span>
+<span id="cb8-12"><a href="#cb8-12"></a> emu<span class="op">.</span><span class="fu">inject</span><span class="op">(</span>currentAddress<span class="op">,</span> <span class="st">&quot;&quot;&quot;</span></span>
+<span id="cb8-13"><a href="#cb8-13"></a> <span class="fu">__libc_strlen</span><span class="op">();</span></span>
+<span id="cb8-14"><a href="#cb8-14"></a> RIP <span class="op">=</span> <span class="fu">__X86_64_POP</span><span class="op">();</span></span>
+<span id="cb8-15"><a href="#cb8-15"></a> <span class="cf">return</span> <span class="op">[</span>RIP<span class="op">];</span></span>
+<span id="cb8-16"><a href="#cb8-16"></a> <span class="st">&quot;&quot;&quot;);</span></span>
+<span id="cb8-17"><a href="#cb8-17"></a></span>
+<span id="cb8-18"><a href="#cb8-18"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the emulator&#39;s memory from the current program</span></span>
+<span id="cb8-19"><a href="#cb8-19"></a></span>
+<span id="cb8-20"><a href="#cb8-20"></a> PcodeThread<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> thread <span class="op">=</span> emu<span class="op">.</span><span class="fu">newThread</span><span class="op">();</span></span>
+<span id="cb8-21"><a href="#cb8-21"></a></span>
+<span id="cb8-22"><a href="#cb8-22"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the thread&#39;s registers</span></span>
+<span id="cb8-23"><a href="#cb8-23"></a></span>
+<span id="cb8-24"><a href="#cb8-24"></a> <span class="cf">while</span> <span class="op">(</span><span class="kw">true</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb8-25"><a href="#cb8-25"></a> monitor<span class="op">.</span><span class="fu">checkCancelled</span><span class="op">();</span></span>
+<span id="cb8-26"><a href="#cb8-26"></a> thread<span class="op">.</span><span class="fu">stepInstruction</span><span class="op">(</span><span class="dv">100</span><span class="op">);</span></span>
+<span id="cb8-27"><a href="#cb8-27"></a> <span class="op">}</span></span>
+<span id="cb8-28"><a href="#cb8-28"></a> <span class="op">}</span></span>
+<span id="cb8-29"><a href="#cb8-29"></a><span class="op">}</span></span></code></pre></div>
<p>The key is to override <code>createUseropLibrary()</code> in an
-anonymous extension of the <code>PcodeEmulator</code>. It is polite to
-compose your library with the one already provided by the super class,
-lest you remove userops and cause unexpected crashes later. For the sake
-of demonstration, we have included an injection that uses the custom
+extension of the <code>PcodeEmulator</code>. It is polite to compose
+your library with the one already provided by the super class, lest you
+remove userops and cause unexpected crashes later. For the sake of
+demonstration, we have included an injection that uses the custom
library, and we have included a monitored loop to execute a single
thread indefinitely. The initialization of the machine and its one
thread is left to the script writer. The emulation <em>is not</em>
implicitly associated with the program! You must copy the program image
-into its state, and you should choose a different location for the
+into its state, and you should choose an appropriate location for the
injection. Refer to the example scripts in Ghidra’s
<code>SystemEmulation</code> module.</p>
<p>If you would like to (temporarily) override the GUI with a custom
userop library, you can by setting the GUI’s emulator factory:</p>
-<div class="sourceCode" id="cb5"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb5-1"><a href="#cb5-1"></a><span class="kw">public</span> <span class="kw">class</span> InstallCustomLibraryScript <span class="kw">extends</span> GhidraScript <span class="kw">implements</span> FlatDebuggerAPI <span class="op">{</span></span>
-<span id="cb5-2"><a href="#cb5-2"></a> <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> CustomPcodeEmulator <span class="kw">extends</span> PcodeEmulator <span class="op">{</span></span>
-<span id="cb5-3"><a href="#cb5-3"></a> <span class="kw">private</span> <span class="fu">CustomPcodeEmulator</span><span class="op">(</span>Language language<span class="op">,</span> PcodeEmulationCallbacks<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb5-4"><a href="#cb5-4"></a> <span class="kw">super</span><span class="op">(</span>language<span class="op">,</span> cb<span class="op">);</span></span>
-<span id="cb5-5"><a href="#cb5-5"></a> <span class="op">}</span></span>
-<span id="cb5-6"><a href="#cb5-6"></a></span>
-<span id="cb5-7"><a href="#cb5-7"></a> <span class="at">@Override</span></span>
-<span id="cb5-8"><a href="#cb5-8"></a> <span class="kw">protected</span> PcodeUseropLibrary<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> <span class="fu">createUseropLibrary</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb5-9"><a href="#cb5-9"></a> <span class="cf">return</span> <span class="kw">super</span><span class="op">.</span><span class="fu">createUseropLibrary</span><span class="op">()</span></span>
-<span id="cb5-10"><a href="#cb5-10"></a> <span class="op">.</span><span class="fu">compose</span><span class="op">(</span><span class="kw">new</span> ModelingScript<span class="op">.</span><span class="fu">SleighStdLibPcodeUseropLibrary</span><span class="op">&lt;&gt;(</span><span class="fu">getLanguage</span><span class="op">()));</span></span>
-<span id="cb5-11"><a href="#cb5-11"></a> <span class="op">}</span></span>
-<span id="cb5-12"><a href="#cb5-12"></a> <span class="op">}</span></span>
-<span id="cb5-13"><a href="#cb5-13"></a></span>
-<span id="cb5-14"><a href="#cb5-14"></a> <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> CustomBytesDebuggerPcodeEmulatorFactory</span>
-<span id="cb5-15"><a href="#cb5-15"></a> <span class="kw">extends</span> DefaultEmulatorFactory <span class="op">{</span></span>
-<span id="cb5-16"><a href="#cb5-16"></a> <span class="at">@Override</span></span>
-<span id="cb5-17"><a href="#cb5-17"></a> <span class="kw">public</span> PcodeMachine<span class="op">&lt;?&gt;</span> <span class="fu">create</span><span class="op">(</span>PcodeDebuggerAccess access<span class="op">,</span> <span class="bu">Writer</span> writer<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb5-18"><a href="#cb5-18"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">CustomPcodeEmulator</span><span class="op">(</span>access<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span> writer<span class="op">.</span><span class="fu">callbacks</span><span class="op">());</span></span>
-<span id="cb5-19"><a href="#cb5-19"></a> <span class="op">}</span></span>
-<span id="cb5-20"><a href="#cb5-20"></a> <span class="op">}</span></span>
-<span id="cb5-21"><a href="#cb5-21"></a></span>
-<span id="cb5-22"><a href="#cb5-22"></a> <span class="at">@Override</span></span>
-<span id="cb5-23"><a href="#cb5-23"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
-<span id="cb5-24"><a href="#cb5-24"></a> <span class="fu">getEmulationService</span><span class="op">().</span><span class="fu">setEmulatorFactory</span><span class="op">(</span><span class="kw">new</span> <span class="fu">CustomBytesDebuggerPcodeEmulatorFactory</span><span class="op">());</span></span>
-<span id="cb5-25"><a href="#cb5-25"></a> <span class="op">}</span></span>
-<span id="cb5-26"><a href="#cb5-26"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb9"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb9-1"><a href="#cb9-1"></a><span class="kw">public</span> <span class="kw">class</span> InstallCustomLibraryScript <span class="kw">extends</span> GhidraScript <span class="kw">implements</span> FlatDebuggerAPI <span class="op">{</span></span>
+<span id="cb9-2"><a href="#cb9-2"></a> <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> CustomPcodeEmulator <span class="kw">extends</span> PcodeEmulator <span class="op">{</span></span>
+<span id="cb9-3"><a href="#cb9-3"></a> <span class="kw">private</span> <span class="fu">CustomPcodeEmulator</span><span class="op">(</span>Language language<span class="op">,</span> PcodeEmulationCallbacks<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb9-4"><a href="#cb9-4"></a> <span class="kw">super</span><span class="op">(</span>language<span class="op">,</span> cb<span class="op">);</span></span>
+<span id="cb9-5"><a href="#cb9-5"></a> <span class="op">}</span></span>
+<span id="cb9-6"><a href="#cb9-6"></a></span>
+<span id="cb9-7"><a href="#cb9-7"></a> <span class="at">@Override</span></span>
+<span id="cb9-8"><a href="#cb9-8"></a> <span class="kw">protected</span> PcodeUseropLibrary<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> <span class="fu">createUseropLibrary</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb9-9"><a href="#cb9-9"></a> <span class="cf">return</span> <span class="kw">super</span><span class="op">.</span><span class="fu">createUseropLibrary</span><span class="op">()</span></span>
+<span id="cb9-10"><a href="#cb9-10"></a> <span class="op">.</span><span class="fu">compose</span><span class="op">(</span><span class="kw">new</span> ModelingScript<span class="op">.</span><span class="fu">SleighStdLibPcodeUseropLibrary</span><span class="op">&lt;&gt;());</span></span>
+<span id="cb9-11"><a href="#cb9-11"></a> <span class="op">}</span></span>
+<span id="cb9-12"><a href="#cb9-12"></a> <span class="op">}</span></span>
+<span id="cb9-13"><a href="#cb9-13"></a></span>
+<span id="cb9-14"><a href="#cb9-14"></a> <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> CustomBytesDebuggerPcodeEmulatorFactory</span>
+<span id="cb9-15"><a href="#cb9-15"></a> <span class="kw">extends</span> DefaultEmulatorFactory <span class="op">{</span></span>
+<span id="cb9-16"><a href="#cb9-16"></a> <span class="at">@Override</span></span>
+<span id="cb9-17"><a href="#cb9-17"></a> <span class="kw">public</span> PcodeMachine<span class="op">&lt;?&gt;</span> <span class="fu">create</span><span class="op">(</span>PcodeDebuggerAccess access<span class="op">,</span> <span class="bu">Writer</span> writer<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb9-18"><a href="#cb9-18"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">CustomPcodeEmulator</span><span class="op">(</span>access<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span> writer<span class="op">.</span><span class="fu">callbacks</span><span class="op">());</span></span>
+<span id="cb9-19"><a href="#cb9-19"></a> <span class="op">}</span></span>
+<span id="cb9-20"><a href="#cb9-20"></a> <span class="op">}</span></span>
+<span id="cb9-21"><a href="#cb9-21"></a></span>
+<span id="cb9-22"><a href="#cb9-22"></a> <span class="at">@Override</span></span>
+<span id="cb9-23"><a href="#cb9-23"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
+<span id="cb9-24"><a href="#cb9-24"></a> <span class="fu">getEmulationService</span><span class="op">().</span><span class="fu">setEmulatorFactory</span><span class="op">(</span><span class="kw">new</span> <span class="fu">CustomBytesDebuggerPcodeEmulatorFactory</span><span class="op">());</span></span>
+<span id="cb9-25"><a href="#cb9-25"></a> <span class="op">}</span></span>
+<span id="cb9-26"><a href="#cb9-26"></a><span class="op">}</span></span></code></pre></div>
<p>This will make your custom userops available in Sleigh injections.
<strong>NOTE</strong>: There is currently no way to introduce custom
userops to Watches or the Go To dialog.</p>
@@ -536,51 +596,51 @@ but what is necessary to illustrate the implementation.</p>
<p>If it is not already provided to you by your dependencies, you will
need to devise the actual model. These need not extend from nor
implement any Ghidra-specific interface, but they can.</p>
-<div class="sourceCode" id="cb6"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb6-1"><a href="#cb6-1"></a><span class="kw">public</span> <span class="kw">class</span> ModelingScript <span class="kw">extends</span> GhidraScript <span class="op">{</span></span>
-<span id="cb6-2"><a href="#cb6-2"></a> <span class="kw">interface</span> Expr <span class="op">{</span></span>
-<span id="cb6-3"><a href="#cb6-3"></a> <span class="dt">int</span> <span class="fu">size</span><span class="op">();</span></span>
-<span id="cb6-4"><a href="#cb6-4"></a> <span class="op">}</span></span>
-<span id="cb6-5"><a href="#cb6-5"></a></span>
-<span id="cb6-6"><a href="#cb6-6"></a> <span class="kw">interface</span> UnExpr <span class="kw">extends</span> Expr <span class="op">{</span></span>
-<span id="cb6-7"><a href="#cb6-7"></a> Expr <span class="fu">u</span><span class="op">();</span></span>
-<span id="cb6-8"><a href="#cb6-8"></a> <span class="op">}</span></span>
-<span id="cb6-9"><a href="#cb6-9"></a></span>
-<span id="cb6-10"><a href="#cb6-10"></a> <span class="kw">interface</span> BinExpr <span class="kw">extends</span> Expr <span class="op">{</span></span>
-<span id="cb6-11"><a href="#cb6-11"></a> Expr <span class="fu">l</span><span class="op">();</span></span>
-<span id="cb6-12"><a href="#cb6-12"></a></span>
-<span id="cb6-13"><a href="#cb6-13"></a> Expr <span class="fu">r</span><span class="op">();</span></span>
-<span id="cb6-14"><a href="#cb6-14"></a> <span class="op">}</span></span>
-<span id="cb6-15"><a href="#cb6-15"></a></span>
-<span id="cb6-16"><a href="#cb6-16"></a> record <span class="fu">LitExpr</span><span class="op">(</span><span class="bu">BigInteger</span> val<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> Expr <span class="op">{}</span></span>
-<span id="cb6-17"><a href="#cb6-17"></a></span>
-<span id="cb6-18"><a href="#cb6-18"></a> record <span class="fu">VarExpr</span><span class="op">(</span>Varnode vn<span class="op">)</span> <span class="kw">implements</span> Expr <span class="op">{</span></span>
-<span id="cb6-19"><a href="#cb6-19"></a> <span class="kw">public</span> <span class="fu">VarExpr</span><span class="op">(</span>AddressSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb6-20"><a href="#cb6-20"></a> <span class="kw">this</span><span class="op">(</span>space<span class="op">.</span><span class="fu">getAddress</span><span class="op">(</span>offset<span class="op">),</span> size<span class="op">);</span></span>
-<span id="cb6-21"><a href="#cb6-21"></a> <span class="op">}</span></span>
-<span id="cb6-22"><a href="#cb6-22"></a></span>
-<span id="cb6-23"><a href="#cb6-23"></a> <span class="kw">public</span> <span class="fu">VarExpr</span><span class="op">(</span>Address address<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb6-24"><a href="#cb6-24"></a> <span class="kw">this</span><span class="op">(</span><span class="kw">new</span> <span class="fu">Varnode</span><span class="op">(</span>address<span class="op">,</span> size<span class="op">));</span></span>
-<span id="cb6-25"><a href="#cb6-25"></a> <span class="op">}</span></span>
-<span id="cb6-26"><a href="#cb6-26"></a></span>
-<span id="cb6-27"><a href="#cb6-27"></a> <span class="at">@Override</span></span>
-<span id="cb6-28"><a href="#cb6-28"></a> <span class="kw">public</span> <span class="dt">int</span> <span class="fu">size</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb6-29"><a href="#cb6-29"></a> <span class="cf">return</span> vn<span class="op">.</span><span class="fu">getSize</span><span class="op">();</span></span>
-<span id="cb6-30"><a href="#cb6-30"></a> <span class="op">}</span></span>
-<span id="cb6-31"><a href="#cb6-31"></a> <span class="op">}</span></span>
-<span id="cb6-32"><a href="#cb6-32"></a></span>
-<span id="cb6-33"><a href="#cb6-33"></a> record <span class="fu">InvExpr</span><span class="op">(</span>Expr u<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> UnExpr <span class="op">{}</span></span>
-<span id="cb6-34"><a href="#cb6-34"></a></span>
-<span id="cb6-35"><a href="#cb6-35"></a> record <span class="fu">AddExpr</span><span class="op">(</span>Expr l<span class="op">,</span> Expr r<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> BinExpr <span class="op">{}</span></span>
-<span id="cb6-36"><a href="#cb6-36"></a></span>
-<span id="cb6-37"><a href="#cb6-37"></a> record <span class="fu">SubExpr</span><span class="op">(</span>Expr l<span class="op">,</span> Expr r<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> BinExpr <span class="op">{}</span></span>
-<span id="cb6-38"><a href="#cb6-38"></a></span>
-<span id="cb6-39"><a href="#cb6-39"></a> <span class="at">@Override</span></span>
-<span id="cb6-40"><a href="#cb6-40"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
-<span id="cb6-41"><a href="#cb6-41"></a> <span class="co">// </span><span class="al">TODO</span><span class="co"> Auto-generated method stub</span></span>
-<span id="cb6-42"><a href="#cb6-42"></a></span>
-<span id="cb6-43"><a href="#cb6-43"></a> <span class="op">}</span></span>
-<span id="cb6-44"><a href="#cb6-44"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb10"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb10-1"><a href="#cb10-1"></a><span class="kw">public</span> <span class="kw">class</span> ModelingScript <span class="kw">extends</span> GhidraScript <span class="op">{</span></span>
+<span id="cb10-2"><a href="#cb10-2"></a> <span class="kw">interface</span> Expr <span class="op">{</span></span>
+<span id="cb10-3"><a href="#cb10-3"></a> <span class="dt">int</span> <span class="fu">size</span><span class="op">();</span></span>
+<span id="cb10-4"><a href="#cb10-4"></a> <span class="op">}</span></span>
+<span id="cb10-5"><a href="#cb10-5"></a></span>
+<span id="cb10-6"><a href="#cb10-6"></a> <span class="kw">interface</span> UnExpr <span class="kw">extends</span> Expr <span class="op">{</span></span>
+<span id="cb10-7"><a href="#cb10-7"></a> Expr <span class="fu">u</span><span class="op">();</span></span>
+<span id="cb10-8"><a href="#cb10-8"></a> <span class="op">}</span></span>
+<span id="cb10-9"><a href="#cb10-9"></a></span>
+<span id="cb10-10"><a href="#cb10-10"></a> <span class="kw">interface</span> BinExpr <span class="kw">extends</span> Expr <span class="op">{</span></span>
+<span id="cb10-11"><a href="#cb10-11"></a> Expr <span class="fu">l</span><span class="op">();</span></span>
+<span id="cb10-12"><a href="#cb10-12"></a></span>
+<span id="cb10-13"><a href="#cb10-13"></a> Expr <span class="fu">r</span><span class="op">();</span></span>
+<span id="cb10-14"><a href="#cb10-14"></a> <span class="op">}</span></span>
+<span id="cb10-15"><a href="#cb10-15"></a></span>
+<span id="cb10-16"><a href="#cb10-16"></a> record <span class="fu">LitExpr</span><span class="op">(</span><span class="bu">BigInteger</span> val<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> Expr <span class="op">{}</span></span>
+<span id="cb10-17"><a href="#cb10-17"></a></span>
+<span id="cb10-18"><a href="#cb10-18"></a> record <span class="fu">VarExpr</span><span class="op">(</span>Varnode vn<span class="op">)</span> <span class="kw">implements</span> Expr <span class="op">{</span></span>
+<span id="cb10-19"><a href="#cb10-19"></a> <span class="kw">public</span> <span class="fu">VarExpr</span><span class="op">(</span>AddressSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb10-20"><a href="#cb10-20"></a> <span class="kw">this</span><span class="op">(</span>space<span class="op">.</span><span class="fu">getAddress</span><span class="op">(</span>offset<span class="op">),</span> size<span class="op">);</span></span>
+<span id="cb10-21"><a href="#cb10-21"></a> <span class="op">}</span></span>
+<span id="cb10-22"><a href="#cb10-22"></a></span>
+<span id="cb10-23"><a href="#cb10-23"></a> <span class="kw">public</span> <span class="fu">VarExpr</span><span class="op">(</span>Address address<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb10-24"><a href="#cb10-24"></a> <span class="kw">this</span><span class="op">(</span><span class="kw">new</span> <span class="fu">Varnode</span><span class="op">(</span>address<span class="op">,</span> size<span class="op">));</span></span>
+<span id="cb10-25"><a href="#cb10-25"></a> <span class="op">}</span></span>
+<span id="cb10-26"><a href="#cb10-26"></a></span>
+<span id="cb10-27"><a href="#cb10-27"></a> <span class="at">@Override</span></span>
+<span id="cb10-28"><a href="#cb10-28"></a> <span class="kw">public</span> <span class="dt">int</span> <span class="fu">size</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb10-29"><a href="#cb10-29"></a> <span class="cf">return</span> vn<span class="op">.</span><span class="fu">getSize</span><span class="op">();</span></span>
+<span id="cb10-30"><a href="#cb10-30"></a> <span class="op">}</span></span>
+<span id="cb10-31"><a href="#cb10-31"></a> <span class="op">}</span></span>
+<span id="cb10-32"><a href="#cb10-32"></a></span>
+<span id="cb10-33"><a href="#cb10-33"></a> record <span class="fu">InvExpr</span><span class="op">(</span>Expr u<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> UnExpr <span class="op">{}</span></span>
+<span id="cb10-34"><a href="#cb10-34"></a></span>
+<span id="cb10-35"><a href="#cb10-35"></a> record <span class="fu">AddExpr</span><span class="op">(</span>Expr l<span class="op">,</span> Expr r<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> BinExpr <span class="op">{}</span></span>
+<span id="cb10-36"><a href="#cb10-36"></a></span>
+<span id="cb10-37"><a href="#cb10-37"></a> record <span class="fu">SubExpr</span><span class="op">(</span>Expr l<span class="op">,</span> Expr r<span class="op">,</span> <span class="dt">int</span> size<span class="op">)</span> <span class="kw">implements</span> BinExpr <span class="op">{}</span></span>
+<span id="cb10-38"><a href="#cb10-38"></a></span>
+<span id="cb10-39"><a href="#cb10-39"></a> <span class="at">@Override</span></span>
+<span id="cb10-40"><a href="#cb10-40"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
+<span id="cb10-41"><a href="#cb10-41"></a> <span class="co">// </span><span class="al">TODO</span><span class="co"> Auto-generated method stub</span></span>
+<span id="cb10-42"><a href="#cb10-42"></a></span>
+<span id="cb10-43"><a href="#cb10-43"></a> <span class="op">}</span></span>
+<span id="cb10-44"><a href="#cb10-44"></a><span class="op">}</span></span></code></pre></div>
<p>It should be fairly apparent how you could add more expression types
to complete the model. There is some odd nuance in the naming of p-code
operations, so do read the documentation carefully. If you are not
@@ -597,94 +657,94 @@ implementation can be an enumeration: one for big endian and one for
little endian. Rarely, it can be a singleton. Conventionally, you should
also include static methods for retrieving an instance by endianness or
processor language:</p>
-<div class="sourceCode" id="cb7"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb7-1"><a href="#cb7-1"></a><span class="kw">public</span> <span class="kw">enum</span> ExprPcodeArithmetic <span class="kw">implements</span> PcodeArithmetic<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb7-2"><a href="#cb7-2"></a> <span class="fu">BE</span><span class="op">(</span>Endian<span class="op">.</span><span class="fu">BIG</span><span class="op">),</span> <span class="fu">LE</span><span class="op">(</span>Endian<span class="op">.</span><span class="fu">LITTLE</span><span class="op">);</span></span>
-<span id="cb7-3"><a href="#cb7-3"></a></span>
-<span id="cb7-4"><a href="#cb7-4"></a> <span class="kw">public</span> <span class="dt">static</span> ExprPcodeArithmetic <span class="fu">forEndian</span><span class="op">(</span>Endian endian<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-5"><a href="#cb7-5"></a> <span class="cf">return</span> endian<span class="op">.</span><span class="fu">isBigEndian</span><span class="op">()</span> <span class="op">?</span> BE <span class="op">:</span> LE<span class="op">;</span></span>
-<span id="cb7-6"><a href="#cb7-6"></a> <span class="op">}</span></span>
-<span id="cb7-7"><a href="#cb7-7"></a></span>
-<span id="cb7-8"><a href="#cb7-8"></a> <span class="kw">public</span> <span class="dt">static</span> ExprPcodeArithmetic <span class="fu">forLanguage</span><span class="op">(</span>Language language<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-9"><a href="#cb7-9"></a> <span class="cf">return</span> language<span class="op">.</span><span class="fu">isBigEndian</span><span class="op">()</span> <span class="op">?</span> BE <span class="op">:</span> LE<span class="op">;</span></span>
-<span id="cb7-10"><a href="#cb7-10"></a> <span class="op">}</span></span>
-<span id="cb7-11"><a href="#cb7-11"></a></span>
-<span id="cb7-12"><a href="#cb7-12"></a> <span class="kw">private</span> <span class="dt">final</span> Endian endian<span class="op">;</span></span>
-<span id="cb7-13"><a href="#cb7-13"></a></span>
-<span id="cb7-14"><a href="#cb7-14"></a> <span class="kw">private</span> <span class="fu">ExprPcodeArithmetic</span><span class="op">(</span>Endian endian<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-15"><a href="#cb7-15"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">endian</span> <span class="op">=</span> endian<span class="op">;</span></span>
-<span id="cb7-16"><a href="#cb7-16"></a> <span class="op">}</span></span>
-<span id="cb7-17"><a href="#cb7-17"></a></span>
-<span id="cb7-18"><a href="#cb7-18"></a> <span class="at">@Override</span></span>
-<span id="cb7-19"><a href="#cb7-19"></a> <span class="kw">public</span> <span class="bu">Class</span><span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getDomain</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb7-20"><a href="#cb7-20"></a> <span class="cf">return</span> Expr<span class="op">.</span><span class="fu">class</span><span class="op">;</span></span>
-<span id="cb7-21"><a href="#cb7-21"></a> <span class="op">}</span></span>
-<span id="cb7-22"><a href="#cb7-22"></a></span>
-<span id="cb7-23"><a href="#cb7-23"></a> <span class="at">@Override</span></span>
-<span id="cb7-24"><a href="#cb7-24"></a> <span class="kw">public</span> Endian <span class="fu">getEndian</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb7-25"><a href="#cb7-25"></a> <span class="cf">return</span> endian<span class="op">;</span></span>
-<span id="cb7-26"><a href="#cb7-26"></a> <span class="op">}</span></span>
-<span id="cb7-27"><a href="#cb7-27"></a></span>
-<span id="cb7-28"><a href="#cb7-28"></a> <span class="at">@Override</span></span>
-<span id="cb7-29"><a href="#cb7-29"></a> <span class="kw">public</span> Expr <span class="fu">unaryOp</span><span class="op">(</span><span class="dt">int</span> opcode<span class="op">,</span> <span class="dt">int</span> sizeout<span class="op">,</span> <span class="dt">int</span> sizein1<span class="op">,</span> Expr in1<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-30"><a href="#cb7-30"></a> <span class="cf">return</span> <span class="cf">switch</span> <span class="op">(</span>opcode<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-31"><a href="#cb7-31"></a> <span class="cf">case</span> PcodeOp<span class="op">.</span><span class="fu">INT_NEGATE</span> <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">InvExpr</span><span class="op">(</span>in1<span class="op">,</span> sizeout<span class="op">);</span></span>
-<span id="cb7-32"><a href="#cb7-32"></a> <span class="kw">default</span> <span class="op">-&gt;</span> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">(</span>PcodeOp<span class="op">.</span><span class="fu">getMnemonic</span><span class="op">(</span>opcode<span class="op">));</span></span>
-<span id="cb7-33"><a href="#cb7-33"></a> <span class="op">};</span></span>
-<span id="cb7-34"><a href="#cb7-34"></a> <span class="op">}</span></span>
-<span id="cb7-35"><a href="#cb7-35"></a></span>
-<span id="cb7-36"><a href="#cb7-36"></a> <span class="at">@Override</span></span>
-<span id="cb7-37"><a href="#cb7-37"></a> <span class="kw">public</span> Expr <span class="fu">binaryOp</span><span class="op">(</span><span class="dt">int</span> opcode<span class="op">,</span> <span class="dt">int</span> sizeout<span class="op">,</span> <span class="dt">int</span> sizein1<span class="op">,</span> Expr in1<span class="op">,</span> <span class="dt">int</span> sizein2<span class="op">,</span></span>
-<span id="cb7-38"><a href="#cb7-38"></a> Expr in2<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-39"><a href="#cb7-39"></a> <span class="cf">return</span> <span class="cf">switch</span> <span class="op">(</span>opcode<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-40"><a href="#cb7-40"></a> <span class="cf">case</span> PcodeOp<span class="op">.</span><span class="fu">INT_ADD</span> <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">AddExpr</span><span class="op">(</span>in1<span class="op">,</span> in2<span class="op">,</span> sizeout<span class="op">);</span></span>
-<span id="cb7-41"><a href="#cb7-41"></a> <span class="cf">case</span> PcodeOp<span class="op">.</span><span class="fu">INT_SUB</span> <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">SubExpr</span><span class="op">(</span>in1<span class="op">,</span> in2<span class="op">,</span> sizeout<span class="op">);</span></span>
-<span id="cb7-42"><a href="#cb7-42"></a> <span class="kw">default</span> <span class="op">-&gt;</span> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">(</span>PcodeOp<span class="op">.</span><span class="fu">getMnemonic</span><span class="op">(</span>opcode<span class="op">));</span></span>
-<span id="cb7-43"><a href="#cb7-43"></a> <span class="op">};</span></span>
-<span id="cb7-44"><a href="#cb7-44"></a> <span class="op">}</span></span>
-<span id="cb7-45"><a href="#cb7-45"></a></span>
-<span id="cb7-46"><a href="#cb7-46"></a> <span class="at">@Override</span></span>
-<span id="cb7-47"><a href="#cb7-47"></a> <span class="kw">public</span> Expr <span class="fu">modBeforeStore</span><span class="op">(</span><span class="dt">int</span> sizeinOffset<span class="op">,</span> AddressSpace space<span class="op">,</span> Expr inOffset<span class="op">,</span></span>
-<span id="cb7-48"><a href="#cb7-48"></a> <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">modAfterLoad</span><span class="op">(</span><span class="dt">int</span> sizeinOffset<span class="op">,</span> AddressSpace space<span class="op">,</span> Expr inOffset<span class="op">,</span></span>
-<span id="cb7-54"><a href="#cb7-54"></a> <span class="dt">int</span> sizeinValue<span class="op">,</span> Expr inValue<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb7-55"><a href="#cb7-55"></a> <span class="cf">return</span> inValue<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>
-<span id="cb7-58"><a href="#cb7-58"></a> <span class="at">@Override</span></span>
-<span id="cb7-59"><a href="#cb7-59"></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-60"><a href="#cb7-60"></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-61"><a href="#cb7-61"></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-62"><a href="#cb7-62"></a> <span class="op">}</span></span>
-<span id="cb7-63"><a href="#cb7-63"></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-64"><a href="#cb7-64"></a> ArrayUtils<span class="op">.</span><span class="fu">reverse</span><span class="op">(</span>reversed<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><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-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="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-70"><a href="#cb7-70"></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-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> 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-75"><a href="#cb7-75"></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-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">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-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>
-<span id="cb7-83"><a href="#cb7-83"></a> <span class="at">@Override</span></span>
-<span id="cb7-84"><a href="#cb7-84"></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-85"><a href="#cb7-85"></a> <span class="cf">return</span> value<span class="op">.</span><span class="fu">size</span><span class="op">();</span></span>
-<span id="cb7-86"><a href="#cb7-86"></a> <span class="op">}</span></span>
-<span id="cb7-87"><a href="#cb7-87"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb11"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb11-1"><a href="#cb11-1"></a><span class="kw">public</span> <span class="kw">enum</span> ExprPcodeArithmetic <span class="kw">implements</span> PcodeArithmetic<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="op">{</span></span>
+<span id="cb11-2"><a href="#cb11-2"></a> <span class="fu">BE</span><span class="op">(</span>Endian<span class="op">.</span><span class="fu">BIG</span><span class="op">),</span> <span class="fu">LE</span><span class="op">(</span>Endian<span class="op">.</span><span class="fu">LITTLE</span><span class="op">);</span></span>
+<span id="cb11-3"><a href="#cb11-3"></a></span>
+<span id="cb11-4"><a href="#cb11-4"></a> <span class="kw">public</span> <span class="dt">static</span> ExprPcodeArithmetic <span class="fu">forEndian</span><span class="op">(</span>Endian endian<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-5"><a href="#cb11-5"></a> <span class="cf">return</span> endian<span class="op">.</span><span class="fu">isBigEndian</span><span class="op">()</span> <span class="op">?</span> BE <span class="op">:</span> LE<span class="op">;</span></span>
+<span id="cb11-6"><a href="#cb11-6"></a> <span class="op">}</span></span>
+<span id="cb11-7"><a href="#cb11-7"></a></span>
+<span id="cb11-8"><a href="#cb11-8"></a> <span class="kw">public</span> <span class="dt">static</span> ExprPcodeArithmetic <span class="fu">forLanguage</span><span class="op">(</span>Language language<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-9"><a href="#cb11-9"></a> <span class="cf">return</span> language<span class="op">.</span><span class="fu">isBigEndian</span><span class="op">()</span> <span class="op">?</span> BE <span class="op">:</span> LE<span class="op">;</span></span>
+<span id="cb11-10"><a href="#cb11-10"></a> <span class="op">}</span></span>
+<span id="cb11-11"><a href="#cb11-11"></a></span>
+<span id="cb11-12"><a href="#cb11-12"></a> <span class="kw">private</span> <span class="dt">final</span> Endian endian<span class="op">;</span></span>
+<span id="cb11-13"><a href="#cb11-13"></a></span>
+<span id="cb11-14"><a href="#cb11-14"></a> <span class="kw">private</span> <span class="fu">ExprPcodeArithmetic</span><span class="op">(</span>Endian endian<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-15"><a href="#cb11-15"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">endian</span> <span class="op">=</span> endian<span class="op">;</span></span>
+<span id="cb11-16"><a href="#cb11-16"></a> <span class="op">}</span></span>
+<span id="cb11-17"><a href="#cb11-17"></a></span>
+<span id="cb11-18"><a href="#cb11-18"></a> <span class="at">@Override</span></span>
+<span id="cb11-19"><a href="#cb11-19"></a> <span class="kw">public</span> <span class="bu">Class</span><span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getDomain</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb11-20"><a href="#cb11-20"></a> <span class="cf">return</span> Expr<span class="op">.</span><span class="fu">class</span><span class="op">;</span></span>
+<span id="cb11-21"><a href="#cb11-21"></a> <span class="op">}</span></span>
+<span id="cb11-22"><a href="#cb11-22"></a></span>
+<span id="cb11-23"><a href="#cb11-23"></a> <span class="at">@Override</span></span>
+<span id="cb11-24"><a href="#cb11-24"></a> <span class="kw">public</span> Endian <span class="fu">getEndian</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb11-25"><a href="#cb11-25"></a> <span class="cf">return</span> endian<span class="op">;</span></span>
+<span id="cb11-26"><a href="#cb11-26"></a> <span class="op">}</span></span>
+<span id="cb11-27"><a href="#cb11-27"></a></span>
+<span id="cb11-28"><a href="#cb11-28"></a> <span class="at">@Override</span></span>
+<span id="cb11-29"><a href="#cb11-29"></a> <span class="kw">public</span> Expr <span class="fu">unaryOp</span><span class="op">(</span><span class="dt">int</span> opcode<span class="op">,</span> <span class="dt">int</span> sizeout<span class="op">,</span> <span class="dt">int</span> sizein1<span class="op">,</span> Expr in1<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-30"><a href="#cb11-30"></a> <span class="cf">return</span> <span class="cf">switch</span> <span class="op">(</span>opcode<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-31"><a href="#cb11-31"></a> <span class="cf">case</span> PcodeOp<span class="op">.</span><span class="fu">INT_NEGATE</span> <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">InvExpr</span><span class="op">(</span>in1<span class="op">,</span> sizeout<span class="op">);</span></span>
+<span id="cb11-32"><a href="#cb11-32"></a> <span class="kw">default</span> <span class="op">-&gt;</span> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">(</span>PcodeOp<span class="op">.</span><span class="fu">getMnemonic</span><span class="op">(</span>opcode<span class="op">));</span></span>
+<span id="cb11-33"><a href="#cb11-33"></a> <span class="op">};</span></span>
+<span id="cb11-34"><a href="#cb11-34"></a> <span class="op">}</span></span>
+<span id="cb11-35"><a href="#cb11-35"></a></span>
+<span id="cb11-36"><a href="#cb11-36"></a> <span class="at">@Override</span></span>
+<span id="cb11-37"><a href="#cb11-37"></a> <span class="kw">public</span> Expr <span class="fu">binaryOp</span><span class="op">(</span><span class="dt">int</span> opcode<span class="op">,</span> <span class="dt">int</span> sizeout<span class="op">,</span> <span class="dt">int</span> sizein1<span class="op">,</span> Expr in1<span class="op">,</span> <span class="dt">int</span> sizein2<span class="op">,</span></span>
+<span id="cb11-38"><a href="#cb11-38"></a> Expr in2<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-39"><a href="#cb11-39"></a> <span class="cf">return</span> <span class="cf">switch</span> <span class="op">(</span>opcode<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-40"><a href="#cb11-40"></a> <span class="cf">case</span> PcodeOp<span class="op">.</span><span class="fu">INT_ADD</span> <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">AddExpr</span><span class="op">(</span>in1<span class="op">,</span> in2<span class="op">,</span> sizeout<span class="op">);</span></span>
+<span id="cb11-41"><a href="#cb11-41"></a> <span class="cf">case</span> PcodeOp<span class="op">.</span><span class="fu">INT_SUB</span> <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">SubExpr</span><span class="op">(</span>in1<span class="op">,</span> in2<span class="op">,</span> sizeout<span class="op">);</span></span>
+<span id="cb11-42"><a href="#cb11-42"></a> <span class="kw">default</span> <span class="op">-&gt;</span> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">(</span>PcodeOp<span class="op">.</span><span class="fu">getMnemonic</span><span class="op">(</span>opcode<span class="op">));</span></span>
+<span id="cb11-43"><a href="#cb11-43"></a> <span class="op">};</span></span>
+<span id="cb11-44"><a href="#cb11-44"></a> <span class="op">}</span></span>
+<span id="cb11-45"><a href="#cb11-45"></a></span>
+<span id="cb11-46"><a href="#cb11-46"></a> <span class="at">@Override</span></span>
+<span id="cb11-47"><a href="#cb11-47"></a> <span class="kw">public</span> Expr <span class="fu">modBeforeStore</span><span class="op">(</span><span class="dt">int</span> sizeinOffset<span class="op">,</span> AddressSpace space<span class="op">,</span> Expr inOffset<span class="op">,</span></span>
+<span id="cb11-48"><a href="#cb11-48"></a> <span class="dt">int</span> sizeinValue<span class="op">,</span> Expr inValue<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-49"><a href="#cb11-49"></a> <span class="cf">return</span> inValue<span class="op">;</span></span>
+<span id="cb11-50"><a href="#cb11-50"></a> <span class="op">}</span></span>
+<span id="cb11-51"><a href="#cb11-51"></a></span>
+<span id="cb11-52"><a href="#cb11-52"></a> <span class="at">@Override</span></span>
+<span id="cb11-53"><a href="#cb11-53"></a> <span class="kw">public</span> Expr <span class="fu">modAfterLoad</span><span class="op">(</span><span class="dt">int</span> sizeinOffset<span class="op">,</span> AddressSpace space<span class="op">,</span> Expr inOffset<span class="op">,</span></span>
+<span id="cb11-54"><a href="#cb11-54"></a> <span class="dt">int</span> sizeinValue<span class="op">,</span> Expr inValue<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb11-55"><a href="#cb11-55"></a> <span class="cf">return</span> inValue<span class="op">;</span></span>
+<span id="cb11-56"><a href="#cb11-56"></a> <span class="op">}</span></span>
+<span id="cb11-57"><a href="#cb11-57"></a></span>
+<span id="cb11-58"><a href="#cb11-58"></a> <span class="at">@Override</span></span>
+<span id="cb11-59"><a href="#cb11-59"></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="cb11-60"><a href="#cb11-60"></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="cb11-61"><a href="#cb11-61"></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="cb11-62"><a href="#cb11-62"></a> <span class="op">}</span></span>
+<span id="cb11-63"><a href="#cb11-63"></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="cb11-64"><a href="#cb11-64"></a> ArrayUtils<span class="op">.</span><span class="fu">reverse</span><span class="op">(</span>reversed<span class="op">);</span></span>
+<span id="cb11-65"><a href="#cb11-65"></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="cb11-66"><a href="#cb11-66"></a> <span class="op">}</span></span>
+<span id="cb11-67"><a href="#cb11-67"></a></span>
+<span id="cb11-68"><a href="#cb11-68"></a> <span class="at">@Override</span></span>
+<span id="cb11-69"><a href="#cb11-69"></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="cb11-70"><a href="#cb11-70"></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="cb11-71"><a href="#cb11-71"></a> <span class="op">}</span></span>
+<span id="cb11-72"><a href="#cb11-72"></a></span>
+<span id="cb11-73"><a href="#cb11-73"></a> <span class="at">@Override</span></span>
+<span id="cb11-74"><a href="#cb11-74"></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="cb11-75"><a href="#cb11-75"></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="cb11-76"><a href="#cb11-76"></a> <span class="op">}</span></span>
+<span id="cb11-77"><a href="#cb11-77"></a></span>
+<span id="cb11-78"><a href="#cb11-78"></a> <span class="at">@Override</span></span>
+<span id="cb11-79"><a href="#cb11-79"></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="cb11-80"><a href="#cb11-80"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>
+<span id="cb11-81"><a href="#cb11-81"></a> <span class="op">}</span></span>
+<span id="cb11-82"><a href="#cb11-82"></a></span>
+<span id="cb11-83"><a href="#cb11-83"></a> <span class="at">@Override</span></span>
+<span id="cb11-84"><a href="#cb11-84"></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="cb11-85"><a href="#cb11-85"></a> <span class="cf">return</span> value<span class="op">.</span><span class="fu">size</span><span class="op">();</span></span>
+<span id="cb11-86"><a href="#cb11-86"></a> <span class="op">}</span></span>
+<span id="cb11-87"><a href="#cb11-87"></a><span class="op">}</span></span></code></pre></div>
<p>We have implemented two arithmetic models: one for big-endian
languages and one for little-endian. The endianness comes into play when
we encode constant values passed to <code>fromConst()</code>. We must
@@ -759,110 +819,110 @@ dynamic analysis when aliasing and indirection is involved.</p>
already familiar with Java naming conventions for “enterprise
applications” or our particular implementation of them, you are about to
see it on full display.</p>
-<div class="sourceCode" id="cb8"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb8-1"><a href="#cb8-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> ExprSpace <span class="op">{</span></span>
-<span id="cb8-2"><a href="#cb8-2"></a> <span class="kw">protected</span> <span class="dt">final</span> <span class="bu">NavigableMap</span><span class="op">&lt;</span><span class="bu">Long</span><span class="op">,</span> Expr<span class="op">&gt;</span> map <span class="op">=</span> <span class="kw">new</span> <span class="bu">TreeMap</span><span class="op">&lt;&gt;(</span><span class="bu">Long</span><span class="op">::</span>compareUnsigned<span class="op">);</span></span>
-<span id="cb8-3"><a href="#cb8-3"></a> <span class="kw">protected</span> <span class="dt">final</span> ExprPcodeExecutorStatePiece piece<span class="op">;</span></span>
-<span id="cb8-4"><a href="#cb8-4"></a> <span class="kw">protected</span> <span class="dt">final</span> AddressSpace space<span class="op">;</span></span>
-<span id="cb8-5"><a href="#cb8-5"></a></span>
-<span id="cb8-6"><a href="#cb8-6"></a> <span class="kw">protected</span> <span class="fu">ExprSpace</span><span class="op">(</span>AddressSpace space<span class="op">,</span> ExprPcodeExecutorStatePiece piece<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-7"><a href="#cb8-7"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">space</span> <span class="op">=</span> space<span class="op">;</span></span>
-<span id="cb8-8"><a href="#cb8-8"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">piece</span> <span class="op">=</span> piece<span class="op">;</span></span>
-<span id="cb8-9"><a href="#cb8-9"></a> <span class="op">}</span></span>
-<span id="cb8-10"><a href="#cb8-10"></a></span>
-<span id="cb8-11"><a href="#cb8-11"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">clear</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb8-12"><a href="#cb8-12"></a> map<span class="op">.</span><span class="fu">clear</span><span class="op">();</span></span>
-<span id="cb8-13"><a href="#cb8-13"></a> <span class="op">}</span></span>
-<span id="cb8-14"><a href="#cb8-14"></a></span>
-<span id="cb8-15"><a href="#cb8-15"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">set</span><span class="op">(</span><span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Expr val<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-16"><a href="#cb8-16"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Handle overlaps / offcut gets and sets</span></span>
-<span id="cb8-17"><a href="#cb8-17"></a> map<span class="op">.</span><span class="fu">put</span><span class="op">(</span>offset<span class="op">,</span> val<span class="op">);</span></span>
-<span id="cb8-18"><a href="#cb8-18"></a> cb<span class="op">.</span><span class="fu">dataWritten</span><span class="op">(</span>piece<span class="op">,</span> space<span class="op">.</span><span class="fu">getAddress</span><span class="op">(</span>offset<span class="op">),</span> size<span class="op">,</span> val<span class="op">);</span></span>
-<span id="cb8-19"><a href="#cb8-19"></a> <span class="op">}</span></span>
-<span id="cb8-20"><a href="#cb8-20"></a></span>
-<span id="cb8-21"><a href="#cb8-21"></a> <span class="kw">public</span> Expr <span class="fu">get</span><span class="op">(</span><span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Reason reason<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-22"><a href="#cb8-22"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Handle overlaps / offcut gets and sets</span></span>
-<span id="cb8-23"><a href="#cb8-23"></a> Expr expr <span class="op">=</span> map<span class="op">.</span><span class="fu">get</span><span class="op">(</span>offset<span class="op">);</span></span>
-<span id="cb8-24"><a href="#cb8-24"></a> <span class="cf">if</span> <span class="op">(</span>expr <span class="op">==</span> <span class="kw">null</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-25"><a href="#cb8-25"></a> <span class="dt">byte</span><span class="op">[]</span> aOffset <span class="op">=</span></span>
-<span id="cb8-26"><a href="#cb8-26"></a> piece<span class="op">.</span><span class="fu">getAddressArithmetic</span><span class="op">().</span><span class="fu">fromConst</span><span class="op">(</span>offset<span class="op">,</span> space<span class="op">.</span><span class="fu">getPointerSize</span><span class="op">());</span></span>
-<span id="cb8-27"><a href="#cb8-27"></a> <span class="cf">if</span> <span class="op">(</span>cb<span class="op">.</span><span class="fu">readUninitialized</span><span class="op">(</span>piece<span class="op">,</span> space<span class="op">,</span> aOffset<span class="op">,</span> size<span class="op">,</span> reason<span class="op">)</span> <span class="op">!=</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-28"><a href="#cb8-28"></a> <span class="cf">return</span> map<span class="op">.</span><span class="fu">get</span><span class="op">(</span>offset<span class="op">);</span></span>
-<span id="cb8-29"><a href="#cb8-29"></a> <span class="op">}</span></span>
-<span id="cb8-30"><a href="#cb8-30"></a> <span class="op">}</span></span>
-<span id="cb8-31"><a href="#cb8-31"></a> <span class="cf">return</span> <span class="kw">null</span><span class="op">;</span></span>
-<span id="cb8-32"><a href="#cb8-32"></a> <span class="op">}</span></span>
-<span id="cb8-33"><a href="#cb8-33"></a></span>
-<span id="cb8-34"><a href="#cb8-34"></a> <span class="kw">public</span> Entry<span class="op">&lt;</span><span class="bu">Long</span><span class="op">,</span> Expr<span class="op">&gt;</span> <span class="fu">getNextEntry</span><span class="op">(</span><span class="dt">long</span> offset<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-35"><a href="#cb8-35"></a> <span class="cf">return</span> map<span class="op">.</span><span class="fu">ceilingEntry</span><span class="op">(</span>offset<span class="op">);</span></span>
-<span id="cb8-36"><a href="#cb8-36"></a> <span class="op">}</span></span>
-<span id="cb8-37"><a href="#cb8-37"></a><span class="op">}</span></span>
-<span id="cb8-38"><a href="#cb8-38"></a></span>
-<span id="cb8-39"><a href="#cb8-39"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> ExprPcodeExecutorStatePiece</span>
-<span id="cb8-40"><a href="#cb8-40"></a> <span class="kw">extends</span> AbstractLongOffsetPcodeExecutorStatePiece<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">,</span> ExprSpace<span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb8-41"><a href="#cb8-41"></a></span>
-<span id="cb8-42"><a href="#cb8-42"></a> <span class="kw">protected</span> <span class="dt">final</span> <span class="bu">Map</span><span class="op">&lt;</span>AddressSpace<span class="op">,</span> ExprSpace<span class="op">&gt;</span> spaceMap <span class="op">=</span> <span class="kw">new</span> <span class="bu">HashMap</span><span class="op">&lt;&gt;();</span></span>
-<span id="cb8-43"><a href="#cb8-43"></a></span>
-<span id="cb8-44"><a href="#cb8-44"></a> <span class="kw">public</span> <span class="fu">ExprPcodeExecutorStatePiece</span><span class="op">(</span>Language language<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-45"><a href="#cb8-45"></a> <span class="kw">super</span><span class="op">(</span>language<span class="op">,</span> BytesPcodeArithmetic<span class="op">.</span><span class="fu">forLanguage</span><span class="op">(</span>language<span class="op">),</span></span>
-<span id="cb8-46"><a href="#cb8-46"></a> ExprPcodeArithmetic<span class="op">.</span><span class="fu">forLanguage</span><span class="op">(</span>language<span class="op">),</span> cb<span class="op">);</span></span>
-<span id="cb8-47"><a href="#cb8-47"></a> <span class="op">}</span></span>
-<span id="cb8-48"><a href="#cb8-48"></a></span>
-<span id="cb8-49"><a href="#cb8-49"></a> <span class="at">@Override</span></span>
-<span id="cb8-50"><a href="#cb8-50"></a> <span class="kw">public</span> MemBuffer <span class="fu">getConcreteBuffer</span><span class="op">(</span>Address address<span class="op">,</span> Purpose purpose<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-51"><a href="#cb8-51"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>
-<span id="cb8-52"><a href="#cb8-52"></a> <span class="op">}</span></span>
-<span id="cb8-53"><a href="#cb8-53"></a></span>
-<span id="cb8-54"><a href="#cb8-54"></a> <span class="at">@Override</span></span>
-<span id="cb8-55"><a href="#cb8-55"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">clear</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb8-56"><a href="#cb8-56"></a> <span class="cf">for</span> <span class="op">(</span>ExprSpace space <span class="op">:</span> spaceMap<span class="op">.</span><span class="fu">values</span><span class="op">())</span> <span class="op">{</span></span>
-<span id="cb8-57"><a href="#cb8-57"></a> space<span class="op">.</span><span class="fu">clear</span><span class="op">();</span></span>
-<span id="cb8-58"><a href="#cb8-58"></a> <span class="op">}</span></span>
-<span id="cb8-59"><a href="#cb8-59"></a> <span class="op">}</span></span>
-<span id="cb8-60"><a href="#cb8-60"></a></span>
-<span id="cb8-61"><a href="#cb8-61"></a> <span class="at">@Override</span></span>
-<span id="cb8-62"><a href="#cb8-62"></a> <span class="kw">protected</span> ExprSpace <span class="fu">getForSpace</span><span class="op">(</span>AddressSpace space<span class="op">,</span> <span class="dt">boolean</span> toWrite<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-63"><a href="#cb8-63"></a> <span class="cf">if</span> <span class="op">(</span>toWrite<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-64"><a href="#cb8-64"></a> <span class="cf">return</span> spaceMap<span class="op">.</span><span class="fu">computeIfAbsent</span><span class="op">(</span>space<span class="op">,</span> s <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">ExprSpace</span><span class="op">(</span>s<span class="op">,</span> <span class="kw">this</span><span class="op">));</span></span>
-<span id="cb8-65"><a href="#cb8-65"></a> <span class="op">}</span></span>
-<span id="cb8-66"><a href="#cb8-66"></a> <span class="cf">return</span> spaceMap<span class="op">.</span><span class="fu">get</span><span class="op">(</span>space<span class="op">);</span></span>
-<span id="cb8-67"><a href="#cb8-67"></a> <span class="op">}</span></span>
-<span id="cb8-68"><a href="#cb8-68"></a></span>
-<span id="cb8-69"><a href="#cb8-69"></a> <span class="at">@Override</span></span>
-<span id="cb8-70"><a href="#cb8-70"></a> <span class="kw">public</span> Entry<span class="op">&lt;</span><span class="bu">Long</span><span class="op">,</span> Expr<span class="op">&gt;</span> <span class="fu">getNextEntryInternal</span><span class="op">(</span>AddressSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-71"><a href="#cb8-71"></a> ExprSpace s <span class="op">=</span> <span class="fu">getForSpace</span><span class="op">(</span>space<span class="op">,</span> <span class="kw">false</span><span class="op">);</span></span>
-<span id="cb8-72"><a href="#cb8-72"></a> <span class="cf">if</span> <span class="op">(</span>s <span class="op">==</span> <span class="kw">null</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-73"><a href="#cb8-73"></a> <span class="cf">return</span> <span class="kw">null</span><span class="op">;</span></span>
-<span id="cb8-74"><a href="#cb8-74"></a> <span class="op">}</span></span>
-<span id="cb8-75"><a href="#cb8-75"></a> <span class="cf">return</span> s<span class="op">.</span><span class="fu">getNextEntry</span><span class="op">(</span>offset<span class="op">);</span></span>
-<span id="cb8-76"><a href="#cb8-76"></a> <span class="op">}</span></span>
-<span id="cb8-77"><a href="#cb8-77"></a></span>
-<span id="cb8-78"><a href="#cb8-78"></a> <span class="at">@Override</span></span>
-<span id="cb8-79"><a href="#cb8-79"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">setInSpace</span><span class="op">(</span>ExprSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Expr val<span class="op">,</span></span>
-<span id="cb8-80"><a href="#cb8-80"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-81"><a href="#cb8-81"></a> space<span class="op">.</span><span class="fu">set</span><span class="op">(</span>offset<span class="op">,</span> size<span class="op">,</span> val<span class="op">,</span> cb<span class="op">);</span></span>
-<span id="cb8-82"><a href="#cb8-82"></a> <span class="op">}</span></span>
-<span id="cb8-83"><a href="#cb8-83"></a></span>
-<span id="cb8-84"><a href="#cb8-84"></a> <span class="at">@Override</span></span>
-<span id="cb8-85"><a href="#cb8-85"></a> <span class="kw">protected</span> Expr <span class="fu">getFromSpace</span><span class="op">(</span>ExprSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Reason reason<span class="op">,</span></span>
-<span id="cb8-86"><a href="#cb8-86"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-87"><a href="#cb8-87"></a> <span class="cf">return</span> space<span class="op">.</span><span class="fu">get</span><span class="op">(</span>offset<span class="op">,</span> size<span class="op">,</span> reason<span class="op">,</span> cb<span class="op">);</span></span>
-<span id="cb8-88"><a href="#cb8-88"></a> <span class="op">}</span></span>
-<span id="cb8-89"><a href="#cb8-89"></a></span>
-<span id="cb8-90"><a href="#cb8-90"></a> <span class="at">@Override</span></span>
-<span id="cb8-91"><a href="#cb8-91"></a> <span class="kw">protected</span> <span class="bu">Map</span><span class="op">&lt;</span>Register<span class="op">,</span> Expr<span class="op">&gt;</span> <span class="fu">getRegisterValuesFromSpace</span><span class="op">(</span>ExprSpace s<span class="op">,</span></span>
-<span id="cb8-92"><a href="#cb8-92"></a> <span class="bu">List</span><span class="op">&lt;</span>Register<span class="op">&gt;</span> registers<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-93"><a href="#cb8-93"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>
-<span id="cb8-94"><a href="#cb8-94"></a> <span class="op">}</span></span>
-<span id="cb8-95"><a href="#cb8-95"></a><span class="op">}</span></span>
-<span id="cb8-96"><a href="#cb8-96"></a></span>
-<span id="cb8-97"><a href="#cb8-97"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> BytesExprPcodeExecutorState <span class="kw">extends</span> PairedPcodeExecutorState<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb8-98"><a href="#cb8-98"></a> <span class="kw">public</span> <span class="fu">BytesExprPcodeExecutorState</span><span class="op">(</span>PcodeExecutorStatePiece<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> <span class="dt">byte</span><span class="op">[]&gt;</span> concrete<span class="op">,</span></span>
-<span id="cb8-99"><a href="#cb8-99"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb8-100"><a href="#cb8-100"></a> <span class="kw">super</span><span class="op">(</span><span class="kw">new</span> PairedPcodeExecutorStatePiece<span class="op">&lt;&gt;(</span>concrete<span class="op">,</span></span>
-<span id="cb8-101"><a href="#cb8-101"></a> <span class="kw">new</span> <span class="fu">ExprPcodeExecutorStatePiece</span><span class="op">(</span>concrete<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span> cb<span class="op">)));</span></span>
-<span id="cb8-102"><a href="#cb8-102"></a> <span class="op">}</span></span>
-<span id="cb8-103"><a href="#cb8-103"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb12"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb12-1"><a href="#cb12-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> ExprSpace <span class="op">{</span></span>
+<span id="cb12-2"><a href="#cb12-2"></a> <span class="kw">protected</span> <span class="dt">final</span> <span class="bu">NavigableMap</span><span class="op">&lt;</span><span class="bu">Long</span><span class="op">,</span> Expr<span class="op">&gt;</span> map <span class="op">=</span> <span class="kw">new</span> <span class="bu">TreeMap</span><span class="op">&lt;&gt;(</span><span class="bu">Long</span><span class="op">::</span>compareUnsigned<span class="op">);</span></span>
+<span id="cb12-3"><a href="#cb12-3"></a> <span class="kw">protected</span> <span class="dt">final</span> ExprPcodeExecutorStatePiece piece<span class="op">;</span></span>
+<span id="cb12-4"><a href="#cb12-4"></a> <span class="kw">protected</span> <span class="dt">final</span> AddressSpace space<span class="op">;</span></span>
+<span id="cb12-5"><a href="#cb12-5"></a></span>
+<span id="cb12-6"><a href="#cb12-6"></a> <span class="kw">protected</span> <span class="fu">ExprSpace</span><span class="op">(</span>AddressSpace space<span class="op">,</span> ExprPcodeExecutorStatePiece piece<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-7"><a href="#cb12-7"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">space</span> <span class="op">=</span> space<span class="op">;</span></span>
+<span id="cb12-8"><a href="#cb12-8"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">piece</span> <span class="op">=</span> piece<span class="op">;</span></span>
+<span id="cb12-9"><a href="#cb12-9"></a> <span class="op">}</span></span>
+<span id="cb12-10"><a href="#cb12-10"></a></span>
+<span id="cb12-11"><a href="#cb12-11"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">clear</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb12-12"><a href="#cb12-12"></a> map<span class="op">.</span><span class="fu">clear</span><span class="op">();</span></span>
+<span id="cb12-13"><a href="#cb12-13"></a> <span class="op">}</span></span>
+<span id="cb12-14"><a href="#cb12-14"></a></span>
+<span id="cb12-15"><a href="#cb12-15"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">set</span><span class="op">(</span><span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Expr val<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-16"><a href="#cb12-16"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Handle overlaps / offcut gets and sets</span></span>
+<span id="cb12-17"><a href="#cb12-17"></a> map<span class="op">.</span><span class="fu">put</span><span class="op">(</span>offset<span class="op">,</span> val<span class="op">);</span></span>
+<span id="cb12-18"><a href="#cb12-18"></a> cb<span class="op">.</span><span class="fu">dataWritten</span><span class="op">(</span>piece<span class="op">,</span> space<span class="op">.</span><span class="fu">getAddress</span><span class="op">(</span>offset<span class="op">),</span> size<span class="op">,</span> val<span class="op">);</span></span>
+<span id="cb12-19"><a href="#cb12-19"></a> <span class="op">}</span></span>
+<span id="cb12-20"><a href="#cb12-20"></a></span>
+<span id="cb12-21"><a href="#cb12-21"></a> <span class="kw">public</span> Expr <span class="fu">get</span><span class="op">(</span><span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Reason reason<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-22"><a href="#cb12-22"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Handle overlaps / offcut gets and sets</span></span>
+<span id="cb12-23"><a href="#cb12-23"></a> Expr expr <span class="op">=</span> map<span class="op">.</span><span class="fu">get</span><span class="op">(</span>offset<span class="op">);</span></span>
+<span id="cb12-24"><a href="#cb12-24"></a> <span class="cf">if</span> <span class="op">(</span>expr <span class="op">==</span> <span class="kw">null</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-25"><a href="#cb12-25"></a> <span class="dt">byte</span><span class="op">[]</span> aOffset <span class="op">=</span></span>
+<span id="cb12-26"><a href="#cb12-26"></a> piece<span class="op">.</span><span class="fu">getAddressArithmetic</span><span class="op">().</span><span class="fu">fromConst</span><span class="op">(</span>offset<span class="op">,</span> space<span class="op">.</span><span class="fu">getPointerSize</span><span class="op">());</span></span>
+<span id="cb12-27"><a href="#cb12-27"></a> <span class="cf">if</span> <span class="op">(</span>cb<span class="op">.</span><span class="fu">readUninitialized</span><span class="op">(</span>piece<span class="op">,</span> space<span class="op">,</span> aOffset<span class="op">,</span> size<span class="op">,</span> reason<span class="op">)</span> <span class="op">!=</span> <span class="dv">0</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-28"><a href="#cb12-28"></a> <span class="cf">return</span> map<span class="op">.</span><span class="fu">get</span><span class="op">(</span>offset<span class="op">);</span></span>
+<span id="cb12-29"><a href="#cb12-29"></a> <span class="op">}</span></span>
+<span id="cb12-30"><a href="#cb12-30"></a> <span class="op">}</span></span>
+<span id="cb12-31"><a href="#cb12-31"></a> <span class="cf">return</span> <span class="kw">null</span><span class="op">;</span></span>
+<span id="cb12-32"><a href="#cb12-32"></a> <span class="op">}</span></span>
+<span id="cb12-33"><a href="#cb12-33"></a></span>
+<span id="cb12-34"><a href="#cb12-34"></a> <span class="kw">public</span> Entry<span class="op">&lt;</span><span class="bu">Long</span><span class="op">,</span> Expr<span class="op">&gt;</span> <span class="fu">getNextEntry</span><span class="op">(</span><span class="dt">long</span> offset<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-35"><a href="#cb12-35"></a> <span class="cf">return</span> map<span class="op">.</span><span class="fu">ceilingEntry</span><span class="op">(</span>offset<span class="op">);</span></span>
+<span id="cb12-36"><a href="#cb12-36"></a> <span class="op">}</span></span>
+<span id="cb12-37"><a href="#cb12-37"></a><span class="op">}</span></span>
+<span id="cb12-38"><a href="#cb12-38"></a></span>
+<span id="cb12-39"><a href="#cb12-39"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> ExprPcodeExecutorStatePiece</span>
+<span id="cb12-40"><a href="#cb12-40"></a> <span class="kw">extends</span> AbstractLongOffsetPcodeExecutorStatePiece<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">,</span> ExprSpace<span class="op">&gt;</span> <span class="op">{</span></span>
+<span id="cb12-41"><a href="#cb12-41"></a></span>
+<span id="cb12-42"><a href="#cb12-42"></a> <span class="kw">protected</span> <span class="dt">final</span> <span class="bu">Map</span><span class="op">&lt;</span>AddressSpace<span class="op">,</span> ExprSpace<span class="op">&gt;</span> spaceMap <span class="op">=</span> <span class="kw">new</span> <span class="bu">HashMap</span><span class="op">&lt;&gt;();</span></span>
+<span id="cb12-43"><a href="#cb12-43"></a></span>
+<span id="cb12-44"><a href="#cb12-44"></a> <span class="kw">public</span> <span class="fu">ExprPcodeExecutorStatePiece</span><span class="op">(</span>Language language<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-45"><a href="#cb12-45"></a> <span class="kw">super</span><span class="op">(</span>language<span class="op">,</span> BytesPcodeArithmetic<span class="op">.</span><span class="fu">forLanguage</span><span class="op">(</span>language<span class="op">),</span></span>
+<span id="cb12-46"><a href="#cb12-46"></a> ExprPcodeArithmetic<span class="op">.</span><span class="fu">forLanguage</span><span class="op">(</span>language<span class="op">),</span> cb<span class="op">);</span></span>
+<span id="cb12-47"><a href="#cb12-47"></a> <span class="op">}</span></span>
+<span id="cb12-48"><a href="#cb12-48"></a></span>
+<span id="cb12-49"><a href="#cb12-49"></a> <span class="at">@Override</span></span>
+<span id="cb12-50"><a href="#cb12-50"></a> <span class="kw">public</span> MemBuffer <span class="fu">getConcreteBuffer</span><span class="op">(</span>Address address<span class="op">,</span> Purpose purpose<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-51"><a href="#cb12-51"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>
+<span id="cb12-52"><a href="#cb12-52"></a> <span class="op">}</span></span>
+<span id="cb12-53"><a href="#cb12-53"></a></span>
+<span id="cb12-54"><a href="#cb12-54"></a> <span class="at">@Override</span></span>
+<span id="cb12-55"><a href="#cb12-55"></a> <span class="kw">public</span> <span class="dt">void</span> <span class="fu">clear</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb12-56"><a href="#cb12-56"></a> <span class="cf">for</span> <span class="op">(</span>ExprSpace space <span class="op">:</span> spaceMap<span class="op">.</span><span class="fu">values</span><span class="op">())</span> <span class="op">{</span></span>
+<span id="cb12-57"><a href="#cb12-57"></a> space<span class="op">.</span><span class="fu">clear</span><span class="op">();</span></span>
+<span id="cb12-58"><a href="#cb12-58"></a> <span class="op">}</span></span>
+<span id="cb12-59"><a href="#cb12-59"></a> <span class="op">}</span></span>
+<span id="cb12-60"><a href="#cb12-60"></a></span>
+<span id="cb12-61"><a href="#cb12-61"></a> <span class="at">@Override</span></span>
+<span id="cb12-62"><a href="#cb12-62"></a> <span class="kw">protected</span> ExprSpace <span class="fu">getForSpace</span><span class="op">(</span>AddressSpace space<span class="op">,</span> <span class="dt">boolean</span> toWrite<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-63"><a href="#cb12-63"></a> <span class="cf">if</span> <span class="op">(</span>toWrite<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-64"><a href="#cb12-64"></a> <span class="cf">return</span> spaceMap<span class="op">.</span><span class="fu">computeIfAbsent</span><span class="op">(</span>space<span class="op">,</span> s <span class="op">-&gt;</span> <span class="kw">new</span> <span class="fu">ExprSpace</span><span class="op">(</span>s<span class="op">,</span> <span class="kw">this</span><span class="op">));</span></span>
+<span id="cb12-65"><a href="#cb12-65"></a> <span class="op">}</span></span>
+<span id="cb12-66"><a href="#cb12-66"></a> <span class="cf">return</span> spaceMap<span class="op">.</span><span class="fu">get</span><span class="op">(</span>space<span class="op">);</span></span>
+<span id="cb12-67"><a href="#cb12-67"></a> <span class="op">}</span></span>
+<span id="cb12-68"><a href="#cb12-68"></a></span>
+<span id="cb12-69"><a href="#cb12-69"></a> <span class="at">@Override</span></span>
+<span id="cb12-70"><a href="#cb12-70"></a> <span class="kw">public</span> Entry<span class="op">&lt;</span><span class="bu">Long</span><span class="op">,</span> Expr<span class="op">&gt;</span> <span class="fu">getNextEntryInternal</span><span class="op">(</span>AddressSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-71"><a href="#cb12-71"></a> ExprSpace s <span class="op">=</span> <span class="fu">getForSpace</span><span class="op">(</span>space<span class="op">,</span> <span class="kw">false</span><span class="op">);</span></span>
+<span id="cb12-72"><a href="#cb12-72"></a> <span class="cf">if</span> <span class="op">(</span>s <span class="op">==</span> <span class="kw">null</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-73"><a href="#cb12-73"></a> <span class="cf">return</span> <span class="kw">null</span><span class="op">;</span></span>
+<span id="cb12-74"><a href="#cb12-74"></a> <span class="op">}</span></span>
+<span id="cb12-75"><a href="#cb12-75"></a> <span class="cf">return</span> s<span class="op">.</span><span class="fu">getNextEntry</span><span class="op">(</span>offset<span class="op">);</span></span>
+<span id="cb12-76"><a href="#cb12-76"></a> <span class="op">}</span></span>
+<span id="cb12-77"><a href="#cb12-77"></a></span>
+<span id="cb12-78"><a href="#cb12-78"></a> <span class="at">@Override</span></span>
+<span id="cb12-79"><a href="#cb12-79"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">setInSpace</span><span class="op">(</span>ExprSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Expr val<span class="op">,</span></span>
+<span id="cb12-80"><a href="#cb12-80"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-81"><a href="#cb12-81"></a> space<span class="op">.</span><span class="fu">set</span><span class="op">(</span>offset<span class="op">,</span> size<span class="op">,</span> val<span class="op">,</span> cb<span class="op">);</span></span>
+<span id="cb12-82"><a href="#cb12-82"></a> <span class="op">}</span></span>
+<span id="cb12-83"><a href="#cb12-83"></a></span>
+<span id="cb12-84"><a href="#cb12-84"></a> <span class="at">@Override</span></span>
+<span id="cb12-85"><a href="#cb12-85"></a> <span class="kw">protected</span> Expr <span class="fu">getFromSpace</span><span class="op">(</span>ExprSpace space<span class="op">,</span> <span class="dt">long</span> offset<span class="op">,</span> <span class="dt">int</span> size<span class="op">,</span> Reason reason<span class="op">,</span></span>
+<span id="cb12-86"><a href="#cb12-86"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-87"><a href="#cb12-87"></a> <span class="cf">return</span> space<span class="op">.</span><span class="fu">get</span><span class="op">(</span>offset<span class="op">,</span> size<span class="op">,</span> reason<span class="op">,</span> cb<span class="op">);</span></span>
+<span id="cb12-88"><a href="#cb12-88"></a> <span class="op">}</span></span>
+<span id="cb12-89"><a href="#cb12-89"></a></span>
+<span id="cb12-90"><a href="#cb12-90"></a> <span class="at">@Override</span></span>
+<span id="cb12-91"><a href="#cb12-91"></a> <span class="kw">protected</span> <span class="bu">Map</span><span class="op">&lt;</span>Register<span class="op">,</span> Expr<span class="op">&gt;</span> <span class="fu">getRegisterValuesFromSpace</span><span class="op">(</span>ExprSpace s<span class="op">,</span></span>
+<span id="cb12-92"><a href="#cb12-92"></a> <span class="bu">List</span><span class="op">&lt;</span>Register<span class="op">&gt;</span> registers<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-93"><a href="#cb12-93"></a> <span class="cf">throw</span> <span class="kw">new</span> <span class="bu">UnsupportedOperationException</span><span class="op">();</span></span>
+<span id="cb12-94"><a href="#cb12-94"></a> <span class="op">}</span></span>
+<span id="cb12-95"><a href="#cb12-95"></a><span class="op">}</span></span>
+<span id="cb12-96"><a href="#cb12-96"></a></span>
+<span id="cb12-97"><a href="#cb12-97"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> BytesExprPcodeExecutorState <span class="kw">extends</span> PairedPcodeExecutorState<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;</span> <span class="op">{</span></span>
+<span id="cb12-98"><a href="#cb12-98"></a> <span class="kw">public</span> <span class="fu">BytesExprPcodeExecutorState</span><span class="op">(</span>PcodeExecutorStatePiece<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> <span class="dt">byte</span><span class="op">[]&gt;</span> concrete<span class="op">,</span></span>
+<span id="cb12-99"><a href="#cb12-99"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb12-100"><a href="#cb12-100"></a> <span class="kw">super</span><span class="op">(</span><span class="kw">new</span> PairedPcodeExecutorStatePiece<span class="op">&lt;&gt;(</span>concrete<span class="op">,</span></span>
+<span id="cb12-101"><a href="#cb12-101"></a> <span class="kw">new</span> <span class="fu">ExprPcodeExecutorStatePiece</span><span class="op">(</span>concrete<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span> cb<span class="op">)));</span></span>
+<span id="cb12-102"><a href="#cb12-102"></a> <span class="op">}</span></span>
+<span id="cb12-103"><a href="#cb12-103"></a><span class="op">}</span></span></code></pre></div>
<p>The abstract class implements a strategy where a dedicated object
handles each address space. Each object typically maintains of map of
offsets (type <code>long</code>) to the model type, i.e.,
@@ -924,63 +984,63 @@ models.</p>
<p>Ghidra supports the construction of augmented emulators through the
<code>AuxEmulatorPartsFactory&lt;Expr&gt;</code> interface. These are
typically singletons.</p>
-<div class="sourceCode" id="cb9"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb9-1"><a href="#cb9-1"></a><span class="kw">public</span> <span class="kw">enum</span> BytesExprEmulatorPartsFactory <span class="kw">implements</span> AuxEmulatorPartsFactory<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb9-2"><a href="#cb9-2"></a> INSTANCE<span class="op">;</span></span>
-<span id="cb9-3"><a href="#cb9-3"></a></span>
-<span id="cb9-4"><a href="#cb9-4"></a> <span class="at">@Override</span></span>
-<span id="cb9-5"><a href="#cb9-5"></a> <span class="kw">public</span> PcodeArithmetic<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getArithmetic</span><span class="op">(</span>Language language<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-6"><a href="#cb9-6"></a> <span class="cf">return</span> ExprPcodeArithmetic<span class="op">.</span><span class="fu">forLanguage</span><span class="op">(</span>language<span class="op">);</span></span>
-<span id="cb9-7"><a href="#cb9-7"></a> <span class="op">}</span></span>
-<span id="cb9-8"><a href="#cb9-8"></a></span>
-<span id="cb9-9"><a href="#cb9-9"></a> <span class="at">@Override</span></span>
-<span id="cb9-10"><a href="#cb9-10"></a> <span class="kw">public</span> PcodeUseropLibrary<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createSharedUseropLibrary</span><span class="op">(</span></span>
-<span id="cb9-11"><a href="#cb9-11"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-12"><a href="#cb9-12"></a> <span class="cf">return</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">();</span></span>
-<span id="cb9-13"><a href="#cb9-13"></a> <span class="op">}</span></span>
-<span id="cb9-14"><a href="#cb9-14"></a></span>
-<span id="cb9-15"><a href="#cb9-15"></a> <span class="at">@Override</span></span>
-<span id="cb9-16"><a href="#cb9-16"></a> <span class="kw">public</span> PcodeUseropLibrary<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createLocalUseropStub</span><span class="op">(</span></span>
-<span id="cb9-17"><a href="#cb9-17"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-18"><a href="#cb9-18"></a> <span class="cf">return</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">();</span></span>
-<span id="cb9-19"><a href="#cb9-19"></a> <span class="op">}</span></span>
-<span id="cb9-20"><a href="#cb9-20"></a></span>
-<span id="cb9-21"><a href="#cb9-21"></a> <span class="at">@Override</span></span>
-<span id="cb9-22"><a href="#cb9-22"></a> <span class="kw">public</span> PcodeUseropLibrary<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createLocalUseropLibrary</span><span class="op">(</span></span>
-<span id="cb9-23"><a href="#cb9-23"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">,</span> PcodeThread<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> thread<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-24"><a href="#cb9-24"></a> <span class="cf">return</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">();</span></span>
-<span id="cb9-25"><a href="#cb9-25"></a> <span class="op">}</span></span>
-<span id="cb9-26"><a href="#cb9-26"></a></span>
-<span id="cb9-27"><a href="#cb9-27"></a> <span class="at">@Override</span></span>
-<span id="cb9-28"><a href="#cb9-28"></a> <span class="kw">public</span> PcodeExecutorState<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createSharedState</span><span class="op">(</span></span>
-<span id="cb9-29"><a href="#cb9-29"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">,</span> BytesPcodeExecutorStatePiece concrete<span class="op">,</span></span>
-<span id="cb9-30"><a href="#cb9-30"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-31"><a href="#cb9-31"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeExecutorState</span><span class="op">(</span>concrete<span class="op">,</span> cb<span class="op">);</span></span>
-<span id="cb9-32"><a href="#cb9-32"></a> <span class="op">}</span></span>
-<span id="cb9-33"><a href="#cb9-33"></a></span>
-<span id="cb9-34"><a href="#cb9-34"></a> <span class="at">@Override</span></span>
-<span id="cb9-35"><a href="#cb9-35"></a> <span class="kw">public</span> PcodeExecutorState<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createLocalState</span><span class="op">(</span></span>
-<span id="cb9-36"><a href="#cb9-36"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">,</span> PcodeThread<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> thread<span class="op">,</span></span>
-<span id="cb9-37"><a href="#cb9-37"></a> BytesPcodeExecutorStatePiece concrete<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-38"><a href="#cb9-38"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeExecutorState</span><span class="op">(</span>concrete<span class="op">,</span> cb<span class="op">);</span></span>
-<span id="cb9-39"><a href="#cb9-39"></a> <span class="op">}</span></span>
-<span id="cb9-40"><a href="#cb9-40"></a><span class="op">}</span></span>
-<span id="cb9-41"><a href="#cb9-41"></a></span>
-<span id="cb9-42"><a href="#cb9-42"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> BytesExprPcodeEmulator <span class="kw">extends</span> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb9-43"><a href="#cb9-43"></a> <span class="kw">public</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>Language language<span class="op">,</span></span>
-<span id="cb9-44"><a href="#cb9-44"></a> PcodeEmulationCallbacks<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> cb<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-45"><a href="#cb9-45"></a> <span class="kw">super</span><span class="op">(</span>language<span class="op">,</span> cb<span class="op">);</span></span>
-<span id="cb9-46"><a href="#cb9-46"></a> <span class="op">}</span></span>
-<span id="cb9-47"><a href="#cb9-47"></a></span>
-<span id="cb9-48"><a href="#cb9-48"></a> <span class="kw">public</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>Language language<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb9-49"><a href="#cb9-49"></a> <span class="kw">this</span><span class="op">(</span>language<span class="op">,</span> PcodeEmulationCallbacks<span class="op">.</span><span class="fu">none</span><span class="op">());</span></span>
-<span id="cb9-50"><a href="#cb9-50"></a> <span class="op">}</span></span>
-<span id="cb9-51"><a href="#cb9-51"></a></span>
-<span id="cb9-52"><a href="#cb9-52"></a> <span class="at">@Override</span></span>
-<span id="cb9-53"><a href="#cb9-53"></a> <span class="kw">protected</span> AuxEmulatorPartsFactory<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getPartsFactory</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb9-54"><a href="#cb9-54"></a> <span class="cf">return</span> BytesExprEmulatorPartsFactory<span class="op">.</span><span class="fu">INSTANCE</span><span class="op">;</span></span>
-<span id="cb9-55"><a href="#cb9-55"></a> <span class="op">}</span></span>
-<span id="cb9-56"><a href="#cb9-56"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb13"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb13-1"><a href="#cb13-1"></a><span class="kw">public</span> <span class="kw">enum</span> BytesExprEmulatorPartsFactory <span class="kw">implements</span> AuxEmulatorPartsFactory<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="op">{</span></span>
+<span id="cb13-2"><a href="#cb13-2"></a> INSTANCE<span class="op">;</span></span>
+<span id="cb13-3"><a href="#cb13-3"></a></span>
+<span id="cb13-4"><a href="#cb13-4"></a> <span class="at">@Override</span></span>
+<span id="cb13-5"><a href="#cb13-5"></a> <span class="kw">public</span> PcodeArithmetic<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getArithmetic</span><span class="op">(</span>Language language<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-6"><a href="#cb13-6"></a> <span class="cf">return</span> ExprPcodeArithmetic<span class="op">.</span><span class="fu">forLanguage</span><span class="op">(</span>language<span class="op">);</span></span>
+<span id="cb13-7"><a href="#cb13-7"></a> <span class="op">}</span></span>
+<span id="cb13-8"><a href="#cb13-8"></a></span>
+<span id="cb13-9"><a href="#cb13-9"></a> <span class="at">@Override</span></span>
+<span id="cb13-10"><a href="#cb13-10"></a> <span class="kw">public</span> PcodeUseropLibrary<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createSharedUseropLibrary</span><span class="op">(</span></span>
+<span id="cb13-11"><a href="#cb13-11"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-12"><a href="#cb13-12"></a> <span class="cf">return</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">();</span></span>
+<span id="cb13-13"><a href="#cb13-13"></a> <span class="op">}</span></span>
+<span id="cb13-14"><a href="#cb13-14"></a></span>
+<span id="cb13-15"><a href="#cb13-15"></a> <span class="at">@Override</span></span>
+<span id="cb13-16"><a href="#cb13-16"></a> <span class="kw">public</span> PcodeUseropLibrary<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createLocalUseropStub</span><span class="op">(</span></span>
+<span id="cb13-17"><a href="#cb13-17"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-18"><a href="#cb13-18"></a> <span class="cf">return</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">();</span></span>
+<span id="cb13-19"><a href="#cb13-19"></a> <span class="op">}</span></span>
+<span id="cb13-20"><a href="#cb13-20"></a></span>
+<span id="cb13-21"><a href="#cb13-21"></a> <span class="at">@Override</span></span>
+<span id="cb13-22"><a href="#cb13-22"></a> <span class="kw">public</span> PcodeUseropLibrary<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createLocalUseropLibrary</span><span class="op">(</span></span>
+<span id="cb13-23"><a href="#cb13-23"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">,</span> PcodeThread<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> thread<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-24"><a href="#cb13-24"></a> <span class="cf">return</span> PcodeUseropLibrary<span class="op">.</span><span class="fu">nil</span><span class="op">();</span></span>
+<span id="cb13-25"><a href="#cb13-25"></a> <span class="op">}</span></span>
+<span id="cb13-26"><a href="#cb13-26"></a></span>
+<span id="cb13-27"><a href="#cb13-27"></a> <span class="at">@Override</span></span>
+<span id="cb13-28"><a href="#cb13-28"></a> <span class="kw">public</span> PcodeExecutorState<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createSharedState</span><span class="op">(</span></span>
+<span id="cb13-29"><a href="#cb13-29"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">,</span> BytesPcodeExecutorStatePiece concrete<span class="op">,</span></span>
+<span id="cb13-30"><a href="#cb13-30"></a> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-31"><a href="#cb13-31"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeExecutorState</span><span class="op">(</span>concrete<span class="op">,</span> cb<span class="op">);</span></span>
+<span id="cb13-32"><a href="#cb13-32"></a> <span class="op">}</span></span>
+<span id="cb13-33"><a href="#cb13-33"></a></span>
+<span id="cb13-34"><a href="#cb13-34"></a> <span class="at">@Override</span></span>
+<span id="cb13-35"><a href="#cb13-35"></a> <span class="kw">public</span> PcodeExecutorState<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> <span class="fu">createLocalState</span><span class="op">(</span></span>
+<span id="cb13-36"><a href="#cb13-36"></a> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> emulator<span class="op">,</span> PcodeThread<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> thread<span class="op">,</span></span>
+<span id="cb13-37"><a href="#cb13-37"></a> BytesPcodeExecutorStatePiece concrete<span class="op">,</span> PcodeStateCallbacks cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-38"><a href="#cb13-38"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeExecutorState</span><span class="op">(</span>concrete<span class="op">,</span> cb<span class="op">);</span></span>
+<span id="cb13-39"><a href="#cb13-39"></a> <span class="op">}</span></span>
+<span id="cb13-40"><a href="#cb13-40"></a><span class="op">}</span></span>
+<span id="cb13-41"><a href="#cb13-41"></a></span>
+<span id="cb13-42"><a href="#cb13-42"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> BytesExprPcodeEmulator <span class="kw">extends</span> AuxPcodeEmulator<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="op">{</span></span>
+<span id="cb13-43"><a href="#cb13-43"></a> <span class="kw">public</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>Language language<span class="op">,</span></span>
+<span id="cb13-44"><a href="#cb13-44"></a> PcodeEmulationCallbacks<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> cb<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-45"><a href="#cb13-45"></a> <span class="kw">super</span><span class="op">(</span>language<span class="op">,</span> cb<span class="op">);</span></span>
+<span id="cb13-46"><a href="#cb13-46"></a> <span class="op">}</span></span>
+<span id="cb13-47"><a href="#cb13-47"></a></span>
+<span id="cb13-48"><a href="#cb13-48"></a> <span class="kw">public</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>Language language<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb13-49"><a href="#cb13-49"></a> <span class="kw">this</span><span class="op">(</span>language<span class="op">,</span> PcodeEmulationCallbacks<span class="op">.</span><span class="fu">none</span><span class="op">());</span></span>
+<span id="cb13-50"><a href="#cb13-50"></a> <span class="op">}</span></span>
+<span id="cb13-51"><a href="#cb13-51"></a></span>
+<span id="cb13-52"><a href="#cb13-52"></a> <span class="at">@Override</span></span>
+<span id="cb13-53"><a href="#cb13-53"></a> <span class="kw">protected</span> AuxEmulatorPartsFactory<span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getPartsFactory</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb13-54"><a href="#cb13-54"></a> <span class="cf">return</span> BytesExprEmulatorPartsFactory<span class="op">.</span><span class="fu">INSTANCE</span><span class="op">;</span></span>
+<span id="cb13-55"><a href="#cb13-55"></a> <span class="op">}</span></span>
+<span id="cb13-56"><a href="#cb13-56"></a><span class="op">}</span></span></code></pre></div>
<p>Lots of boilerplate. Essentially, all the parts factory does is give
us a flat interface for providing all the parts necessary to construct
our augmented emulator: the model arithmetic, userop libraries for the
@@ -993,31 +1053,30 @@ and construct our augmented state.</p>
</section>
<section id="use-in-dynamic-analysis" class="level2">
<h2>Use in Dynamic Analysis</h2>
-<p>What we have constructed so far is suitable for constructing and
-using our augmented emulator in a script. Using it is about as
-straightforward as the plain concrete emulator. The exception may be
-when accessing its state, you will need to be cognizant of the
-pairing.</p>
-<div class="sourceCode" id="cb10"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb10-1"><a href="#cb10-1"></a><span class="kw">public</span> <span class="kw">class</span> ModelingScript <span class="kw">extends</span> GhidraScript <span class="op">{</span></span>
-<span id="cb10-2"><a href="#cb10-2"></a></span>
-<span id="cb10-3"><a href="#cb10-3"></a> <span class="co">// ...</span></span>
-<span id="cb10-4"><a href="#cb10-4"></a></span>
-<span id="cb10-5"><a href="#cb10-5"></a> <span class="at">@Override</span></span>
-<span id="cb10-6"><a href="#cb10-6"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
-<span id="cb10-7"><a href="#cb10-7"></a> BytesExprPcodeEmulator emu <span class="op">=</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>currentProgram<span class="op">.</span><span class="fu">getLanguage</span><span class="op">());</span></span>
-<span id="cb10-8"><a href="#cb10-8"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the machine</span></span>
-<span id="cb10-9"><a href="#cb10-9"></a> PcodeExecutorState<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> state <span class="op">=</span> emu<span class="op">.</span><span class="fu">getSharedState</span><span class="op">();</span></span>
-<span id="cb10-10"><a href="#cb10-10"></a> state<span class="op">.</span><span class="fu">setVar</span><span class="op">(</span>currentAddress<span class="op">,</span> <span class="dv">4</span><span class="op">,</span> <span class="kw">true</span><span class="op">,</span></span>
-<span id="cb10-11"><a href="#cb10-11"></a> Pair<span class="op">.</span><span class="fu">of</span><span class="op">(</span><span class="kw">new</span> <span class="dt">byte</span><span class="op">[]</span> <span class="op">{</span> <span class="dv">1</span><span class="op">,</span> <span class="dv">2</span><span class="op">,</span> <span class="dv">3</span><span class="op">,</span> <span class="dv">4</span> <span class="op">},</span> <span class="kw">new</span> <span class="fu">VarExpr</span><span class="op">(</span>currentAddress<span class="op">,</span> <span class="dv">4</span><span class="op">)));</span></span>
-<span id="cb10-12"><a href="#cb10-12"></a> PcodeThread<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> thread <span class="op">=</span> emu<span class="op">.</span><span class="fu">newThread</span><span class="op">();</span></span>
-<span id="cb10-13"><a href="#cb10-13"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the thread</span></span>
-<span id="cb10-14"><a href="#cb10-14"></a> <span class="cf">while</span> <span class="op">(</span><span class="kw">true</span><span class="op">)</span> <span class="op">{</span></span>
-<span id="cb10-15"><a href="#cb10-15"></a> monitor<span class="op">.</span><span class="fu">checkCancelled</span><span class="op">();</span></span>
-<span id="cb10-16"><a href="#cb10-16"></a> thread<span class="op">.</span><span class="fu">stepInstruction</span><span class="op">(</span><span class="dv">100</span><span class="op">);</span></span>
-<span id="cb10-17"><a href="#cb10-17"></a> <span class="op">}</span></span>
-<span id="cb10-18"><a href="#cb10-18"></a> <span class="op">}</span></span>
-<span id="cb10-19"><a href="#cb10-19"></a><span class="op">}</span></span></code></pre></div>
+<p>What we have built so far is suitable for constructing and using our
+augmented emulator in a script. Using it is about as straightforward as
+the plain concrete emulator. The exception may be when accessing its
+state, you will need to be cognizant of the pairing.</p>
+<div class="sourceCode" id="cb14"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb14-1"><a href="#cb14-1"></a><span class="kw">public</span> <span class="kw">class</span> ModelingScript <span class="kw">extends</span> GhidraScript <span class="op">{</span></span>
+<span id="cb14-2"><a href="#cb14-2"></a></span>
+<span id="cb14-3"><a href="#cb14-3"></a> <span class="co">// ...</span></span>
+<span id="cb14-4"><a href="#cb14-4"></a></span>
+<span id="cb14-5"><a href="#cb14-5"></a> <span class="at">@Override</span></span>
+<span id="cb14-6"><a href="#cb14-6"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
+<span id="cb14-7"><a href="#cb14-7"></a> BytesExprPcodeEmulator emu <span class="op">=</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>currentProgram<span class="op">.</span><span class="fu">getLanguage</span><span class="op">());</span></span>
+<span id="cb14-8"><a href="#cb14-8"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the machine</span></span>
+<span id="cb14-9"><a href="#cb14-9"></a> PcodeExecutorState<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> state <span class="op">=</span> emu<span class="op">.</span><span class="fu">getSharedState</span><span class="op">();</span></span>
+<span id="cb14-10"><a href="#cb14-10"></a> state<span class="op">.</span><span class="fu">setVar</span><span class="op">(</span>currentAddress<span class="op">,</span> <span class="dv">4</span><span class="op">,</span> <span class="kw">true</span><span class="op">,</span></span>
+<span id="cb14-11"><a href="#cb14-11"></a> Pair<span class="op">.</span><span class="fu">of</span><span class="op">(</span><span class="kw">new</span> <span class="dt">byte</span><span class="op">[]</span> <span class="op">{</span> <span class="dv">1</span><span class="op">,</span> <span class="dv">2</span><span class="op">,</span> <span class="dv">3</span><span class="op">,</span> <span class="dv">4</span> <span class="op">},</span> <span class="kw">new</span> <span class="fu">VarExpr</span><span class="op">(</span>currentAddress<span class="op">,</span> <span class="dv">4</span><span class="op">)));</span></span>
+<span id="cb14-12"><a href="#cb14-12"></a> PcodeThread<span class="op">&lt;</span>Pair<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">&gt;&gt;</span> thread <span class="op">=</span> emu<span class="op">.</span><span class="fu">newThread</span><span class="op">();</span></span>
+<span id="cb14-13"><a href="#cb14-13"></a> <span class="co">// </span><span class="al">TODO</span><span class="co">: Initialize the thread</span></span>
+<span id="cb14-14"><a href="#cb14-14"></a> <span class="cf">while</span> <span class="op">(</span><span class="kw">true</span><span class="op">)</span> <span class="op">{</span></span>
+<span id="cb14-15"><a href="#cb14-15"></a> monitor<span class="op">.</span><span class="fu">checkCancelled</span><span class="op">();</span></span>
+<span id="cb14-16"><a href="#cb14-16"></a> thread<span class="op">.</span><span class="fu">stepInstruction</span><span class="op">(</span><span class="dv">100</span><span class="op">);</span></span>
+<span id="cb14-17"><a href="#cb14-17"></a> <span class="op">}</span></span>
+<span id="cb14-18"><a href="#cb14-18"></a> <span class="op">}</span></span>
+<span id="cb14-19"><a href="#cb14-19"></a><span class="op">}</span></span></code></pre></div>
<p><strong>NOTE</strong>: When accessed as a paired state, all sets will
affect both pieces. If you use the arithmetic to generate them, remember
that it will use <code>fromConst</code> on both sub-arithmetics to
@@ -1048,39 +1107,39 @@ The only functionality we need to provide is a means of serializing
also human readable, since that will make it straightforward to display
in the UI. We need only provide a <code>PieceHandler</code> for our new
state piece.</p>
-<div class="sourceCode" id="cb11"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb11-1"><a href="#cb11-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> ExprPieceHandler</span>
-<span id="cb11-2"><a href="#cb11-2"></a> <span class="kw">extends</span> AbstractSimplePropertyBasedPieceHandler<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">,</span> <span class="bu">String</span><span class="op">&gt;</span> <span class="op">{</span></span>
-<span id="cb11-3"><a href="#cb11-3"></a> <span class="at">@Override</span></span>
-<span id="cb11-4"><a href="#cb11-4"></a> <span class="kw">public</span> <span class="bu">Class</span><span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> <span class="fu">getAddressDomain</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb11-5"><a href="#cb11-5"></a> <span class="cf">return</span> <span class="dt">byte</span><span class="op">[].</span><span class="fu">class</span><span class="op">;</span></span>
-<span id="cb11-6"><a href="#cb11-6"></a> <span class="op">}</span></span>
-<span id="cb11-7"><a href="#cb11-7"></a></span>
-<span id="cb11-8"><a href="#cb11-8"></a> <span class="at">@Override</span></span>
-<span id="cb11-9"><a href="#cb11-9"></a> <span class="kw">public</span> <span class="bu">Class</span><span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getValueDomain</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb11-10"><a href="#cb11-10"></a> <span class="cf">return</span> Expr<span class="op">.</span><span class="fu">class</span><span class="op">;</span></span>
-<span id="cb11-11"><a href="#cb11-11"></a> <span class="op">}</span></span>
-<span id="cb11-12"><a href="#cb11-12"></a></span>
-<span id="cb11-13"><a href="#cb11-13"></a> <span class="at">@Override</span></span>
-<span id="cb11-14"><a href="#cb11-14"></a> <span class="kw">protected</span> <span class="bu">String</span> <span class="fu">getPropertyName</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb11-15"><a href="#cb11-15"></a> <span class="cf">return</span> <span class="st">&quot;Expr&quot;</span><span class="op">;</span></span>
-<span id="cb11-16"><a href="#cb11-16"></a> <span class="op">}</span></span>
-<span id="cb11-17"><a href="#cb11-17"></a></span>
-<span id="cb11-18"><a href="#cb11-18"></a> <span class="at">@Override</span></span>
-<span id="cb11-19"><a href="#cb11-19"></a> <span class="kw">protected</span> <span class="bu">Class</span><span class="op">&lt;</span><span class="bu">String</span><span class="op">&gt;</span> <span class="fu">getPropertyType</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb11-20"><a href="#cb11-20"></a> <span class="cf">return</span> <span class="bu">String</span><span class="op">.</span><span class="fu">class</span><span class="op">;</span></span>
-<span id="cb11-21"><a href="#cb11-21"></a> <span class="op">}</span></span>
-<span id="cb11-22"><a href="#cb11-22"></a></span>
-<span id="cb11-23"><a href="#cb11-23"></a> <span class="at">@Override</span></span>
-<span id="cb11-24"><a href="#cb11-24"></a> <span class="kw">protected</span> Expr <span class="fu">decode</span><span class="op">(</span><span class="bu">String</span> propertyValue<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb11-25"><a href="#cb11-25"></a> <span class="cf">return</span> Unfinished<span class="op">.</span><span class="fu">TODO</span><span class="op">(</span><span class="st">&quot;Left as an exercise&quot;</span><span class="op">);</span></span>
-<span id="cb11-26"><a href="#cb11-26"></a> <span class="op">}</span></span>
-<span id="cb11-27"><a href="#cb11-27"></a></span>
-<span id="cb11-28"><a href="#cb11-28"></a> <span class="at">@Override</span></span>
-<span id="cb11-29"><a href="#cb11-29"></a> <span class="kw">protected</span> <span class="bu">String</span> <span class="fu">encode</span><span class="op">(</span>Expr value<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb11-30"><a href="#cb11-30"></a> <span class="cf">return</span> Unfinished<span class="op">.</span><span class="fu">TODO</span><span class="op">(</span><span class="st">&quot;Left as an exercise&quot;</span><span class="op">);</span></span>
-<span id="cb11-31"><a href="#cb11-31"></a> <span class="op">}</span></span>
-<span id="cb11-32"><a href="#cb11-32"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb15"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb15-1"><a href="#cb15-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> ExprPieceHandler</span>
+<span id="cb15-2"><a href="#cb15-2"></a> <span class="kw">extends</span> AbstractSimplePropertyBasedPieceHandler<span class="op">&lt;</span><span class="dt">byte</span><span class="op">[],</span> Expr<span class="op">,</span> <span class="bu">String</span><span class="op">&gt;</span> <span class="op">{</span></span>
+<span id="cb15-3"><a href="#cb15-3"></a> <span class="at">@Override</span></span>
+<span id="cb15-4"><a href="#cb15-4"></a> <span class="kw">public</span> <span class="bu">Class</span><span class="op">&lt;</span><span class="dt">byte</span><span class="op">[]&gt;</span> <span class="fu">getAddressDomain</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb15-5"><a href="#cb15-5"></a> <span class="cf">return</span> <span class="dt">byte</span><span class="op">[].</span><span class="fu">class</span><span class="op">;</span></span>
+<span id="cb15-6"><a href="#cb15-6"></a> <span class="op">}</span></span>
+<span id="cb15-7"><a href="#cb15-7"></a></span>
+<span id="cb15-8"><a href="#cb15-8"></a> <span class="at">@Override</span></span>
+<span id="cb15-9"><a href="#cb15-9"></a> <span class="kw">public</span> <span class="bu">Class</span><span class="op">&lt;</span>Expr<span class="op">&gt;</span> <span class="fu">getValueDomain</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb15-10"><a href="#cb15-10"></a> <span class="cf">return</span> Expr<span class="op">.</span><span class="fu">class</span><span class="op">;</span></span>
+<span id="cb15-11"><a href="#cb15-11"></a> <span class="op">}</span></span>
+<span id="cb15-12"><a href="#cb15-12"></a></span>
+<span id="cb15-13"><a href="#cb15-13"></a> <span class="at">@Override</span></span>
+<span id="cb15-14"><a href="#cb15-14"></a> <span class="kw">protected</span> <span class="bu">String</span> <span class="fu">getPropertyName</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb15-15"><a href="#cb15-15"></a> <span class="cf">return</span> <span class="st">&quot;Expr&quot;</span><span class="op">;</span></span>
+<span id="cb15-16"><a href="#cb15-16"></a> <span class="op">}</span></span>
+<span id="cb15-17"><a href="#cb15-17"></a></span>
+<span id="cb15-18"><a href="#cb15-18"></a> <span class="at">@Override</span></span>
+<span id="cb15-19"><a href="#cb15-19"></a> <span class="kw">protected</span> <span class="bu">Class</span><span class="op">&lt;</span><span class="bu">String</span><span class="op">&gt;</span> <span class="fu">getPropertyType</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb15-20"><a href="#cb15-20"></a> <span class="cf">return</span> <span class="bu">String</span><span class="op">.</span><span class="fu">class</span><span class="op">;</span></span>
+<span id="cb15-21"><a href="#cb15-21"></a> <span class="op">}</span></span>
+<span id="cb15-22"><a href="#cb15-22"></a></span>
+<span id="cb15-23"><a href="#cb15-23"></a> <span class="at">@Override</span></span>
+<span id="cb15-24"><a href="#cb15-24"></a> <span class="kw">protected</span> Expr <span class="fu">decode</span><span class="op">(</span><span class="bu">String</span> propertyValue<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb15-25"><a href="#cb15-25"></a> <span class="cf">return</span> Unfinished<span class="op">.</span><span class="fu">TODO</span><span class="op">(</span><span class="st">&quot;Left as an exercise&quot;</span><span class="op">);</span></span>
+<span id="cb15-26"><a href="#cb15-26"></a> <span class="op">}</span></span>
+<span id="cb15-27"><a href="#cb15-27"></a></span>
+<span id="cb15-28"><a href="#cb15-28"></a> <span class="at">@Override</span></span>
+<span id="cb15-29"><a href="#cb15-29"></a> <span class="kw">protected</span> <span class="bu">String</span> <span class="fu">encode</span><span class="op">(</span>Expr value<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb15-30"><a href="#cb15-30"></a> <span class="cf">return</span> Unfinished<span class="op">.</span><span class="fu">TODO</span><span class="op">(</span><span class="st">&quot;Left as an exercise&quot;</span><span class="op">);</span></span>
+<span id="cb15-31"><a href="#cb15-31"></a> <span class="op">}</span></span>
+<span id="cb15-32"><a href="#cb15-32"></a><span class="op">}</span></span></code></pre></div>
<p>This piece handler identifies itself as suitable for handling pieces
where the address domain is concrete <code>byte[]</code> and the value
domain is our abstract <code>Expr</code>. It then claims the property
@@ -1092,19 +1151,19 @@ you’d like to do the exercise of implementing the piecewise and/or
overlapping variable access.</p>
<p>Last, we implement the final <code>Expr</code>-augmented emulator
factory:</p>
-<div class="sourceCode" id="cb12"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb12-1"><a href="#cb12-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> BytesExprEmulatorFactory <span class="kw">implements</span> EmulatorFactory <span class="op">{</span></span>
-<span id="cb12-2"><a href="#cb12-2"></a> <span class="at">@Override</span></span>
-<span id="cb12-3"><a href="#cb12-3"></a> <span class="kw">public</span> <span class="bu">String</span> <span class="fu">getTitle</span><span class="op">()</span> <span class="op">{</span></span>
-<span id="cb12-4"><a href="#cb12-4"></a> <span class="cf">return</span> <span class="st">&quot;Expr&quot;</span><span class="op">;</span></span>
-<span id="cb12-5"><a href="#cb12-5"></a> <span class="op">}</span></span>
-<span id="cb12-6"><a href="#cb12-6"></a></span>
-<span id="cb12-7"><a href="#cb12-7"></a> <span class="at">@Override</span></span>
-<span id="cb12-8"><a href="#cb12-8"></a> <span class="kw">public</span> PcodeMachine<span class="op">&lt;?&gt;</span> <span class="fu">create</span><span class="op">(</span>PcodeDebuggerAccess access<span class="op">,</span> <span class="bu">Writer</span> writer<span class="op">)</span> <span class="op">{</span></span>
-<span id="cb12-9"><a href="#cb12-9"></a> writer<span class="op">.</span><span class="fu">putHandler</span><span class="op">(</span><span class="kw">new</span> <span class="fu">ExprPieceHandler</span><span class="op">());</span></span>
-<span id="cb12-10"><a href="#cb12-10"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>access<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span> writer<span class="op">.</span><span class="fu">callbacks</span><span class="op">());</span></span>
-<span id="cb12-11"><a href="#cb12-11"></a> <span class="op">}</span></span>
-<span id="cb12-12"><a href="#cb12-12"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb16"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb16-1"><a href="#cb16-1"></a><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> BytesExprEmulatorFactory <span class="kw">implements</span> EmulatorFactory <span class="op">{</span></span>
+<span id="cb16-2"><a href="#cb16-2"></a> <span class="at">@Override</span></span>
+<span id="cb16-3"><a href="#cb16-3"></a> <span class="kw">public</span> <span class="bu">String</span> <span class="fu">getTitle</span><span class="op">()</span> <span class="op">{</span></span>
+<span id="cb16-4"><a href="#cb16-4"></a> <span class="cf">return</span> <span class="st">&quot;Expr&quot;</span><span class="op">;</span></span>
+<span id="cb16-5"><a href="#cb16-5"></a> <span class="op">}</span></span>
+<span id="cb16-6"><a href="#cb16-6"></a></span>
+<span id="cb16-7"><a href="#cb16-7"></a> <span class="at">@Override</span></span>
+<span id="cb16-8"><a href="#cb16-8"></a> <span class="kw">public</span> PcodeMachine<span class="op">&lt;?&gt;</span> <span class="fu">create</span><span class="op">(</span>PcodeDebuggerAccess access<span class="op">,</span> <span class="bu">Writer</span> writer<span class="op">)</span> <span class="op">{</span></span>
+<span id="cb16-9"><a href="#cb16-9"></a> writer<span class="op">.</span><span class="fu">putHandler</span><span class="op">(</span><span class="kw">new</span> <span class="fu">ExprPieceHandler</span><span class="op">());</span></span>
+<span id="cb16-10"><a href="#cb16-10"></a> <span class="cf">return</span> <span class="kw">new</span> <span class="fu">BytesExprPcodeEmulator</span><span class="op">(</span>access<span class="op">.</span><span class="fu">getLanguage</span><span class="op">(),</span> writer<span class="op">.</span><span class="fu">callbacks</span><span class="op">());</span></span>
+<span id="cb16-11"><a href="#cb16-11"></a> <span class="op">}</span></span>
+<span id="cb16-12"><a href="#cb16-12"></a><span class="op">}</span></span></code></pre></div>
<p>It merely takes the framework-provided trace <code>Writer</code> and
adds our <code>ExprPieceHandler</code> to it.</p>
<p>This factory can then be installed using a script. The script will
@@ -1113,14 +1172,14 @@ however, your script-based factory will not be listed in the menus.
Also, if you change your emulator, you must re-run the script to install
those modifications. You might also want to invalidate the emulation
cache.</p>
-<div class="sourceCode" id="cb13"><pre
-class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb13-1"><a href="#cb13-1"></a><span class="kw">public</span> <span class="kw">class</span> InstallExprEmulatorScript <span class="kw">extends</span> GhidraScript <span class="kw">implements</span> FlatDebuggerAPI <span class="op">{</span></span>
-<span id="cb13-2"><a href="#cb13-2"></a> <span class="at">@Override</span></span>
-<span id="cb13-3"><a href="#cb13-3"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
-<span id="cb13-4"><a href="#cb13-4"></a> <span class="fu">getEmulationService</span><span class="op">()</span></span>
-<span id="cb13-5"><a href="#cb13-5"></a> <span class="op">.</span><span class="fu">setEmulatorFactory</span><span class="op">(</span><span class="kw">new</span> ModelingScript<span class="op">.</span><span class="fu">BytesExprEmulatorFactory</span><span class="op">());</span></span>
-<span id="cb13-6"><a href="#cb13-6"></a> <span class="op">}</span></span>
-<span id="cb13-7"><a href="#cb13-7"></a><span class="op">}</span></span></code></pre></div>
+<div class="sourceCode" id="cb17"><pre
+class="sourceCode numberSource java numberLines"><code class="sourceCode java"><span id="cb17-1"><a href="#cb17-1"></a><span class="kw">public</span> <span class="kw">class</span> InstallExprEmulatorScript <span class="kw">extends</span> GhidraScript <span class="kw">implements</span> FlatDebuggerAPI <span class="op">{</span></span>
+<span id="cb17-2"><a href="#cb17-2"></a> <span class="at">@Override</span></span>
+<span id="cb17-3"><a href="#cb17-3"></a> <span class="kw">protected</span> <span class="dt">void</span> <span class="fu">run</span><span class="op">()</span> <span class="kw">throws</span> <span class="bu">Exception</span> <span class="op">{</span></span>
+<span id="cb17-4"><a href="#cb17-4"></a> <span class="fu">getEmulationService</span><span class="op">()</span></span>
+<span id="cb17-5"><a href="#cb17-5"></a> <span class="op">.</span><span class="fu">setEmulatorFactory</span><span class="op">(</span><span class="kw">new</span> ModelingScript<span class="op">.</span><span class="fu">BytesExprEmulatorFactory</span><span class="op">());</span></span>
+<span id="cb17-6"><a href="#cb17-6"></a> <span class="op">}</span></span>
+<span id="cb17-7"><a href="#cb17-7"></a><span class="op">}</span></span></code></pre></div>
<p>Alternatively, and this is recommended once your emulator is
“production ready,” you should create a proper Module project using the
GhidraDev plugin for Eclipse. You will need to break all the nested
diff --git a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.md b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.md
index 5da7b2eddd..dfbeb7292e 100644
--- a/GhidraDocs/GhidraClass/Debugger/B4-Modeling.md
+++ b/GhidraDocs/GhidraClass/Debugger/B4-Modeling.md
@@ -37,7 +37,7 @@ By providing common stubs in a userop library, the user can stub the external fu
### Modeling by Java Callbacks
A userop library is created by implementing the `PcodeUseropLibrary` interface, most likely by extending `AnnotatedPcodeUseropLibrary`.
-For example, to provide a stub for `strlen`:
+For example, to provide a stub for `strnlen`:
```java {.numberLines}
public static class JavaStdLibPcodeUseropLibrary<T> extends AnnotatedPcodeUseropLibrary<T> {
@@ -47,7 +47,7 @@ public static class JavaStdLibPcodeUseropLibrary<T> extends AnnotatedPcodeUserop
private final Register regRDI;
private final Register regRSI;
- public JavaStdLibPcodeUseropLibrary(SleighLanguage language) {
+ public JavaStdLibPcodeUseropLibrary(Language language) {
space = language.getDefaultSpace();
regRSP = language.getRegister("RSP");
regRAX = language.getRegister("RAX");
@@ -56,21 +56,18 @@ public static class JavaStdLibPcodeUseropLibrary<T> extends AnnotatedPcodeUserop
}
@PcodeUserop
- public void __x86_64_RET(
- @OpExecutor PcodeExecutor<T> executor,
- @OpState PcodeExecutorState<T> state) {
+ public void __x86_64_POP(@OpExecutor PcodeExecutor<T> executor,
+ @OpState PcodeExecutorState<T> state, @OpOutput Varnode out) {
PcodeArithmetic<T> arithmetic = state.getArithmetic();
T tRSP = state.getVar(regRSP, Reason.EXECUTE_READ);
- long lRSP = arithmetic.toLong(tRSP, Purpose.OTHER);
+ long lRSP = arithmetic.toLong(tRSP, Purpose.LOAD);
T tReturn = state.getVar(space, lRSP, 8, true, Reason.EXECUTE_READ);
- long lReturn = arithmetic.toLong(tReturn, Purpose.BRANCH);
state.setVar(regRSP, arithmetic.fromConst(lRSP + 8, 8));
- ((PcodeThreadExecutor<T>) executor).getThread()
- .overrideCounter(space.getAddress(lReturn));
+ state.setVar(out, tReturn);
}
@PcodeUserop
- public void __libc_strlen(@OpState PcodeExecutorState<T> state) {
+ public void __libc_strnlen(@OpState PcodeExecutorState<T> state) {
PcodeArithmetic<T> arithmetic = state.getArithmetic();
T tStr = state.getVar(regRDI, Reason.EXECUTE_READ);
long lStr = arithmetic.toLong(tStr, Purpose.OTHER);
@@ -91,7 +88,11 @@ public static class JavaStdLibPcodeUseropLibrary<T> extends AnnotatedPcodeUserop
Here, we implement the stub using Java callbacks.
This is more useful when modeling things outside of Ghidra's definition of machine state, e.g., to simulate kernel objects in an underlying operating system.
Nevertheless, it can be used to model simple state changes as well.
-A user would place a breakpoint at either the call site or the call target, have it invoke `__libc_strlen()`, and then invoke either `emu_skip_decoded()` or `__x86_64_RET()` depending on where the breakpoint was placed.
+A user would place a breakpoint at either the call site or the call target, have it invoke `__libc_strnlen()`, and then invoke either `emu_skip_decoded()` or `RIP = __x86_64_POP(); return [RIP];` depending on where the breakpoint was placed.
+**NOTE**: Control transfers should rarely, if ever, be performed within a userop, except internal to that userop.
+This assures advanced execution engines can better process the control graph of the target.
+In particular, invoking `thread.overrideCounter()` from within a Java-callback userop is *not* recommended.
+It is better to place such control transfers in the injection, which is why we include `return [RIP];` rather than having an `__x86_64_RET()` userop that performs the control transfer.
### Modeling by Sleigh Semantics
@@ -100,79 +101,124 @@ You may notice the library uses a type parameter `T`, which specifies the type o
Leaving it as `T` indicates the library is compatible with any type.
For a concrete emulator, `T := byte[]`, and so there is no loss in making things concrete, and then converting back to `T` using the `arithmetic` object.
However, if the emulator has been augmented, as we will discuss below, the model may become confused, because values computed by a careless userop will appear to the model a literal constant.
-To avoid this, you should keep everything a T and use the `arithmetic` object to perform any arithmetic operations.
-Alternatively, you can implement the userop using pre-compiled Sleigh code:
+To avoid this, you should keep everything a `T` and use the `arithmetic` object to perform any arithmetic operations.
+Alternatively, you can implement the userop using Sleigh code:
```java {.numberLines}
public static class SleighStdLibPcodeUseropLibrary<T> extends AnnotatedPcodeUseropLibrary<T> {
- private static final String SRC_RET = """
- RIP = *:8 RSP;
- RSP = RSP + 8;
- return [RIP];
- """;
- private static final String SRC_STRLEN = """
- __result = 0;
- <loop>
- if (*:1 (str+__result) == 0 || __result >= maxlen) goto <exit>;
- __result = __result + 1;
- goto <loop>;
- <exit>
- """;
- private final Register regRAX;
- private final Register regRDI;
- private final Register regRSI;
- private final Varnode vnRAX;
- private final Varnode vnRDI;
- private final Varnode vnRSI;
-
- private PcodeProgram progRet;
- private PcodeProgram progStrlen;
-
- public SleighStdLibPcodeUseropLibrary(SleighLanguage language) {
- regRAX = language.getRegister("RAX");
- regRDI = language.getRegister("RDI");
- regRSI = language.getRegister("RSI");
- vnRAX = new Varnode(regRAX.getAddress(), regRAX.getMinimumByteSize());
- vnRDI = new Varnode(regRDI.getAddress(), regRDI.getMinimumByteSize());
- vnRSI = new Varnode(regRSI.getAddress(), regRSI.getMinimumByteSize());
+ @PcodeUserop
+ public SleighPcodeUseropDefinition __x86_64_POP(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
+ __op_output = *:8 RSP;
+ RSP = RSP + 8;
+ """).build();
}
@PcodeUserop
- public void __x86_64_RET(@OpExecutor PcodeExecutor<T> executor,
- @OpLibrary PcodeUseropLibrary<T> library) {
- if (progRet == null) {
- progRet = SleighProgramCompiler.compileUserop(executor.getLanguage(),
- "__x86_64_RET", List.of(), SRC_RET, PcodeUseropLibrary.nil(), List.of());
- }
- progRet.execute(executor, library);
+ public SleighPcodeUseropDefinition __libc_strnlen(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
+ RAX = __libc_strnlen_generic(RDI, RSI);
+ """).build();
}
@PcodeUserop
- public void __libc_strlen(@OpExecutor PcodeExecutor<T> executor,
- @OpLibrary PcodeUseropLibrary<T> library) {
- if (progStrlen == null) {
- progStrlen = SleighProgramCompiler.compileUserop(executor.getLanguage(),
- "__libc_strlen", List.of("__result", "str", "maxlen"),
- SRC_STRLEN, PcodeUseropLibrary.nil(), List.of(vnRAX, vnRDI, vnRSI));
- }
- progStrlen.execute(executor, library);
+ public SleighPcodeUseropDefinition __libc_strnlen_generic(BuilderStage1 builder) {
+ return builder.params("str", "maxlen").body(_ -> """
+ local result = 0;
+ <loop>
+ if (*:1 (str+result) == 0 || result >= maxlen) goto <exit>;
+ result = result + 1;
+ goto <loop>;
+ <exit>
+ __op_output = result;
+ """).build();
}
}
```
-At construction, we capture the varnodes we need to use.
-We could just use them directly in the source, but this demonstrates the ability to alias them, which makes the Sleigh source more re-usable across target architectures.
-We then lazily compile each userop upon its first invocation.
-These are technically still Java callbacks, but our implementation delegates to the executor, giving it the compiled p-code program.
+Each userop implementation is still annotated with `@PcodeUserop`; however, the return type `SleighPcodeUseropDefinition` tells the framework the userop is not a run-time callback, but a factory method for Sleigh source code.
+The builder provides a fluent style for specifying the different forms, parameters, and bodies of the userop.
+The examples above are fairly simple.
+
+The `params(...)` call indicates the number and names of parameters.
+The `body(...)` call generates the Sleigh source for the userop, typically expressed using a lambda.
+The lambda takes `List<Varnode>` and returns a `String` of Sleigh source.
+Upon encountering a callother to this userop, the emulator invokes the lambda, giving the actual varnode arguments, and executes the generated Sleigh.
+The arguments are often ignored, because the Sleigh source can refer to them by the names given in `params(...)`.
+Finally, we call `build()` to create the userop definition and return it.
+
+Overloading is possible, but we discuss that later.
+The `__libc_strnlen` userop delegates to `__libc_strnlen_generic`, which in turn implements `strnlen` naively.
+It loops from 0 to maxlen until it finds a zero.
+Note that the generic userop does not refer to any x86-specific registers.
+
+Userops can refer to any other userop defined either by the language's Sleigh spec file, by the userop library, or by any other userop library composed with it.
+Arguments (inputs) and the output varnodes are passed by reference.
+Technically, userops can read and write to any of them freely, but conventionally, they should read only from inputs and write only to the output.
+The output varnode is named `__op_output`.
+The input varnode names are specified in the call to `params()`.
+The compiled result is as if those varnodes were substituted for their arguments.
+Note that expressions are given intermediate unique varnodes.
+When used as a userop input argument, the expression is evaluated once, then that temporary varnode is passed.
+Thus, writing to an input risks undefined behavior.
+Conventionally, userops should write to `__op_output` exactly once, at or near the end of the userop.
+
+With is mind, we re-examine the definition of `__libc_strnlen`:
+
+```sleigh
+RAX = __libc_strnlen_generic(RDI, RSI);
+```
+
+It implements `strnlen` for the System V ABI by naming the appropriate register for each parameter and return value.
+(A more sophisticated implementation of this library could take a `CompilerSpec` and/or calling convention argument in its constructor to generate the appropriate register names.)
+Essentially, the generic parameter names (and `__op_output`) become aliased to the register names.
+The generated p-code will be exactly the same as if it had been defined:
+
+```sleigh
+local result = 0;
+<loop>
+if (*:1 (RDI+result) == 0 || result >= RSI) goto <exit>;
+result = result + 1;
+goto <loop>;
+<exit>
+RAX = result;
+```
+
+#### Overloading
+
+Two kinds of overloading are possible:
+
+1. The userop has multiple forms, each having a different number of parameters
+2. A single form's implementation depends on the size of at least one varnode argument
+
+The first kind is handled using the `overload()` method on the builder and then repeating the `params().body()` sequence for each form.
+For example
+
+```java
+return builder.params("a").body(args -> """
+ ...
+ """).overload().params("a", "b").body(args -> """
+ ...
+ """).build();
+```
+
+The second kind is handled by inspecting the actual argument list in the lambda expression.
+This can often be accomplished using a `switch` expression on the size of a varnode, e.g.:
-The advantage here is that the p-code will use the underlying arithmetic appropriately.
-However, for some models, that may actually not be desired.
-Some symbolic models might just like to see an abstract call to `strlen()`.
+```java
+return builder.params("n").body(a -> switch(a.get(0).getSize()) {
+ case 4 -> "__op_output = sin_float(n);";
+ case 8 -> "__op_output = sin_double(n);";
+}).build();
+```
+
+In this example, we select between a single-precision and double-precision `sin` operation, based on the size of the input varnode.
+This pattern of delegating to size-specific userops is common, and those userops can be Java callbacks.
+Both kinds of overloading may be applied to the same userop definition.
### Modeling by Structured Sleigh
-The disadvantage to pre-compiled p-code is all the boilerplate and manual handling of Sleigh compilation.
-Additionally, when stubbing C functions, you have to be mindful of the types, and things may get complicated enough that you pine for more C-like control structures.
+When stubbing C functions, you have to be mindful of the types, and things may get complicated enough that you pine for more C-like control structures.
The same library can be implemented using an incubating feature we call *Structured Sleigh*:
```java {.numberLines}
@@ -187,24 +233,25 @@ public static class StructuredStdLibPcodeUseropLibrary<T>
super(cs);
}
- @StructuredUserop
- public void __x86_64_RET() {
- Var RSP = lang("RSP", type("void **"));
- Var RIP = lang("RIP", type("void *"));
- RIP.set(RSP.deref());
+ @StructuredUserop(type = "undefined *")
+ public void __x86_64_POP() {
+ Var RSP = lang("RSP", type("undefined **"));
+ Var result = temp(type("undefined *"));
+ result.set(RSP.deref());
RSP.addiTo(8);
- _return(RIP);
+ _result(result);
}
@StructuredUserop
- public void __libc_strlen() {
+ public void __libc_strnlen() {
Var result = lang("RAX", type("long"));
Var str = lang("RDI", type("char *"));
Var maxlen = lang("RSI", type("long"));
- _for(result.set(0), result.ltiu(maxlen).andb(str.index(result).deref().eq(0)),
- result.inc(), () -> {
- });
+ RVal inBounds = result.ltiu(maxlen);
+ RVal notTerm = str.index(result).deref().neq(0);
+ _for(result.set(0), inBounds.andb(notTerm), result.inc(), () -> {
+ });
}
}
}
@@ -218,10 +265,10 @@ In a sense, Structured Sleigh is a DSL hosted in Java....
Unfortunately, we cannot overload operators in Java, so we are stuck using method invocations.
Another disadvantage is the dependence on a compiler spec for type resolution.
-Structured Sleigh is not the best suited for all circumstances, e.g., the implementation of `__x86_64_RET` is odd to express.
+Structured Sleigh is not the best suited for all circumstances, e.g., the implementation of `__x86_64_POP` is odd to express.
Arguably, there is no real need to ascribe high-level types to `RSP` and `RIP` when expressing low-level operations.
Luckily, these implementation techniques can be mixed.
-A single library can implement the `RET` using pre-compiled Sleigh, but `strlen` using Structured Sleigh.
+A single library could implement the `POP` using (raw) Sleigh, but `strnlen` using Structured Sleigh.
### Modeling System Calls
@@ -254,7 +301,8 @@ public class CustomLibraryScript extends GhidraScript {
};
emu.inject(currentAddress, """
__libc_strlen();
- __X86_64_RET();
+ RIP = __X86_64_POP();
+ return [RIP];
""");
// TODO: Initialize the emulator's memory from the current program
@@ -271,12 +319,12 @@ public class CustomLibraryScript extends GhidraScript {
}
```
-The key is to override `createUseropLibrary()` in an anonymous extension of the `PcodeEmulator`.
+The key is to override `createUseropLibrary()` in an extension of the `PcodeEmulator`.
It is polite to compose your library with the one already provided by the super class, lest you remove userops and cause unexpected crashes later.
For the sake of demonstration, we have included an injection that uses the custom library, and we have included a monitored loop to execute a single thread indefinitely.
The initialization of the machine and its one thread is left to the script writer.
The emulation *is not* implicitly associated with the program!
-You must copy the program image into its state, and you should choose a different location for the injection.
+You must copy the program image into its state, and you should choose an appropriate location for the injection.
Refer to the example scripts in Ghidra's `SystemEmulation` module.
If you would like to (temporarily) override the GUI with a custom userop library, you can by setting the GUI's emulator factory:
@@ -291,7 +339,7 @@ public class InstallCustomLibraryScript extends GhidraScript implements FlatDebu
@Override
protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
return super.createUseropLibrary()
- .compose(new ModelingScript.SleighStdLibPcodeUseropLibrary<>(getLanguage()));
+ .compose(new ModelingScript.SleighStdLibPcodeUseropLibrary<>());
}
}
@@ -753,7 +801,7 @@ Finally, for the states, we just take the provided concrete state and construct
## Use in Dynamic Analysis
-What we have constructed so far is suitable for constructing and using our augmented emulator in a script.
+What we have built so far is suitable for constructing and using our augmented emulator in a script.
Using it is about as straightforward as the plain concrete emulator.
The exception may be when accessing its state, you will need to be cognizant of the pairing.
diff --git a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/CustomLibraryScript.java b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/CustomLibraryScript.java
index fe8ab24338..cfb0c39dd3 100644
--- a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/CustomLibraryScript.java
+++ b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/CustomLibraryScript.java
@@ -31,7 +31,8 @@ public class CustomLibraryScript extends GhidraScript {
};
emu.inject(currentAddress, """
__libc_strlen();
- __X86_64_RET();
+ RIP = __X86_64_POP();
+ return [RIP];
""");
// TODO: Initialize the emulator's memory from the current program
diff --git a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/InstallCustomLibraryScript.java b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/InstallCustomLibraryScript.java
index 887f8ade77..1682f93683 100644
--- a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/InstallCustomLibraryScript.java
+++ b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/InstallCustomLibraryScript.java
@@ -31,7 +31,7 @@ public class InstallCustomLibraryScript extends GhidraScript implements FlatDebu
@Override
protected PcodeUseropLibrary<byte[]> createUseropLibrary() {
return super.createUseropLibrary()
- .compose(new ModelingScript.SleighStdLibPcodeUseropLibrary<>(getLanguage()));
+ .compose(new ModelingScript.SleighStdLibPcodeUseropLibrary<>());
}
}
diff --git a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.java b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.java
index 6b2ddfa289..6397c49316 100644
--- a/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.java
+++ b/GhidraDocs/GhidraClass/Debugger/ghidra_scripts/ModelingScript.java
@@ -20,18 +20,17 @@ import java.util.Map.Entry;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
-import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.app.script.GhidraScript;
import ghidra.debug.api.emulation.EmulatorFactory;
import ghidra.debug.api.emulation.PcodeDebuggerAccess;
import ghidra.lifecycle.Unfinished;
import ghidra.pcode.emu.*;
-import ghidra.pcode.emu.DefaultPcodeThread.PcodeThreadExecutor;
import ghidra.pcode.emu.auxiliary.AuxEmulatorPartsFactory;
import ghidra.pcode.emu.auxiliary.AuxPcodeEmulator;
import ghidra.pcode.exec.*;
import ghidra.pcode.exec.PcodeArithmetic.Purpose;
import ghidra.pcode.exec.PcodeExecutorStatePiece.Reason;
+import ghidra.pcode.exec.SleighPcodeUseropDefinition.BuilderStage1;
import ghidra.pcode.exec.trace.TraceEmulationIntegration.AbstractSimplePropertyBasedPieceHandler;
import ghidra.pcode.exec.trace.TraceEmulationIntegration.Writer;
import ghidra.pcode.struct.StructuredSleigh;
@@ -53,7 +52,7 @@ public class ModelingScript extends GhidraScript {
private final Register regRDI;
private final Register regRSI;
- public JavaStdLibPcodeUseropLibrary(SleighLanguage language) {
+ public JavaStdLibPcodeUseropLibrary(Language language) {
space = language.getDefaultSpace();
regRSP = language.getRegister("RSP");
regRAX = language.getRegister("RAX");
@@ -62,21 +61,18 @@ public class ModelingScript extends GhidraScript {
}
@PcodeUserop
- public void __x86_64_RET(
- @OpExecutor PcodeExecutor<T> executor,
- @OpState PcodeExecutorState<T> state) {
+ public void __x86_64_POP(@OpExecutor PcodeExecutor<T> executor,
+ @OpState PcodeExecutorState<T> state, @OpOutput Varnode out) {
PcodeArithmetic<T> arithmetic = state.getArithmetic();
T tRSP = state.getVar(regRSP, Reason.EXECUTE_READ);
- long lRSP = arithmetic.toLong(tRSP, Purpose.OTHER);
+ long lRSP = arithmetic.toLong(tRSP, Purpose.LOAD);
T tReturn = state.getVar(space, lRSP, 8, true, Reason.EXECUTE_READ);
- long lReturn = arithmetic.toLong(tReturn, Purpose.BRANCH);
state.setVar(regRSP, arithmetic.fromConst(lRSP + 8, 8));
- ((PcodeThreadExecutor<T>) executor).getThread()
- .overrideCounter(space.getAddress(lReturn));
+ state.setVar(out, tReturn);
}
@PcodeUserop
- public void __libc_strlen(@OpState PcodeExecutorState<T> state) {
+ public void __libc_strnlen(@OpState PcodeExecutorState<T> state) {
PcodeArithmetic<T> arithmetic = state.getArithmetic();
T tStr = state.getVar(regRDI, Reason.EXECUTE_READ);
long lStr = arithmetic.toLong(tStr, Purpose.OTHER);
@@ -96,57 +92,32 @@ public class ModelingScript extends GhidraScript {
// ----------------------
public static class SleighStdLibPcodeUseropLibrary<T> extends AnnotatedPcodeUseropLibrary<T> {
- private static final String SRC_RET = """
- RIP = *:8 RSP;
- RSP = RSP + 8;
- return [RIP];
- """;
- private static final String SRC_STRLEN = """
- __result = 0;
- <loop>
- if (*:1 (str+__result) == 0 || __result >= maxlen) goto <exit>;
- __result = __result + 1;
- goto <loop>;
- <exit>
- """;
- private final Register regRAX;
- private final Register regRDI;
- private final Register regRSI;
- private final Varnode vnRAX;
- private final Varnode vnRDI;
- private final Varnode vnRSI;
-
- private PcodeProgram progRet;
- private PcodeProgram progStrlen;
-
- public SleighStdLibPcodeUseropLibrary(SleighLanguage language) {
- regRAX = language.getRegister("RAX");
- regRDI = language.getRegister("RDI");
- regRSI = language.getRegister("RSI");
- vnRAX = new Varnode(regRAX.getAddress(), regRAX.getMinimumByteSize());
- vnRDI = new Varnode(regRDI.getAddress(), regRDI.getMinimumByteSize());
- vnRSI = new Varnode(regRSI.getAddress(), regRSI.getMinimumByteSize());
+ @PcodeUserop
+ public SleighPcodeUseropDefinition __x86_64_POP(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
+ __op_output = *:8 RSP;
+ RSP = RSP + 8;
+ """).build();
}
@PcodeUserop
- public void __x86_64_RET(@OpExecutor PcodeExecutor<T> executor,
- @OpLibrary PcodeUseropLibrary<T> library) {
- if (progRet == null) {
- progRet = SleighProgramCompiler.compileUserop(executor.getLanguage(),
- "__x86_64_RET", List.of(), SRC_RET, PcodeUseropLibrary.nil(), List.of());
- }
- progRet.execute(executor, library);
+ public SleighPcodeUseropDefinition __libc_strnlen(BuilderStage1 builder) {
+ return builder.params().body(_ -> """
+ RAX = __libc_strnlen_generic(RDI, RSI);
+ """).build();
}
@PcodeUserop
- public void __libc_strlen(@OpExecutor PcodeExecutor<T> executor,
- @OpLibrary PcodeUseropLibrary<T> library) {
- if (progStrlen == null) {
- progStrlen = SleighProgramCompiler.compileUserop(executor.getLanguage(),
- "__libc_strlen", List.of("__result", "str", "maxlen"),
- SRC_STRLEN, PcodeUseropLibrary.nil(), List.of(vnRAX, vnRDI, vnRSI));
- }
- progStrlen.execute(executor, library);
+ public SleighPcodeUseropDefinition __libc_strnlen_generic(BuilderStage1 builder) {
+ return builder.params("str", "maxlen").body(_ -> """
+ local result = 0;
+ <loop>
+ if (*:1 (str+result) == 0 || result >= maxlen) goto <exit>;
+ result = result + 1;
+ goto <loop>;
+ <exit>
+ __op_output = result;
+ """).build();
}
}
@@ -163,24 +134,25 @@ public class ModelingScript extends GhidraScript {
super(cs);
}
- @StructuredUserop
- public void __x86_64_RET() {
- Var RSP = lang("RSP", type("void **"));
- Var RIP = lang("RIP", type("void *"));
- RIP.set(RSP.deref());
+ @StructuredUserop(type = "undefined *")
+ public void __x86_64_POP() {
+ Var RSP = lang("RSP", type("undefined **"));
+ Var result = temp(type("undefined *"));
+ result.set(RSP.deref());
RSP.addiTo(8);
- _return(RIP);
+ _result(result);
}
@StructuredUserop
- public void __libc_strlen() {
+ public void __libc_strnlen() {
Var result = lang("RAX", type("long"));
Var str = lang("RDI", type("char *"));
Var maxlen = lang("RSI", type("long"));
- _for(result.set(0), result.ltiu(maxlen).andb(str.index(result).deref().eq(0)),
- result.inc(), () -> {
- });
+ RVal inBounds = result.ltiu(maxlen);
+ RVal notTerm = str.index(result).deref().neq(0);
+ _for(result.set(0), inBounds.andb(notTerm), result.inc(), () -> {
+ });
}
}
}
diff --git a/GhidraDocs/build.gradle b/GhidraDocs/build.gradle
index afdba52075..25625a8c6a 100644
--- a/GhidraDocs/build.gradle
+++ b/GhidraDocs/build.gradle
@@ -33,7 +33,19 @@ sourceSets {
}
configurations {
- ghidraClassImplementation.extendsFrom implementation
+ ghidraClassImplementation.extendsFrom implementation
+ ghidraClassArtifacts {
+ canBeConsumed = true
+ }
+}
+
+task ghidraClassJar(type:Jar) {
+ from sourceSets.ghidraClass.output
+ archiveFileName = 'GhidraDocs-Examples.jar'
+}
+
+artifacts {
+ ghidraClassArtifacts(ghidraClassJar)
}
dependencies {