Author Topic: Problems understanding code  (Read 10962 times)

Offline ceeman

  • Jr. Member
  • *
  • Posts: 2
Problems understanding code
« on: December 09, 2020, 08:51:31 PM »
section .text
    global _start
   
_start:
    xor edx, edx
    xor ebx, ebx
    mov ecx, STR1

looptop:
    cmp byte[ecx], 0
    je loopend
    cmp byte[ecx], 65
    jge inc_fun
    inc edx
    jmp loopbot
   
inc_fun:   
    inc ebx
   
loopbot:
    inc ecx
    jmp looptop
   
loopend:
    mov eax, 1
    int 0x80

section .data
    STR1 db 'Hello, DAT103',0xa,0x0


I have this code, but can seem to put my head around it.
Most of all i wonder what happens when ecx is set to STR1, and what happens when comparing byte[ecx],0.
I can't see how it prints anything at all either, but the solution says it is 8.
Anyone can figure this out? Thanks.

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: Problems understanding code
« Reply #1 on: December 09, 2020, 10:31:58 PM »
Hi ceeman,

Welcome to the forum.

Why?

I think we can figure out what this code does, but I doubt if we can figure out why !

Code: [Select]
mov ecx. STR1
puts the address ("offset") of the string into the register. Straightforward enough...
Code: [Select]
cmp byte [ecx], 0
will find the end of the string when we get there. In the meantime, we seem to count lowercase letters... into ebx... When we hit the sys_exit, this will be the exit code. If you type "echo ?$" Linux will print this exit code. I don't know where "8" might come from. Perhaps better to ask where you found the code?

Best,
Frank









Offline debs3759

  • Global Moderator
  • Full Member
  • *****
  • Posts: 224
  • Country: gb
    • GPUZoo
Re: Problems understanding code
« Reply #2 on: December 09, 2020, 11:43:18 PM »
It looks to me like you are counting the number of ASCII characters that are equal to or greater than "A", which gives you the result 8. That's "Hello" and "DAT".

What are you expecting?
My graphics card database: www.gpuzoo.com

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: Problems understanding code
« Reply #3 on: December 09, 2020, 11:59:21 PM »
Ah, right you are - greater than 'A', not greater than 'a'. Thank you!

Best,
Frank


Offline ceeman

  • Jr. Member
  • *
  • Posts: 2
Re: Problems understanding code
« Reply #4 on: December 10, 2020, 10:53:40 AM »
Hello, and thanks for the replies. This code was from an exam where they asked for:
a) What is the result that the exit() syscall passes to a caller, for example, the shell if you run the program from the command line? (Line 12: cmp byte[ecx], 97) Solution: 4
b) What is the result if Line 12 in program is replaced by cmp byte[ecx], 65? (Originally it was cmp byte[ecx], 97). Solution: 8.

Thanks for the explanation, it made way more sense now. Thank you!