Mach-O 64-bit format does not support 32-bit absolute addresses, cannot put byte in resb buffer [duplicate] - macos

This question already has an answer here:
Mach-O 64-bit format does not support 32-bit absolute addresses. NASM Accessing Array
(1 answer)
Closed 4 years ago.
%include "along64.inc"
default rel
section .data
EnterMsg : db "Enter a number to add to the list; enter 0 when you done" ,0ah,0
ExitMsg : db "The sorted list: " ,0ah,0
InputError1 : db "Input Error; Integers Only" ,0ah,0
InputError2 : db "Input Error; Maximum list is 100" ,0ah,0
InputError3 : db "Input Error; Enter AT LEAST ONE Int" ,0ah,0
segment .bss
a: resq 100 ;creates a new array with 100 values set to 0
section .text
global main
main:
mov rbx,0
mov rcx,0 ;sets counter to 0
mov rdx, EnterMsg ;moves EnterMsg to rdx to be called by WriteString
call WriteString ;prints EnterMsg
jmp read ;calls readInput label
read: ;reads the input
call ReadInt ;reads integer
jo invalidInput ;jumps if not an integer value
cmp rcx, 100 ;compares rcx and 100
jg tooManyInts ;if rcx is already 100, then cannot add int to array, so jump to error
cmp rax,0 ;tests for the 0 input
je Loop1 ;jumps to Loop1 if zero
mov [a +(rcx*4)], rax ;adds read integer to array
inc rcx ;increments counter
jmp read ;loops if input is not 0
Loop1:
cmp rcx, 2 ;compares rcx to 2
jmp badInput ;jumps to badinput if less than 2
push rcx ;pushes rcx for number of numbers to print
dec rcx ;decrements rcx because 0-based indexing
Loop2:
push rcx ;saves outer loop count
mov rbx, 0 ;sets rbx to 0 because 0 based indexing
Loop3:
mov rax,qword[a +(rbx * 4)] ;moves current value of array, as determined by value of
;rbx*4, to rax
cmp [a + (rbx * 4) + 4], rax ;compares next value of array with rax
jg Loop4 ;if greater, jumps to L4
xchg rax,qword[a + (rbx*4)+4] ;if less, exchanges values
mov qword[a + (rbx * 4)], rax ;and moves new value of rax to the current value of the array
Loop4:
inc rbx ;increments rbx to iterate through array
loop Loop3 ;inner loop iterates through array values once
pop rcx ;pops rcx that was previously pushed to reset count for outer loop
loop Loop2 ;loops back to L2 to iterate through all values of array again
SetWrite:
mov rbx, 0 ;resets rbx to 0
pop rcx ;pops intial count for rcx, to determine how many times
;writeint should be called
call Crlf ;prints new line
mov rdx, ExitMsg ;moves ExitMsg to rdx
call WriteString ;writes ExitMsg
WriteArray:
mov [a + rcx],rax ;moves values of array to rax, where WriteInt calls from
call WriteInt ;writes current value of rax
call Crlf ;prints new line
add rbx, 4 ;increments rbx by 4
loop WriteArray ;loops rcx times
jmp exit ;jumps to exit
WriteArrayOne:
call Crlf ;prints new line
mov rdx, ExitMsg ;moves ExitMsg to rdx
call WriteString ;writes ExitMsg
mov qword[a +rbx],rax ;moves first value of array to rax, where WriteInt calls from
call WriteInt ;writes value of rax
call Crlf ;prints new line
jmp exit ;jumps to exit
invalidInput: ;jumps here if input is not an integer
mov rdx,InputError1 ;moves InputError1 to rdx
call WriteString ;prints InputError1
jmp exit ;exits
tooManyInts:
mov rdx, InputError2 ;moves InputError2 to rdx
call WriteString ;writes InputError2
jmp exit ;exits
badInput:
cmp rcx, 1 ;if rcx == 1, prints that one value
jmp WriteArrayOne ;jumps to WriteOne which writes first int in the array
mov rdx, InputError3 ;if zero, moves InputError3 to rdx
call WriteString ;writes InputError3
jmp exit ;exits
exit: ;exits program
int 80h

Your [a+rbx*4] and similar all assemble to absolute addressing with 32 bit displacement. You should load the address into a register first, then apply the indexing. For example:
lea rdx, [a]
mov [rdx + rcx*8], rax
Note that a qword is 8 bytes, so you should scale by that, or, if you have 4 byte integers you need to change to 32 bit register.

Related

Segfault when trying to get a byte from memory address

Im trying to make Sieve of Eratosthenes work with big numbers
The problem I have is that it is giving me a segfault but idk why
It works up until about 100k
But the algorithm works if I replace cmp byte [rbx], 0 with cmp dword [rbx], 0
Im very confused as to why that is happening since all the values in the array are 0's and 1's so a byte should be enough
btw with cmp dword [rbx], 0 the results are incorrect so I cant use that
X86 64
%macro crossOut 4
xor rdi, rdi ;edi keeps track of how many numbers were crossed out
;if 0 end loop
mov rbx, %1 ;array
add rbx, %2 ;move position to starting index
mov rax, %3 ;every nth number to be crossed out
mov rbp, %4 ; array length
mov rcx, 0 ;counter
%%loop:
add rcx, rax
cmp rcx, rbp
jge %%exit
add rbx, rax
cmp byte [rbx], 0
je %%crossout
jmp %%loop
%%crossout:
mov byte [rbx], 1
inc rdi
jmp %%loop
%%exit:
cmp rdi, 0
%endmacro
See this CodeReview question for the OP's full program.
You are reading past the end of the numbers buffer because your code does not take into account the 2nd macro parameter (an offset into the array)!
The first time the offset in the array is 0, and the code will run ok. But later you add to the offset while keeping the array length the same, and so memory that does not belong to the array is addressed.
<---- RBP=10 ----->
0,0,0,0,0,0,0,0,0,0
First time RCX allows 4 iterations {2,4,6,8} less than 10:
<---- RBP=10 ----->
RBX
v
0,0,1,0,1,0,1,0,1,0
^ ^ ^ ^
1° 2° 3° 4°
Second time RCX allows 3 iterations {3,6,9} less than 10:
<---- RBP=10 ----->
RBX
v
0,0,1,0,1,0,1,1,1,0,?
^ ^ ^
1° 2° 3°
The 3° is past the buffer and, depending on total array length, at some point this buffer overrun will segfault!
The quick fix is to initialize RCX at the value for the starting index %2 instead of zeroing it.
%macro crossOut 4
xor edi, edi ;edi keeps track of how many numbers were crossed out
;if 0 end loop
mov rbx, %1 ;array
add rbx, %2 ;move position to starting index
mov rax, %3 ;every nth number to be crossed out
mov rbp, %4 ; array length
mov rcx, %2 ;counter
%%loop:
add rcx, rax
cmp rcx, rbp
jge %%exit
add rbx, rax
cmp byte [rbx], 0
je %%crossout
jmp %%loop
%%crossout:
mov byte [rbx], 1
inc rdi
jmp %%loop
%%exit:
cmp rdi, 0
%endmacro
A better fix is to establish an absolute last address that you have RBX compare against:
%macro crossOut 4
xor edi, edi ; EDI keeps track of how many numbers were crossed out
; if 0 end loop
mov rbx, %1 ; array
mov rcx, %4 ; array length
add rcx, rbx ; Last address
add rbx, %2 ; move position to starting index
mov rax, %3 ; every nth number to be crossed out
%%loop:
add rbx, rax
cmp rbx, rcx
jae %%exit
cmp byte [rbx], 0
jne %%loop
%%crossout:
mov byte [rbx], 1
inc rdi
jmp %%loop
%%exit:
cmp rdi, 0
%endmacro
Please notice that
je %%crossout
jmp %%loop
%%crossout:
is better written as
jne %%loop
%%crossout:

Finding Smallest Number in List

