Skip to content

Commit

Permalink
ld.so: load libs with same name experiments
Browse files Browse the repository at this point in the history
  • Loading branch information
johannst committed Apr 10, 2024
1 parent 16e5ab0 commit ae49886
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/development/ld.so.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ symbol=default_main; lookup in file=/lib64/ld-linux-x86-64.so.2 [0]
./main: error: symbol lookup error: undefined symbol: default_main (fatal)
```
## Load lib with same name from different locations
The sources in [ldso/samename][src-samename] show some experiments, loading the
libs with the same name but potentially from different locations (paths).
## Dynamic Linking (x86_64)
Dynamic linking basically works via one indirect jump. It uses a combination of
function trampolines (`.plt` section) and a function pointer table (`.got.plt`
Expand Down Expand Up @@ -260,3 +264,4 @@ Using `radare2` we can analyze this in more detail:
As we can see the offset from relocation at index `0` points to `GOT[3]`.
[src-deepbind]: https://github.com/johannst/notes/tree/master/src/development/ldso/deepbind
[src-samename]: https://github.com/johannst/notes/tree/master/src/development/ldso/samename
13 changes: 13 additions & 0 deletions src/development/ldso/samename/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
all:
mkdir -p foo bar
gcc -g -o foo/lib.so lib.c -shared -fPIC -DNAME=\"foo\"
gcc -g -o bar/lib.so lib.c -shared -fPIC -DNAME=\"bar\"
gcc -g -o main main.c -ldl
./main foo/lib.so bar/lib.so
LD_LIBRARY_PATH=foo:bar ./main lib.so lib.so
LD_LIBRARY_PATH=bar:foo ./main lib.so lib.so
LD_LIBRARY_PATH=foo ./main lib.so foo/lib.so
LD_LIBRARY_PATH=foo ./main lib.so bar/lib.so

clean:
$(RM) -r foo bar main
9 changes: 9 additions & 0 deletions src/development/ldso/samename/lib.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#include <stdio.h>

#ifndef NAME
#define NAME __FILE_NAME__
#endif

void moose() {
puts(NAME " says moose");
}
36 changes: 36 additions & 0 deletions src/development/ldso/samename/main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>

void print_libso() {
FILE* m = fopen("/proc/self/maps", "r");
assert(m);

char line[256];
while (fgets(line, sizeof(line), m)) {
if (strstr(line, "lib.so")) {
printf("%s", line);
}
}
fclose(m);
}

int main(int argc, char* argv[]) {
for (int i = 1; i < argc; ++i) {
void* h = dlopen(argv[i], RTLD_LAZY | RTLD_GLOBAL);
if (!h) {
puts(dlerror());
return 1;
}

void (*next)() = dlsym(h, "moose");
assert(next);
next();

// leak lib, we want to priint the mmap.
}

print_libso();
return 0;
}

0 comments on commit ae49886

Please sign in to comment.