threads / rfc / 52832

patch, 2 partsRe: [GSoC][RFC][PATCH 2/2] STRBUF_INIT_CONST: Adapting strbuf_* functions

Subject: Re: [GSoC][RFC][PATCH 2/2] STRBUF_INIT_CONST: Adapting strbuf_* functions

## tl;dr

8 messages between Feb 18, 2020 and Feb 19, 2020. Diffs are folded; open one to read it.

replies: 7people: 4as markdown or json

Abhishek Kumar· Feb 18, 2020, 09:30 UTC · lore
Greetings Robear,

I don't have the expertise to talk about the larger picture here, but I have the following suggestions if you do go with it.

I don't agree with this patchset being two different patches - The changes in the second patch eliminate possibly buggy behavior of using the new function.

I would also prefer the term "immutable" over "const" since const already has implications in C programming.

> STRBUF_INIT_CONST: a new way to initialize strbuf

Use imperative mood and be more specific in the commit title - `strbuf: Teach strbuf to initialize immutable strings`

> In a previous commit, a new function `STRBUF_INIT_CONST(const_str)`,
> which would allow for the quick initialization of constant `strbuf`s,
> was introduced.
Redundant if you merge both patches.

In this commit, I check through the strbuf_* functions to edit the ones that would try to edit the passed `strbuf` so that they are guaranteed to behave in a predictable way when met with a constant.

Show 14 quoted lines
> Added Functions:
>   `strbuf_make_var`
>
> Updated Functions:
>   `strbuf_grow`
>   `strbuf_setlen`
>   `strbuf_trim`
>    `strbuf_trim_trailing_dir_sep`
>    `strbuf_trim_trailing_newline`
>    `strbuf_tolower`
>    `strbuf_splice`
>
> Functions where comments were added to clarify the expected behavior:
>    `strbuf_getcwd`
I feel this is self-explanatory when you go through the diff.
Signed-off-by: Robear Selwans <robear.selwans@outlook.com>
---
 strbuf.c | 25 +++++++++++++++++++++++++
 strbuf.h | 14 ++++++++++++++
 2 files changed, 39 insertions(+)
Show changes to 2 files +23 −1

strbuf.c, strbuf.h

diff --git a/strbuf.c b/strbuf.c
index f19da55b07..48af039b6e 100644
--- a/strbuf.c
+++ b/strbuf.c
@@ -89,6 +89,8 @@ void strbuf_attach(struct strbuf *sb, void *buf,
size_t len, size_t alloc)

 void strbuf_grow(struct strbuf *sb, size_t extra)
 {
+    if (sb->len > sb->alloc)
+        strbuf_make_var(sb);
     int new_buf = !sb->alloc;
     if (unsigned_add_overflows(extra, 1) ||
         unsigned_add_overflows(sb->len, extra + 1))
@@ -100,8 +102,18 @@ void strbuf_grow(struct strbuf *sb, size_t extra)
         sb->buf[0] = '\0';
 }

+void strbuf_make_var(struct strbuf *sb)
+{
+    char* str_cpy;
+    ALLOC_ARRAY(str_cpy, sb->len + 1);
+    memcpy(str_cpy, sb->buf, sb->len);
+    strbuf_attach(sb, str_cpy, sb->len, sb->len + 1);
+}
+
 void strbuf_trim(struct strbuf *sb)
 {
+    if (sb->len > sb->alloc)
+        strbuf_make_var(sb);
     strbuf_rtrim(sb);
     strbuf_ltrim(sb);
 }
@@ -115,6 +127,8 @@ void strbuf_rtrim(struct strbuf *sb)

 void strbuf_trim_trailing_dir_sep(struct strbuf *sb)
 {
+    if (sb->len > sb->alloc)
+        strbuf_make_var(sb);
     while (sb->len > 0 && is_dir_sep((unsigned char)sb->buf[sb->len - 1]))
         sb->len--;
     sb->buf[sb->len] = '\0';
@@ -122,6 +136,9 @@ void strbuf_trim_trailing_dir_sep(struct strbuf *sb)

 void strbuf_trim_trailing_newline(struct strbuf *sb)
 {
+    if (sb->buf[sb->len - 1] == '\n')
> +        if (sb->len > sb->alloc)
> +            strbuf_make_var(sb);

Enclose this explicitly in braces.

     if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {
         if (--sb->len > 0 && sb->buf[sb->len - 1] == '\r')
             --sb->len;
@@ -158,6 +175,8 @@ int strbuf_reencode(struct strbuf *sb, const char
*from, const char *to)

 void strbuf_tolower(struct strbuf *sb)
 {
+    if (sb->len > sb->alloc)
+        strbuf_make_var(sb);
     char *p = sb->buf, *end = sb->buf + sb->len;
     for (; p < end; p++)
         *p = tolower(*p);
@@ -234,6 +253,8 @@ void strbuf_splice(struct strbuf *sb, size_t pos,
size_t len,
         die("`pos' is too far after the end of the buffer");
     if (pos + len > sb->len)
         die("`pos + len' is too far after the end of the buffer");
+    if (sb->len > sb->alloc)
+        strbuf_make_var(sb);

     if (dlen >= len)
         strbuf_grow(sb, dlen - len);
@@ -572,6 +593,10 @@ int strbuf_readlink(struct strbuf *sb, const char
*path, size_t hint)

 int strbuf_getcwd(struct strbuf *sb)
 {
+    /*
+     * If sb was a constant, then an error would lead to
+     * strbuf_release() being called on the sb.
+     */
     size_t oldalloc = sb->alloc;
     size_t guessed_len = 128;

diff --git a/strbuf.h b/strbuf.h
index 1a1753424c..a33bc4d90e 100644
--- a/strbuf.h
+++ b/strbuf.h
@@ -128,6 +128,10 @@ static inline void strbuf_swap(struct strbuf *a,
struct strbuf *b)
     SWAP(*a, *b);
 }

> +/**
> + * Constant string buffer is turned into a variable one.
> + */
> +void strbuf_make_var(struct strbuf *sb);

Use imperative mood - Convert an immutable string buffer to a variable
string buffer.

 /**
  * Functions related to the size of the buffer
@@ -160,6 +164,16 @@ void strbuf_grow(struct strbuf *sb, size_t amount);
  */
 static inline void strbuf_setlen(struct strbuf *sb, size_t len)
 {
> +    if (sb->len > sb->alloc)
> +    {
> +        if (!len)
> +        {
> +            sb->buf = strbuf_slopbuf;
> +            return;
> +        }
> +        else
> +            strbuf_make_var(sb);
> +    }

Use braces on the same line as the condition.

     if (len > (sb->alloc ? sb->alloc - 1 : 0))
         die("BUG: strbuf_setlen() beyond buffer");
     sb->len = len;
--
2.17.1
Junio C Hamano· Feb 18, 2020, 20:46 UTC · re: Abhishek Kumar · lore
Abhishek Kumar <abhishekkumar8222@gmail.com> writes:
> I would also prefer the term "immutable" over "const" since const
> already has implications in C programming.

As long as the implication the established word conveys is what the patch wants to do, it is *better* not to invent another phrase and instead use the well-known term, no?

>> STRBUF_INIT_CONST: a new way to initialize strbuf
>
> Use imperative mood and be more specific in the commit title -
> `strbuf: Teach strbuf to initialize immutable strings`
s/T/t/;
> I feel this is self-explanatory when you go through the diff.
True.
Show 5 quoted lines
>  void strbuf_grow(struct strbuf *sb, size_t extra)
>  {
> +    if (sb->len > sb->alloc)
> +        strbuf_make_var(sb);
>      int new_buf = !sb->alloc;
This introduces decl-after-stmt error.

Also, isn't "if (sb->alloc < sb->len)" too loose a check for the new feature? AFAICS in 1/2, a strbuf that is still borrowing a const string always has sb->alloc==0. Other instances of strbuf that happens to satisify the above condition, e.g. (sb->len == 5 && sb->alloc == 1), is an error. If we are to check the condition about sb->len, shouldn't we diagnose such a case as an error, no?

> +void strbuf_make_var(struct strbuf *sb)
> +{
> +    char* str_cpy;

Isn't make_var() an implementation detail that should not leak to the strbuf API users? IOW, does it have to be extern?

In our codebase (eh, rather, in C as opposed to C++), the asterisk sticks to the identifier, not to the type.

Show 7 quoted lines
>  void strbuf_trim_trailing_newline(struct strbuf *sb)
>  {
> +    if (sb->buf[sb->len - 1] == '\n')
>> +        if (sb->len > sb->alloc)
>> +            strbuf_make_var(sb);
>
> Enclose this explicitly in braces.

Yup. Also the repetition we see is a sign that something is wrong. Perhaps adding a small inline helper

	static inline void strbuf_premutate(sb) 
	{
		if (!sb->alloc) {
			... body of strbuf_make_var() comes here ...
		}
	}
and getting rid of strbuf_make_var() would help?

As Peff, I am a bit hesitant about leaving a strbuf that hasn't been made mutable around, though.

Robear Selwans· Feb 19, 2020, 01:43 UTC · re: Junio C Hamano · lore
On Tue, Feb 18, 2020 at 10:46 PM Junio C Hamano <gitster@pobox.com> wrote:
Show 5 quoted lines
> Abhishek Kumar <abhishekkumar8222@gmail.com> writes:
> >> STRBUF_INIT_CONST: a new way to initialize strbuf
> > Use imperative mood and be more specific in the commit title -
> > `strbuf: Teach strbuf to initialize immutable strings`
> s/T/t/;
I don't get what you mean by that.
Show 6 quoted lines
> Also, isn't "if (sb->alloc < sb->len)" too loose a check for the new
> feature?  AFAICS in 1/2, a strbuf that is still borrowing a const
> string always has sb->alloc==0.  Other instances of strbuf that
> happens to satisify the above condition, e.g. (sb->len == 5 &&
> sb->alloc == 1), is an error.  If we are to check the condition
> about sb->len, shouldn't we diagnose such a case as an error, no?

AFAIK after reading the documentation for `strbuf`, there is no other case where `sb->len > sb->alloc` as `alloc` needs to always be more than `len`. I'd like to be corrected if mistaken, though.

> As Peff, I am a bit hesitant about leaving a strbuf that hasn't been
> made mutable around, though.

Yeah, I started to get that when I read Peff's reply. I think I'll go with the approach that Peff suggested, where the constant string is copied to a stack array and so is made mutable to a degree. Since this is a different way, I guess I'll make that from scratch instead of editing the existing one.

Jeff King· Feb 19, 2020, 02:05 UTC · re: Robear Selwans · lore
On Wed, Feb 19, 2020 at 03:43:26AM +0200, Robear Selwans wrote:
Show 7 quoted lines
> On Tue, Feb 18, 2020 at 10:46 PM Junio C Hamano <gitster@pobox.com> wrote:
> > Abhishek Kumar <abhishekkumar8222@gmail.com> writes:
> > >> STRBUF_INIT_CONST: a new way to initialize strbuf
> > > Use imperative mood and be more specific in the commit title -
> > > `strbuf: Teach strbuf to initialize immutable strings`
> > s/T/t/;
> I don't get what you mean by that.

We don't usually capitalize the sentence fragment in a subject line (hence "replace T with t", but said in sed jargon).

Show 9 quoted lines
> > Also, isn't "if (sb->alloc < sb->len)" too loose a check for the new
> > feature?  AFAICS in 1/2, a strbuf that is still borrowing a const
> > string always has sb->alloc==0.  Other instances of strbuf that
> > happens to satisify the above condition, e.g. (sb->len == 5 &&
> > sb->alloc == 1), is an error.  If we are to check the condition
> > about sb->len, shouldn't we diagnose such a case as an error, no?
> AFAIK after reading the documentation for `strbuf`, there is no other
> case where `sb->len > sb->alloc` as `alloc` needs to always be more
> than `len`. I'd like to be corrected if mistaken, though.

Yeah, I don't see how it could be for an allocated buffer, since that would imply writing past the allocated size.

Show 7 quoted lines
> > As Peff, I am a bit hesitant about leaving a strbuf that hasn't been
> > made mutable around, though.
> Yeah, I started to get that when I read Peff's reply. I think I'll go with
> the approach that Peff suggested, where the constant string is
> copied to a stack array and so is made mutable to a degree. Since
> this is a different way, I guess I'll make that from scratch instead of
> editing the existing one.

Yeah, I think it's sufficiently different to start from scratch. Do note that I think you may need to stuff an extra bit into the struct somehow. For a const string, you can set alloc to "0" to denote the situation. But if we're going to be able to attach another buffer that can be written to (but may not yet be full), you'd need to be able to set alloc to the true size of that buffer. And then we need some way to note that it's not a real heap buffer.

There are probably clever tricks you could play with the low bits of the "alloc" field to avoid making the struct any bigger. But given the way we use strbufs, I suspect it may not bring a measurable performance improvement. And I do have dreams of eventually adding more bits. E.g., there are a few cases where it would be convenient to extend the "strbuf that points to a stack buffer but grows" into "strbuf that points to a stack buffer but truncates" (e.g., in our error handling routines which want to avoid calling malloc).

That's definitely a few steps out from where we are now, of course, but we may get there eventually.

-Peff
Junio C Hamano· Feb 19, 2020, 03:13 UTC · re: Robear Selwans · lore
Robear Selwans <rwagih.rw@gmail.com> writes:
Show 9 quoted lines
>> Also, isn't "if (sb->alloc < sb->len)" too loose a check for the new
>> feature?  AFAICS in 1/2, a strbuf that is still borrowing a const
>> string always has sb->alloc==0.  Other instances of strbuf that
>> happens to satisify the above condition, e.g. (sb->len == 5 &&
>> sb->alloc == 1), is an error.  If we are to check the condition
>> about sb->len, shouldn't we diagnose such a case as an error, no?
> AFAIK after reading the documentation for `strbuf`, there is no other
> case where `sb->len > sb->alloc` as `alloc` needs to always be more
> than `len`. I'd like to be corrected if mistaken, though.

Yes, but the case that matters to _your_ use is sb->alloc == 0. You do not want to let a broken strbuf (presumably broken by changes other than your own) to pass, when you can detect it. And for that, paying attention to sb->len _might_ make sense, but then the check won't be

	if (sb->alloc < sb->len)
		make it mutable;
you'd rather be writing something like
	if (!sb->alloc)
		make it mutable;
	else if (sb->alloc < sb->len)
		BUG("somebody fed a corrupt strbuf to me");

If the primary purpose of make_mutable() is *not* about catching random strbuf corruption, then the whole "else if" part is not needed, and the check should become a equation only about sb->alloc, not a comparison between alloc and len (which would trigger for *both* your const-initialized strbuf *and* a corrupt one you did not anticipate to see).

Robear Selwans· Feb 19, 2020, 04:34 UTC · re: Junio C Hamano · lore
On Wed, Feb 19, 2020 at 5:13 AM Junio C Hamano <gitster@pobox.com> wrote:
Show 16 quoted lines
>
> Yes, but the case that matters to _your_ use is sb->alloc == 0.  You
> do not want to let a broken strbuf (presumably broken by changes
> other than your own) to pass, when you can detect it.  And for that,
> paying attention to sb->len _might_ make sense, but then the check
> won't be
>
>         if (sb->alloc < sb->len)
>                 make it mutable;
>
> you'd rather be writing something like
>
>         if (!sb->alloc)
>                 make it mutable;
>         else if (sb->alloc < sb->len)
>                 BUG("somebody fed a corrupt strbuf to me");

Ooh so what you meant, is that corrupt `strbuf`s need to be anticipated even if they don't make much sense. Smart.

Junio C Hamano· Feb 19, 2020, 10:44 UTC · re: Robear Selwans · lore
Robear Selwans <rwagih.rw@gmail.com> writes:
Show 21 quoted lines
> On Wed, Feb 19, 2020 at 5:13 AM Junio C Hamano <gitster@pobox.com> wrote:
>>
>> Yes, but the case that matters to _your_ use is sb->alloc == 0.  You
>> do not want to let a broken strbuf (presumably broken by changes
>> other than your own) to pass, when you can detect it.  And for that,
>> paying attention to sb->len _might_ make sense, but then the check
>> won't be
>>
>>         if (sb->alloc < sb->len)
>>                 make it mutable;
>>
>> you'd rather be writing something like
>>
>>         if (!sb->alloc)
>>                 make it mutable;
>>         else if (sb->alloc < sb->len)
>>                 BUG("somebody fed a corrupt strbuf to me");
>
> Ooh so what you meant, is that corrupt `strbuf`s need to be
> anticipated even if they
> don't make much sense. Smart.

I don't know if that is smart, but the point is that sb->alloc is the only thing you need to care about if you want to see if the strbuf is borrowing from a const string, and it does not make much sense not to catch a corruption, _if_ you are to check the value of sb->len as well.

← back to recent threads