qemu-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Better alternative to strncpy in QEMU.


From: Paolo Bonzini
Subject: Re: Better alternative to strncpy in QEMU.
Date: Tue, 13 Apr 2021 09:32:22 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Thunderbird/78.7.0

On 12/04/21 06:51, Thomas Huth wrote:


I think this is pretty much the same as g_strlcpy() from the glib:

https://developer.gnome.org/glib/2.66/glib-String-Utility-Functions.html#g-strlcpy
So I guess Paolo had something different in mind when adding this task?

Yes, I did. strncpy is used legitimately when placing data in a fixed-size buffer that is written to a socket, to a file or to guest memory. The problem with using g_strlcpy in those cases is that it does not write past the first '\0' character, and therefore it can leak host data.

What I had in mind was basically strncpy plus an assertion that the last copied byte will be set to 0. It can be written in many ways, for example strncpy followed by assert(dest[destlen - 1] == '\0'), or like assert(strlen(src) < destlen) followed by strncpy, or of course you could write a for loop by hand.

Once you do that, you can split uses of strncpy in two: those where the reader expects the last byte to be zero, and those where the reader does not. (I don't expect many cases of the first type, because the reader always has to think of how to handle a malicious data stream that does not have a zero termination).

As long as you avoid the accidentally quadratic behavior that Peter pointed out, any way is fine since performance does not matter on these paths. Making the code nice and readable is more important.

Paolo




reply via email to

[Prev in Thread] Current Thread [Next in Thread]