2889 words
14 minutes
240502_Assembly_x86_64_basic001

link#





x86_64_Assembly Language Programming with Ubuntu(eBook)#

어셈블러의 비교#


CPU Instructions#

General
Instruction
Function Call
Instructions
Stack
Instructions
mov
jmp
add
sub
call
ret
push
pop

Top 10 Craziest Assembly Language Instructions | Creel#


Mara Bos#

@m_ou_se ⚛️📋 I made an overview of the ARMv8 and x86-64 machine instructions for all the common atomic operations:

https://twitter.com/m_ou_se/status/1590333332012662784/photo/1

Assembly Debugging#

https://www.gnu.org/software/ddd/manual/

https://github.com/BetelGeuseee/x86-assembly-yasm

내가 공부하려고 정리중(x86_64_Assembly)#

https://youtube.com/playlist?list=PLcMveqN_07mb4_M06LrKJK5LHVKGFyICB&si=7PUFD9S4OuLJQCHv


rust_웹으로 어셈블리 보기Assembly#

https://rust.godbolt.org/

  • 뒤에 최적화 옵션
-C opt-level=3 --target i686-unknown-linux-gnu

vim tab setting#

set tabstop=4
set shiftwidth=4

Vim _ Assembly Highlight Syntax#


:set ft=nasm  " assembly highlight syntax

NeoVim(asm-lsp)#

cargo install asm-lsp
# or to get the latest version from github
cargo install --git https://github.com/bergercookie/asm-lsp

x86 and x86_64 Assembly(VSCode Extension)#


To debug NASM you might want to use DDD.#

To debug NASM you might want to use DDD. The following course teaches assembly for Intel/Linux using NASM and DDD, you might want to have a look at it as you might find it helpful:

Getting started with NASM and DDD —> https://www.youtube.com/watch?v=YyovCxsMVio

Assembly integer arithmetic —> https://www.youtube.com/watch?v=-KfZaJclqk4

Assembly floating-point arithmetic —> https://www.youtube.com/watch?v=n1gIv40VSgA

Assembly control instructions —> https://www.youtube.com/watch?v=s38DcLv1wYk

Assembly and process stack —> https://www.youtube.com/watch?v=7nPru8b7SjY

Assembly functions —> https://www.youtube.com/watch?v=QOPOeDPlNZo

Stack buffer overflow —> https://www.youtube.com/watch?v=BW2obfJtkPw

System services —> https://www.youtube.com/watch?v=qzTlkJsq3Xo

https://www.reddit.com/r/asm/comments/ba4qi9/debugging_nasm/




외국 사람이 만든 x86_64 설명서 github 예시 좋다.!#

https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/

Debugging BIOS Assembly Visually with Visual Studio Code and GDB [Ep 13]#

https://youtu.be/aMSFaAcup50?si=91Qr4sMRqIsa5_TT

3분안에 설명하는 Assembly Language#

10분안에 익히는 x86 Assembly | x86 Assembly Crash Course | HackUCF#

https://youtu.be/75gBFiFtAb8?si=skDTgz3WiarSaKbY


x86asm.net#

http://ref.x86asm.net/coder64.html


x86-x64 명령어 레퍼런스 읽는 법#

https://modoocode.com/316

The Go tools for Windows + Assembler#

http://godevtool.com/


1.4.4.1 YASM References#

http://yasm.tortall.net/

1.4.4.1 YASM References The YASM assembler is an open source assembler commonly available on Linux-based systems. The YASM references are as follows:

1.4.4.2 DDD Debugger References#

The DDD debugger is an open source debugger capable of supporting assembly language.

Additional information regarding DDD may be at a number of assembly language sites and can be found through an Internet search.


Assembly Language#

https://github.com/EbookFoundation/free-programming-books/blob/main/books/free-programming-books-langs.md#non-x86

x86 Assembly : Hello World#

https://youtu.be/HgEGAaYdABA

x86_64_Assembly_my_project#

  • x86_64_Assembly Language Programming with Ubuntu

http://www.egr.unlv.edu/~ed/assembly64.pdf

apt install(Linux OS)#

$ sudo apt install nasm
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  nasm
0 upgraded, 1 newly installed, 0 to remove and 11 not upgraded.
Need to get 375 kB of archives.
After this operation, 3,345 kB of additional disk space will be used.
Get:1 http://us.archive.ubuntu.com/ubuntu jammy/universe amd64 nasm amd64 2.15.05-1 [375 kB]
Fetched 375 kB in 2s (217 kB/s)
Selecting previously unselected package nasm.
(Reading database ... 263485 files and directories currently installed.)
Preparing to unpack .../nasm_2.15.05-1_amd64.deb ...
Unpacking nasm (2.15.05-1) ...
Setting up nasm (2.15.05-1) ...
Processing triggers for man-db (2.10.2-1) ...

