The call function only knows the types of parameters at runtime in C?

Let's say I have a function:

int foo (int A, char B){...} 

One of the features that I want to implement is the ability for the user to call any function in the application through the Linux terminal. Since the input is for software, in the terminal they print something like:

foo 2 'a'

Then my application parses this, and using character tables, it can find the address for foo() , as well as the type for all its parameters.

However, I'm not sure how to pass the parameters of the function when called, since I can have hundreds of different combinations of parameter types depending on the function being called.

Any hint on how this could be achieved without hundreds of nested if statements casting the parameters to the correct types before calling the functions?

This functionality is similar to what GDB has, where you can make call foo(2,'a') and GDB calls this function for you.

+6
source share
2 answers

There are two approaches to this. If you have described everything that you want to do, you can use the dyncall library so that you do not have to worry about the specifics of the platform / compiler, calling the semantics yourself:

The dyncall library encapsulates the semantics of invoking architecture, OS, and compiler functions in the parameters of the virtual link argument from left to right, and then the invocation interface, allowing programmers to invoke C functions completely. In other words, instead of directly invoking a function, the dyncall library provides a mechanism for manually entering function parameters and then call call.

Another approach is if you want to do more: for example. What if the argument cannot be created by a literal? What if the argument is the result of another function? Can you write f(123, g("a")) in the console? Can you write x=g("a"); f(x) x=g("a"); f(x) ? And if(cond) x="a" else x="b"; f(x) if(cond) x="a" else x="b"; f(x) In this case, you need to implement a scripting language, for example, for example. LUA.

+3
source

If you compile your binary file with debugging information, you can extract it using libdwarf ( https://www.prevanders.net/dwarf.html ), so for each function you can get a list of parameters with types, and you know how to interpret user input.

0
source

All Articles