How to Write a KMOD

How to write a kmod module

This is a re-post, because I deleted this article by accident.

Writing a KMDB module is slightly different from writing a MDB one, especially in building the binary file, now I'm trying to illustrate the difference between them. Here's a simple kmod that contains only one dcmd:

$ cat simple_trace.c
#include <sys/mdb_modapi.h>

static int
simple_trace(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t \*argv)
{
        /\* do nothing \*/
        mdb_printf("Hello KMDB");
        return DCMD_OK;
}

static const mdb_dcmd_t dcmds[] = {
        {"simple_trace", "wait...", "Hello world", simple_trace },
        { NULL }
};

static const mdb_modinfo_t modinfo = {
        MDB_API_VERSION, dcmds, NULL
};

const mdb_modinfo_t \*
_mdb_init(void)
{
        return &modinfo;
}

When running this dcmd, it does nothing but print "Hello KMDB" on the console, but this is a good start point to write a real kmod.

As you can see, the source code looks no difference from a MDB module, but the Makefile is different:

$ cat Makefile
OBJS = simple_trace.o
KMODULE = simple_trace

CFLAGS +=  -D_KERNEL -D_KMDB

CC=cc
LD=ld

all: $(OBJS)
        $(LD) -dy -r -Nmisc/kmdbmod -o $(KMODULE) $(OBJS)

.KEEP_STATE:

%.o: %.c
        $(CC) $(CFLAGS) -c $<

clean:
        rm -f $(OBJS)

It modifies the .dynamic section of the binary file, and make it loadable to KMDB. You can now load this module into KMDB:

# mdb -K

Welcome to kmdb
Loaded modules: [ crypto ptm ufs unix krtld sppp nca uhci lofs genunix ip
logindmux usba specfs nfs random sctp ]
[1]> ::load /tmp/simple_trace
Loaded modules: [ simple_trace ]
[0]> ::simple_trace
Hello KMDB
[0]>

and check what ld did to the binary file:

$ elfdump simple_trace
......
Dynamic Section:  .dynamic
     index  tag            value
       [0]  NEEDED         0x1             misc/kmdbmod
       [1]  FLAGS          0x4             [ TEXTREL ]
       [2]  FLAGS_1        0               0
Technorati Tag:
Technorati Tag:
Technorati Tag:
评论:

发表一条评论:
  • HTML语法: 禁用
About

yu

Search

Categories
Archives
« 四月 2014
星期日星期一星期二星期三星期四星期五星期六
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
今天