diff mbox series

[FFmpeg-devel] compat: Fix the fallback definition of stdc_trailing_zeros

Message ID 20240924085338.89777-1-martin@martin.st
State New
Headers show
Series [FFmpeg-devel] compat: Fix the fallback definition of stdc_trailing_zeros | expand

Checks

Context Check Description
andriy/make_x86 success Make finished
andriy/make_fate_x86 success Make fate finished

Commit Message

Martin Storsjö Sept. 24, 2024, 8:53 a.m. UTC
While shifting "value" to left, we would iterate through all bits
of an unsigned long long, while we only expect to count through
"size * CHAR_BIT" bits.

This fixes fate with MSVC.
---
 compat/stdbit/stdbit.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

Comments

Anton Khirnov Sept. 24, 2024, 9:27 a.m. UTC | #1
Quoting Martin Storsjö (2024-09-24 10:53:38)
> While shifting "value" to left, we would iterate through all bits
> of an unsigned long long, while we only expect to count through
> "size * CHAR_BIT" bits.
> 
> This fixes fate with MSVC.
> ---
>  compat/stdbit/stdbit.h | 3 ++-
>  1 file changed, 2 insertions(+), 1 deletion(-)
> 
> diff --git a/compat/stdbit/stdbit.h b/compat/stdbit/stdbit.h
> index b434fc2357..3197a24938 100644
> --- a/compat/stdbit/stdbit.h
> +++ b/compat/stdbit/stdbit.h
> @@ -179,9 +179,10 @@ static inline unsigned int __stdc_trailing_zeros(unsigned long long value,
>                                                   unsigned int size)
>  {
>      unsigned int zeros = size * CHAR_BIT;
> +    unsigned long long mask = (1ULL << (size * CHAR_BIT)) - 1;

This is UB for size == sizeof(unsigned long long).

>  
>      while (value != 0) {
> -        value <<= 1;
> +        value = (value << 1) & mask;

Otherwise looks ok.
diff mbox series

Patch

diff --git a/compat/stdbit/stdbit.h b/compat/stdbit/stdbit.h
index b434fc2357..3197a24938 100644
--- a/compat/stdbit/stdbit.h
+++ b/compat/stdbit/stdbit.h
@@ -179,9 +179,10 @@  static inline unsigned int __stdc_trailing_zeros(unsigned long long value,
                                                  unsigned int size)
 {
     unsigned int zeros = size * CHAR_BIT;
+    unsigned long long mask = (1ULL << (size * CHAR_BIT)) - 1;
 
     while (value != 0) {
-        value <<= 1;
+        value = (value << 1) & mask;
         zeros--;
     }