My goal in this code is to find the smallest number in the list. I used bubble sort method in this case; unfortunately, the code is not giving me the smallest/minimum number. Please take a look, Thanks:
include irvine32.inc
.data
input byte 100 dup(0)
stringinput byte "Enter any string: ",0
totallength byte "The total length is: ",0
minimum byte "The minimum value is: ",0
.code
stringLength proc
push ebp
mov ebp, esp
push ebx
push ecx
mov eax, 0
mov ebx, [ebp+8]
L1:
mov ecx, [ebx] ;you can use ecx, cx, ch, cl
cmp ecx, 0 ;you can use ecx, cx, ch, cl
JE L2
add ebx, 1
add eax, 1
jmp L1
L2:
pop ecx
pop ebx
mov ebp, esp
pop ebp
ret 4
stringLength endp
BubbleSort PROC uses ECX
push edx
xor ecx,ecx
mov ecx, 50
OUTER_LOOP:
push ecx
xor ecx,ecx
mov ecx,14
mov esi, OFFSET input
COMPARE:
xor ebx,ebx
xor edx,edx
mov bl, byte ptr ds:[esi]
mov dl, byte ptr ds:[esi+1]
cmp bl,dl
jg SWAP1
CONTINUE:
add esi,2
loop COMPARE
mov esi, OFFSET input
pop ecx
loop OUTER_LOOP
jmp FINISHED
SWAP1:
xchg bl,dl
mov byte ptr ds:[esi+1],dl
mov byte ptr ds:[esi],bl
jmp CONTINUE
FINISHED:
pop edx
ret 4
BubbleSort ENDP
main proc
call clrscr
mov edx, offset stringinput
call writeString
mov edx, offset input
call writeString
call stringLength
mov edx, offset input
mov ecx, sizeof input
call readstring
call crlf
mov edx,offset totallength
call writestring
call writedec
call crlf
mov edx, offset minimum
call crlf
call writeString
push offset input
call BubbleSort
mov edx, offset input
call writeString
call crlf
exit
main endp
end main
I haven't looked over your code, because sorting is an over complicated method for what you want to do. Not only that, but most of us don't pay too much attention to uncommented code. Just takes to long to figure out what you're trying to do.
Simply iterate through the entire list and start with 255 (FFH) in AL let's say. Each time you come across a number that is smaller than the one in AL, then replace it with that value and then when loop is finished, AL will have the lowest value.
If you need to know where it is in the list, you could maybe use AH which would be the difference between start address and current address. Knowledge of the instruction set is essential as finding the length of the string can be simplified by;
mov di, input ; Point to beginning of buffer
mov cx, -1 ; for a maximum of 65535 characters
xor al, al ; Looking for NULL
rep scasb
neg cx
dec cx ; CX = length of string.
Remember, ES needs to point to #DATA

NASM ReadConsoleA or WriteConsoleA Buffer Debugging Issue

