How to shutdown the machine? I'm building a tiny OS of my own

3.3k views Asked by At

Can the hlt instruction in assembly shutdown a computer it as it halts the processor? if it can be done using what i have told, is it the right way?

Can hlt shutdown the machine?

start:
    xor ax, ax; ;clear ax
    mov bx, ax; ;clear bx
    cli ;stop all interrupts
    hlt ;halt the cpu

If this is not the way to be done of if this will not shutdown the system please tell me the right way to do it.

3

There are 3 answers

2
wallyk On BEST ANSWER

The hlt instruction stops the x86 until an interrupt occurs. Unless all interrupts are disabled, that will stop the processor for only a millisecond or so.

To power down a modern computer, use the ACPI (Advanced Configuration and Power Interface).

3
alvin On

halt instruction does not turn off the power. it puts the processor into a non-executing state.
usually, you can come out of the halt state upon processor reset.
in some microcontrollers, specific interrupts can also bring the processor out of the halt state. power off is a motherboard/bios specific operation.

3
hutheano On

By using these two lines of code:

    cli                     ; stop all interrupts
    hlt                     ; halt the cpu

you could halt a bootable program for x86 pc:

    BITS 16

start:
    mov ax, 07C0h           ; Set up 4K stack space after this bootloader
    add ax, 288             ; (4096 + 512) / 16 bytes per paragraph
    mov ss, ax
    mov sp, 4096

    mov ax, 07C0h           ; Set data segment to where we're loaded
    mov ds, ax


    cld                     ; clear direction flag
    mov si, text_string     ; Put string position into SI
    call print_string       ; Call our string-printing routine


    cli                     ; stop all interrupts
    hlt                     ; halt the cpu

    jmp $                   ; Jump here - infinite loop!


    text_string db 'Hello World!', 0


print_string:               ; Routine: output string in SI to screen
    mov ah, 0Eh             ; int 10h 'print char' function

.repeat:
    lodsb                   ; Get character from string
    cmp al, 0
        je .done            ; If char is zero, end of string
    int 10h                 ; Otherwise, print it
    jmp .repeat

.done:
    ret


    times 510-($-$$) db 0   ; Pad remainder of boot sector with 0s
    dw 0xAA55               ; The standard PC boot signature

Save it as "prog.asm", then use "nasm" to create boot sector:

nasm -f bin -o boot.img prog.asm

Now you could use "qemu" to test it:

qemu-system-i386 -drive file=boot.img,index=0,media=disk,format=raw -boot c -net none

Note: Removing those two lines mentioned above, causes your virtual machine to use maximum cpu cycles available.

Edit: Added "cld" instruction. As mentioned by Michael, it was necessary to make sure text_string is loaded from left-to-right.