Commit Graph

207 Commits

Author SHA1 Message Date
Mike Ash
81a6a7166c [RemoteMirror] Put a limit on pointer-chasing loops to avoid infinite loops. Report Slab's Next pointer as a separate chunk.
When iterating over linked lists in the target process, bugs or corrupt data might cause us to enter an infinite loop. Limit these loops to a fixed number of iterations so that we fail more gracefully. These limits should be set to a level that no healthy program will approach.

Report Slab's Next pointer as a separate chunk in asyncTaskSlabAllocations. This lets tools see it as a pointer and see the connection to the next slab.

rdar://91289920
2022-04-14 14:32:20 -04:00
John McCall
148357f899 Implement extended existential shapes and type metadata.
The immediate use case is only concretely-constrained existential
types, which could use a much simpler representation, but I've
future-proofed the representation as much as I can; thus, the
requirement signature can have arbitrary parameters and
requirements, and the type can have an arbitrary type as the
sub-expression.  The latter is also necessary for existential
metatypes.

The chief implementation complexity here is that we must be able
to agree on the identity of an existential type that might be
produced by substitution.  Thus, for example, `any P<T>` when
`T == Int` must resolve to the same type metadata as
`any P<Int>`.  To handle this, we identify the "shape" of the
existential type, consisting of those parts which cannot possibly
be the result of substitution, and then abstract the substitutable
"holes" as an application of a generalization signature.  That
algorithm will come in a later patch; this patch just represents
it.

Uniquing existential shapes from the requirements would be quite
complex because of all the symbolic mangled names they use.
This is particularly true because it's not reasonable to require
translation units to agree about what portions they mangle vs.
reference symbolically.  Instead, we expect the compiler to do
a cryptographic hash of a mangling of the shape, then use that
as the unique key identifying the shape.

This is just the core representation and runtime interface; other
parts of the runtime, such as dynamic casting and demangling
support, will come later.
2022-03-27 18:24:17 -04:00
Mike Ash
ae2b5140ed [RemoteMirror][swift-inspect] Decode locks in priority-escalation concurrency runtime.
When possible, decode the DrainLock/ExecutionLock fields of tasks and actors in concurrency runtimes built with priority escalation, and show the corresponding thread info in swift-inspect output.

We weren't properly decoding actor flags previously, so fix that up as well and have Remote Mirror split them out into separate fields so clients don't have to. We were missing the Job Storage field from the definition of DefaultActorImpl in RuntimeInternals.h, fix that so we actually read the right data.

rdar://88598003
2022-03-18 15:41:16 -04:00
Mike Ash
5fd87a8ee3 [swift-inspect][RemoteMirror] Decode job/task/actor flags.
Have RemoteMirror internally decode these flags fields and return them as separate fields in the task/actor info. Handle the structures both with and without task escalation support.

Also show when a task is the current task on a thread in swift-inspect's task listing.

