TLS Modification

PE TLS Overview

LIEF can be used to modify, create, or remove Thread Local Storage (TLS) information.

TLS Modifications

All attributes of the interface can be modified as long as the changes are consistent with the layout of the PE binary. For instance, you can adjust the TLS callbacks by removing, reordering, or adding addresses:
import lief

pe: lief.PE.Binary = ...

callbacks: list[int] = pe.tls.callbacks

# Remove the last entry
callbacks.pop()

# Add an address
callbacks.append(0x140001010)

tls.callbacks = callbacks

pe.write("tls_modified.exe")

Relocations

Note that LIEF automatically manages the relocations that must be created or removed when modifying the TLS callbacks.

TLS Creation

If a PE binary does not contain TLS metadata, LIEF can be used to create this structure.

First, we can create and initiate a TLS instance:

import lief

tls = lief.PE.TLS()

tls.callbacks = [
    0x140001000,
    0x140001010,
]
pe: lief.PE.Binary = ...

pe.tls = tls # `tls` defined previously

pe.write("tls_demo.exe")

Relocations

Similary to the TLS callbacks modifications, LIEF automatically manages the relocations. In addition, it automatically initialize (if not set by the user) AddressOfIndex which is mandatory when defining up TLS metadata.