Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a fixed-length padded string in GNU assembler

Tags:

assembly

gnu

arm

I'm trying to define some data in a fixed-size structure in assembler. I'd like to declare string data of a fixed number of bytes, initialised with a string. In C it would be:

char my_string[32] = "hello";

Which is 32 bytes, and padded with however many zeros needed at the end.

What would be the equivalent in assembler? I know I can manually count the length of my string and declare the necessary number of zero bytes to pad to 32, e.g.:

my_string:
  .asciz "hello"
  .zero 26

But how can I do it if the string is being defined dynamically, such as from an external define or include?

like image 493
Craig McQueen Avatar asked Mar 06 '26 15:03

Craig McQueen


2 Answers

I think I'd use a macro with local labels for this. For example:

    .macro padded_string string, max
1:
    .ascii "\string"
2:
    .iflt \max - (2b - 1b)
    .error "String too long"
    .endif

    .ifgt \max - (2b - 1b)
    .zero \max - (2b - 1b)
    .endif

    .endm

...used like this:

my_string:
    padded_string "Hello world!", 16

(This has C-like behaviour of not adding the terminating 0 if the string is exactly max characters long. To ensure the string is terminated, just change the .ascii to .asciz.)

like image 66
Matthew Slattery Avatar answered Mar 08 '26 13:03

Matthew Slattery


What you are describing is still a static string, albeit of unknown size. You can get the size of the string my subtracting the address of the string from current data pointer ($). Subtract the size of the string from the maximum size and you know how many zeroes to add:

my_string:
    .ascii "mystery string"
    .zero (maxsize-($-my_string)) ;maxsize-actualsize

which can be simplified to:

my_string:
    .ascii "mystery string"
    .zero (maxsize+my_string-$)
like image 30
Jens Björnhager Avatar answered Mar 08 '26 12:03

Jens Björnhager