From: Jeff Hostetler Date: Wed, 22 Dec 2021 16:28:23 GMT Subject: Re: [PATCH 2/9] trace2: convert tr2tls_thread_ctx.thread_name from strbuf to char* Message-ID: In-Reply-To: On 12/21/21 2:22 AM, Junio C Hamano wrote: > "Jeff Hostetler via GitGitGadget" writes: > >> From: Jeff Hostetler >> >> Use a 'char *' to hold the thread name rather than a 'struct strbuf'. >> The thread name is set when the thread is created and should not be >> be modified afterwards. Replace the strbuf with an allocated pointer >> to make that more clear. > > Sounds good. Use of strbuf is perfectly fine while you compute the > final value of the string, but as a more permanent location to store > the result, it often is unsuitable (and strbuf_split_buf() is a prime > example of how *not* to design your API function around the type). > >> diff --git a/trace2/tr2_tls.c b/trace2/tr2_tls.c >> index 7da94aba522..cd8b9f2f0a0 100644 >> --- a/trace2/tr2_tls.c >> +++ b/trace2/tr2_tls.c >> @@ -35,6 +35,7 @@ struct tr2tls_thread_ctx *tr2tls_create_self(const char *thread_name, >> uint64_t us_thread_start) >> { >> struct tr2tls_thread_ctx *ctx = xcalloc(1, sizeof(*ctx)); >> + struct strbuf buf_name = STRBUF_INIT; >> >> /* >> * Implicitly "tr2tls_push_self()" to capture the thread's start >> @@ -47,12 +48,13 @@ struct tr2tls_thread_ctx *tr2tls_create_self(const char *thread_name, >> >> ctx->thread_id = tr2tls_locked_increment(&tr2_next_thread_id); >> >> - strbuf_init(&ctx->thread_name, 0); >> if (ctx->thread_id) >> - strbuf_addf(&ctx->thread_name, "th%02d:", ctx->thread_id); >> - strbuf_addstr(&ctx->thread_name, thread_name); >> - if (ctx->thread_name.len > TR2_MAX_THREAD_NAME) >> - strbuf_setlen(&ctx->thread_name, TR2_MAX_THREAD_NAME); >> + strbuf_addf(&buf_name, "th%02d:", ctx->thread_id); >> + strbuf_addstr(&buf_name, thread_name); >> + if (buf_name.len > TR2_MAX_THREAD_NAME) >> + strbuf_setlen(&buf_name, TR2_MAX_THREAD_NAME); >> + >> + ctx->thread_name = strbuf_detach(&buf_name, NULL); > > This is not exactly a new problem, but if we use a mechanism to > allow arbitrary long string (like composing with strbuf and > detaching the resulting string as is), instead of having a fixed > name[] array embedded in the ctx structure, I wonder if applying the > maximum length this early makes sense. Such a truncation would > allow more than one ctx structures to share the same name, which > somehow feels error prone, inviting a mistake to use .thread_name > member as an identifier, when its only intended use is to give a > human-readable and not necessarily unique label. Of course, if the > maximum is reasonably low, like a few dozen bytes, it may even make > sense to embed an array of the fixed size and not worry about an > extra pointer. > I'll convert it to a flex-array at the bottom of the CTX structure and then defer the truncation to the _perf target (which only does that to keep the columns lined up). That will simplify things considerably. Thanks Jeff