Commit Graph

88 Commits

Author SHA1 Message Date
Michał Górny fd1da784ac [compiler-rt] [scudo] Use -mcrc32 on x86 when available
Update the hardware CRC32 logic in scudo to support using `-mcrc32`
instead of `-msse4.2`.  The CRC32 intrinsics use the former flag
in the newer compiler versions, e.g. in clang since 12fa608af4.
With these versions of clang, passing `-msse4.2` is insufficient
to enable the instructions and causes build failures when `-march` does
not enable CRC32 implicitly:

    /var/tmp/portage/sys-libs/compiler-rt-sanitizers-14.0.0/work/compiler-rt/lib/scudo/scudo_crc32.cpp:20:10: error: always_inline function '_mm_crc32_u32' requires target feature 'crc32', but would be inlined into function 'computeHardwareCRC32' that is compiled without support for 'crc32'
      return CRC32_INTRINSIC(Crc, Data);
             ^
    /var/tmp/portage/sys-libs/compiler-rt-sanitizers-14.0.0/work/compiler-rt/lib/scudo/scudo_crc32.h:27:27: note: expanded from macro 'CRC32_INTRINSIC'
    #  define CRC32_INTRINSIC FIRST_32_SECOND_64(_mm_crc32_u32, _mm_crc32_u64)
                              ^
    /var/tmp/portage/sys-libs/compiler-rt-sanitizers-14.0.0/work/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_platform.h:132:36: note: expanded from macro 'FIRST_32_SECOND_64'
    #  define FIRST_32_SECOND_64(a, b) (a)
                                       ^
    1 error generated.

For backwards compatibility, use `-mcrc32` when available and fall back
to `-msse4.2`.  The `<smmintrin.h>` header remains in use as it still
works and is compatible with GCC, while clang's `<crc32intrin.h>`
is not.

Use __builtin_ia32*() rather than _mm_crc32*() when using `-mcrc32`
to preserve compatibility with GCC.  _mm_crc32*() are aliases
to __builtin_ia32*() in both compilers but GCC requires `-msse4.2`
for the former, while both use `-mcrc32` for the latter.

Originally reported in https://bugs.gentoo.org/835870.

Differential Revision: https://reviews.llvm.org/D122789
2022-04-01 13:00:21 +02:00
Nikita Popov 985c717cdb Revert "[compiler-rt] [scudo] Use -mcrc32 on x86 when available"
This reverts commit 09b53121c3.

Breaks the build with GCC 11.2 on x86_64:

In file included from /home/npopov/repos/llvm-project/compiler-rt/lib/scudo/scudo_crc32.h:27,
                 from /home/npopov/repos/llvm-project/compiler-rt/lib/scudo/scudo_crc32.cpp:14:
/usr/lib/gcc/x86_64-redhat-linux/11/include/smmintrin.h: In function ‘__sanitizer::u32 __scudo::computeHardwareCRC32(__sanitizer::u32, __sanitizer::uptr)’:
/usr/lib/gcc/x86_64-redhat-linux/11/include/smmintrin.h:846:1: error: inlining failed in call to ‘always_inline’ ‘long long unsigned int _mm_crc32_u64(long long unsigned int, long long unsigned int)’: target specific option mismatch
  846 | _mm_crc32_u64 (unsigned long long __C, unsigned long long __V)
2022-04-01 09:40:48 +02:00
Michał Górny 09b53121c3 [compiler-rt] [scudo] Use -mcrc32 on x86 when available
Update the hardware CRC32 logic in scudo to support using `-mcrc32`
instead of `-msse4.2`.  The CRC32 intrinsics use the former flag
in the newer compiler versions, e.g. in clang since 12fa608af4.
With these compilers, passing `-msse4.2` is insufficient to enable
the instructions and causes build failures when `-march` does not enable
CRC32:

    /var/tmp/portage/sys-libs/compiler-rt-sanitizers-14.0.0/work/compiler-rt/lib/scudo/scudo_crc32.cpp:20:10: error: always_inline function '_mm_crc32_u32' requires target feature 'crc32', but would be inlined into function 'computeHardwareCRC32' that is compiled without support for 'crc32'
      return CRC32_INTRINSIC(Crc, Data);
             ^
    /var/tmp/portage/sys-libs/compiler-rt-sanitizers-14.0.0/work/compiler-rt/lib/scudo/scudo_crc32.h:27:27: note: expanded from macro 'CRC32_INTRINSIC'
    #  define CRC32_INTRINSIC FIRST_32_SECOND_64(_mm_crc32_u32, _mm_crc32_u64)
                              ^
    /var/tmp/portage/sys-libs/compiler-rt-sanitizers-14.0.0/work/compiler-rt/lib/scudo/../sanitizer_common/sanitizer_platform.h:132:36: note: expanded from macro 'FIRST_32_SECOND_64'
    #  define FIRST_32_SECOND_64(a, b) (a)
                                       ^
    1 error generated.

For backwards compatibility, use `-mcrc32` when available and fall back
to `-msse4.2`.  The `<smmintrin.h>` header remains in use as it still
works and is compatible with GCC, while clang's `<crc32intrin.h>`
is not.

Originally reported in https://bugs.gentoo.org/835870.

