how to malloc a struct in system call - linux

struct test{
/*...*/
}
asmlinkage syscall(){
struct test *t;
t = (struct test *)malloc(sizeof(struct test));
//...
}
During I compiled whole kernel the follow error showing.
implicit declaration of function 'malloc'
Seems I can't include stdlib.h, but if I don't use malloc, the t pointer will be NULL.
That cause unable to handle kernel NULL pointer dereference at (null)
How to assign a pointer to t?

this assign a pointer to pointer type
struct test *t;
use follow code
struct test t;
done

Related

Rust ffi pointer does not panic when out of bounds

For some reason, when I run the code below, it does not panic or throw any errors...?
Isn't this a seg fault?
Why is this happening? How do I check the size of the passed pointer to avoid panics? (without the user having to pass a "size" variable as well)
#[repr(C)]
pub struct MyStruct {
pub item: u32
// a bunch of other fields as well
}
#[no_mangle]
pub unsafe extern fn do_something(mut data: *mut MyStruct) {
println!("{:p}", data);
data= data.offset(100);
println!("{:p}", data);
println!("{}", (*data).item);
if data.is_null() {
println!("datais null");
}
}
After I build, (and generate header using cbindgen) I link and use in a sample program like so:
#include "my_bindings.h"
int main() {
MyStruct *data = new MyStruct[2];
do_something(data);
return 0;
}
This is the output I get:
0x55f0ba739eb0
0x55f0ba73a108
0
An out of bounds access is not necessarily a segmentation fault, it's just an unidentified behaviour, the data that's out of bounds may still be a part of your application so the OS won't kill your application.
Unfortunately this is unsafe code, so rust can't do anything about it, and you should wrap it in a safer rust container along with the container length (you must pass the length), that panic on out of bounds access, as in the following answer Creating a Vec in Rust from a C array pointer and safely freeing it?

kthread_work and kthread_worker functionality

I need to use the kthread functions for a work processor and the distinction between the two is not very clear to me. This is my understanding of the fields.
struct kthread_worker {
spinlock_t lock; // lock to update the work queue
struct list_head work_list; // list kthread_work items
struct task_struct *task; // handle for thread
struct kthread_work *current_work; // ?
};
struct kthread_work {
struct list_head node; // list of threads?
kthread_work_func_t func; // func to execute?
struct kthread_worker *worker; // worker associated with this work item
};
My questions are:
Any clarification on the unclear fields.
kthread_work_func_t is a func ptr expecting an argument of kthread_work. How does that work? It should point to the function you want the thread to execute, right?
kthread_worker is a worker, which can execute works (kthread_work). Work can be added to worker at any time. Worker executes works one by one. If no work is currently available, worker waits.
kthread_work_func_t is a func ptr expecting an argument of kthread_work. How does that work? It should point to the function you want the thread to execute, right?
Yes, it is just function you want to execute as work.
If only one work uses this function(e.g., this is some sort of garbage collector), function may simply ignore its argument.
If you want to have several works, which uses same functionality but with different parameters, you may embed kthread_work structure into your structure, which contain these parameters:
struct my_work
{
struct kthread_work work; //Base work object
int i; // Your parameter
}
// Parametrized work function
void my_func(struct kthread_work* work)
{
// Extract actual work object
struct my_work* my_work = container_of(work, struct my_work, work);
// Parameter for the work
int i = my_work->i;
// Do something
...
// Free memory used for work object
kfree(my_work);
}
// Helper for add your work with given parameter
void add_my_work(struct kthread_worker* worker, int i)
{
// Allocate your work object on the heap
struct my_work* my_work = kmalloc(sizeof(struct my_work), GFP_KERNEL);
// Initialize base work structure
init_kthread_work(&my_work->work, &my_func);
// Store parameter
work->i = i;
queue_kthread_work(worker, &my_work->work);
}
Any clarification on the unclear fields.
As you can see from previous example, knowing fields of struct kthread_worker and struct kthread_work is rarely useful for just using it. But actually semantic is simple:
struct kthread_worker {
spinlock_t lock; // lock to update the work queue
struct list_head work_list; // list kthread_work items
struct task_struct *task; // handle for thread
struct kthread_work *current_work; // (+) currently executed work object
};
struct kthread_work {
struct list_head node; // (+) element in the kthread_worker.work_list
kthread_work_func_t func; // func to execute
struct kthread_worker *worker; // worker associated with this work item
};

GraphicsMagick FFI issue

