Commit Graph

15330 Commits

Author SHA1 Message Date
Dave Lee a553969712 [lldb] Remove unused AproposAllSubCommands (NFC) 2022-01-02 11:30:51 -08:00
Kazu Hirata 7e163afd9e Remove redundant void arguments (NFC)
Identified by modernize-redundant-void-arg.
2022-01-02 10:20:19 -08:00
Kazu Hirata 677bbec9fd Remove unused "using" (NFC)
Identified by misc-unused-using-decls.
2022-01-02 10:20:17 -08:00
Kazu Hirata 8b649f98f6 [lldb] Add NOLINT(modernize-use-nullptr)
thread_result_t is defined as unsigned on Windows.

This patch prevents clang-tidy from replacing 0 with nullptr.
2022-01-01 13:14:59 -08:00
Kazu Hirata f4ffcab178 Remove redundant string initialization (NFC)
Identified by readability-redundant-string-init.
2022-01-01 12:34:11 -08:00
Kazu Hirata b8336280d8 [lldb] Use nullptr instead of 0 or NULL (NFC)
This is a re-submission of 24d2405588
without the hunks in HostNativeThreadBase.{h,cpp}, which break builds
on Windows.

Identified with modernize-use-nullptr.
2022-01-01 11:54:25 -08:00
Kazu Hirata 95f7112be8 Revert "[lldb] Use nullptr instead of 0 or NULL (NFC)"
This reverts commit 913457acf0.

It again broke builds on Windows:

  lldb/source/Host/common/HostNativeThreadBase.cpp(37,14): error:
  assigning to 'lldb::thread_result_t' (aka 'unsigned int') from
  incompatible type 'std::nullptr_t'
2022-01-01 11:15:14 -08:00
Kazu Hirata 913457acf0 [lldb] Use nullptr instead of 0 or NULL (NFC)
This is a re-submission of 24d2405588
without the hunk in HostNativeThreadBase.h, which breaks builds on
Windows.

Identified with modernize-use-nullptr.
2022-01-01 10:48:56 -08:00
Nico Weber 4f2eeb6a65 Revert "[lldb] Use nullptr instead of 0 or NULL (NFC)"
This reverts commit 24d2405588.
Breaks building on Windows:

    ../../lldb/include\lldb/Host/HostNativeThreadBase.h(49,36): error:
        cannot initialize a member subobject of type 'lldb::thread_result_t'
        (aka 'unsigned int') with an rvalue of type 'std::nullptr_t'
      lldb::thread_result_t m_result = nullptr;
                                       ^~~~~~~
    1 error generated.
2022-01-01 13:35:54 -05:00
Kazu Hirata 24d2405588 [lldb] Use nullptr instead of 0 or NULL (NFC)
Identified with modernize-use-nullptr.
2022-01-01 08:54:05 -08:00
Pavel Labath 249a5fb005 [lldb/qemu] Support setting arg0 of the debugged program
Just what it says on the box.
2021-12-31 10:57:35 +01:00
Pavel Labath 9b8f9d33db [lldb/qemu] More flexible emulator specification
This small patch adds two useful improvements:
- allows one to specify the emulator path as a bare filename, and have
  it be looked up in the PATH
- allows one to leave the path empty and have the filename be derived
  from the architecture.
2021-12-30 15:14:41 +01:00
Pavel Labath fdd741dd31 [lldb/linux] Fix a bug in wait status handling
The MonitorCallback function was assuming that the "exited" argument is
set whenever a thread exits, but the caller was only setting that flag
for the main thread.

This patch deletes the argument altogether, and lets MonitorCallback
compute what it needs itself.

This is almost NFC, since previously we would end up in the
"GetSignalInfo failed for unknown reasons" branch, which was doing the
same thing -- forgetting about the thread.
2021-12-29 11:06:30 +01:00
PoYao Chang 633b002944 [lldb] Fix PR52702 by fixing bool conversion of Mangled
Remove the Mangled::operator! and Mangled::operator void* where the
comments in header and implementation files disagree and replace them
with operator bool.

This fix PR52702 as https://reviews.llvm.org/D106837 used the buggy
Mangled::operator! in Symbol::SynthesizeNameIfNeeded. For example,
consider the symbol "puts" in a hello world C program:

// Inside Symbol::SynthesizeNameIfNeeded
(lldb) p m_mangled
(lldb_private::Mangled) $0 = (m_mangled = None, m_demangled = "puts")
(lldb) p !m_mangled
(bool) $1 = true          # should be false!!
This leads to Symbol::SynthesizeNameIfNeeded overwriting m_demangled
part of Mangled (in this case "puts").

In conclusion, this patch turns
callq  0x401030                  ; symbol stub for: ___lldb_unnamed_symbol36
back into
callq  0x401030                  ; symbol stub for: puts .

Differential Revision: https://reviews.llvm.org/D116217
2021-12-29 17:17:52 +08:00
Pavel Labath caa7e765e5 [lldb] Make ProcessLauncherPosixFork (mostly) async-signal-safe
Multithreaded applications using fork(2) need to be extra careful about
what they do in the fork child. Without any special precautions (which
only really work if you can fully control all threads) they can only
safely call async-signal-safe functions. This is because the forked
child will contain snapshot of the parents memory at a random moment in
the execution of all of the non-forking threads (this is where the
similarity with signals comes in).

For example, the other threads could have been holding locks that can
now never be released in the child process and any attempt to obtain
them would block. This is what sometimes happen when using tcmalloc --
our fork child ends up hanging in the memory allocation routine. It is
also what happened with our logging code, which is why we added a
pthread_atfork hackaround.

This patch implements a proper fix to the problem, by which is to make
the child code async-signal-safe. The ProcessLaunchInfo structure is
transformed into a simpler ForkLaunchInfo representation, one which can
be read without allocating memory and invoking complex library
functions.

Strictly speaking this implementation is not async-signal-safe, as it
still invokes library functions outside of the posix-blessed set of
entry points. Strictly adhering to the spec would mean reimplementing a
lot of the functionality in pure C, so instead I rely on the fact that
any reasonable implementation of some functions (e.g.,
basic_string::c_str()) will not start allocating memory or doing other
unsafe things.

The new child code does not call into our logging infrastructure, which
enables us to remove the pthread_atfork call from there.

Differential Revision: https://reviews.llvm.org/D116165
2021-12-29 09:45:47 +01:00
Greg Clayton 48207b2559 Fix "settings set -g" so it works again.
When we switched options over to use the Options.td file, a bug was introduced that caused the "-g" option for "settings set" to require a filename arguemnt. This patch fixes this issue and adds a test so this doesn't regress.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D116012
2021-12-28 11:03:09 -08:00
Greg Clayton a2154b1951 Cache the manual DWARF index out to the LLDB cache directory when the LLDB index cache is enabled.
This patch add the ability to cache the manual DWARF indexing results to disk for faster subsequent debug sessions. Manual DWARF indexing is time consuming and causes all DWARF to be fully parsed and indexed each time you debug a binary that doesn't have an acceptable accelerator table. Acceptable accelerator tables include .debug_names in DWARF5 or Apple accelerator tables.

This patch breaks up testing by testing all of the encoding and decoding of required C++ objects in a gtest unit test, and then has a test to verify the debug info cache is generated correctly.

This patch also adds the ability to track when a symbol table or DWARF index is loaded or saved to the cache in the "statistics dump" command. This is essential to know in statistics as it can help explain why a debug session was slower or faster than expected.

Reviewed By: labath, wallace

Differential Revision: https://reviews.llvm.org/D115951
2021-12-28 11:00:28 -08:00
Kazu Hirata 0542d15211 Remove redundant string initialization (NFC)
Identified with readability-redundant-string-init.
2021-12-26 09:39:26 -08:00
Luís Ferreira 46cdcf0873 [lldb] Add support for UTF-8 unicode formatting
This patch adds missing formatting for UTF-8 unicode.

Cross-referencing https://reviews.llvm.org/D66447

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D112564
2021-12-25 20:19:09 +00:00
Kazu Hirata 2d303e6781 Remove redundant return and continue statements (NFC)
Identified with readability-redundant-control-flow.
2021-12-24 23:17:54 -08:00
Kazu Hirata 76f0f1cc5c Use {DenseSet,SetVector,SmallPtrSet}::contains (NFC) 2021-12-24 21:43:06 -08:00
Kazu Hirata 62e48ed10f Use isa instead of dyn_cast (NFC) 2021-12-24 21:22:27 -08:00
Kazu Hirata 9c0a4227a9 Use Optional::getValueOr (NFC) 2021-12-24 20:57:40 -08:00
Jason Molenda 8a26ba6a02 Load binary by UUID from qProcessInfo packet fields
Support three new keys in the qProcessInfo response from the remote
gdb stub to handle the case of attaching to a core running some type
of standalone/firmware code and the stub knows the UUID and load
address-or-slide for the binary.  There will be no proper DynamicLoader
plugin in this scenario, but we can try to locate and load the binary
into lldb at the correct offset.

Differential Revision: https://reviews.llvm.org/D116211
rdar://75191077
2021-12-23 15:20:50 -08:00
Zequan Wu c3f0e1ea3e [LLDB][DWARF] Fix duplicate TypeSP in type list
Differential Revision: https://reviews.llvm.org/D115308
2021-12-22 16:36:56 -08:00
Michał Górny fb785877a9 [lldb] [Process/FreeBSDKernel] Introduce libkvm support
Introduce initial support for using libkvm on FreeBSD.  The library
can be used as an alternate implementation for processing kernel
coredumps but it can also be used to access live kernel memory through
specifying "/dev/mem" as the core file, i.e.:

    lldb --core /dev/mem /boot/kernel/kernel

Differential Revision: https://reviews.llvm.org/D116005
2021-12-22 16:14:03 +01:00
Pavel Labath e7c48f3cd5 [lldb] Use GetSupportedArchitectures on darwin platforms
This finishes the GetSupportedArchitectureAtIndex migration. There are
opportunities to simplify this even further, but I am going to leave
that to the platform owners.

Differential Revision: https://reviews.llvm.org/D116028
2021-12-22 13:47:33 +01:00
Pavel Labath 2efc6892d8 [lldb/python] Avoid more dangling pointers in python glue code 2021-12-22 13:47:06 +01:00
Jason Molenda 682532ca57 Support v2 of 'main bin spec' Mach-O LC_NOTE in corefiles
Version 2 of 'main bin spec' LC_NOTE allows for the specification
of a slide of where the binary is loaded in the corefile virtual
address space.  It also adds a (currently unused) platform field
for the main binary.

Some corefile creators will only have a UUID and an offset to be
applied to the binary.

Changed TestFirmwareCorefiles.py to test this new form of
'main bin spec' with a slide, and also to run on both x86_64
and arm64 macOS systems.

Differential Revision: https://reviews.llvm.org/D116094
rdar://85938455
2021-12-22 00:02:27 -08:00
Sam McCall af27466c50 Reland "[AST] Add UsingType: a sugar type for types found via UsingDecl"
This reverts commit cc56c66f27.
Fixed a bad assertion, the target of a UsingShadowDecl must not have
*local* qualifiers, but it can be a typedef whose underlying type is qualified.
2021-12-20 18:03:15 +01:00
Sam McCall cc56c66f27 Revert "[AST] Add UsingType: a sugar type for types found via UsingDecl"
This reverts commit e1600db19d.

Breaks sanitizer tests, at least on windows:
https://lab.llvm.org/buildbot/#/builders/127/builds/21592/steps/4/logs/stdio
2021-12-20 17:53:56 +01:00
Sam McCall e1600db19d [AST] Add UsingType: a sugar type for types found via UsingDecl
Currently there's no way to find the UsingDecl that a typeloc found its
underlying type through. Compare to DeclRefExpr::getFoundDecl().

Design decisions:
- a sugar type, as there are many contexts this type of use may appear in
- UsingType is a leaf like TypedefType, the underlying type has no TypeLoc
- not unified with UnresolvedUsingType: a single name is appealing,
  but being sometimes-sugar is often fiddly.
- not unified with TypedefType: the UsingShadowDecl is not a TypedefNameDecl or
  even a TypeDecl, and users think of these differently.
- does not cover other rarer aliases like objc @compatibility_alias,
  in order to be have a concrete API that's easy to understand.
- implicitly desugared by the hasDeclaration ASTMatcher, to avoid
  breaking existing patterns and following the precedent of ElaboratedType.

Scope:
- This does not cover types associated with template names introduced by
  using declarations. A future patch should introduce a sugar TemplateName
  variant for this. (CTAD deduced types fall under this)
- There are enough AST matchers to fix the in-tree clang-tidy tests and
  probably any other matchers, though more may be useful later.

Caveats:
- This changes a fairly common pattern in the AST people may depend on matching.
  Previously, typeLoc(loc(recordType())) matched whether a struct was
  referred to by its original scope or introduced via using-decl.
  Now, the using-decl case is not matched, and needs a separate matcher.
  This is similar to the case of typedefs but nevertheless both adds
  complexity and breaks existing code.

Differential Revision: https://reviews.llvm.org/D114251
2021-12-20 17:15:38 +01:00
Pavel Labath 35870c4422 [lldb] Summary provider for char flexible array members
Add a summary provider which can print char[] members at the ends of
structs.

Differential Revision: https://reviews.llvm.org/D113174
2021-12-20 12:30:34 +01:00
Pavel Labath 7406d236d8 [lldb/python] Fix (some) dangling pointers in our glue code
This starts to fix the other half of the lifetime problems in this code
-- dangling references. SB objects created on the stack will go away
when the function returns, which is a problem if the python code they
were meant for stashes a reference to them somewhere.  Most of the time
this goes by unnoticed, as the code rarely has a reason to store these,
but in case it does, we shouldn't respond by crashing.

This patch fixes the management for a couple of SB objects (Debugger,
Frame, Thread). The SB objects are now created on the heap, and
their ownership is immediately passed on to SWIG, which will ensure they
are destroyed when the last python reference goes away. I will handle
the other objects in separate patches.

I include one test which demonstrates the lifetime issue for SBDebugger.
Strictly speaking, one should create a test case for each of these
objects and each of the contexts they are being used. That would require
figuring out how to persist (and later access) each of these objects.
Some of those may involve a lot of hoop-jumping (we can run python code
from within a frame-format string). I don't think that is
necessary/worth it since the new wrapper functions make it very hard to
get this wrong.

