Alias for a C function in IAR - c

I need a symbol alias to be the alias for the function function as described in this question, but for IAR compiler/linker. I have tried answers for GCC, but those don't work, obviously:
// source code
void alias(void) __attribute__ ((alias ("function")));
Error[Pe130]: expected a "{" C:\project\test.c 61
void alias(void) asm("function");
Error[Pe065]: expected a ";" C:\project\test.c 61
#pragma weak alias=function
Error[e46]: Undefined external "alias" referred in ?ABS_ENTRY_MOD ( )
// linker options:
-Dalias=function
Fatal Error[e163]: The command line symbol "function" in -Dalias=function is not defined.
Does anyone know how I can define a function alias in IAR/Xlink?
A little background: I'm responsible for a module which is used in several projects. In order to test it, I have developed test cases for testIDEA tool which validate assertions at certain breakpoints. However, some common functions have different names in different projects (e.g. the initialization function could be called init(), init_mcu(), startup() etc.) so every time my module is integrated in a new project, I have to modify my test cases to match the new function names. What I'd like to do instead is to define a common alias (e.g. test_init()) to whatever the init function is called, so that my test cases can always set a breakpoint using this common name. I expect this symbol to make it to the ELF file, where it can be seen by the debugger.

From the IAR C/C++ Development Guide (p. 258):
To make the definition of foo a weak definition, write:
#pragma weak foo
To make NMI_Handler a weak alias for Default_Handler, write:
#pragma weak NMI_Handler=Default_Handler
If NMI_Handler is not defined elsewhere in the program, all references to NMI_Handler will refer to Default_Handler.
So, try something like this:
void f1(void);
void f2(void);
#pragma weak f1=f2
void f2(void) {}

After a close look at xlink options I've found the one which sort of suits my needs:
-e -enew=old [,old] …
Use -e to configure a program at link time by redirecting a function call from one function to another.
This can also be used for creating stub functions; i.e. when a system is not yet complete, undefined function calls can be directed to a dummy routine until the real function has been written.
I ended up with this code:
void alias(void) {
// copy the body of function()
}
// Linker parameters
-ealias=function
This redirects all calls to function() to alias(), regardless the actual name function has. Sure it's an ugly hack because I have to copy the code, but I get what I wanted: I can set a breakpoint to alias() by name.

Related

Does XC8 compiler support weak symbols?

gcc has __attribute__((weak)) which allows to create a weak symbol such as a function. This allows the user to redefine a function. I would like to have the same behavior in XC8.
More info:
I am writing a driver for XC8 and I would like to delegate low level initialization to a user defined function.
I know it is possible to redefine a function: there is the putch function that is implemented in XC8's source file and which is called by the printf function. The user is allowed to reimplement putch inside his application. There are two functions with the same name, but no error is raised.
putch's implementation in XC8's source files has a comment saying "Weak implementation. User implementation may be required", so it must be possible.
I looked at pragmas in XC8's user guide, but there is no directive related to this question.
A linker will only search static libraries to resolve a symbol that is not already resolved by input object files, so replacing static library functions can be done without weak linkage. Weak linkage is useful for code provided as source or object code rather then as a static library.
So if no weak linkage directive is supported, you could create a static library for the "weak" symbols and link that.
The XC8 manual documents behaviour for both the IAR compatibility directive __weak and a weak pragma, and in both cases the directives are ignored (supported only in XC16 and XC32), so you will have to use the above suggested method, which is in any case far more portable - if somewhat inconvenient.
In the case of putch() I suspect that this is not working as you believe. I would imagine that this is not a matter of weak linkage at all; in the static library containing printf() an unresolved link to putch() exists, and the linker resolves it with whatever you provide; if you were to compile and link both the Microchip implementation and yours from source code you would get a linker error; equally if you were to provide no implementation whatsoever you would get a linker error.
XC8 compiler does support the "weak" attribute.
The weak attribute causes the declaration to be emitted as a weak symbol. A weak symbol indicates that if a global version of the same symbol is available, that version should be used instead. When the weak attribute is applied to a reference to an external symbol, the symbol is not required for linking.
For example:
extern int __attribute__((weak)) s;
int foo(void)
{
if (&s)
return s;
return 0; /* possibly some other value */
}
In the above program, if s is not defined by some other module, the program will still link but s will not be given an address.
The conditional verifies that s has been defined (and returns its value if it has). Otherwise '0' is returned.
There are many uses for this feature, mostly to provide generic code that can link with an optional library.
A variable can also be qualified with the "weak" attribute.
For example:
char __attribute__((weak)) input;
char input __attribute__((weak));

Is there a way in C to have the compiler/linker give an error if a function is not defined?

