开发者

Callback throwing a segfault from within a shared object

开发者 https://www.devze.com 2023-03-07 12:58 出处:网络
As I understand it, when my .so is loaded using dlopen, the shared object is mapped into the address space of the calling process. I can call functions and access globals of the .so without error. How

As I understand it, when my .so is loaded using dlopen, the shared object is mapped into the address space of the calling process. I can call functions and access globals of the .so without error. However, whenever I pass a .so function a callback pointer to a function in the main program, the following happen:

  • The .so function goes onto the call stack as expected.
  • The address of the callback changes from 0x400F09 (as seen in the main program) to 0x6052A0 (as seen in the .so).
  • When I try to call the callback there's a segfault.

Is this some sort of fundamental memory mapping problem, or is there something trickier afoot?

Thanks.


Edit:

Here is the offending code. In the main program:

static unsigned char      innerFunc_1(unsigned char      x) { return x+1; }
static unsigned short     innerFunc_2(unsigned short     x) { return x+1; }
static unsigned int       innerFunc_4(unsigned int       x) { return x+1; }
static unsigned long long innerFunc_8(unsigned long long x) { return x+1; }

static void *restrict innerFuncs[] =
{
    innerFunc_1,
    innerFunc_2,
    innerFunc_4,
    innerFunc_8
};

typedef void(*IterFunc)(void *context, void *innerFunc);

static IterFunc *restrict fptrIter;

// ...

fptrIter[fptrIterOffset()] = dlsym(libhandle, name);

// ...

unsigned (*fptrInner)(unsigned) = innerFuncs[dimElmSize.index];
fptrInner(10); // does not segfault
fptrIter[fptrIterOffset()](pcontext, fptrInner);

In the .so:

typedef unsigned (*InnerFu开发者_开发百科nc_4)(unsigned x);

void iter_pointstoarray_4_1loop_lrud
    (InnerFunc_4 innerFunc)
{
    innerFunc(0); // Segfaults
}


It turns out that the inner function had the wrong function prototype. Fixing the prototype and the manner in which it was called fixed the segfault. Such is the danger of compiling things in a way that they can't be checked as thoroughly by the compiler.

0

精彩评论

暂无评论...
验证码 换一张
取 消