Function Index with GCC Address Assignment

I ran into something that I totally don't understand. There is a prototype function:

typedef void ( * TMain ) ( void ); 

and function variable:

 TMain myFunc = MyFunc; ... myFunc (); 

This works great, of course. Why not.

From the MAP file, I know that “MyFunc” is at location 0x20100. And now the funniest thing. After assigning "myFunc = MyFunc;" the variable "myFunc" does not contain the value 0x20100, but rather 0x20101!

My problem is that I need to call a function from which I know the address from the table. So I thought I could do it like this

 myFunc = ( TMain ) myTable [ 5 ]; // that would be 0x20100 myFunc (); // which produces a proper crash 

However if i do

 myFunc = ( TMain ) ( ( Int8 * ) myTable [ 5 ] + 1 ); myFunc (); 

then it works.

What's going on here? Should I always add offset 1 or is it more or less random? Or is there a better (and working) way to accomplish a task?

Thanks so much for any hint. Walter

+6
source share
2 answers

Several CPU architectures reserve the first bytes of a function for specific purposes. VAXen has a save register mask. CDC Cyber ​​places the return address there. Some use some bits of the “address” to indicate addressing (I cannot remember which ones, but they have been since the 1970s).

If you really do not know what you are doing, you should not write code that performs such pointer arithmetic. Assign the variable the name of the function and execute it: it is guaranteed that it will work with every C implementation.

+3
source

I assume you are on an ARM target and you created your program in Thumb mode? (Thumb is the default for ARM Ubuntu or Linaro.)

The lower bit of the function address indicates the CPU in which the command should interpret this function. 0 - ARM mode. 1 - Thumb mode. Thus, all the pointers of the Thumb-mode function will be odd.

Other architectures also use this idiom, one way or another. It is usually safe to simply omit the lower two bits of the address (making it aligned by 4 bytes) and assume that this is the true location of the function.

+3
source

Source: https://habr.com/ru/post/907377/


All Articles