# cs6332: e9patch tutorial
In this tutorial, we will go over the [part1] example from [the unit5 resource][unit5]. The example code contains a trampoline routine ([part1.c]) and a driver script ([part1.sh]). You can also find the resource file at `/home/labs/unit5.zip`.
## Trampoline routine [part1.c]
The file implements three functions:
* `void init(void)` — An initializer function that is called once at the beginning of the program.
* `void fini(void)` — A finalizer function that is called once at the end of the program.
* `void memcounter(const void *addr)` — A callback function that will be invoked for each instruction containing a memory operand (as we will illustrate later). The argument addr indicates the address of the instruction being instrumented.
`memcounter()` increments the counter each time execution reaches a patched instruction site. Its unused `addr` argument demonstrates how to pass instruction metadata to a callback. `fini()` writes the report during normal exit of the dynamically linked example. A crash or a call to `_exit()` can bypass this hook. This example uses the support code provided by E9Patch in `stdlib.c`. See the [User Guide].
```c=
#include "stdlib.c"
static uint64_t mem_counter = 0;
void memcounter(const void *addr)
{
(void)addr;
mem_counter++;
}
void fini(void)
{
FILE *out = fopen("output.txt", "w");
if (out == NULL) {
return;
}
fprintf(out, "Executed instructions matching defined(mem[0]): %llu\n",
(unsigned long long)mem_counter);
fclose(out);
}
```
## Driver script [part1.sh]
The driver script takes a single argument specifying the target program to be instrumented. After receiving the target binary, the script first compiles the trampoline routine (line 8), and then instruments the target program (line 11).
- **`-M 'defined(mem[0])'`**: Selects and instruments instructions that contain memory operations.
- **`-P 'memcounter((static) addr)@part1'`**: Injects a call to the `memcounter()` function from `part1.c` at each selected instruction. The argument `addr` represents the address of the instrumented instruction. A full list of available attributes can be found in the [User Guide].
```bash=
#!/bin/bash
set -e
if [[ $# -ne 1 ]]; then
printf 'Usage: %s <target_program>\n' "$0" >&2
exit 1
fi
target=$1
prog="$(basename -- "$target")_part1"
e9compile part1.c
e9tool -M 'defined(mem[0])' -P 'memcounter((static) addr)@part1' \
"$target" -o "$prog"
# Remove the previous report so a missing report is visible.
rm -f -- output.txt
"./$prog"
cat output.txt
# output the result.
echo ""
cat output.txt
```
The example run of the above instrumentation looks like the following:
```shell=
$ cd part1
part1 $ ./part1.sh /bin/ls
gcc -fno-stack-protector -fno-builtin -fno-exceptions -fpie -O2 -Wno-unused-function -U_FORTIFY_SOURCE -mno-mmx -mno-sse -mno-avx -mno-avx2 -mno-avx512f -msoft-float -mstringop-strategy=loop -fno-tree-vectorize -fomit-frame-pointer -I /usr/share/e9compile/include/ -c -Wall ./part1.c
gcc part1.o -o part1 -pie -nostdlib -Wl,-z -Wl,max-page-size=4096 -Wl,-z -Wl,norelro -Wl,-z -Wl,stack-size=0 -Wl,--export-dynamic -Wl,--entry=0x0 -Wl,--strip-all
....
-----------------------------------------------
mode = Linux ELF executable
input_binary = /bin/ls
output_binary = ls_part1
num_patched = 5626 / 5626 (100.00%)
num_patched_B2 = 1063 / 5626 (18.89%)
num_patched_T1 = 799 / 5626 (14.20%)
num_patched_T2 = 57 / 5626 (1.01%)
num_patched_T3 = 95 / 5626 (1.69%)
num_virtual_mappings = 965
num_physical_mappings = 149 (15.44%)
num_virtual_bytes = 3952640
num_physical_bytes = 610304 (15.44%)
input_file_size = 133792
output_file_size = 842722 (629.87%)
time_elapsed = 54ms
memory_used = 7196KB
-----------------------------------------------
ls_part1 output.txt part1 part1.c part1.sh README.md
===================================================
Number of memory instructions executed: 3441
===================================================
```
:::info
**Extending this template for Part 1.** This example counts only *memory* instructions, and it places one probe per matched instruction (`-M 'defined(mem[0])'`). That is fine here, but Part 1 also requires a count of *all executed instructions*. For that total, do not place a probe on every instruction; use grouped probes instead (for example, add a basic block's static instruction count each time the block executes), as required in the handout. Dense per-instruction instrumentation can cause E9Patch's patching tactics to interfere with one another. See Section 5.2 (limitation L3) of the [E9Patch paper][e9patch].
:::
## Resources
* [The e9patch framework][e9patch]
* [User guide]
* [Programming guide]
###### tags: `e9patch`,`cs6332`,`tutorial`
---
[User guide]:https://github.com/GJDuck/e9patch/blob/master/doc/e9tool-user-guide.md
[Programming guide]:https://github.com/GJDuck/e9patch/blob/master/doc/e9patch-programming-guide.md
[e9patch]:https://github.com/GJDuck/e9patch
[unit5]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/releases
[part1]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/tree/main/part1?ref_type=heads
[part1.c]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/tree/main/part1/part1.c?ref_type=heads
[part1.sh]:https://gitlab.syssec.org/kjee/unit5-static-binary-rewriter/-/tree/main/part1/part1.sh?ref_type=heads