I am writing a NASM Assembly program on Windows to get the user to enter in two single digit numbers, add these together and then output the result. I am trying to use the Windows API for input and output.
Unfortunately, whilst I can get it to read in one number as soon as the program loops round to get the second the program ends rather than asking for the second value.
The output of the program shown below:
What is interesting is that if I input 1 then the value displayed is one larger so it is adding to something!
This holds for other single digits (2-9) entered as well.
I am pretty sure it is related to how I am using the ReadConsoleA function but I have hit a bit of a wall attempting to find a solution. I have installed gdb to debug the program and assembled it as follows:
nasm -f win64 -g -o task9.obj task9.asm
GoLink /console /entry _main task9.obj kernel32.dll
gdb task9
But I just get the following error:
"C:\Users\Administrator\Desktop/task9.exe": not in executable format: File format not recognized
I have since read that NASM doesn't output the debug information needed for the Win64 format but I am not 100% sure about that. I am fairly sure I have the 64-bit version of GDB installed:
My program is as follows:
extern ExitProcess ;windows API function to exit process
extern WriteConsoleA ;windows API function to write to the console window (ANSI version)
extern ReadConsoleA ;windows API function to read from the console window (ANSI version)
extern GetStdHandle ;windows API to get the for the console handle for input/output
section .data ;the .data section is where variables and constants are defined
STD_OUTPUT_HANDLE equ -11
STD_INPUT_HANDLE equ -10
digits db '0123456789' ;list of digits
input_message db 'Please enter your next number: '
length equ $-input_message
section .bss ;the .bss section is where space is reserved for additional variables
input_buffer: resb 2 ;reserve 64 bits for user input
char_written: resb 4
chars: resb 1 ;reversed for use with write operation
section .text ;the .text section is where the program code goes
global _main ;tells the machine which label to start program execution from
_num_to_str:
cmp rax, 0 ;compare value in rax to 0
jne .convert ;if not equal then jump to label
jmp .output
.convert:
;get next digit value
inc r15 ;increment the counter for next digit
mov rcx, 10
xor rdx, rdx ;clear previous remainder result
div rcx ;divide value in rax by value in rcx
;quotient (result) stored in rax
;remainder stored in rdx
push rdx ;store remainder on the stack
jmp _num_to_str
.output:
pop rdx ;get the last digit from the stack
;convert digit value to ascii character
mov r10, digits ;load the address of the digits into rsi
add r10, rdx ;get the character of the digits string to display
mov rdx, r10 ;digit to print
mov r8, 1 ;one byte to be output
call _print
;decide whether to loop
dec r15 ;reduce remaining digits (having printed one)
cmp r15, 0 ;are there digits left to print?
jne .output ;if not equal then jump to label output
ret
_print:
;get the output handle
mov rcx, STD_OUTPUT_HANDLE ;specifies that the output handle is required
call GetStdHandle ;returns value for handle to rax
mov rcx, rax
mov r9, char_written
call WriteConsoleA
ret
_read:
;get the input handle
mov rcx, STD_INPUT_HANDLE ;specifies that the input handle is required
call GetStdHandle
;get value from keyboard
mov rcx, rax ;place the handle for operation
mov rdx, input_buffer ;set name to receive input from keyboard
mov r8, 2 ;max number of characters to read
mov r9, chars ;stores the number of characters actually read
call ReadConsoleA
movzx r12, byte[input_buffer]
ret
_get_value:
mov rdx, input_message ;move the input message into rdx for function call
mov r8, length ;load the length of the message for function call
call _print
xor r8, r8
xor r9, r9
call _read
.end:
ret
_main:
mov r13, 0 ;counter for values input
mov r14, 0 ;total for calculation
.loop:
xor r12, r12
call _get_value ;get value from user
sub r12, '0' ;convert char to integer
add r14, r12 ;add value to total
;decide whether to loop for another character or not
inc r13
cmp r13, 2
jne .loop
;convert total to ASCII value
mov rax, r14 ;num_to_str expects total in rax
mov r15, 0 ;num_to_str uses r15 as a counter - must be initialised
call _num_to_str
;exit the program
mov rcx, 0 ;exit code
call ExitProcess
I would really appreciate any assistance you can offer either with resolving the issue or how to resolve the issue with gdb.
I found the following issues with your code:
Microsoft x86-64 convention mandates rsp be 16 byte aligned.
You must reserve space for the arguments on the stack, even if you pass them in registers.
Your chars variable needs 4 bytes not 1.
ReadConsole expects 5 arguments.
You should read 3 bytes because ReadConsole returns CR LF. Or you could just ignore leading whitespace.
Your _num_to_str is broken if the input is 0.
Based on Jester's suggestions this is the final program:
extern ExitProcess ;windows API function to exit process
extern WriteConsoleA ;windows API function to write to the console window (ANSI version)
extern ReadConsoleA ;windows API function to read from the console window (ANSI version)
extern GetStdHandle ;windows API to get the for the console handle for input/output
section .data ;the .data section is where variables and constants are defined
STD_OUTPUT_HANDLE equ -11
STD_INPUT_HANDLE equ -10
digits db '0123456789' ;list of digits
input_message db 'Please enter your next number: '
length equ $-input_message
NULL equ 0
section .bss ;the .bss section is where space is reserved for additional variables
input_buffer: resb 3 ;reserve 64 bits for user input
char_written: resb 4
chars: resb 4 ;reversed for use with write operation
section .text ;the .text section is where the program code goes
global _main ;tells the machine which label to start program execution from
_num_to_str:
sub rsp, 32
cmp rax, 0
jne .next_digit
push rax
inc r15
jmp .output
.next_digit:
cmp rax, 0 ;compare value in rax to 0
jne .convert ;if not equal then jump to label
jmp .output
.convert:
;get next digit value
inc r15 ;increment the counter for next digit
mov rcx, 10
xor rdx, rdx ;clear previous remainder result
div rcx ;divide value in rax by value in rcx
;quotient (result) stored in rax
;remainder stored in rdx
sub rsp, 8 ;add space on stack for value
push rdx ;store remainder on the stack
jmp .next_digit
.output:
pop rdx ;get the last digit from the stack
add rsp, 8 ;remove space from stack for popped value
;convert digit value to ascii character
mov r10, digits ;load the address of the digits into rsi
add r10, rdx ;get the character of the digits string to display
mov rdx, r10 ;digit to print
mov r8, 1 ;one byte to be output
call _print
;decide whether to loop
dec r15 ;reduce remaining digits (having printed one)
cmp r15, 0 ;are there digits left to print?
jne .output ;if not equal then jump to label output
add rsp, 32
ret
_print:
sub rsp, 40
;get the output handle
mov rcx, STD_OUTPUT_HANDLE ;specifies that the output handle is required
call GetStdHandle ;returns value for handle to rax
mov rcx, rax
mov r9, char_written
mov rax, qword 0 ;fifth argument
mov qword [rsp+0x20], rax
call WriteConsoleA
add rsp, 40
ret
_read:
sub rsp, 40
;get the input handle
mov rcx, STD_INPUT_HANDLE ;specifies that the input handle is required
call GetStdHandle
;get value from keyboard
mov rcx, rax ;place the handle for operation
xor rdx, rdx
mov rdx, input_buffer ;set name to receive input from keyboard
mov r8, 3 ;max number of characters to read
mov r9, chars ;stores the number of characters actually read
mov rax, qword 0 ;fifth argument
mov qword [rsp+0x20], rax
call ReadConsoleA
movzx r12, byte[input_buffer]
add rsp, 40
ret
_get_value:
sub rsp, 40
mov rdx, input_message ;move the input message into rdx for function call
mov r8, length ;load the length of the message for function call
call _print
call _read
.end:
add rsp, 40
ret
_main:
sub rsp, 40
mov r13, 0 ;counter for values input
mov r14, 0 ;total for calculation
.loop:
call _get_value ;get value from user
sub r12, '0' ;convert char to integer
add r14, r12 ;add value to total
;decide whether to loop for another character or not
inc r13
cmp r13, 2
jne .loop
;convert total to ASCII value
mov rax, r14 ;num_to_str expects total in rax
mov r15, 0 ;num_to_str uses r15 as a counter - must be initialised
call _num_to_str
;exit the program
mov rcx, 0 ;exit code
call ExitProcess
add rsp, 40
ret
As it turned out I was actually missing a 5th argument in the WriteConsole function as well.

