Created
November 10, 2018 01:29
-
-
Save twitchyliquid64/892e36982814fef5323f13c4e06bb9e1 to your computer and use it in GitHub Desktop.
My first kernel module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <linux/init.h> | |
#include <linux/module.h> | |
#include <linux/fs.h> | |
#include <linux/uaccess.h> | |
static ssize_t dev_read(struct file *fptr, char __user *buff, size_t count, loff_t *position); | |
static struct file_operations fops = { | |
.owner = THIS_MODULE, | |
.read = dev_read, | |
}; | |
static int dev_major = 0; | |
static char* dev_name = "crap"; | |
static int init(void) | |
{ | |
int major = register_chrdev (0, dev_name, &fops); | |
if (major < 0) | |
return -ENOSYS; | |
printk( KERN_NOTICE "Got dynamically allocated major number %i", major ); | |
dev_major = major; | |
return 0; | |
} | |
static void exit(void) | |
{ | |
if (dev_major != 0) { | |
printk( KERN_NOTICE "Releasing dynamically allocated major number %i", dev_major ); | |
unregister_chrdev(dev_major, dev_name); | |
} | |
return; | |
} | |
static char* msg = "ABSOLUTE UNIT\n"; | |
static int msg_size = sizeof("ABSOLUTE UNIT\n")-1; | |
static ssize_t dev_read(struct file *fptr, char __user *buff, size_t count, loff_t *position) { | |
printk( KERN_NOTICE "Got read for size %i at offset %i", count, *position ); | |
if (*position >= msg_size) | |
return 0; //Nothing left to read. | |
int remaining = msg_size - *position; | |
if (remaining <= count) { | |
if(copy_to_user(buff, msg + *position, remaining) != 0) | |
return -EFAULT; | |
*position += remaining; | |
return remaining; | |
} | |
// Must not fit into buffer. | |
if(copy_to_user(buff, msg + *position, count) != 0) | |
return -EFAULT; | |
*position += count; | |
return count; | |
} | |
MODULE_LICENSE("GPL"); | |
module_init(init); | |
module_exit(exit); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
obj-m := crapmod.o | |
module_name-objs := crapmod.o | |
all: | |
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules | |
clean: | |
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean | |
load: all | |
sudo insmod ./crapmod.ko | |
unload: | |
sudo rmmod crapmod |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment