[swift-evolution] A proposal for inline assembly

Ethin Probst harlydavidsen at gmail.com
Sat Dec 3 17:12:16 CST 2016

Hello all,
My name is Ethin and I am new to this community. However, I certainly
am no newbie when it comes to software development, and have emailed
all of you to file a proposal of inline assembly in Swift. The
assembly language would be within an asm {...} block. The asm keyword
could also take an optional argument: the type of assembler to use. As
there are many different types of assemblers out there, I thought this
should be implemented as well. Furthermore, the asm keyword could also
take a second optional argument: the extra arguments to pass to the
assembler. The full syntax of the keyword would look something like:
asm (assembler, assembler_args)
    // asm goes here...
For instance, below is a hello world application in NASM assembly
language (taken from Wikipedia) with no extra arguments for Linux:
asm ("nasm")
global _start

section .text
	mov	eax, 4 ; write
	mov	ebx, 1 ; stdout
	mov	ecx, msg
	mov	edx, msg.len
	int	0x80   ; write(stdout, msg, strlen(msg));

	mov	eax, 1 ; exit
	mov	ebx, 0
	int	0x80   ; exit(0)

section .data
msg:	db	"Hello, world!", 10
.len:	equ	$ - msg
And here is one for Mac OS X with the -G, -Fstabs, and -felf arguments to nasm:
asm ("nasm", "-G -Fstabs -felf")
global _start

section .data

	query_string:		db	"Enter a character:  "
	query_string_len:	equ	$ - query_string
	out_string:			db	"You have input:  "
	out_string_len:		equ	$ - out_string

section .bss

	in_char:			resw 4

section .text


	mov	rax, 0x2000004	 	; put the write-system-call-code into register rax
	mov	rdi, 1				; tell kernel to use stdout
	mov	rsi, query_string	; rsi is where the kernel expects to find the
address of the message
	mov	rdx, query_string_len	; and rdx is where the kernel expects to
find the length of the message

	; read in the character
	mov	rax, 0x2000003		; read system call
	mov	rdi, 0				; stdin
	mov	rsi, in_char		; address for storage, declared in section .bss
	mov	rdx, 2				; get 2 bytes from the kernel's buffer (one for the
carriage return)

	; show user the output
	mov	rax, 0x2000004		; write system call
	mov	rdi, 1				; stdout
	mov	rsi, out_string
	mov	rdx, out_string_len

	mov	rax, 0x2000004		; write system call
	mov	rdi, 1				; stdout
	mov	rsi, in_char
	mov	rdx, 2				; the second byte is to apply the carriage return
expected in the string

	; exit system call
	mov	rax, 0x2000001		; exit system call
        xor     rdi, rdi
Again, both assembly language examples were taken from Wikipedia. I am
no asm expert, I assure you, and with the lack of material available
on assembly language these days... it's quite hard to learn it. I
thank you for taking your time to read this proposal and have a nice
Ethin D. Probst

More information about the swift-evolution mailing list