advanced-microcode-patching / shiva

A custom ELF linker/loader for installing ET_REL binary patches at runtime
Other
152 stars 13 forks source link

Write initial Shiva Prelinker "shiva-ld" code. #4

Closed elfmaster closed 1 year ago

elfmaster commented 1 year ago

The Shiva Prelinker description taken from the Preliminary design and specification

The shiva-ld program applies several modifications to the test_function_patch ELF executable.
1. Specifies “/lib/shiva” as the interpreter in the PT_INTERP segment
2. Creates a new dynamic segment area in the executable (See 4.2.A on custom PT_DYNAMIC)
2.A SHIVA_DT_SEARCH specifies the module search path “/opt/shiva/modules/”
2.B SHIVA_DT_NEEDED specifies the module basename “fpatch.o”
2.C SHIVA_DT_EXTERNAL_REL location of pre-compiled reloc data for the executable
2.D SHIVA_DT_PTD_REL location of pre-compiled PTD relocations (See section 4.6)
The shiva-ld tools is responsible for applying the correct ELF meta-data to the binary so that at runtime
the kernel loads “/lib/shiva” as the interpreter, which in turn will load and link the patch. Since ELF
executables don’t contain ELF relocation data (Other than for shared library imports) Shiva can and
will analyze every instruction in the executable’s .text to find all instructions that must be linked to the

patch module; this is slow at runtime, and can be heavily optimized by shiva-ld generating pre-
compiled relocation data that lives in .shiva.xref.rel. (See section 5.0 Shiva runtime linking on target

executable). Additionally, the PTD (See section 4.7) commands generate custom Shiva relocation
records that are specifically for Program Transformation. To avoid all of the runtime calculations
necessary for building up to Program Transformation, shiva-ld will generate the necessary
transformation meta-data, and store it in .shiva.ptd.rel.
The shiva-ld tool creates an extra loadable segment in the target executable, large enough for an
updated PT_DYNAMIC segment, and all of the linking meta-data for Shiva.
So compiling and installing a patch to an ELF binary happens in 3 steps:
Pre-Runtime: Compile the patch, and pre-link it to the executable
1. gcc -fno-pic -mcmodel=large fpatch.c -o fpatch.o
2. shiva-ld ./test /lib/shiva /opt/shiva/modules/fpatch.o
Runtime: The Shiva linker applies the patch at runtime
3. ./test
elfmaster commented 1 year ago

To implement the above description, we will need to create a PT_NOTE to PT_LOAD conversion and add an extra segment large enough to contain a new and extended PT_DYNAMIC segment with additional custom dynamic tags used by Shiva.

elfmaster commented 1 year ago

Complete.