Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 3개 있습니다.)
Linux: 54. 리눅스/WSL - hello world 어셈블리 코드 x86/x64 (nasm)
; https://www.sysnet.pe.kr/2/0/13181

Windows: 217. Windows 환경에서의 Hello World x64 어셈블리 예제 (MASM 버전)
; https://www.sysnet.pe.kr/2/0/13182

개발 환경 구성: 653. Windows 환경에서의 Hello World x64 어셈블리 예제 (NASM 버전)
; https://www.sysnet.pe.kr/2/0/13185




Windows 환경에서의 Hello World x64 어셈블리 예제 (NASM 버전)

윈도우에서의 간단한 어셈블리 예제를 MASM 버전으로 알아봤는데요,

Windows 환경에서의 Hello World x64 어셈블리 예제 (MASM 버전)
; https://www.sysnet.pe.kr/2/0/13182

MASM + CRT 함수를 사용하는 경우 발생하는 컴파일 오류 정리
; https://www.sysnet.pe.kr/2/0/13183

ml64.exe와 link.exe x64 실행 환경 구성
; https://www.sysnet.pe.kr/2/0/13184

당연히 NASM(Netwide Assembler) 버전도 리눅스만 지원하는 것이 아니고 윈도우도 지원합니다. 게다가 Windows 11을 사용하고 있다면, (이제는 기본 설치된) winget을 이용해 이렇게 쉽게 설치할 수 있습니다.

c:\temp> winget install --id=NASM.NASM
Found NASM [NASM.NASM] Version 2.15.05
This application is licensed to you by its owner.
Microsoft is not responsible for, nor does it grant any licenses to, third-party packages.
Downloading https://www.nasm.us/pub/nasm/releasebuilds/2.15.05/win64/nasm-2.15.05-installer-x64.exe
  ██████████████████████████████   992 KB /  992 KB
Successfully verified installer hash
Starting package install...
Successfully installed

nasm 설치는 다음의 디렉터리에 구성되는데,

%USERPROFILE%\AppData\Local\bin\NASM

winget 설치 단계에서 함께 생성되는 바탕화면의 (nasmpath.bat을 가리키는) "nasm" 단축 아이콘을 통해 명령행 환경으로 진입할 수 있습니다. 혹은, 위의 경로를 윈도우의 환경 변수 설정에 PATH로 추가하던지, 아니면 위의 경로에 있는 "nasmpath.bat" 파일을 직접 실행해 명령행 창을 띄우면 됩니다.

하지만 그렇게 해서 nasm.exe를 실행해 어셈블리 언어를 컴파일해도, 이후의 링킹 작업은 할 수 없습니다. 이를 위해 link.exe가 필요한데요, 어쩔 수 없이 이것 때문에라도 "Visual Studio 2022 (Community)" 또는 "Build Tools for Visual Studio 2022"를 설치해야 합니다. (이때 구성 요소로 "C++을 사용한 데스크톱 개발(Desktop development with C++)"을 선택해야 합니다.)

이렇게 nasm과 link가 준비되었으면 지난 글에 설명한 PATH와 LIB 환경 변수를 설정하는 것으로 빌드 환경 구성이 마무리됩니다.

// Visual Studio 2022 Enterprise 버전인 경우
// 14.34.31933 버전은 "... Command Prompt for VS 2022" 명령행 창에서 VCToolsVersion 환경 변수와 연결돼 있습니다.
// 10.0.22000.0 버전은 "... Command Prompt for VS 2022" 명령행 창에서 UCRTVersion 환경 변수와 연결돼 있습니다.

c:\temp> SET PATH=%PATH%;C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.34.31933\bin\Hostx64\x64

c:\temp> SET LIB=C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.34.31933\lib\x64;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22000.0\ucrt\x64;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22000.0\um\x64




자, 이렇게 해서 환경 구성이 되었으면 이제 지난번 MASM으로 했던 실습을 그대로 nasm 문법으로 변환해 컴파일할 수 있습니다. ^^

우선, 콘솔 출력을 하는 hello world 예제를 다음과 같이 구성할 수 있습니다.

; nhello.asm (nasm)

     section .data
message: db 'Hello, World!', 0
message_length equ $-message

    section .text
    global main
    extern  GetStdHandle
    extern  WriteFile
    extern  ExitProcess

main:
    sub  rsp, 28h  

    ; hStdOut = GetstdHandle( STD_OUTPUT_HANDLE)
    mov     rcx, -11
    call    GetStdHandle

    ; WriteFile( hstdOut, message, length(message), &bytes, 0);
    mov     rcx, rax
    mov     rdx, message
    mov     r8, message_length
    mov     r9, 0
    push    0
    call    WriteFile

    ; ExitProcess(0)
    mov     rcx, rax
    call    ExitProcess

보는 바와 같이 문법 자체만 NASM을 따를 뿐, 내부의 ABI는 윈도우의 x64 체계를 따르기 때문에 Macro Assembler와 비교해 어셈블리 코드 자체는 거의 동일합니다.

물론, 빌드 및 실행까지 잘됩니다.

c:\temp> nasm -f win64 nhello.asm

// 또는 이렇게 Link
// link /subsystem:console /nodefaultlib /entry:main nhello.obj kernel32.lib

c:\temp> link /subsystem:console /entry:main nhello.obj kernel32.lib
Microsoft (R) Incremental Linker Version 14.12.25835.0
Copyright (C) Microsoft Corporation.  All rights reserved.


c:\temp> nhello
Hello, World!




그다음 MessageBox 예제는 별다르게 신기할 것이 없고,

