Minimal Init

Here is a minimal init program that runs after the kernel boot.  Well, it does nothing except printing a hello world statement.  The system kernel panics once the program finishes.

螢幕快照 2018-02-16 上午2.44.28

The program working principle is to first mount the device file system, with the nmount(2) system call.  Then, print to the “/dev/console” and quit.  Before the program runs, in order for the system to boot, you will need to prepare the boot sector (like before), and the appropriate “/boot” directory (just copy from the system you have on hand).  Other than this, you also need an empty “/dev” for mounting the device file system, and the compiled code at “/sbin/init”.  The latter has to be compiled in statically without linked library.

It will be a good starting point if you like the FreeBSD monolithic kernel but not the user space.  Or you want to build a special appliance, like a giant virtual machine?  Hmm…

The code currently does not have function to start programs, nor the function to configure the network ports.  This may be explained later if time allows.

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/uio.h>
#include <sys/param.h>
#include <sys/mount.h>

void setup_devfs(void);
void setup_console(void);

main(int argc, char** argv)
  printf("\nhello world!\n");

  struct iovec iov[4];
  iov[0].iov_base = "fstype";
  iov[0].iov_len = 7;
  iov[1].iov_base = "devfs";
  iov[1].iov_len = 6;
  iov[2].iov_base = "fspath";
  iov[2].iov_len = 7;
  iov[3].iov_base = "/dev";
  iov[3].iov_len = 5;
  nmount(iov, 4, 0);

  int fd;
  fd = open("/dev/console", O_RDWR | O_NONBLOCK);
  dup2(fd, 0);
  dup2(fd, 1);
  dup2(fd, 2);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s