[issue44689] MacOS: Python binaries not portable between Catalina and Big Sur

Tobias Bergkvist report at bugs.python.org
Thu Jul 22 08:43:27 EDT 2021


Tobias Bergkvist <tobias at bergkv.ist> added the comment:

You are absolutely right! From the manpage of dlopen(3) on MacOS Big Sur:

> dlopen() examines the mach-o file specified by path. If the file is compatible with the current process and has not already been loaded into the current process, it is loaded and linked.  After being linked, if it contains any initializer functions, they are called, before dlopen() returns. dlopen() can load dynamic libraries and bundles.  It returns a handle that can be used with dlsym() and dlclose(). A second call to dlopen() with the same path will return the same handle, but the internal reference count for the handle will be incremented. Therefore all dlopen() calls should be balanced with a dlclose() call.

Essentially, if the shared library contains initializer functions that have some kind of side-effects, dlopen will also trigger these side-effects.

Basic example:
```
// mylib.c
#include <stdio.h>
void myinit(void) {
    printf("Hello from mylib\n");
}
__attribute__((section("__DATA,__mod_init_func"))) typeof(myinit) *__init = myinit;
```

---
```
// main.c
#include <dlfcn.h>
#include <stdio.h>
int main(void) {
    void* handle = dlopen("./mylib.dyld", RTLD_LAZY);
    if (handle == NULL) printf("Failed to load"); 
}
```

$ clang mylib.c -shared -o mylib.dyld
$ clang main.c -o main
$ ./main
Hello from mylib

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44689>
_______________________________________


More information about the Python-bugs-list mailing list