Skip to content

Instantly share code, notes, and snippets.

@mlabbe
Last active March 6, 2020 04:54
Show Gist options
  • Save mlabbe/08ac4da4e47c514940aa94a5326230e7 to your computer and use it in GitHub Desktop.
Save mlabbe/08ac4da4e47c514940aa94a5326230e7 to your computer and use it in GitHub Desktop.
Override a function at link time by weakening it with objcopy
#!/bin/sh -x
rm -f *.o weak
CC=clang-9
LD=$CC
CFLAGS="-fno-inline-functions -O0"
$CC -c weak.c -o weak.o $CFLAGS
$CC -c weak_b.c -o weak_b.o $CFLAGS
$CC -c weak_c.c -o weak_c.o $CFLAGS
# weaken the symbol moveme in weak_c.o
llvm-objcopy-9 --weaken-symbol=moveme weak_c.o weak_c.o
$LD weak.o weak_b.o weak_c.o -o weak && \
./weak
$ ./weak
success!
void moveme(void);
int main(void) {
// whichever one was linked gets called
moveme();
return 0;
}
#include<stdio.h>
void moveme(void) {
puts("success!");
}
#include <stdio.h>
void moveme(void) {
puts("this function gets weakened before linking and this should not be called");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment