4 ms·
Part of the code is: unsafe { std::ptr::write(stack_ptr.offset(SSIZE - 16) as *mut u64, hello as u64); ctx.rsp = stack_ptr.offset(SSIZE - 1
by amluto 7y ago
Part of the code is:
unsafe {
std::ptr::write(stack_ptr.offset(SSIZE - 16) as *mut u64, hello as u64);
ctx.rsp = stack_ptr.offset(SSIZE - 16) as u64;
gt_switch(&mut ctx, &mut n);
}
Only the last line should be unsafe — the first line appears to be writing in bounds to a Vec, which is easy (and much more readable) in safe Rust.
Linux used to do its actual context switch in C with inline asm, and it changed to being in straight asm a while back. This was absolutely a win. Rather than trying to make everything work out behind the compiler’s back, it’s much more straightforward to write a function in asm that does the stack switch.
- gravitas 7y agoFantastic (IMHO) read on the last paragraph's history and code movement: https://www.maizure.org/projects/evolution_x86_context_switch_linux/ https://www.maizure.org/projects/evolution_x86_context_switc...
- oconnor663 7y agoThe ptr::write is needed because the stack vector contains bytes and the code wants to do a pointer cast and write a u64. It could be done in safe Rust with u64::to_ne_bytes and a copy_from_slice or something like that, but since all of this code is extravagantly unsafe anyway, I think it's reasonably clear to Just Do It :)
- paines 7y ago>Linux used to do its actual context switch in C with inline asm, and it changed to being in straight asm a while back. Could you be a bit more specific, maybe a link to the diff e.g. THANKS!