Differential Revision: https://reviews.llvm.org/D115925
2021-12-20 09:42:08 +01:00
Jonas Devlieghere fa1260697e [lldb] Remove reproducer replay functionality
This is part of a bigger rework of the reproducer feature. See [1] for
more details.

[1] https://lists.llvm.org/pipermail/lldb-dev/2021-September/017045.html
2021-12-17 17:14:52 -08:00
Benjamin Kramer 12873d1a67 Silence unused variable warning in release builds
lldb/source/Core/DataFileCache.cpp:278:10: warning: unused variable 'pos' [-Wunused-variable]
    auto pos = m_string_to_offset.find(s);
         ^
lldb/source/Core/DataFileCache.cpp:277:18: warning: unused variable 'stroff' [-Wunused-variable]
    const size_t stroff = encoder.GetByteSize() - strtab_offset;
                 ^
2021-12-17 16:07:02 +01:00
Pavel Labath 586765c0ee [lldb/qemu] Add emulator-env-vars setting
This setting is for variables we want to pass to the emulator only --
then will be automatically removed from the target environment by our
environment diffing code. This variable can be used to pass various
QEMU_*** variables (although most of these can be passed through
emulator-args as well), as well as any other variables that can affect
the operation of the emulator (e.g. LD_LIBRARY_PATH).
2021-12-17 13:59:21 +01:00
Pavel Labath 11dc235c7d [lldb] Fix matchers for char array formatters
They were being applied too narrowly (they didn't cover signed char *,
for instance), and too broadly (they covered SomeTemplate<char[6]>) at
the same time.

Differential Revision: https://reviews.llvm.org/D112709
2021-12-17 10:06:38 +01:00
Greg Clayton da816ca0cb Added the ability to cache the finalized symbol tables subsequent debug sessions to start faster.
This is an updated version of the https://reviews.llvm.org/D113789 patch with the following changes:
- We no longer modify modification times of the cache files
- Use LLVM caching and cache pruning instead of making a new cache mechanism (See DataFileCache.h/.cpp)
- Add signature to start of each file since we are not using modification times so we can tell when caches are stale and remove and re-create the cache file as files are changed
- Add settings to control the cache size, disk percentage and expiration in days to keep cache size under control

This patch enables symbol tables to be cached in the LLDB index cache directory. All cache files are in a single directory and the files use unique names to ensure that files from the same path will re-use the same file as files get modified. This means as files change, their cache files will be deleted and updated. The modification time of each of the cache files is not modified so that access based pruning of the cache can be implemented.

The symbol table cache files start with a signature that uniquely identifies a file on disk and contains one or more of the following items:
- object file UUID if available
- object file mod time if available
- object name for BSD archive .o files that are in .a files if available

If none of these signature items are available, then the file will not be cached. This keeps temporary object files from expressions from being cached.

When the cache files are loaded on subsequent debug sessions, the signature is compare and if the file has been modified (uuid changes, mod time changes, or object file mod time changes) then the cache file is deleted and re-created.

Module caching must be enabled by the user before this can be used:

symbols.enable-lldb-index-cache (boolean) = false

(lldb) settings set symbols.enable-lldb-index-cache true

There is also a setting that allows the user to specify a module cache directory that defaults to a directory that defaults to being next to the symbols.clang-modules-cache-path directory in a temp directory:

(lldb) settings show symbols.lldb-index-cache-path
/var/folders/9p/472sr0c55l9b20x2zg36b91h0000gn/C/lldb/IndexCache

If this setting is enabled, the finalized symbol tables will be serialized and saved to disc so they can be quickly loaded next time you debug.

Each module can cache one or more files in the index cache directory. The cache file names must be unique to a file on disk and its architecture and object name for .o files in BSD archives. This allows universal mach-o files to support caching multuple architectures in the same module cache directory. Making the file based on the this info allows this cache file to be deleted and replaced when the file gets updated on disk. This keeps the cache from growing over time during the compile/edit/debug cycle and prevents out of space issues.

If the cache is enabled, the symbol table will be loaded from the cache the next time you debug if the module has not changed.

The cache also has settings to control the size of the cache on disk. Each time LLDB starts up with the index cache enable, the cache will be pruned to ensure it stays within the user defined settings:

(lldb) settings set symbols.lldb-index-cache-expiration-days <days>

A value of zero will disable cache files from expiring when the cache is pruned. The default value is 7 currently.

(lldb) settings set symbols.lldb-index-cache-max-byte-size <size>

A value of zero will disable pruning based on a total byte size. The default value is zero currently.
(lldb) settings set symbols.lldb-index-cache-max-percent <percentage-of-disk-space>

A value of 100 will allow the disc to be filled to the max, a value of zero will disable percentage pruning. The default value is zero.

Reviewed By: labath, wallace

Differential Revision: https://reviews.llvm.org/D115324
2021-12-16 09:59:55 -08:00
Adrian Prantl 11c2af04f2 Remove redundant check (NFC) 2021-12-15 14:54:03 -08:00
Adrian Prantl 8b62429063 Use StringRef instead of char* (NFC) 2021-12-15 14:48:39 -08:00
Michał Górny 9c7fbc3f9b [lldb] Introduce a FreeBSDKernel plugin for vmcores
Introduce a FreeBSDKernel plugin that provides the ability to read
FreeBSD kernel core dumps.  The plugin utilizes libfbsdvmcore to provide
support for both "full memory dump" and minidump formats across variety
of architectures supported by FreeBSD.  It provides the ability to read
kernel memory, as well as the crashed thread status with registers
on arm64, i386 and x86_64.

Differential Revision: https://reviews.llvm.org/D114911
2021-12-14 22:07:20 +01:00
Jonas Devlieghere 100863ccd8 [lldb] Check if language is supported before creating a REPL instance
Currently, we'll try to instantiate a ClangREPL for every known
language. The plugin manager already knows what languages it supports,
so rely on that to only instantiate a REPL when we know the requested
language is supported.

rdar://86439474

Differential revision: https://reviews.llvm.org/D115698
2021-12-14 12:05:35 -08:00
Luís Ferreira efefc4ee3b [lldb][NFC] Format lldb/include/lldb/Symbol/Type.h
Reviewed By: teemperor, JDevlieghere, dblaikie

Differential Revision: https://reviews.llvm.org/D113604
2021-12-14 19:31:18 +00:00
Michał Górny 76c876e7e6 Revert "[lldb] Introduce a FreeBSDKernel plugin for vmcores"
This reverts commit aedb328a4d.
I have failed to make the new tests conditional to the presence
of libfbsdvmcore.
2021-12-14 18:17:54 +01:00
Michał Górny aedb328a4d [lldb] Introduce a FreeBSDKernel plugin for vmcores
Introduce a FreeBSDKernel plugin that provides the ability to read
FreeBSD kernel core dumps.  The plugin utilizes libfbsdvmcore to provide
support for both "full memory dump" and minidump formats across variety
of architectures supported by FreeBSD.  It provides the ability to read
kernel memory, as well as the crashed thread status with registers
on arm64, i386 and x86_64.

Differential Revision: https://reviews.llvm.org/D114911
2021-12-14 18:03:38 +01:00
Jonas Devlieghere 58473d84e0 [lldb] Use LLDB_VERSION_STRING instead of CLANG_VERSION_STRING 2021-12-13 16:58:39 -08:00
Jason Molenda f2120328e8 Add support for a "load binary" LC_NOTE in mach-o corefiles
Add lldb support for a Mach-O "load binary" LC_NOTE which provides
a UUID, load address/slide, and possibly a name of a binary that
should be loaded when examining the core.

struct load_binary
{
    uint32_t version;        // currently 1
    uuid_t   uuid;           // all zeroes if uuid not specified
    uint64_t load_address;   // virtual address where the macho is loaded, UINT64_MAX if unavail
    uint64_t slide;          // slide to be applied to file address to get load address, 0 if unavail
    char     name_cstring[]; // must be nul-byte terminated c-string, '\0' alone if name unavail
} __attribute__((packed));

Differential Revision: https://reviews.llvm.org/D115494
rdar://85069250
2021-12-13 13:21:56 -08:00
Pavel Labath 82de8df26f [lldb] Clarify StructuredDataImpl ownership
StructuredDataImpl ownership semantics is unclear at best. Various
structures were holding a non-owning pointer to it, with a comment that
the object is owned somewhere else. From what I was able to gather that
"somewhere else" was the SBStructuredData object, but I am not sure that
all created object eventually made its way there. (It wouldn't matter
even if they did, as we are leaking most of our SBStructuredData
objects.)

Since StructuredDataImpl is just a collection of two (shared) pointers,
there's really no point in elaborate lifetime management, so this patch
replaces all StructuredDataImpl pointers with actual objects or
unique_ptrs to it. This makes it much easier to resolve SBStructuredData
leaks in a follow-up patch.

Differential Revision: https://reviews.llvm.org/D114791
2021-12-13 21:04:51 +01:00
Med Ismail Bennani 72e25978f9 [lldb/API] Add SetDataWithOwnership method to SBData
This patch introduces a new method to SBData: SetDataWithOwnership.

Instead of referencing the pointer to the data, this method copies the
data buffer into lldb's heap memory.

This can prevent having the underlying DataExtractor object point to
freed/garbage-collected memory.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-12-13 11:05:06 -08:00
Kazu Hirata d2377f24e1 Ensure newlines at the end of files (NFC) 2021-12-12 11:04:44 -08:00
Jason Molenda efdac16b38 Remove one change from https://reviews.llvm.org/D115431
The change to ArchSpec::SetArchitecture that was setting the
ObjectFile of a mach-o binary to llvm::Triple::MachO.  It's not
necessary for my patch, and it changes the output of image list -t
causing TestUniversal.py to fail on x86_64 systems.  The bots
turned up the failure, I was developing and testing this on
an Apple Silicon mac.
2021-12-10 01:04:07 -08:00
Jason Molenda 223e8ca026 Set a default number of address bits on Darwin arm64 systems
With arm64e ARMv8.3 pointer authentication, lldb needs to know how
many bits are used for addressing and how many are used for pointer
auth signing.  This should be determined dynamically from the inferior
system / corefile, but there are some workflows where it still isn't
recorded and we fall back on a default value that is correct on some
Darwin environments.

This patch also explicitly sets the vendor of mach-o binaries to
Apple, so we select an Apple ABI instead of a random other ABI.

It adds a function pointer formatter for systems where pointer
authentication is in use, and we can strip the ptrauth bits off
of the function pointer address and get a different value that
points to an actual symbol.

Differential Revision: https://reviews.llvm.org/D115431
rdar://84644661
2021-12-09 22:53:01 -08:00
Med Ismail Bennani 20db8e07f9 [lldb/Target] Refine source display warning for artificial locations (NFC)
This is a post-review update for D115313, to rephrase source display
warning messages for artificial locations, making them more
understandable for the end-user.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-12-09 14:38:14 -08:00
Alisamar Husain cfb0750891 Unify libstdcpp and libcxx formatters for `std::optional`
Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D115178
2021-12-09 13:10:43 -08:00
Haojian Wu eaf4f60507 [lldb] Remove unused lldb.cpp
lldb.cpp is unused after ccf1469a4c

Differential Revision: https://reviews.llvm.org/D115438
2021-12-09 17:54:27 +01:00
Lasse Folger b2e2eece9a [lldb][NFC] clang-format some files as preparation for https://reviews.llvm.org/D114627
Reviewed By: werat

Differential Revision: https://reviews.llvm.org/D115110
2021-12-09 12:38:00 +01:00
Med Ismail Bennani edf410e48f [lldb/Target] Slide source display for artificial locations at function start
It can happen that a line entry reports that some source code is located
at line 0. In DWARF, line 0 is a special location which indicates that
code has no 1-1 mapping with source.

When stopping in one of those artificial locations, lldb doesn't know which
line to display and shows the beginning of the file instead.

This patch mitigates this behaviour by checking if the current symbol context
of the line entry has a matching function, in which case, it slides the
source listing to the start of that function.

This patch also shows the user a warning explaining why lldb couldn't
show sources at that location.

rdar://83118425

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-12-08 15:25:29 -08:00
Jonas Devlieghere ccf1469a4c [lldb] Make lldbVersion a full fledged library
Because of its dependency on clang (and potentially other compilers
downstream, such as swift) lldb_private::GetVersion already lives in its
own library called lldbBase. Despite that, its implementation was spread
across unrelated files. This patch improves things by introducing a
Version library with its own directory, header and implementation file.

The benefits of this patch include:

 - We can get rid of the ugly quoting macros.
 - Other parts of LLDB can read the version number from
   lldb/Version/Version.inc.
 - The implementation can be swapped out for tools like lldb-server than
   don't need to depend on clang at all.

Differential revision: https://reviews.llvm.org/D115211
2021-12-08 15:14:34 -08:00
Benjamin Kramer 81f4874cbf Silence format string warning harder.
This can be unsigned long or unsigned long long depending on where it's
compiled. Use the ugly portable way.
PlatformWindows.cpp:397:63: warning: format specifies type 'unsigned long long' but the argument has type 'uint64_t' (aka 'unsigned long')
2021-12-08 19:37:32 +01:00
Saleem Abdulrasool 906e60b9f9 lldb: silence a warning on the Windows error path (NFCI)
This corrects the printf specifier for the `error_code` parameter that
was reported by @thakis.
2021-12-08 09:01:10 -08:00
Pavel Labath ae316ac66f [lldb/qemu] Sort entries in QEMU_(UN)SET_ENV
The test for this functionality was failing on the darwin bot, because
the entries came out in opposite order. While this does not impact
functionality, and the algorithm that produces it is technically
deterministic (the nondeterminism comes from the contents of the host
environment), it seems like it would be more user-friendly if the
entries came out in a more predictible order.

Therefore I am adding the sort call to the actual code instead of
relaxing test expectations.
2021-12-08 15:56:32 +01:00
Pavel Labath 45aa435661 [lldb/qemu] Separate host and target environments
Qemu normally forwards its (host) environment variables to the emulated
process. While this works fine for most variables, there are some (few, but
fairly important) variables where this is not possible. LD_LIBRARY_PATH
is the probably the most important of those -- we don't want the library
search path for the emulated libraries to interfere with the libraries
that the emulator itself needs.

