How to compile glibc for use without an operating system
I would like to compile the functions of glibc to an ob开发者_如何学运维ject file which will then be linked to a program which I am running on a computer without any operating system. Some functions, such as open
, I want to just fail with ENOSYS
. Other functions I will write myself, such as putchar
, and then have glibc use those functions in it's own (like printf
). I also want to use functions that don't need a file system or process management system or anything like that, such as strlen
. How can I do this?
Most C libraries rely on the kernel heavily, so it's not reasonable to port 'em. But since most of it doesn't need to be implemented, you can get away easily with a few prototypes for stubs and gcc builtins.
You can implement stubs easily using weak symbols:
#define STUB __attribute__((weak, alias("__stub"))) int
#define STUB_PTR __attribute__((weak, alias("__stub0"))) void *
int __stub();
void *__stub0();
Then defining the prototypes becomes trivial:
STUB read(int, void*, int);
STUB printf(const char *, ...);
STUB_PTR mmap(void*, int, int, int, int, int);
And the actual functions could be:
int __stub()
{
errno = ENOSYS;
return -1;
}
void *__stub0()
{
errno = ENOSYS;
return NULL;
}
If you need some non-trivial function, like printf
, take it from uClibc instead of glibc (or some other smaller implementation).
精彩评论