rdar://88598003
2022-03-14 16:20:05 -04:00
Tim Kientzle
4d91b45988 [RemoteMirror] Get spare bit info from reflection records (#40906)
This adds a new reflection record type carrying spare bit information for multi-payload enums.

The compiler includes this for any type that might need it in order to accurately reflect the contents of the enum. The RemoteMirror library will use this if present to determine how to project the contents of the enum. If not present (for example, in older binaries), the RemoteMirror library falls back on an internal calculation of the spare bitmask.

A few notes:
 * The internal calculation is not perfect.  In particular, it does not support MPEs that contain other enums (e.g., optionals).  It should accurately refuse to project any MPE that it does not correctly support.
 * The new reflection field is designed to be expandable; this might someday avoid the need for a new section.

Resolves rdar://61158214
2022-02-21 17:06:14 -08:00
Rokhini Prabhu
a3e3c3fcbb Update the Reflection headers to deal with the new layout changes in the
DefaultActor

Radar-Id: rdar://problem/86100521
2022-02-16 10:22:18 -08:00
Rokhini Prabhu
d77edf6cd9 Merge pull request #41088 from apple/rokhinip/76127624-task-priority-escalation
Task Priority Escalation
2022-02-08 10:00:55 -08:00
Rokhini Prabhu
ff10907a8e Change ActiveTaskStatus layout in order to be able to track the identity
of the thread that is executing the task.

Radar-Id: rdar://problem/76127624
2022-02-07 16:34:46 -08:00
Saleem Abdulrasool
7c8005197c Merge pull request #41221 from apple/compnerd/padding
Reflection: correct conformance table iteration
2022-02-06 10:13:43 -08:00
Saleem Abdulrasool
ff7ba2a7ea Reflection: correct conformance table iteration
Adjust the iteration of the conformance table to match the current data structure layout.

`MapData` is a view into the `ConformanceState`:
~~~
[+0x00] Cache                 [Type: swift::ConcurrentReadableHashMap<ConformaanceCacheEntry, swift::StaticMutex>]
[+0x28] SectionsToScan        [Type: swift::ConcurrentReadableArray<ConformanceSection>]
[+0x50] scanSectionsBackwards [Type: bool]
~~~

`Cache` itself is a structure:
~~~
[+0x00] ReaderCount           [Type: std::atomic<uint32_t>]
[+0x04] ElementCount          [Type: std::atomic<uint32_t>]
[+0x08] Elements              [Type: std::atomic<swift::ConcurrentReadableHashMap<ConformanceCacheEntry, swift::staticMutex>::ElementStorage *>]
~~~

The `ElementStorage` backing `Elements` actually looks like:
~~~
[+0x00] Capacity              [Type: uint32_t]
[+0x08] Elem                  [Typwe: ConformanceCacheEntry]
~~~

The `Capacity` field will be pointer aligned (a previous change has changed this
to be explicitly pointer sized bit-sliced).  However, we would previously fail
to accomodate the `Capacity` field, and read the contents shifted by the size of
`Capacity`.  This repairs the iteration off the `ConformanceCache`.
2022-02-04 17:10:58 -08:00
Saleem Abdulrasool
3253400ed1 Reflection: drop compatibility with old runtime layouts
This removes the compatibility code (which seems suspect) for the runtime datastructures.  Identified through Windows, this path will potentially misread the field and treat a pair of `uint32_t` as a pointer, which may succeed any way.
2022-02-04 17:01:40 -08:00
Mike Ash
bd434d4a56 Merge pull request #41160 from mikeash/swift-inspect-concurrency
[RemoteMirror][swift-inspect] Add a command to inspect the state of the concurrency runtime.
2022-02-04 12:41:20 -05:00
Mike Ash
a82ea120a4 [RemoteMirror][swift-inspect] Add a command to inspect the state of the concurrency runtime.
Most of the new inspection logic is in Remote Mirror. New code in swift-inspect calls the new Remote Mirror functions and formats the resulting information for display.

Specific Remote Mirror changes:

* Add a call to check if a given metadata is an actor.
* Add calls to get information about actors and tasks.
* Add a `readObj` call to MemoryReader that combines the read and the cast, greatly simplifying code chasing pointers in the remote process.
* Add a generalized facility to the C shims that can allocate a temporary object that remains valid until at least the next call, which is used to return various temporary arrays from the new calls. Remove the existing `lastString` and `lastChunks` member variables in favor of this new facility.

Swift-inspect changes:

* Add a new dump-concurrency command.
* Add a new `ConcurrencyDumper.swift` file with the implementation. The dumper needs to do some additional work with the results from Remote Mirror to build up the task tree and this keeps it all organized.
* Extend `Inspector` to query the target's threads and fetch each thread's current task.

Concurrency runtime changes:

* Add `_swift_concurrency_debug` variables pointing to the various future adapters. Remote Mirror uses these to provide a better view of a tasks's resume pointer.

rdar://85231338
2022-02-04 09:28:32 -05:00
Artem Chikin
f432f1b414 Fix section name lookup in findMachOSectionByName to do comparison up-to the 16-byte section name limit, instead of the queried name length. 2022-01-27 11:23:41 -08:00
Artem Chikin
e934fe201a Add extraction protocol conformance descriptor extraction, as read from an object file image, to TypeRefBuilder. 2022-01-26 13:54:02 -08:00
Artem Chikin
d6d4216371 Add Conformance section to ReflectionInfo read from object files 2022-01-24 16:46:35 -08:00
Mike Ash
f3493bf149 [Reflection] Fix async task slab size calculation.
The calculation failed to account for padding after the slab struct itself. We already account for this padding in HeaderSize, so use that instead of the raw struct size.

rdar://87607280
2022-01-19 12:38:41 -05:00
Mike Ash
cf3c131e7c [Reflection] Add API for inspecting async task allocation slabs.
We remove the existing `swift_reflection_iterateAsyncTaskAllocations` API that attempts to provide all necessary information about a tasks's allocations starting from the task. Instead, we split it into two pieces: `swift_reflection_asyncTaskSlabPointer` to get the first slab for a task, and `+swift_reflection_asyncTaskSlabAllocations` to get the allocations in a slab, and a pointer to the next slab.

We also add a dummy metadata pointer to the beginning of each slab. This allows tools to identify slab allocations on the heap without needing to locate every single async task object. They can then use `swift_reflection_asyncTaskSlabAllocations` on such allocations to find out about the contents.

rdar://82549631
2021-11-18 14:15:25 -05:00
Mike Ash
89d93a000d [Runtime] Replace std::max_align_t with MaximumAlignment from MetadataValues.h.
On Windows, std::max_align_t is only 8-byte aligned, but Swift assumes 16-byte alignment. MaximumAlignment is our notion of the maximum alignment of a type, so use that instead.
2021-11-18 13:56:05 -05:00
Saleem Abdulrasool
3c9c564eba Revert "[Reflection] Add API for inspecting async task allocation slabs." 2021-11-17 18:47:13 -08:00
Mike Ash
7c7dc5d5b3 [Reflection] Add API for inspecting async task allocation slabs.
We remove the existing `swift_reflection_iterateAsyncTaskAllocations` API that attempts to provide all necessary information about a tasks's allocations starting from the task. Instead, we split it into two pieces: `swift_reflection_asyncTaskSlabPointer` to get the first slab for a task, and `+swift_reflection_asyncTaskSlabAllocations` to get the allocations in a slab, and a pointer to the next slab.

We also add a dummy metadata pointer to the beginning of each slab. This allows tools to identify slab allocations on the heap without needing to locate every single async task object. They can then use `swift_reflection_asyncTaskSlabAllocations` on such allocations to find out about the contents.

rdar://82549631
2021-11-11 16:58:14 -05:00
Mike Ash
2e4754344a [Reflection] Fix ReflectionContext::allocationMetadataPointer.
The definition of GenericMetadataCacheEntry was wrong, causing the function to return garbage.
2021-10-15 15:17:32 -04:00
Mike Ash
c0e6e1d878 [Reflection] Fix iterateAsyncTaskAllocations.
Fix the declaration of AsyncTask and add a test for iterateAsyncTaskAllocations. Reflection's declaration of AsyncTask had fallen out of sync with the real thing. The test that was supposed to catch this was never actually committed, oops.

Add a swift_reflection_libraryVersion variable to Remote Mirror to indicate the presence of this fix. In the future, the value can be incremented to signal the presence of other changes that can't otherwise be detected.

rdar://80035307
2021-07-02 17:33:20 -04:00
Augusto Noronha
0a67868a13 Implement ReflectionContext::addImage with section finder
Implement a version of addImage that takes in a closure responsible
for finding the sections of interest. This allows for the registration
of metadata even in situations where the object file is not complete
(for example, when generated by the JIT).
2021-06-24 17:35:57 -03:00
Alastair Houghton
eb68120112 [RemoteMirror] Add new API for getting the type descriptor address.
This will allow the heap tool to work out which binary a dynamically allocated
class comes from, by looking up its nominal type descriptor address and then
seeing which binary contains that.

Fixes rdar://65742351.
2021-06-17 10:50:21 +01:00
Augusto Noronha
f41d192b48 Implement projectExistentialAndUnwrapClass
Implement a version of projectExistential tailored for LLDB. There are 2
differences when projecting existentials for LLDB:

1 - When it comes to existentials, LLDB stores the address of the error
    pointer, which must be dereferenced.
2 - When the existential wraps a class type, LLDB expects the address
    returned is the class instance itself and not the address of the
    reference.

This patch also adapts the swift reflection test machinery to test
projectExistentialAndUnwrapClass as well. This is done by exposing
the new functionality from swift reflection test.  It is tested in
existentials.swift, and ensures that the typeref information is
exactly the same as what is expected from projectExistential,
except the out address.

(cherry picked from commit 55e971e06750c3ba29722d558cc5400298f6bdaf)
2021-06-16 08:54:50 -03:00
Augusto Noronha
b54d42653e Read machO sections section by section
This changes how ReflectionContext reads machO reflection sections by reading them individually instead of as one big memory block spanning from the first to the last section (and including whatever else is in between). This change will enable an optimization on LLDB's side where, if we're reading read-only data, we read from the file-cache instead of the child process, which should speed up debugging when working with remote processes.
2021-04-23 14:16:50 -03:00
Adrian Prantl
38148be26f Add missing error handling to ReflectionContext
We found crashes deep in TypeRefBuilder that could traced back to a likely
nullptr RemoteRef<> section address. It is very plausible that this is
connected to a failed MemoryReader::getBytes() call, which can fail but
isn't checked.

This patch adds missing error checks to every call to readBytes().

rdar://74445486
(cherry picked from commit 714cefbba4)
2021-02-24 15:09:14 -08:00
Mike Ash
31f68b1687 [RemoteMirror] Add a call for iterating over the allocations belonging to an AsyncTask.
rdar://72907056
2021-02-11 17:14:38 -05:00
John McCall
0fb407943f [NFC] Rename swift_runtime_unreachable to swift_unreachable and make it use LLVM's support when available. 2020-10-03 02:54:56 -04:00
Adrian Prantl
4b9cf31ba0 Add a callback to swift::reflection::MemoryReader that allows LLDB to provide
swift::reflection::TypeInfo for (Clang-)imported non-Objective-C types. This is
needed to reflect on the size mixed Swift / Clang types, when no type metadata
is available for the C types.

This is a necessary ingredient for the TypeRef-based Swift context in
LLDB. Because we do not have reflection metadata for pure C types in Swift,
reflection cannot compute TypeInfo for NominalTypeRefs for those types. By
providing this callback, LLDB can supply this information for DWARF, and
reflection can compute TypeInfos for mixed Swift/C types.
2020-08-25 15:19:49 -07:00
Mike Ash
ecd6d4ddec Add a new ConcurrentReadableHashMap type. Switch the protocol conformance cache
to use it.

ConcurrentReadableHashMap is lock-free for readers, with writers using a lock to
ensure mutual exclusion amongst each other. The intent is to eventually replace
all uses ConcurrentMap with ConcurrentReadableHashMap.

ConcurrentReadableHashMap provides for relatively quick lookups by using a hash
table. Rearders perform an atomic increment/decrement in order to inform writers
that there are active readers. The design attempts to minimize wasted memory by
storing the actual elements out-of-line, and having the table store indices into
a separate array of elements.

The protocol conformance cache now uses ConcurrentReadableHashMap, which
provides faster lookups and less memory use than the previous ConcurrentMap
implementation. The previous implementation caches
ProtocolConformanceDescriptors and extracts the WitnessTable after the cache
lookup. The new implementation directly caches the WitnessTable, removing an
extra step (potentially a quite slow one) from the fast path.

The previous implementation used a generational scheme to detect when negative
cache entries became obsolete due to new dynamic libraries being loaded, and
update them in place. The new implementation just clears the entire cache when
libraries are loaded, greatly simplifying the code and saving the memory needed
to track the current generation in each negative cache entry. This means we need
to re-cache all requested conformances after loading a dynamic library, but
loading libraries at runtime is rare and slow anyway.

rdar://problem/67268325
2020-08-20 13:05:30 -04:00
Augusto Noronha
d2e162676d Fix reading elf section from file buffer 2020-08-13 08:26:11 -03:00
Augusto Noronha
7cd920403d Fix reading metadata from ELF sections 2020-08-11 20:45:23 -03:00
adrian-prantl
722da4bbfa Merge pull request #33358 from augusto2112/reflection-section-constants
Add functionality that returns correct reflection section name for different object files (Mach-O, ELF, COFF)
2020-08-11 16:18:00 -07:00
Augusto Noronha
34c55e2d99 Add functionality that returns correct reflection section name for different object files 2020-08-10 17:21:08 -03:00
Mike Ash
b65d2b5f99 [Reflection][swift-inspect] Add a command for dumping metadata cache nodes. 2020-07-15 14:01:49 -04:00
Mike Ash
5eb226557b [swift-inspect] Support DLQ_GetPtrAuthMask. While we're in there, fix an snprintf warning in ReflectionContext.h 2020-07-10 12:34:25 -04:00
Augusto Noronha
5cee6f3d6a Unify 'MetadataSections' data structure, as well as common ELF and COFF procedures 2020-06-29 19:35:44 -03:00
Mike Ash
c925ce502b Merge pull request #32388 from mikeash/swift-inspect-tag-names
[Reflection][swift-inspect] Show tag names when dumping raw metadata allocations.
2020-06-17 16:14:20 -04:00
Mike Ash
3fcf86ac01 [Reflection][swift-inspect] Show tag names when dumping raw metadata allocations. 2020-06-17 11:31:12 -04:00
David Zarzycki
bf8f50f6eb [Reflection] NFC: Workaround LLVM C++ standard library weirdness
Pull request #32244 introduced the use of `std::stringstream` but that
causes vtables to be generated and we don't want that.
2020-06-16 08:08:34 -04:00
Mike Ash
cd624bf380 [Runtime][Reflection][swift-inspect] Add facilities for tracking and examining backtraces for metadata allocations.
rdar://problem/63674755
2020-06-11 14:49:52 -04:00
Mike Ash
aea7d03063 [Reflection] Remove useless TaggedUnion.h include. Comment swift_metadata_allocation_tag. 2020-05-29 08:31:04 -07:00
Mike Ash
88046363f1 Minor cleanup of initial swiftdt work. 2020-05-29 08:31:03 -07:00
Mike Ash
7ca1392678 [Reflection] Clean up the ReflectionContext additions.
Move the internal runtime structures into RuntimeInternals.h. Remove leftover methods. Comment the new methods.

rdar://problem/55481578
2020-05-29 08:31:03 -07:00
Mike Ash
ad09919891 [Runtime] Expose the protocol conformance state as a _swift_debug variable.
Have Remote Mirror look that up instead of the C++ mangled name.

rdar://problem/55481578
2020-05-29 08:31:03 -07:00
Mike Ash
b73b325e10 [Runtime] Only enable metadata allocation tracking when requested with an environment variable.
Expose _swift_debug variables for Remote Mirror to use for tracking metadata allocation, and adopt them in Remote Mirror.

rdar://problem/55481578
2020-05-29 08:31:03 -07:00
Mike Ash
d9805ca4eb [Reflection] Add error messages to the new Remote Mirror calls and plumb them through swiftdt.
rdar://problem/55481578
2020-05-29 08:31:03 -07:00
Mike Ash
df5580bcfc [Tools] Move metadata dumping into swiftdt, have Remote Mirror just iterate and inspect.
rdar://problem/55481578
2020-05-29 08:31:03 -07:00