Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace C standard library function ?

Tags:

c

How can we replace a C standard library function with our own implementation of that function ?

For example, how can I replace strcpy() with my own implementation of strcpy() and have all calls link to the new implementations instead?

like image 538
Gary Gauh Avatar asked Feb 02 '12 04:02

Gary Gauh


People also ask

What happens if standard library is not present in C?

But in pure C, with no extensions, and the standard library functions removed, you basically can't do anything other than read the command line arguments, do some work, and return a status code from main .

Is there a standard library for C?

The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it.

Why we Cannot use C standard library function in kernel module?

If you need to use functions from standard library, you have to re-implement that functionality because of a simple reason - there is no standard C library. C library is basically implemented on the top of the Linux kernel (or other operating system's kernel).

Which function is known as standard library function?

C Standard library functions or simply C Library functions are inbuilt functions in C programming. The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program.


1 Answers

At least with GCC and glibc, the symbols for the standard C functions are weak and thus you can override them. For example,

strcpy.c:

#include <string.h>
#include <stdio.h>

char * strcpy(char *dst, const char *src)
{
  char *d = dst;
  while (*src) {
    *d = *src;
    d++;
    src++;
  }
  printf("Called my strcpy()\n");

  return (dst);
}

int main(void)
{
  char foo[10];
  strcpy(foo, "hello");

  puts(foo);

  return 0;
}

And build it like this:

gcc -fno-builtin -o strcpy strcpy.c

and then:

$ ./strcpy 
Called my strcpy()
hello

Note the importance of -fno-builtin here. If you don't use this, GCC will replace the strcpy() call to a builtin function, of which GCC has a number.

I'm not sure if this works with other compilers/platforms.

like image 137
FatalError Avatar answered Nov 04 '22 07:11

FatalError