phil-opp / blog_os

Writing an OS in Rust

Home Page:http://os.phil-opp.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Misaligned Pointer panic in the Paging Introduction post

PitchBlackNights opened this issue · comments

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.

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.

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

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

commented

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

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

commented

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

commented

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.

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