如何从动态负载库执行未知功能? [英] How to execute unknown functions from dynamic load libraries?

查看:63
本文介绍了如何从动态负载库执行未知功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计时就知道从动态库中加载函数很容易。
只是这样做:

It's easy to load functions from dynamic libraries when you know this function in design time. just do something like this:

   int (*fn)(int);

   l0 = dlopen("./libfoo.so", RTLD_LAZY);
   if (!l0) 
   {
      fprintf(stderr, "l0 %s\n", dlerror());
      return 1;
   }


   fn = (int (*)(int))dlsym(l0, "foo");


   if ((error = dlerror()) != NULL)  
   {
      fprintf(stderr, "fn:%s\n", error);
      return 1;
   }

   x=(*fn)(y);

...

如何执行设计时未知的库函数?在运行时,您具有函数名称以及参数指针数组和参数大小数组:

How to execute library function when it's unknown in design time? In runtime you have a function name and array of arguments pointers and array of arguments sizes:

char * fn_name = foo;
int foo_argc;
void * foo_argv [];
int foo_argv_size [];

char* fn_name="foo"; int foo_argc; void* foo_argv[]; int foo_argv_size[];

在脚本语言中这是小菜一碟,但是如何在c ++中很好地实现呢?

In scripting language it's a piece a cake task, but how to implement this nicely in c++?

推荐答案

实际上,如果您知道函数的调用约定及其接收的参数,则实际上存在一种在运行时调用函数的方法。但这不属于标准的C / C ++语言范围。

There's actually a method to call a function at run-time if you know its calling convention and which parameters it receives. This however lies out of the standard C/C++ language scope.

对于x86汇编程序:

假设以下内容:


  1. 您知道要在固态缓冲区中为函数准备所有参数,完全按照将其打包在堆栈中的方式

  2. 您的函数不会按值获取/返回C ++对象。

您可以然后使用以下函数:

You may use then the following function:

int CallAnyFunc(PVOID pfn, PVOID pParams, size_t nSizeParams)
{
    // Reserve the space on the stack
    // This is equivalent (in some sense) to 'push' all the parameters into the stack.
    // NOTE: Don't just subtract the stack pointer, better to call _alloca, because it also takes
    // care of ensuring all the consumed memory pages are accessible
    _alloca(nSizeParams);

    // Obtain the stack top pointer
    char* pStack;
    _asm {
        mov pStack, esp
    };

    // Copy all the parameters into the stack
    // NOTE: Don't use the memcpy function. Because the call to it
    // will overwrite the stack (which we're currently building)
    for (size_t i = 0; i < nSizeParams; i++)
        pStack[i] = ((char*) pParams)[i];

    // Call your function
    int retVal;
    _asm {
        call pfn
        // Most of the calling conventions return the value of the function (if anything is returned)
        // in EAX register
        mov retVal, eax
    };

    return retVal;
}

您可能需要根据使用的调用约定调整此功能

You may need to adjust this function, depending on the calling convention used

这篇关于如何从动态负载库执行未知功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