Daros911
Daros911

Reputation: 435

Assembler printf function strange behavior

I've opened a simple Hello World program in IDA (Pro 7.5) like that:

    global  _main
    extern  _printf

    section .text
_main:
    push    message
    call    _printf
    add     esp, 4
    push    message2
    call    _printf
    add     esp, 4
    ret
message:
    db  'Hello, World 1', 0xD, 0xA, 0 
message2:
    db  'Hello, World 2', 0xD, 0xA, 0

Now i've made a simple detour - moved the code and data definition to the unused end of the code segment like this:

str1  db 'Hello, World1',0Dh,0Ah,0
                                         ; DATA XREF: .text:detour↓o
str2  db 'Hello, World2',0Dh,0Ah,0
                                         ; DATA XREF: .text:00404057↓o
str3  db 'Hello, World3',0Dh,0Ah,0
                                         ; DATA XREF: .text:00404064↓o↓o
      db    0
      db    0
 ; ---------------------------------------------------------------------------

 detour:                                 ; CODE XREF: .text:_main↑j
   push    offset str1     ; "Hello, World 1\r\n"
   call    _printf
   add     esp, 4
   push    offset str2     ; "Hello, World 2\r\n"
   call    _printf
   add     esp, 4
   push    offset str3     ; "Hello, World 3\r\n"
   call    _printf
   add     esp, 4
   jmp     go_back

Leaving in the main function only the jmp code like that:

_main:                                 
  jmp detour
go_back:                              
  retn

And this yeiled me a problem. The output of the patched program is :

Hello, World1

Hello, World2

Hello, World3

ABh@@Hello, World2

Hello, World3

ABh@@Hello, World3

ABh@@

Instead just:

Hello, World 1
Hello, World 2
Hello, World 3

Where do that extra 3 lines an empty rows

ABh@@Hello, World2

Hello, World3

ABh@@Hello, World3

ABh@@

come from?

Upvotes: 0

Views: 134

Answers (1)

nevilad
nevilad

Reputation: 985

Printf prints strings until it finds a zero symbol.

Your original strings are zero terminated (0 at the end):

db  'Hello, World 1', 0xD, 0xA, 0 

The new one, except str3, are not:

str1  db 'Hello, World 1',0Dh,0Ah
str2  db 'Hello, World 2',0Dh,0Ah
str3  db 'Hello, World 3',0Dh,0Ah
      db    0

Thus the first printf call prints all 3 strings, the second str2 and str3, and the third str3.

Upvotes: 1

Related Questions