access dlopen flags

家住魔仙堡 提交于 2020-01-23 03:21:15

问题


I'm inside a shared object (code) loaded with dlopen. I want to know the flags given to the loading call. I do not have access to the loader (code) - e.g. it may be a script interpreter - but I have to create subsequent dlopen calls with the same flags.

How can I do this?


回答1:


I think this is NOT possible without the aid of debuggers.

From the latest glibc code , here is the source code of dlopen

void *
dlopen (const char *file, int mode)
{
  return __dlopen (file, mode, RETURN_ADDRESS (0));
}

And __dlopen is in turn defined as

void *
__dlopen (const char *file, int mode DL_CALLER_DECL)
{
# ifdef SHARED
  if (__builtin_expect (_dlfcn_hook != NULL, 0))
    return _dlfcn_hook->dlopen (file, mode, DL_CALLER);
# endif

  struct dlopen_args args;
  args.file = file;
  args.mode = mode;
  args.caller = DL_CALLER;

# ifdef SHARED
  return _dlerror_run (dlopen_doit, &args) ? NULL : args.new;
# else
  if (_dlerror_run (dlopen_doit, &args))
    return NULL;

  __libc_register_dl_open_hook ((struct link_map *) args.new);
  __libc_register_dlfcn_hook ((struct link_map *) args.new);

  return args.new;
# endif
}

The flags you are looking for, RTLD_LAZY, RTLD_NOW, RTLD_GLOBAL and RTLD_LOCAL are ORed and stored in mode variable. As you can see there is no route through which it is passed back or anything like that.

EDIT: It seems there indeed is a way of achieving what you want as shown by the other answer. If you can un-accept my answer, I can delete it so as to help future visitors




回答2:


You could use the following library in place of a debugger:

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

typedef void *(*orig_dlopen_type)(const char *file, int mode);

void *dlopen(const char *file, int mode)
{
    fprintf(stderr, "dlopen called (mode: %d) on %s\n", mode, file);
    orig_dlopen_type orig_dlopen;
    orig_dlopen = (orig_dlopen_type)dlsym(RTLD_NEXT, "dlopen");
    return orig_dlopen(file, mode);
}

Compile with gcc -shared -fPIC dlopen_trace.c -o dlopen_trace.so -ldl

Then execute your program as normal with LD_PRELOAD=dlopen_trace.so. You should get a debug line printed every time dlopen is called.

If you want you can also modify the flags en-route...



来源:https://stackoverflow.com/questions/9874396/access-dlopen-flags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!