I am currently learning a bit of Assembler on Linux and I need your advice.
Here is the small program:
.section .data
zahlen:
.float 12,44,5,143,223,55,0
.section .text
.global _start
_start:
movl $0, %edi
movl zahlen (,%edi,4), %eax
movl %eax, %ebx
begin_loop:
cmpl $0, %eax
je prog_end
incl %edi
movl zahlen (,%edi,4), %eax
cmpl %ebx, %eax
jle begin_loop
movl %eax, %ebx
jmp begin_loop
prog_end:
movl $1, %eax
int $0x80
The program seems to compiling and running fine.
But I have some unclear questions/behaviors:
if I check the return value, which is the highers number in register %ebx, with the command "echo %?" it always return 0. I expect the value 223.
Any Idea why this happens?
I checked with DDD and gdb compiling with debugging option. So i saw that the program runs the correct steps.
But if i want to exam the register with command ie. "i r eax" it only shows me the address i believe, not the value. Same on DDD. I see only registers rax rbx and so on.
Here i need some advise to get on the right track.
Any Help appreciated.
Thanks
The "main" registers eax, ebx, ecx, edx, etc. are all designed to work with integers only. A float is a shorthand term that typically refers to a very specific data format (namely, the IEEE-754 binary32 standard), for which your CPU has dedicated registers and hardware to work with. As you saw, you are allowed to load them into integer registers as-is, but the value isn't going to convert itself like it would in a high-level, dynamically-typed language. Your code loaded the raw bit pattern instead, which likely is not at all what you intended.
This is because assembly has no type safety or runtime type-checking. The CPU has no knowledge of what type you declared your data as in your program. So when loading from memory into eax the CPU assumes that the data is a 32-bit integer, even if you declared it in your source code as something else.
If you're curious as to what a float actually looks like you can check this out: Floating Point to Hex Calculator
Switching from float to long solved the problem. Think mistake by myself. Also compiling and linking as 32bit shows the right registers in the debugger.
Related
Consider this GNU Assembler program, that copies one byte at a time from stdin to stdout, with a delay of one second between each:
#include <sys/syscall.h>
.global _start
_start:
movq $1, -16(%rsp)
movq $0, -8(%rsp)
movl $1, %edx
.again:
xorl %edi, %edi
leaq -17(%rsp), %rsi
movl $SYS_read, %eax
syscall
cmpq $1, %rax
jne .end
leaq -16(%rsp), %rdi
xorl %esi, %esi
movl $SYS_nanosleep, %eax
syscall
movl $1, %edi
leaq -17(%rsp), %rsi
movl $SYS_write, %eax
syscall
jmp .again
.end:
xorl %edi, %edi
movl $SYS_exit_group, %eax
syscall
It passes pointers to the red zone to syscalls, for both inputs and outputs, and also expects the rest of the red zone to be preserved across unrelated syscalls. Is this a safe use of the red zone that's guaranteed to always work, or is it UB that just happened to appear to work in my test?
Is this a safe use of the red zone that's guaranteed to always work, or is it UB that just happened to appear to work in my test?
It's guaranteed to be safe by the kernel developers.
In general (to guard against deliberately malicious software) CPUs are designed so that when you switch from a lower privilege level (user-space) to a higher privilege level (kernel) the CPU forces a stack switch (e.g. from "untrusted user-space stack" to "more trusted kernel stack"); and CPU also does the reverse (switching stacks when returning from higher privilege level to lower privilege level).
This makes it easy for kernel developers to ensure that system calls (and IRQs, etc) don't interfere with a user-space thread's red zone; but it doesn't necessarily prevent a kernel from interfering with a user-space thread's red zone (a kernel could do extra work for no reason to interfere, if the kernel developer wanted their kernel to be awful).
I have an inputfile.txt which looks like this: 3 4 2 0 8 1 5 3
I'm trying to write inside an outputfile.txt each character of inputfile incremented by 1.
So inside outputfile.txt I should see 4 5 3 1 9 2 6 4.
I have tried to write this piece of code but I have several doubts.
.section .data
buff_size: .long 18
.section .bss
.lcomm buff, 18
.section .text # declaring our .text segment
.globl _start # telling where program execution should start
_start:
popl %eax # Get the number of arguments
popl %ebx # Get the program name
popl %ebx # Get the first actual argument - file to read
# open the file
movl $5, %eax # open
movl $0, %ecx # read-only mode
int $0x80
# read the file
movl $0, %esi
movl %eax, %ebx # file_descriptor
analyzecharacter: #here I want to read a single character
movl $3, %eax
movl $buff, %edi
leal (%esi,%edi,1), %ecx
movl $1, %edx
int $0x80
add $1, %esi #this point is not clear to me, what I'd like to do is to increment the index of the buffer in order to be positioned on the next cell of buffer array, I've added 1 but I think is not correct
cmp $8, %esi # if I've read all 8 characters then I'll exit
je exit
openoutputfile:
popl %ebx # Get the second actual argument - file to write
movl $5, %eax # open
movl $2, %ecx # read-only mode
int $0x80
writeinoutputfile:
#increment by 1 and write the character to STDOUT
movl %eax, %ebx # file_descriptor
movl $4, %eax
leal (%esi,%edi,1), %ecx
add $1, %ecx #increment by 1
movl $1, %edx
int $0x80
jmp analyzecharacter
exit:
movl $1, %eax
movl $0, %ebx
int $0x80
I have 2 problems/doubts:
1- my first doubt is about this instruction: add $1, %esi. Is this the right way to move through buffer array?
2- The second doubt is: When I analyze each character should I always invoke openoutputfile label? I think that in this way I'm reopening the file and the previous content is overwritten.
Indeed if I run the program I see only a single character \00 (a garbage character, caused by the value of %esi in this instruction I guess: leal (%esi,%edi,1), %ecx ).
I hope my problems are clear, I'm pretty new to assembly and I've spent several hours on this.
FYI:
I'm using GAS Compiler and the syntax is AT&T.
Moreover I'm on Ubuntu 64 bit and Intel CPU.
So, how I would do the code...
Thinking about it, I'm so used to Intel syntax, that I'm unable to write AT&T source from my head on the web without bugs (and I'm too lazy to actually do the real thing and debug it), so I will try to avoid writing instructions completely and just describe the process, to let you fill up the instructions.
So let's decide you want to do it char by char, version 1 of my source:
start:
; verify the command line has enough parameters, if not jump to exitToOs
; open both input and output files at the start of the code
processingLoop:
; read single char
; if no char was read (EOF?), jmp finishProcessing
; process it
; write it
jmp processingLoop
finishProcessing:
; close both input and output files
exitToOs:
; exit back to OS
now "run" it in your mind, verify all the major branch points make sense and will handle correctly for all major corner cases.
make sure you understand how the code will work, where it will loop, and where and why it will break out of loop.
make sure there's no infinite loop, or leaking of resources
After going trough my checklist, there's one subtle problem with this design, it's not rigorously checking file system errors, like failing to open either of the files, or writing the character (but your source doesn't care either). Otherwise I think it should work well.
So let's extend it in version 2 to be more close to real ASM instructions (asterisk marked instructions are by me, so probably with messed syntax, it's up to you to make final version of those):
start:
; verify the command line has enough parameters, if not jump to exitToOs
popl %eax # Get the number of arguments
* cmpl $3,eax ; "./binary fileinput fileoutput" will have $3 here?? Debug!
* jnz exitToOs
; open both input and output files at the start of the code
movl $5, %eax # open
popl %ebx # Get the program name
; open input file first
popl %ebx # Get the first actual argument - file to read
movl $0, %ecx # read-only mode
int $0x80
cmpl $-1, %eax ; valid file handle?
jz exitToOs
* movl %eax, ($varInputHandle) ; store input file handle to memory
; open output file, make it writable, create if not exists
movl $5, %eax # open
popl %ebx # Get the second actual argument - file to write
* ; next two lines should use octal numbers, I hope the syntax is correct
* movl $0101, %ecx # create flag + write only access (if google is telling me truth)
* movl $0666, %edx ; permissions for out file as rw-rw-rw-
int $0x80
cmpl $-1, %eax ; valid file handle?
jz exitToOs
movl %eax, ($varOutputHandle) ; store output file handle to memory
processingLoop:
; read single char to varBuffer
movl $3, %eax
movl ($varInputHandle), %ebx
movl $varBuffer, %ecx
movl $1, %edx
int $0x80
; if no char was read (EOF?), jmp finishProcessing
cmpl $0, %eax
jz finishProcessing ; looks like total success, finish cleanly
;TODO process it
* incb ($varBuffer) ; you wanted this IIRC?
; write it
movl $4, %eax
movl ($varOutputHandle), %ebx # file_descriptor
movl $varBuffer, %ecx ; BTW, still set from char read, so just for readability
movl $1, %edx ; this one is still set from char read too
int $0x80
; done, go for the next char
jmp processingLoop
finishProcessing:
movl $0, ($varExitCode) ; everything went OK, set exit code to 0
exitToOs:
; close both input and output files, if any of them is opened
movl ($varOutputHandle), %ebx # file_descriptor
call closeFile
movl ($varInputHandle), %ebx
call closeFile
; exit back to OS
movl $1, %eax
movl ($varExitCode), %ebx
int $0x80
closeFile:
cmpl $-1, %ebx
ret z ; file not opened, just ret
movl $6, %eax ; sys_close
int $0x80
; returns 0 when OK, or -1 in case of error, but no handling here
ret
.data
varExitCode: dd 1 ; no idea about AT&T syntax, "dd" is "define dword" in NASM
; default value for exit code is "1" (some error)
varInputHandle: dd -1 ; default = invalid handle
varOutputHandle: dd -1 ; default = invalid handle
varBuffer: db ? ; (single byte buffer)
Whoa, I actually wrote it fully? (of course it needs the syntax check + cleanup of asterisks, and ";" for comments, etc...)
But I mean, the comments from version 1 were already so detailed, that each required only handful of ASM instructions, so it was not that difficult (although now I see I did submit the first answer 53min ago, so this was about ~1h of work for me (including googling and a bit of other errands elsewhere)).
And I absolutely don't get how some human may want to use AT&T syntax, which is so ridiculously verbose. I can easily understand why the GCC is using it, for compilers this is perfectly fine.
But maybe you should check NASM, which is "human" oriented (to write only as few syntax sugar, as possible, and focus on instructions). The major problem (or advantage in my opinion) with NASM is Intel syntax, e.g. MOV eax,ebx puts number ebx into eax, which is Intels fault, taking LD syntax from other microprocessors manufacturers, ignoring the LD = load meaning, and changing it to MOV = move to not blatantly copy the instruction set.
Then again, I have absolutely no idea why ADD $1,%eax is the correct way in AT&T (instead of eax,1 order), and I don't even want to know, but it doesn't make any sense to me (the reversed MOV makes at least some sense due to LD origins of Intel's MOV syntax).
OTOH I can relate to cmp $number,%reg since I started to use "yoda" formatting in C++ to avoid variable value changes by accident in if (compare: if (0 = variable) vs if (variable = 0), both having typo = instead of wanted == .. the "yoda" one will not compile even with warnings OFF).
But ... oh.. this is my last AT&T ASM answer for this week, it annoys hell out of me. (I know this is personal preference, but all those additional $ and % annoys me just as much, as the reversed order).
Please, I spend serious amount of time writing this. Try to spend serious time studying it, and trying to understand it. If confused, ask in comments, but it would be pitiful waste of our time, if you would completely miss the point and not learn anything useful from this. :) So keep on.
Final note: and search hard for some debugger, find something what suits you well (probably some visual one like old "TD" from Borland in DOS days would be super nice for newcomer), but it's absolutely essential for you to improve quickly, to be able to step instruction by instruction over the code, and watch how the registers and memory content do change values. Really, if you would be able to debug your own code, you would soon realize you are reading second character from wrong file handle in %ebx... (at least I hope so).
Just to clear 1) early: add $1, %esi is indeed equivalent to inc %esi.
While you are learning assembler, I would go for the inc variant, so you don't forget about its existence and get used to it. Back in 286-586 times it would be also faster to execute, today the add is used instead - because of the complexity of micro architecture (μops), where inc is tiny fraction more complicated for CPU (translating it back to add μops I guess, but you shouldn't worry about this while learning basics, aim rather for "human" readability of the source, do not any performance tricks yet).
Is it the right way?
Well, you should firstly decide whether you want to parse it per character (or rather go for byte, as character is nowadays often utf8 glyph, which can have size from 1 to 6 or how many bytes; I'm not even sure) OR to process it with buffers.
Your mix of the two is making it easy to do additional mistakes in the code.
From a quick look I see:
you read only single byte per syscall, yet you store it at new place
in buffer+counter (why? Just use single byte buffer, if you work per byte)
when counter is 8, you exit (not processing the 8th
read byte at all).
you lose forever your input file descriptor after opening output file first time by popl %ebx (leaking file handles is very bad)
then second char is read from output file (reusing the file handle from write)
then you popl %ebx again, but there's no third parameter on command line, i.e. you fetch undefined memory from stack
indeed you reopen the output file each time, so unless it's in append mode, it will overwrite content.
That's probably all major blunders you did, but that's actually so many, that I would suggest you to start over from scratch.
I will try to do a quick my version in next answer (as this one is getting a bit long), to show you how I would do it. But at first please try (hard) to find all the points I did highlight above, and understand how your code works. If you will fully understand what your instructions do, and why they really do the error I described, you will have much easier time to design your next code, plus debugging it. So the more of the points you will really find, and fully understand, the better for you.
"BTW notes":
I never did linux asm programming (I'm now itching to do something after reading about your effort), but from some wiki about system calls I read:
All registers are preserved during the syscall.
Except return value in eax of course.
Keep this in mind, it may save you some hassle with repeating register setup before call, if you group syscalls appropriately.
When I compare $0 against %eax for error checking, and enter no input when prompted, the error message does not display. However, when I compare $1 against %eax and enter no input, the error message displays. I'm aware that a read syscall returns the amount of bytes read into %eax, although I'm unsure as to why it returns a byte was read when no input is given, the man pages also don't give me any indication to why this is the case. Is stdin input null-terminated or is it something else?
movl $3, %eax
movl $0, %ebx
movl $BUFFER, %ecx
movl $BUFFER_SIZE, %edx
int $0x80
cmpl $0, %eax
jle input_error
If cmpl $0 is changed to cmpl $1, and no input is given, it jumps to input_error, with cmpl $0 program flow proceeds when no input is given.
You can't call sys_read with these parameters and to expect that there will be no input.
sys_read is blocking call. So, it will block until some input appears. In your case, IMO, you press ENTER and in this case, sys_read returns with 1 byte read in the buffer - LF, ascii code 0Ah and eax=1.
P.S. It is not my job, but better use FASM or at least NASM. This way you will get much more help in your ASM programming. GAS has really terrible syntax. :)
So, as a challenge, and for performance, I'm writing a simple server in assembly. The only way I know of is via system calls. (through int 0x80) Obviously, I'm going to need more memory than allocated at assemble, or at load, so I read up and decided I wanted to use sbrk(), mainly because I don't understand mmap() :p
At any rate, Linux provides no interrupt for sbrk(), only brk().
So... how do I find the current program break to use brk()? I thought about using getrlimit(), but I don't know how to get a resource (the process id I'd guess) to pass to getrlimit(). Or should I find some other way to implement sbrk()?
The sbrk function can be implemented by getting the current value and subtracting the desired amount manually. Some systems allow you to get the current value with brk(0), others keep track of it in a variable [which is initialized with the address of _end, which is set up by the linker to point to the initial break value].
This is a very platform-specific thing, so YMMV.
EDIT: On linux:
However, the actual Linux system call returns the new program break on success. On failure, the system call returns the current break. The glibc wrapper function does some work (i.e., checks whether the new break is less than addr) to provide the 0 and -1 return values described above.
So from assembly, you can call it with an absurd value like 0 or -1 to get the current value.
Be aware that you cannot "free" memory allocated via brk - you may want to just link in a malloc function written in C. Calling C functions from assembly isn't hard.
Source:
#include <unistd.h>
#define SOME_NUMBER 8
int main() {
void *ptr = sbrk(8);
return 0;
}
Compile using with Assembly Output option
gcc -S -o test.S test.c
Then look at the ASM code
_main:
Leh_func_begin1:
pushq %rbp
Ltmp0:
movq %rsp, %rbp
Ltmp1:
subq $16, %rsp
Ltmp2:
movl $8, %eax
movl %eax, %edi
callq _sbrk
movq %rax, -16(%rbp)
movl $0, -8(%rbp)
movl -8(%rbp), %eax
movl %eax, -4(%rbp)
movl -4(%rbp), %eax
addq $16, %rsp
popq %rbp
ret
Leh_func_end1:
There is no system call for it but you should be able to still make the call
I ran gcc -S over this:
int main()
{
printf ("Hello world!");
}
and I got this assembly code:
.file "test.c"
.section .rodata
.LC0:
.string "Hello world!"
.text
.globl main
.type main, #function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $20, %esp
movl $.LC0, (%esp)
call printf
addl $20, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.3.0 20080428 (Red Hat 4.3.0-8)"
.section .note.GNU-stack,"",#progbits
I am curious to understand this output. Can someone share some pointers in understanding this output, or if someone could mark comments against each of these lines/group of lines explaining what it does it would be great.
Here how it goes:
.file "test.c"
The original source file name (used by debuggers).
.section .rodata
.LC0:
.string "Hello world!"
A zero-terminated string is included in the section ".rodata" ("ro" means "read-only": the application will be able to read the data, but any attempt at writing into it will trigger an exception).
.text
Now we write things into the ".text" section, which is where code goes.
.globl main
.type main, #function
main:
We define a function called "main" and globally visible (other object files will be able to invoke it).
leal 4(%esp), %ecx
We store in register %ecx the value 4+%esp (%esp is the stack pointer).
andl $-16, %esp
%esp is slightly modified so that it becomes a multiple of 16. For some data types (the floating-point format corresponding to C's double and long double), performance is better when the memory accesses are at addresses which are multiple of 16. This is not really needed here, but when used without the optimization flag (-O2...), the compiler tends to produce quite a lot of generic useless code (i.e. code which could be useful in some cases but not here).
pushl -4(%ecx)
This one is a bit weird: at that point, the word at address -4(%ecx) is the word which was on top of the stack prior to the andl. The code retrieves that word (which should be the return address, by the way) and pushes it again. This kind of emulates what would be obtained with a call from a function which had a 16-byte aligned stack. My guess is that this push is a remnant of an argument-copying sequence. Since the function has adjusted the stack pointer, it must copy the function arguments, which were accessible through the old value of the stack pointer. Here, there is no argument, except the function return address. Note that this word will not be used (yet again, this is code without optimization).
pushl %ebp
movl %esp, %ebp
This is the standard function prologue: we save %ebp (since we are about to modify it), then set %ebp to point to the stack frame. Thereafter, %ebp will be used to access the function arguments, making %esp free again. (Yes, there is no argument, so this is useless for that function.)
pushl %ecx
We save %ecx (we will need it at function exit, to restore %esp at the value it had before the andl).
subl $20, %esp
We reserve 32 bytes on the stack (remember that the stack grows "down"). That space will be used to storea the arguments to printf() (that's overkill, since there is a single argument, which will use 4 bytes [that's a pointer]).
movl $.LC0, (%esp)
call printf
We "push" the argument to printf() (i.e. we make sure that %esp points to a word which contains the argument, here $.LC0, which is the address of the constant string in the rodata section). Then we call printf().
addl $20, %esp
When printf() returns, we remove the space allocated for the arguments. This addl cancels what the subl above did.
popl %ecx
We recover %ecx (pushed above); printf() may have modified it (the call conventions describe which register can a function modify without restoring them upon exit; %ecx is one such register).
popl %ebp
Function epilogue: this restores %ebp (corresponding to the pushl %ebp above).
leal -4(%ecx), %esp
We restore %esp to its initial value. The effect of this opcode is to store in %esp the value %ecx-4. %ecx was set in the first function opcode. This cancels any alteration to %esp, including the andl.
ret
Function exit.
.size main, .-main
This sets the size of the main() function: at any point during assembly, "." is an alias for "the address at which we are adding things right now". If another instruction was added here, it would go at the address specified by ".". Thus, ".-main", here, is the exact size of the code of the function main(). The .size directive instructs the assembler to write that information in the object file.
.ident "GCC: (GNU) 4.3.0 20080428 (Red Hat 4.3.0-8)"
GCC just loves to leave traces of its action. This string ends up as a kind of comment in the object file. The linker will remove it.
.section .note.GNU-stack,"",#progbits
A special section where GCC writes that the code can accommodate a non-executable stack. This is the normal case. Executable stacks are needed for some special usages (not standard C). On modern processors, the kernel can make a non-executable stack (a stack which triggers an exception if someone tries to execute as code some data which is on the stack); this is viewed by some people as a "security feature" because putting code on the stack is a common way to exploit buffer overflows. With this section, the executable will be marked as "compatible with a non-executable stack" which the kernel will happily provide as such.
Here is some supplement to #Thomas Pornin's answer.
.LC0 local constant, e.g string literal.
.LFB0 local function beginning,
.LFE0 local function ending,
The suffix of these label is a number, and start from 0.
This is gcc assembler convention.
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $20, %esp
these instructions don't compare in your c program, they're always executed at the beginning of every function (but it depends on compiler/platform)
movl $.LC0, (%esp)
call printf
this block corresponds to your printf() call. the first instruction places on the stack its argument (a pointer to "hello world") then calls the function.
addl $20, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
these instructions are opposite to the first block, they're some sort of stack manipulation stuffs. always executed too