As an exercise, I'm attempting to write a GraphicsMagick FFI wrapper in Rust. I'm having an issue replicating some reference C code:
Demo C code:
Image
*image = (Image *) NULL;
ImageInfo
*imageInfo;
ExceptionInfo
exception;
InitializeMagick(NULL);
imageInfo=CloneImageInfo(0);
GetExceptionInfo(&exception);
And here is my (naive) translation to Rust:
let img: *mut ffi::Image;
let img_info: *mut ffi::ImageInfo;
let exception: *mut ffi::ExceptionInfo = ptr::null_mut();
unsafe {
ffi::InitializeMagick(ptr::null_mut());
img_info =
ffi::CloneImageInfo(ptr::null_mut() as *const ffi::ImageInfo);
ffi::GetExceptionInfo(exception);
// ...
}
This compiles just fine, but when I try to run it, I see:
magick/error.c:388: GetExceptionInfo: Assertion `exception != (ExceptionInfo *) ((void *)0)' failed
which is caused by ffi::GetExceptionInfo(exception). The only difference seems to be that the C exception isn't "initialized", but I don't know enough about C to know if there is a difference between a null and an empty/uninitialized pointer.
The difference between your C and Rust code is that the C version allocates an ExceptionInfo instance on the stack and passes into the GetExceptionInfo a pointer referencing that instance.
Your Rust code, on the other hand, passes a NULL pointer.
GetExceptionInfo specifically guards against being passed a NULL pointer, you can see the assertion's code here, in magick/error.c.
I don't know what kind of FFI bindings you use, but if the ExceptionInfo is fully defined in them then you should be able to allocate it on the stack and pass a reference to it just like in the C version:
let mut exception: ffi::ExceptionInfo = unsafe {std::mem::uninitialized()};
unsafe {ffi::GetExceptionInfo (&mut exception);}
The error message states (rewritten a bit):
Assertion exception != NULL failed
That is, you cannot pass NULL to that method. Note the C code:
ExceptionInfo exception;
This is not a pointer. You need to allocate space for it and then pass in a reference to the allocated space.
The documentation shows the definition:
typedef struct _ExceptionInfo
{
char
*reason,
*description;
ExceptionType
severity;
unsigned long
signature;
} ExceptionInfo;
You will need to represent this in Rust. Something like this untested code:
extern crate libc;
#[repr(C)]
struct ExceptionInfo {
reason: *const libc::c_char,
description: *const libc::c_char,
severity: ExceptionType,
signature: libc::c_ulong,
}
#[repr(C)]
enum ExceptionType {
UndefinedException,
WarningException = 300,
// the rest
}
Then you need to allocate it and pass a reference. More untested code:
let img_info;
let mut exception = ffi::ExceptionInfo::new();
unsafe {
ffi::InitializeMagick(ptr::null_mut());
img_info =
ffi::CloneImageInfo(ptr::null_mut() as *const ffi::ImageInfo);
ffi::GetExceptionInfo(&mut exception);
// ...
}
Note that Rust style is 4 space indents.

Kernel module, multiple high resolution timers

I want to implement multiple hrtimers, but I'm not sure how to use all of them with same callback function. For example I have array of type my_struct where one of the field is a struct hrtimer.
When I enter the callback function how to determine which element of the array is calling it?
Use the container_of macro:
struct my_struct {
int my_something;
struct hrtimer my_timer;
...
};
enum hrtimer_restart my_callback(struct hrtimer *hrtimer)
{
struct my_struct my = container_of(hrtimer, struct my_struct, my_timer);
my->my_something = 42;
...
}

Is it possible to find the corresponding task_struct from sched_entity?

I know if we have task_struct, surly we can get the contained sched_entity because it's one field in the task struct. But can we get the pointer to the task_struct given the shed_entity? Following is the sched_entity structure:
struct sched_entity {
struct load_weight load; /* for load-balancing */
struct rb_node run_node;
struct list_head group_node;
unsigned int on_rq;
u64 exec_start;
u64 sum_exec_runtime;
u64 vruntime;
u64 prev_sum_exec_runtime;
u64 nr_migrations;
#ifdef CONFIG_SCHEDSTATS
struct sched_statistics statistics;
#endif
#ifdef CONFIG_FAIR_GROUP_SCHED
struct sched_entity *parent;
/* rq on which this entity is (to be) queued: */
struct cfs_rq *cfs_rq;
/* rq "owned" by this entity/group: */
struct cfs_rq *my_q;
#endif
};
It seems that there is no place where I can get the task_struct. My final goal is to get the sched_entity of the task group_leader containing the task with this shed_entity :>
The Linux kernel code provides a standard way to take a pointer to an element contained within a structure, and get back a pointer to the containing structure: the container_of macro, which is used extensively throughout the kernel.
In this case, if you have a struct sched_entity *foo, you can get the enclosing task_struct with:
struct task_struct *task = container_of(foo, struct task_struct, se);
(Obviously this is only safe if you know for sure that the original struct sched_entity * pointer is pointing to a struct sched_entity which is inside a struct task_struct, so be careful...)

Resources