Re: [PATCH 0/9] commit-reach: -Wsign-compare follow-ups
- From
Patrick Steinhardt <ps@pks.im>
- Date
- Dec 28, 2024, 08:41 UTC
- Message-ID
- <Z2-5nnBzPKP3iPxl@pks.im>
- In-Reply-To
- <20241227213729.GA796141@coredump.intra.peff.net>
On Fri, Dec 27, 2024 at 04:37:29PM -0500, Jeff King wrote:
Show 26 quoted lines
> On Fri, Dec 27, 2024 at 12:08:03PM -0800, Junio C Hamano wrote:
> I doubt there is a way to tell the compiler that (or that a compiler
> could even switch to an unsigned ptrdiff type if it knew that). But I
> wonder if there is a generalized helper we can devise that would avoid
> simply casting here. I guess that could be a checked cast like:
>
> static inline size_t ptrdiff_to_size(ptrdiff_t v)
> {
> if (v < 0)
> BUG("surprising negative value: %"PRIdMAX, v);
> return (size_t)v;
> }
>
> or even:
>
> static inline bool has_space(const void *vs, const void *ve, size_t want)
> {
> const char *s = vs, e = ve;
> return want <= ptrdiff_to_size(ve - vs);
> }
>
> I don't love hiding basic things like this behind macros or inlines. But
> allocation and bounds comparisons do have gotchas (especially against an
> adversary that can try to create pathological situations). Maybe it's worth
> having an easy way to do them safely without having to think about each
> one. I dunno.I think having a wrapper like `cast_ptrdiff_to_size_t()` would be a sensible solution for now, also because it fits in nicely with `cast_size_t_to_int()`. I'll introduce such a wrapper once I've got a good excuse to do so.
Patrick