# Emulation

Emulation is a bit of a loaded term, unfortunately.
Most of the confusion deals with the scope of the emulated target.
Do you just need to step through a few instructions, or a whole function?
Do you need to include external modules?
Do you need to simulate system calls?
Do you need to simulate connected devices?
Most of Ghidra's GUI-accessible emulation features focus on the smaller scope, though it does provide programming interfaces for advanced users to extend that scope.
Those more advanced features are covered in [Modeling](B4-Modeling.md).

This module assumes you have completed the Beginner portion of this course.

## P-code Emulation and Caveats

Ghidra's emulator uses the same p-code as is used by the decompiler.
P-code describes the semantics of each instruction by constructing a sequence of p-code operations.
The p-code specifications for most of Ghidra's languages were designed with decompilation, not necessarily emulation, in mind.
While in most cases, p-code for decompilation suffices for emulation, there are cases where design decisions were made, e.g., to keep decompiler output simple, that makes them less suitable for emulation.
This may manifest, e.g., in an excess of user-defined p-code ops, or *userops*.
The [Modeling](B4-Modeling.md) module discusses ways to implement or stub those userops in the emulator.
Some processor modules provide those stubs "out of the box."
If the emulator ever halts with an "unimplemented userop" message, then you have run into this problem.

## Use Cases

As already hinted at the start of this module, there are several use cases for emulation, and Ghidra tries to meet these cases by integrating emulation into the Debugger UI.
Some of the use cases accessible from the UI are:

* Extrapolation and interpolation of a live target.
* Emulation of a program image.
* P-code semantics debugging.

We will explore each case with a tutorial and exercise.

## Extrapolation and Interpolation

This is perhaps the easiest use case, assuming you already have started a live session.
*Extrapolation* is predicting execution of the target into the future, without allowing the actual target to execute.
Instead, we will allow an emulator to step forward, while reading its initial state from the live target.
This allows you, e.g., to experiment with various patches, or to force execution down a certain path.
If you devise a patch, you can then apply it to the live target and allow it to execute for real.
*Interpolation* is similar, but from a snapshot that is in the past.
It can help answer the question, "How did I get here?"
It is more limited, because missing state for snapshots in the past cannot be recovered.

In this tutorial, we will examine the command-line argument parser in `termmines`.

1. Launch `termmines` using GDB in the Ghidra Debugger.
1. If you have not already, do a bit of static analysis to identify the argument parsing function.
   It should be the first function called by `main`.
1. Use a breakpoint to interrupt the live target when it enters this function.
1. Change the **Control mode** drop-down to **Control Emulator**.
1. Click ![step into button](images/stepinto.png) **Step Into** to step the emulator forward.
1. Click ![skip over button](images/skipover.png) **Skip Over** and ![step back button](images/stepback.png) **Step Back** to experiment with different execution paths.

About those two new actions:

* ![skip over button](images/skipover.png) **Skip Over**:
  Step the current thread by skipping one instruction.
* ![step back button](images/stepback.png) **Step Back**:
  Step the current thread backward one instruction, or undo an emulated skip or patch.

**Quick Exercise**: Try to get the program counter onto the call to `exit(-1)` using only those three step buttons.

You should see things behave more or less the same as they would if it were the live target.
The main exception is the Terminal window.
It always displays the state of the live target, as it is unaware of the emulator.
You can make changes to the emulator's machine state, set breakpoints, etc., just as you would in **Control Target** mode.
**NOTE**: You may see Ghidra interact with the target, despite being in **Control Emulator** mode, because Ghidra lazily initializes the emulator's state.
If the emulated target reads a variable that Ghidra has not yet captured into the current snapshot, Ghidra will read that variable from the live target, capture it, and provide its value to the emulator.

### Stepping Schedules

If you had not noticed before, the trace tabs include the current snapshot number.
If you have stepped in the emulator, it will also contain the sequence of steps emulated.
Recall the *time* element of the Debugger's *coordinates*.
(See the [Navigation](A5-Navigation.md) module if you need a refresher.)
The time element, called the *schedule*, consists of both the current snapshot and the sequence of steps to emulate.
The tab displays that schedule.
If you have done any patching of the emulator's state, you may notice some more complicated "steps" in the schedule.
The syntax is:

* *Schedule* &rarr; *Snapshot* \[ `:` \[ *Step* ( `;` *Step* ) \* \] \[ `.` *Step* ( `;` *Step* ) \* \] \]
* *Step* &rarr; [ `t` *Id* `-` ] ( *Tick* | *Skip* | *Patch* )
* *Tick* &rarr; *Count*
* *Skip* &rarr; `s` *Count*
* *Patch* &rarr; `{` *SleighStmt* `}`

In essence, the schedule is the starting snapshot, followed by zero or more machine-instruction steps followed by zero or more p-code-operation steps.
Each step is optionally preceded by a thread id.
If omitted, the thread id is the same as the previous step.
If the first step has no thread id, it applies to the snapshot's event thread.
A plain number indicates the number of instructions or operations to execute.
An `s` prefix indicates skip instead of execute.
Curly braces specify a patch using a single Sleigh statement.
Here are some examples:

* `0` &mdash; The first snapshot in the trace.
* `3` &mdash; Snapshot number 3.
* `3:10` &mdash; Emulate 10 machine instructions on the event thread, starting at snapshot 3.
* `3:t1-10` &mdash; Same as above, but on the second thread rather than the event thread.
* `3:10;t1-10` &mdash; Start at snapshot 3. Step the event thread 10 instructions. Step the second thread 10 instructions.
* `3:10.4` &mdash; Start at snapshot 3. Step the event thread 10 instructions then 4 p-code ops.
* `3:{RAX=0x1234};10` &mdash; Start at snapshot 3. Override RAX with 0x1234, then step 10 instructions.

The explication of schedules allows Ghidra to cache emulated machine states and manage its emulators internally.
You can have Ghidra recall or generate the machine state for any schedule by pressing **`CTRL`-`G`** or using **Debugger &rarr; Go To Time** in the menus.

Assuming you got the program counter onto `exit(-1)` earlier:

1. Write down the current schedule.
1. Change back to **Control Target** mode.
   Ghidra will navigate back to the current snapshot, so PC wil