Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Use safe arithmetic for memory allocation in Unix shims - #13553

Merged
stephentoub merged 6 commits into
dotnet:masterfrom
stephentoub:safemath
Nov 11, 2016
Merged

stephentoub merged 6 commits into
dotnet:masterfrom
stephentoub:safemath

Conversation

@stephentoub

Copy link
Copy Markdown
Member

There are a handful of places in the corefx shims where we use malloc with the result of some arithmetic operation. This PR fixes those to ensure we're not overflowing.

Where I could, I simply switched to using new to allocate an array, letting the compiler handle any overflows. For the rest of the cases, I added two helpers, multiply_s and add_s, that are used to do the operations safely. Where possible, these are implemented using __builtin_mul_overflow and __builtin_add_overflow. For when we're using too old a version of clang/gcc to have those, I've copied over coreclr's ClrSafeInt (with minimal changes to get it to compile, e.g. using static_cast instead of C-style casts) and use that... I kept the original copy and the changes to the copy in separate commits to make it easy to see the diff from coreclr.

cc: @jkotas, @bartonjs
Fixes https://github.com/dotnet/corefx/issues/13385

We'd like to be able to use builtins for overflow checking, but the relevant builtins (e.g. __builtin_mul_overflow) aren't available with the compiler versions we currently use on all platforms.  In the meantime, we'll use the ClrSafeInt implementation from coreclr.

This commit brings over the files, but they don't yet compile.
Made a minimal set of changes to get safemath/debugmacrosext to compile on Linux and macOS with the compiler versions being used in the repo, the default warnings enabled, and the lack of other files that coreclr depends on.
Use the builtins when available, otherwise fall back to using ClrSafeInt.
Let's the language handle overflow detection.
@stephentoub
stephentoub merged commit 68be7c6 into dotnet:master Nov 11, 2016
@stephentoub
stephentoub deleted the safemath branch November 11, 2016 03:49
@bartonjs

Copy link
Copy Markdown
Member

LGTM :)

@karelz karelz modified the milestone: 1.2.0 Dec 3, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Security] Use safe integer arithmetic for memory allocation

4 participants