Differential Revision: https://reviews.llvm.org/D122789
2022-03-31 17:49:42 +02:00
Dmitry Vyukov 765921de5b sanitizer_common: prefix thread-safety macros with SANITIZER_
Currently we use very common names for macros like ACQUIRE/RELEASE,
which cause conflicts with system headers.
Prefix all macros with SANITIZER_ to avoid conflicts.

Reviewed By: vitalybuka

Differential Revision: https://reviews.llvm.org/D116652
2022-01-07 15:11:00 +01:00
Dmitry Vyukov 0da172b176 sanitizer_common: add thread safety annotations
Enable clang Thread Safety Analysis for sanitizers:
https://clang.llvm.org/docs/ThreadSafetyAnalysis.html

Thread Safety Analysis can detect inconsistent locking,
deadlocks and data races. Without GUARDED_BY annotations
it has limited value. But this does all the heavy lifting
to enable analysis and allows to add GUARDED_BY incrementally.

Reviewed By: melver

Differential Revision: https://reviews.llvm.org/D105716
2021-07-12 11:46:49 +02:00
Mitch Phillips e78b64df98 [Scudo] Use GWP-ASan's aligned allocations and fixup postalloc hooks.
This patch does a few cleanup things:
 1. The non-standalone scudo has a problem where GWP-ASan allocations
 may not meet alignment requirements where Scudo was requested to have
 alignment >= 16. Use the new GWP-ASan API to fix this.
 2. The standalone variant loses some debugging information inside of
 GWP-ASan because we ask GWP-ASan to allocate an aligned size in the
 frontend. This means reports end up with 'UaF on a 16-byte allocation'
 for a 1-byte allocation with 16-byte alignment. Also use the new API to
 fix this.
 3. Add post-alloc hooks for GWP-ASan intercepted allocations, and add
 stats tracking for GWP-ASan allocations.
 4. Add a small test that checks the alignment of the frontend
 allocator, so that it can be used under GWP-ASan torture mode.
 5. Add GWP-ASan torture mode as a testing configuration to catch these
 regressions.

Depends on D94830, D95889.

Reviewed By: cryptoad

Differential Revision: https://reviews.llvm.org/D95884
2021-05-10 12:56:18 -07:00
Mitch Phillips 643ccf6e4b Revert "[Scudo] Use GWP-ASan's aligned allocations and fixup postalloc hooks."
This reverts commit a683abe5c0.

Broke the upstream buildbots:
https://lab.llvm.org/buildbot/#/builders/37/builds/3731/steps/16/logs/stdio
2021-04-23 15:40:38 -07:00
Mitch Phillips a683abe5c0 [Scudo] Use GWP-ASan's aligned allocations and fixup postalloc hooks.
This patch does a few cleanup things:
 1. The non-standalone scudo has a problem where GWP-ASan allocations
 may not meet alignment requirements where Scudo was requested to have
 alignment >= 16. Use the new GWP-ASan API to fix this.
 2. The standalone variant loses some debugging information inside of
 GWP-ASan because we ask GWP-ASan to allocate an aligned size in the
 frontend. This means reports end up with 'UaF on a 16-byte allocation'
 for a 1-byte allocation with 16-byte alignment. Also use the new API to
 fix this.
 3. Add post-alloc hooks for GWP-ASan intercepted allocations, and add
 stats tracking for GWP-ASan allocations.
 4. Add a small test that checks the alignment of the frontend
 allocator, so that it can be used under GWP-ASan torture mode.
 5. Add GWP-ASan torture mode as a testing configuration to catch these
 regressions.

Depends on D94830, D95889.

Reviewed By: cryptoad

Differential Revision: https://reviews.llvm.org/D95884
2021-04-23 10:07:36 -07:00
Mitch Phillips 6a42cbf6d2 [GWP-ASan] Add inbuilt options parser.
Adds a modified options parser (shamefully pulled from Scudo, which
shamefully pulled it from sanitizer-common) to GWP-ASan. This allows
customers (Android) to parse options strings in a common way.

Depends on D94117.

AOSP side of these patches is staged at:

 - sepolicy (sysprops should only be settable by the shell, in both root and
 unrooted conditions):
 https://android-review.googlesource.com/c/platform/system/sepolicy/+/1517238

 - zygote updates:
 https://android-review.googlesource.com/c/platform/frameworks/base/+/1515009

 - bionic changes to add `gwp_asan.<process_name>` system property, and
 GWP_ASAN_OPTIONS environment variable:
 https://android-review.googlesource.com/c/platform/bionic/+/1514989

Reviewed By: eugenis

Differential Revision: https://reviews.llvm.org/D92696
2021-01-15 12:57:05 -08:00
Mitch Phillips a8520f6970 [GWP-ASan] Minor refactor of optional components.
In preparation for the inbuilt options parser, this is a minor refactor
of optional components including:
 - Putting certain optional elements in the right header files,
 according to their function and their dependencies.
 - Cleaning up some old and mostly-dead code.
 - Moving some functions into anonymous namespaces to prevent symbol
 export.

Reviewed By: cryptoad, eugenis

Differential Revision: https://reviews.llvm.org/D94117
2021-01-14 11:14:11 -08:00
Kamil Rytarowski 7b2dd58eb0 [compiler-rt] [scudo] Fix typo in function attribute
Fixes the build after landing https://reviews.llvm.org/D87562
2020-09-17 16:57:30 +02:00
Kamil Rytarowski 85e578f53a [compiler-rt] Replace INLINE with inline
This fixes the clash with BSD headers.

Reviewed By: vitalybuka

Differential Revision: https://reviews.llvm.org/D87562
2020-09-17 16:24:20 +02:00
Mitch Phillips 4f029d1be4 [GWP-ASan] Split the unwinder into segv/non-segv.
Note: Resubmission with frame pointers force-enabled to fix builds with
-DCOMPILER_RT_BUILD_BUILTINS=False

Summary:
Splits the unwinder into a non-segv (for allocation/deallocation traces) and a
segv unwinder. This ensures that implementations can select an accurate, slower
unwinder in the segv handler (if they choose to use the GWP-ASan provided one).
This is important as fast frame-pointer unwinders (like the sanitizer unwinder)
don't like unwinding through signal handlers.

Reviewers: morehouse, cryptoad

Reviewed By: morehouse, cryptoad

Subscribers: cryptoad, mgorny, eugenis, pcc, #sanitizers

Tags: #sanitizers

Differential Revision: https://reviews.llvm.org/D83994
2020-07-21 08:25:37 -07:00
Hans Wennborg ab6263c925 Revert 502f0cc0e3 "[GWP-ASan] Split the unwinder into segv/non-segv."
It was causing tests to fail in -DCOMPILER_RT_BUILD_BUILTINS=OFF builds:

   GwpAsan-Unittest :: ./GwpAsan-x86_64-Test/BacktraceGuardedPoolAllocator.DoubleFree
   GwpAsan-Unittest :: ./GwpAsan-x86_64-Test/BacktraceGuardedPoolAllocator.UseAfterFree

see comment on the code review.

> Summary:
> Splits the unwinder into a non-segv (for allocation/deallocation traces) and a
> segv unwinder. This ensures that implementations can select an accurate, slower
> unwinder in the segv handler (if they choose to use the GWP-ASan provided one).
> This is important as fast frame-pointer unwinders (like the sanitizer unwinder)
> don't like unwinding through signal handlers.
>
> Reviewers: morehouse, cryptoad
>
> Reviewed By: morehouse, cryptoad
>
> Subscribers: cryptoad, mgorny, eugenis, pcc, #sanitizers
>
> Tags: #sanitizers
>
> Differential Revision: https://reviews.llvm.org/D83994

This reverts commit 502f0cc0e3.
2020-07-21 11:18:07 +02:00
Mitch Phillips 502f0cc0e3 [GWP-ASan] Split the unwinder into segv/non-segv.
Summary:
Splits the unwinder into a non-segv (for allocation/deallocation traces) and a
segv unwinder. This ensures that implementations can select an accurate, slower
unwinder in the segv handler (if they choose to use the GWP-ASan provided one).
This is important as fast frame-pointer unwinders (like the sanitizer unwinder)
don't like unwinding through signal handlers.

Reviewers: morehouse, cryptoad

Reviewed By: morehouse, cryptoad

Subscribers: cryptoad, mgorny, eugenis, pcc, #sanitizers

Tags: #sanitizers

Differential Revision: https://reviews.llvm.org/D83994
2020-07-17 12:59:47 -07:00
Mitch Phillips a62586846f [GWP-ASan] Crash Handler API.
Summary:
Forewarning: This patch looks big in #LOC changed. I promise it's not that bad, it just moves a lot of content from one file to another. I've gone ahead and left inline comments on Phabricator for sections where this has happened.

This patch:
 1. Introduces the crash handler API (crash_handler_api.h).
 2. Moves information required for out-of-process crash handling into an AllocatorState. This is a trivially-copied POD struct that designed to be recovered from a deceased process, and used by the crash handler to create a GWP-ASan report (along with the other trivially-copied Metadata struct).
 3. Implements the crash handler API using the AllocatorState and Metadata.
 4. Adds tests for the crash handler.
 5. Reimplements the (now optionally linked by the supporting allocator) in-process crash handler (i.e. the segv handler) using the new crash handler API.
 6. Minor updates Scudo & Scudo Standalone to fix compatibility.
 7. Changed capitalisation of errors (e.g. /s/Use after free/Use After Free).

Reviewers: cryptoad, eugenis, jfb

Reviewed By: eugenis

Subscribers: merge_guards_bot, pcc, jfb, dexonsmith, mgorny, cryptoad, #sanitizers, llvm-commits

Tags: #sanitizers, #llvm

Differential Revision: https://reviews.llvm.org/D73557
2020-02-05 15:39:17 -08:00
Mitch Phillips d4acc4720e [GWP-ASan] [Scudo] Add GWP-ASan backtrace for alloc/free to Scudo.
Summary:
Adds allocation and deallocation stack trace support to Scudo. The
default provided backtrace library for GWP-ASan is supplied by the libc
unwinder, and is suitable for production variants of Scudo. If Scudo in future
has its own unwinder, it may choose to use its own over the generic unwinder
instead.

Reviewers: cryptoad

Reviewed By: cryptoad

Subscribers: kubamracek, mgorny, #sanitizers, llvm-commits, morehouse, vlad.tsyrklevich, eugenis

Tags: #sanitizers, #llvm

Differential Revision: https://reviews.llvm.org/D64085

llvm-svn: 364966
2019-07-02 20:33:19 +00:00
Mitch Phillips 21184ec5c4 [GWP-ASan] Integration with Scudo [5].
Summary:
See D60593 for further information.

This patch adds GWP-ASan support to the Scudo hardened allocator. It also
implements end-to-end integration tests using Scudo as the backing allocator.
The tests include crash handling for buffer over/underflow as well as
use-after-free detection.

Reviewers: vlad.tsyrklevich, cryptoad

Reviewed By: vlad.tsyrklevich, cryptoad

Subscribers: kubamracek, mgorny, #sanitizers, llvm-commits, morehouse

Tags: #sanitizers, #llvm

Differential Revision: https://reviews.llvm.org/D62929

llvm-svn: 363584
2019-06-17 17:45:34 +00:00
Kostya Kortchinsky f0fbeaf44a [scudo] Tuning changes based on feedback from current use
Summary:
This tunes several of the default parameters used within the allocator:
- disable the deallocation type mismatch on Android by default; this
  was causing too many issues with third party libraries;
- change the default `SizeClassMap` to `Dense`, it caches less entries
  and is way more memory efficient overall;
- relax the timing of the RSS checks, 10 times per second was too much,
  lower it to 4 times (every 250ms), and update the test so that it
  passes with the new default.

Reviewers: eugenis

Reviewed By: eugenis

Subscribers: srhines, delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D57116

llvm-svn: 352057
2019-01-24 15:56:54 +00:00
Chandler Carruth 2946cd7010 Update the file headers across all of the LLVM projects in the monorepo
to reflect the new license.

We understand that people may be surprised that we're moving the header
entirely to discuss the new license. We checked this carefully with the
Foundation's lawyer and we believe this is the correct approach.

Essentially, all code in the project is now made available by the LLVM
project under our new license, so you will see that the license headers
include that license only. Some of our contributors have contributed
code under our old license, and accordingly, we have retained a copy of
our old license notice in the top-level files in each project and
repository.

llvm-svn: 351636
2019-01-19 08:50:56 +00:00
Kostya Kortchinsky 9920489a2a [scudo] Replace eraseHeader with compareExchangeHeader for Quarantined chunks
Summary:
The reason for the existence of `eraseHeader` was that it was deemed faster
to null-out a chunk header, effectively making it invalid, rather than marking
it as available, which incurred a checksum computation and a cmpxchg.

A previous use of `eraseHeader` was removed with D50655 due to a race.

Now we remove the second use of it in the Quarantine deallocation path and
replace is with a `compareExchangeHeader`.

The reason for this is that greatly helps debugging some heap bugs as the chunk
header is now valid and the chunk marked available, as opposed to the header
being invalid. Eg: we get an invalid state error, instead of an invalid header
error, which reduces the possibilities. The computational penalty is negligible.

Reviewers: alekseyshl, flowerhack, eugenis

Reviewed By: eugenis

Subscribers: delcypher, jfb, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D51224

llvm-svn: 340633
2018-08-24 18:21:32 +00:00
Kostya Kortchinsky 3afc797e42 [scudo] Fix race condition in deallocation path when Quarantine is bypassed
Summary:
There is a race window in the deallocation path when the Quarantine is bypassed.
Initially we would just erase the header of a chunk if we were not to use the
Quarantine, as opposed to using a compare-exchange primitive, to make things
faster.

It turned out to be a poor decision, as 2 threads (or more) could simultaneously
deallocate the same pointer, and if the checks were to done before the header
got erased, this would result in the pointer being added twice (or more) to
distinct thread caches, and eventually be reused.

Winning the race is not trivial but can happen with enough control over the
allocation primitives. The repro added attempts to trigger the bug, with a
moderate success rate, but it should be enough to notice if the bug ever make
its way back into the code.

Since I am changing things in this file, there are 2 smaller changes tagging
along, marking a variable `const`, and improving the Quarantine bypass test at
runtime.

Reviewers: alekseyshl, eugenis, kcc, vitalybuka

Reviewed By: eugenis, vitalybuka

Subscribers: delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D50655

llvm-svn: 339705
2018-08-14 18:34:52 +00:00
Kostya Kortchinsky cccd21d42c [scudo] Simplify internal names (NFC)
Summary:
There is currently too much redundancy in the class/variable/* names in Scudo:
- we are in the namespace `__scudo`, so there is no point in having something
  named `ScudoX` to end up with a final name of `__scudo::ScudoX`;
- there are a lot of types/* that have `Allocator` in the name, given that
  Scudo is an allocator I figure this doubles up as well.

So change a bunch of the Scudo names to make them shorter, less redundant, and
overall simpler. They should still be pretty self explaining (or at least it
looks so to me).

The TSD part will be done in another CL (eg `__scudo::ScudoTSD`).

Reviewers: alekseyshl, eugenis

Reviewed By: alekseyshl

Subscribers: delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D49505

llvm-svn: 337557
2018-07-20 15:07:17 +00:00
Kostya Kortchinsky 63c33b1c9b [scudo] Move noinline functions definitions out of line
Summary:
Mark `isRssLimitExceeded` as `NOINLINE`, and move it's definition as well as
the one of `performSanityChecks` out of the class definition, as requested.

Reviewers: filcab, alekseyshl

Reviewed By: alekseyshl

Subscribers: delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D48228

llvm-svn: 335054
2018-06-19 15:36:30 +00:00
Kostya Kortchinsky 4adf24502e [scudo] Add verbose failures in place of CHECK(0)
Summary:
The current `FailureHandler` mechanism was fairly opaque with regard to the
failure reason due to using `CHECK(0)`. Scudo is a bit different from the other
Sanitizers as it prefers to avoid spurious processing in its failure path. So
we just `dieWithMessage` using a somewhat explicit string.

Adapted the tests for the new strings.

While this takes care of the `OnBadRequest` & `OnOOM` failures, the next step
is probably to migrate the other Scudo failures in the same failes (header
corruption, invalid state and so on).

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: filcab, mgorny, delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D48199

llvm-svn: 334843
2018-06-15 16:45:19 +00:00
Kostya Kortchinsky 76969eaf3d [scudo] Add C++17 aligned new/delete operators support
Summary:
This CL adds support for aligned new/delete operators (C++17). Currently we
do not support alignment inconsistency detection on deallocation, as this
requires a header change, but the APIs are introduced and are functional.

Add a smoke test for the aligned version of the operators.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D48031

llvm-svn: 334505
2018-06-12 14:42:40 +00:00
Kostya Kortchinsky 4410e2c43f [scudo] Improve the scalability of the shared TSD model
Summary:
The shared TSD model in its current form doesn't scale. Here is an example of
rpc2-benchmark (with default parameters, which is threading heavy) on a 72-core
machines (defaulting to a `CompactSizeClassMap` and no Quarantine):
- with tcmalloc: 337K reqs/sec, peak RSS of 338MB;
- with scudo (exclusive): 321K reqs/sec, peak RSS of 637MB;
- with scudo (shared): 241K reqs/sec, peak RSS of 324MB.

This isn't great, since the exclusive model uses a lot of memory, while the
shared model doesn't even come close to be competitive.

This is mostly due to the fact that we are consistently scanning the TSD pool
starting at index 0 for an available TSD, which can result in a lot of failed
lock attempts, and touching some memory that needs not be touched.

This CL attempts to make things better in most situations:
- first, use a thread local variable on Linux (intead of pthread APIs) to store
  the current TSD in the shared model;
- move the locking boolean out of the TSD: this allows the compiler to use a
  register and potentially optimize out a branch instead of reading it from the
  TSD everytime (we also save a tiny bit of memory per TSD);
- 64-bit atomic operations on 32-bit ARM platforms happen to be expensive: so
  store the `Precedence` in a `uptr` instead of a `u64`. We lose some
  nanoseconds of precision and we'll wrap around at some point, but the benefit
  is worth it;
- change a `CHECK` to a `DCHECK`: this should never happen, but if something is
  ever terribly wrong, we'll crash on a near null AV if the TSD happens to be
  null;
- based on an idea by dvyukov@, we are implementing a bound random scan for
  an available TSD. This requires computing the coprimes for the number of TSDs,
  and attempting to lock up to 4 TSDs in an random order before falling back to
  the current one. This is obviously slightly more expansive when we have just
  2 TSDs (barely noticeable) but is otherwise beneficial. The `Precedence` still
  basically corresponds to the moment of the first contention on a TSD. To seed
  on random choice, we use the precedence of the current TSD since it is very
  likely to be non-zero (since we are in the slow path after a failed `tryLock`)

With those modifications, the benchmark yields to:
- with scudo (shared): 330K reqs/sec, peak RSS of 327MB.

So the shared model for this specific situation not only becomes competitive but
outperforms the exclusive model. I experimented with some values greater than 4
for the number of TSDs to attempt to lock and it yielded a decrease in QPS. Just
sticking with the current TSD is also a tad slower. Numbers on platforms with
less cores (eg: Android) remain similar.

Reviewers: alekseyshl, dvyukov, javed.absar

Reviewed By: alekseyshl, dvyukov

Subscribers: srhines, kristof.beyls, delcypher, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D47289

llvm-svn: 334410
2018-06-11 14:50:31 +00:00
Kostya Kortchinsky e5c9e9f0bd [scudo] Quarantine optimization
Summary:
It turns out that the previous code construct was not optimizing the allocation
and deallocation of batches. The class id was read as a class member (even
though a precomputed one) and nothing else was optimized. By changing the
construct this way, the compiler actually optimizes most of the allocation and
deallocation away to only work with a single class id, which not only saves some
CPU but also some code footprint.

Reviewers: alekseyshl, dvyukov

Reviewed By: dvyukov

Subscribers: dvyukov, delcypher, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D46961

llvm-svn: 332502
2018-05-16 18:12:31 +00:00
Kostya Kortchinsky d8803d3d92 [scudo] Adding an interface function to print allocator stats
Summary:
This adds `__scudo_print_stats` as an interface function to display the Primary
and Secondary allocator statistics for Scudo.

Reviewers: alekseyshl, flowerhack

Reviewed By: alekseyshl

Subscribers: delcypher, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D46016

llvm-svn: 330857
2018-04-25 18:52:29 +00:00
Kostya Kortchinsky 4563b78b99 [sanitizer] Allow for the allocator "names" to be set by the tools
Summary:
In the same spirit of SanitizerToolName, allow the Primary & Secondary
allocators to have names that can be set by the tools via PrimaryAllocatorName
and SecondaryAllocatorName.

Additionally, set a non-default name for Scudo.

Reviewers: alekseyshl, vitalybuka

Reviewed By: alekseyshl, vitalybuka

Subscribers: kubamracek, delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D45600

llvm-svn: 330055
2018-04-13 19:21:27 +00:00
Kostya Kortchinsky a51139046e [scudo] Add Chunk::getSize, rework Chunk::getUsableSize
Summary:
Using `getActuallyAllocatedSize` from the Combined resulting in mediocre
compiled code, as the `ClassId != 0` predicament was not propagated there,
resulting in additional branches and dead code. Move the logic in the frontend,
which results in better compiled code. Also I think it makes it slightly easier
to distinguish between the size the user requested, and the size that was
actually allocated by the allocator.

`const` a couple of things as well.

This has no functional impact.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D44444

llvm-svn: 327525
2018-03-14 15:50:32 +00:00
Kostya Kortchinsky e245ec0cf0 [scudo] Make logging more consistent
Summary:
A few changes related to logging:
- prepend `Scudo` to the error messages so that users can identify that we
  reported an error;
- replace a couple of `Report` calls in the RSS check code with
  `dieWithMessage`/`Print`, mark a condition as `UNLIKELY` in the process;
- change some messages so that they all look more or less the same. This
  includes the `CHECK` message;
- adapt a couple of tests with the new strings.

A couple of side notes: this results in a few 1-line-blocks, for which I left
brackets. There doesn't seem to be any style guide for that, I can remove them
if need be. I didn't use `SanitizerToolName` in the strings, but directly
`Scudo` because we are the only users, I could change that too.

Reviewers: alekseyshl, flowerhack

Reviewed By: alekseyshl

Subscribers: mgorny, delcypher, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D44171

llvm-svn: 326901
2018-03-07 16:22:16 +00:00
Kostya Kortchinsky beeea6227b [scudo] Introduce Chunk::getHeaderSize
Summary:
Instead of using `AlignedChunkHeaderSize`, introduce a `constexpr` function
`getHeaderSize` in the `Chunk` namespace. Switch `RoundUpTo` to a `constexpr`
as well (so we can use it in `constexpr` declarations). Mark a few variables
in the areas touched as `const`.

Overall this has no functional change, and is mostly to make things a bit more
consistent.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: delcypher, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D43772

llvm-svn: 326206
2018-02-27 16:14:49 +00:00
Kostya Kortchinsky 4223af42b8 [scudo] Add default implementations for weak functions
Summary:
This is in preparation for platforms where `SANITIZER_SUPPORTS_WEAK_HOOKS` is 0.
They require a default implementation.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: delcypher, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D42557

llvm-svn: 323795
2018-01-30 17:59:49 +00:00
Kostya Kortchinsky 1ebebde8b7 [scudo] Allow for weak hooks, gated by a define
Summary:
Hooks in the allocation & deallocation paths can be a security risk (see for an
example https://scarybeastsecurity.blogspot.com/2016/11/0day-exploit-advancing-exploitation.html
which used the glibc's __free_hook to complete exploitation).

But some users have expressed a need for them, even if only for tests and
memory benchmarks. So allow for `__sanitizer_malloc_hook` &
`__sanitizer_free_hook` to be called if defined, and gate them behind a global
define `SCUDO_CAN_USE_HOOKS` defaulting to 0.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D42430

llvm-svn: 323278
2018-01-23 23:07:42 +00:00
Kostya Kortchinsky 33802be579 [scudo] Fix for the Scudo interface function scope
Summary:
A forgotten include in `scudo_allocator.cpp` made the symbol only local :/

Before:
```
nm ./lib/clang/7.0.0/lib/linux/libclang_rt.scudo-i686-android.so | grep rss
00024730 t __scudo_set_rss_limit
```
After:
```
nm ./lib/clang/7.0.0/lib/linux/libclang_rt.scudo-i686-android.so | grep rs
00024760 T __scudo_set_rss_limit
```
And we want `T`!

This include also means that we can get rid of the `extern "C"` in the C++
file, the compiler does fine without it (note that this was already the case
for all the `__sanitizer_*` interface functions.

Reviewers: alekseyshl, eugenis

Reviewed By: eugenis

Subscribers: #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D42199

llvm-svn: 322782
2018-01-17 23:10:02 +00:00
Kostya Kortchinsky 541c5a0797 [scudo] s/unsigned long/size_t/ for __scudo_set_rss_limit
Summary:
`__scudo_set_rss_limit`'s `LimitMb` should really be a `size_t`. Update
accordingly the prototype. To avoid the `NOLINT` and conform with the other
Sanitizers, use the sanitizers types for the internal definition. This should
have no functional change.

Additionally, capitalize a variable name to follow the LLVM coding standards.

Reviewers: alekseyshl, flowerhack

Reviewed By: alekseyshl

Subscribers: #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D41704

llvm-svn: 321803
2018-01-04 17:05:04 +00:00
Kostya Kortchinsky efe3d3436a [scudo] Refactor ScudoChunk
Summary:
The initial implementation used an ASan like Chunk class that was deriving from
a Header class. Due to potential races, we ended up working with local copies
of the Header and never using the parent class fields. ScudoChunk was never
constructed but cast, and we were using `this` as the pointer needed for our
computations. This was meh.

So we refactored ScudoChunk to be now a series of static functions within the
namespace `__scudo::Chunk` that take a "user" pointer as first parameter (former
`this`). A compiled binary doesn't really change, but the code is more sensible.

Clang tends to inline all those small function (in -O2), but GCC left a few not
inlined, so we add the `INLINE` keyword to all.

Since we don't have `ScudoChunk` pointers anymore, a few variables were renamed
here and there to introduce a clearer distinction between a user pointer
(usually `Ptr`) and a backend pointer (`BackendPtr`).

Reviewers: alekseyshl, flowerhack

Reviewed By: alekseyshl

Subscribers: #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D41200

llvm-svn: 320745
2017-12-14 21:32:57 +00:00
Kostya Kortchinsky f22f5fe910 [scudo] Adding a public Scudo interface
Summary:
The first and only function to start with allows to set the soft or hard RSS
limit at runtime. Add associated tests.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: mgorny, #sanitizers, llvm-commits

Differential Revision: https://reviews.llvm.org/D41128

llvm-svn: 320611
2017-12-13 20:41:35 +00:00
Kostya Kortchinsky f50246da65 [sanitizer] Introduce a vDSO aware timing function
Summary:
See D40657 & D40679 for previous versions of this patch & description.

A couple of things were fixed here to have it not break some bots.
Weak symbols can't be used with `SANITIZER_GO` so the previous version was
breakin TsanGo. I set up some additional local tests and those pass now.

I changed the workaround for the glibc vDSO issue: `__progname` is initialized
after the vDSO and is actually public and of known type, unlike
`__vdso_clock_gettime`. This works better, and with all compilers.

The rest is the same.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: srhines, kubamracek, krytarowski, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D41121

llvm-svn: 320594
2017-12-13 16:23:54 +00:00
Kostya Kortchinsky 4ac0b1e6e9 [scudo] Inline getScudoChunk function.
Summary:
getScudoChunk function is implicitly inlined for optimized builds on
clang, but not on gcc. It's a small enough function that it seems
sensible enough to just inline it by default.

Reviewers: cryptoad, alekseyshl

Reviewed By: cryptoad

Differential Revision: https://reviews.llvm.org/D41138

llvm-svn: 320592
2017-12-13 16:10:39 +00:00
Kostya Kortchinsky ab5f6aaa75 [sanitizer] Revert rL320409
Summary: D40679 broke a couple of builds, reverting while investigating.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: srhines, kubamracek, krytarowski, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D41088

llvm-svn: 320417
2017-12-11 21:03:12 +00:00
Kostya Kortchinsky d276d72441 [sanitizer] Introduce a vDSO aware time function, and use it in the allocator [redo]
Summary:
Redo of D40657, which had the initial discussion. The initial code had to move
into a libcdep file, and things had to be shuffled accordingly.

`NanoTime` is a time sink when checking whether or not to release memory to
the OS. While reducing the amount of calls to said function is in the works,
another solution that was found to be beneficial was to use a timing function
that can leverage the vDSO.

We hit a couple of snags along the way, like the fact that the glibc crashes
when clock_gettime is called from a preinit_array, or the fact that
`__vdso_clock_gettime` is mangled (for security purposes) and can't be used
directly, and also that clock_gettime can be intercepted.

The proposed solution takes care of all this as far as I can tell, and
significantly improve performances and some Scudo load tests with memory
reclaiming enabled.

@mcgrathr: please feel free to follow up on
https://reviews.llvm.org/D40657#940857 here. I posted a reply at
https://reviews.llvm.org/D40657#940974.

Reviewers: alekseyshl, krytarowski, flowerhack, mcgrathr, kubamracek

Reviewed By: alekseyshl, krytarowski

Subscribers: #sanitizers, mcgrathr, srhines, llvm-commits, kubamracek

Differential Revision: https://reviews.llvm.org/D40679

llvm-svn: 320409
2017-12-11 19:23:12 +00:00
Kostya Kortchinsky 9fcb91b3eb [scudo] Minor code generation improvement
Summary:
It looks like clang was generating somewhat weird assembly with the current
code. `FromPrimary`, even though `const`,  was replaced every time with the code
generated for `size <= SizeClassMap::kMaxSize` instead of using a variable or
register, and `FromPrimary` didn't induce `ClassId != 0` for the compiler, so a
dead branch was generated for `getActuallyAllocatedSize(Ptr, ClassId)` since
it's never called for `ClassId = 0` (Secondary backed allocations) [this one
was more wishful thinking on my side than anything else].

I rearranged the code bit so that the generated assembly is less clunky.

Also changed 2 whitespace inconsistencies that were bothering me.

Reviewers: alekseyshl, flowerhack

Reviewed By: flowerhack

Subscribers: llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D40976

llvm-svn: 320160
2017-12-08 16:36:37 +00:00
Kostya Kortchinsky df6ba242bf [scudo] Get rid of the thread local PRNG & header salt
Summary:
It was deemed that the salt in the chunk header didn't improve security
significantly (and could actually decrease it). The initial idea was that the
same chunk would different headers on different allocations, allowing for less
predictability. The issue is that gathering the same chunk header with different
salts can give information about the other "secrets" (cookie, pointer), and that
if an attacker leaks a header, they can reuse it anyway for that same chunk
anyway since we don't enforce the salt value.

So we get rid of the salt in the header. This means we also get rid of the
thread local Prng, and that we don't need a global Prng anymore as well. This
makes everything faster.

We reuse those 8 bits to store the `ClassId` of a chunk now (0 for a secondary
based allocation). This way, we get some additional speed gains:
- `ClassId` is computed outside of the locked block;
- `getActuallyAllocatedSize` doesn't need the `GetSizeClass` call;
- same for `deallocatePrimary`;
We add a sanity check at init for this new field (all sanity checks are moved
in their own function, `init` was getting crowded).

Reviewers: alekseyshl, flowerhack

Reviewed By: alekseyshl

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D40796

llvm-svn: 319791
2017-12-05 17:08:29 +00:00
Kostya Kortchinsky 0207b6fbbf [scudo] Overhaul hardware CRC32 feature detection
Summary:
This patch aims at condensing the hardware CRC32 feature detection and making
it slightly more effective on Android.

The following changes are included:
- remove the `CPUFeature` enum, and get rid of one level of nesting of
  functions: we only used CRC32, so we just implement and use
  `hasHardwareCRC32`;
- allow for a weak `getauxval`: the Android toolchain is compiled at API level
  14 for Android ARM, meaning no `getauxval` at compile time, yet we will run
  on API level 27+ devices. The `/proc/self/auxv` fallback can work but is
  worthless for a process like `init` where the proc filesystem doesn't exist
  yet. If a weak `getauxval` doesn't exist, then fallback.
- couple of extra corrections.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: kubamracek, aemerson, srhines, kristof.beyls, llvm-commits

Differential Revision: https://reviews.llvm.org/D40322

llvm-svn: 318859
2017-11-22 18:30:44 +00:00
Kostya Kortchinsky 58f2656d7e [scudo] Soft and hard RSS limit checks
Summary:
This implements an opportunistic check for the RSS limit.

For ASan, this was implemented thanks to a background thread checking the
current RSS vs the set limit every 100ms. This was deemed problematic for Scudo
due to potential Android concerns (Zygote as pointed out by Aleksey) as well as
the general inconvenience of having a permanent background thread.

If a limit (soft or hard) is specified, we will attempt to update the RSS limit
status (exceeded or not) every 100ms. This is done in an opportunistic way: if
we can update it, we do it, if not we return the current status, mostly because
we don't need it to be fully consistent (it's done every 100ms anyway). If the
limit is exceeded `allocate` will act as if OOM for a soft limit, or just die
for a hard limit.

We use the `common_flags()`'s `hard_rss_limit_mb` & `soft_rss_limit_mb` for
configuration of the limits.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D40038

llvm-svn: 318301
2017-11-15 16:40:27 +00:00
Kostya Kortchinsky a2b715f883 [scudo] Simplify initialization and flags
Summary:
This is mostly some cleanup and shouldn't affect functionalities.

Reviewing some code for a future addition, I realized that the complexity of
the initialization path was unnecessary, and so was maintaining a structure
for the allocator options throughout the initialization.

So we get rid of that structure, of an extraneous level of nesting for the
`init` function, and correct a couple of related code inaccuracies in the
flags cpp.

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D39974

llvm-svn: 318157
2017-11-14 16:14:53 +00:00
Kostya Kortchinsky 8d4ba5fd23 [scudo] Allow for non-Android Shared TSD platforms, part 1
Summary:
This first part just prepares the grounds for part 2 and doesn't add any new
functionality. It mostly consists of small refactors:
- move the `pthread.h` include higher as it will be used in the headers;
- use `errno.h` in `scudo_allocator.cpp` instead of the sanitizer one, update
  the `errno` assignments accordingly (otherwise it creates conflicts on some
  platforms due to `pthread.h` including `errno.h`);
- introduce and use `getCurrentTSD` and `setCurrentTSD` for the shared TSD
  model code;

Reviewers: alekseyshl

Reviewed By: alekseyshl

Subscribers: llvm-commits, srhines

Differential Revision: https://reviews.llvm.org/D38826

llvm-svn: 315583
2017-10-12 15:01:09 +00:00
Kostya Kortchinsky b59abb2590 [scudo] Scudo thread specific data refactor, part 3
Summary:
Previous parts: D38139, D38183.

In this part of the refactor, we abstract the Linux vs Android TSD dissociation
in favor of a Exclusive vs Shared one, allowing for easier platform introduction
and configuration.

Most of this change consist of shuffling the files around to reflect the new
organization.

We introduce `scudo_platform.h` where platform specific definition lie. This
involves the TSD model and the platform specific allocator parameters. In an
upcoming CL, those will be configurable via defines, but we currently stick
with conservative defaults.

Reviewers: alekseyshl, dvyukov

Reviewed By: alekseyshl, dvyukov

Subscribers: srhines, llvm-commits, mgorny

Differential Revision: https://reviews.llvm.org/D38244

llvm-svn: 314224
2017-09-26 17:20:02 +00:00