Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the weak_alias function do and where is it defined

Tags:

So I'm looking through the source of gcc compiler and I've come along this in fork.c:

int
__fork ()
{
  __set_errno (ENOSYS);
  return -1;
}
libc_hidden_def (__fork)
stub_warning (fork)

weak_alias (__fork, fork)
#include <stub-tag.h>

I'm trying to figure out what weak_alias does. I've used the grep command inside the glibc source files to find all occurrences of #define weak_alias:

grep -r "#define weak_alias"

I've found many occurrences of the macro:

#define weak_alias(n, a)

but the macros don't actually explain anything. They just define that statement they don't show how its being replaced. For example one occurrence is in profil.c:

/* Turn off the attempt to generate ld aliasing records. */
#undef weak_alias
#define weak_alias(a,b)

So any ideas what weak_alias does and where it is being defined?

Thanks in advance

like image 661
Programmer123 Avatar asked Jan 20 '16 06:01

Programmer123


People also ask

What is Weak_alias?

Default Handlers in C: weak_alias function tells the linker that new is to be a weak alias for old . That is, this definition of new is a weak symbol. If there is no other definition of a symbol called new , this old definition stands. Might seems alien to you first, so go through a below example & read again.

What are strong and weak symbols in C?

c , we define a strong symbol gvar and it is initialized to 5. In main. c , we only define the variable gvar , and it is a weak symbol. When we compile the program using GCC, the gvar in main.

What is weak attribute in C?

The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.


2 Answers

from https://github.com/lattera/glibc/blob/master/include/libc-symbols.h

/* Define ALIASNAME as a weak alias for NAME.
   If weak aliases are not available, this defines a strong alias.  */
# define weak_alias(name, aliasname) _weak_alias (name, aliasname)
# define _weak_alias(name, aliasname) \
  extern __typeof (name) aliasname __attribute__ ((weak, alias (#name)));

About weak symbol:

https://en.wikipedia.org/wiki/Weak_symbol

like image 146
Sam Liao Avatar answered Sep 20 '22 12:09

Sam Liao


It is a macro that does the following:

It declares a weak function, if you didnt provide a strong symbol name for that function it will call the function you have laised it to. for example

int _foo(){ return 1;}

//And weak alias
int __attribute__((weak, alias("_foo"))) foo();

So if you haven't provided actual implementation for foo it will basically use _foo and return 1.

like image 29
Anton Stafeyev Avatar answered Sep 24 '22 12:09

Anton Stafeyev