Search code examples
assemblyx86dosx86-16fasm

Simple FASM "Hello world!" crashes on DOS interrupt


In my high-school homework I have to write a program, that uses DOS Interrupts to input and output strings instead of std printf/scanf But when I attempting to run this program:

format ELF
use16
section '.data' writeable
    msg db 'Hello, world!', 0


section '.text' executable
public _main
_main:
   mov ebp, esp; for correct debugging
   mov   ah, 1
   int   21h 
   mov  ah,4Ch
   int   21h
   xor eax, eax
ret

It's just crashing. I attached debugger and found out that it crashes on this line: int 21h. I absolutely have no ideas about why it happens.
I use FASM, SASM IDE and Windows XP SP3 x32


Solution

  • When using SASM IDE and you use format ELFin your assembly code, FASM will assemble the file to an ELF object (.o file) and then use (by default) a MinGW version of GCC and LD to link that ELF object to a Windows executable (PE32). These executables run as native Windows programs, not DOS. You can not use DOS interrupts inside a Windows PE32 executable since the DOS interrupts do not exist in that environment. The end result is that it crashes on the int 21h.

    If you want to create a DOS executable that can run in 32-bit Windows XP you could do this:

    format MZ                   ; DOS executable format
    stack 100h
    
    entry code:main             ; Entry point is label main in code segment
    
    segment text
    msg db 'Hello, world!$'     ; DOS needs $ terminated string
    
    segment code
    main:
        mov   ax, text
        mov   ds, ax            ; set up the DS register and point it at
                                ; text segment containing our data
        mov   dx, msg
        mov   ah, 9
        int   21h               ; Write msg to standard output
    
        mov   ah, 4Ch
        int   21h               ; Exit DOS program
    

    This will generate a DOS program with an exe extension. Unfortunately you can not use SASM IDE to debug or run a DOS program. you can run the generated program from the 32-bit Windows XP command line. 32-bit versions of Windows run DOS programs inside the NTVDM (virtual DOS machine).