Skip to content

Commit b8213a7

Browse files
authored
Merge pull request #174 from rust-osdev/nop
Add a function for the `nop` instruction
2 parents fe8d09c + 0b2bf80 commit b8213a7

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/asm/asm.s

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,12 @@ _x86_64_asm_hlt:
234234
hlt
235235
retq
236236

237+
.global _x86_64_asm_nop
238+
.p2align 4
239+
_x86_64_asm_nop:
240+
nop
241+
retq
242+
237243
.global _x86_64_asm_rdfsbase
238244
.p2align 4
239245
_x86_64_asm_rdfsbase:

src/asm/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ extern "C" {
3030
)]
3131
pub(crate) fn x86_64_asm_hlt();
3232

33+
#[cfg_attr(
34+
any(target_env = "gnu", target_env = "musl"),
35+
link_name = "_x86_64_asm_nop"
36+
)]
37+
pub(crate) fn x86_64_asm_nop();
38+
3339
#[cfg_attr(
3440
any(target_env = "gnu", target_env = "musl"),
3541
link_name = "_x86_64_asm_read_from_port_u8"

src/instructions/mod.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,25 @@ pub fn hlt() {
2323
}
2424
}
2525

26+
/// Executes the `nop` instructions, which performs no operation (i.e. does nothing).
27+
///
28+
/// This operation is useful to work around the LLVM bug that endless loops are illegally
29+
/// optimized away (see https://github.com/rust-lang/rust/issues/28728). By invoking this
30+
/// instruction (which is marked as volatile), the compiler should no longer optimize the
31+
/// endless loop away.
32+
#[inline]
33+
pub fn nop() {
34+
#[cfg(feature = "inline_asm")]
35+
unsafe {
36+
llvm_asm!("nop" :::: "volatile");
37+
}
38+
39+
#[cfg(not(feature = "inline_asm"))]
40+
unsafe {
41+
crate::asm::x86_64_asm_nop();
42+
}
43+
}
44+
2645
/// Emits a '[magic breakpoint](https://wiki.osdev.org/Bochs#Magic_Breakpoint)' instruction for the [Bochs](http://bochs.sourceforge.net/) CPU
2746
/// emulator. Make sure to set `magic_break: enabled=1` in your `.bochsrc` file.
2847
#[cfg(feature = "inline_asm")]

0 commit comments

Comments
 (0)