# Technical Documentation: unicorn-engine/unicorn

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/unicorn-engine/unicorn)

### Overview (`README.md`)

Unicorn Engine
==============

[](https://pepy.tech/project/unicorn)
[](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:unicorn)

**LOOKING FOR CONTRIBUTORS!** See [this](https://github.com/unicorn-engine/unicorn/issues/2237).
==============

<p align="center">
<img width="250" src="docs/unicorn-logo.png">
</p>

Unicorn is a lightweight, multi-platform, multi-architecture CPU emulator framework, based on [QEMU](http://qemu.org).

Unicorn offers some unparalleled features:

- Multi-architecture: ARM, ARM64 (ARMv8), M68K, MIPS, PowerPC, RISCV, SPARC, S390X, TriCore and X86 (16, 32, 64-bit)
- Clean/simple/lightweight/intuitive architecture-neutral API
- Implemented in pure C language, with bindings for Crystal, Clojure, Visual Basic, Perl, Rust, Ruby, Python, Java, .NET, Go, Delphi/Free Pascal, Haskell, Pharo, Lua and Zig.
- Native support for Windows & *nix (with Mac OSX, Linux, Android, *BSD & Solaris confirmed)
- High performance via Just-In-Time compilation
- Support for fine-grained instrumentation at various levels
- Thread-safety by design
- Distributed under free software license GPLv2

Further information is available at http://www.unicorn-engine.org


License
-------

This project is released under the [GPL license](COPYING).


Compilation & Docs
------------------

See [docs/COMPILE.md](docs/COMPILE.md) file for how to compile and install Unicorn.

More documentation is available in [docs/README.md](docs/README.md).

For common questions, read [docs/FAQ.md](docs/FAQ.md) before raising an issue.

Contact
-------

[Contact us](http://www.unicorn-engine.org/contact/) via mailing list, email or twitter for any questions.


Join [our group](https://t.me/+lnNl0fPpyCYzZmVh) for instant feedback.

Contribute
----------

If you want to contribute, please pick up something from our [Github issues](https://github.com/unicorn-engine/unicorn/issues).

We also maintain a list of more challenged problems in [milestones](https://github.com/unicorn-engine/unicorn/milestones) for our regular release.

Please send pull request to our [dev branch](https://github.com/unicorn-engine/unicorn/tree/dev).

[CREDITS.TXT](CREDITS.TXT) records important contributors of our project.

---

### Overview (`docs/README.md`)

Documention of Unicorn engine.

* How to compile & install Unicorn.

	http://unicorn-engine.org/docs/

* Tutorial on programming with C & Python languages.

	http://unicorn-engine.org/docs/tutorial.html

* Compare Unicorn & QEMU

	http://unicorn-engine.org/docs/beyond_qemu.html

* Uncorn-Engine Documentation

	https://github.com/kabeor/Unicorn-Engine-Documentation

---

### Overview (`bindings/dotnet/README.md`)

This documentation explains how to use the .NET binding for Unicorn
from source. 

0. Install the core engine as a dependency

   Follow README in the root directory to compile & install the core.

1. Compile the code

    You need to have at least version 5.0 of .NET installed.

    1. Windows

        To compile the code open the UnicornSln.sln with Microsoft Visual
        Studio 12 or with a newer version and just press Ctrl+Shift+B to build 
        the solution.

    2. Linux

        To compile the code open a terminal in this directory
        and enter the following command to build the solution:
        `dotnet build`
	
2. Usage

	The solution includes the testing project UnicornTests with examples 
	of usage. 
	
	In order to use the library in your project just add a reference to 
	the .NET library and be sure to copy the unmanaged unicorn.dll 
	library in the output directory.

	The naming convention used is the Upper Camel Case, this mean that to 
	invoke the uc_mem_read method you have to search for the MemRead method.

---

### Overview (`bindings/go/README.md`)

To download/update the Unicorn Go bindings, run:

    go get -u github.com/unicorn-engine/unicorn/bindings/go

A very basic usage example follows

_(Does not handle most errors for brevity. Please see sample.go for a more hygenic example):_

    package main

    import (
        "fmt"
        uc "github.com/unicorn-engine/unicorn/bindings/go/unicorn"
    )

    func main() {
        mu, _ := uc.NewUnicorn(uc.ARCH_X86, uc.MODE_32)
        // mov eax, 1234
        code := []byte{184, 210, 4, 0, 0}
        mu.MemMap(0x1000, 0x1000)
        mu.MemWrite(0x1000, code)
        if err := mu.Start(0x1000, 0x1000+uint64(len(code))); err != nil {
            panic(err)
        }
        eax, _ := mu.RegRead(uc.X86_REG_EAX)
        fmt.Printf("EAX is now: %d\n", eax)
    }

An example program exercising far more Unicorn functionality and error handling can be found in sample.go.

---

### Overview (`bindings/java/README.md`)

This documentation explains how to install the Java binding for Unicorn
from source.

0. Follow `docs/COMPILE.md` in the root directory to compile the core to the `build` directory.

   Note: by default, the Java binding native library will be built by statically linking to
   `../../build/libunicorn.a`, thereby removing `libunicorn` as a runtime dependency, but
   making the produced native library `libunicorn_java` bigger.

   If you instead want to dynamically link against the installed `libunicorn`, change
   `LIBS=../../build/libunicorn.a` to `LIBS=-lunicorn` in `Makefile`.

1. Install a JDK for your platform.

2. Install Maven: https://maven.apache.org/install.html.

3. Change directories into the java bindings and build the Maven package:

        $ mvn package

This will automatically build and test the Unicorn Java bindings.

The bindings consist of the native JNI library (`libunicorn_java.{so,dylib,dll}`)
and the Java JAR (`target/unicorn-2.xx.jar`). You will need to have the native
library on `java.library.path` and the JAR on your classpath.

The `src/main/test/java` directory contains some sample code to show how to use Unicorn API.
`samples` is a set of sample classes showcasing the various features of the Unicorn API,
while `tests` is a set of JUnit tests for the API.

- `Sample_<arch>.java`:
  These show how to access architecture-specific information for each
  architecture.

- `Shellcode.java`:
  This shows how to analyze a Linux shellcode.

- `SampleNetworkAuditing.java`:
  Unicorn sample for auditing network connection and file handling in shellcode.

---

### Overview (`bindings/pascal/README.md`)

# unicorn-engine-pascal

Pascal/Delphi language binding for the [Unicorn emulator](http://www.unicorn-engine.org/)
([GitHub](https://github.com/unicorn-engine/unicorn)).

*Unicorn* is a lightweight multi-platform, multi-architecture CPU emulator framework
based on [QEMU](http://www.qemu.org/).

## License

`GPLv2`

## Compilers Compatibility

#### Free Pascal >= v3 
  - `Mac OS` 
  - `Windows` 
  - `Linux`
#### Delphi
  - `Windows`
## Features

* Same API as the C core 
  - with some workarounds for Pascals case insensitivity: 


    `uc_mem_write()` -> `uc_mem_write_()`, `uc_mem_read()` -> `uc_mem_read_()`
  - and the missing feature passing variable number of arguments to functions (`...`): 
    
    i solve it by using -> `args : Array of Const;` 
    you can pass args inside [] like :
    ```pascal
    uc_hook_add(uc, trace, UC_HOOK_INSN, @HookIn, nil, 1,0,[UC_X86_INS_IN];
    ```
    the main loader in `Unicorn_dyn.pas` , check X86 example for more info .


* Multiplatform (Mac OS , Windows and Linux are tested)

## Examples
* `X86` Emulate 16, 32, 64 Bit x86


## Version History
* `1.1`
    * Add Delphi Compatibility [ Windows ]
* `1.0`
    * this is the first version it has all APIs of UNICORN v1.0.1

## TODO
  - Add more Examples
  - Add <b>Mac , Linux</b> Support for Delphi

---

### Overview (`bindings/python/README.md`)

# Unicorn

Unicorn is a lightweight, multi-platform, multi-architecture CPU emulator framework
based on [QEMU](http://qemu.org).

Unicorn offers some unparalleled features:

- Multi-architecture: ARM, ARM64 (ARMv8), M68K, MIPS, PowerPC, RISCV, SPARC, S390X, TriCore and X86 (16, 32, 64-bit)
- Clean/simple/lightweight/intuitive architecture-neutral API
- Implemented in pure C language, with bindings for Crystal, Clojure, Visual Basic, Perl, Rust, Ruby, Python, Java, .NET, Go, Delphi/Free Pascal, Haskell, Pharo, and Lua.
- Native support for Windows & *nix (with Mac OSX, Linux, *BSD & Solaris confirmed)
- High performance via Just-In-Time compilation
- Support for fine-grained instrumentation at various levels
- Thread-safety by design
- Distributed under free software license GPLv2

Further information is available at http://www.unicorn-engine.org

# Python Bindings for Unicorn

Originally written by Nguyen Anh Quynh, polished and redesigned by elicn, maintained by all community contributors.

## Install

Install a prebuilt wheel from PyPI:

```bash
python3 -m pip install unicorn
```

In case you would like to develop the bindings:

```bash
DEBUG=1 THREADS=4 python3 -m pip install --user -e .
# Workaround for Pylance
DEBUG=1 THREADS=4 python3 -m pip install --user -e . --config-settings editable_mode=strict
```

or install it by building it by yourself:

```bash
THREADS=4 python3 -m pip install --user .
```

Explanations for arguments:

- `THREADS=4` will use 4 threads for building.
- `DEBUG=1` will build debug version of unicorn.
- `--user` will install the bindings to your user directory instead of requiring root permission.
- `-e` infers the editable mode, which gives your instant feedback instead of re-compiling every time.

Note that you should setup a valid building environment according to docs/COMPILE.md but not necessarily build it because `setup.py` will do this for you. 

## Python2 compatibility

By default, Unicorn python bindings works with Python3.7 and above, as it offers more powerful features which improves developing efficiency compared to Python2. However, Unicorn will only keep compatible with all features Unicorn1 offers regarding Python2 because it has reached end-of-life for more than 3 years at the time of writing this README. While offering all features for both Python2 & Python3 is desirable and doable, it inevitably costs too much efforts to maintain and few users really rely on this. Therefore, we assume that if users still stick to Python2, previous Unicorn1 features should be enough. If you really want some new features Unicorn2 offers, please check and pull request to `unicorn/unicorn_py2`. We are happy to review and accept!
Even though the build of wheel packages requires Python3, it's still possible to re-tag the wheel produced from Python3 with `py2` tag and then run `python2 -m pip install <retagged-wheel-py>`. For detailed commands please refer to our workflow files.

---

### Overview (`bindings/ruby/README.md`)

# Installation

## Software requirements

### Linux
- ruby >= 1.9.3
- rubygems
- make
- gcc

### Mac OS
- ruby >= 1.9.3
- rubygems
- make
- XCode

## Install unicorn
 * cd path_to_unicorn
 * ./make.sh install

## Install ruby binding
 * cd bindings/ruby
 * make install

---

### Overview (`bindings/zig/README.md`)

# Unicorn-engine-Zig

[Zig](https://ziglang.org/) bindings for the [Unicorn](http://www.unicorn-engine.org/) emulator with utility functions.

*Unicorn* is a lightweight multi-platform, multi-architecture CPU emulator framework
based on [QEMU](http://www.qemu.org/).

## How to use

Using the [Zig Build System](https://ziglang.org/learn/build-system/), you can include
the following into your local `build.zig.zon`

``` zig
.{
    .dependencies = .{
        .unicorn = .{
            .url = "https://github.com/unicorn-engine/unicorn/archive/<ref SHA>.tar.gz",
            .hash = "<hash>",
        }
    },
}
```

Note that currently the only module exported publicly is `unicorn-sys`

---

### Overview (`bindings/rust/sys/README.md`)

# Unicorn-engine-sys

Low-level Rust bindings for the [Unicorn](http://www.unicorn-engine.org/) emulator. This crate only exposes the C API of Unicorn.

Checkout Unicorn2 source code at [dev branch](https://github.com/unicorn-engine/unicorn/tree/dev).

```
/* Detailed source-code truncated for AI context efficiency. */
```

Further sample code can be found in [tests](./src/tests).

## Usage

Add this to your `Cargo.toml`:

```
[dependencies]
unicorn-engine-sys = "2.1.4"
```

---

### Overview (`bindings/rust/unicorn-engine/README.md`)

# Unicorn-engine

Rust bindings for the [Unicorn](http://www.unicorn-engine.org/) emulator with utility functions.

Checkout Unicorn2 source code at [dev branch](https://github.com/unicorn-engine/unicorn/tree/dev).

```rust
use unicorn_engine::{Arch, Mode, Prot, SECOND_SCALE, Unicorn, RegisterARM};

fn main() {
    let arm_code32: Vec<u8> = vec![0x17, 0x00, 0x40, 0xe2]; // sub r0, #23

    let mut emu = Unicorn::new(Arch::ARM, Mode::LITTLE_ENDIAN).expect("failed to initialize Unicorn instance");
    emu.mem_map(0x1000, 0x4000, Prot::ALL).expect("failed to map code page");
    emu.mem_write(0x1000, &arm_code32).expect("failed to write instructions");

    emu.reg_write(RegisterARM::R0, 123).expect("failed write R0");
    emu.reg_write(RegisterARM::R5, 1337).expect("failed write R5");

    emu.emu_start(0x1000, (0x1000 + arm_code32.len()) as u64, 10 * SECOND_SCALE, 1000).expect("failed to start emulation");
    assert_eq!(emu.reg_read(RegisterARM::R0).unwrap(), 100);
    assert_eq!(emu.reg_read(RegisterARM::R5).unwrap(), 1337);
}
```

Further sample code can be found in [tests](./src/tests).

## Usage

Add this to your `Cargo.toml`:

```
[dependencies]
unicorn-engine = "2.1.1"
```

## Acknowledgements

These bindings were once based on Sébastien Duquette's (@ekse) [unicorn-rs](https://github.com/unicorn-rs/unicorn-rs).
We picked up the project, as it is no longer maintained.
Thanks to all contributors.

---

### COMPILE (`docs/COMPILE.md`)

This HOWTO introduces how to build Unicorn2 natively on Linux/Mac/Windows or cross-build to Windows from Linux host.

Note: By default, CMake will build both the shared and static libraries while only static libraries are built if unicorn is used as a Cmake subdirectory. In most cases, you don't need to care about which kind of library to build. ONLY use `BUILD_SHARED_LIBS=no`if you know what you are doing.

## Native build on Linux/macOS

This builds Unicorn2 on Linux/macOS. Note that this also applies to Apple Silicon M1 users.

- Install `cmake` and `pkg-config` with your favorite package manager:

Ubuntu:

``` bash
sudo apt install cmake pkg-config
```

macOS:

```bash
brew install cmake pkg-config
```

Note you need to install these build dependencies for python bindings on macOS too.

- Build with the following commands.

```bash
mkdir build; cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make
```

## Native build on Windows, with MSVC

This builds Unicorn2 on Windows, using Microsoft MSVC compiler.

- Require `cmake` & `Microsoft Visual Studio` (>=16.8).

- From Visual Studio Command Prompt, build with the following commands.

```bash
mkdir build; cd build
cmake .. -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release
nmake
```

Note, other generators like `Ninja` and `Visual Studio 16 2019` would also work.

```bash
mkdir build; cd build
cmake .. -G "Visual Studio 16 2019" -A "win32" -DCMAKE_BUILD_TYPE=Release
msbuild unicorn.sln -p:Plaform=Win32 -p:Configuration=Release
```

## Cross build with NDK

To cross-build and run Unicorn2 on the Android platform, firstly you need to download [NDK](https://developer.android.com/ndk/downloads).

For newer NDK, please make sure your cmake version is above 3.19.

Then generate the project like:

```bash
mkdir build; cd build;
cmake .. -DCMAKE_TOOLCHAIN_FILE=$NDK/build/cmake/android.toolchain.cmake -DANDROID_ABI=$ABI -DANDROID_NATIVE_API_LEVEL=$MINSDKVERSION
make
```

You may get the possible values from this [page](https://developer.android.com/ndk/guides/cmake).

Unicorn2 support cross-build for `armeabi-v7a`, `arm64-v8a`, `x86` and `x86_64`.

Note the build is only tested and guaranteed to work under Linux and macOS, however, other systems may still work.

## Cross build from Linux host to Windows, with Mingw

This cross-builds Unicorn2 from **Linux host** to Windows, using `Mingw` compiler.

- Install required package.

```bash
sudo apt install mingw-w64-x86-64-dev
```

- Build Unicorn and samples with the following commands.

```bash
mkdir build; cd build
cmake .. -DCMAKE_TOOLCHAIN_FILE=../mingw64-w64.cmake
make
```

## Native build on Windows host, with MSYS2/Mingw

This builds Unicorn2 on **Windows host**, using **MSYS2/Mingw** compiler.

This requires MSYS2 to be installed on the Windows machine. You need to download & install MSYS2 from https://www.msys2.org.

Then from MSYS2 console, install packages below:

```bash
pacman -S mingw-w64-x86_64-toolchain mingw-w64-x86_64-cmake mingw-w64-x86_64-ninja
```

- Build Unicorn and samples with the following commands.

```bash
export PATH=/mingw64/bin:$PATH
mkdir build; cd build
/mingw64/bin/cmake .. -G "Ninja"
ninja -C .
```

Note that the way to build on MSYS changes as time goes, please keep in mind that always use the cmake shipped with mingw64.

## Cross build from Linux host to other architectures

This cross-builds Unicorn2 from **Linux host** to other architectures, using a cross compiler.

- Install cross compiler package. For example, cross-compile to ARM requires the below command.

```bash
sudo apt install gcc-arm-linux-gnueabihf
```

- Build Unicorn and samples with the following commands. The compiler name differs according to your targets.

```bash
mkdir build; cd build
cmake .. -DCMAKE_C_COMPILER=gcc-arm-linux-gnueabihf
make
```

## Building from vcpkg

The Unicorn port in vcpkg is kept up to date by Microsoft team members and community contributors. The url of vcpkg is: https://github.com/Microsoft/vcpkg . You can download and install unicorn using the vcpkg dependency manager:

```bash
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh  # ./bootstrap-vcpkg.bat for Windows
./vcpkg integrate install
./vcpkg install unicorn
```

If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.

---

### FAQ (`docs/FAQ.md`)

## Why is my execution so slow?

Typically, it’s due to

- Instrumenting every instruction executed.
- Instrumenting every memory access.

Optimize your program with less instrumentation, e.g. by using `UC_HOOK_BLOCK` instead of `UC_HOOK_CODE`

## Why do I get a wrong PC after emulation stops?

<details>
  <summary>For version < 2.1.4 </summary>
  
Updating PC is a very large overhead (10x slower in the worst case, see FAQ above) for emulation so the PC sync guarantee is explained below in several cases:

- A `UC_HOOK_CODE` hook is installed. In this case, the PC is sync-ed _everywhere_ within the effective range of the hook. However, on some architectures, the PC might by sync-ed all the time if the hook is installed in any range. Note using `count` in `uc_emu_start` implies installing a `UC_HOOK_CODE` hook.
- A `UC_HOOK_MEM_READ` or `UC_HOOK_MEM_WRITE` hook is installed. In this case, the PC is sync-ed exactly before any read/write events within the effective range of the hook.
- Emulation (`uc_emu_start`) terminates without any exception. In this case, the PC will point to the next instruction.
- No hook mentioned above is installed and emulation terminates with exceptions. In this case, the PC is sync-ed at the basic block boundary, in other words, the first instruction of the basic block where the exception happens.

Below is an example:

```
mov x0, #1 <--- the PC will be here
mov x1, #2
ldr x0, [x1] <--- exception here
```

If `ldr x0, [x1]` fails with memory exceptions, the PC will be left at the beginning of the basic block, in this case `mov x0, #1`.

However, if a `UC_HOOK_MEM_READ` hook is installed, the PC will be sync-ed:

```
mov x0, #1 
mov x1, #2
ldr x0, [x1] <--- exception here and PC sync-ed here
```
  
</details>

<details>
  <summary>For version >= 2.1.4 </summary>

We should always have valid PC all the time. Please report an issue for your case.

</details>

## I get an “Unhandled CPU Exception”, why?

Unicorn is a pure CPU emulator and usually it’s due to no handler registered for instructions like `syscall` and `SVC`. If you expect syscall and userland emulation, you probably would like [qiling framework](https://github.com/qilingframework/qiling).

## I would like to instrument a specific instruction but get a `UC_ERR_HOOK`, why?

Currently, only a small subset of the instructions can be instrumented.

On x86, all available instructions are: `in` `out` `syscall` `sysenter` `cpuid`.

## Emulating some instructions gives an error like "Invalid Instruction", what should I do?

1. Some instructions are not enabled by default on some architectures. For example, you have to setup CSR on RISC-V or VFP on ARM before emulating floating-point instructions. Refer to the corresponding manual to check if you leave out possible switches in special registers.
2. Different CPU models support different sets of instructions. This is especially observed on ARM CPUs. For example, for `THUMB2` big-endian instructions, consider setting CPU model to `cortex-r5` or `arm_max`. See [#1725](https://github.com/unicorn-engine/unicorn/issues/1725) and [#1724](https://github.com/unicorn-engine/unicorn/issues/1724).
3. If you are on ARM, please check whether you are emulating a THUMB instruction. If so, please use `UC_MODE_THUMB` and make sure the starting address is odd. 
4. If it's not the cases above, it might be some newer instruction sets that qemu5 doesn’t support.
5. Note some instruction sets are not implemented by the latest QEMU.

If you are still using Unicorn1, please upgrade to Unicorn2 for better support.

## Memory hooks get called multiple times for a single instruction

There are several possibilities, e.g.:

- The instruction might access memory multiple times like `rep stos` in x86.
- The address to access is bad-aligned and thus the MMU emulation will split the access into several aligned memory access. In worst cases on some arch, it leads to byte by byte access.

## I can't recover from unmapped read/write even I return `true` in the hook, why?

This is a minor change in memory hooks behavior between Unicorn1 and Unicorn2. To gracefully recover from memory read/write error, you have to map the invalid memory before you return true.

It is due to the fact that, if users return `true` without memory mapping set up correctly, we don't know what to do next. In Unicorn1, the behavior is __undefined__ in this case but in Unicorn2 we would like to force users to set up memory mapping in the hook to continue execution.

See the [sample](https://github.com/unicorn-engine/unicorn/blob/c05fbb7e63aed0b60fc2888e08beceb17bce8ac4/samples/sample_x86.c#L1379-L1393) for details.

## My emulation gets weird read/write error and CPU exceptions.

For MIPS, you might have an address that falls in MIPS `kseg` segments. In that case, MMU is bypassed and you have to make sure the corresponding physical memory is mapped. See [#217](https://github.com/unicorn-engine/unicorn/issues/217), [#1371](https://github.com/unicorn-engine/unicorn/issues/1371), [#1550](https://github.com/unicorn-engine/unicorn/issues/1371).

For ARM, you might have an address that falls in some non-executable segments. For example, for m-class ARM cpu, some memory area is not executable according to [the ARM document](https://developer.arm.com/documentation/ddi0403/d/System-Level-Architecture/System-Address-Map/The-system-address-map?lang=en). 

## KeyboardInterrupt is not raised during `uc.emu_start`

This is intended as python [signal module](https://docs.python.org/3.10/library/signal.html) states:

> A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes.

A workaround is to start emulation in another thread.

## Editing an instruction doesn't take effect/Hooks added during emulation are not called.

Unicorn is a fork of QEMU and inherits most QEMU internal mechanisms, one of which is called TB chaining. In short, every block (in most cases, a `basic block`) is translated, executed and __cached__. Therefore, any operation on cached addresses won't immediately take effect without a call to `uc_ctl_remove_cache`. Check a more detailed discussion here: [#1561](https://github.com/unicorn-engine/unicorn/issues/1561)

Note, this doesn't mean you have to care about Self Modifying Code because the read/write happens within emulation (TB execution) and QEMU would handle such special cases. For technical details, refer to the [QEMU paper](https://www.usenix.org/legacy/event/usenix05/tech/freenix/full_papers/bellard/bellard.pdf).

TLDR: To ensure any modification to an address will take effect:

1. Call `uc_ctl_remove_cache` on the target address.
2. Call `uc_reg_write` to write current PC to the PC register, if the modification happens during emulation. It restarts emulation (but doesn't quit `uc_emu_start`) on current address to re-translate the block.

## How to emulate interrupts (or ticks) with Unicorn?

As stated, Unicorn is a pure CPU emulator. For such emulation, you have two choices:

- Use the `timeout` parameter of `uc_emu_start`
- Use the `count` parameter of `uc_emu_start`

After emulation stops, you may check anything you feel interested and resume emulation accordingly.

Note that for cortex-m `exec_return`, Unicorn has a magic software exception with interrupt number 8. You may register a hook to handle that.

## Why not keep up the upstream qemu?

To provide end users with simple API, Unicorn does lots of dirty hacks within qemu code which prevents it from sync painlessly.

## Is there anyway to disable softmmu to speed up execution?

Yes, it’s possible but that is not Unicorn’s goal and there is no simple switch in qemu to disable softmmu.

Starting from 2.0.2, Unicorn will emulate the MMU depending on the emulated architecture without further hacks. That said, Unicorn offers the full ability of the target MMU implementation. While this enables more possibilities of Uncorn, it has a few drawbacks:

- As previous question points out already, some memory regions are not writable/executable.
- You have to always check architecture-specific registers to confirm MMU status.
- `uc_mem_map` will always deal with physical addresses while `uc_emu_start` accepts virtual addresses.

Therefore, if you still prefer the previous `paddr = vaddr` simple mapping, we have a simple experimental MMU implementation that can be switched on by: `uc_ctl_tlb_mode(uc, UC_TLB_VIRTUAL)`. With this mode, you could also add a `UC_HOOK_TLB_FILL` hook to manage the TLB. When a virtual address is not cached, the hook will be called. Besides, users are allowed to flush the tlb with `uc_ctl_flush_tlb`.

In theory, `UC_TLB_VIRTUAL` will achieve better performance as it skips all MMU details, though not benchmarked.

## Something is wrong - I would like to dig deeper

Unicorn uses at several places logging by the qemu implementation.
This might provide a first glance what could be wrong.

The logs contains optionally the filename and the line number including
additional messages to indicate what is happening.
However, the qemu logs are partially commented-out and incomplete, but give it a try.
You might want to dig deeper - and add your own log messages where you expect or try to find the bug.

To enable logs, you must recompile Unicorn with `-DUNICORN_LOGGING=yes` to cmake.

Logs are written in different log levels, which might result into a very verbose logging if enabled.
To control the log level information, two environment variables could be used.

`UNICORN_LOG_LEVEL` and `UNICORN_LOG_DETAIL_LEVEL`.

These environment variables are parsed into `uint32_t` values once, (due to performance reasons)
so set these environment variables before you execute any line of Unicorn.
Allowed are hexa-decimal, decimal and octal values, which fits into a buffer of 10 chars. (see stroul for details).

To define how detailed and what should be logged, use the following environment variables:

- `UNICORN_LOG_LEVEL`=\<32bit mask\>
  - The qemu bit mask what should be logged.
  - Use the value of `UINT32_MAX` to log everything.
  - If no bit is set in the mask, there will be no logging.
- `UNICORN_LOG_DETAIL_LEVEL`=\<level\>
  - The level defines how the filename and line is constructed.
    - 0: no filename and no line is used.
    - 1: full filename including the leading path is used with line information.
    - 2: just the filename with line information. It might be a little confusing,
    as the file name can be used in several places.
  - If unsure or unwanted, leave this variable undefined or set it to 0.

As an example to set up the environment for python correctly, see the example below.

```python
import os
os.environ['UNICORN_LOG_LEVEL'] = "0xFFFFFFFF" # verbose - print anything 
os.environ['UNICORN_LOG_DETAIL_LEVEL'] = "1" # full filename with line info
```

Please note that file names are statically compiled in and can reveal the paths
of the file system used during compilation.

## Does Unicorn support ARM PAC (Pointer Authentication)?

Yes! However, Unicorn by default disables it and enabling it involves a few coding and document reading.

TLDR:

Taken from [#1789](https://github.com/unicorn-engine/unicorn/issues/1789).

```C
    uc_arm64_cp_reg reg;

    // SCR_EL3
    reg.op0 = 0b11;
    reg.op1 = 0b110;
    reg.crn = 0b0001;
    reg.crm = 0b0001;
    reg.op2 = 0b000;

    err = uc_reg_read(uc, UC_ARM64_REG_CP_REG, &reg);
    assert(err == UC_ERR_OK);

    // NS && RW && API
    reg.val |= (1 | (1<<10) | (1<<17));

    err = uc_reg_write(uc, UC_ARM64_REG_CP_REG, &reg);
    assert(err == UC_ERR_OK);

    // SCTLR_EL1
    reg.op0 = 0b11;
    reg.op1 = 0b000;
    reg.crn = 0b0001;
    reg.crm = 0b0000;
    reg.op2 = 0b000;

    err = uc_reg_read(uc, UC_ARM64_REG_CP_REG, &reg);
    assert(err == UC_ERR_OK);

    // EnIA && EnIB
    reg.val |= (1<<31) | (1<<30);

    err = uc_reg_write(uc, UC_ARM64_REG_CP_REG, &reg);
    assert(err == UC_ERR_OK);
    
    // HCR_EL2
    reg.op0 = 0b11;
    reg.op1 = 0b100;
    reg.crn = 0b0001;
    reg.crm = 0b0001;
    reg.op2 = 0b000;

    // HCR.API
    reg.val |= (1ULL<<41);

    err = uc_reg_write(uc, UC_ARM64_REG_CP_REG, &reg);
    assert(err == UC_ERR_OK);
```

For further explanation, refer to related ARM documents. Here is an incomplete list:

- [System register control of pointer authentication](https://developer.arm.com/documentation/ddi0487/latest/)
- [EnIA & EnIB](https://developer.arm.com/documentation/ddi0595/2021-12/AArch64-Registers/SCTLR-EL1--System-Control-Register--EL1-?lang=en#fieldset_0-31_31-1)
- [HCR.API](https://developer.arm.com/documentation/ddi0601/2020-12/AArch64-Registers/HCR-EL2--Hypervisor-Configuration-Register?lang=en#fieldset_0-41_41-1)
Note you could find the definitions of these registers at the end of corresponding documents.

## I debug my application but soon get an access violation inside unicorn.

This is intended for Windows. See discussion in [#1841](https://github.com/unicorn-engine/unicorn/issues/1841).

## My code does not do what I would expect - is this a bug?

Please create a github issue and provide as many details as possible.

- [ ] Simplified version of your script / source
  - Make sure that "no" external dependencies are needed.
  - E.g. remove additional use of capstone or CTF tools.
- [ ] Used Unicorn git-hash commit
  - Make sure to exclude any changes of you made in unicorn.
  - Alternativily provide the repo link to your commit.
- [ ] Detailed explaination what is expected
  - Try to verify if the instructions can be processed by qemu.
  - Dumping the registers of unicorn and qemu helps a lot.
- [ ] Detailed explaination what is observed
  - Describe what's going on (and what you might think about it).
- [ ] Output from your executed script
  - You might have additional log messages which could be helpful.
- [ ] Output from the qemu-logs
  - Try to gather more informations by enabling the qemu logging.
- [ ] More details
  - Attach more details to help reproduce the bug.
  - Like attaching a repo link to the CTF challenge containing the binary or source code.

## I'd like to make contributions, where do I start?

See [milestones](https://github.com/unicorn-engine/unicorn/milestones) and [coding convention](https://github.com/unicorn-engine/unicorn/wiki/Coding-Convention
).

Be sure to send pull requests for our **dev** branch only.

## Which qemu version is Unicorn based on?

Prior to 2.0.0, Unicorn is based on qemu 2.2.1. After that, Unicorn is based on qemu 5.0.1.

---

### Hooks (`docs/Hooks.md`)

## Introduction

In general, all the hooks can be bound to a region of the emulated memory, so that they will only fire when that region is reached (or accessed). The hooks are also stored in a list, so the more hooks that you add, the more processing that is needed by the system to dispatch them. This can make your emulation slow down if you have a lot of hooks present.

Some hooks can return a value, which if non-0 will abort execution.


## UC_HOOK_BLOCK

*What is it?*

Let's first deal with the `UC_HOOK_BLOCK` case. These hooks are called whenever the code execution starts within a 'basic block' in the emulated code. A 'basic block' is a sequence of instructions without any conditional branch or special processing instructions (or other events like the end of mapped memory) - a sequence that can be entirely emulated in (effectively) a linear path. The UC_HOOK_BLOCK is called with the address of the start of the block that's being executed and the size of that block (in bytes).

Because the block hooks are only called on entry to a section of code which must be executed, you can guarantee the execution passes through all the instructions in the block. If some instructions are conditional, the effect of the instruction might be null - e.g. `ADDEQ r0, r0, r1` in ARM is a conditional add that only happens if the Z flag is set. The basic block might contain any number of these conditional instructions as the execution still passes through the instructions.

*Why might you use it?*

If you want a gross understanding of the code path, knowing where the system executed, you might use a block hook. Your hook might write diagnostics about where the code was at that time and the state of registers. This would give you a very clear picture of how the execution was passing through the system. Loops, for example, might result in the same block hook being fired repeatedly, as the code passes through the same code, ending in the conditional jump back to the start of the loop.

If you were disassembling the code, you could perform the disassembly on each block for its entire range, rather than using a code hook.


## UC_HOOK_CODE

*What is it?*

The `UC_HOOK_CODE` is more fine-grained than the `UC_HOOK_BLOCK`. This occurs on every instruction that is executed, before it is executed. So whilst `UC_HOOK_BLOCK` is "I'm about to run this section of code", `UC_HOOK_CODE` is "I'm about to run this instruction". There being a lot of code hooks means that your hook will be called a lot. The hook is called (like the block hook) with the address of the code being executed, and its size. The size will only ever cover one instruction, however.

*Why might you use it?*

If you want to breakpoint the code at a particular place, this hook is a perfect way to do that. Calling `uc_emu_stop` will cause the emulation to stop at this point.

You might also use it to trace the execution with a disassembly, in a similar way to the block hooks, above. Because you're executing at the instruction level, this means that you can read the registers as they are before the code is executed, which may be useful for your disassembly.

If you want to inject behaviour you might use this hook to modify the registers - including modifying the program counter, to jump to a different place.


## UC_HOOK_MEM_READ, UC_HOOK_MEM_WRITE, UC_HOOK_READ_MEM_AFTER

*What is it?*

The `UC_HOOK_MEM_READ` and `UC_HOOK_MEM_WRITE` hooks are called whilst the emulator is executing instructions. When the code being emulated tries to read or write memory within the range, the hooks will be called.

For `UC_HOOK_MEM_READ`, the hook is called with the address that is being read, and the size of the access. A 'value' is passed, but this operation occurs before the value has been read, so its content is indeterminate.

For `UC_HOOK_MEM_WRITE`, the hook is called with the address that is being written, the size of the access and the value that was written to it.

For `UC_HOOK_MEM_READ_AFTER`, the hook is called *after* the read has occurred. It is the same as `UC_HOOK_MEM_READ` except that the value has been populated.

These hooks are not used if you directly access the memory using the Unicorn `mem_*` functions.

*Why might you use it?*

If you were providing watchpoints that track accesses to memory, you might use any of these 3 hooks. You could report all the registers and the program counter at the time of access - even reporting a stack backtrace if you knew the calling standard.

You might use these `UC_HOOK_MEM_READ` and `UC_HOOK_MEM_WRITE` operations to fake memory mapped IO. If you had a memory mapped device that you wanted to expose to the system, you could use a `UC_HOOK_MEM_READ` hook to write a suitable value into memory for the memory mapped register being accessed. The execution of the instruction would then pick up the new value that you had written.

Similarly, the `UC_HOOK_MEM_WRITE` could update your internal state with the register that had been written to the address.

You might implement memory protection in a different manner than the standard Unicorn form. For example, you might check that processor mode and decide whether the memory is actually accessible or not to the code that is performing that access. This isn't usually an operation of the CPU (although some CPUs and MMUs do have this ability), but for diagnosing whether a given section of code should be *able* to access other memory this could be useful.


## UC_HOOK_MEM_FETCH

*What is it?*

The `UC_HOOK_MEM_FETCH` hook is not used.

*Why might you use it?*

You wouldn't. It's deprecated and will never be called.


## UC_HOOK_MEM_READ_UNMAPPED, UC_HOOK_MEM_WRITE_UNMAPPED, UC_HOOK_MEM_FETCH_UNMAPPED

*What is it?*

All 3 of these hooks are called when there is an access to a region for which there is no memory mapping.

The `UC_HOOK_MEM_READ_UNMAPPED` hooks is called when the code tries to read an unmapped memory region.

The `UC_HOOK_MEM_WRITE_UNMAPPED` hooks is called when the code tries to write to an unmapped memory region.

The `UC_HOOK_MEM_FETCH_UNMAPPED` hooks is called when the emulator needs to read an unmapped memory region to fetch code to execute.

In all cases, you can either map the page in with the `uc_mem_map*` function or return non-0 to abort execution.

*Why might you use it?*

You might use these for dynamic memory mapping, only mapping in the memory when it is needed - which could be useful for a virtual-memory type system.

You might use it for trapping bad accesses at the time that they happen (although the usual abort that you would get will also give you this information).



## UC_HOOK_MEM_READ_PROT, UC_HOOK_MEM_WRITE_PROT, UC_HOOK_MEM_FETCH_PROT

*What is it?*

All 3 of these hooks are called when there is an access to a region for which there is a memory mapping but the memory was mapped with one of the `UC_PROT_*` restrictions.

The `UC_HOOK_MEM_READ_PROT` hooks is called when the code tries to read a region that isn't allowed to be read.

The `UC_HOOK_MEM_WRITE_PROT` hooks is called when the code tries to write to a region that isn't allowed to be written.

The `UC_HOOK_MEM_FETCH_PROT` hooks is called when the emulator needs to read an instruction from a region that isn't allowed to execute.

In all cases you can either map the page in with the `uc_mem_protect*` function or return non-0 to abort execution.

*Why might you use it?*

You might change the protection level of the region to allow the memory to be accessed, or you might return non-0 to abort execution.

---

### OPENBSD NOTES (`docs/OPENBSD-NOTES.md`)

## Circumventing OpenBSD 6.0's W^X Protections

OpenBSD 6.0 and above enforces data-execution prevention (DEP or
W^X) by default, preventing memory from being mapped as 
simultaneously writeable and executable (i.e., W|X). This causes
problems for Unicorn, if left in place.  If you're seeing
errors like the following:
```
/home/git/unicorn >> ./sample_arm
Emulate ARM code
zsh: abort (core dumped)  ./sample_arm
```
then W^X is likely the culprit. If we run it again with ktrace
and look at the output with kdump, we see that this is indeed
the issue:
``` 
 82192 sample_arm CALL  mmap(0,0x800000,0x7<PROT_READ|PROT_WRITE|PROT_EXEC>,0x1002<MAP_PRIVATE|MAP_ANON>,-1,0)
 82192 sample_arm PSIG  SIGABRT SIG_DFL
 82192 sample_arm NAMI  "sample_arm.core"
```
Right now, we're in the /home filesystem. Let's look at its mount
options in /etc/fstab:
```
1234abcdcafef00d.g /home ffs rw,nodev,nosuid 1 2
```
If we edit the options to include ```wxallowed```, appending
this after nosuid, for example, then we're golden:
```
1234abcdcafef00d.g /home ffs rw,nodev,nosuid,wxallowed 1 2
```

Note that this *does* diminish the security of your filesystem 
somewhat, and so if you're particularly particular about such
things, we recommend setting up a dedicated filesystem for 
any activities that require ```(W|X)```, such as unicorn
development and testing. 

In order for these changes to take effect, you will need to
reboot. 

_Time passes..._

Let's try this again. There's no need to recompile unicorn or 
the samples, as (W^X) is strictly a runtime issue. 

First, we double check to see if /home has been mounted with
wxallowed:
```
/home >> mount | grep home
/dev/sd3g on /home type ffs (local, nodev, nosuid, wxallowed)
```
Okay, now let's try running that sample again...
```
/home/git/unicorn/samples >> ./sample_arm
Emulate ARM code
>>> Tracing basic block at 0x10000, block size = 0x8
>>> Tracing instruction at 0x10000, instruction size = 0x4
>>> Emulation done. Below is the CPU context
>>> R0 = 0x37
>>> R1 = 0x3456
==========================
Emulate THUMB code
>>> Tracing basic block at 0x10000, block size = 0x2
>>> Tracing instruction at 0x10000, instruction size = 0x2
>>> Emulation done. Below is the CPU context
>>> SP = 0x1228
```
works fine.

---

### Testing (`docs/Testing.md`)

# Testing in Unicorn

Unicorn focus on the testing to reduce bugs and ensure the expected behaviors. The `tests/` directory contains a few subdirectories for testing purposes.

- `unit/`: C unit tests since Unicorn 2.
- `regress/`: The regression tests written in Python and C, imported from Unicorn 1.
- `rust-tests/`: The tests written in rust.
- `fuzz/`: The fuzz drivers for OSS-Fuzz.
- `benchmarks/`: The benchmark suite imported from Unicorn 1.

## Contribution Guide

Generally, it is ideal to add new tests whenever a PR is made. `unit/` should be the first place for the new tests to go.

---

### Unicorn1 Logo (`docs/unicorn1-logo.txt`)

/\'.         _,.
                 |:\ \.     .'_/
            _.-  |(\\ \   .'_.'
        _.-'  ,__\\ \\_),/ _/
      _:.'  .:::::::.___  ,'
      //   ' ./::::::\<o\(
     //     /|::/   `"(   \
    ;/_    / ::(       `.  `.
   /_'/   | ::::\        `.  \
   '//    '\ :::':\_    _, ` _'-
   / |     '\.:/|::::.._ `-__ )/
   | |       \;| \:(    '.(_ \_)
   | |        \(  \::.    '-)
   \ \  ,          '""""---.
    \ \ \    ,        _.-...)
     \ \/\.  \:,___.-'..:::/
      \ |\\:,.\:::::'.::::/
       `  `:;::::'.::;::'
             '":;:""'

---

--- METRICS ---
- Files Extracted: 17
- Estimated Token Budget: ~11006 tokens
- Canonical Reference: https://codewiki.google/github.com/unicorn-engine/unicorn
