0

My code is required to have a string that will be printed to the console, alongside a string length counting program that will count it instead of manually putting length of string in edx register. But i am getting strange characters printed right after the string is printed.


global          _start

section         .text

_start:

  mov           edi, message
  call          _strlen
  mov           edx, eax

  mov           eax, 4
  mov           ebx, 1
  mov           ecx, message
  int 80h

  mov           eax, 1
  mov           ebx, 5
  int 80h

 section         .data
message: db     "My name is Stanley Hudson", 0Ah
_strlen:

  push          ebx
  push          ecx

  mov           ebx, edi
  xor           al, al
  mov           ecx, 0xffffffff

  repne         scasb               ; REPeat while Not Equal [edi] != al

  sub           edi, ebx            ; length = offset of (edi – ebx)
  mov           eax, edi

  pop           ebx
  pop           ecx
  ret

Here is the output

Akash
  • 3
  • 1
  • Please provide output right in the question itself, instead of some link .See [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Shivam Jha Sep 26 '20 at 19:30

2 Answers2

2

strlen searches for a 0 byte terminating the string, but your string doesn't have one, so it goes until it does find a zero byte and returns a value that's too large.

You want to write

message: db     "My name is Stanley Hudson", 0Ah, 0
                                               ; ^^^

Another bug is that your _strlen function is apparently in the .data section, because you didn't go back to section .text after your string. x86-32 doesn't have the NX bit so the .data section is executable and everything still works, but it's surely not what you intend.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • 1
    The .data section is executable when that source is built with nasm && ld even if you run under an x86-64 kernel, unless you manually set `section .note.GNU-stack noalloc noexec nowrite progbits` to override the strange nasm + `ld` default of ending up with a binary with Linux's `READ_IMPLIES_EXEC` (what `-zexecstack` uses): [Unexpected exec permission from mmap when assembly files included in the project](//stackoverflow.com/q/58260465). Besides, x86-32 *does* have the NX bit in PAE page tables, in case anyone actually was running a 32-bit kernel, not just 32-bit code under 64-bit kernel. – Peter Cordes Sep 25 '20 at 04:33
  • NASM version of that Q&A [Why data and stack segments are executable?](https://stackoverflow.com/q/7863200) – Peter Cordes Sep 25 '20 at 04:35
  • @Nate thank you so much. It worked. Im very new to this language and im glad to have this kind of community. – Akash Sep 25 '20 at 14:21
-1

To get rid of the special characters write the strlen function before the start process and create a new register for the newline character

M.Sajid
  • 63
  • 1
  • 1
  • 5