How do you do a selection sort in MASM Assembly?

So I'm trying to sort an array in ascending order, and it just doesn't seem to work for me. I know my swap procedure is wrong, and my minIndex procedure only works half the time, but the randomly filled array generates just fine.
Working Code Thanks to vitsoft:
include Irvine32.inc
; Constants
NUM_INTEGERS = 20
NUM_RANGE = 99d
TO_ENSURE_NOT_ZERO = 1d
.data
; Declare Arrays
; Declare Array of 20 Integers
array byte NUM_INTEGERS dup(?)
; Displayed Annotation for Unsorted Array
unsortedArrayText byte "Randomly Generated Array, Unsorted: ", 0dh, 0ah, 0
; Displayed Annotation for Sorted Array
sortedArrayText byte "Randomly Generated Array, Sorted from Lowest to Highest: ", 0dh, 0ah, 0
.code
main PROC
; Get Random Values for Array
call fillArrayRandomly
; Display Array with Annotation
mov edx, offset unsortedArrayText
call WriteString
mov ecx, offset array
push ecx
call displayArray
; Sort Array
mov esi, offset array
mov ecx, NUM_INTEGERS
call findMinimum
mov edi, offset array
mov ecx, NUM_INTEGERS
call selectionSort
; Display Sorted Array with Annotation
mov edx, offset sortedArrayText
call WriteString
mov ecx, offset array
push ecx
call displayArray
; Exit Program
exit
main endp
; Fill Array with Random Values
fillArrayRandomly PROC
; Set Counter to NUM_INTEGERS and Index to 0
mov eax, 0
mov ecx, NUM_INTEGERS
mov esi, 0
getRandomNumber:
; Fill Array with Random Numbers and Increment ESI for Offset
mov ah, NUM_RANGE
call RandomRange
add ah, TO_ENSURE_NOT_ZERO
testUniqueness:
mov al, array [esi]
cmp al, ah
jne uniqueNumber
loop getRandomNumber
uniqueNumber:
mov array [esi], ah
inc esi
loop getRandomNumber
ret
fillArrayRandomly ENDP
; Display Array
displayArray PROC
pushad
mov eax, 0
mov ecx, NUM_INTEGERS
mov esi, 0
display:
mov al, array[esi]
call WriteDec
mov al, TAB
call WriteChar
inc esi
loop display
popad
call Crlf
ret
displayArray ENDP
; Selection Sort
selectionSort PROC
dec ecx
mov ebx, edi
mov edx, ecx
startOuterLoop:
mov edi, ebx
mov esi, edi
inc esi
push ecx
mov ecx, edx
startInnerLoop:
mov al, [esi]
cmp al, [edi]
pushf
inc esi
inc edi
popf
jae doNotSwap
call swap
doNotSwap:
loop startInnerLoop
pop ecx
loop startOuterLoop
ret
selectionSort ENDP
; Find Minimum Index
findMinimum PROC
mov edi, esi
minimumIndex:
mov al, [esi]
cmp al, [edi]
jae skip
mov edi, esi
skip:
inc esi
loop minimumIndex
ret
findMinimum ENDP
; Swap
swap PROC
mov al, [esi - 1]
mov ah, [edi - 1]
mov [esi - 1], ah
mov [edi - 1], al
ret
swap ENDP
END main
LOAD EFFECTIVE ADDRESS computes address of 2nd operand and moves it to the first operand.
lea esi,[edi+1] can be replaced with
mov esi,edi
inc esi
if you don't mind that INC will also change ZERO flag.
You should learn cmpsb and other string instructions ASAP, they are very useful.
cmpsb can be replaced with
MOV AL,[ESI]
CMP AL,[EDI]
PUSHF
INC ESI
INC EDI
POPF
After selectionSort has been called, the minimal value will be in the first field of your array.
Nevertheless, if your assignment was to find a pointer to the minimal value of array, here you are:
findMinimum PROC ; Return EDI=offset of leftmost byte in array with minimal value
; Input: ESI is offset of an byte array, ECX is the size of array
MOV EDI,ESI ; Initialize pointer with so far minimal value
next:MOV AL,[ESI] ; Load next value
CMP AL,[EDI] ; Compare with minimal value so far
JAE skip
MOV EDI,ESI ; Value loaded from [ESI] was below, so ESI is better candidate
skip:INC ESI ; Advance offset in array
LOOP next
RET
findMinimum ENDP
.data
unsortedArrayText DB "Randomly Generated Array, Unsorted: ", 0dh, 0ah, 0
sortedArrayText DB "Randomly Generated Array, Sorted from Lowest to Highest: ", 0dh, 0ah, 0
array DB "An array of bytes (characters) which will be sorted"
NewLine DB 0dh, 0ah, 0
NUM_INTEGERS EQU NewLine - array ; Number of integers (characters) in array
.code
main PROC
; Display Array with Annotation
; mov edx, offset unsortedArrayText
; call WriteString
ConsoleWrite unsortedArrayText
; push offset array
; call displayArray
ConsoleWrite array
; Sort Array
; push offset array
; call selectionSort
MOV EDI,array
MOV ECX,NUM_INTEGERS
CALL selectionSort
; Display Sorted Array with Annotation
; mov edx, offset sortedArrayText
; call WriteString
ConsoleWrite sortedArrayText
; push offset array
; call displayArray
ConsoleWrite array
; Exit Program
;exit
TerminateProgram
main endp
; Selection Sort
selectionSort PROC ; Bubble sort ECX byte array pointed to with EDI
DEC ECX ; Number of compare is NUM_INTEGERS-1
MOV EBX,EDI ; Save array pointer to EBX
MOV EDX,ECX ; Save number of compare to EDX
OuterLoop:
MOV EDI,EBX ; Restore array pointer
LEA ESI,[EDI+1] ; Neibourghing field
PUSH ECX ; Save OuterLoop counter on stack
MOV ECX,EDX ; Initialize InnerLoop counter
InnerLoop:
CMPSB ; compare the first byte [EDI] with its neibourgh [ESI], advance EDI,ESI
JAE NoSwap
CALL swap
NoSwap:
LOOP InnerLoop
POP ECX ; Restore OuterLoop counter
LOOP OuterLoop
RET
selectionSort ENDP
swap PROC ; Swap bytes at [EDI-1] and [ESI-1]
MOV AL,[ESI-1]
MOV AH,[EDI-1]
MOV [ESI-1],AH
MOV [EDI-1],AL
RET
swap ENDP
This worked well, statically defined array was sorted in few miliseconds:
C:\ASM>bubblesortexample.exe
Randomly Generated Array, Unsorted:
An array of bytes (characters) which will be sorted
Randomly Generated Array, Sorted from Lowest to Highest:
()Aaaaabbcccdeeeefhhhiillnoorrrrrssstttwwyy
C:\ASM>

