phil-opp / blog_os

Writing an OS in Rust
http://os.phil-opp.com
Apache License 2.0
15.58k stars 1.07k forks source link

Misaligned Pointer panic in the Paging Introduction post #1215

Closed PitchBlackNights closed 1 year ago

PitchBlackNights commented 1 year ago

I don't know if this is very important, but it's been driving me crazy trying to fix it.

I'm almost at the end of the Introduction to Paging. I'm at the test to see if reading and writing to the code segment address will cause a paging fault.

When I run the binary, it spits out:

panicked at 'misaligned pointer dereference: address must be a multiple of 0x4 but is 0x204f63', src\main.rs:18:22

Here is the code in question (I'm guessing that it's really complaining about line 16, which is the first line included in this snippet):

let ptr = 0x204f63 as *mut u32;

unsafe { let x = *ptr; }
println!("Read Worked");

unsafe { *ptr = 42; }
println!("Write Worked");

I've gotten this error on previous uses of 0xdeadbeaf as a virtual address, so I would always just swap those out for unnecessarily large addresses like 0x4444444444.

I did look to see if anyone else was having this error, and I did find one person.

TeeJaey commented 1 year ago

I would like to comment that I am also running into this issue.

I so far always swapped 0xdeadbeaf for 0xdeadbea0 since that is a multiple of 0x4.

While that works, I am worried I might run into bigger problems later down the line.

carloalbertogiordano commented 1 year ago

Hi, maybe the read_unaligned and the write_unaligned could be used in this case. I have not encountered this error so far. Here are some links: https://doc.rust-lang.org/std/ptr/fn.read_unaligned.html https://doc.rust-lang.org/std/ptr/fn.write_unaligned.html

PitchBlackNights commented 1 year ago

@carloalbertogiordano Thanks, but those can't be used as the os doesn't contain, or support, the std crate

bjorn3 commented 1 year ago

These functions are re-exports from libcore, which is supported. So you can write core::ptr::read_unaligned and core::ptr::write_unaligned.

PitchBlackNights commented 1 year ago

Okay, thanks @bjorn3 ! I haven't tried it, but I think it will work. I'll leave this open for now though, as it should be working without read/write_unaligned

cubed-guy commented 1 year ago

@bjorn3 Can confirm. core::ptr::write_unaligned does work. But, any idea as to why the standard syntax doesn't work anymore?

bjorn3 commented 1 year ago

Dereferencing unaligned pointers is UB. Previously if you were lucky the compiler wouldn't miscompile it, but to catch this UB, rustc recently added a compiler pass when debug assertions are enabled which adds code to check on every pointer dereference if the pointer is aligned or not and if not aborts. This helps finding this UB.

PitchBlackNights commented 1 year ago

Okay, so that's just how rustc compiles it now. Thanks!