【问题标题】:Unable to hook ncurses functions with LD_PRELOAD无法使用 LD_PRELOAD 挂钩 ncurses 函数
【发布时间】:2019-12-24 08:41:45
【问题描述】:

我正在尝试挂钩一些 ncurses 函数,但它们没有任何效果。 ncurses 不是静态链接的,所以我不明白为什么它不起作用。

test.cpp

#include <cstdio>
#include <cstdlib>
#include <curses.h>

int main() {
  initscr();
  cbreak();
  noecho();

  getch();

  endwin();

  return 0;
}

编译:gcc test.cpp -o test -std=c++11 -lncurses

hook.cpp

#include <dlfcn.h>
#include <cstdio>
#include <cstdlib>

int getch() {
  typedef int getch ();
  getch* old_getch = (getch*) dlsym(RTLD_NEXT, "getch");

  int result = old_getch();

  fprintf(stderr, "getch() = %i\n", result);

  return result;
}

int noecho() {
  typedef int noecho ();
  noecho* old_noecho = (noecho*) dlsym(RTLD_NEXT, "noecho");

  int result = old_noecho();

  fprintf(stderr, "noecho() = %i\n", result);

  return result;
}

int endwin() {
  typedef int endwin ();
  endwin* old_endwin = (endwin*) dlsym(RTLD_NEXT, "endwin");

  int result = old_endwin();

  printf("endwin called");

  return result;
}

编译:gcc hook.cpp -o hook.so -shared -ldl -fPIC -std=c++11

很遗憾,它什么也没输出,我完全被难住了。

【问题讨论】:

  • 您的方法可能需要extern "c"
  • 我尝试过挂钩其他方法,例如 rand(),效果很好。我试过了,没有解决问题。
  • 废话,extern "c" 解决了我的一些问题,noecho() 和 endwin() 钩子工作,但 getch() 钩子仍然不会让步
  • 它很可能是一个宏——查阅文件 curses.h
  • 谢谢,它确实是一个宏,它就在我头上飞过。您介意将其发布为答案,以便我将其标记为已解决吗?

标签: c++ linux hook ncurses ld-preload


【解决方案1】:

规范没有说明getch 必须是函数(不是宏)。实际上,在 ncurses-6.1 中,getch 定义为

#define getch() wgetch(stdscr)

尽管如此,libncurses 中有一个getch 函数(它只是调用wgetch(stdscr)),所以dlsym(libncurses_handle,"getch") 确实有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多