ASM Build & Execution#

  • elf64
nasm -felf64 add.asm && ld add.o && ./a.out
  • elf32
$ nasm -f elf32 -o hello.o hello.asm

$ ls
hello.asm  hello.o

$ ld -m elf_i386 -o hello hello.o

$ ls
hello  hello.asm  hello.o

$ ./hello
Hello World!

ASM hello.asm#

; World World x86_64 Intel Cpu Assembly
; hello.asm

global _start

section     .text:

_start:
    mov eax, 0x4                    ; use the write syscall
    mov ebx, 1                      ; use stdout as the fd
    mov ecx, message                ; use the message as the buffer
    mov edx, message_length         ; and supply the length
    int 0x80                        ; invoke the syscall

    ; now gracefully exit

    mov eax, 0x1
    mov ebx, 0
    int 0x80


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


Windows OS#

choco install nasm
  • This package uses the official nasm Windows installer, which doesn’t add nasm to PATH. You may voice out your request in the nasm issue tracker, in which there is an existing issue filed

  • PATH설정해줘야함. 나 같은 경우는 “C:\Program Files\NASM” 여기 PATH 설정함.

https://community.chocolatey.org/packages/nasm



Rust Languages & Assemblyrust1#


RustLang inline-assembly#

https://doc.rust-lang.org/reference/inline-assembly.html

https://doc.rust-lang.org/rust-by-example/unsafe/asm.html


Rust ~~~~~~~~~ ~~~~~~~#



Assembly 기초 basic#

assembly

Bootsector Game From Scratch - Space Invaders (x86 asm) Game만들기(Assembly로)#

https://youtu.be/TVvTDjMph1M


ASCII Table#

https://www.asciitable.com/

$ python

Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> 0x0a
10

>>> chr(0x0a)
'\n'

>>>



====================================================

x86_64_Assembly Language Programming with Ubuntuassembly#

Data Storage Sizes(page 8.)#

Data Storage Sizes
StorageSize(bits)Size(bytes)
Byte8-bits1 byte
Word16-bits2 bytes
Double-word32-bits4 bytes
Quadword64-bits8 bytes
Double quadword128-bits16 bytes

http://www.egr.unlv.edu/~ed/assembly64.pdf

Data Storage Sizes(page9.)
C/C++ declarations are mapped as follows:
C/C++
Declaration
StorageSize(bits)Size(bytes)
charByte8-bits1 byte
Word16-bits2 bytes
Double-word32-bits4 bytes
Quadword64-bits8 bytes
Double quadword128-bits16 bytes

General Purpose Registers(GPRs) page 10#

  • General-purpose register layout
  • The x86-64 general-purpose registers are
    • aliased: each has multiple names, which refer to overlapping bytes in the register.