; nhello_msgbox.asm

    section .data
msgtitle db 'x64 App', 0
message db 'Hello World!', 0

    section .text
    global main
    extern ExitProcess
    extern MessageBoxA

main:
    sub  rsp, 28h  

    mov     rcx, 0
    mov     rdx, message
    mov     r8, msgtitle
    mov     r9, 0
    call    MessageBoxA

    mov     rcx, rax
    call    ExitProcess

c:\temp> nasm -f win64 nhello_msgbox.asm

// 또는 이렇게 Link
// c:\temp> link /subsystem:console /nodefaultlib /entry:main nhello_msgbox.obj kernel32.lib user32.lib

c:\temp> link /subsystem:console /entry:main nhello_msgbox.obj kernel32.lib user32.lib
Microsoft (R) Incremental Linker Version 14.12.25835.0
Copyright (C) Microsoft Corporation.  All rights reserved.

c:\temp> nhello_msgbox.exe
...[MessageBox 창]...

CRT 연결하는 것도,

; hello_cpp.asm

    section .data
message db 'Hello World!', 0

    section .text
    global main
    extern ExitProcess
    extern printf

main:
    sub  rsp, 28h  

    mov     rcx, message
    call    printf

    mov     rcx, rax
    call    ExitProcess

간단하게 해결됩니다.

c:\temp> nasm -f win64 nhello_cpp.asm

// 또는 이렇게 Link
// link /subsystem:console /nodefaultlib nhello_cpp.obj vcruntime.lib kernel32.lib ucrt.lib libcmt.lib legacy_stdio_definitions.lib legacy_stdio_wide_specifiers.lib /entry:mainCRTStartup

c:\temp> link /subsystem:console nhello_cpp.obj kernel32.lib libcmt.lib /entry:mainCRTStartup
Microsoft (R) Incremental Linker Version 14.34.31933.0
Copyright (C) Microsoft Corporation.  All rights reserved.


c:\temp> nhello_cpp
Hello World!




다음과 같은 오류가 발생한다면?

c:\temp> link /subsystem:console /nodefaultlib /entry:main nhello.obj kernel32.lib
Microsoft (R) Incremental Linker Version 14.12.25835.0
Copyright (C) Microsoft Corporation.  All rights reserved.

nhello.obj : error LNK2017: 'ADDR32' relocation to '.data' invalid without /LARGEADDRESSAWARE:NO
LINK : fatal error LNK1165: link failed because of fixup errors

메시지에서 알려주는 것처럼 link에 /LARGEADDRESSAWARE:NO 옵션을 주면 오류 없이 깨끗하게 빌드 및 실행이 되긴 합니다.

c:\temp> link /subsystem:console /nodefaultlib /entry:main nhello.obj kernel32.lib /LARGEADDRESSAWARE:NO
Microsoft (R) Incremental Linker Version 14.12.25835.0
Copyright (C) Microsoft Corporation.  All rights reserved.

c:\temp> nhello.exe
Hello, World!

하지만 이렇게 되면 nhello.exe 프로세스 내의 모든 모듈들이 2GB 내의 주소 공간에 배치가 됩니다. 사실 이게 좀 이해가 안 되는데요, 위의 오류가 발생하는 원인은 MASM으로 만들었던 이전 예제 코드(hello.asm)에서는 아무 문제 없이 컴파일이 되었던 아래의 코드 때문입니다.

     section .data
message: db 'Hello, World!', 0

    section .text
        ; ...[생략]...
    lea     rdx, [message]

아마도 nasm이 멀티 플랫폼을 지원해서 그런 것인지... lea 명령어의 두 번째 operand가 32비트 값으로 취급하는 어떤 제약이 있는 것이 아닌가... 생각됩니다. (혹시 위의 코드가 왜 nasm에서 오류인지 아시는 분은 덧글 부탁드리겠습니다. ^^ )

어쨌든, lea가 아닌 (이번 글의 예제에서는 수정해서 적용한) "mov rdx, message" 명령어를 사용해 대체하면 아무런 오류 없이 빌드가 잘됩니다. 특이하게도 동일한 유형의 lea 코드를 리눅스/WSL에서 실습하면 컴파일/링크 시에 아무런 오류가 없습니다.

// 윈도우와 달리 리눅스/WSL에서 빌드하면,
// $ nasm -f elf64 -o app.o app.asm
// $ ld app.o -o app
// lea의 두 번째 operand에 대한 오류가 없음

section .data
    message: db "Hello World!", 0x0a
    message_length equ $-message

section .text
global _start

_start:
    mov rax, 1 ; sys_write
    mov rdi, 1 ; stdout
    ; mov rsi, message ; buf
    lea rsi, [message] // mov rsi, message를 lea 명령어로 바꿈
    mov rdx, message_length ; count
    syscall

    mov rax, 60 ; sys_exit
    mov rdi, 0 ; error code 0
    syscall




다음과 같은 오류가 발생한다면?

error LNK2001: unresolved external symbol __volatile_metadata

bufferoverflowu.lib를 함께 링크하면 됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 12/6/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13641정성태6/11/20248660Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20248833Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20248443오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20248524오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20248446Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20248089닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20248940Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20249416Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20248945스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20248562Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
13631정성태5/19/20249322Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법 [1]
13630정성태5/19/20248866닷넷: 2263. C# - Thread가 Task보다 더 빠르다는 어떤 예제(?)
13629정성태5/18/20249163개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/20248540개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/20248606오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/20248873Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/20248929닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/20248722Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20248418닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/20249206닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/20248637오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/20248547VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/20248860닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20248653닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20249471닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/20248618닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...