For this reason, qemu provides a mechanism (QEMU_SET_ENV,
QEMU_UNSET_ENV) to set variables only for the emulated process. This
patch makes use of that functionality to pass any user-provided
variables to the emulated process. Since we're piggy-backing on the
normal lldb environment-handling mechanism, all the usual mechanism to
provide environment (target.env-vars setting, SBLaunchInfo, etc.) work
out-of-the-box, and the only thing we need to do is to properly
construct the qemu environment variables.

This patch also adds a new setting -- target-env-vars, which represents
environment variables which are added (on top of the host environment)
to the default launch environments of all (qemu) targets. The reason for
its existence is to enable the configuration (e.g., from a startup
script) of the default launch environment, before any target is created.
The idea is that this would contain the variables (like the
aforementioned LD_LIBRARY_PATH) common to all targets being debugged on
the given system. The user is, of course, free to customize the
environment for a particular target in the usual manner.

The reason I do not want to use/recommend the "global" version of the
target.env-vars setting for this purpose is that the setting would apply
to all targets, whereas the settings (their values) I have mentioned
would be specific to the given platform.

Differential Revision: https://reviews.llvm.org/D115246
2021-12-08 13:08:19 +01:00
David Spickett 3a870bffb1 [lldb] Add missing space in C string format memory read warning
Also add tests to check that we print the warning in the right
circumstances.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D114877
2021-12-08 11:20:25 +00:00
Jim Ingham f75885977c Fix error reporting for "process load" and add a test for it.
Differential Revision: https://reviews.llvm.org/D115017
2021-12-07 15:08:05 -08:00
Zequan Wu a3a8ed33a1 [LLDB][NativePDB] Fix function decl creation for class methods
This is a split of D113724. Calling `TypeSystemClang::AddMethodToCXXRecordType`
to create function decls for class methods.

Differential Revision: https://reviews.llvm.org/D113930
2021-12-07 10:41:28 -08:00
Greg Clayton 244258e35a Modify DataEncoder to be able to encode data in an object owned buffer.
DataEncoder was previously made to modify data within an existing buffer. As the code progressed, new clients started using DataEncoder to create binary data. In these cases the use of this class was possibly, but only if you knew exactly how large your buffer would be ahead of time. This patchs adds the ability for DataEncoder to own a buffer that can be dynamically resized as data is appended to the buffer.

Change in this patch:
- Allow a DataEncoder object to be created that owns a DataBufferHeap object that can dynamically grow as data is appended
- Add new methods that start with "Append" to append data to the buffer and grow it as needed
- Adds full testing of the API to assure modifications don't regress any functionality
- Has two constructors: one that uses caller owned data and one that creates an object with object owned data
- "Append" methods only work if the object owns it own data
- Removes the ability to specify a shared memory buffer as no one was using this functionality. This allows us to switch to a case where the object owns its own data in a DataBufferHeap that can be resized as data is added

"Put" methods work on both caller and object owned data.
"Append" methods work on only object owned data where we can grow the buffer. These methods will return false if called on a DataEncoder object that has caller owned data.

The main reason for these modifications is to be able to use the DateEncoder objects instead of llvm::gsym::FileWriter in https://reviews.llvm.org/D113789. This patch wants to add the ability to create symbol table caching to LLDB and the code needs to build binary caches and save them to disk.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D115073
2021-12-07 09:44:57 -08:00
Pavel Labath 611fdde4c7 [lldb/qemu] Add emulator-args setting
This setting allows the user to pass additional arguments to the qemu instance.
While we may want to introduce dedicated settings for the most common qemu
arguments (-cpu, for one), having this setting allows us to avoid creating a
setting for every possible argument.

Differential Revision: https://reviews.llvm.org/D115151
2021-12-07 14:19:43 +01:00
Jaroslav Sevcik f72ae5cba1 [lldb] Fix windows path guessing for root paths
Fix recognizing "<letter>:\" as a windows path.

Differential Revision: https://reviews.llvm.org/D115104
2021-12-07 11:16:04 +01:00
Med Ismail Bennani caea440a11 [lldb/plugins] Add arm64(e) support to ScriptedProcess
This patch adds support for arm64(e) targets to ScriptedProcess, by
providing the `DynamicRegisterInfo` to the base `lldb.ScriptedThread` class.
This allows create and debugging ScriptedProcess on Apple Silicon
hardware as well as Apple mobile devices.

It also replace the C++ asserts on `ScriptedThread::GetDynamicRegisterInfo`
by some error logging, re-enables `TestScriptedProcess` for arm64
Darwin platforms and adds a new invalid Scripted Thread test.

rdar://85892451

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-12-06 16:11:59 -08:00
Dave Lee 13278efd0c [lldb] Remove some trivial scoped timers
While profiling lldb (from swift/llvm-project), these timers were noticed to be short lived and high firing, and so they add noise more than value.

The data points I recorded are:

`FindTypes_Impl`: 49,646 calls, 812ns avg, 40.33ms total
`AppendSymbolIndexesWithName`: 36,229 calls, 913ns avg, 33.09ms total
`FindAllSymbolsWithNameAndType`: 36,229 calls, 1.93µs avg, 70.05ms total
`FindSymbolsWithNameAndType`: 23,263 calls, 3.09µs avg, 71.88ms total

Differential Revision: https://reviews.llvm.org/D115182
2021-12-06 15:22:28 -08:00
Danil Stefaniuc 6622c14113 [formatters] Add a pointer and reference tests for a list and forward_list formatters for libstdcpp and libcxx
This adds extra tests for libstdcpp and libcxx list and forward_list formatters to check whether formatter behaves correctly when applied on pointer and reference values.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D115137
2021-12-06 13:42:03 -08:00
Walter Erquinigo 2ea3c8a50a [formatters] Add a deque formatter for libstdcpp and fix the libcxx one
This adds the formatters for libstdcpp's deque as a python
implementation. It adds comprehensive tests for the two different
storage strategies deque uses. Besides that, this fixes a couple of bugs
in the libcxx implementation. Finally, both implementation run against
the same tests.

This is a minor improvement on top of Danil Stefaniuc's formatter.
2021-12-06 13:42:03 -08:00
Aaron Ballman 1f257accd7 Speculatively fix the LLDB build bots from 6c75ab5f66
It looks like some renames got missed.
2021-12-06 13:30:15 -05:00
Pavel Labath 5c4cb323e8 [lldb/qemu] Add support for pty redirection
Lldb uses a pty to read/write to the standard input and output of the
debugged process. For host processes this would be automatically set up
by Target::FinalizeFileActions. The Qemu platform is in a unique
position of not really being a host platform, but not being remote
either. It reports IsHost() = false, but it is sufficiently host-like
that we can use the usual pty mechanism.

This patch adds the necessary glue code to enable pty redirection. It
includes a small refactor of Target::FinalizeFileActions and
ProcessLaunchInfo::SetUpPtyRedirection to reduce the amount of
boilerplate that would need to be copied.

I will note that qemu is not able to separate output from the emulated
program from the output of the emulator itself, so the two will arrive
intertwined. Normally this should not be a problem since qemu should not
produce any output during regular operation, but some output can slip
through in case of errors. This situation should be pretty obvious (to a
human), and it is the best we can do anyway.

For testing purposes, and inspired by lldb-server tests, I have extended
the mock emulator with the ability "program" the behavior of the
"emulated" program via command-line arguments.

Differential Revision: https://reviews.llvm.org/D114796
2021-12-06 15:03:21 +01:00
Pavel Labath 85578db68a [lldb/lua] Add a file that should have been a part of a52af6d3 2021-12-06 14:58:39 +01:00
Pavel Labath a52af6d371 [lldb] Remove extern "C" from lldb-swig-lua interface
This is the lua equivalent of 9a14adeae0.
2021-12-06 14:57:44 +01:00
Michał Górny fdc1638b5c [lldb] [Process/elf-core] Disable for FreeBSD vmcores
Recognize FreeBSD vmcores (kernel core dumps) through OS ABI = 0xFF
+ ELF version = 0, and do not process them via the elf-core plugin.
While these files use ELF as a container format, they contain raw memory
dump rather than proper VM segments and therefore are not usable
to the elf-core plugin.

Differential Revision: https://reviews.llvm.org/D114967
2021-12-06 14:40:02 +01:00
Kazu Hirata ee4b462693 [lldb] Fix a warning
This patch fixes:

  lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp:386:13:
  error: comparison between NULL and non-pointer ('lldb::addr_t' (aka
  'unsigned long') and NULL) [-Werror,-Wnull-arithmetic]
2021-12-04 18:34:29 -08:00
Saleem Abdulrasool f1585a4b47 Windows: support `DoLoadImage`
This implements `DoLoadImage` and `UnloadImage` in the Windows platform
plugin modelled after the POSIX platform plugin.  This was previously
unimplemented and resulted in a difficult to decipher error without any
logging.

This implementation is intended to support enables the use of LLDB's
Swift REPL on Windows.

Paths which are added to the library search path are persistent and
applied to all subsequent loads.  This can be adjusted in the future by
storing all the cookies and restoring the path prior to returning from
the helper.  However, the dynamic path count makes this a bit more
challenging.

Reviewed By: @JDevlieghere
Differential Revision: https://reviews.llvm.org/D77287
2021-12-04 11:11:47 -08:00
Jordan Rupprecht fddedcaeb8 [NFC] const-ify some methods on CommandReturnObject 2021-12-03 14:54:03 -08:00
Jason Molenda fddafa110d Simplify logic to identify dyld_sim in Simulator debugging on macos
When debugging a Simulator process on macOS (e.g. the iPhone simulator),
the process will have both a dyld, and a dyld_sim present.  The dyld_sim
is an iOS Simulator binary.  The dyld is a macOS binary.  Both are
MH_DYLINKER filetypes.  lldb needs to identify & set a breakpoint in
dyld, so it has to distinguish between these two.

Previously lldb was checking if the inferior target was x86 (indicating
macOS) and the OS of the MH_DYLINKER binary was iOS/watchOS/etc -- if
so, then this is dyld_sim and we should ignore it.  Now with arm64
macOS systems, this check was invalid, and we would set our breakpoint
for new binaries being loaded in dyld_sim, causing binary loading to
be missed by lldb.

This patch uses the Target's ArchSpec triple environment, to see if
this process is a simulator process.  If this is a Simulator process,
then we only recognize a MH_DYLINKER binary with OS type macOS as
being dyld.

This patch also removes some code that handled pre-2016 era debugservers
which didn't give us the OS type for each binary.  This was only being
used on macOS, where we don't need to handle the presence of very old
debugservers.

Differential Revision: https://reviews.llvm.org/D115001
rdar://85907839
2021-12-02 18:14:13 -08:00
Greg Clayton 7e6df41f65 [NFC] Refactor symbol table parsing.
Symbol table parsing has evolved over the years and many plug-ins contained duplicate code in the ObjectFile::GetSymtab() that used to be pure virtual. With this change, the "Symbtab *ObjectFile::GetSymtab()" is no longer virtual and will end up calling a new "void ObjectFile::ParseSymtab(Symtab &symtab)" pure virtual function to actually do the parsing. This helps centralize the code for parsing the symbol table and allows the ObjectFile base class to do all of the common work, like taking the necessary locks and creating the symbol table object itself. Plug-ins now just need to parse when they are asked to parse as the ParseSymtab function will only get called once.

This is a retry of the original patch https://reviews.llvm.org/D113965 which was reverted. There was a deadlock in the Manual DWARF indexing code during symbol preloading where the module was asked on the main thread to preload its symbols, and this would in turn cause the DWARF manual indexing to use a thread pool to index all of the compile units, and if there were relocations on the debug information sections, these threads could ask the ObjectFile to load section contents, which could cause a call to ObjectFileELF::RelocateSection() which would ask for the symbol table from the module and it would deadlock. We can't lock the module in ObjectFile::GetSymtab(), so the solution I am using is to use a llvm::once_flag to create the symbol table object once and then lock the Symtab object. Since all APIs on the symbol table use this lock, this will prevent anyone from using the symbol table before it is parsed and finalized and will avoid the deadlock I mentioned. ObjectFileELF::GetSymtab() was never locking the module lock before and would put off creating the symbol table until somewhere inside ObjectFileELF::GetSymtab(). Now we create it one time inside of the ObjectFile::GetSymtab() and immediately lock it which should be safe enough. This avoids the deadlocks and still provides safety.

Differential Revision: https://reviews.llvm.org/D114288
2021-11-30 13:54:32 -08:00
Pavel Labath 1408684957 [lldb] Introduce PlatformQemuUser
This adds a new platform class, whose job is to enable running
(debugging) executables under qemu.

