Commit e42b7314 authored by Vincent Pelletier's avatar Vincent Pelletier

Tolerate open and fopen being called before our own constructor.

An easy example of this is coreutils' "ls", when linked against libselinux:
libselinux will/may call fopen("/proc/filesystems", "re") during its own
constructor, which may be called before our.
Another example is inkscape, which contains static C++ classes (such as
Inkscape::Util::UnitTable::UnitTable) which may themselves call (f)open.
C++ runtime seems to call such static constructors before our contructor,
leading to the same issue. GCC documentation (as of version 8.0.1) says:
  However, at present, the order in which constructors for C++ objects
  with static storage duration and functions decorated with attribute
  constructor are invoked is unspecified. In mixed declarations,
  attribute init_priority can be used to impose a specific ordering.
parent 48241da3
......@@ -20,7 +20,7 @@ Requirements
------------
- make
- gcc (source uses __attribute__)
- a C compiler
- glibc (source uses RTLD_NEXT)
Building
......
......@@ -56,7 +56,7 @@ static inline void *dlsym_or_abort(const char *name) {
return symbol;
}
static void __attribute__ ((constructor)) init(void) {
static void init(void) {
original_open = dlsym_or_abort("open");
original_fopen = dlsym_or_abort("fopen");
replacement_hosts = getenv("HOSTS");
......@@ -67,6 +67,8 @@ static void __attribute__ ((constructor)) init(void) {
}
int open(const char *__file, int __oflag, ...) {
if (!original_open)
init();
if (!strcmp(__file, ORIGINAL_HOSTS_PATH))
__file = replacement_hosts;
if (__oflag & (O_CREAT | PURE_O_TMPFILE)) {
......@@ -82,6 +84,8 @@ int open(const char *__file, int __oflag, ...) {
}
FILE *fopen(const char *path, const char *mode) {
if (!original_fopen)
init();
if (!strcmp(path, ORIGINAL_HOSTS_PATH))
path = replacement_hosts;
return (*original_fopen)(path, mode);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment