minor cleanup
authorRalph Ronnquist <ralph.ronnquist@gmail.com>
Wed, 26 Oct 2022 01:09:14 +0000 (12:09 +1100)
committerRalph Ronnquist <ralph.ronnquist@gmail.com>
Wed, 26 Oct 2022 01:09:14 +0000 (12:09 +1100)
libtarmap-0.c

index 339fdbd2793e449cc979957f3fbf29cd1946b4bd..89c0f4a337977e270278ae789dc965eda2efe82d 100644 (file)
@@ -12,9 +12,7 @@
 #include <unistd.h>
 #include <errno.h>
 
-static int (*real_open)(const char *pathname, int flags);
-static int (*real_openat)(int dirfd, const char *pathname, int flags);
-static FILE *(*real_fopen)(const char *pathname, const char *mode);
+static void *libc6;
 
 // The environment variable name
 #define TARMAP "TARMAP"
@@ -71,6 +69,10 @@ static FILE *tryopentar(const char *pathname) {
 
 // Override "openat"
 int openat(int dirfd, const char *pathname, int flags) {
+    static int (*real_openat)(int, const char*, int);
+    if ( real_openat == 0 ) {
+       real_openat = dlsym( libc6, "openat" );
+    }
     //fprintf( stderr, "openat( %s )\n", pathname );
     if ( data.tarmap ) {
        FILE *file = tryopentar( pathname );
@@ -78,11 +80,15 @@ int openat(int dirfd, const char *pathname, int flags) {
            return fileno( file );
        }
     }
-    return ( real_openat )? real_openat( dirfd, pathname, flags ) : 0;
+    return real_openat( dirfd, pathname, flags );
 }
 
 // Override "open"
 int open(const char *pathname, int flags) {
+    static int (*real_open)(const char *pathname, int flags);
+    if ( real_open == 0 ) {
+       real_open = dlsym( libc6, "open" );
+    }
     //fprintf( stderr, "open( %s )\n", pathname );
     if ( data.tarmap ) {
        FILE *file = tryopentar( pathname );
@@ -90,33 +96,32 @@ int open(const char *pathname, int flags) {
            return fileno( file );
        }
     }
-    return ( real_open )? real_open( pathname, flags ) : -1;
+    return real_open( pathname, flags );
 }
 
 // Override "fopen"
 FILE *fopen(const char *pathname, const char *mode) {
+    static FILE *(*real_fopen)(const char *pathname, const char *mode);
+    if ( real_fopen == 0 ) {
+       real_fopen = dlsym( libc6, "fopen" );
+    }
     if ( data.tarmap ) {
        FILE *file = tryopentar( pathname );
        if ( file ) {
            return file;
        }
     }
-    return ( real_fopen )? real_fopen( pathname, mode ) : 0;
+    return real_fopen( pathname, mode );
 }
 
 /**
  * Initialize the dynamic library.
  */
 void so_init() {
-    static int done = 0;
-    if ( done ) {
+    if ( libc6 ) {
        return;
     }
-    done = 1;
-    void *lib = dlopen( "libc.so.6", RTLD_LAZY );
-    real_open = dlsym( lib, "open" );
-    real_openat = dlsym( lib, "openat" );
-    real_fopen = dlsym( lib, "fopen" );
+    libc6 = dlopen( "libc.so.6", RTLD_LAZY );
     char *tarfile = getenv( TARMAP );
     if ( tarfile == 0 || *tarfile == 0 ) {
        //fprintf( stderr, "(libtarmap: no tar)\n" );