Skip to content

Comment on x86 assembly doesn’t have to be scary (2018)parent

Comments

You don't have to: Windows programming using NASM is easy:)

  ; To build:
  ;   nasm -fobj hello.asm
  ;   alink -oPE -subsys con hello -entry main

  bits 32

  import imp_CreateFileW      kernel32.dll    CreateFileW
  import imp_WriteConsoleW    kernel32.dll    WriteConsoleW
  import imp_CloseHandle      kernel32.dll    CloseHandle
  import imp_ExitProcess      kernel32.dll    ExitProcess
  import imp_GetLastError     kernel32.dll    GetLastError

  extern imp_CreateFileW
  extern imp_WriteConsoleW
  extern imp_CloseHandle
  extern imp_ExitProcess
  extern imp_GetLastError

  %define CreateFile      [imp_CreateFileW]
  %define WriteConsole    [imp_WriteConsoleW]
  %define CloseHandle     [imp_CloseHandle]
  %define ExitProcess     [imp_ExitProcess]
  %define GetLastError    [imp_GetLastError]

  global main

  section .text use32
    
  main:

    push dword 0 ; hTemplateFile = 0
    push dword 0 ; dwFlagsAndAttributes = 0
    push dword 3 ; dwCreationDisposition = OPEN_EXISTING
    push dword 0 ; lpSecurityAttributes = NULL
    push dword 2 ; dwShareMode = FILE_SHARE_WRITE
    push dword 0x40000000 ; dwDesiredAccess = GENERIC_WRITE
    push dword filename 
    call CreateFile
    mov [handle], eax
    
    push dword 0 ; lpReserved = NULL
    push dword nChars ; lpNumberOfCharsWritten
    push dword 16; nNumberOfCharsToWrite
    push dword hello ; lpBuffer
    push eax ; hFile
    call WriteConsole

    mov eax, [handle]
    push eax
    call CloseHandle
    
    push dword 0
    call ExitProcess
    
  err:

    call GetLastError
    push eax
    call ExitProcess

  section .data use32

  filename:   db      __utf16__('CONOUT$'), 0, 0
  hello:      db      __utf16__('Hello Console!'), 13, 0, 10, 0, 0, 0
  handle:     resd    1
  nChars:     resd    1
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.