This commit is contained in:
Ciro Santilli
2016-07-30 09:38:06 +01:00
commit d45ceace5d
9 changed files with 318 additions and 0 deletions

33
host/Makefile Normal file
View File

@@ -0,0 +1,33 @@
OUT_EXT := .ko
OBJ_EXT := .o
RUN := hello
RUN_EXT := $(RUN)$(OUT_EXT)
obj-m += hello.o
ccflags-y := -Wno-declaration-after-statement -std=gnu99
.PHONY: clean ins log rm run my-ins
all: $(RUN_EXT) ins_rm_mod.out
hello.ko: hello.c
make -C /lib/modules/$(shell uname -r)/build M="$(PWD)" modules
clean:
make -C /lib/modules/$(shell uname -r)/build M="$(PWD)" clean
rm -f *.out
ins: all
sudo insmod '$(RUN_EXT)'
log:
dmesg
rm:
if lsmod | grep -Eq '^$(RUN) '; then sudo rmmod '$(RUN_EXT)'; fi
ins_rm_mod.out: ins_rm_mod.c
gcc -Wall -std=gnu99 -o '$@' '$<'
ins_rm_run: ins_rm_mod.out $(RUN_EXT)
sudo ./ins_rm_mod.out

34
host/README.md Normal file
View File

@@ -0,0 +1,34 @@
# Host
Simple things that can be demonstrated by inserting a module into the currently running host. Tested on Ubuntu 16.04.
1. [hello](hello.c)
1. [ins_rm_mod.c](ins_rm_mod.c)
## Rationale
This method easier to setup, but it is not recommended for development, as:
- it may break your system.
- you can't control which kernel version to use
Use VMs instead.
## Usage
We only use it for super simple examples.
Build, insert and remove a hello world module:
make ins
make rm
make log
The last lines of the log should contain:
init_module
cleanup_module
Insert and remove a module from a C program:
make ins_rm_run

13
host/hello.c Normal file
View File

@@ -0,0 +1,13 @@
#include <linux/module.h>
#include <linux/kernel.h>
int init_module(void)
{
printk(KERN_INFO "init_module\n");
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "cleanup_module\n");
}

36
host/ins_rm_mod.c Normal file
View File

@@ -0,0 +1,36 @@
/*
http://stackoverflow.com/questions/5947286/how-can-linux-kernel-modules-be-loaded-from-c-code/38606527#38606527
*/
#define _GNU_SOURCE
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#define init_module(mod, len, opts) syscall(__NR_init_module, mod, len, opts)
#define delete_module(name, flags) syscall(__NR_delete_module, name, flags)
int main(void) {
int fd = open("hello.ko", O_RDONLY);
struct stat st;
fstat(fd, &st);
size_t image_size = st.st_size;
void *image = malloc(image_size);
read(fd, image, image_size);
close(fd);
if (init_module(image, image_size, "") != 0) {
perror("init_module");
return EXIT_FAILURE;
}
free(image);
if (delete_module("hello", O_NONBLOCK) != 0) {
perror("delete_modul");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}