Selection sort procedure in assembly

I think I'm having trouble with my swap, and how I'm accessing the elements in my array. Right now, all of the code runs, but the list does not change after the sort. He's the high level sort I'm trying to implement
for(k=0; k<request-1; k++) {
i = k;
for(j=k+1; j<request; j++) {
if(array[j] > array[i])
i = j;
}
exchange(array[k], array[i]);
}
Here's the assembly code. Note: the assignment is about pushing and popping elements on/off the stack, so I can't change the parameters.
;this is a library with macros for things like printing numbers and strings
INCLUDE Irvine32.inc
MIN = 10 ;lower range limit
MAX = 200 ;upper range limit
LRANGE = 100
HRANGE = 999
.data
;title, intro, and prompts
title_1 BYTE "PROGRAMMING ASSIGNMENT 5: RANDOM GEN/SORT", 0dh, 0ah, 0
intro_1 BYTE "This program generates random numbers in the range (100 - 999),", 0dh, 0ah
BYTE "displays the original list, sorts the list, and calculates the median value.", 0dh, 0ah
BYTE "Finally, it displays the sorted list in descending order.", 0dh, 0ah, 0
prompt_1 BYTE "How many numbers should be generated? (10 - 200): ", 0
error_1 BYTE "Out of range.", 0dh, 0ah, 0
display_1 BYTE "List of random numbers: ", 0dh, 0ah, 0
display_2 BYTE "The median is: ", 0
display_3 BYTE "The sorted list: ", 0dh, 0ah, 0
;placeholders for user entries and calculated data
randArray DWORD MAX DUP(?)
userNum DWORD ? ;integer to be entered by user
;strings for posting results
goodBye_1 BYTE "Thank you for using the Gen/sort-ulator! Good-bye!", 0
.code
main PROC
call Randomize
;Title Screen
push OFFSET title_1
push OFFSET intro_1
call Intro
;Get and validate user numbers
push OFFSET error_1
push OFFSET prompt_1
push OFFSET userNum
call GetData
;Fill Array with random numbers
push OFFSET randArray
push userNum
call FillArray
;display unsorted results
push OFFSET randArray
push userNum
push OFFSET display_1
call DisplayList
;sort the results
push OFFSET randArray
push userNum
call SortList
;display the median
push OFFSET randArray
push userNum
push OFFSET display_2
call median
;display sorted results
push OFFSET randArray
push userNum
push OFFSET display_3
call DisplayList
;Say "goodbye"
push OFFSET goodBye_1
call Goodbye
exit ; exit to operating system
main ENDP
;-------------------------------------------------------
;Gives an Intro to the program
; Receives parameters on the system stack (in the order pushed):
; Address of the title
; Address of the intro
;post: intro displayed
;registers: none
;-------------------------------------------------------
Intro PROC
pushad
mov ebp, esp
mov edx, [ebp+40]
call writeString
call CrLf
mov edx, [ebp+36]
call writeString
call CrLf
popad
ret 8
Intro ENDP
;-------------------------------------------------------
;Prompts user for an integer, int stores in userNum
; Receives parameters on the system stack (in the order pushed):
; Address of the error message
; Address of the prompt
; Address of return value
;Post: userNum
;registers: none
;-------------------------------------------------------
GetData PROC
pushad
;setup stack and prompt for entry
mov ebp, esp
reenter:
mov edx, [ebp+40]
mov ebx, [ebp+36]
call WriteString
call ReadInt
;validate entry
cmp eax, MIN ;if eax < LOWER
jl badEntry ;jump to summary
cmp eax, MAX ;if eax > UPPER
jg badEntry ;reprompt
jmp goodEntry ;else jump to end, we have a good value
;bad entry reprompt
badEntry:
mov edx, [ebp+44]
call WriteString
jmp reenter
goodEntry:
call CrLf
mov [ebx], eax
popad
ret 12
GetData ENDP
;-------------------------------------------------------
;Fills array with a number of random integers within RANGE
;Recieves parameters on the system stack (in order pushed)
; array
; userNum
;Post: array is filled with userNum number of randoms
;Registers used: none
;-------------------------------------------------------
FillArray PROC
pushad
mov ebp, esp
mov ecx, [ebp+36] ;initialize loop counter with user entry
mov edi, [ebp+40] ;setup array offset
fillLoop:
call nextRand
add edi, 4
loop fillLoop
popad
ret 8
FillArray ENDP
;-------------------------------------------------------
; Procedure nextRand
; adapted from check lecture 20 solutions
; Procedure to get the next random number in the range specified by the user.
; Preconditions: LRANGE < HRANGE
; Registers used: eax, edi
;-------------------------------------------------------
nextRand PROC
mov eax, HRANGE
sub eax, LRANGE
inc eax ;add 1 to get the number of integers in range
call RandomRange
add eax, LRANGE ;eax has value in [LOW - HIGH]
mov [edi],eax
ret
nextRand ENDP
;-------------------------------------------------------
;Sorts the contents of an integer array
; Receives parameters on the system stack (in order pushed)
; Array
; Array Size
;registers: none
;-------------------------------------------------------
sortList PROC
pushad
mov ebp, esp
mov ecx, [ebp+36]
mov edi, [ebp+40]
dec ecx ;ecx < request-1
mov ebx, 0 ;ebx=k
;for(k=0; k<request-1; k++)
outerLoop:
mov eax, ebx ;eax=i=k
mov edx, eax
inc edx ;edx=j=k+1
push ecx
mov ecx, [ebp+36] ;ecx < request
;for(j=k+1; j<request; j++)
innerLoop:
mov esi, [edi+edx*4]
cmp esi, [edi+eax*4]
jle skip
mov eax, edx
skip:
inc edx
loop innerLoop
;swap elements
lea esi, [edi+ebx*4]
push esi
lea esi, [edi+eax*4]
push esi
call exchange
pop ecx
inc ebx
loop outerLoop
popad
ret 8
sortList ENDP
;-------------------------------------------------------
; Exchange k and i
; Receives parameters on the system stack (in order pushed)
; array[k]
; array[i]
;registers: none
;-------------------------------------------------------
Exchange PROC
pushad
mov ebp,esp
mov eax, [ebp+40] ;array[k] low number
mov ecx, [eax]
mov ebx, [ebp+36] ;array[i] high number
mov edx, [ebx]
mov [eax], edx
mov [ebx], ecx
popad
ret 8
Exchange ENDP
;-------------------------------------------------------
;Displays the median of an integer array
; Receives parameters on the system stack (in order pushed)
; Array
; Array Size
; display string
;registers: none
;-------------------------------------------------------
Median PROC
pushad
mov ebp, esp
mov edi, [ebp+44]
;display string
mov edx, [ebp+36]
call writeString
;calculate median element
mov eax, [ebp+40]
cdq
mov ebx, 2
div ebx
shl eax, 2
add edi, eax
cmp edx, 0
je isEven
;Array size is odd, so display the middle value
mov eax, [edi]
call writeDec
call CrLf
call CrLf
jmp endMedian
isEven:
;Array size is even so average the two middle values
mov eax, [edi]
add eax, [edi-4]
cdq
mov ebx, 2
div ebx
call WriteDec
call CrLf
call CrLf
endMedian:
popad
ret 12
Median ENDP
;-------------------------------------------------------
;Displays the contents of an integer array, 10 per row
; Receives parameters on the system stack (in order pushed)
; Array
; Array Size
; display string
;registers: none
;-------------------------------------------------------
DisplayList PROC
pushad
mov ebp, esp
;display string
mov edx, [ebp+36]
call writeString
call CrLf
mov ecx, [ebp+40]
mov edi, [ebp+44]
mov ebx, 0
;display array contents
listloop:
inc ebx ;counter for 10 items per row
mov eax, [edi]
call writeDec
add edi, 4
cmp ebx, 10
jne noReturn ;jump if 10 items are not yet printed
call CrLf
mov ebx, 0
jmp noTab ;this skips adding a tab on a new row
noReturn:
mov al, TAB
call writeChar
noTab:
loop listloop
call CrLf
popad
ret 12
DisplayList ENDP
;-------------------------------------------------------
;Says good-bye to the user
; Receives parameters on the system stack:
; Address of string
;registers: none
;-------------------------------------------------------
Goodbye PROC
pushad
mov ebp, esp
mov edx, [ebp+36]
call writeString
call CrLf
popad
ret 4
Goodbye ENDP
END main
In order to exchange elements you should be passing their address (in other words, a pointer to each). What you did was just swapping the values passed as parameters, which were also immediately freed. Your code is the equivalent of this C function:
void Exchange(int x, int y)
{
int eax = x;
int ebx = y;
x = ebx;
y = eax;
}
You need something like:
void Exchange(int* x, int* y)
{
int eax = *x;
int ebx = *y;
*x = ebx;
*y = eax;
}
In asm, that may look like:
Exchange PROC
pushad
mov eax, [esp+40]
mov ecx, [eax]
mov ebx, [esp+36]
mov edx, [ebx]
mov [eax], edx
mov [ebx], ecx
popad
ret 8
Exchange ENDP
To call this function you would use the following:
lea esi, [edi+ebx*4]
push esi
lea esi, [edi+eax*4]
push esi
call Exchange
Note your Exchange function had an instruction mov eax, [edi] which I couldn't make sense of.
Update: Yes, you can emulate the functionality of LEA by doing the calculations manually. For example, lea esi, [edi+ebx*4] becomes:
mov esi, ebx
shl esi, 2 ; esi=ebx*4
add esi, edi ; esi=edi+ebx*4

Resources