In my case I am writing a simple plugin system in C using dlfcn.h (linux). The plugins are compiled separately from the main program and result in a bunch of .so files.
There are certain functions that must be defined in the plugin in order for the the plugin to be called properly by the main program. Ideally I would like each plugin to have included in it a .h file or something that somehow states what functions a valid plugin must have, if these functions are not defined in the plugin I would like the plugin to fail compilation.
I don't think you can enforce that a function be defined at compile time. However, if you use gcc toolchain, you can use the --undefined flag when linking to enforce that a symbol be defined.
ld --undefined foo
will treat foo as though it is an undefined symbol that must be defined for the linker to succeed.
You cannot do that.
It's common practice, to only define two exported functions in a library opened by dlopen(), one to import functions in your plugin and one to export functions of your plugin.
A few lines of code are better than any explanation:
struct plugin_import {
void (*draw)(float);
void (*update)(float);
};
struct plugin_export {
int (*get_version)(void);
void (*set_version)(int);
};
extern void import(struct plugin_import *);
extern void export(struct plugin_export *);
int setup(void)
{
struct plugin_export out = {0};
struct plugin_import in;
/* give the plugin our function pointers */
in.draw = &draw, in.update = &update;
import(&in);
/* get our functions out of the plugin */
export(&out);
/* verify that all functions are defined */
if (out.get_version == NULL || out.set_version == NULL)
return 1;
return 0;
}
This is very similar to the system Quake 2 used. You can look at the source here.
With the only difference, Quake 2 only exported a single function, which im- and exports the functions defined by the dynamic library at once.
Well after doing some research and asking a few people that I know of on IRC I have found the following solution:
Since I am using gcc I am able to use a linker script.
linker.script:
ASSERT(DEFINED(funcA), "must define funcA" ) ;
ASSERT(DEFINED(funcB), "must define funcB" ) ;
If either of those functions are not defined, then a custom error message will be output when the program tries to link.
(more info on linker script syntax can be found here: http://www.math.utah.edu/docs/info/ld_3.html)
When compiling simply add the linker script file after the source file:
gcc -o test main.c linker.script
Another possibility:
Something that I didn't think of (seems a bit obvious now) that was brought to my attention is you can create small program that loads your plugin and checks to see that you have valid function pointers to all of the functions that you want your plugin to have. Then incorporate this into your build system, be it a makefile or a script or whatever. This has the benefit that you are no longer limited to using a particular compiler to make this work. As well as you can do some more sophisticated checks for other other things. The only downside being you have a little more work to do to get it set up.

What are weak functions and what are their uses? I am using a stm32f429 micro controller

Wikipedia says:
A weak symbol denotes a specially annotated symbol during linking of
Executable and Linkable Format (ELF) object files. By default, without
any annotation, a symbol in an object file is strong. During linking,
a strong symbol can override a weak symbol of the same name. In
contrast, two strong symbols that share a name yield a link error
during link-time. When linking a binary executable, a weakly declared
symbol does not need a definition. In comparison, (by default) a
declared strong symbol without a definition triggers an undefined
symbol link error. Weak symbols are not mentioned by C or C++ language
standards; as such, inserting them into code is not very portable.
Even if two platforms support the same or similar syntax for marking
symbols as weak, the semantics may differ in subtle points, e.g.
whether weak symbols during dynamic linking at runtime lose their
semantics or not.
What are the weak functions and what are their uses? I am using an stm32f429 micro controller. There are some weak functions in the library. But I can't understand, what they and their use!
I searched about it on google but did't get a satisfactory answer.
When a function is prepended with the descriptor __weak it basically means that if you (the coder) do not define it, it is defined here.
Let us take a look at my arch-nemesis "HAL_UART_RxCpltCallback()".
This function exists within the HAL of the STM32F4-HAL code base that you can download from ST-Micro.
Within the file stm32f4xx_hal_uart.c file you will find this function defined as:
__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_RxCpltCallback could be implemented in the user file
*/
}
So, as the note within the code here says, place this function inside your own user files. However when you do that, do not put in the __weak term. This means that the linker will take your definition of the HAL_UART_RxCpltCallback() function and not the one defined within the stm32f4xx_hal_uart.c file.
This gives the generic code base the ability to always compile. You don't have to write a whole bunch of functions that you are not interested in but it will compile. When it comes time to writing your own, you just have to NOT define yours as __weak and write it.
Simple? Helpful?
Cheers!!
Let's say we have a common (library) protocol interface protocol.c, and upon receiving data we wish to execute application specific logic in our communication interface com.c. This can be solved with a weak function.
/// protocol.h
void protocol_recCallback(protocol_t *prt);
/// protocol.c
__weak void protocol_recCallback(protocol_t *prt) {}
void protocol_rx(protocol_t *prt)
{
// Common protocol interface
protocol_recCallback(prt); // This will call application specific function in com.c
}
/// com.c
#include "protocol.h"
void protocol_recCallback(protocol_t *prt)
{
// Application specific code is executed here
}
Advantage:
If protocol_recCallback() is not defined in com.c. The linker will not output an undefined reference and the __weak function will be called.
__weak function are methods that can be overwritten by user function with same name, used to define vector tables, and default handlers
Normal function writing (declaration and definition) are considered strong meaning that the function name cannot be re declared, you will get compiler/linker error
Declaring the function as week it can be overwritten by user code
void USART1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler")));
uint32_t vectors[75] __attribute__((section(".isr_vector")));
vectors[0] = STACK_START;
vectors[52] = USART1_IRQHandler;
void Default_Handler(void) {
while(1);
}
uart1.c (user code)
void USART1_IRQHandler(){
...
}
in the above sample code the USART1_IRQHandler is defined as weak function and aliased to Default_handler
User can override this function using the same name without any compiler/linker error if user define the USART1_IRQHandler in uart1.c this new function definition will be used
In addition to "This gives the generic code base the ability to always compile." __weak allows you to regenerating(in CubeMX) your code without touching your __weak +less callback function code.
if you write your code in this:
__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_RxCpltCallback could be implemented in the user file
*/
}
and regenarate in cubemx for some reason. Your code will blow up!

