Memo: How to build OpenBSD from source code and add system call on QEMU

Introduction

Memorandum for myself. I just follow these three articles. Thanks dude.


Prolly This's the easiest way to try kernel hack.

I tried with OpenBSD 5.6

How to install OpenBSD on QEMU

#    on host
$ cd work
$ qemu-img create -f qcow2 ./obsd56.qcow2 20G
$ wget http://ftp5.usa.openbsd.org/pub/OpenBSD/5.6/i386/install56.iso
$ qemu-system-i386 -m 256M -net nic -net user -cdrom ./install56.iso ./obsd56.qcow2
#    install OpenBSD on QEMU
#    Then quit qemu once with the following commands
#    $ Ctrl-Alt-2
#    (qemu) quit

How to boot OpenBSD on QEMU

$ qemu-system-i386 -m 256M -net nic -net user ./obsd56.qcow2
#    boot OpenBSD on QEMU

How to get OpenBSD source code via ftp

#    on QEMU
$ cd /tmp
$ ftp ftp://ftp5.usa.openbsd.org/pub/OpenBSD/5.6/sys.tar.gz
$ cd /usr/src
$ tar xzf /tmp/sys.tar.gz

How to add a new system call

#    on QEMU
$ cd /usr/src/sys/kern
$ vi syscalls.master
#   modify "260" to the following line
#   260 STD { int sys_hello(void); }
$ make init_sysent.c
$ vi sys_hello.c
#   edit sys_hello.c as written below
$ cd ../conf
$ vi files
#   add the following line
#   file kern/sys_hello.c
/* /usr/src/sys/kern/sys_hello.c */
#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/proc.h>
#include <sys/mount.h>
#include <sys/syscallargs.h>

int sys_hello(struct proc *p,
              void        *v,
              register_t  *retval) {
    printf("Hello World\n");
    return (0);
}

How to build OpenBSD from source code for debug

#    on QEMU
$ cd /usr/src/sys/arch/i386/conf
$ cp GENERIC DEBUG
$ vi DEBUG
#   add the following line
#   makeoptions DEBUG="-g"
$ config DEBUG
$ cd ../compile/DEBUG
$ make depend
$ COPTS="-O0" make
$ make install
$ reboot

make user program using the new system call

#    on QEMU
$ cd /tmp
$ vi main.c
#   edit main.c as written below
$ gcc main.c
$ ./a.out
Hello World
/* /tmp/main.c */
int main(int argc, char **argv) {
  syscall(260);
}

Etc. How to get OpenBSD source code via CVS

$ cd work
$ export CVSROOT=anoncvs@anoncvs1.usa.openbsd.org:/cvs
$ cvs -d$CVSROOT checkout -rOPENBSD_5_6 -P src