Reputation: 69
I know if you want say two characters input, you'd use:
input_str: .ascii "??"
and then later:
mov $2, %edx
such as in:
.data
input_str: .ascii "??"
.text
.global _start
_start:
mov $3, %eax # eax = 3 = function number for "read"
mov $0, %ebx # ebx = 0 = file descriptor (stdin)
mov $input_str, %ecx # ecx = address of input buffer
mov $2, %edx # edx = buffer maximum size
int $0x80 # Call Linux kernel API
# eax = error code or number of bytes read
etc...
But what if you were asking for a sentence of random length? How do you read how many there after input?
Upvotes: 0
Views: 1340
Reputation: 7051
There are different tricks to handle random length data and all of them need dynamically allocated memory.
The simplest way to provide it in Linux is to use sys_brk function, but it allows only one memory block to be allocated.
There are libraries that provide heap management. One such library, entirely in assembly language is FreshLib. Another option is to link with the C standard library.
Then, there are two cases to read the data in the dynamically allocated buffer, depending on whether or not you know the data length in advance (in run time).
It is simple - allocate the buffer with the needed size and read the data entirely.
The only possible way to read stream data in the memory is to read a fixed chunks of this data and then to copy it into the dynamically allocated buffer. When the buffer is filled up, you need to reallocate it with bigger size and then to continue until the all data is read.
Note, that the memory reallocation is expensive operation, so it is better to allocate more than needed memory. Common algorithm is to double the size of the allocated memory on every reallocation. Personally I think this strategy is too aggressive and often use multiplying the size by 1.5;
It is often possible to not read the whole data in the memory, but to process it on the fly as it is read in small fixed chunks. This method needs a little bit more complex algorithms, but has the big advantage to use very small memory, not need dynamically allocated memory and avoids the copy of the data between multiply memory locations.
Upvotes: 1