gcc: Can you put function pointers to a different section (not .data)?

For doing Unit Testing of an embedded project on the host, I started to use function pointers to be able to change between the 'real' implementation of a function and a mock at runtime.
So, my function 'foo' looks like this in the .c file:
// the 'real' implementation of the function to be used during runtime
void fooImplementation ( )
{
/* ... */
}
// the function pointer, initialized to the 'real' implementation
void (*foo) ( ) = fooImplementation;
It came out that the target processor (Blackfin) generates an exception, because the function pointer resides in the internal L1 data memory which isn't allowed to carry code but only data.
A solution that works is to assign an attribute to each function pointer so it is put into a different section that doesn't reside in L1 data memory, e.g.:
void (*foo) ( ) __attribute__ (( section(".ext_mem"))) = fooImplementation;
But this makes the code a little bit hard to read and is error prone (if you forget to assign the attribute, unit tests will run fine but the code will generate the exception as soon as the function is called on the target).
So my question is if there is some way to tell gcc to put all function pointers to a different section by default.
There is no such option, in gcc, to specially put all function pointers in a particular section, by default. Unless, ofcourse you rewrite the compiler and linker rules.
You have to use the __attribute__ keyword, as you mentioned in the question. If the code looks complex, you could create a macro around it:
#define SPECIAL_FOO(x) void (*x) ( ) __attribute__ (( section(".ext_mem")))
and then use it like this:
SPECIAL_FOO(foo) = fooImplementation;
There's however another way, too. You could see this SO thread to understand more about creating custom linker scripts to accomplish your task:Forcing certain compiler-generated variables into specific ELF sections (with gcc)

Linking LLVM JIT code to external C++ functions

I'm writing a LLVM scripting engine that JIT compiles scripting code in a custom language. My problem is that I'm unable to call external functions (even the C99 erf() function is failing).
For example if I extern "C" the erf function,
extern "C" double erft(double x){
return erf(x);
}
and create a function with external linkage
std::vector<const Type*> Double1(1,Type::getDoubleTy(getGlobalContext()));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),Double1,false);
Function *erft = Function::Create(FT,Function::ExternalLinkage,"erft",TheModule);
get the following error message when running my script with erft(0.0) :
LLVM ERROR: Program used external function 'erft' which could not be resolved!
Doing the mapping manually,
void ExecutionEngine::addGlobalMapping( const GlobalValue * erfF, void * erft);
will get me the following error:
declaration of `void llvm::ExecutionEngine::addGlobalMapping(const llvm::GlobalValue*, void*)' outside of class is not definition
Obviously I'm doing something very wrong. Any help would be much appreciated
Assuming you haven't disabled it (by calling EE->DisableSymbolSearching()) then LLVM will use dlsym() to find the symbols in the JIT program itself. Depending on your platform, that might mean that you need to build your JIT with -fPIC, or that it might not be available at all (such as on Windows).
Aside from automatic symbol searching, you can always register the individual functions yourself using EE->addGlobalMapping(GV, &function) where GV = the llvm::Function* function declaration that matches the native function you're calling. In your case with ertf() that's:
EE->addGlobalMapping(erft, &::erft);
Note that you named the global function erft() and the local variable erft, hence the "::". Please pick different names next time!
This might be happening because you forgot to add the "libm" depedency, try using:
[your module]->addLibrary("m");
See here for more information about the Module::addLibrary().
I don't know llvm, but this make no sense:
void ExecutionEngine::addGlobalMapping( const GlobalValue * erfF, void * erft);
That defines a new function in C++. What you need to do is somehow register your function with LLVM. Defining that function is like trying to add new methods to the LLVM classes, not what you want to do.

Resources