Commit Graph

296 Commits

Author SHA1 Message Date
Mike Ash
a317b8737a Merge pull request #30739 from mikeash/remote-mirror-fix-ownsaddress
[Reflection] Fix the ownsAddress function to claim heap-allocated Metadatas
2020-04-01 14:46:49 -04:00
tbkka
3c8fde7885 Implement MultiPayloadEnum support for projectEnumValue (#30635)
This code rearchitects and simplifies the projectEnumValue support by
introducing a new `TypeInfo` subclass for each kind of enum, including trivial,
no-payload, single-payload, and three different classes for multi-payload enums:

* "UnsupportedEnum" that we don't understand.  This returns "don't know" answers for all requests in cases where the runtime lacks enough information to accurately handle a particular enum.

* MP Enums that only use a separate tag value.  This includes generic enums and other dynamic layouts, as well as enums whose payloads have no spare bits.

* MP Enums that use spare bits, possibly in addition to a separate tag.  This logic can only be used, of course, if we can in fact compute a spare bit mask that agrees with the compiler.

The final challenge is to choose one of the above three handlings for every MPE.  Currently, we do not have an accurate source of information for the spare bit mask, so we never choose the third option above.  We use the second option for dynamic MPE layouts (including generics) and the first for everything else.

TODO: Once we can arrange for the compiler to expose spare bit mask data, we'll be able to use that to drive more MPE cases.
2020-03-31 15:12:44 -07:00
Mike Ash
5da118eef2 [Reflection] Fix the ownsAddress function to claim heap-allocated Metadatas.
ownsAddress was a simple range check on images, but that won't find Metadatas that get allocated on the heap. If an address isn't found, try reading it as a Metadata and doing a range check on the type context descriptor too.

rdar://problem/60981575
2020-03-31 16:49:56 -04:00
tbkka
94a09104fe Don't try to look up info for a null TypeRef (#30640)
This indirectly hardens the `swift_reflection_infoForTypeRef` API
against being invoked with a null TypeRef pointer.  The API already
handles a nullptr being returned from `TypeConverter::getTypeInfo`
by converting it into a standard "UNKNOWN" type info descriptor.

Resolves rdar://60633988
2020-03-25 18:27:59 -07:00
tbkka
ee36c1cc3e RemoteMirror: Project some multi-payload enums (#30357)
* First part of multi-payload enum support

This handles multi-payload enums with fixed
layouts that don't use spare payload bits.
It includes XI calculations that allow us to
handle single-payload enums where the payload
ultimately includes a multi-payload enum
(For example, on 32-bit platforms, String uses
a multi-payload enum, so this now supports single-payload
enums carrying Strings.)
2020-03-11 18:48:39 -07:00
Mike Ash
b80e33b514 Fix reuse of the payload area when the discriminator != 0 2020-03-09 11:58:54 -07:00
tbkka
0d361bd3ea Teach RemoteMirror how to project enum values (#30161)
Teach RemoteMirror how to project enum values

This adds two new functions to the SwiftRemoteMirror
facility that support inspecting enum values.

Currently, these support non-payload enums and
single-payload enums, including nested enums and
payloads with struct, tuple, and reference payloads.
In particular, it handles nested `Optional` types.

TODO: Multi-payload enums use different strategies for
encoding the cases that aren't yet supported by this
code.

Note: This relies on information from dataLayoutQuery
to correctly decode invalid pointer values that are used
to encode enums.  Existing clients will need to augment
their DLQ functions before using these new APIs.

Resolves rdar://59961527

```
/// Projects the value of an enum.
///
/// Takes the address and typeref for an enum and determines the
/// index of the currently-selected case within the enum.
///
/// Returns true iff the enum case could be successfully determined.
/// In particular, note that this code may fail for valid in-memory data
/// if the compiler is using a strategy we do not yet understand.
SWIFT_REMOTE_MIRROR_LINKAGE
int swift_reflection_projectEnumValue(SwiftReflectionContextRef ContextRef,
                                      swift_addr_t EnumAddress,
                                      swift_typeref_t EnumTypeRef,
                                      uint64_t *CaseIndex);

/// Finds information about a particular enum case.
///
/// Given an enum typeref and index of a case, returns:
/// * Typeref of the associated payload or zero if there is no payload
/// * Name of the case if known.
///
/// The Name points to a freshly-allocated C string on the heap.  You
/// are responsible for freeing the string (via `free()`) when you are finished.
SWIFT_REMOTE_MIRROR_LINKAGE
int swift_reflection_getEnumCaseTypeRef(SwiftReflectionContextRef ContextRef,
                                        swift_typeref_t EnumTypeRef,
                                        unsigned CaseIndex,
                                        char **CaseName,
                                        swift_typeref_t *PayloadTypeRef);
```


Co-authored-by: Mike Ash <mikeash@apple.com>
2020-03-06 13:17:40 -08:00
Adrian Prantl
ea2b5eced9 Reflection: Implement a TypeRef -> Demangle tree adapter.
To allow more pervasive use of TypeRefs in LLDB, we need a way to build mangled
names from TypeRef pointers to allow round-tripping between TypeRefs and AST
types. The goal is to experiment with making lldb::CompilerType backed by
TypeRefs instead of AST types.

<rdar://problem/55412775>
2020-01-14 17:50:01 -08:00
David Zarzycki
3d1739fa86 NFC: Fix -Wdeprecated-copy warnings 2020-01-07 16:09:00 -05:00
Ivan Smetanin
dd7d173c97 [stdlib] [reflection] Excise iostream from reflection 2019-10-14 20:28:20 +03:00
Joe Groff
8821c6cf26 swift-reflection-dump: Create ReflectionContext with correct target pointer size
Necessary to make sure we read pointers as the right size, and use the correct object layouts
when using swift-reflection-dump for cross-platform dumps.
2019-10-02 12:41:59 -07:00
Joe Groff
5d3ee68f9c swift-reflection-dump: Base ObjectMemoryReader address space on image vm address.
As the base of the "remote" address space ObjectMemoryReader presents for an image, use the
image's own preferred VM address mappings. If there are multiple images loaded, differentiate
them by using the top 16 bits of the remote address space as an index into the array of images.

This should make it so that absolute pointers in the file Just Work without sliding in most
cases; we'd only need to mix in the image index in order to have a value that is also a valid
remote address.
2019-10-01 12:12:25 -07:00
Joe Groff
40e40103a8 Merge pull request #27418 from jckarter/reflection-symbolic-absolute-pointer
MetadataReader: Add an API for reading absolute pointers.
2019-09-30 08:48:32 -07:00
Joe Groff
4012a207c8 MetadataReader: Add an API for reading absolute pointers.
Pointer data in some remote reflection targets may required relocation, or may not be
fully resolvable, such as when we're dumping info from a single image on disk that
references other dynamic libraries. Add a `RemoteAbsolutePointer` type that can hold a
symbol, offset, or combination of both, and add APIs to `MemoryReader` and `MetadataReader`
for reading pointers that can get unresolved relocation info from an image, or apply
relocations to pointer information. MetadataReader can use the symbol name information to
fill in demanglings of symbolic-reference-bearing mangled names by using the information
from the symbol name to fill in the name even though the context descriptors are not
available.

For now, this is NFC (MemoryReader::resolvePointer just forwards the pointer data), but
lays the groundwork for implementation of relocation in ObjectMemoryReader.
2019-09-28 16:53:34 -07:00
Joe Groff
12bf25e75d Merge pull request #27388 from jckarter/reflection-remove-start-addresses
swift-reflection-dump: Virtualize logical-to-physical address mapping.
2019-09-27 14:09:22 -07:00
Saleem Abdulrasool
8db900634d Revert "Fix parsing of ELF images"
This reverts commit e2b6a3d982.  This
broke on the handling of x86_64 relocation as well as the Windows build
process.
2019-09-27 08:14:32 -07:00
Jordan Rose
a6dd630ca3 Eliminate Builtin.UnknownObject as an AST type (#27378)
This removes it from the AST and largely replaces it with AnyObject
at the SIL and IRGen layers. Some notes:

- Reflection still uses the notion of "unknown object" to mean an
  object with unknown refcounting. There's no real reason to make
  this different from AnyObject (an existential containing a
  single object with unknown refcounting), but this way nothing
  changes for clients of Reflection, and it's consistent with how
  native objects are represented.

- The value witness table and reflection descriptor for AnyObject
  use the mangling "BO" instead of "yXl".

- The demangler and remangler continue to support "BO" because it's
  still in use as a type encoding, even if it's not an AST-level
  Type anymore.

- Type-based alias analysis for Builtin.UnknownObject was incorrect,
  so it's a good thing we weren't using it.

- Same with enum layout. (This one assumed UnknownObject never
  referred to an Objective-C tagged pointer. That certainly wasn't how
  we were using it!)
2019-09-26 17:48:04 -07:00
Alexander Shaposhnikov
e2b6a3d982 Fix parsing of ELF images 2019-09-26 14:37:36 -07:00
Joe Groff
14453147d6 Reflection: Remove StartAddress from ReflectionInfo.
We now get the local/remote mapping from RemoteRef when we need it.
2019-09-26 12:09:52 -07:00
Joe Groff
633471c092 Reflection: Share demangler with MetadataReader.
TypeRefBuilder and MetadataReader had nearly identical symbolic reference resolvers,
but diverged because TypeRefBuilder had its own local/remote address management mechanism,
and because TypeRefBuilder tries to resolve opaque types to their underlying types, whereas
other MetadataReader clients want to preserve them as written in source. The first problem
has been addressed by making TypeRefBuilder use `RemoteRef` everywhere, and the second
can be handled with a flag (and might be able to be handled more elegantly with some more
refactoring of general opaque type handling in MetadataReader).
2019-09-26 11:28:00 -07:00
Joe Groff
8c4df3b4c2 Reflection: Traffic in RemoteRefs.
Instead of passing around raw local pointers and references, and spreading
tricky offset arithmetic around with the Local/RemoteAddress fields in
ReflectionInfo, have the TypeRefBuilder code use RemoteRefs everywhere,
which keep the remote/local mapping together in one unit and provide
centralized API for this logic.

This doesn't yet change how code uses the RemoteRef address data to
follow pointers across objects, for things like reading type refs, but
that should be much easier to do after this lands.
2019-09-25 20:28:03 -07:00
Joe Groff
83b34ab8d3 Merge pull request #27306 from jckarter/remove-reflection-offsets
Reflection: Remove vestigial Offset fields from ReflectionInfo
2019-09-24 10:04:20 -07:00
Joe Groff
bc3795eb53 Reflection: Remove vestigial Offset fields from ReflectionInfo
These are now always zero, because memory readers handle virtual address mapping.
The `swift_reflection_info_t` structure used by the C RemoteMirror API keeps
its offset fields because it's supposed to be a stable API, but we now assert that
the values are always zero.
2019-09-23 14:32:26 -07:00
Joe Groff
ebca730bcf Merge pull request #27274 from jckarter/detemplate-remote-ref
Reflection: Make RemoteRef template not depend on Runtime.
2019-09-23 13:45:03 -07:00
Joe Groff
88a833f19c Reflection: Move resolveRelativeField functionality onto RemoteRef
Resolving a direct relative reference given a RemoteRef doesn't need the MetadataReader,
since the offset should already be in the local buffer; we can add it to RemoteRef's
saved remote address and get a new remote address. Refactor the API to make as much as
possible of it available directly on RemoteRef.
2019-09-20 15:01:57 -07:00
Joe Groff
f1cb0d11ef Reflection: Make RemoteRef template not depend on Runtime.
The only thing the Runtime affects is the width of the StoredPointer for the remote address, for
which storing a uint64_t ought to be enough for anyone we care about so far. This will make it
easier to store and use RemoteRefs in code that isn't or shouldn't ideally be templatized on
Runtime (such as TypeRefBuilder, and ultimately ReflectionContext, from the Reflection library.)
2019-09-20 12:43:51 -07:00
Joe Groff
761b02949a ReflectionContext: Remove platform #ifs for image format checks.
In principle, swift-reflection-* ought to work with cross-compiled binaries. Dispatch out to reading
MachO, PE, or ELF section metadata based on the magic of an image passed to `addImage` instead of
using #ifs to pick an implementation based on the host platform. (This still doesn't fully address
other host/target differences like word size or endianness, but is progress toward making the tool
target-agnostic.)
2019-09-18 11:43:35 -07:00
Joe Groff
f1e84994ed Demangler: Make symbolic reference resolver part of demangle(Symbol|Type) calls.
This makes for a cleaner and less implicit-context-heavy API, and makes it easier for symbolic
reference resolvers to do context-dependent things (like map the in-memory base address back to a
remote address in MetadataReader).
2019-09-13 15:47:08 -07:00
Joe Groff
33e7ed74bc ReflectionContext: Keep read range properly-aligned.
If a Mach-O image got emitted in just the wrong way, the range of `__TEXT,__swift*` sections to
read could end up starting at an unaligned address (because things like type refs have only one
byte alignment), and this would cause the reflection context to read an unaligned chunk of the
remote memory, causing alignment errors when addresses are mapped to the local copy. Keep the ranges
at least 8-byte-aligned to stave off the alignment issues we might run into with any metadata
structures, which are generally at most pointer aligned. Fixes rdar://problem/54556791
2019-08-26 16:24:26 -07:00
Joe Groff
4e493b0051 Reflection: Look through opaque type descriptors.
Turn an opaque type reference in a mangled name into its underlying type, if we can.
rdar://problem/46140707
2019-06-26 17:58:52 -07:00
Michael Gottesman
093691a82f Add a C++ mode to .h header. 2019-06-02 17:03:41 -07:00
Davide Italiano
b4434fdd8d [Reflection] Fix the computation of boundaries in getFieldName(). 2019-05-06 17:27:20 -07:00
Davide Italiano
1acedc6c69 [Reflection] Check that the offset is within the section.
<rdar://problem/49043621>
2019-05-03 17:09:09 -07:00
Joe Groff
95c43f4e18 Decode opaque types in the runtime demangler. 2019-04-17 14:44:40 -07:00
Joe Groff
05dfec0cda Push the conformance accessor hack down into getTypeByMangledName. 2019-04-17 14:44:40 -07:00
Saleem Abdulrasool
f13031f61d Reflection: remove unnecessary offset for MachO
Don't bother passing the slide for the MachO image as it is always 0.
2019-04-08 18:52:48 -07:00
Saleem Abdulrasool
f2986035ad Reflection: remove unnecessary offset for ELF
Don't bother passing the slide for the ELF image as it is always 0.
2019-04-08 18:52:48 -07:00
Saleem Abdulrasool
5b2e95d01f Reflection: remove unnecessary offset for COFF
Don't bother passing the slide for the COFF image as it is always 0.
2019-04-08 18:52:48 -07:00
Saleem Abdulrasool
8bf851064a Reflection: load the builtin section on Windows
This loads the builtin section metadata on Windows which is needed for
the tests.
2019-04-03 11:18:50 -07:00
Alexander Shaposhnikov
33fa33ff0d [Reflection] Fix several issues for COFF and ELF
Previously when ReflectionContext was parsing the image of a binary
(for ELF or COFF) it was making some incorrect assumptions about the location
of sections in the memory of a remote process. In particular, it was using the offsets
rather than the virtual addresses and it was incorrectly calculating the references (relative pointers)
inside the metadata. In this diff we address these issues and adjust swift-reflection-dump
(used in tests) to emulate the runtime behavior more closely.
This diff has been extensively tested, the reflection tests are green on OSX and Linux,
on Windows it fixes 2 new tests:
    Reflection/typeref_decoding.swift
    stdlib/ReflectionHashing.swift
So now (with some minor fixes to the lit testsing infrastructure) the following reflection
tests pass:
    Reflection/box_descriptors.sil
    Reflection/capture_descriptors.sil
    Reflection/typeref_decoding.swift
    stdlib/ReflectionHashing.swift
2019-04-02 21:22:56 -07:00
Erik Eckstein
d7fd45d74a Remangler: Use a bump-pointer allocated string instead of std::string
Done by replacing DemanglerPrinter with a bump-pointer allocated CharVector buffer.
This avoids malloc calls.

SR-10028
rdar://problem/48575729
2019-03-06 14:37:03 -08:00
Erik Eckstein
3bd7f027f8 Runtime: use SmallVector instead of std::vector to avoid memory allocations in most cases.
This dramatically reduces the number of needed malloc calls.
Unfortunately I had to add the implementation of SmallVectorBase::grow_pod to the runtime, as we don't link LLVM. This is a bad hack, but better than re-inventing a new SmallVector implementation.

SR-10028
rdar://problem/48575729
2019-03-06 14:37:03 -08:00
Saleem Abdulrasool
0cf91f343e Reflection: add PE/COFF magic checking for inspection
When we inspect a binary, verify that it is a PE/COFF binary before
trying to interpret it as a PE/COFF binary.  This prepares the code
for extraction of the file inspection and will permit cross-platform
builds to introspect foreign binaries.
2019-02-28 09:03:04 -08:00
Daniel Rodríguez Troitiño
3f76e63b6e Merge pull request #22899 from drodriguez/reflection-context-fix-2
Reflection: try holding 32/64 address offset in target machine pointers.
2019-02-27 11:34:36 -08:00
Alexander Shaposhnikov
848b8efd34 [Reflection] Add first bits to support COFF
In this diff we add first bits to make reflection work on Windows,
in particular, properly extract the metadata from the corresponding sections.
With this diff box_descriptors.sil and capture_descriptors.sil start passing on Windows
after some minor tweaks to the lit testing infrastructure.
2019-02-26 17:12:53 -08:00
Daniel Rodríguez Troitiño
8bee95d232 Reflection: try holding 32/64 address offset in type big enough for all architectures.
When compiling for a 32 bit machine, uintptr_t from ReflectionInfo will
be the integer sized to hold a 32 bit pointer, so a 64 bit pointer might
not fit.

This commit removes the solution in
0f20c486e0 and does a runtime check that
the calculated offset will fit into the target machine uintptr_t, which
might not be true for 32 bits machines trying to read 64 bits images,
which should not be that common (and those images have to have offsets
bigger than what a 32 bits number can hold).
2019-02-26 13:31:35 -08:00
Saleem Abdulrasool
0f20c486e0 Reflection: prevent address truncation on ELF64
Ensure that we use the address type as specified by ELF rather than
truncate to a 32-bit value.
2019-02-24 15:40:48 -08:00
Daniel Rodríguez Troitiño
942d68e4eb Merge pull request #22632 from drodriguez/swift-reflection-dump-elf-32
[swift-reflection-dump] Support for ELF32.
2019-02-21 10:48:24 -08:00
Daniel Rodríguez Troitiño
ec86064209 [swift-reflection-dump] Support for ELF32.
Split the addImage method for ELF into two branches for ELF32 and for
ELF64 depending on the value stored in the identifier of the image.

Most of the code of the previous function moves into readELFSections,
which is build similar to the already existing readMachOSections. The
code is only modified to use the types from the template parameter.

This fixes a couple of reflection tests in Android armv7 (and I suppose
it should also fix the same problem in other 32 bits platforms which use
ELF).
2019-02-19 13:06:10 -08:00
Erik Eckstein
80e86fb5c3 Runtime: make the demangler use stack allocated memory.
This reduces the amount of mallocs significantly.
2019-02-15 09:29:49 -08:00