Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers and unknown number of arguments in C++

I came across the following weird chunk of code.Imagine you have the following typedef:

typedef int (*MyFunctionPointer)(int param_1, int param_2);

And then , in a function , we are trying to run a function from a DLL in the following way:

LPCWSTR DllFileName;    //Path to the dll stored here
LPCSTR _FunctionName;   // (mangled) name of the function I want to test

MyFunctionPointer functionPointer;

HINSTANCE hInstLibrary = LoadLibrary( DllFileName );
FARPROC functionAddress = GetProcAddress( hInstLibrary, _FunctionName );

functionPointer = (MyFunctionPointer) functionAddress;

//The values are arbitrary
int a = 5;
int b = 10;
int result = 0;

result = functionPointer( a, b );  //Possible error?

The problem is, that there isn't any way of knowing if the functon whose address we got with LoadLibrary takes two integer arguments.The dll name is provided by the user at runtime, then the names of the exported functions are listed and the user selects the one to test ( again, at runtime :S:S ). So, by doing the function call in the last line, aren't we opening the door to possible stack corruption? I know that this compiles, but what sort of run-time error is going to occur in the case that we are passing wrong arguments to the function we are pointing to?

like image 880
Emil D Avatar asked Mar 04 '10 14:03

Emil D


1 Answers

There are three errors I can think of if the expected and used number or type of parameters and calling convention differ:

  • if the calling convention is different, wrong parameter values will be read
  • if the function actually expects more parameters than given, random values will be used as parameters (I'll let you imagine the consequences if pointers are involved)
  • in any case, the return address will be complete garbage, so random code with random data will be run as soon as the function returns.

In two words: Undefined behavior

like image 151
Raphaël Saint-Pierre Avatar answered Nov 04 '22 07:11

Raphaël Saint-Pierre