(For general information about qemu, I recommend reading the RFC thread
on lldb-dev
<https://lists.llvm.org/pipermail/lldb-dev/2021-October/017106.html>.)

This initial patch implements the necessary boilerplate as well as the
minimal amount of functionality needed to actually be able to do
something useful (which, in this case means debugging a fully statically
linked executable).

The knobs necessary to emulate dynamically linked programs, as well as
to control other aspects of qemu operation (the emulated cpu, for
instance) will be added in subsequent patches. Same goes for the ability
to automatically bind to the executables of the emulated architecture.

Currently only two settings are available:
- architecture: the architecture that we should emulate
- emulator-path: the path to the emulator

Even though this patch is relatively small, it doesn't lack subtleties
that are worth calling out explicitly:
- named sockets: qemu supports tcp and unix socket connections, both of
  them in the "forward connect" mode (qemu listening, lldb connecting).
  Forward TCP connections are impossible to realise in a race-free way.
  This is the reason why I chose unix sockets as they have larger, more
  structured names, which can guarantee that there are no collisions
  between concurrent connection attempts.
- the above means that this code will not work on windows. I don't think
  that's an issue since user mode qemu does not support windows anyway.
- Right now, I am leaving the code enabled for windows, but maybe it
  would be better to disable it (otoh, disabling it means windows
  developers can't check they don't break it)
- qemu-user also does not support macOS, so one could contemplate
  disabling it there too. However, macOS does support named sockets, so
  one can even run the (mock) qemu tests there, and I think it'd be a
  shame to lose that.

Differential Revision: https://reviews.llvm.org/D114509
2021-11-30 14:16:08 +01:00
Pavel Labath a6e673643c [lldb] Inline Platform::LoadCachedExecutable into its (single) caller 2021-11-30 14:15:49 +01:00
Pavel Labath 9a14adeae0 [lldb] Remove 'extern "C"' from the lldb-swig-python interface
The LLDBSWIGPython functions had (at least) two problems:
- There wasn't a single source of truth (a header file) for the
  prototypes of these functions. This meant that subtle differences
  in copies of function declarations could go by undetected. And
  not-so-subtle differences would result in strange runtime failures.
- All of the declarations had to have an extern "C" interface, because
  the function definitions were being placed inside and extert "C" block
  generated by swig.

This patch fixes both problems by moving the function definitions to the
%header block of the swig files. This block is not surrounded by extern
"C", and seems more appropriate anyway, as swig docs say it is meant for
"user-defined support code" (whereas the previous %wrapper code was for
automatically-generated wrappers).

It also puts the declarations into the SWIGPythonBridge header file
(which seems to have been created for this purpose), and ensures it is
included by all code wishing to define or use these functions. This
means that any differences in the declaration become a compiler error
instead of a runtime failure.

Differential Revision: https://reviews.llvm.org/D114369
2021-11-30 11:06:09 +01:00
Luís Ferreira 2e5c47eda1
Revert "[lldb][NFC] Format lldb/include/lldb/Symbol/Type.h"
This reverts commit 6f99e1aa58.
2021-11-30 00:52:53 +00:00
Luís Ferreira 6f99e1aa58
[lldb][NFC] Format lldb/include/lldb/Symbol/Type.h
Reviewed By: teemperor, JDevlieghere

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

Signed-off-by: Luís Ferreira <contact@lsferreira.net>
2021-11-29 23:55:58 +00:00
David Spickett 0df522969a Revert "Reland "[lldb] Remove non address bits when looking up memory regions""
This reverts commit fac3f20de5.

I found this has broken how we detect the last memory region in
GetMemoryRegions/"memory region" command.

When you're debugging an AArch64 system with pointer authentication,
the ABI plugin will remove the top bit from the end address of the last
user mapped area.

(lldb)
[0x0000fffffffdf000-0x0001000000000000) rw- [stack]

ABI plugin removes anything above the 48th bit (48 bit virtual addresses
by default on AArch64, leaving an address of 0.

(lldb)
[0x0000000000000000-0x0000000000400000) ---

You get back a mapping for 0 and get into an infinite loop.
2021-11-26 15:35:02 +00:00
Venkata Ramanaiah Nalamothu 7f05ff8be4 [Bug 49018][lldb] Fix incorrect help text for 'memory write' command
Certain commands like 'memory write', 'register read' etc all use
the OptionGroupFormat options but the help usage text for those
options is not customized to those commands.

One such example is:

  (lldb) help memory read
           -s <byte-size> ( --size <byte-size> )
               The size in bytes to use when displaying with the selected format.
  (lldb) help memory write
	   -s <byte-size> ( --size <byte-size> )
               The size in bytes to use when displaying with the selected format.

This patch allows such commands to overwrite the help text for the options
in the OptionGroupFormat group as needed and fixes help text of memory write.

llvm.org/pr49018.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D114448
2021-11-26 19:14:26 +05:30
Venkata Ramanaiah Nalamothu 94038c570f [lldb] Fix 'memory write' to not allow specifying values when writing file contents
Currently the 'memory write' command allows specifying the values when
writing the file contents to memory but the values are actually ignored. This
patch fixes that by erroring out when values are specified in such cases.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D114544
2021-11-26 15:50:36 +05:30
Zarko Todorovski 5162b558d8 [clang][NFC] Inclusive terms: rename AccessDeclContextSanity to AccessDeclContextCheck
Rename function to more inclusive name.

Reviewed By: quinnp

Differential Revision: https://reviews.llvm.org/D114029
2021-11-25 16:21:06 -05:00
Pavel Kosov 1aab5e653d [LLDB] Provide target specific directories to libclang
On Linux some C++ and C include files reside in target specific directories, like /usr/include/x86_64-linux-gnu.
Patch adds them to libclang, so LLDB jitter has more chances to compile expression.

OS Laboratory. Huawei Russian Research Institute. Saint-Petersburg

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D110827
2021-11-25 21:27:02 +03:00
Pavel Labath 165545c7a4 [lldb/gdb-remote] Ignore spurious ACK packets
Although I cannot find any mention of this in the specification, both
gdb and lldb agree on sending an initial + packet after establishing the
connection.

OTOH, gdbserver and lldb-server behavior is subtly different. While
lldb-server *expects* the initial ack, and drops the connection if it is
not received, gdbserver will just ignore a spurious ack at _any_ point
in the connection.

This patch changes lldb's behavior to match that of gdb. An ACK packet
is ignored at any point in the connection (except when expecting an ACK
packet, of course). This is inline with the "be strict in what you
generate, and lenient in what you accept" philosophy, and also enables
us to remove some special cases from the server code. I've extended the
same handling to NAK (-) packets, mainly because I don't see a reason to
treat them differently here.

(The background here is that we had a stub which was sending spurious
+ packets. This bug has since been fixed, but I think this change makes
sense nonetheless.)

Differential Revision: https://reviews.llvm.org/D114520
2021-11-25 12:34:08 +01:00
Pavel Labath a6fedbf20c [lldb/gdb-remote] Remove initial pipe-draining workaround
This code, added in rL197579 (Dec 2013) is supposed to work around what
was presumably a qemu bug, where it would send unsolicited stop-reply
packets after the initial connection.

At present, qemu does not exhibit such behavior. Also, the 10ms delay
introduced by this code is sufficient to mask bugs in other stubs, but
it is not sufficient to *reliably* mask those bugs. This resulted in
flakyness in one of our stubs, which was (incorrectly) sending a +
packet at the start of the connection, resulting in a small-but-annoying
number of dropped connections.

Differential Revision: https://reviews.llvm.org/D114529
2021-11-25 12:33:23 +01:00
Levon Ter-Grigoryan f23b829a26 Fixed use of -o and -k in LLDB under Windows when statically compiled with vcruntime.
Right now if the LLDB is compiled under the windows with static vcruntime library, the -o and -k commands will not work.

The problem is that the LLDB create FILE* in lldb.exe and pass it to liblldb.dll which is an object from CRT.
Since the CRT is statically linked each of these module has its own copy of the CRT with it's own global state and the LLDB should not share CRT objects between them.

In this change I moved the logic of creating FILE* out of commands stream from Driver class to SBDebugger.
To do this I added new method: SBError SBDebugger::SetInputStream(SBStream &stream)

Command to build the LLDB:
cmake -G Ninja -DLLVM_ENABLE_PROJECTS="clang;lldb;libcxx"  -DLLVM_USE_CRT_RELEASE="MT" -DLLVM_USE_CRT_MINSIZEREL="MT" -DLLVM_USE_CRT_RELWITHDEBINFO="MT" -DP
YTHON_HOME:FILEPATH=C:/Python38 -DCMAKE_C_COMPILER:STRING=cl.exe -DCMAKE_CXX_COMPILER:STRING=cl.exe ../llvm

Command which will fail:
lldb.exe -o help

See discord discussion for more details: https://discord.com/channels/636084430946959380/636732809708306432/854629125398724628
This revision is for the further discussion.

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D104413
2021-11-24 16:17:08 +00:00
Pavel Labath 96beb30fbb [lldb] Move GetSupportedArchitectureAtIndex to PlatformDarwin
All other platforms use GetSupportedArchitectures now.
2021-11-24 15:48:23 +01:00
Pavel Labath 6f82264dbb [lldb/gdb-remote] Remove more non-stop mode remnants
The read thread handling is completely dead code now that non-stop mode
no longer exists.
2021-11-24 10:00:43 +01:00
Zequan Wu 22ced33a2f [LLDB][NativePDB] Allow find functions by full names
I don't see a reason why not to. If we allows lookup functions by full names,
I can change the test case in D113930 to use `lldb-test symbols --find=function --name=full::name --function-flags=full ...`,
though the duplicate method decl prolem is still there for `lldb-test symbols --dump-ast`.
That's a seprate bug, we can fix it later.

Differential Revision: https://reviews.llvm.org/D114467
2021-11-23 17:57:05 -08:00
Danil Stefaniuc 9a9d9a9b00 [formatters] List and forward_list capping_size determination and application
This diff is adding the capping_size determination for the list and forward list, to limit the number of children to be displayed. Also it modifies and unifies tests for libcxx and libstdcpp list data formatter.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D114433
2021-11-23 14:18:51 -08:00
Danil Stefaniuc 193bf2e820 [formatters] Capping size limitation avoidance for the libcxx and libcpp bitset data formatters.
This diff is avoiding the size limitation introduced by the capping size for the libcxx and libcpp bitset data formatters.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D114461
2021-11-23 14:03:59 -08:00
Walter Erquinigo a48501150b Make some libstd++ formatters safer
We need to add checks that ensure that some core variables are valid, so
that we avoid printing out garbage data. The worst that could happen is
that an non-initialized variable is being printed as something with
123123432 children instead of 0.

Differential Revision: https://reviews.llvm.org/D114458
2021-11-23 13:52:32 -08:00
Walter Erquinigo 4ba5da8e3d Improve optional formatter
As suggested by @labath in https://reviews.llvm.org/D114403, we should
make the formatter more resilient to corrupted data. The Libcxx version
explicitly checks for engaged = 1, so we can do that as well for safety.

Differential Revision: https://reviews.llvm.org/D114450
2021-11-23 13:52:17 -08:00
Tonko Sabolčec f66b69a392 [lldb] Fix lookup for global constants in namespaces
LLDB uses mangled name to construct a fully qualified name for global
variables. Sometimes DW_TAG_linkage_name attribute is missing from
debug info, so LLDB has to rely on parent entries to construct the
fully qualified name.

Currently, the fallback is handled when the parent DW_TAG is either
DW_TAG_compiled_unit or DW_TAG_partial_unit, which may not work well
for global constants in namespaces. For example:

  namespace ns {
    const int x = 10;
  }

may produce the following debug info:

  <1><2a>: Abbrev Number: 2 (DW_TAG_namespace)
     <2b>   DW_AT_name        : (indirect string, offset: 0x5e): ns
  <2><2f>: Abbrev Number: 3 (DW_TAG_variable)
     <30>   DW_AT_name        : (indirect string, offset: 0x61): x
     <34>   DW_AT_type        : <0x3c>
     <38>   DW_AT_decl_file   : 1
     <39>   DW_AT_decl_line   : 2
     <3a>   DW_AT_const_value : 10

Since the fallback didn't handle the case when parent tag is
DW_TAG_namespace, LLDB wasn't able to match the variable by its fully
qualified name "ns::x". This change fixes this by additional check
if the parent is a DW_TAG_namespace.

Reviewed By: werat, clayborg

Differential Revision: https://reviews.llvm.org/D112147
2021-11-23 12:53:03 +01:00
Walter Erquinigo e3dea5cf0e [formatters] Add a formatter for libstdc++ optional
Besides adding the formatter and the summary, this makes the libcxx
tests also work for this case.

This is the polished version of https://reviews.llvm.org/D114266,
authored by Danil Stefaniuc.

Differential Revision: https://reviews.llvm.org/D114403
2021-11-22 15:36:46 -08:00
Walter Erquinigo 91f78eb5cf Revert "[lldb] Load the fblldb module automatically"
This reverts commit 2e6a0a8b81.

It was pushed by mistake..
2021-11-22 13:13:43 -08:00
Danil Stefaniuc fcd288b52a [formatters] Add a libstdcpp formatter for for unordered_map, unordered_set, unordered_multimap, unordered_multiset
This diff adds a data formatter and tests for libstdcpp's unordered_map, unordered_set, unordered_multimap, unordered_multiset

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D113760
2021-11-22 13:08:36 -08:00
Walter Erquinigo 2e6a0a8b81 [lldb] Load the fblldb module automatically
Summary:
```
// Facebook only:
// We want to load automatically the fblldb python module as soon as lldb or
// lldb-vscode start. This will ensure that logging and formatters are enabled
// by default.
//
// As we want to have a mechanism for not triggering this by default, if the
// user is starting lldb disabling .lldbinit support, then we also don't load
// this module. This is equivalent to appending this line to all .lldbinit
// files.
//
// We don't have the fblldb module on windows, so we don't include it for that
// build.
```

Test Plan:
the fbsymbols module is loaded automatically

```
./bin/lldb
(lldb) help fbsymbols
Facebook {mini,core}dump utility.  Expects 'raw' input (see 'help raw-input'.)
```

Reviewers: wanyi

Reviewed By: wanyi

Subscribers: mnovakovic, serhiyr, phabricatorlinter

Differential Revision: https://phabricator.intern.facebook.com/D29372804

Tags: accept2ship

Signature: 29372804:1624567770:07836e50e576bd809124ed80a6bc01082190e48f

[lldb] Load fblldbinit instead of fblldb

Summary: Once accepted, it'll merge it with the existing commit in our branch so that we keep the commit list as short as possible.

Test Plan: https://www.internalfb.com/diff/D30293094

Reviewers: aadsm, wanyi

Reviewed By: aadsm

Subscribers: mnovakovic, serhiyr

Differential Revision: https://phabricator.intern.facebook.com/D30293211

Tags: accept2ship

Signature: 30293211:1628880953:423e2e543cade107df69da0ebf458e581e54ae3a
2021-11-22 13:08:36 -08:00
Pavel Labath 7f09ab08de [lldb] Fix [some] leaks in python bindings
Using an lldb_private object in the bindings involves three steps
- wrapping the object in it's lldb::SB variant
- using swig to convert/wrap that to a PyObject
- wrapping *that* in a lldb_private::python::PythonObject

Our SBTypeToSWIGWrapper was only handling the middle part. This doesn't
just result in increased boilerplate in the callers, but is also a
functionality problem, as it's very hard to get the lifetime of of all
of these objects right. Most of the callers are creating the SB object
(step 1) on the stack, which means that we end up with dangling python
objects after the function terminates. Most of the time this isn't a
problem, because the python code does not need to persist the objects.
However, there are legitimate cases where they can do it (and even if
the use case is not completely legitimate, crashing is not the best
response to that).

For this reason, some of our code creates the SB object on the heap, but
it has another problem -- it never gets cleaned up.

This patch begins to add a new function (ToSWIGWrapper), which does all
of the three steps, while properly taking care of ownership. In the
first step, I have converted most of the leaky code (except for
SBStructuredData, which needs a bit more work).

Differential Revision: https://reviews.llvm.org/D114259
2021-11-22 15:14:52 +01:00
Jim Ingham d9f56feda8 Remove unused variable. 2021-11-18 15:58:20 -08:00
Keith Smiley 0c4464a5bd [lldb] Fix formatted log statement
Previously this would output literally without replacements

Differential Revision: https://reviews.llvm.org/D114178
2021-11-18 15:09:38 -08:00
Quinn Pham 95af9d888b [NFC][lldb] Inclusive language: remove instances of master from comments in lldb
[NFC] As part of using inclusive language within the llvm project, this patch
replaces master in these comments.

Reviewed By: clayborg, JDevlieghere

Differential Revision: https://reviews.llvm.org/D114123
2021-11-18 12:34:13 -06:00
Pavel Labath 4c56f734b3 [lldb] (Partially) enable formatting of utf strings before the program is started
The StringPrinter class was using a Process instance to read memory.
This automatically prevented it from working before starting the
program.

This patch changes the class to use the Target object for reading
memory, as targets are always available. This required moving
ReadStringFromMemory from Process to Target.

This is sufficient to make frame/target variable work, but further
changes are necessary for the expression evaluator. Preliminary analysis
indicates the failures are due to the expression result ValueObjects
failing to provide an address, presumably because we're operating on
file addresses before starting. I haven't looked into what would it take
to make that work.

Differential Revision: https://reviews.llvm.org/D113098
2021-11-18 14:45:17 +01:00
Pavel Labath 3a56f5622f [lldb] Convert internal platform usages GetSupportedArchitectures 2021-11-18 13:31:09 +01:00
Greg Clayton a68ccda203 Revert "[NFC] Refactor symbol table parsing."
This reverts commit 951b107eed.

Buildbots were failing, there is a deadlock in /Users/gclayton/Documents/src/llvm/clean/llvm-project/lldb/test/Shell/SymbolFile/DWARF/DW_AT_range-DW_FORM_sec_offset.s when ELF files try to relocate things.
2021-11-17 18:07:28 -08:00
Jim Ingham 92eaad2dd7 Revert "Revert "Make it possible for lldb to launch a remote binary with no local file.""
This reverts commit dd5505a8f2.

I picked the wrong class for the test, should have been GDBRemoteTestBase.
2021-11-17 17:59:47 -08:00
Greg Clayton 951b107eed [NFC] Refactor symbol table parsing.
Symbol table parsing has evolved over the years and many plug-ins contained duplicate code in the ObjectFile::GetSymtab() that used to be pure virtual. With this change, the "Symbtab *ObjectFile::GetSymtab()" is no longer virtual and will end up calling a new "void ObjectFile::ParseSymtab(Symtab &symtab)" pure virtual function to actually do the parsing. This helps centralize the code for parsing the symbol table and allows the ObjectFile base class to do all of the common work, like taking the necessary locks and creating the symbol table object itself. Plug-ins now just need to parse when they are asked to parse as the ParseSymtab function will only get called once.

Differential Revision: https://reviews.llvm.org/D113965
2021-11-17 15:14:01 -08:00
Pavel Labath 1b468f1c1b [lldb] Port PlatformWindows, PlatformOpenBSD and PlatformRemoteGDBServer to GetSupportedArchitectures 2021-11-17 20:09:31 +01:00
Jim Ingham dd5505a8f2 Revert "Make it possible for lldb to launch a remote binary with no local file."
The reworking of the gdb client tests into the PlatformClientTestBase broke
the test for this.  I did the mutatis mutandis for the move, but the test
still fails.  Reverting till I have time to figure out why.

This reverts commit b715b79d54.
2021-11-16 16:46:21 -08:00
Jim Ingham b715b79d54 Make it possible for lldb to launch a remote binary with no local file.
We don't actually need a local copy of the main executable to debug
a remote process.  So instead of treating "no local module" as an error,
see if the LaunchInfo has an executable it wants lldb to use, and if so
use it.  Then report whatever error the remote server returns.

Differential Revision: https://reviews.llvm.org/D113521
2021-11-16 16:06:07 -08:00
Lawrence D'Anna 4c2cf3a314 [lldb] fix -print-script-interpreter-info on windows
Apparently "{sys.prefix}/bin/python3" isn't where you find the
python interpreter on windows, so the test I wrote for
-print-script-interpreter-info is failing.

We can't rely on sys.executable at runtime, because that will point
to lldb.exe not python.exe.

We can't just record sys.executable from build time, because python
could have been moved to a different location.

But it should be OK to apply relative path from sys.prefix to sys.executable
from build-time to the sys.prefix at runtime.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D113650
2021-11-16 13:50:20 -08:00
Pavel Labath 098c01c132 [lldb] Refactor Platform::ResolveExecutable
Module resolution is probably the most complex piece of lldb [citation
needed], with numerous levels of abstraction, each one implementing
various retry and fallback strategies.

It is also a very repetitive, with only small differences between
"host", "remote-and-connected" and "remote-but-not-(yet)-connected"
scenarios.

The goal of this patch (first in series) is to reduce the number of
abstractions, and deduplicate the code.

One of the reasons for this complexity is the tension between the desire
to offload the process of module resolution to the remote platform
instance (that's how most other platform methods work), and the desire
to keep it local to the outer platform class (its easier to subclass the
outer class, and it generally makes more sense).

This patch resolves that conflict in favour of doing everything in the
outer class. The gdb-remote (our only remote platform) implementation of
ResolveExecutable was not doing anything gdb-specific, and was rather
similar to the other implementations of that method (any divergence is
most likely the result of fixes not being applied everywhere rather than
intentional).

It does this by excising the remote platform out of the resolution
codepath. The gdb-remote implementation of ResolveExecutable is moved to
Platform::ResolveRemoteExecutable, and the (only) call site is
redirected to that. On its own, this does not achieve (much), but it
creates new opportunities for layer peeling and code sharing, since all
of the code now lives closer together.

Differential Revision: https://reviews.llvm.org/D113487
2021-11-16 12:52:51 +01:00
Pavel Labath 669e57ebd1 [lldb] Simplify specifying of platform supported architectures
The GetSupportedArchitectureAtIndex pattern forces the use of
complicated patterns in both the implementations of the function and in
the various callers.

This patch creates a new method (GetSupportedArchitectures), which
returns a list (vector) of architectures. The
GetSupportedArchitectureAtIndex is kept in order to enable incremental
rollout. Base Platform class contains implementations of both of these
methods, using the other method as the source of truth. Platforms
without infinite stacks should implement at least one of them.

This patch also ports Linux, FreeBSD and NetBSD platforms to the new
API. A new helper function (CreateArchList) is added to simplify the
common task of creating a list of ArchSpecs with the same OS but
different architectures.

Differential Revision: https://reviews.llvm.org/D113608
2021-11-16 11:43:48 +01:00
Greg Clayton dbd36e1e9f Add the stop count to "statistics dump" in each target's dictionary.
It is great to know how many times the target has stopped over its lifetime as each time the target stops, and possibly resumes without the user seeing it for things like shared library loading and signals that are not notified and auto continued, to help explain why a debug session might be slow. This is now included as "stopCount" inside each target JSON.

Differential Revision: https://reviews.llvm.org/D113810
2021-11-15 18:59:09 -08:00
Zequan Wu f17404a733 [LLDB][NativePDB] Fix image lookup by address
`image lookup -a ` doesn't work because the compilands list is always empty.
Create CU at given index if doesn't exit.

Differential Revision: https://reviews.llvm.org/D113821
2021-11-15 12:30:23 -08:00
Andy Yankovsky 95102b7dc3 [lldb] Unwrap the type when dereferencing the value
The value type can be a typedef of a reference (e.g. `typedef int& myint`).
In this case `GetQualType(type)` will return `clang::Typedef`, which cannot
be casted to `clang::ReferenceType`.

Fix a regression introduced in https://reviews.llvm.org/D103532.

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D113673
2021-11-15 14:48:19 +01:00
Shao-Ce SUN 0c660256eb [NFC] Trim trailing whitespace in *.rst 2021-11-15 09:17:08 +08:00
Raphael Isemann c3a3e65ecc Revert "[lldb] Fix that the embedded Python REPL crashes if it receives SIGINT"
This reverts commit cef1e07cc6.

It broke the windows bot.
2021-11-13 18:18:24 +01:00
Quinn Pham 84c5702b76 [lldb][NFC] Inclusive language: rename m_master in ASTImporterDelegate
[NFC] As part of using inclusive language within the llvm project, this patch
replaces `m_master` in `ASTImporterDelegate` with `m_main`.

Reviewed By: teemperor, clayborg

Differential Revision: https://reviews.llvm.org/D113720
2021-11-12 12:04:14 -06:00
Quinn Pham 52a3ed5b93 [lldb][NFC] Inclusive language: replace master/slave names for ptys
[NFC] This patch replaces master and slave with primary and secondary
respectively when referring to pseudoterminals/file descriptors.

Reviewed By: clayborg, teemperor

Differential Revision: https://reviews.llvm.org/D113687
2021-11-12 10:54:18 -06:00
Raphael Isemann cef1e07cc6 [lldb] Fix that the embedded Python REPL crashes if it receives SIGINT
When LLDB receives a SIGINT while running the embedded Python REPL it currently
just crashes in `ScriptInterpreterPythonImpl::Interrupt` with an error such as
the one below:

```

Fatal Python error: PyThreadState_Get: the function must be called with the GIL
held, but the GIL is released (the current Python thread state is NULL)

```

The faulty code that causes this error is this part of `ScriptInterpreterPythonImpl::Interrupt`:
```
    PyThreadState *state = PyThreadState_GET();
    if (!state)
      state = GetThreadState();
    if (state) {
      long tid = state->thread_id;
      PyThreadState_Swap(state);
      int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
```

The obvious fix I tried is to just acquire the GIL before this code is running
which fixes the crash but the `KeyboardInterrupt` we want to raise immediately
is actually just queued and would only be raised once the next line of input has
been parsed (which e.g. won't interrupt Python code that is currently waiting on
a timer or IO from what I can see). Also none of the functions we call here is
marked as safe to be called from a signal handler from what I can see, so we
might still end up crashing here with some bad timing.

Python 3.2 introduced `PyErr_SetInterrupt` to solve this and the function takes
care of all the details and avoids doing anything that isn't safe to do inside a
signal handler. The only thing we need to do is to manually setup our own fake
SIGINT handler that behaves the same way as the standalone Python REPL signal
handler (which raises a KeyboardInterrupt).

From what I understand the old code used to work with Python 2 so I kept the old
code around until we officially drop support for Python 2.

There is a small gap here with Python 3.0->3.1 where we might still be crashing,
but those versions have reached their EOL more than a decade ago so I think we
don't need to bother about them.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D104886
2021-11-12 14:19:15 +01:00
Alex Langford ac33e65d21 [lldb][NFC] Delete commented out code in AddressRange 2021-11-11 15:42:27 -08:00
Quinn Pham 04cbfa950e [lldb][NFC] Inclusive Language: rename master plan to controlling plan
[NFC] As part of using inclusive language within the llvm project, this patch
renames master plan to controlling plan in lldb.

Reviewed By: jingham

Differential Revision: https://reviews.llvm.org/D113019
2021-11-11 15:04:44 -06:00
Raphael Isemann b72727a75a [lldb][NFC] Remove commented out code in SymbolFileDWARF 2021-11-11 12:45:38 +01:00
David Spickett 9db2541d4c [lldb][AArch64] Add UnwindPlan for Linux sigreturn
This adds a specific unwind plan for AArch64 Linux sigreturn frames.
Previously we assumed that the fp would be valid here but it is not.

https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/vdso/sigreturn.S

On Ubuntu Bionic it happened to point to an old frame info which meant
you got what looked like a correct backtrace. On Focal, the info is
completely invalid. (probably due to some code shuffling in libc)

This adds an UnwindPlan that knows that the sp in a sigreturn frame
points to an rt_sigframe from which we can offset to get saved
sp and pc values to backtrace correctly.

Based on LibUnwind's change: https://reviews.llvm.org/D90898

A new test is added that sets all compares the frames from the initial
signal catch to the handler break. Ensuring that the stack/frame pointer,
function name and register values match.
(this test is AArch64 Linux specific because it's the only one
with a specific unwind plan for this situation)

Fixes https://bugs.llvm.org/show_bug.cgi?id=52165

Reviewed By: omjavaid, labath

Differential Revision: https://reviews.llvm.org/D112069
2021-11-11 11:32:06 +00:00
Luís Ferreira 96a7359908 [lldb] Add support for demangling D symbols
This is part of https://github.com/dlang/projects/issues/81 .

This patch enables support for D programming language demangler by using a
pretty printed stacktrace with demangled D symbols, when present.

Signed-off-by: Luís Ferreira <contact@lsferreira.net>

Reviewed By: JDevlieghere, teemperor

Differential Revision: https://reviews.llvm.org/D110578
2021-11-11 11:11:21 +01:00
Med Ismail Bennani 676576b6f0 [lldb/Plugins] Refactor ScriptedThread register context creation
This patch changes the ScriptedThread class to create the register
context when Process::RefreshStateAfterStop is called rather than
doing it in the thread constructor.

This is required to update the thread state for execution control.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-11-11 00:13:58 +01:00
Zequan Wu cc9ced0ed4 [LLDB][Breakpad] Make lldb understand INLINE and INLINE_ORIGIN records in breakpad.
Teach LLDB to understand INLINE and INLINE_ORIGIN records in breakpad.
They have the following formats:
```
INLINE inline_nest_level call_site_line call_site_file_num origin_num [address size]+
INLINE_ORIGIN origin_num name
```
`INLNIE_ORIGIN` is simply a string pool for INLINE so that we won't have
duplicated names for inlined functions and can show up anywhere in the symbol
file.
`INLINE` follows immediately after `FUNC` represents the ranges of momery
address that has functions inlined inside the function.

Differential Revision: https://reviews.llvm.org/D113330
2021-11-10 11:20:32 -08:00
Zequan Wu fbf665a008 [LLDB][Breakpad] Create a function for each compilation unit.
Since every FUNC record (in breakpad) is a compilation unit, creating the
function for the CU allows `ResolveSymbolContext` to resolve
`eSymbolContextFunction`.

Differential Revision: https://reviews.llvm.org/D113163
2021-11-10 10:51:16 -08:00
Jordan Rupprecht 360d901bf0 Revert "[lldb] Disable minimal import mode for RecordDecls that back FieldDecls"
This reverts commit 3bf96b0329.

It causes crashes as reported in PR52257 and a few other places. A reproducer is bundled with this commit to verify any fix forward. The original test is left in place, but marked XFAIL as it now produces the wrong result.

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D113449
2021-11-10 10:38:01 -08:00
Lawrence D'Anna bbef51eb43 [lldb] make it easier to find LLDB's python
It is surprisingly difficult to write a simple python script that
can reliably `import lldb` without failing, or crashing.   I'm
currently resorting to convolutions like this:

    def find_lldb(may_reexec=False):
		if prefix := os.environ.get('LLDB_PYTHON_PREFIX'):
			if os.path.realpath(prefix) != os.path.realpath(sys.prefix):
				raise Exception("cannot import lldb.\n"
					f"  sys.prefix should be: {prefix}\n"
					f"  but it is: {sys.prefix}")
		else:
			line1, line2 = subprocess.run(
				['lldb', '-x', '-b', '-o', 'script print(sys.prefix)'],
				encoding='utf8', stdout=subprocess.PIPE,
				check=True).stdout.strip().splitlines()
			assert line1.strip() == '(lldb) script print(sys.prefix)'
			prefix = line2.strip()
			os.environ['LLDB_PYTHON_PREFIX'] = prefix

		if sys.prefix != prefix:
			if not may_reexec:
				raise Exception(
					"cannot import lldb.\n" +
					f"  This python, at {sys.prefix}\n"
					f"  does not math LLDB's python at {prefix}")
			os.environ['LLDB_PYTHON_PREFIX'] = prefix
			python_exe = os.path.join(prefix, 'bin', 'python3')
			os.execl(python_exe, python_exe, *sys.argv)

		lldb_path = subprocess.run(['lldb', '-P'],
			check=True, stdout=subprocess.PIPE,
				encoding='utf8').stdout.strip()

		sys.path = [lldb_path] + sys.path

This patch aims to replace all that with:

  #!/usr/bin/env lldb-python
  import lldb
  ...

... by adding the following features:

* new command line option: --print-script-interpreter-info.  This
   prints language-specific information about the script interpreter
   in JSON format.

* new tool (unix only): lldb-python which finds python and exec's it.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D112973
2021-11-10 10:33:34 -08:00
Med Ismail Bennani 738621d047 [lldb/bindings] Change ScriptedThread initializer parameters
This patch changes the `ScriptedThread` initializer in couple of ways:
- It replaces the `SBTarget` parameter by a `SBProcess` (pointing to the
  `ScriptedProcess` that "owns" the `ScriptedThread`).
- It adds a reference to the `ScriptedProcessInfo` Dictionary, to pass
  arbitrary user-input to the `ScriptedThread`.

This patch also fixes the SWIG bindings methods that call the
`ScriptedProcess` and `ScriptedThread` initializers by passing all the
arguments to the appropriate `PythonCallable` object.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-11-10 17:43:28 +01:00
Med Ismail Bennani ad0f7d3d4a
[lldb] Fix Scripted ProcessLaunchInfo Argument nullptr deref
This patch adds a new `StructuredData::Dictionary` constructor that
takes a `StructuredData::ObjectSP` as an argument. This is used to pass
the opaque_ptr from the `SBStructuredData` used to initialize a
ScriptedProecss, to the `ProcessLaunchInfo` class.

This also updates `SBLaunchInfo::SetScriptedProcessDictionary` to
reflect the formentionned changes which solves the nullptr deref.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-11-10 16:43:19 +00:00
Pavel Labath ff7ce0af04 [lldb] DeConstStringify the Property class
Most of the interfaces were converted already, this just converts the
internal implementation.
2021-11-10 15:07:30 +01:00
Michał Górny 82ce912743 [lldb] [gdb-server] Fix fill_clamp to handle signed src types
Fix the fill_clamp() function to handle signed source types.  Make sure
that the source value is always non-negative, and cast it to unsigned
when verifying the upper bound.  This fixes compiler warnings about
comparing unsigned and signed types.

Differential Revision: https://reviews.llvm.org/D113519
2021-11-10 09:38:55 +01:00
Michał Górny 3f1372365a [lldb] Support gdbserver signals
GDB and LLDB use different signal models.  GDB uses a predefined set
of signal codes, and maps platform's signos to them.  On the other hand,
LLDB has historically simply passed native signos.

In order to improve compatibility between LLDB and gdbserver, the GDB
signal model should be used.  However, GDB does not provide a mapping
for all existing signals on Linux and unsupported signals are passed
as 'unknown'.  Limiting LLDB to this behavior could be considered
a regression.

To get the best of both worlds, use the LLDB signal model when talking
to lldb-server, and the GDB signal model otherwise.  For this purpose,
new versions of lldb-server indicate "native-signals+" via qSupported.
At the same time, we also detect older versions of lldb-server
via QThreadSuffixSupported for backwards compatibility.  If neither test
succeeds, we assume gdbserver or another implementation using GDB model.

Differential Revision: https://reviews.llvm.org/D108078
2021-11-10 09:38:55 +01:00
Danil Stefaniuc 577c1eecf8 [formatters] Add a libstdcpp formatter for forward_list and refactor list formatter
This diff adds a data formatter for libstdcpp's forward_list. Besides, it refactors the existing code by extracting the common functionality between libstdcpp forward_list and list formatters into the AbstractListSynthProvider class.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D113362
2021-11-09 21:33:08 -08:00
Adrian Prantl c9881c7d99 Support looking up absolute symbols
The Swift stdlib uses absolute symbols in the dylib to communicate
feature flags to the process. LLDB's expression evaluator needs to be
able to find them. This wires up absolute symbols so they show up in
the symtab lookup command, which is also all that's needed for them to
be visible to the expression evaluator JIT.

rdar://85093828

Differential Revision: https://reviews.llvm.org/D113445
2021-11-09 09:44:37 -08:00
Pavel Labath a40929dcd2 [lldb] Fix cross-platform kills
This patch fixes an amusing bug where a Platform::Kill operation would
happily terminate a proces on a completely different platform, as long
as they have the same process ID. This was due to the fact that the
implementation was iterating through all known (debugged) processes in
order terminate them directly.

This patch just deletes that logic, and makes everything go through the
OS process termination APIs. While it would be possible to fix the logic
to check for a platform match, it seemed to me that the implementation
was being too smart for its own good -- accessing random Process
objects without knowing anything about their state is risky at best.
Going through the os ensures we avoid any races.

I also "upgrade" the termination signal to a SIGKILL to ensure the
process really dies after this operation.

Differential Revision: https://reviews.llvm.org/D113184
2021-11-09 15:31:07 +01:00
Jonas Devlieghere 1ab9a2906e [lldb] Fix C2360: initialization of 'identifier' is skipped by 'case' label
Make sure that every case has its own lexical block.
2021-11-05 23:09:35 -07:00
Jonas Devlieghere cd7a2bf94b [lldb] Don't set the OS for ARMGetSupportedArchitectureAtIndex
Don't set the OS when computing supported architectures in
PlatformDarwin::ARMGetSupportedArchitectureAtIndex.

Differential revision: https://reviews.llvm.org/D113159
2021-11-05 22:52:28 -07:00
Jonas Devlieghere 05fbe75890 [lldb] Remove nested switches from ARMGetSupportedArchitectureAtIndex (NFC)
Remove the nested switches from the ARMGetSupportedArchitectureAtIndex
implementation.

Differential revision: https://reviews.llvm.org/D113155
2021-11-05 21:12:00 -07:00
Jonas Devlieghere 6d48e2505c [lldb] Use std::string instead of llvm::Twine in GDBRemoteCommunicationClient
From the documentation:

  A Twine is not intended for use directly and should not be stored, its
  implementation relies on the ability to store pointers to temporary
  stack objects which may be deallocated at the end of a statement.
  Twines should only be used accepted as const references in arguments,
  when an API wishes to accept possibly-concatenated strings.

rdar://84799118

Differential revision: https://reviews.llvm.org/D113314
2021-11-05 13:19:00 -07:00
Jonas Devlieghere 10eb32f45d [lldb] Improve 'lang objc tagged-pointer info' command
Don't try to get a class descriptor for a pointer that doesn't look like
a tagged pointer. Also print addresses as fixed-width hex and update the
test.
2021-11-05 13:19:00 -07:00
Martin Storsjö a2c9cf4c76 [lldb] Use is_style_posix() for path style checks
Since a8b54834a1, there are two
distinct Windows path styles, `windows_backslash` (with the old
`windows` being an alias for it) and `windows_slash`.
4e4883e1f3 added helpers for
inspecting path styles.

The newly added windows_slash path style doesn't end up used in
LLDB yet anyway, as LLDB is quite decoupled from most of
llvm::sys::path and uses its own FileSpec class. To take it in
use, it could be hooked up in `FileSpec::Style::GetNativeStyle`
(in lldb/source/Utility/FileSpec.cpp) just like in the `real_style`
function in llvm/lib/Support/Path.cpp in
df0ba47c36.

It is not currently clear whether there's a real need for using
the Windows path style with forward slashes in LLDB (if there's any
other applications interacting with it, expecting that style), and
what other changes in LLDB are needed for that to work, but this
at least makes some of the checks more ready for the new style,
simplifying code a bit.

Differential Revision: https://reviews.llvm.org/D113255
2021-11-05 21:50:45 +02:00
Raphael Isemann f6b7bcc64a [lldb][NFC] StringRef-ify name param in CreateClassTemplateDecl 2021-11-04 15:28:02 +01:00
Raphael Isemann 7323d07483 [lldb][NFC] Remove a bunch of unnecessary nullptr checks
Those nullptr checks are after we already accessed the pointer.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D113175
2021-11-04 15:21:03 +01:00
Raphael Isemann b738a69ab8 [lldb][NFC] StringRef-ify the name parameter in CreateEnumerationType
Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D113176
2021-11-04 14:49:16 +01:00
Muhammad Omair Javaid b595137fe1 [LLDB] Fix Cpsr size for WoA64 target
CPSR on Arm64 is 4 bytes in size but windows on Arm implementation is trying to read/write 8 bytes against a byte register causing LLDB unit tests failures.

Ref: https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-arm64_nt_context

Reviewed By: mstorsjo

Differential Revision: https://reviews.llvm.org/D112471
2021-11-04 17:43:31 +05:00
Jonas Devlieghere f9e6be5cc1 [lldb] Update tagged pointer command output and test.
- Use formatv to print the addresses.
 - Add check for 0x0 which is treated as an invalid address.
 - Use a an address that's less likely to be interpreted as a real
   tagged pointer.
2021-11-03 15:04:36 -07:00
David Spickett fac3f20de5 Reland "[lldb] Remove non address bits when looking up memory regions"
This reverts commit 5fbcf67734.

ProcessDebugger is used in ProcessWindows and NativeProcessWindows.
I thought I was simplifying things by renaming to DoGetMemoryRegionInfo
in ProcessDebugger but the Native process side expects "GetMemoryRegionInfo".

Follow the pattern that WriteMemory uses. So:
* ProcessWindows::DoGetMemoryRegioninfo calls ProcessDebugger::GetMemoryRegionInfo
* NativeProcessWindows::GetMemoryRegionInfo does the same
2021-11-03 13:56:51 +00:00
David Spickett 5fbcf67734 Revert "[lldb] Remove non address bits when looking up memory regions"
This reverts commit 6f5ce43b43 due to
build failure on Windows.
2021-11-03 13:27:41 +00:00
Pavel Labath 30f922741a [lldb] Remove ConstString from plugin names in PluginManager innards
This completes de-constification of plugin names.
2021-11-03 13:14:21 +01:00
David Spickett 6f5ce43b43 [lldb] Remove non address bits when looking up memory regions
On AArch64 we have various things using the non address bits
of pointers. This means when you lookup their containing region
you won't find it if you don't remove them.

This changes Process GetMemoryRegionInfo to a non virtual method
that uses the current ABI plugin to remove those bits. Then it
calls DoGetMemoryRegionInfo.

That function does the actual work and is virtual to be overriden
by Process implementations.

A test case is added that runs on AArch64 Linux using the top
byte ignore feature.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D102757
2021-11-03 11:10:42 +00:00
Jonas Devlieghere 50b40b0518 [lldb] Improve error reporting in `lang objc tagged-pointer info`
Improve error handling for the lang objc tagged-pointer info. Rather
than failing silently, report an error if we couldn't convert an
argument to an address or resolve the class descriptor.

  (lldb) lang objc tagged-pointer info 0xbb6404c47a587764
  error: could not get class descriptor for 0xbb6404c47a587764

  (lldb) lang objc tagged-pointer info n1
  error: could not convert 'n1' to a valid address

Differential revision: https://reviews.llvm.org/D112945
2021-11-02 14:25:42 -07:00
Pavel Labath adf5e9c9b6 [lldb] Remove ConstString from TypeSystem and REPL plugin names 2021-11-02 16:13:52 +01:00
Benjamin Kramer 48677f58b0 [lldb] Unbreak the macOS build after dfd499a61c 2021-11-02 09:47:44 +01:00
Xu Jun dfd499a61c [lldb][NFC] avoid unnecessary roundtrips between different string types
The amount of roundtrips between StringRefs, ConstStrings and std::strings is
getting a bit out of hand, this patch avoid the unnecessary roundtrips.

Reviewed By: wallace, aprantl

Differential Revision: https://reviews.llvm.org/D112863
2021-11-01 22:15:01 -07:00
Xu Jun fe19ae352c normalize file path when searching the source map
The key stored in the source map is a normalized path string with host's
path style, so it is also necessary to normalize the file path during
searching the map

Reviewed By: wallace, aprantl

Differential Revision: https://reviews.llvm.org/D112439
2021-11-01 22:13:55 -07:00
Quinn Pham 68bb4e1648 [lldb][NFC] Inclusive Language: Replace master with main
[NFC] This patch fixes a URL within a git repo whose master branch was renamed
to main.
2021-11-01 12:25:41 -05:00
Danil Stefaniuc 82ed106567 [formatters] Add a libstdcpp formatter for multiset and unify tests across stdlibs
This diff adds a data formatter for libstdcpp's multiset. Besides, it improves and unifies the tests for multiset for libcxx and libstdcpp for maintainability.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D112785
2021-10-30 15:07:23 -07:00
Danil Stefaniuc f869e0be44 [formatters] Add a libstdcpp formatter for multimap and unify modify tests across stdlibs
This diff adds a data formatter for libstdcpp's multimap. Besides, it improves and unifies the tests for multimap for libcxx and libstdcpp for maintainability.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D112752
2021-10-30 12:53:32 -07:00
Raphael Isemann 4cf9d1e449 [lldb][NFC] Modernize for-loops in ModuleList
Reviewed By: mib

Differential Revision: https://reviews.llvm.org/D112379
2021-10-30 13:40:58 +02:00
Raphael Isemann 85bcc1eb2f [lldb] Make SBType::IsTypeComplete more consistent by forcing the loading of definitions
Currently calling SBType::IsTypeComplete returns true for record types if and
only if the underlying record in our internal Clang AST has a definition.

The function however doesn't actually force the loading of any external
definition from debug info, so it currently can return false even if the type is
actually defined in a program's debug info but LLDB hasn't lazily created the
definition yet.

This patch changes the behaviour to always load the definition first so that
IsTypeComplete now consistently returns true if there is a definition in the
module/target.

The motivation for this patch is twofold:

* The API is now arguably more useful for the user which don't know or care
about the internal lazy loading mechanism of LLDB.

* With D101950 there is no longer a good way to ask a Decl for a definition
without automatically pulling in a definition from the ExternalASTSource. The
current behaviour doesn't seem useful enough to justify the necessary
workarounds to preserve it for a time after D101950.

Note that there was a test that used this API to test lazy loading of debug info
but that has been replaced with TestLazyLoading by now (which just dumps the
internal Clang AST state instead).

Reviewed By: aprantl

Differential Revision: https://reviews.llvm.org/D112615
2021-10-30 13:28:27 +02:00
Raphael Isemann e2ede1715d [lldb] Update field offset/sizes when encountering artificial members such as vtable pointers
`DWARFASTParserClang::ParseSingleMember` turns DWARF DIEs that describe
struct/class members into their respective Clang representation (e.g.,
clang::FieldDecl). It also updates a record of where the last field
started/ended so that we can speculatively fill any holes between a field and a
bitfield with unnamed bitfield padding.

Right now we are completely ignoring 'artificial' members when parsing the DWARF
of a struct/class. The only artificial member that seems to be emitted in
practice for C/C++ seems to be the vtable pointer.

By completely skipping both the Clang AST node creation and the updating of the
last-field record, we essentially leave a hole in our layout with the size of
our artificial member. If the next member is a bitfield we then speculatively
fill the hole with an unnamed bitfield. During CodeGen Clang inserts an
artificial vtable pointer into the layout again which now occupies the same
offset as the unnamed bitfield. This later brings down Clang's
`CGRecordLowering::insertPadding` when it checks that none of the fields of the
generated record layout overlap.

Note that this is not a Clang bug. We explicitly set the offset of our fields in
LLDB and overwrite whatever Clang makes up.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D112697
2021-10-30 13:22:21 +02:00
Michał Górny 16a816a19e [lldb] [gdb-remote] Fix processing generic regnums
Fix regression in processing generic regnums that was introduced
in fa456505b8 ("[lldb] [gdb-remote]
Refactor getting remote regs to use local vector").  Since then,
the "generic" field was wrongly interpreted as integer rather than
string constant.

Thanks to Ted Woodward for noticing and providing the correct code.
2021-10-29 21:37:46 +02:00
Pavel Labath a394231819 [lldb] Remove ConstString from SymbolVendor, Trace, TraceExporter, UnwindAssembly, MemoryHistory and InstrumentationRuntime plugin names 2021-10-29 12:08:57 +02:00
Luís Ferreira ac73f567cf [lldb] Remove forgotten FIXME on CPlusPlus formatters
The patch [1] introduced this FIXME but ended up not being removed when fixed.

[1]: f68df12fb0

Signed-off-by: Luís Ferreira <contact@lsferreira.net>

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D112586
2021-10-29 11:32:40 +02:00
Luís Ferreira 5e316012d0 [lldb] Refactor C/C++ string and char summary providers
This patch refactors C/C++ formatters to avoid repetitive code by using templates.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D112658
Signed-off-by: Luís Ferreira <contact@lsferreira.net>
2021-10-29 11:22:02 +02:00
Pavel Labath 3abd063fc7 [lldb] Make TypeSystemClang::GetFullyUnqualifiedType work for constant arrays
Unqualify (constant) arrays recursively, just like we do for pointers.
This allows for better pretty printer matching.

Differential Revision: https://reviews.llvm.org/D112708
2021-10-29 11:13:59 +02:00
Michał Górny e9dcd8b37b [lldb] [Host/Terminal] Fix warnings with termios disabled
Thanks to Nico Weber for the suggestion.

Differential Revision: https://reviews.llvm.org/D112632
2021-10-29 09:58:09 +02:00
Jim Ingham e655769c4a Fix a bug in Launch when using an async debugger & remote platform.
We weren't setting the listener back to the unhijacked one in this
case, so that a continue after the stop fails.  It thinks the process
is still running.  Also add tests for this behavior.

Differential Revision: https://reviews.llvm.org/D112747
2021-10-28 17:02:43 -07:00
Jim Ingham 1227fa7e90 Remove unused ValueObjectDynamicValue::SetOwningSP & backing ivar
This has no uses and the ValueObjectDynamicValue already tracks
its ownership through the parent it is passed when made.  I can't
find any vestiges of the use of this API, maybe it was from some
earlier design?

Resetting the backing ivar was the only job the destructor did, so I
set that to default as well.

Differential Revision: https://reviews.llvm.org/D112677
2021-10-28 16:06:01 -07:00
Michał Górny e50f02ba7e [lldb] [Host/ConnectionFileDescriptor] Refactor to improve code reuse
Refactor ConnectionFileDescriptor to improve code reuse for different
types of sockets.  Unify method naming.

While at it, remove some (now-)dead code from Socket.

Differential Revision: https://reviews.llvm.org/D112495
2021-10-28 19:24:10 +02:00
Raphael Isemann f5c65be510 [lldb][NFC] Improve CppModuleConfiguration documentation a bit 2021-10-28 16:39:06 +02:00
Pavel Labath 5f4980f004 [lldb] Remove ConstString from Process, ScriptInterpreter and StructuredData plugin names 2021-10-28 10:15:03 +02:00
Michał Górny 073c5d0e47 [lldb] [Host/Socket] Make DecodeHostAndPort() return a dedicated struct
Differential Revision: https://reviews.llvm.org/D112629
2021-10-28 09:57:50 +02:00
Greg Clayton 1300556479 Add unix signal hit counts to the target statistics.
Android and other platforms make wide use of signals when running applications and this can slow down debug sessions. Tracking this statistic can help us to determine why a debug session is slow.

The new data appears inside each target object and reports the signal hit counts:

      "signals": [
        {
          "SIGSTOP": 1
        },
        {
          "SIGUSR1": 1
        }
      ],

Differential Revision: https://reviews.llvm.org/D112683
2021-10-27 22:31:14 -07:00
Greg Clayton fb25496832 Add breakpoint resolving stats to each target.
This patch adds breakpoints to each target's statistics so we can track how long it takes to resolve each breakpoint. It also includes the structured data for each breakpoint so the exact breakpoint details are logged to allow for reproduction of slow resolving breakpoints. Each target gets a new "breakpoints" array that contains breakpoint details. Each breakpoint has "details" which is the JSON representation of a serialized breakpoint resolver and filter, "id" which is the breakpoint ID, and "resolveTime" which is the time in seconds it took to resolve the breakpoint. A snippet of the new data is shown here:

  "targets": [
    {
      "breakpoints": [
        {
          "details": {...},
          "id": 1,
          "resolveTime": 0.00039291599999999999
        },
        {
          "details": {...},
          "id": 2,
          "resolveTime": 0.00022679199999999999
        }
      ],
      "totalBreakpointResolveTime": 0.00061970799999999996
    }
  ]

This provides full details on exactly how breakpoints were set and how long it took to resolve them.

Differential Revision: https://reviews.llvm.org/D112587
2021-10-27 16:50:11 -07:00
Med Ismail Bennani 8dbbe3356b Revert "[lldb] [Host/ConnectionFileDescriptor] Refactor to improve code reuse"
This reverts commit e1acadb61d.
2021-10-27 23:57:33 +02:00
Jonas Devlieghere 8bac9e3686 [lldb] Fixup code addresses in the Objective-C language runtime
Upstream the calls to ABI::FixCodeAddress in the Objective-C language
runtime.

Differential revision: https://reviews.llvm.org/D112662
2021-10-27 14:48:03 -07:00
Danil Stefaniuc 3eb9e6536a [formatters] Add a libstdcpp formatter for set and unify tests across stdlibs
This diff adds a data formatter for libstdcpp's set. Besides, it unifies the tests for set for libcxx and libstdcpp for maintainability.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D112537
2021-10-27 11:55:11 -07:00
Raphael Isemann 9d7006c4ae [lldb][NFC] Move a declaration in DWARFASTParserClang to its first use. 2021-10-27 17:46:50 +02:00
Nico Weber 99f5f0a2b7 fix comment typos to cycle bots 2021-10-27 09:43:42 -04:00
Michał Górny e1acadb61d [lldb] [Host/ConnectionFileDescriptor] Refactor to improve code reuse
Refactor ConnectionFileDescriptor to improve code reuse for different
types of sockets.  Unify method naming.

While at it, remove some (now-)dead code from Socket.

Differential Revision: https://reviews.llvm.org/D112495
2021-10-27 12:45:52 +02:00
Pavel Labath f5158ca48c Modernize Platform::GetOSKernelDescription 2021-10-27 10:46:47 +02:00
Pavel Labath 49481b5380 Remove ConstString from Language, LanguageRuntime, SystemRuntime and SymbolFile plugin names 2021-10-27 08:25:44 +02:00
Greg Clayton 2887d9fd86 Add new key/value pairs to the module statistics for "statistics dump".
The new key/value pairs that are added to each module's stats are:
"debugInfoByteSize": The size in bytes of debug info for each module.
"debugInfoIndexTime": The time in seconds that it took to index the debug info.
"debugInfoParseTime": The time in seconds that debug info had to be parsed.

At the top level we add up all of the debug info size, parse time and index time with the following keys:
"totalDebugInfoByteSize": The size in bytes of all debug info in all modules.
"totalDebugInfoIndexTime": The time in seconds that it took to index all debug info if it was indexed for all modules.
"totalDebugInfoParseTime": The time in seconds that debug info was parsed for all modules.

Differential Revision: https://reviews.llvm.org/D112501
2021-10-26 15:09:31 -07:00
Danil Stefaniuc 566bfbb740 [formatters] Add a libstdcpp formatter for bitset and unify tests across stdlibs
This diff adds a data formatter for libstdcpp's bitset. Besides, it unifies the tests for bitset for libcxx and libstdcpp for maintainability.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D112180
2021-10-26 14:49:50 -07:00
Michał Górny 4373f3595f [lldb] [Host] Move port predicate-related logic to gdb-remote
Remove the port predicate from Socket and ConnectionFileDescriptor,
and move it to gdb-remote.  It is specifically relevant to the threading
used inside gdb-remote and with the new port callback API, we can
reliably move it there.  While at it, switch from the custom Predicate
to std::promise/std::future.

Differential Revision: https://reviews.llvm.org/D112357
2021-10-26 13:53:08 +02:00
Michał Górny 58d28b931f [lldb] [lldb-gdbserver] Unify listen/connect code to use ConnectionFileDescriptor
Unify the listen and connect code inside lldb-server to use
ConnectionFileDescriptor uniformly rather than a mix of it and Acceptor.
This involves:

- adding a function to map legacy values of host:port parameter
  (including legacy server URLs) into CFD-style URLs

- adding a callback to return "local socket id" (i.e. UNIX socket path
  or TCP port number) between listen() and accept() calls in CFD

- adding a "unix-abstract-accept" scheme to CFD

As an additional advantage, this permits lldb-server to accept any URL
known to CFD including the new serial:// scheme.  Effectively,
lldb-server can now listen on the serial port.  Tests for connecting
over a pty are added to test that.

Differential Revision: https://reviews.llvm.org/D111964
2021-10-26 13:06:19 +02:00
Pavel Labath 93c7ed8c3f [lldb] Fix PlatformAppleSimulator for a458ef4f 2021-10-26 13:03:47 +02:00
Michał Górny f279e50fd0 [lldb] [Communication] Add a WriteAll() method that resumes writing
Add a Communication::WriteAll() that resumes Write() if the initial call
did not write all data.  Use it in GDBRemoteCommunication when sending
packets in order to fix handling partial writes (i.e. just resume/retry
them rather than erring out).  This fixes LLDB failures when writing
large packets to a pty.

Differential Revision: https://reviews.llvm.org/D112169
2021-10-26 12:45:45 +02:00
Pavel Labath 0a39a9c2cb Modernize and simplify HostInfo::GetOSKernelDescription
Replace bool+by-ref argument with llvm::Optional, and move the common
implementation into HostInfoPOSIX. Based on my (simple) experiment,
the uname and the sysctl approach return the same value on MacOS, so
there's no need for a mac-specific implementation of this functionality.

Differential Revision: https://reviews.llvm.org/D112457
2021-10-26 11:17:02 +02:00
Pavel Labath a458ef4f73 [lldb] Remove ConstString from Platform plugin names 2021-10-26 10:04:35 +02:00
Pavel Labath b69564d94d [lldb/DWARF] Move a declaration closer to its use
Adresses post-commit feedback on D112310.
2021-10-26 09:58:10 +02:00
Greg Clayton c571988e9d Add modules stats into the "statistics dump" command.
The new module stats adds the ability to measure the time it takes to parse and index the symbol tables for each module, and reports modules statistics in the output of "statistics dump" along with the path, UUID and triple of the module. The time it takes to parse and index the symbol tables are also aggregated into new top level key/value pairs at the target level.

Differential Revision: https://reviews.llvm.org/D112279
2021-10-25 11:50:02 -07:00
Michał Górny 1bd258fd4e [lldb] [DynamicRegisterInfo] Remove AddRegister() and make Finalize() protected
Now that AddRegister() is no longer used, remove it.  While at it,
we can also make Finalize() protected as all supported API methods
call it internally.

Differential Revision: https://reviews.llvm.org/D111498
2021-10-25 20:05:30 +02:00
Michał Górny 26c584f4f1 [lldb] [gdb-remote] Remove HardcodeARMRegisters() hack
HardcodeARMRegisters() is a hack that was supposed to be used "until
we can get an updated debugserver down on the devices".  Since it was
introduced back in 2012, there is a good chance that the debugserver
has been updated at least once since then.  Removing this code makes
transition to the new DynamicRegisterInfo API easier.

Differential Revision: https://reviews.llvm.org/D111491
2021-10-25 20:05:29 +02:00
Pavel Labath a53978c95c [lldb] Remove a trailing \0 from the result of HostInfoMacOSX::GetOSBuildString
This has been in there since forever, but only started to matter once
40e4ac3e changed how we print the string.
2021-10-25 17:33:06 +02:00
Michał Górny 9d63b90b59 [lldb] [Host/ConnectionFileDescriptor] Do not use non-blocking mode
Disable non-blocking mode that's enabled only for file:// and serial://
protocols.  All read operations should be going through the select(2)
in ConnectionFileDescriptor::BytesAvaliable, which effectively erases
(non-)blocking mode differences in reading.  We do want to perform
writes in the blocking mode.

Differential Revision: https://reviews.llvm.org/D112442
2021-10-25 16:24:00 +02:00
Pavel Labath 40e4ac3e5b [lldb] Modernize Platform::GetOSBuildString 2021-10-25 15:58:58 +02:00
Raphael Isemann 309fccdac9 [lldb][NFC] Use llvm::Optional to refer to Optional
clang::Optional is just an alias used within Clang.
2021-10-25 11:37:15 +02:00
Pavel Labath 1397c56d7a Fix windows build for 6fa1b4ff4 2021-10-25 11:12:39 +02:00
Michał Górny 0e5a4147e5 [lldb] [Utility/UriParser] Return results as 'struct URI'
Return results of URI parsing as 'struct URI' instead of assigning them
via output parameters.

Differential Revision: https://reviews.llvm.org/D112314
2021-10-25 10:58:21 +02:00
Michał Górny 21bb808eb4 [lldb] Support serial port parity checking
Differential Revision: https://reviews.llvm.org/D112365
2021-10-25 10:51:46 +02:00
Pavel Labath 6fa1b4ff4b Remove ConstString from DynamicLoader, JITLoader and Instruction plugin names 2021-10-25 10:32:35 +02:00
Pavel Labath c1055f0919 [lldb/DWARF] Don't create lldb_private::Functions for gc'ed DW_TAG_subprograms
Front-load the first_valid_code_address check, so that we avoid creating
the function object (instead of simply refusing to use it in queries).

Differential Revision: https://reviews.llvm.org/D112310
2021-10-25 10:32:35 +02:00
Kazu Hirata 4bd46501c3 Use llvm::any_of and llvm::none_of (NFC) 2021-10-24 17:35:33 -07:00
Kazu Hirata 7cc8fa2dd2 Use llvm::is_contained (NFC) 2021-10-24 09:32:57 -07:00
Kazu Hirata 4ba9d9c84f Use StringRef::contains (NFC) 2021-10-23 20:41:46 -07:00
Kazu Hirata d8e4170b0a Ensure newlines at the end of files (NFC) 2021-10-23 08:45:29 -07:00
Martin Storsjö ea9e9d61b5 [lldb] [Host/SerialPort] Fix build with GCC 7 2021-10-23 12:52:55 +03:00
Michał Górny ff56d80eaa [lldb] [Host/FreeBSD] Remove unused variable (NFC) 2021-10-23 11:38:35 +02:00
Med Ismail Bennani 42e4959253 [lldb/Formatters] Remove space from vector type string summaries (NFCI)
This patch changes the string summaries for vector types by removing the
space between the type and the bracket, conforming to 277623f4d5.

This should also fix TestCompactVectors failure.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-10-22 21:18:54 +02:00
Pavel Labath f37463b2ee [lldb] Another build fix for 8b8070e23
This particular usage was guarded by !__linux__, so it broke everywhere
else. It should probably be replaced by something else.
2021-10-22 15:29:38 +02:00
Michał Górny ff569ed030 [lldb] [Utility/UriParser] Replace port==-1 with llvm::None
Use llvm::Optional<uint16_t> instead of int for port number
in UriParser::Parse(), and use llvm::None to indicate missing port
instead of a magic value of -1.

Differential Revision: https://reviews.llvm.org/D112309
2021-10-22 14:39:18 +02:00
Pavel Labath 43f8845dd3 [lldb] Fix build errors from 8b8070e23
I missed windows and openbsd.
2021-10-22 14:28:52 +02:00
Pavel Labath 8b8070e234 Host::GetOSBuildString 2021-10-22 12:59:58 +02:00
Michał Górny 66e06cc8cb [llvm] [ADT] Update llvm::Split() per Pavel Labath's suggestions
Optimize the iterator comparison logic to compare Current.data()
pointers.  Use std::tie for assignments from std::pair.  Replace
the custom class with a function returning iterator_range.

Differential Revision: https://reviews.llvm.org/D110535
2021-10-22 12:27:46 +02:00
Pavel Labath b5e9f83ea4 [lldb] Remove ConstString from ABI, Architecture and Disassembler plugin names 2021-10-22 10:29:19 +02:00
Greg Clayton d7b338537c Modify "statistics dump" to dump JSON.
This patch is a smaller version of a previous patch https://reviews.llvm.org/D110804.

This patch modifies the output of "statistics dump" to be able to get stats from the current target. It adds 3 new stats as well. The output of "statistics dump" is now emitted as JSON so that it can be used to track performance and statistics and the output could be used to populate a database that tracks performance. Sample output looks like:

(lldb) statistics dump
{
  "expressionEvaluation": {
    "failures": 0,
    "successes": 0
  },
  "firstStopTime": 0.34164492800000001,
  "frameVariable": {
    "failures": 0,
    "successes": 0
  },
  "launchOrAttachTime": 0.31969605400000001,
  "targetCreateTime": 0.0040863039999999998
}

The top level keys are:

"expressionEvaluation" which replaces the previous stats that were emitted as plain text. This dictionary contains the success and fail counts.
"frameVariable" which replaces the previous stats for "frame variable" that were emitted as plain text. This dictionary contains the success and fail counts.
"targetCreateTime" contains the number of seconds it took to create the target and load dependent libraries (if they were enabled) and also will contain symbol preloading times if that setting is enabled.
"launchOrAttachTime" is the time it takes from when the launch/attach is initiated to when the first private stop occurs.
"firstStopTime" is the time in seconds that it takes to stop at the first stop that is presented to the user via the LLDB interface. This value will only have meaning if you set a known breakpoint or stop location in your code that you want to measure as a performance test.

This diff is also meant as a place to discuess what we want out of the "statistics dump" command before adding more funcionality. It is also meant to clean up the previous code that was storting statistics in a vector of numbers within the lldb_private::Target class.

Differential Revision: https://reviews.llvm.org/D111686
2021-10-21 12:14:21 -07:00
David Blaikie aee4925507 Recommit: Compress formatting of array type names (int [4] -> int[4])
Based on post-commit review discussion on
2bd8493847 with Richard Smith.

Other uses of forcing HasEmptyPlaceHolder to false seem OK to me -
they're all around pointer/reference types where the pointer/reference
token will appear at the rightmost side of the left side of the type
name, so they make nested types (eg: the "int" in "int *") behave as
though there is a non-empty placeholder (because the "*" is essentially
the placeholder as far as the "int" is concerned).

This was originally committed in 277623f4d5

Reverted in f9ad1d1c77 due to breakages
outside of clang - lldb seems to have some strange/strong dependence on
"char [N]" versus "char[N]" when printing strings (not due to that name
appearing in DWARF, but probably due to using clang to stringify type
names) that'll need to be addressed, plus a few other odds and ends in
other subprojects (clang-tools-extra, compiler-rt, etc).
2021-10-21 11:34:43 -07:00
Pavel Labath 6c88086ba8 [lldb] Fix a thinko in 2ace1e57
An empty plugin name means we should try everything.

Picked up by the windows bot.
2021-10-21 14:05:49 +02:00
Benjamin Kramer 39724158d3 [lldb] Silence -Wpessimizing-move warning
lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp:3635:10: error: moving a local object in a return statement prevents copy elision [-Werror,-Wpessimizing-move]
  return std::move(merged);
         ^
2021-10-21 12:59:00 +02:00
Pavel Labath 2ace1e5753 [lldb] Remove ConstString from GetPluginNameStatic of some plugins
This patch deals with ObjectFile, ObjectContainer and OperatingSystem
plugins. I'll convert the other types in separate patches.

In order to enable piecemeal conversion, I am leaving some ConstStrings
in the lowest PluginManager layers. I'll convert those as the last step.

Differential Revision: https://reviews.llvm.org/D112061
2021-10-21 12:58:45 +02:00
Jaroslav Sevcik 5a3556aa55 [lldb] Add omitted abstract formal parameters in DWARF symbol files
This patch fixes a problem introduced by clang change
https://reviews.llvm.org/D95617 and described by
https://bugs.llvm.org/show_bug.cgi?id=50076#c6, where inlined functions
omit unused parameters both in the stack trace and in `frame var`
command. With this patch, the parameters are listed correctly in the
stack trace and in `frame var` command.

Specifically, we parse formal parameters from the abstract version of
inlined functions and use those formal parameters if they are missing
from the concrete version.

Differential Revision: https://reviews.llvm.org/D110571
2021-10-21 12:33:42 +02:00
Michał Górny b8c3683d46 [lldb] [Host/SerialPort] Add std::moves for better compatibility 2021-10-21 11:08:05 +02:00
Michał Górny cbe7898447 [lldb] [Host/Terminal] Add missing #ifdef for baudRateToConst() 2021-10-21 11:00:17 +02:00
Michał Górny 4a7b4beac7 [lldb] Add serial:// protocol for connecting to serial port
Add a new serial:// protocol along with SerialPort that provides a new
API to open serial ports.  The URL consists of serial device path
followed by URL-style options, e.g.:

    serial:///dev/ttyS0?baud=115200&parity=even

If no options are provided, the serial port is only set to raw mode
and the other attributes remain unchanged.  Attributes provided via
options are modified to the specified values.  Upon closing the serial
port, its original attributes are restored.

Differential Revision: https://reviews.llvm.org/D111355
2021-10-21 10:46:45 +02:00
Michał Górny 92fb574c9f [lldb] [Host] Add setters for common teletype properties to Terminal
Add setters for common teletype properties to the Terminal class:

- SetRaw() to enable common raw mode options

- SetBaudRate() to set the baud rate

- SetStopBits() to select the number of stop bits

- SetParity() to control parity bit in the output

- SetHardwareControlFlow() to enable or disable hardware control flow
  (if supported)

Differential Revision: https://reviews.llvm.org/D111030
2021-10-21 10:33:38 +02:00
Raphael Isemann 46fb5d5ddf [lldb][NFC] clang-format CPlusPlusLanguage.cpp 2021-10-21 10:01:18 +02:00
Daniel Jalkut d531e5cf58 [LLDB] [NFC] Typo fix in usage text for "type filter" command
When you invoke "help type filter" the resulting help shows:

Syntax: type synthetic [<sub-command-options>]

This patch fixes the help so it says "type filter" instead of "type synthetic".

patch by: "Daniel Jalkut <jalkut@red-sweater.com>"

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D112199
2021-10-21 12:22:52 +05:30
Jonas Devlieghere 207998c242 [lldb] Remove variable "any" which is set but not used 2021-10-20 12:08:35 -07:00
Michał Górny f290efc326 [lldb] [ABI/X86] Support combining xmm* and ymm*h regs into ymm*
gdbserver does not expose combined ymm* registers but rather XSAVE-style
split xmm* and ymm*h portions.  Extend value_regs to support combining
multiple registers and use it to create user-friendly ymm* registers
that are combined from split xmm* and ymm*h portions.

Differential Revision: https://reviews.llvm.org/D108937
2021-10-20 15:06:45 +02:00
Michał Górny 99277a81f8 [lldb] [Process/Utility] Fix value_regs/invalidate_regs for ARM
Fix incorrect values for value_regs, and incomplete values for
invalidate_regs in RegisterInfos_arm.  The value_regs entry needs
to list only one base (i.e. larger) register that needs to be read
to get the value for this register, while invalidate_regs needs to list
all other registers (including pseudo-register) whose values would
change when this register is written to.

7a8ba4ffbe fixed a similar problem
for ARM64.

Differential Revision: https://reviews.llvm.org/D112066
2021-10-20 15:06:45 +02:00
Michał Górny 192331b890 [lldb] [Process/Linux] Support arbitrarily-sized FPR writes on ARM
Support arbitrarily-sized FPR writes on ARM in order to fix writing qN
registers directly.  Currently, writing them works only by accident
due to value_regs splitting them into smaller writes via dN and sN
registers.

Differential Revision: https://reviews.llvm.org/D112131
2021-10-20 15:06:44 +02:00
Michał Górny 6561c074c0 [lldb] [Process/Utility] Define qN regs on ARM via helper macro
Add a FPU_QREG macro to define qN registers.  This is a piece-wise
attempt of reconstructing D112066 with the goal of figuring out which
part of the larger change breaks the buildbot.

Differential Revision: https://reviews.llvm.org/D112066
2021-10-20 13:08:17 +02:00
Pavel Labath ffbff6c511 [lldb/DWARF] Ignore debug info pointing to the low addresses
specifically, ignore addresses that point before the first code section.

This resurrects D87172 with several notable changes:
- it fixes a bug where the early exits in InitializeObject left
  m_first_code_address "initialized" to LLDB_INVALID_ADDRESS (0xfff..f),
  which caused _everything_ to be ignored.
- it extends the line table fix to function parsing as well, where it
  replaces a similar check which was checking the executable permissions
  of the section. This was insufficient because some
  position-independent elf executables can have an executable segment
  mapped at file address zero. (What makes this fix different is that it
  checks for the executable-ness of the sections contained within that
  segment, and those will not be at address zero.)
- It uses a different test case, with an elf file with near-zero
  addresses, and checks for both line table and function parsing.

Differential Revision: https://reviews.llvm.org/D112058
2021-10-20 11:19:30 +02:00
Lawrence D'Anna 8ac5a6641f [lldb] improve the help strings for gdb-remote and kdp-remote
The help string can be more helpful by explaining these are
aliases for 'process connect'

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D111965
2021-10-19 13:08:21 -07:00