Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

linux - Assembly: printf not printing new line

I have the following code that prints the number of parameters passed to ./main. Notice the fmt in the rodata section. I've included the new line , just like in C, but instead of printing the new line, it prints:

Number of parameters: 1

My code is:

;main.asm
GLOBAL main
EXTERN printf

section .rodata:
fmt db "Number of parameters: %d 
", 0 

section .text:

main:

    push ebp
    mov ebp, esp    ;stackframe

    push dword[ebp+8]       ;prepara los parametros para printf
    push fmt
    call printf
    add esp, 2*4

    mov eax, 0      ;return value

    leave           ;desarmado del stack frame
    ret

I know that including a 10 before the 0 and after the "Number..." in fmt will print it, but I want printf to do it. I assemble the code with NASM and then link it via GCC to create my executable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you use quotes or double quotes around a string in NASM, it doesn't accept C style escape sequences. On Linux you can encode as ASCII 10 like this:

fmt db "Number of parameters: %d", 10, 0 

There is an alternative. NASM supports backquotes (backticks) which will allow NASM to process the characters between them as C style escape sequences. This should work as well:

fmt db `Number of parameters: %d 
`, 0

Please note: Those are not single quotes, but backticks. This is described in the NASM documentation:

3.4.2 Character Strings

A character string consists of up to eight characters enclosed in either single quotes ('...'), double quotes ("...") or backquotes (...). Single or double quotes are equivalent to NASM (except of course that surrounding the constant with single quotes allows double quotes to appear within it and vice versa); the contents of those are represented verbatim. Strings enclosed in backquotes support C-style -escapes for special characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...