Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can make alias on external defined function in C?

Tags:

c

alias

gcc

weak

During compiling this C code

extern void Default_Handler(void);
void NMI_Handler(void) __attribute__ ((weak, alias ("Default_Handler")));

I've recive this

error: 'NMI_Handler' aliased to undefined symbol 'Default_Handler'

How I can make alias on external defined function?

Compiler:

gcc version 7.2.1 20170904 (release) [ARM/embedded-7-branch revision 255204] (GNU Tools for Arm Embedded Processors 7-2017-q4-major)
like image 353
Immortal_Buka Avatar asked Mar 06 '23 23:03

Immortal_Buka


2 Answers

To alias an external function, you can use objcopy. Here's an example:

Say I have the definition of a function and I alias it, like in the following program (called myimp.c):

// myimp.c
int
myadd(int x, int y)
{
    return x+y;
}

int
coolguy (int x, int y) __attribute__((alias("myadd")));

If we compile this (but don't link) we get an object file and we can check out its symbols:

# compile
$ cc -c myimp.c
# look at the symbols
$ nm myimp.o
0000000000000000 T coolguy
0000000000000000 T myadd

So we can see that the __attribute__((alias("myadd")) is simply adding a symbol coolguy with the same value, 0000000000000000, as myadd. If you look in the man page for nm, it will say that T means it is a global symbol in the .text section. This makes sense because the function is not static and comprises instructions (as opposed to data).

So if we have the object file, but not the source, and we want to add a function alias we can do so using objcopy --add-symbol.

Say we have the object file resulting from compiling this source code:

// myimp2.c
int
myadd(int x, int y)
{
    return x+y;
}

Compiling as above, we'll get myimp2.o, whose symbol table tools like this:

# look at the symbols
$ nm myimp2.o
0000000000000000 T myadd

So we want to add the coolguy symbol, which we do as follows

# objcopy --add-symbol coolguy=.text:0000000000000000,global myimp2.o myimp2_augmented.o

Look at the documentation on --add-symbol in the objcopy man page. Basically .text specifies the section, after the colon the value, and then global I found by passing a bad type and objcopy failed and told me a list of the valid types, from which I chose global.

Try running nm on myimp2_augmented.o, you'll see that we've added the symbol.

Now you should be able to link with myimp2_augmented.o instead of myimp.o and your program can call coolguy without linking errors.

like image 84
mondaugen Avatar answered Mar 10 '23 10:03

mondaugen


As suggested here, add the following to your linker command file:

PROVIDE(NMI_Handler = Default_Handler);

(And remove the weak alias declaration from the C code.)

like image 29
Jeremy Avatar answered Mar 10 '23 10:03

Jeremy