Archive for the ‘C’ Category

GCC C __attribute__ feature

Most of compilers support optimization level in which each level has special significance to optimize the source in terms of size, performance etc. This can be enabled by specified command line arguments, mostly known as options.

Moreover GCC compiler has a special characteristic additionally – declaring attributes of a function. The source can be optimized at programming level. While writing the source, the programmer has a chance to instruct the compiler to what should be taken care.

__attribute__ keyword is used when a function (declared only) is a declared and the corresponding instruction/s is/are mentioned with it.  There are many ways to do nasty things with it found here.

In the embedded system, the code is nicely put together in different sections according to the design/requirements.  The code goes into the text section. It happens that while starting the OS, it is so better to gather the initialization code together that as soon as the initialization is over, the related code can be removed from the main memory.  This can be achieved by combining initialization code into init section i.e  __attribute__ section(“.init”). This is where my journey has started for attribute feature.

This function attibute has been widely used in L4 micro-kernel, which provides a secured approach for embedded systems facilitating the hardware manufactures to protect their patents/innovation without exposing to the outside world.

There are many things can be done using Linux and GCC pair, but today this is enough to start with.

C Function Calling conventions

  1. __cdecl
  • Standard/default calling convention in Unix/Win32
  • Caller should push and pop the arguments (right to left)
  • Variable number of argument functions such as printf, scanf can be used with because the callee cannot know the number of parameters
  • Freeing stack Instructions are inserted after every call of the function, so it increases the code size if many calls are made
  1. __stdcall/PASCAL
  • Microsoft Win32 supported
  • Arguments are pushed (left to right) by the called and stack is cleaned up by the callee
  • No variable number of argument functions are allowed
  • Conserve some code space (one time cleanup by callee)
  1. __fastcall
  • Microsoft Win32 supported
  • Registers are used for passing arguments
  • The registers are pushed to and popped from the stack (first two arguments are copied into the registers, the rest should resort to the stack by_stdcall fashion)
  • Bit overhead
  • Used for local functions within the module

Check out more detailed explanation