0
votes

I am trying to use the strstr C function in a NASM assembly program but cannot seem to get it to print out correctly. I have tried multiple variations of this, but I think I may be misinterpreting how NASM returns the pointer value from C as I either get a blank line returned in the printf or a '(null)'. Could some help fill me in as why I cannot get the correct return value to be printed?

section .data

    str1 db "Here is some text with a word",0x0A,0x00
    str2 db "text",0x0A, 0x00
    strFmt db "%s",0x0A,0x00

    global _start
    extern printf
    extern strstr

section .text

_start:

    push ebp
    mov ebp, esi

    push str2
    push str1
    call strstr
    add esp, 8

    mov dword [myString], eax

    push dword [myString]
    push strFmt
    call printf
    add esp, 8

_exit:
    mov ebx, 0
    mov eax, 1
    int 0x80
1
This looks like a typo: mov ebp, esi. I'll bet you meant for the source to be esp there. Also, what is myString? That's not defined in the code you've shown, even though you use it. Why not just push eax directly? - Cody Gray
I see you use int 0x80, so I assume this is Linux or macOS. Please, next time, add this information in your question. Things are slightly different on, say, Windows. - Rudy Velthuis

1 Answers

1
votes

The main issue is the 0x0A in the search string. It's a part of the string, as everything before the terminating null is a part of it. It must be listed separately because C-style escape sequences inside strings won't be resolved by the assembler. A "test\n" won't be found by strstr. Remove the 0x0A and strstr will found the search string.

As Cody Gray mentioned, the block with mov ebp, esi is strange—you probably meant the idiomatic mov ebp, esp. Moreover, it's not needed in this example. Also superfluous is the indirection with myString—just push eax directly.

printf writes the output first to a buffer. You exit the program with a int 80h system call. This call will destroy everything of the process including the printf-buffer. So the buffer won't be outputted. There are two ways to solve the problem:

1) Use the C function exit instead of the system call:

section .data
    str1 db "Here is some text with a word",0x0A,0x00
    str2 db "text",0x00
    strFmt db "%s",0x0A,0x00

global _start
extern printf, strstr, exit

section .text

_start:

    push str2
    push str1
    call strstr
    add esp, 8

    push eax
    push strFmt
    call printf
    add esp, 8

_exit:
    push 0
    call exit

2) Add a call to the C function fflush:

section .data
    str1 db "Here is some text with a word",0x0A,0x00
    str2 db "text",0x00
    strFmt db "%s",0x0A,0x00

global _start
extern printf, strstr, fflush

section .text

_start:

    push str2
    push str1
    call strstr
    add esp, 8

    push eax
    push strFmt
    call printf
    add esp, 8

    push 0
    call fflush

_exit:
    mov ebx, 0
    mov eax, 1
    int 0x80