overriding fclose(2)

Ondřej Bílka neleai@seznam.cz
Mon May 12 11:40:00 GMT 2014


On Mon, May 12, 2014 at 03:05:51PM +0530, vijay nag wrote:
> On Mon, May 12, 2014 at 1:07 PM, Ondřej Bílka <neleai@seznam.cz> wrote:
> > On Mon, May 12, 2014 at 11:50:35AM +0530, vijay nag wrote:
> >> Hello glibc,
> >>
> >> I'm trying to override/wrap fclose(2) libc call the following way.
> >>
> >> #include <stdio.h>
> >>
> >> #undef fclose
> >> extern int _IO_new_fclose(_IO_FILE *fp);  /* defined in ./libio/iofclose.c */
> >>
> >> int __attribute__((weak)) fclose(FILE *stream)
> >> {
> >>      /* extra actions before libc fclose */
> >>
> >>      return _IO_new_fclose(stream);
> >> }
> >>
> 
> > You could get correct function from dynamic linker like by
> > dlsym(RTLD_NEXT, "fclose").
> This is a linker error during link time. How can I override fclose(3)
> given its run time address ? dlsym will resolve the address via PLT(If
> PIC enabled for library) and I don't want  to overwrite PLT entry for
> fclose(3) either.  I used _IO_fclose(stream) instead of
> _IO_new_fclose(stream) and it seems to be working fine now.

What link error? A suggested way to do this is following, you need link
with -ldl here:

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#undef fclose

int fclose (FILE *fp)
{
  printf ("closed\n");
  int (*original_fclose)(FILE *) = dlsym (RTLD_NEXT, "fclose");
  return original_fclose(fp);
}
      

int main ()
{ 
  FILE *f=fopen ("foo", "r");
  fclose(f);
}



More information about the Libc-help mailing list