Re: [PATCH 10/13] gdbsupport: add xstrcpy
Simon Marchi <[email protected]>
| Newsgroups | gmane.comp.gdb.patches,gmane.comp.gnu.binutils |
|---|---|
| Message-ID | <[email protected]> |
On 8/17/26 12:45 PM, Andrew Burgess wrote: > Simon Marchi <[email protected]> writes: > >> Add xstrcpy, a "safe" alternative to strcpy. It works like strcpy, but >> accepts the size of the destination buffer, and asserts that the string >> fits in it. >> >> Return the number of characters copied, so that it's possible to easily >> chain calls like this: >> >> p += xstrcpy (p, end - p, ",C"); > > Don't functions that take a buffer size usually include an 'n' in the > name. That seems to be true for libc, but also throughout GDB. Would > it not be a good idea to adopt that here too. > > This isn't exactly strncpy, but it seems similar. While strncpy can > result in a non-null terminated output string, this "xstrncpy" asserts > that the source fits into the output buffer without being truncated. > But otherwise, it's the same function I think? I hesitated about naming it strncpy. I decided against it because the new function doesn't behave exactly like strcnpy on one specific point: if the source is smaller than destination, strncpy fills the remainder of the destination buffer with zeroes. Not sure if that matters in practice, but it could be the source of a subtle bug if one blindly switches strncpy for xstrncpy. Both strcpy and strncpy return a pointer to the beginning of the destination buffer, which is different than my xstrcpy, which returns the number of bytes written. The latter seems more useful to me, as it makes it possible to easily chain the calls. It seems like xstrcpy is more like a wrapper for strlcpy, so we could always call it xstrlcpy. The only thing is that the argument order is not the same: int xstrcpy (char *dst, size_t size, const char *src); size_t strlcpy (char *dst, const char *src, size_t size); So if we named it xstrlcpy, I would want to match xstrlcpy's argument order, otherwise it's just confusing. Personally, I don't strlcpy's argument order as much, because `size` describes `dst`, so I like having it right next to it. But I could live with it. I just noticed that strcpy_s exists in C11, and it is in the same order as xstrcpy: errno_t strcpy_s (char* restrict dest, rsize_t destsz, const char* restrict src); It looks like we could use that, but we also want to return the number of bytes written, which this does not provide. I also considered accepting `dst` as a `gdb::array_view<char>`, which would side-step the argument order problem, but the caller's are not really ready for that, so their would look look awkward. In any case, I still believe that the xstrcpy makes sense, because it is really like "strcpy, but safe". Given all this, what would be your choice? Simon