Skip to content

Instantly share code, notes, and snippets.

@valpackett
Created March 26, 2018 22:17
Show Gist options
  • Save valpackett/92b0e25c5d4bac46d4fc722bcf9d3a38 to your computer and use it in GitHub Desktop.
Save valpackett/92b0e25c5d4bac46d4fc722bcf9d3a38 to your computer and use it in GitHub Desktop.
Linker removes struct :(

This fails with gold or LLD linkers, but works fine with bfd. And it only fails when a static library is involved. (Using objects directly is fine)

(lldb) bt
* thread #1, name = 'app', stop reason = signal SIGSEGV
    frame #0: 0x0000000000000000
  * frame #1: 0x00000000002012e2 app`main + 34
    frame #2: 0x0000000000201095 app`_start(ap=<unavailable>, cleanup=<unav
ailable>) at crt1.c:74
(lldb) p lib_thing_impl
(void *) $0 = 0x0000000000000000
(lldb) p lib_thing_instance
(void *) $1 = 0x0000000000204008
(lldb) p *lib_thing_instance
(lldb)
#include <stdio.h>
#include "libstruct.h"
#include "libinit.h"
int main() {
lib_init();
printf("%d\n", lib_thing_instance->foo());
return 0;
}
#include "libstruct.h"
void lib_init() {
lib_thing_instance = &lib_thing_impl;
}
void lib_init();
#include "libstruct.h"
static int foo() {
return 69420;
}
struct lib_thing lib_thing_impl = {
.foo = foo
};
#pragma once
struct lib_thing {
int (*foo)();
};
struct lib_thing *lib_thing_instance;
struct lib_thing lib_thing_impl;
libstruct.o: libstruct.c libstruct.h
cc -c -o $@ libstruct.c
libinit.o: libinit.c libinit.h
cc -c -o $@ libinit.c
lib.a: libstruct.o libinit.o
ar rcs $@ libstruct.o libinit.o
app: app.c lib.a
cc -o $@ app.c lib.a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment