Commit Graph

142 Commits

Author SHA1 Message Date
Matthew Parkinson
ca1540c0d9 Remove allow_reserve feature
This was original designed for Project Snowflake to enable a careful
interoperation between an allocator and the thread suspend behaviour in
.NET.

This feature is not being tested or used by any current project.  This
form of interop would be better served by designing a special Pal to
interop with the CLR if this is ever needed.

This commit removes the feature.
2021-03-21 19:00:54 +00:00
Matthew Parkinson
8824622136 Better reciprocal division and modulus.
The previous reciprocal division branch on the prime that the sizeclass
was constructed from. All sizeclasses can be represented as
  2^n * {1,3,5,7}
This lead to a very small table, but some work to calculate the
appropriate shifts and multiplications to implement reciprocal division.

This commit uses a completely uniform representation for every
sizeclass using a lookup table.  Due to the precise ranges that we query
the modulus and rounding on, we can do this much more efficiently.

The func-release-rounding exhaustively tests all the queries we are
interested in.
2021-03-19 20:11:15 +00:00
Nathaniel Filardo
486ef10c21 NFC: bump pointers have just one associated Slab
Rather than ::get()-ing the `Superslab` and `Slab` for each object we just
created from the bump pointer, recognize that these objects necessarily come
from the same `Slab` (and so the same `Superslab`).  In the eventuality of
CHERI, this means we'll amplify once per bump pointer, not once per created
object.
2021-03-19 15:17:56 +00:00
Nathaniel Filardo
c5e08573bf NFC: prepare RemoteCache API for amplification
When post()-ing the RemoteCache to message queues, we push an entire bucket
onto a remote allocator's incoming queue (specifically, the allocator owning
the front Remote in the bucket we're moving).  In order to do that, we need to
exceed the bounds of the Remote allocation and reference its Allocslab header
(to get the ->message_queue).  On StrictProvenance architectures, this will
require that we amplify the head Remote* and then engage in some pointer math.

While Remotes contain the address of the message_queue as the allocator's
identity, this may not be a pointer, just an address, and may have undergone
obfuscation anyway.
2021-03-19 15:17:56 +00:00
Matthew Parkinson
ed615eade9 Refactor checks to improve codegen. 2021-03-19 11:28:39 +00:00
Matthew Parkinson
50f412157f Protect free list pointers stored in object space
Free list pointers can be exploited by attackers. This commit implements
a simple encoding scheme to detect corruption of the pointers.  This can
be used to detect UAF and double free.

This does not currently address anything for Medium or Large
allocations.  It also does not address cross thread deallocations.

Co-authored-by: Nathaniel Wesley Filardo <nfilardo@microsoft.com>
2021-03-19 11:28:39 +00:00
Nathaniel Filardo
cbab7a3455 NFC: pointer_offset* functions always return void*
This requires that the caller perform the cast on the output rather than the
input, which is a little closer to the truth.  Shuffle some casts into the right
position.
2021-03-16 09:29:19 +00:00
Nathaniel Filardo
f295a3f191 alloc: de-static external_pointer
Like alloc_size, this will require amplification internally.

This patch also restores performance to the status quo ante; Clang can once
again see enough to generate the same code as it did before de-static-ing
alloc_size.
2021-03-16 09:29:19 +00:00
Nathaniel Filardo
1042fc908a alloc: de-static alloc_size
We're going to need to amplify the pointer and that's going to require access
to our AddressSpaceManager, which we only get non-statically through our
LargeAlloc.

This patch unto itself makes the world slower, perhaps because Clang can't see
the certainty of aliasing of the static and non-static paths to the same
structure.  However, when we also de-static external_pointer, that goes away and
things return to the status quo ante.
2021-03-16 09:29:19 +00:00
Nathaniel Filardo
c9588655b0 NFC: alloc_size s/size/chunkmap_slab_kind/
While here, SNMALLOC_ASSERT() that large allocs end up with sensible slab kind
values.
2021-03-16 09:29:19 +00:00
Nathaniel Filardo
08344cfa94 NFC: external_pointer s/size/chunkmap_slab_kind/
While here, SNMALLOC_ASSERT() that large allocs end up with sensible slab kind
values.
2021-03-16 09:29:19 +00:00
Nathaniel Filardo
4f6cf8cb40 NFC: make Slab, Mediumslab interfaces static
Going forward, this gives us explicit pointers with which to carry bounds
annotations.  Otherwise, assuming AuthPtr overloads operator->, a OOP-style call
like

    AuthPtr<Slab, Bounds> slab;
    slab->foo()

will create a `Slab* this` within the body of `Slab::foo`, leaving it unable to
see or propagate the Bounds annotation.  If it invokes callees that expect
`AuthPtr` arguments, it will therefore have to fabricate new `Bounds` unsafely.
2021-03-16 09:29:19 +00:00
Nathaniel Filardo
49fefc3f83 NFC: introduce SlabNext type for intra-small-slab free pointers
Mostly cosmetic, but eliminates some void*-s and makes intention clearer.
2021-03-16 09:29:19 +00:00
Matthew Parkinson
59edf294d0 Move link out of object space.
The link object was previously stored in a disused object.  This is
good for reducing meta-data, but if we want to reduce the meta-data
corruption potential, then this is not a good design choice.

This commit moves it into the Metaslab.
2021-03-15 13:28:03 +00:00
Matthew Parkinson
e7dce55f19 Move is_start_of_object into Metaslab. 2021-03-15 13:28:03 +00:00
Nathaniel Wesley Filardo
e1ba7cd592 Systematize validity checks on dealloc paths (#285)
Replace the generic check_size() calls with per-{small,medium,large} code paths,
which follow the progression...

* _unchecked: no validation has been performed; check the chunkmap and move
  to...

* _checked_chunkmap: the chunkmap indicates that this is the correct slab-type,
  and so we have reason to believe that our supposed Allocslab pointers are of
  the correct types.  Use those pointers to read the sizeclass and move to...

* _checked_sizeclass: additionally, the Allocslab metadata confirms that our
  sizeclass matches the expected value.  Check that we are at the start of an
  object and move to...

* _start: we now believe we have a pointer to the start of a live object.  On
  a sufficiently capable architecture, we will eventually atomically check that
  our pointer is not (scheduled to be) revoked (and/or not reversioned).  If
  this test passes, our prior pointer arithmetic and loads are justified
  (assuming correctness of the quarantine/revocation/reuse) machinery.

The size-less dealloc(void*) path by necessity reads the chunkmap and sizeclass
data itself and so there's no reason to re-validate; as such, it jumps directly
to the _okcmsc point.  Similarly, we assume that remote queues are full of
already validated objects, and so the remote handling paths continue to jump
further along even than the _start methods.
2021-03-02 09:11:33 +00:00
Nathaniel Filardo
6259457790 Add -Wconversion to clang builds
MSVC has strong opinions on implicit conversions as used in CI, while Clang both
locally and in CI has weaker opinions.  In an effort to avoid subsequent
roundtrips through CI, make clang more strict.  Adding -Wconversion definitely
increases the strength of clang's opinions, apparently to include frowning on
some that even MSVC considers OK, so go make explicit the current implicit
behavior.
2021-03-01 20:18:01 +00:00
Nathaniel Filardo
023290664d NFC: Front "deallocating start of an object" tests
Confirm that the client has given dealloc() a start-of-object pointer before
that pointer propagates very far (esp., before it enters the remote queues).

As these tests are not free, structure the code so that future interfaces can
skip over them if there's reason to be sure we're at the start of an object.
(On CHERI, for example, one could imagine using sealed pointers.)

For architectures with SSM/MTE, immediately after this test we can update the
memory granule to guard against double-frees; leave TODOs in place.
2021-02-09 19:15:40 +00:00
Nathaniel Filardo
975a2bd6db handle_dealloc_remote: restructure to avoid amplification when routing
When forwarding a Remote message, we can now operate entirely with local state:
access to our RemoteCache and the message itself.
2020-12-21 14:12:02 +00:00
Nathaniel Filardo
bf742cef84 handle_dealloc_remote{,_slow}: use Remote's sizeclass information
This removes a bunch of pointer math (which would need amplification) to find
and read the sizeclass from slab headers.
2020-12-21 14:12:02 +00:00
Nathaniel Filardo
7c04a9dad6 Remote: store the sizeclass, too
Squeeze some bits out of allocator IDs so that we can land the sizeclass in
each Remote object.  The intent is that, on StrictProvenance architectures like
CHERI, we will be able to route Remote messages through RemoteCache-s without
needing to amplify back to read the sizeclass metadata field out of the slab
headers.
2020-12-21 14:12:02 +00:00
Nathaniel Filardo
c1d5f48797 Clarify ChunkMapSuperslabKind values 2020-12-16 15:57:19 +00:00
Matthew Parkinson
923705e514 Natural alignment for USE_MALLOC (#248)
* Add concept of natural alignment to tests.

snmalloc naturally aligns blocks very heavily, so that
the largest power-of-two in the rounded size is the alignment.
This checks that in the test, and provides a method for
finding the natural alignment of a block.

* Improve USE_MALLOC to provide alignment

snmalloc provides a lot of alginment guarantees. This ensures that when
we pass through to the system allocator we still get those alignment
guarantees.

The commit also fixes the tests to work with USE_MALLOC, and builds a
set of unit tests for ctest to check behaviour.
2020-09-28 10:08:19 +01:00
Nathaniel Filardo
1e8d0bd743 MemoryProviderStateMixin is not a PAL 2020-09-09 12:55:48 +01:00
Matthew Parkinson
333190a27d Add some default initialisers. (#207)
* Add some default initialisers.
2020-05-29 17:12:00 +01:00
Nathaniel Filardo
3d3b048776 mediumslab: stop assuming page-alignedness of objects
With large pages (e.g. the 64K that Debian defaults to for ppc64), this
is a bit much to ask.  It's only not true for the bottom few medium size
classes, tho', as all sizes above 256K are multiples of 64K with the
current two mantissa bits size schedule.
2020-05-23 15:42:10 +00:00
Matthew Parkinson
87dfd41553 Improve code quality for alloc_size (#196)
* Improve code quality for alloc_size

* Made error noreturn.

* Update docs.

* Move annoation
2020-05-23 16:16:12 +01:00
Matthew Parkinson
8d6823b3ed Merge pull request #190 from mjp41/error_message
Add error message for failure during init.
2020-05-20 10:40:59 +01:00
Nathaniel Filardo
79ad6630d3 alloc: eliminate external_pointer/address distinction
Just always work with pointers using the functions defined in
ds/address.h.  This more obviously preserves provenance through the
chain of reasoning.  Note that there is still risk of malloc() being
used as an amplification oracle on CHERI, but there's no additional risk
from this change.

Rename the external_address into external_pointer.
2020-05-19 14:53:55 +00:00
Matthew Parkinson
185781ef52 Add error message for failure during init! 2020-05-19 10:21:00 +01:00
Matthew Parkinson
a9cfc3a2b4 Various minor changes to aid compiling with std14 (#182)
These changes make the code compile in clang10 with -std14.
2020-05-07 15:02:31 +01:00
SchrodingerZhu
a43773c5b7 add android support (#171)
* adjust for android

* update docs

* add const qualifier to `alloc_size`

* check const qualifier in cmake
2020-04-18 07:58:13 +01:00
Matthew Parkinson
d4fccfa4ab Fix callbacks
This change does two things
* correctly passes the template parameters into the callbacks fixing
  correct zeroing of memory.
* By making the callbacks more specific it removes the warnings that GCC
was generating.
2020-04-14 11:39:00 +01:00
Paul Liétar
794a5912c7 Replace uses of std::function by function_ref. 2020-04-09 15:47:11 +02:00
Matthew Parkinson
74657d9dbc Defensive code for alloc/dealloc during TLS teardown (#161)
* Defensive code for alloc/dealloc during TLS teardown

If an allocation or deallocation occurs during TLS teardown, then it is
possible for a new allocator to be created and then this is leaked. On
the mimalloc-bench mstressN benchmark this was observed leading to a
large memory leak.

This fix, detects if we are in the TLS teardown phase, and if so,
the calls to alloc or dealloc must return the allocator once they have
perform the specific operation.

Uses a separate variable to represent if a thread_local's destructor has
run already.  This is used to detect thread teardown to put the
allocator into a special slow path to avoid leaks.

* Added some printing first operation to track progress

* Improve error messages on posix

Flush errors, print assert details, and present stack traces.

* Detect incorrect use of pool.

* Clang format.

* Replace broken LL/SC implementation

LL/SC implementation was broken, this replaces it with
a locking implementation. Changes the API to support LL/SC
for future implementation on ARM.

* Improve TLS teardown.

* Make std::function fully inlined.

* Factor out PALLinux stack trace.

* Add checks for leaking allocators.

* Add release build of Windows Clang
2020-04-07 15:37:26 +01:00
Matthew Parkinson
7bb00a7169 Add checks for deallocation with size (#160)
Ensure that the size deallocated with is the correct size. If the size
supplied is wrong, then internal invariants can break.
2020-04-02 07:04:52 +01:00
Matthew Parkinson
d900e29424 Improve slow path performance for allocation (#143)
* Remote dealloc refactor.

* Improve remote dealloc

Change remote to count down to 0, so fast path does not need a constant.

Use signed value so that branch does not depend on addition.

* Inline remote_dealloc

The fast path of remote_dealloc is sufficiently compact that it can be
inlined.

* Improve fast path in Slab::alloc

Turn the internal structure into tail calls, to improve fast path.
Should be no algorithmic changes.

* Refactor initialisation to help fast path.

Break lazy initialisation into two functions, so it is easier to codegen
fast paths.

* Minor tidy to statically sized dealloc.

* Refactor semi-slow path for alloc

Make the backup path a bit faster.  Only algorithmic change is to delay
checking for first allocation. Otherwise, should be unchanged.

* Test initial operation of a thread

The first operation a new thread takes is special.  It results in
allocating an allocator, and swinging it into the TLS.  This makes
this a very special path, that is rarely tested.  This test generates
a lot of threads to cover the first alloc and dealloc operations.

* Correctly handle reusing get_noncachable

* Fix large alloc stats

Large alloc stats aren't necessarily balanced on a thread, this changes
to tracking individual pushs and pops, rather than the net effect
(with an unsigned value).

* Fix TLS init on large alloc path

* Add Bump ptrs to allocator

Each allocator has a bump ptr for each size class.  This is no longer
slab local.

Slabs that haven't been fully allocated no longer need to be in the DLL
for this sizeclass.

* Change to a cycle non-empty list

This change reduces the branching in the case of finding a new free
list. Using a non-empty cyclic list enables branch free add, and a
single branch in remove to detect the empty case.

* Update differences

* Rename first allocation

Use needs initialisation as makes more sense for other scenarios.

* Use a ptrdiff to help with zero init.

* Make GlobalPlaceholder zero init

The GlobalPlaceholder allocator is now a zero init block of memory.
This removes various issues for when things are initialised. It is made read-only
to we detect write to it on some platforms.
2020-03-31 09:17:53 +01:00
Matthew Parkinson
77c453600b OE fixes (#157)
* Only compile OE PAL if required.

* OE:reserve: Fix bug in loop.

* Handle out of memory by returning nullptr.
2020-03-25 08:10:39 +00:00
Amaury Chamayou
8e3efcb1dc Assert not going through the PAL (#140)
* Assert not going through the PAL

* Make it more difficult to assert() accidentally
2020-03-11 15:58:44 +00:00
Matthew Parkinson
76eaf1adad Remote dealloc refactor. (#138)
Improve remote dealloc

- Outline the slow path to improve code gen significantly

- Handle message queue only on slow path for remote dealloc.

- Change remote size to count down 0, so fast path does not need a constant.

- Use signed value so that branch does not depend on addition.
2020-03-10 08:12:57 +00:00
Amaury Chamayou
acbcbce597 replace assert with SNMALLOC_ASSERT 2020-03-04 16:57:44 +00:00
Matthew Parkinson
02427f98f0 Clangformat. 2020-02-04 14:12:28 +00:00
Matthew Parkinson
2e289573c8 Move all decommit strategy into LargeAllocator
The code for decommit was distribured in the code base.
Removing Decommit All means that it can logically reside in
lthe arge allocator.
2020-01-29 12:29:32 +00:00
Matthew Parkinson
2e4b289991 Removed DecommitAll strategy
The DecommitAll strategy performs badly.  We are not
functionally testing it, and it does not seem investing in it due to its
performance.
2020-01-29 11:58:57 +00:00
Matthew Parkinson
4212ac8e4e Improve codegen for sized free. (#115)
For languages like Verona or Rust, the deallocation calls know the
size of the object originally requested.  This change optimises that
code path to create a much better fast path.
2020-01-22 17:41:08 +00:00
Matthew Parkinson
e8e0f60ccf Fix GCC 9 error. 2020-01-07 11:06:12 +00:00
Nathaniel Filardo
4d6759aca4 Make "pal_supports" not a function
But rather a template vardecl, as per C++14
2019-12-04 16:54:41 +00:00
Nathaniel Filardo
83c467eb92 ds/address: add pointer diff function
And use it rather than open-coding subtraction of two address_cast-s.
2019-11-26 15:50:22 +00:00
Nathaniel Filardo
eb2d8890de Additional provenance preservation 2019-11-26 15:37:52 +00:00
Nathaniel Filardo
20e804728b Move bits::is_aligned_block to address.h
And chase consequences
2019-11-26 15:33:09 +00:00