Skip to content
This repository has been archived by the owner on Mar 7, 2021. It is now read-only.

Commit

Permalink
Start hacking towards a test case
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Jun 20, 2019
1 parent a720a1a commit 4795eb3
Show file tree
Hide file tree
Showing 6 changed files with 170 additions and 1 deletion.
3 changes: 3 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ use std::process::Command;

const INCLUDED_TYPES: &[&str] = &["file_system_type", "mode_t", "umode_t", "ctl_table"];
const INCLUDED_FUNCTIONS: &[&str] = &[
"cdev_add",
"cdev_alloc",
"cdev_del",
"register_filesystem",
"unregister_filesystem",
"krealloc",
Expand Down
3 changes: 2 additions & 1 deletion src/bindings_helper.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/uaccess.h>

Expand Down
50 changes: 50 additions & 0 deletions src/chrdev.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use core::mem;
use core::ops::Range;

use crate::bindings;
Expand Down Expand Up @@ -33,6 +34,30 @@ impl DeviceNumberRegion {
}
return Ok(DeviceNumberRegion { dev, count });
}

pub fn register_device<T: FileOperations>(
&mut self,
) -> error::KernelResult<DeviceRegistration> {
let cdev = unsafe { bindings::cdev_alloc() };
if cdev.is_null() {
return Err(error::Error::ENOMEM);
}
unsafe {
(*cdev).owner = &mut bindings::__this_module;
(*cdev).ops = &T::VTABLE.0 as *const bindings::file_operations;
}
let cdev = DeviceRegistration {
cdev,
_registration: self,
};
// TODO: Need to handle multiple register_device calls by going through the devs and
// erroring if we run out.
let rc = unsafe { bindings::cdev_add(cdev.cdev, self.dev, 1) };
if rc != 0 {
return Err(error::Error::from_kernel_errno(rc));
}
return Ok(cdev);
}
}

impl Drop for DeviceNumberRegion {
Expand All @@ -42,3 +67,28 @@ impl Drop for DeviceNumberRegion {
}
}
}

pub struct DeviceRegistration<'a> {
_registration: &'a DeviceNumberRegion,
cdev: *mut bindings::cdev,
}

impl Drop for DeviceRegistration<'_> {
fn drop(&mut self) {
unsafe {
bindings::cdev_del(self.cdev);
}
}
}

pub struct FileOperationsVtable(bindings::file_operations);

impl FileOperationsVtable {
fn new<T: FileOperations>() -> FileOperationsVtable {
return FileOperationsVtable(unsafe { mem::zeroed() });
}
}

pub trait FileOperations {
const VTABLE: FileOperationsVtable;
}
11 changes: 11 additions & 0 deletions tests/chrdev/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "chrdev-tests"
version = "0.1.0"
authors = ["Alex Gaynor <[email protected]>", "Geoffrey Thomas <[email protected]>"]
edition = "2018"

[lib]
crate-type = ["staticlib"]

[dependencies]
linux-kernel-module = { path = "../.." }
45 changes: 45 additions & 0 deletions tests/chrdev/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#![no_std]
#![feature(const_str_as_bytes)]

use linux_kernel_module;

struct CycleFile;

impl linux_kernel_module::chrdev::FileOperations for CycleFile {
const VTABLE: linux_kernel_module::chrdev::FileOperationsVtable =
linux_kernel_module::chrdev::FileOperationsVtable::new::<Self>();

fn read(
&mut self,
buf: &linux_kernel_module::user_ptr::UserSlicePtrWriter,
) -> linux_kernel_module::KernelResult<()> {
for c in b"123456789".iter().cycle().take(buf.len()) {
buf.write(c)?;
}
return Ok(());
}
}

struct ChrdevTestModule {
_dev_region: linux_kernel_module::chrdev::DeviceNumberRegion,
_chrdev_registration: linux_kernel_module::chrdev::DeviceRegistration<CycleFile>,
}

impl linux_kernel_module::KernelModule for ChrdevTestModule {
fn init() -> linux_kernel_module::KernelResult<Self> {
let dev_region =
linux_kernel_module::chrdev::DeviceNumberRegion::allocate(0..1, "chrdev-tests\x00")?;
let chrdev_registration = dev_region.register_device::<CycleFile>()?;
Ok(ChrdevTestModule {
_dev_region: dev_region,
_chrdev_registration: chrdev_registration,
})
}
}

linux_kernel_module::kernel_module!(
ChrdevTestModule,
author: "Alex Gaynor and Geoffrey Thomas",
description: "A module for testing character devices",
license: "GPL"
);
59 changes: 59 additions & 0 deletions tests/chrdev/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use kernel_module_tests::with_kernel_module;
use std::fs;

fn get_device_number() -> u32 {
let devices = fs::read_to_string("/proc/devices").unwrap();
let dev_no_line = devices
.lines()
.find(|l| l.ends_with("chrdev-tests"))
.unwrap();
let elements = dev_no_line.rsplitn(2, " ").collect::<Vec<_>>();
assert_eq!(elements.len(), 2);
assert_eq!(elements[0], "chrdev-tests");
return elements[1].trim().parse().unwrap();
}

fn temporary_file_path() -> PathBuf {
let p = env::temp_dir();
p.push("chrdev-test-device");
return p
}

struct<'a> UnlinkOnDelete<'a> {
path: &'a Path,
}

impl Drop for UnlinkOnDrop {
fn drop(&mut self) {
fs::remove_file(self.path);
}
}

fn mknod(path: &Path, mode: u32, device_number: u32) -> UnlinkOnDrop {
let result = libc::mknod(CString::new(p).unwrap(), mode, device_number);
assert_eq(result, 0);
return UnlinkOnDrop{path};
}

#[test]
fn test_mknod() {
with_kernel_module(|| {
let device_number = get_device_number();
let _u = mknod(temporary_file_path(), 0o600, device_number);
});
}

#[test]
fn test_read() {
with_kernel_module(|| {
let device_number = get_device_number();
let p = temporary_file_path()
let _u = mknod(temporary_file_path(), 0o600, device_number);

let f = fs::File::open(p);
let data = vec![0; 12];
f.read_exact(&mut data).unwrap();
assert_eq(data, "123456789123")
});

}

0 comments on commit 4795eb3

Please sign in to comment.