Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mitigate arithmetic wrap-around (overflow and underflow) #345

Open
3 tasks
kees opened this issue Sep 15, 2023 · 2 comments
Open
3 tasks

Mitigate arithmetic wrap-around (overflow and underflow) #345

kees opened this issue Sep 15, 2023 · 2 comments

Comments

@kees
Copy link

kees commented Sep 15, 2023

We must mitigate all arithmetic wrap-around (overflow and underflow). This requires solving it for each of the three variable types:

@kees
Copy link
Author

kees commented Sep 15, 2023

One of the common "wrap" patterns is if (val + offset < val) { ... }. These can be found and replaced by Coccinelle:

@found@
unsigned long ULONG;
expression OFFSET;
@@

 {
+       unsigned long sum;
        ...
        (
-       ULONG + OFFSET < ULONG
+       check_add_overflow(ULONG, OFFSET, &sum)
        )
        ...
        (
-       ULONG + OFFSET
+       sum
        )
        ...
 }

@kees
Copy link
Author

kees commented Sep 15, 2023

And to generally locate them:

@wrap_check@
void *PTR;
unsigned long ULONG;
unsigned int UINT;
expression OFFSET;
@@

        (
(
-       PTR + OFFSET < PTR
+       ULONG_MAX - OFFSET > PTR
|
-       ULONG + OFFSET < ULONG
+       ULONG_MAX - OFFSET > ULONG
|
-       UINT + OFFSET < UINT
+       UINT_MAX - OFFSET > UINT
)
        )

But this conversion results in worse code gen. It may be useful to add a wrapper macro:

#define would_add_overflow(a, b) ({ \
    typeof(a) __maybe_overflowed_sum; \
    check_add_overflow(a, b, &__maybe_overflowed_sum); \
})

See https://godbolt.org/z/Kc7vsMd9W

@kees kees changed the title Mitigate arithmetic overflow and underflow Mitigate arithmetic wrap-around (overflow and underflow) Sep 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant