samuelbrody1249
samuelbrody1249

Reputation: 4767

Short-form to get string length in assembly

To get the length of a string, I am using the following function:

string:     .asciz "hello world!\n"
get_string_length:
    mov $0, %eax    # size goes in rax
  .L1_loop:
    movzbw string(,%eax,1), %ebx
    cmp $0, %ebx
    je .L1_exit
    inc %eax
    jmp .L1_loop
  .L1_exit:
    ret

However, I have also seen the following:

hello_world:
    .ascii "hello world\n"
    hello_world_len = . - hello_world

How does the following work? That is the . notation and all to get the length? For example, in this github snippet here: https://github.com/cirosantilli/linux-kernel-module-cheat/blob/9dccafe00d9b0affa8847836a71ebb4c37be7090/userland/arch/x86_64/freestanding/linux/hello.S

Upvotes: 3

Views: 3223

Answers (1)

zx485
zx485

Reputation: 29052

The first version determines the length at run-time and the second version sets the length at assembly time.

The . in the second expression represents the current address (in the data segment). Then, the expression

hello_world_len = . - hello_world

subtracts the starting address of the string .ascii "hello world\n"indicated by the label hello_world: from the current address(indicated by the .) resulting in the length value hello_world_len.

Upvotes: 7

Related Questions