General-purpose register layout
rax
<-- 64 bits -->
8bit8bit8bit8biteax
(Lowest 32-bits
<---------------- ---------------------->
8bit8bit8bit8bit8bit8bit<--- ax --->
Lowest 16-bits
8bit8bit8bit8bit8bit8bitah
<-- 8-bits -->
al
<-- 8-bits -->
Byte 7Byte 6Byte 5Byte 4Byte 3Byte 2Byte 1Byte 0

General Purpose Registers(GPRs)
64-bit registerLowest
32-bits
Lowest
16-bits
Lowest
8-bits
raxeaxaxal
rbxebxbxbl
rcxecxcxcl
rdxedxdxdl
rsiesisisil
rdiedididil
rbpebpbpbpl
rspespspspl
r8r8dr8wr8b
r9r9dr9wr9b
r10r10dr10wr10b
r11r11dr11wr11b
r12r12dr12wr12b
r13r13dr13wr13b
r14r14dr14wr14b
r15r15dr15wr15b

http://www.egr.unlv.edu/~ed/assembly64.pdf


Stack Pointer Register (RSP)#

  • Stack Pointer Register
Stack Pointer RegisterRSP
  • One of the CPU registers, rsp, is used to point to the current top of the stack. The rsp register should not be used for data or other uses. Additional information regarding the stack and stack operations is provided in Chapter 9, Process Stack.

Base Pointer Register (RBP)#

Base Pointer RegisterRBP
  • One of the CPU registers, rbp, is used as a base pointer during function calls. The rbp register should not be used for data or other uses. Additional information regarding the functions and function calls is provided in Chapter 12, Functions.

Instruction Pointer Register (RIP)#

Instruction Pointer RegisterRIP
  • In addition to the GPRs, there is a special register, rip, which is used by the CPU to point to the next instruction to be executed. Specifically, since the rip points to the next instruction, that means the instruction being pointed to by rip, and shown in the debugger, has not yet been executed. This is an important distinction which can be confusing when reviewing code in a debugger.

Flag Register (rFlags)#

  • Assembly Language & Computer Architecture | MIT OpenCourseWare(33min05sec)

  • The flag register, rFlags, is used for status and CPU control information

  • This register stores status information about the instruction that was just executed. Of the 64-bits in the rFlag register, many are reserved for future use.

  • Arithmetic and logic operations update status flags in the RFLAGS register.

decq %rbx   
jne .LBB7_1
  • decq %rbx; Decrement %rbx, and set ZF if the result is 0.
Flag Register (rFlags)
RFLAGS Register
Name
Description
Symbol
or
(Abbreviation)
Bit(s)Use
CarryCF0Used to indicate if the previous operation resulted in a carry.
Reserved1
ParityPF2Used to indicate if the last byte has an even number of 1's (i.e., even parity).
Reserved3
AdjustAF4Used to support Binary Coded Decimal operations.
Reserved5
ZeroZF6Used to indicate if the previous operation resulted in a zero result.
SignSF7Used to indicate if the result of the previous operation resulted in a 1 in the most significant bit (indicating negative in the context of signed data).
TrapTF8
Interrupt
enable
IF9
DirectionDF10Used to specify the direction (increment or decrement) for some string operations.
OverflowOF11Used to indicate if the previous operation resulted in an overflow.
System flags or
reserved
12 - 63

Common x86-64 Registers#

NumberWidth
(bits)
Names(s)Purpose
1664(many)General-purpose registers
616%ss,%[c-g]sSegment registers
164RFLAGSFlags register
164%ripInstruction pointer register
764%cr[0-4,8], %xcr0Control registers
864%mm[0-7]MMX registers
132mxcsrSSE2 control register
16128%xmm[0-15]XMM registers (for SSE)
256%ymm[0-15]YMM registers (for AVX)
880%st([0-7])x87 FPU data registers
116x87 CWx87 FPU control register
116x87 SWx87 FPU status register
148x87 FPU instruction
pointer register
148x87 FPU data operand
pointer register
116x87 FPU tag register
111x87 FPU opcode register

x86-64 Data Types#

x86-64 Data Types
C declarationC
constant
x86-64
size
(bytes)
Assembly
suffix
x-86-64
data type
char'c'1bByte
short1722wWord
int1724l or dDouble word
unsigned
int
172U4l or dDouble word
long172L8qQuad word
unsigned long172UL8qQuad word
char *"6.172"8qQuad word
float6.172F4sSingle precision
double6.1728dDouble precision
long double6.172L16(10)tExtended precision

28min30sec https://youtu.be/L1ung0wil9Y?si=XEBdCmwbP48LLYOE



Computer Architecture(Page 7)#

1


Common x86-64 Opcodes#

Opcodes
Type of perationExample
Data
movement
Movemov
Conditional
move
cmov
Sign or
zero extension
movs, movz
Stackpush, pop
Arithmetic
and logic
Integer
arithmetric
add, sub, mul, imul,div, idiv,
lea,sal, sar, shl, shr, rol,
ror, inc, dec,neg
Binary logicand, or, xor, not
Boolean logictest, cmp
Control
transfer
Unconditional
jump
jmp
Conditional
jump
j<condition>
Subroutinescall, ret

Condition Codes#

Condition Codes
Condition codeTranslationRFLAGS status flags
checked
aif aboveCF = 0 and ZF = 0
aeif above or equalCF = 0
con carryCF = 1
eif equalZF = 1
geif greater or equalSF = OF
neif not equalZF = 0
oon overflowOF = 1
zif zeroZF = 1

CPU Block Diagram(Page 15)#

Image

Memory Layout(Page17)#

General Memory Layout
high memory








low memory
stack
.
.
.
heap
BSS - uninitialized data
data
text (code)
reserved

http://www.egr.unlv.edu/~ed/assembly64.pdf


Memory Hierarchy(Page18)#

Memory Hierarchy
Smaller, faster,
and more expensive








Larger,slower,
and less expensive
CPU
Registers
Cache
Primary Storage
Main Memory(RAM)
Secondary Storage
(disk drives, SSD's, etc.)
Tertiary Storage
(remote storage, optical, backups,etc.)

http://www.egr.unlv.edu/~ed/assembly64.pdf

Some typical performance and size characteristics (Page19)#

Memory UnitExample SizeTypical Speed
Registers16, 64-bit registers~1 nanoseconds13
Cache Memory4 - 8+ Megabytes14
(L1 and L2)
~5-60 nanoseconds
Primary Storage
(i.e., main memory)
2 - 32+ Gigabytes15~100-150 nanoseconds
Secondary Storage
(i.e., disk, SSD's, etc.)
500 Gigabytes -
4+ Terabytes16
~3-15 milliseconds17

Data Section(Page34) - All initialized variables & constants#

Refer to the following sections for a series of examples using various data types.

The supported data types are as follows:

section .data
All initialized variables and constants
Declaration
db8-bit variable(s)
dw16-bit variable(s)
dd32-bit variable(s)
dq64-bit variable(s)
ddq128-bit variable(s) -> integer
dt128-bit variable(s) -> float

http://www.egr.unlv.edu/~ed/assembly64.pdf

ex)


; The general format is:

; <variableName> <dataType> <initialValue>

section .data

  bVar     db      10             ; byte variable
  cVar     db      "H"            ; single character
  strng    db      "Hello World"  ; string
  wVar     dw      5000           ; 16-bit variable
  dVar     dd      50000          ; 32-bit variable
  arr      dd      100, 200, 300  ; 3 element array
  flt1     dd      3.14159        ; 32-bit float
  qVar     dq      1000000000     ; 64-bit variable

The value specified must be able to fit in the specified data type. For example, if the value of a byte sized variables is defined as 500, it would generate an assembler error.


BSS Section(Page35) - All uninitialized variables#

Uninitialized data is declared in the “section .bss” section.

The supported data types are as follows:

section .bss
Uninitialized data
Declaration
resb8-bit variable(s)
resw16-bit variable(s)
resd32-bit variable(s)
resq64-bit variable(s)
resdq128-bit variable(s)

ex)

; The general format is:

; <variableName> <resType> <count>

section .bbs

  bArr    resb    10     ; 10 element byte array
  wArr    resw    50     ; 50 element word array
  dArr    resd    100    ; 100 element double array
  qArr    resq    200    ; 200 element quad array


; The allocated array is not initialized to any specific value.

http://www.egr.unlv.edu/~ed/assembly64.pdf


Text Section(Page36)#


; Code Section
section .text

global _start
_start:

4.7 Example Program(page37)#

; Simple example demonstrating basic program format and layout.
; Ed Jorgensen
; July 18, 2014
; ************************************************************
; Some basic data declarations
section .data
; -----
  ; Define constants
  EXIT_SUCCESS equ 0 ; successful operation
  SYS_exit equ 60 ; call code for terminate
  ; -----
  ; Byte (8-bit) variable declarations
  bVar1   db 17
  bVar2   db 9
  bResult db 0
  ; -----
  ; Word (16-bit) variable declarations
  wVar1   dw 17000
  wVar2   dw 9000
  wResult dw 0
  ; -----
  ; Double-word (32-bit) variable declarations
  dVar1   dd 17000000
  dVar2   dd 9000000
  dResult dd 0

  ; -----
  ; quadword (64-bit) variable declarations
  qVar1   dq 170000000
  qVar2   dq 90000000
  qResult dq 0
; ************************************************************

; Code Section
section .text
global _start
_start:

  ; Performs a series of very basic addition operations
  ; to demonstrate basic program format.
  ; ----------
  ; Byte example
  ; bResult = bVar1 + bVar2
   mov al, byte [bVar1]
   add al, byte [bVar2]
   mov byte [bResult], al

  ; ----------
  ; Word example
  ; wResult = wVar1 + wVar2
   mov ax, word [wVar1]
   add ax, word [wVar2]
   mov word [wResult], ax

  ; ----------
  ; Double-word example
  ; dResult = dVar1 + dVar2
   mov eax, dword [dVar1]
   add eax, dword [dVar2]
   mov dword [dResult], eax

  ; ----------
  ; Quadword example
  ; qResult = qVar1 + qVar2
   mov rax, qword [qVar1]
   add rax, qword [qVar2]
   mov qword [qResult], rax
  ; ************************************************************
  ; Done, terminate program.
last:
  mov rax, SYS_exit ; Call code for exit
  mov rdi, EXIT_SUCCESS ; Exit program with success
  syscall

http://www.egr.unlv.edu/~ed/assembly64.pdf

240502_Assembly_x86_64_basic001
https://younghakim7.github.io/blog/posts/240502_assembly_x86_64_basic001/
Author
YoungHa
Published at
2024-05-02