C late binding with unknown arguments - c

I am presently in a case where I need to call a lot of function pointers that has been extracted at runtime. The problem is that the arguments are unknown at compilation time.
But, at runtime I receive datas that allows me to know the arguments of the function and I can even store the arguments in a char* array. The problem is that I don't have a function pointer model to cast it into.
In high level language, I know there is function like "InvokeMethode(String name,Byte[] args)" that interpret the bytes array like arguments. Since reflection does not exist in C, I have no hope to see this with a function pointer.
One solution that I have in mind (and it's really bad), is to create a model of function pointer at compilation time that will cast in a "hardcoded way" the ptr to the right type to use like this:
void callFunc64Bits(void* funcPtr,long long args);
void callFuncVoid(void* funcPtr);
The problem is that I will have to create like 100 function like this that will cast the pointer correctly.
Is there a way to do it more efficiently?
Thank you very much!

This is a hard problem without, unfortunately, good or easy answers.
See this former SO question: Run-time parameters in gcc (inverse va_args/varargs)
See this C FAQ question: http://c-faq.com/varargs/invvarargs.html
See this collection of "wacky ideas" by the C FAQ list maintainer: http://c-faq.com/varargs/wacky.html
Addendum: see this former SO question: How to call functions by their pointers passing multiple arguments in C?
...which mentions "libffi": http://sourceware.org/libffi/

Related

How to declare a function if it's return value and parameters are given in command line and unknown before implementation? [duplicate]

I am presently in a case where I need to call a lot of function pointers that has been extracted at runtime. The problem is that the arguments are unknown at compilation time.
But, at runtime I receive datas that allows me to know the arguments of the function and I can even store the arguments in a char* array. The problem is that I don't have a function pointer model to cast it into.
In high level language, I know there is function like "InvokeMethode(String name,Byte[] args)" that interpret the bytes array like arguments. Since reflection does not exist in C, I have no hope to see this with a function pointer.
One solution that I have in mind (and it's really bad), is to create a model of function pointer at compilation time that will cast in a "hardcoded way" the ptr to the right type to use like this:
void callFunc64Bits(void* funcPtr,long long args);
void callFuncVoid(void* funcPtr);
The problem is that I will have to create like 100 function like this that will cast the pointer correctly.
Is there a way to do it more efficiently?
Thank you very much!
This is a hard problem without, unfortunately, good or easy answers.
See this former SO question: Run-time parameters in gcc (inverse va_args/varargs)
See this C FAQ question: http://c-faq.com/varargs/invvarargs.html
See this collection of "wacky ideas" by the C FAQ list maintainer: http://c-faq.com/varargs/wacky.html
Addendum: see this former SO question: How to call functions by their pointers passing multiple arguments in C?
...which mentions "libffi": http://sourceware.org/libffi/

Run-time parameters in gcc (inverse va_args/varargs)

I'm trying to make some improvements to a interpreter for microcontrollers that I'm working on. For executing built-in functions I currently have something like this (albeit a bit faster):
function executeBuiltin(functionName, functionArgs) {
if (functionName=="foo") foo(getIntFromArg(functionArgs[0]));
if (functionName=="bar") bar(getIntFromArg(functionArgs[0]),getBoolFromArg(functionArgs[1]),getFloatFromArg(functionArgs[2]));
if (functionName=="baz") baz();
...
}
But it is for an embedded device (ARM) with very limited resources, and I need to cut down on the code size drastically. What I'd like to do is to have a general-purpose function for calling other functions with different arguments - something like this:
function executeBuiltin(functionName, functionArgs) {
functionData = fast_lookup(functionName);
call_with_args(functionData.functionPointer, functionData.functionArgumentTypes, functionArgs);
}
So I want to be able to call a standard C function and pass it whatever arguments it needs (which could all be of different types). For this, I need a call_with_args function.
I want to avoid re-writing every function to take argc+argv. Ideally each function that was called would be an entirely standard C function.
There's a discussion about this here - but has anything changed since 1993 when that post was written? Especially as I'm running on ARM where arguments are in registers rather than on the stack. Even if it's not in standard C, is there anything GCC specific that can be done?
UPDATE: It seems that despite behaviour being 'undefined' according to the spec, it looks like because of the way C calls work, you can pass more arguments to a function than it is expecting and everything will be fine, so you can unpack all the arguments into an array of uint32s, and can then just pass each uint32 to the function.
That makes writing 'nice' code for calls much easier, and it appears to work pretty well (on 32 bit platforms). The only problem seems to be when passing 64 bit numbers and compiling for 64bit x86 as it seems to do something particularly strange in that case.
Would it be possible to do at compile time with macros?
Something along the lines of:
https://www.redhat.com/archives/libvir-list/2014-March/msg00730.html
If runtime was required, perhaps __buildin_apply_args() could be leveraged.
from this document, section 5.5, Parameter Passing, it seems like parameters are passed both in registers and in stack, as with most of today platforms.
With "non standard C" I am thinking to pack the parameters and call the function following the documentation with some asm(). However you need a minimal information about the signature of the function being called anyway (I mean, how many bits for each argument to be passed).
From this point of view I would prefer to prepare an array of function names, an array of function pointers and an array of enumerated function signatures (in the number of bits of each argument... you don't need to differentiate void* from char* for example) and a switch/case on the signatures, and a switch/case on the last one. So I have reported two answers here.
You can do a very simple serialization to pass arbitrary arguments. Create an array and memcpy sizeof(arg) bytes into it for each passed argument.
Or you can create structs for function arguments.
Every function takes a char* or a void*. Then you pass either a pointer to a struct with that functions parameters, or you define a set of macros or functions to encode and decode arbitrary data from an array and pass the pointer to that array.

How can one implement an array of functions on C?

I am trying to implement an interpreter. I'd love to go with GCC first class labels to make it threaded code, but I should hold on to a standard this time, so naturally I am left with function table. So, I'm doing this:
unsigned short int FUN_TABLE[MAX_FUN] (void*);
And I want to fill it with functions, each getting pointer to its operands, doing its part, returning length of the whole instruction in memory to a dispatcher.
The thing is, I can't even compile it due to the following error: declaration of FUN_TABLE as array of functions. Considering it is exactly what I am trying to achieve, why is this an error, why should I pay it attention, and if I shouldn't, how to suppress it in elegant and standardized manner?
You can define an array of function pointers like this (pseudocode):
int (*funcArr2[10])(param, param, ...) = {NULL};
However, you should be aware that this means that all these functions have the same set of arguments. You can not declare an array with function pointers to totall different functions with regard to their signature.
GCC is telling you: "there is no such thing as an array of functions".
Considering it is exactly what I am trying to achieve, why is this an error, why should I pay it attention
Because you are trying to achieve something that does not exist in the C language. But instead, you can achieve the desired functionality through an array of function pointers.
The syntax of declaring a function pointer is
return_type (*func_ptr_name)(parameters)
and the syntax for declaring an array of function pointers is
return_type (*func_ptr_name[n])(parameters)
Since that syntax is quite obscure, you will not want to use it. The solution is to use typedefs:
typedef unsigned short (*func_table_t)(void*);
// declare an array of function pointers, using readable syntax:
func_table_t func_table [MAX_FUNC] =
{
&some_function,
&some_other_function,
...
};
Arrays of functions aren't legal. Your easiest work around would be an array of pointers to functions -- but this implies that each function being pointed to from the array has the same signature.

Template in ansi C?

How I can create function with other types of data (some struct or sth)? In C++ exist templates, but in C?
I hear about void *, but i dont know if it works.
Any ideas?
Well, the way to do it is with void *. You might also need use function pointers, for example if you need to compare generic values.
The other way to do it is to use xmacros, but that's generally more for reducing code duplication for very similar structures.
void * is the solution in C as any pointer has the same sizeof() as void *. Of course, you get no type safety, but it's as good an abstraction as you can get with C. Furthermore, you could look at stdarg.h and variadic functions, but again, you should keep track yourself of what you're doing, since the compiler won't aid you one bit.

Getting function argument types

Suppose I have a call to a function which takes a variable number of arguments in my source code. I want to do some kind of static analysis on this source code to find the type of the arguments being actually passed to the function. For example, if my function call is -
foo(a, b, c)
I want to find the data type of a, b and c and store this information.
You pretty well have to do the parse-and-build-a-symbol-table part of compiling the program.
Which means running the preprocessor, and lexing as well.
That's the bad news.
The good news is that you don't have to do much of the hard stuff. No need to build a AST, every part of the code except typedefs; struct, union, and enum definitions; variable-or-function declarations-and-definitions; and analyzing the function call arguments can be a no-op.
On further thought prompted by Chris' comments: You do have to be able to analyze the types of expressions and handle the va-arg promotions, as well.
It is still a smaller project than writing a whole compiler, but should be approached with some thought.
If this is in C++, you can hack together some RTTI using typeid etc.
http://en.wikipedia.org/wiki/Run-time_type_information

Resources