1

I've created shared library (will be used like plugin). There are a lot of functions like a

extern "C" long __attribute__ ((__cdecl__)) SumAgrs(long X, long Y, long Z, long *Out)
{
    *Out = X + Y + Z;
    return 0;
}

I would like to call functions from this library in C++(GCC, Linux), but not in compile time. When I use inline assembler, the "push" instruction corrupt local variables, and i have no idea how to fix it.

typedef int (*FARPROC)();

void *dl_handle = dlopen("plugin.so", RTLD_LAZY);
FARPROC proc = (FARPROC)dlsym(dl_handle, "SumAgrs");

long result;

asm("leal %0, %%eax\n\r" \
    "pushl %%eax" : : "m" (result));
asm("pushl $10");
asm("pushl $15");
asm("pushl $20");
asm("call *%0" : : "m" (proc));

Result binary file contains something like call *24(%esp). So my pushl change %esp and call cause segmentation fault. But how to avoid this behavior?

thx

2 Answers 2

1

Look at libffi: "A Portable Foreign Function Interface Library"

"The libffi library provides a portable, high level programming interface to various calling conventions. This allows a programmer to call any function specified by a call interface description at run-time."

http://sourceware.org/libffi/

Sign up to request clarification or add additional context in comments.

Comments

0

You needn't assembler to call functions, actually:

extern "C" 
{
    typedef long __attribute__ ((__cdecl__)) (*Proc)(long X, long Y, long Z, long *Out);
}

void *dl_handle = dlopen("plugin.so", RTLD_LAZY);
Proc proc = (Proc)dlsym(dl_handle, "SumAgrs");

proc(...); // call

Note, that either you call functions with c-code, or with ASM inline, your code for call generated in compile time. You cannot pass string variable to asm, because code for your asm inline should be generated during program compilation. That means you cannot do

std::string asm_code;
std:: cin >> asm_code;
asm(asm_code);

3 Comments

Functions will be called from script and parameters are stored in array. So the compile time "call" isn't solution.
no no, with the ASM inline, the code will be generated in run-time. For example (pseudocode): foreach (params) { push parm; } call func;
@user1173308, You cannot act like that! You never sure, that foreach(params) does not use stack pointer inside it, and of course, it does not assume you will change it by hands! Do not write such code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.