Commit Graph

28856 Commits

Author SHA1 Message Date
Jason Molenda
3ad618f4ae Update qHostInfo/LC_NOTE so multiple address bits can be specified
On AArch64 systems, we may have different page table setups for
low memory and high memory, and therefore a different number of
bits used for addressing depending on which half of memory the
address is in.

This patch extends the qHostInfo and LC_NOTE "addrable bits" so
that it can specify the number of addressing bits in high memory
and in low memory separately.  It builds on the patch I added in
https://reviews.llvm.org/D151292 where Process tracks the separate
address masks, and there is a user setting to set them manually.

Differential Revision: https://reviews.llvm.org/D157667
rdar://113225907
2023-08-15 13:21:33 -07:00
Kazu Hirata
04da7490d8 [lldb] Fix warnings
This patch fixes warnings like:

  lldb/source/Core/ModuleList.cpp:1086:3: error: 'scoped_lock' may not
  intend to support class template argument deduction
  [-Werror,-Wctad-maybe-unsupported]
2023-08-15 12:46:36 -07:00
Augusto Noronha
4a390a56ae [lldb] Implement ModuleList::Swap 2023-08-15 11:33:34 -07:00
Augusto Noronha
22413641e2 [lldb] Fix data race in PipePosix
Thread sanitizer reports the following data race:

```
WARNING: ThreadSanitizer: data race (pid=43201)
  Write of size 4 at 0x00010520c474 by thread T1 (mutexes: write M0, write M1):
    #0 lldb_private::PipePosix::CloseWriteFileDescriptor() PipePosix.cpp:242 (liblldb.18.0.0git.dylib:arm64+0x414700) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #1 lldb_private::PipePosix::Close() PipePosix.cpp:217 (liblldb.18.0.0git.dylib:arm64+0x4144e8) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #2 lldb_private::ConnectionFileDescriptor::Disconnect(lldb_private::Status*) ConnectionFileDescriptorPosix.cpp:239 (liblldb.18.0.0git.dylib:arm64+0x40a620) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #3 lldb_private::Communication::Disconnect(lldb_private::Status*) Communication.cpp:61 (liblldb.18.0.0git.dylib:arm64+0x2a9318) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #4 lldb_private::process_gdb_remote::ProcessGDBRemote::DidExit() ProcessGDBRemote.cpp:1167 (liblldb.18.0.0git.dylib:arm64+0x8ed984) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)

  Previous read of size 4 at 0x00010520c474 by main thread (mutexes: write M2, write M3):
    #0 lldb_private::PipePosix::CanWrite() const PipePosix.cpp:229 (liblldb.18.0.0git.dylib:arm64+0x4145e4) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #1 lldb_private::ConnectionFileDescriptor::Disconnect(lldb_private::Status*) ConnectionFileDescriptorPosix.cpp:212 (liblldb.18.0.0git.dylib:arm64+0x40a4a8) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #2 lldb_private::Communication::Disconnect(lldb_private::Status*) Communication.cpp:61 (liblldb.18.0.0git.dylib:arm64+0x2a9318) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #3 lldb_private::process_gdb_remote::GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote&, lldb_private::Timeout<std::__1::ratio<1l, 1000000l>>, bool) GDBRemoteCommunication.cpp:373 (liblldb.18.0.0git.dylib:arm64+0x8b9c48) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
    #4 lldb_private::process_gdb_remote::GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote&, lldb_private::Timeout<std::__1::ratio<1l, 1000000l>>, bool) GDBRemoteCommunication.cpp:243 (liblldb.18.0.0git.dylib:arm64+0x8b9904) (BuildId: 2983976beb2637b5943bff32fd12eb8932000000200000000100000000000e00)
```

Fix this by adding a mutex to PipePosix.

Differential Revision: https://reviews.llvm.org/D157654
2023-08-15 11:30:35 -07:00
Jonas Devlieghere
f2ec73c746
[lldb] Move deprecation message from implementation to header (NFC)
Address Alex's post commit review feedback from D158000.
2023-08-15 10:41:11 -07:00
Jonas Devlieghere
23312cde45
[lldb] Remove {Get,Set}CloseInputOnEOF and deprecate SB equivalent (NFC)
These functions have been NO-OPs since 2014 (44d937820b). Remove them
and deprecate the corresponding functions in SBDebugger.

Differential revision: https://reviews.llvm.org/D158000
2023-08-15 10:37:04 -07:00
Justin Bogner
dcb6d212fd Reapply "[Option] Add "Visibility" field and clone the OptTable APIs to use it"
This reverts commit 4e3b89483a, with
fixes for places I'd missed updating in lld and lldb. I've also
renamed OptionVisibility::Default to "DefaultVis" to avoid ambiguity
since the undecorated name has to be available anywhere Options.inc is
included.

Original message follows:

This splits OptTable's "Flags" field into "Flags" and "Visibility",
updates the places where we instantiate Option tables, and adds
variants of the OptTable APIs that use Visibility mask instead of
Include/Exclude flags.

We need to do this to clean up a bunch of complexity in the clang
driver's option handling - there's a whole slew of flags like
CoreOption, NoDriverOption, and FlangOnlyOption there today to try to
handle all of the permutations of flags that the various drivers need,
but it really doesn't scale well, as can be seen by things like the
somewhat recently introduced CLDXCOption.

Instead, we'll provide an additive model for visibility that's
separate from the other flags. For things like "HelpHidden", which is
used as a "subtractive" modifier for option visibility, we leave that
in "Flags" and handle it as a special case.

Note that we don't actually update the users of the Include/Exclude
APIs here or change the flags that exist in clang at all - that will
come in a follow up that refactors clang's Options.td to use the
increased flexibility this change allows.

Differential Revision: https://reviews.llvm.org/D157149
2023-08-15 01:16:58 -07:00
Alex Langford
5a25f97e69 [lldb][NFCI] Change parameter type in Process::SetExitStatus
My primary motivation here is actually to change something in
UnixSignals, but this change is a necesary precondition.

I've also updated the documentation and rewritten the log statements to
use `formatv` instead of `printf` (printf-style formatting and
llvm::StringRef don't mix well).

Differential Revision: https://reviews.llvm.org/D157662
2023-08-14 15:49:03 -07:00
Alex Langford
69fdbdc449 [lldb] Remove support for SBHostOS threading functionality
As stated on Discourse*, these methods have been deprecated. I am
removing their implementation. They will now do nothing and return a
value indicating failure (where appropriate).
Due to the LLDB project's commitment to ABI stability at the SB API
layer, we cannot remove these symbols completely.

Discourse link: https://discourse.llvm.org/t/do-you-use-the-threading-functionality-in-sbhostos/71973
2023-08-14 14:33:08 -07:00
Alex Langford
e634c2f714 [lldb] Remove use of __future__ in python
These were useful primarily for the Python 2 to 3 transition. Python 2
is no longer supported so these are no longer necessary.

Differential Revision: https://reviews.llvm.org/D157759
2023-08-14 14:14:48 -07:00
Venkata Ramanaiah Nalamothu
254a31273a [lldb][NFC] Use MCInstrAnalysis when available in the disassembler plugin
Since the info in MCInstrDesc is based on opcodes only, it is often quite
inaccurate. The MCInstrAnalysis has been added so that targets can provide
accurate info, which is based on registers used by the instruction, through
the own versions of MCInstrDesc functions.

The RISCVMCInstrAnalysis, which needs to refine several MCInstrDesc methods,
is a good example for this.

Given the llvm-objdump also uses MCInstrAnalysis, I think this change is in
the right direction.

The default implementation of MCInstrAnalysis methods forward the query to
MCInstrDesc functions. Hence, no functional change is intended/expected.

To avoid bloating up MCInstrAnalysis, only the methods provided by it and
the ones used by disassembler plugin are changed to use MCInstrAnalysis when
available.

Though I am not sure if it will be useful, making MCInstrAnalysis available
in the disassembler plugin would allow enabling symbolize operands (D84191)
feature in lldb's disassembler as well.

Reviewed By: jasonmolenda

Differential Revision: https://reviews.llvm.org/D156086
2023-08-14 08:37:41 +05:30
Med Ismail Bennani
706e875da3 [lldb/crashlog] Skip images with empty path and 0 UUID from loading
This patch skips images with an empty path or a 0 UUID from loading as a
SymbolFileJSON.

rdar://112107986

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

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-08-11 23:59:42 -07:00
Med Ismail Bennani
75bed9655a [lldb/crashlog] Fix sticky image parsing logic
Prior to this patch, when a user loaded multiple crash report in lldb,
they could get in a situation where all the targets would keep the same
architecture and executable path as the first one that we've created.

The reason behind this was that even if we created a new CrashLog
object, which is derived from a Symbolicator class that has a newly
constructoted image list as a default argument, because that default
argument is only created once when the function is defined, every CrashLog
object would share the same list.

That will cause use to append newly parsed  images to the same
Symbolicator image list accross multiple CrashLog objects.

To address this, this patch changes the default argument value for the
image parameter to `None` and only initialize it as an empty list when
no argument was passed.

This also removes the image list stored in each CrashLog parsers since
they shouldn't have any state and should be re-usable. So now, the only
source of truth is stored in the CrashLog object.

rdar://84984949

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

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-08-11 23:59:42 -07:00
Med Ismail Bennani
4677041d61 [lldb/crashlog] Move CrashLogParseMode into TextCrashLogParser (NFC)
This patch moves CrashLogParseMode into TextCrashLogParser since it's
the only class using it.

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-08-11 23:59:42 -07:00
Med Ismail Bennani
8f75c4d01e [lldb/crashlog] Make TextCrashLogParser more resilient to new lines
This patch changes the parsing logic for the legacy crash report format
to avoid interrupting the parsing if there are new lines in the middle
of a section.

To do, the parser starts to skip all consecutive empty lines. If the
number of lines skipped is greater than 1, the parser considers that it
reached a new setion of the report and should reset the parsing mode to
back to normal.

Otherwise, it tries to parse the next line in the current parsing mode.
If it succeeds, the parser will also skip that line since it has already
been parsed and continue the parsing.

rdar://107022595

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

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-08-11 23:59:42 -07:00
Med Ismail Bennani
f043e66e98 [lldb/crashlog] Make register output match lldb ordering in legacy mode
This patch changes the way we dump the registers from the legacy
crashlog command to make sure that the ordering matches the one from lldb.

rdar://109172073

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

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-08-11 23:59:41 -07:00
Jason Molenda
ebf249066a [lldb] SBTarget::AddModule do all searches by UUID, set Target arch
Make SBTarget::AddModule possibly call out to an external program to
find the binary by UUID if it can't be found more easily, the same
way `target modules add -u ...` works from the commandline.

If the Target does not have an architecture set yet, use the
Module's Arch to initialize it.  Allows an API writer to create
a target with no arch, and inherit it from the first binary they
load with AddModules.

Differential Revision: https://reviews.llvm.org/D157659
rdar://113657555
2023-08-11 14:20:38 -07:00
Jonas Devlieghere
be237b76da
[lldb] Improve error message when trying to debug a non-debuggable process
On the Swift forums, people are disabling SIP in order to debug process
that are missing the get-task-allow entitlement. Improve the error to
give developers a hint at the potential issues.

rdar://113704200

Differential revision: https://reviews.llvm.org/D157640
2023-08-11 10:47:00 -07:00
Jie Fu
989f25001a [lldb] 'scoped_lock' may not intend to support class template argument deduction (NFC)
/data/home/jiefu/llvm-project/lldb/source/Host/common/File.cpp:251:3: error: 'scoped_lock' may not intend to support class template argument deduction [-Werror,-Wctad-maybe-unsupported]
  std::scoped_lock lock(m_descriptor_mutex, m_stream_mutex);
  ^
/opt/rh/gcc-toolset-12/root/usr/lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/mutex:692:11: note: add a deduction guide to suppress this warning
    class scoped_lock
          ^
/data/home/jiefu/llvm-project/lldb/source/Host/common/File.cpp:316:3: error: 'scoped_lock' may not intend to support class template argument deduction [-Werror,-Wctad-maybe-unsupported]
  std::scoped_lock lock(m_descriptor_mutex, m_stream_mutex);
  ^
/opt/rh/gcc-toolset-12/root/usr/lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/mutex:692:11: note: add a deduction guide to suppress this warning
    class scoped_lock
          ^
2 errors generated.
2023-08-11 09:06:11 +08:00
Michael Buch
487ab39a50 [lldb][test] Remove tests relying on deprecated std::char_traits specializations
(motivated by test failures after D157058)

With D157058 the base template for `std::char_traits` was removed from
libc++. Quoting the release notes:

```
The base template for ``std::char_traits`` has been removed. If you are using
``std::char_traits`` with types other than ``char``, ``wchar_t``, ``char8_t``,
``char16_t``, ``char32_t`` or a custom character type for which you
specialized ``std::char_traits``, your code will no longer work.
```

This patch simply removes all such instantiations to make sure the
tests that run against the latest libc++ version pass.

One could try testing the existence of this base template from within
the test source files but this doesn't seem like something we want
support.

Differential Revision: https://reviews.llvm.org/D157636
2023-08-10 19:48:44 +01:00
Alex Langford
d21ec35dcf [lldb][NFCI] Remove use of ifdef __cpluplus where unneeded
Just about every file in the lldb project is built with C++ enabled.
Unless I've missed something, these macro guards don't really accomplish
very much.

Differential Revision: https://reviews.llvm.org/D157538
2023-08-10 11:24:40 -07:00
Jonas Devlieghere
9c135f1478
[lldb] Fix data race in NativeFile
TSan reports the following data race:

  Write of size 4 at 0x000109e0b160 by thread T2 (...):
    #0 lldb_private::NativeFile::Close() File.cpp:329
    #1 lldb_private::ConnectionFileDescriptor::Disconnect(...) ConnectionFileDescriptorPosix.cpp:232
    #2 lldb_private::Communication::Disconnect(...) Communication.cpp:61
    #3 lldb_private::process_gdb_remote::ProcessGDBRemote::DidExit() ProcessGDBRemote.cpp:1164
    #4 lldb_private::Process::SetExitStatus(...) Process.cpp:1097
    #5 lldb_private::process_gdb_remote::ProcessGDBRemote::MonitorDebugserverProcess(...) ProcessGDBRemote.cpp:3387

  Previous read of size 4 at 0x000109e0b160 by main thread (...):
    #0 lldb_private::NativeFile::IsValid() const File.h:393
    #1 lldb_private::ConnectionFileDescriptor::IsConnected() const ConnectionFileDescriptorPosix.cpp:121
    #2 lldb_private::Communication::IsConnected() const Communication.cpp:79
    #3 lldb_private::process_gdb_remote::GDBRemoteCommunication::WaitForPacketNoLock(...) GDBRemoteCommunication.cpp:256
    #4 lldb_private::process_gdb_remote::GDBRemoteCommunication::WaitForPacketNoLock(...) GDBRemoteCommunication.cpp:244
    #5 lldb_private::process_gdb_remote::GDBRemoteClientBase::SendPacketAndWaitForResponseNoLock(...) GDBRemoteClientBase.cpp:246

I originally tried fixing the problem at the ConnectionFileDescriptor
level, but that operates on an IOObject which can have different thread
safety guarantees depending on its implementation.

For this particular issue, the problem is specific to NativeFile.
NativeFile can hold a file descriptor and/or a file stream. Throughout
its implementation, it checks if the descriptor or stream is valid and
do some operation on it if it is. While that works in a single threaded
environment, nothing prevents another thread from modifying the
descriptor or stream between the IsValid check and when it's actually
being used.

This patch prevents such issues by returning a ValueGuard RAII object.
As long as the object is in scope, the value is guaranteed by a lock.

Differential revision: https://reviews.llvm.org/D157347
2023-08-10 11:13:47 -07:00
Martin Storsjö
68744ffbdd [lldb] Fix building with latest libc++
Since https://reviews.llvm.org/D157058 in libc++,
the base template for char_traits has been removed - it is only
provided for char, wchar_t, char8_t, char16_t and char32_t.
(Thus, to use basic_string with a type other than those, we'd need
to supply suitable traits ourselves.)

For this particular use, a vector works just as well as basic_string.

Differential Revision: https://reviews.llvm.org/D157589
2023-08-10 12:59:35 +03:00
Alex Langford
f2d32ddcec [lldb] Sink StreamFile into lldbHost
StreamFile subclasses Stream (from lldbUtility) and is backed by a File
(from lldbHost). It does not depend on anything from lldbCore or any of its
sibling libraries, so I think it makes sense for this to live in
lldbHost instead.

Differential Revision: https://reviews.llvm.org/D157460
2023-08-09 17:17:18 -07:00
Alex Langford
20c77a5789 [lldb] Sink StreamBuffer into lldbUtility
lldbUtility seems like a more suitable place for StreamBuffer.

Differential Revision: https://reviews.llvm.org/D157463
2023-08-09 17:10:13 -07:00
Alex Langford
44c876fd75 [lldb][NFCI] Remove MappedHash.h
This is no longer used as of 8e71d14972.

Differential Revision: https://reviews.llvm.org/D157455
2023-08-09 15:48:23 -07:00
Jonas Devlieghere
1a8d9a7657
[lldb] Fix data race in ThreadedCommunication
TSan reports the following race:

  Write of size 8 at 0x000107707ee8 by main thread:
    #0 lldb_private::ThreadedCommunication::StartReadThread(...) ThreadedCommunication.cpp:175
    #1 lldb_private::Process::SetSTDIOFileDescriptor(...) Process.cpp:4533
    #2 lldb_private::Platform::DebugProcess(...) Platform.cpp:1121
    #3 lldb_private::PlatformDarwin::DebugProcess(...) PlatformDarwin.cpp:711
    #4 lldb_private::Target::Launch(...) Target.cpp:3235
    #5 CommandObjectProcessLaunch::DoExecute(...) CommandObjectProcess.cpp:256
    #6 lldb_private::CommandObjectParsed::Execute(...) CommandObject.cpp:751
    #7 lldb_private::CommandInterpreter::HandleCommand(...) CommandInterpreter.cpp:2054

  Previous read of size 8 at 0x000107707ee8 by thread T5:
    #0 lldb_private::HostThread::IsJoinable(...) const HostThread.cpp:30
    #1 lldb_private::ThreadedCommunication::StopReadThread(...) ThreadedCommunication.cpp:192
    #2 lldb_private::Process::ShouldBroadcastEvent(...) Process.cpp:3420
    #3 lldb_private::Process::HandlePrivateEvent(...) Process.cpp:3728
    #4 lldb_private::Process::RunPrivateStateThread(...) Process.cpp:3914
    #5 std::__1::__function::__func<lldb_private::Process::StartPrivateStateThread(...) function.h:356
    #6 lldb_private::HostNativeThreadBase::ThreadCreateTrampoline(...) HostNativeThreadBase.cpp:62
    #7 lldb_private::HostThreadMacOSX::ThreadCreateTrampoline(...) HostThreadMacOSX.mm:18

The problem is the lack of synchronization between starting and stopping
the read thread. This patch fixes that by protecting those operations
with a mutex.

Differential revision: https://reviews.llvm.org/D157361
2023-08-09 15:15:42 -07:00
Alex Langford
335d0e3a6e [lldb][NFCI] Remove unused IOStreamMacros
These are unused AFAICT.

Differential Revision: https://reviews.llvm.org/D157450
2023-08-09 11:42:41 -07:00
Jason Molenda
0d8d31bbf5 When loading kernel binary, use DownloadObjectAndSymbolFile last
When lldb starts a kernel debug session, it has the UUID of the
kernel binary.  lldb will try three different methods to find a
binary and symbol file for this UUID.  Currently it calls out to
Symbols::DownloadObjectAndSymbolFile() first, which may be the
slowest method when a DBGShellCommand can find the UUID on a
network filesystem or downloaded from a server.

This patch tries the local searches first, then falls back to that
method.

Differential Revision: https://reviews.llvm.org/D157165
2023-08-08 17:30:57 -07:00
Jason Molenda
1290869ef2 Show error messages from DebugSymbols DBGShellCommand agent
The DebugSymbols DBGShellsCommand, which can find the symbols
for binaries, has a mechanism to return error messages when
it cannot find a symbol file.  Those errors were not printed
to the user for several corefile use case scenarios; this
patch fixes that.

Also add dyld/process logging for the LC_NOTE metadata parsers
in ObjectFileMachO, to help in seeing what lldb is basing its
searches on.

Differential Revision: https://reviews.llvm.org/D157160
2023-08-08 17:10:20 -07:00
Jason Molenda
c5f81100e4 When ProcessMachCore has metadata for a binary, don't scan
Mach-O corefiles have several possible types of metadata for the
binaries that were running when the corefile was written.
ProcessMachCore will try to find these binaries, and load them.
When we have a hint, but could not find the binary, this change
makes ProcessMachCore not fall back to scanning the corefile looking
for ANY binary that it could load.  We sometimes have multiple binaries
present in the memory in a corefile, but only the correct binary
should be loaded, the others are data.

Differential Revision: https://reviews.llvm.org/D157168
rdar://112602508
2023-08-08 15:49:53 -07:00
Jonas Devlieghere
d5cad05506
[lldb] Remve old CODE_OWNERS.txt 2023-08-08 08:55:00 -07:00
Jonas Devlieghere
013a8fc26e
[lldb] Update LLDB Code Ownership
Discourse discussion: https://discourse.llvm.org/t/rfc-update-lldb-code-ownership/72253

Differential revision: https://reviews.llvm.org/D156949
2023-08-08 08:54:03 -07:00
Jonas Devlieghere
caa5167769
Revert "[lldb] Fix data race in ConnectionFileDescriptor"
This reverts commit 0bdbe7bd7f because it
broke the bots.
2023-08-07 19:11:11 -07:00
Jonas Devlieghere
0bdbe7bd7f
[lldb] Fix data race in ConnectionFileDescriptor
TSan reports the following data race:

  Write of size 4 at 0x000109e0b160 by thread T2 (mutexes: write M0, write M1):
    #0 NativeFile::Close() File.cpp:329
    #1 ConnectionFileDescriptor::Disconnect(lldb_private::Status*) ConnectionFileDescriptorPosix.cpp:232
    #2 Communication::Disconnect(lldb_private::Status*) Communication.cpp:61
    #3 process_gdb_remote::ProcessGDBRemote::DidExit() ProcessGDBRemote.cpp:1164
    #4 Process::SetExitStatus(int, char const*) Process.cpp:1097
    #5 process_gdb_remote::ProcessGDBRemote::MonitorDebugserverProcess(...) ProcessGDBRemote.cpp:3387

  Previous read of size 4 at 0x000109e0b160 by main thread (mutexes: write M2):
    #0 NativeFile::IsValid() const File.h:393
    #1 ConnectionFileDescriptor::IsConnected() const ConnectionFileDescriptorPosix.cpp:121
    #2 Communication::IsConnected() const Communication.cpp:79
    #3 process_gdb_remote::GDBRemoteCommunication::WaitForPacketNoLock(...) GDBRemoteCommunication.cpp:256
    #4 process_gdb_remote::GDBRemoteCommunication::WaitForPacketNoLock(...l) GDBRemoteCommunication.cpp:244
    #5 process_gdb_remote::GDBRemoteClientBase::SendPacketAndWaitForResponseNoLock(llvm::StringRef, StringExtractorGDBRemote&) GDBRemoteClientBase.cpp:246

The problem is that in WaitForPacketNoLock's run loop, it checks that
the connection is still connected. This races with the
ConnectionFileDescriptor disconnecting. Most (but not all) access to the
IOObject in ConnectionFileDescriptorPosix is already gated by the mutex.
This patch just protects IsConnected in the same way.

Differential revision: https://reviews.llvm.org/D157347
2023-08-07 18:37:52 -07:00
Jonas Devlieghere
300c5aaa0a
[lldb] Remove unused Socket::PreDisconnect (NFC) 2023-08-07 15:50:06 -07:00
Jason Molenda
57cbd26a68 Flag for LoadBinaryWithUUIDAndAddress, to create memory image or not
DynamicLoader::LoadBinaryWithUUIDAndAddress can create a Module based
on the binary image in memory, which in some cases contains symbol
names and can be genuinely useful.  If we don't have a filename, it
creates a name in the form `memory-image-0x...` with the header address.

In practice, this is most useful with Darwin userland corefiles
where the binary was stored in the corefile in whole, and we can't
find a binary with the matching UUID.  Using the binary out of
the corefile memory in this case works well.

But in other cases, akin to firmware debugging, we merely end up
with an oddly named binary image and no symbols.

Add a flag to control whether we will create these memory images
and add them to the Target or not; only set it to true when working
with a userland Mach-O image with the "all image infos" LC_NOTE for
a userland corefile.

Differential Revision: https://reviews.llvm.org/D157167
2023-08-07 15:19:45 -07:00
Jonas Devlieghere
17226c976e
[lldb] Make TSan errors fatal when running the test suite
Set the halt_on_error runtime flag to make TSan errors fatal when
running the test suite. For the API tests the environment variables are
set conditionally on whether the TSan is enabled. The Shell and Unit
tests don't have that logic but setting the environment variable is
harmless. For consistency, I've also mirrored the ASAN option
(detect_stack_use_after_return=1) for the Shell tests.

Differential revision: https://reviews.llvm.org/D157152
2023-08-07 13:20:38 -07:00
Eymen Ünay
aa2784876a [lldb] Fix typo in comments and in test
Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D157214
2023-08-07 12:56:55 +00:00
David Spickett
91a0e832d4 [lldb] Make IR interpreter timeout test more loose
This has failed once in a while on our Windows on Arm bot:
https://lab.llvm.org/buildbot/#/builders/219/builds/4688

Traceback (most recent call last):
  File "C:\Users\tcwg\llvm-worker\lldb-aarch64-windows\...
    self.assertGreaterEqual(duration_sec, 1)
AssertionError: 0.9907491207122803 not greater than or equal to 1

We're not here to check that Python/the C++ lib/the OS implemented
timers correctly, so accept anything 0.95 or greater.
2023-08-07 09:42:26 +00:00
Jie Fu
a330759d6e [lldb] Fix -Wsign-compare in TestSectionSize.cpp (NFC)
In file included from /data/workspace/llvm-project/lldb/unittests/ObjectFile/PECOFF/TestSectionSize.cpp:10:
/data/workspace/llvm-project/third-party/unittest/googletest/include/gtest/gtest.h:1620:28: error: comparison of integers of different signs: 'c
onst unsigned long' and 'const int' [-Werror,-Wsign-compare]
GTEST_IMPL_CMP_HELPER_(NE, !=);
~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
2023-08-05 08:34:19 +08:00
Jie Fu
34fe58e0bc [lldb] Add a deduction guides for scoped_lock in OptionValue.cpp & ThreadList.cpp (NFC)
/data/llvm-project/lldb/source/Interpreter/OptionValue.cpp:28:3: error: 'scoped_lock' may not intend to support class template argument deduction [-Werror,-Wctad-maybe-unsupported]
  std::scoped_lock lock(m_mutex, other.m_mutex);
  ^
/opt/rh/gcc-toolset-12/root/usr/lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/mutex:692:11: note: add a deduction guide to suppress this warning
    class scoped_lock
          ^
1 error generated.

/data/llvm-project/lldb/source/Target/ThreadList.cpp:739:5: error: 'scoped_lock' may not intend to support class template argument deduction [-Werror,-Wctad-maybe-unsupported]
    std::scoped_lock guard(GetMutex(), rhs.GetMutex());
    ^
/opt/rh/gcc-toolset-12/root/usr/lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/mutex:692:11: note: add a deduction guide to suppress this warning
    class scoped_lock
          ^
1 error generated.
2023-08-05 07:56:38 +08:00
Augusto Noronha
d75dc9a8a8 [lldb] Fix ThreadList::Update not locking the rhs's mutex
ThreadList::Update is being caught by thread sanitizer. There's even a
comment on the function that both mutexes should be lock (even though
only the "this" mutex was actually being locked). Fix this by locking
both mutexes.

Differential Revision: https://reviews.llvm.org/D157153
2023-08-04 16:01:20 -07:00
Augusto Noronha
318f600722 [lldb] Protect OptionValue accesses from data races
Thread sanitizer is catching data races in OptionValue, protect accesses
to OptionValue with a mutex.

Differential Revision: https://reviews.llvm.org/D157041
2023-08-04 15:33:46 -07:00
Jonas Devlieghere
ecbe78c124
[lldb] Fix Python test formatting (NFC)
All Python files in the LLVM repository were reformatted with Black [1].
Files inside the LLDB subproject were reformatted in 2238dcc393. This
patch updates a handful of tests that were added or modified since then
and weren't formatted with Black.

[1] https://discourse.llvm.org/t/rfc-document-and-standardize-python-code-style/68257
2023-08-04 14:36:13 -07:00
Jonas Devlieghere
e0053bc04e
[lldb] Bump SWIG minimum version to 4
SWIG 4 was released in 2019 and has been the de-facto standard for a
while now. All bots are running SWIG 4.0 or later.

This was motivated by #64279 which discovered that 662548c broke the
LLDB build with SWIG 3 on Windows.

Differential revision: https://reviews.llvm.org/D156804
2023-08-04 14:34:01 -07:00
Jan Svoboda
3f092f37b7 [llvm] Extract common OptTable bits into macros
All command-line tools using `llvm::opt` create an enum of option IDs and a table of `OptTable::Info` object. Most of the tools use the same ID (`OPT_##ID`), kind (`Option::KIND##Class`), group ID (`OPT_##GROUP`) and alias ID (`OPT_##ALIAS`). This patch extracts that common code into canonical macros. This results in fewer changes when tweaking the `OPTION` macros emitted by the TableGen backend.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D157028
2023-08-04 13:57:13 -07:00
Hiroshi Yamauchi
e9040e875d [lldb][PECOFF] Exclude alignment padding when reading section data
There can be zero padding bytes at a section end for file alignment in
PECOFF. Exclude those padding bytes when reading the section data.

Differential Revision: https://reviews.llvm.org/D157059
2023-08-04 13:38:30 -07:00
Tom Yang
786bab4334 Display PC instead of <unknown> for stack trace in vscode
It isn't useful for users to see "<unknown>" as a stack trace when lldb fails to symbolicate a stack frame. I've replaced "<unknown>" with the value of the program counter instead.

Test Plan:

To test this, I opened a target that lldb fails to symbolicate in
VSCode, and observed in the CALL STACK section that instead of being
shown as "<unknown>", those stack frames are represented by their
program counters.

I added a new test case, `TestVSCode_stackTraceMissingFunctionName` that
exercises this feature.

I also ran `lldb-dotest -p TestVSCode` and saw that the tests passed.

Differential Revision: https://reviews.llvm.org/D156732
2023-08-04 11:07:27 -07:00
Jim Ingham
4185656625 Fix the NSIndexSet data formatter for changes in macOS Sonoma. 2023-08-04 09:55:59 -07:00
J. Ryan Stinnett
e383776ad0 [LLDB][CMake][NFC] Remove unused LLDB_LINKER_SUPPORTS_GROUPS variable
The `LLDB_LINKER_SUPPORTS_GROUPS` CMake variable was added back in 2019 as part
of https://reviews.llvm.org/D71306, but it appears to have been unused even
then. This removes the unused variable.

Differential Revision: https://reviews.llvm.org/D156997
2023-08-04 11:24:36 +01:00
David Spickett
27a0a743cf Revert "[lldb][lldb-vscode] Skip disassembler test on Arm"
This reverts commit 54458c525a.

The timeouts we were seeing have been fixed by 9a3f0cd717
and I think this was experiencing the same issue.
2023-08-04 09:26:40 +00:00
Alex Langford
08dc847d55 [lldb][NFCI] Add SBTraceCursor.h to swig headers file
Differential Revision: https://reviews.llvm.org/D156934
2023-08-03 16:41:17 -07:00
Tom Yang
9a3f0cd717 Fix crash in lldb-vscode when missing function name
Summary:
In cases where the PC has no function name, lldb-vscode crashes.

`lldb::SBFrame::GetDisplayFunctionName()` returns a `nullptr`, and when we
attempt to construct an `std::string`, it raises an exception.

Test plan:
This can be observed with creating a test file (credit to @clayborg for
the example):
```
int main() {
  typedef void (*FooCallback)();
  FooCallback foo_callback = (FooCallback)0;
  foo_callback(); // Crash at zero!
  return 0;
}
```
and attempting to debug the file through VSCode.

I add a test case in D156732 which should cover this.

Differential Revision: https://reviews.llvm.org/D156970
2023-08-03 12:56:37 -07:00
David Spickett
165f45a877 [lldb][lldb-vscode] Pretty print JSON to log files
This makes anlysing test failures much more easy.

For SendJSON this is simple, just use llvm::format instead.

For GetNextObject/ReadJSON it's a bit more tricky.
* Print the "Content-Length:" line in ReadJSON, but not the json.
* Back in GetNextObject, if the JSON doesn't parse, it'll be
  printed as a normal string along with an error message.
* If we didn't error before, we have a JSON value so we pretty print it.
* Finally, if it isn't an object we'll log an error for that,
  not including the JSON.

Before:
```
<--
Content-Length: 81

{"command":"disconnect","request_seq":5,"seq":0,"success":true,"type":"response"}
```

After:
```
<--
Content-Length: 81

{
  "command": "disconnect",
  "request_seq": 5,
  "seq": 0,
  "success": true,
  "type": "response"
}
```

There appear to be some responses that include strings that are themselves JSON,
and this won't pretty print those but I think it's still worth doing.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D156979
2023-08-03 15:09:12 +00:00
David Spickett
bdeb35bda4 [lldb][lldb-vscode] Fix nullptr dereference when JSON is not an object
Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D156977
2023-08-03 14:56:24 +00:00
David Spickett
6239227172 [lldb][AArch64] Save/restore TLS registers around expressions
Previously lldb was storing them but not restoring them. Meaning that this function:
```
void expr(uint64_t value) {
  __asm__ volatile("msr tpidr_el0, %0" ::"r"(value));
}
```
When run from lldb:
```
(lldb) expression expr()
```
Would leave tpidr as `value` instead of the original value of the register.

A check for this scenario has been added to TestAArch64LinuxTLSRegisters.py,
which covers tpidr and the SME excluisve tpidr2 register when it's present.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D156512
2023-08-03 12:33:49 +00:00
David Spickett
43ad521f2f [lldb][AArch64] Add reading of TLS tpidr register from core files
7e229217f4 did live processes, this does
core files. Pretty simple, there is an NT_ARM_TLS note that contains
at least tpidr, and on systems with the Scalable Matrix Extension (SME), tpidr2
as well.

tpidr2 will be handled in future patches for SME support.

This NT_ARM_TLS note has always been present but it seems convenient to
handle it as "optional" inside of LLDB. We'll probably want the flexibility
when supporting tpidr2.

Normally the C library would set tpidr but all our test sources build
without it. So I've updated the neon test program to write to tpidr
and regenerated the corefile.

I've removed the LLDB_PTRACE_NT_ARM_TLS that was unused, we get
what we need from llvm's defs instead.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D156118
2023-08-03 12:06:06 +00:00
Augusto Noronha
5f45a87bf0 [lldb] Print hint if object description is requested but not implemented
Lots of users use "po" as their default print command. If the type
doesn't implement the description function the output is often not what
the user wants. Print a hint telling the user that they might prefer
using "p" instead.

Differential Revision: https://reviews.llvm.org/D153489
2023-08-02 15:33:32 -07:00
Jonas Devlieghere
61af957aea
[lldb] Make IR interpretation interruptible
Check the interrupt flag while interpreting IR expressions and allow the
user to interrupt them.

Differential revision: https://reviews.llvm.org/D156822
2023-08-02 13:56:24 -07:00
Alex Langford
6c2e324916 [lldb] Re-add compile-time checks for SPI in HosInfoMacOSX
There were some checks removed previously in
bc196970b5.

However, all these SPIs are actually defined in macOS 12 and onward, not
macOSX 10.12 as the previous commit would suggest. As a result, if you
have access to these SPIs lldb will fail to compile correctly.

Instead of adding back the __builtin_availability checks, it seems
easier just to check the minimum deployment target with Availability
macros.

Differential Revision: https://reviews.llvm.org/D156838
2023-08-02 10:21:54 -07:00
David Spickett
54458c525a [lldb][lldb-vscode] Skip disassembler test on Arm
This is failing and/or causing time outs (hard to tell which ) on
our Arm Linux bot:
https://lab.llvm.org/buildbot/#/builders/17/builds/41108
2023-08-02 14:36:24 +00:00
Michael Buch
5ce7831b40 [lldb][test] Skip *-dbg-info-content API tests
These tests started failing on the public build-bots recently
with following error:
```
AssertionError: 'error: Couldn't lookup symbols:
  __ZNSt3__122__libcpp_verbose_abortEPKcz
' is not success
```

We've seen this previously when the SDKs we used to compile the
`std` module differ from the test program.
(see D146714, rdar://107052293, D139361, rdar://102427461)

Skip these tests on older MacOS versions for now.

This is possibly related to the recent `std` module changes in D144322.

rdar://113227172

Differential Revision: https://reviews.llvm.org/D156827
2023-08-01 23:43:24 +02:00
Wanyi Ye
ca76281917 [lldb] Fix test TestBSDArchives.py properly
The previous patch D156367 introduced a test debugging thin archive with one of the linked object file missing. It actually failed on green dragon build bots. I put up a speculative fix (4520cc066b) that only fixed the symptom of it.

The actual root cause was that the timestamps were set to 0 when creating the thin archive
Makefile command
```
llvm-ar -rcsDT libfoo-thin.a a.o b.o
```
Where the flag "[D] - use zero for timestamps and uids/gids (default)" according to the llvm-ar help
Use "[U] - use actual timestamps and uids/gids" fixed the timestamp

Now the test is actually getting error from missing object file linked to the thin archive instead of the mismatched timestamp.
This means removing one of the object file a.o should only result in failure breaking at `a()`; breaking at `b()` should work just fine.

Test Plan:

All 4 test cases passed
```
▶ ./bin/llvm-lit -vv ../llvm-project/lldb/test/API/functionalities/archives/TestBSDArchives.py
llvm-lit: /Users/wanyi/local/llvm-project/lldb/test/API/lit.cfg.py:173: warning: Could not set a default per-test timeout. Requires the Python psutil module but it could not be found. Try installing it via pip or via your operating system's package manager.
-- Testing: 1 tests, 1 workers --
PASS: lldb-api :: functionalities/archives/TestBSDArchives.py (1 of 1)

Testing Time: 8.07s
  Passed: 1

1 warning(s) in tests
```

Differential Revision: https://reviews.llvm.org/D156564
2023-08-01 16:38:58 -04:00
Jonas Devlieghere
59237bb52c
[lldb] Use a time-based timeout in IRInterpreter
At the moment the IRInterpreter will stop interpreting an expression
after a hardcoded 4096 instructions. After it reaches the limit it will
stop interpreting and leave the process in whatever state it was when
the timeout was reached.

This patch changes the instruction limit to a timeout and uses the
user-specified expression timeout value for this. The main motivation is
to allow users on targets where we can't use the JIT to run more
complicated expressions if they really want to (which they can do now by
just increasing the timeout).

The time-based approach also seems much more meaningful than the
arbitrary (and very low) instruction limit. 4096 instructions can be
interpreted in a few microseconds on some setups but might take much
longer if we have a slow connection to the target. I don't think any
user actually cares about the number of instructions that are executed
but only about the time they are willing to wait for a result.

Based off an original patch by Raphael Isemann.

Differential revision: https://reviews.llvm.org/D102762
2023-08-01 10:50:49 -07:00
Alex Langford
b8aba26c82 [lldb][NFCI] More forward declarations in SBDefines.h
I noticed these were missing.

Differential Revision: https://reviews.llvm.org/D156764
2023-08-01 09:57:07 -07:00
Alex Langford
6888de1187 [lldb] Fix building LLDB standlone without framework
In a809720102 I refactored some logic to
deal with the clang resource directory in standalone LLDB builds.
However, this logic escaped me because it only runs when you do not
build LLDB.framework.

Differential Revision: https://reviews.llvm.org/D156763
2023-08-01 09:50:36 -07:00
David Blaikie
4e429fd2a7 Few linter fixes
size() > 0 -> !empty
indentation
mismatched names on parameters in decls/defs
const on value return types
2023-07-31 18:52:57 +00:00
Alex Langford
db9087a696 [lldb] Clean up uses of UuidCompatibility.h
This commit does a few related things:
- Removes unused function `uuid_is_null`
- Removes unneeded includes of UuidCompatibility.h
- Renames UuidCompatibility to AppleUuidCompatibility and adds a comment
  to clarify intent of header.
- Moves AppleUuidCompatibility to the include directory

Differential Revision: https://reviews.llvm.org/D156562
2023-07-31 10:30:07 -07:00
Jonas Devlieghere
68918125c1
[lldb] Improve memory usage by freeing CTF types (NFC)
Improve memory usage by reducing the lifetime of CTF types. Once a CTF
type has been converted to a (complete) LLDB type, there's no need to
keep it in memory anymore. For most types, we can free them right after
creating the corresponding LLDB types. The only exception is record
types, which are only completed lazily.

Differential revision: https://reviews.llvm.org/D156606
2023-07-31 09:47:46 -07:00
John Harrison
ca71dc1b54 [lldb-vscode] Adding support for the "disassemble" request.
Instead of creating psuedo source files for each stack frame this change adopts the new DAP “disassemble” request, allowing clients to inspect assembly instructions of files with debug info in addition to files without debug info.

[[ https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Disassemble | spec ]]

See attached screenshot of the disassembly view. {F28473848}

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D156493
2023-07-31 12:44:23 -04:00
Jonas Devlieghere
b95c9b7af3
[lldb] Remove the last radar link in LLDB source code (NFC)
This was probably the only really useful radar in our source code. It's
a request to be able to tell if __LINKEDIT has been mapped or not. I've
left a comment in the radar that we should update the corresponding code
if and when such an ability becomes available.
2023-07-30 15:28:07 -07:00
Jonas Devlieghere
b699bf671a
[lldb] Replace another inconsequential radar link (NFC)
The existing comment already explains what the problem is. The radar
tracks caching negative lookups in xcrun. Having a backlink is handy,
but it's not necessary as the radar references the LLDB workaround.
Furthermore, we have other places in LLDB that work around xcrun not
caching negative that should potentially be reconsidered at that time.
2023-07-30 15:25:08 -07:00
Jonas Devlieghere
2fcade935a
[lldb] Replace radars link with documenting comment (NFC)
This replaces two radar links with improved comments explaining the
underlying issues.

 - The first issue is working around a compiler bug that was fixed in
   f454dfb6b5.
 - The second issue is an invariant that doesn't actually hold. The
   latter was marked as FIXME but there was nothing in the radar about a
   possible alternative solution.

Both radars were closed.
2023-07-30 15:17:16 -07:00
Jonas Devlieghere
949d4d1602
[lldb] Replace radar link with documenting comment (NFC)
This replaces the radar link with a comment explaining the underlying
problem, which is that when the (dynamic) type of an object changes, so
does their synthetic filter of choice, which requires us to regenerate
the filter.
2023-07-30 14:28:29 -07:00
Jonas Devlieghere
7963aa13ac
[lldb] Remove inconsequential radar link (NFC)
The comment after the radar link already explains the issue. There's no
additional information in the radar and has been marked as closed by the
corresponding code change. This commit removes the link and reflows the
comment.
2023-07-30 14:24:50 -07:00
Jonas Devlieghere
b96ea7e1f1
[lldb] Remove workaround in InstrumentationRuntimeASan
The code was commented out because it would trigger an assert in the
source manager. I can no longer reproduce the assert and none of the
ASan tests are failing with the code re-enabled.
2023-07-30 14:15:34 -07:00
Jonas Devlieghere
858a2865d3
[lldb] Remove outdated comment and radar link (NFC)
The comment and radar referenced PyThreadState_Get which is no longer
used there and instead has been replaced to a call to
PyThreadState_GetDict which has different semantics. Unlike
PyThreadState_Get, it can return NULL and it is okay to call this
function when no current thread state is available.
2023-07-30 13:51:49 -07:00
Jonas Devlieghere
b9bb946ca3
[lldb] Re-enable Clang Modules in source/Host directory on macOS
Re-enable clang modules for source/Host when targetting macOS 14 or
later, in which the underlying issue has been fixed.
2023-07-30 13:40:56 -07:00
Vlad Serebrennikov
fa2b038cad [lldb][NFC] Replace some counting loops with std::distance 2023-07-30 19:22:02 +03:00
Jonas Devlieghere
12f3d97fc6
[lldb] Support recursive record types in CTF
Support recursive record types in CTF, for example a struct that
contains a pointer to itself:

  struct S {
    struct S *n;
  };

We are now more lazy when creating LLDB types. When encountering a
record type (struct or union) we create a forward declaration and only
complete it when requested.

Differential revision: https://reviews.llvm.org/D156498
2023-07-29 22:32:24 -07:00
Jonas Devlieghere
b9867df64a
[lldb] Fix CTF parsing of large structs
Fix parsing of large structs. If the size of a struct exceeds a certain
threshold, the offset is encoded using two 32-bit integers instead of
one.

Differential revision: https://reviews.llvm.org/D156490
2023-07-29 19:37:08 -07:00
Jonas Devlieghere
9c70a3d917
[lldb] Support CTF forward declarations
Add support for parsing CTF forward declarations and converting them
into LLDB types.

Differential revision: https://reviews.llvm.org/D156483
2023-07-28 19:10:36 -07:00
John Harrison
1bf6f55911 [lldb-vscode] Adding support for displaying backtraces.
On Apple platforms when debugging with libBacktraceRecording.dylib backtraces are stored as part of the thread stack. This change includes support for displaying the back traces when they are present in the stack trace.

To use this on macOS a binary needs to be run with the following environment variables configured:

DYLD_LIBRARY_PATH=/usr/lib/system/introspection
DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib
{F28473587}

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D156465
2023-07-28 16:54:27 -04:00
Jonas Devlieghere
0a5e0d3fad
[lldb] Split CTF parsing and type creation (NFC)
Separate parsing CTF and creating LLDB types. This is a prerequisite to
parsing forward references and recursive types.

Differential revision: https://reviews.llvm.org/D156447
2023-07-28 09:41:47 -07:00
Wanyi Ye
4520cc066b [lldb] Fix TestBSDArchives failure
This is a speculative fix for the lldb API test suite
Build bot failures see: https://green.lab.llvm.org/green/view/LLDB/job/as-lldb-cmake/3262/
2023-07-27 17:30:16 -04:00
Wanyi Ye
4b9eed9c64 [BSDArchive] NULL check the child object file ptr before accessing its member
Recently we've observed lldb crashes caused by missing object file linked to a thin archive (.a) files. The crash is due to a missing NULL check in the code when looking for child object file referred by the thin archive. Malformed archive file should not crash LLDB. Instead, it should report the error and continue.

New error message will look like the following

```
error: libfoo.a(__objects__/foo/barAppDelegate.mm.o) failed to load objfile for path/to/libfoo.a.
Debugging will be degraded for this module.
```

Test Plan:

llvm-lit test
```
./bin/llvm-lit -sv ../llvm-project/lldb/test/API/functionalities/archives/TestBSDArchives.py
```

Test without code change will error out with LLDB crash
```
--
Command Output (stderr):
--
PASS: LLDB (~/llvm-upstream/Debug/bin/clang-arm64) :: test (TestBSDArchives.BSDArchivesTestCase)
PASS: LLDB (~/llvm-upstream/Debug/bin/clang-arm64) :: test_frame_var_errors_when_archive_missing (TestBSDArchives.BSDArchivesTestCase)
FAIL: LLDB (~/llvm-upstream/Debug/bin/clang-arm64) :: test_frame_var_errors_when_mtime_mistmatch_for_object_in_archive (TestBSDArchives.BSDArchivesTestCase)
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.      HandleCommand(command = "b a")
1.      HandleCommand(command = "breakpoint set --name 'a'")
Fatal Python error: Segmentation fault

Current thread 0x00000001f7b99e00 (most recent call first):
  File "~/llvm-upstream/Debug/bin/LLDB.framework/Resources/Python/lldb/__init__.py", line 3270 in HandleCommand
  File "~/llvm-upstream/llvm-project/lldb/packages/Python/lldbsuite/test/lldbtest.py", line 2070 in runCmd
  File "~/llvm-upstream/llvm-project/lldb/packages/Python/lldbsuite/test/lldbtest.py", line 2421 in expect
  File "~/llvm-upstream/llvm-project/lldb/test/API/functionalities/archives/TestBSDArchives.py", line 156 in test_frame_var_errors_when_thin_archive_malformed
...
```

Differential Revision: https://reviews.llvm.org/D156367
2023-07-27 13:21:31 -04:00
Jeffrey Tan
ca84935293 Fix lldb-vscode frame id integer overflow
This patch fixes a 32bit integer overflow in lldb-vscode.
The current implementation of frame_id does `(thread_index << 19 | frame_index)`. Since thread_index is a 32 bit integer this leaves only 32 - 19 == 13 bits available for the thread_index. As a result, lldb-vscode can only handle 2^13 == 8192 threads. Normally, this would be sufficient, but we have seen crazy process having +12000 threads, causing the frame_id algorithm above to integer overflow during casting.

The patch fixes the overflow by up casting to 64 bit integer first before bit shifiting.

Differential Revision: https://reviews.llvm.org/D156375
2023-07-26 16:12:41 -07:00
John Harrison
011cc6d8bf [lldb-vsocde] Cleaning up the usage of the Separate helper in Options.td.
Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D154990
2023-07-26 15:27:17 -04:00
Michael Buch
b0b2b6bab4 [lldb][PlatformDarwin] Parse SDK path for module compilation from debug-info
When we build the Clang module compilation command (e.g., when
a user requests import of a module via `expression @import Foundation`),
LLDB will try to determine which SDK directory to use as the `sysroot`.
However, it currently does so by simply enumerating the `SDKs` directory
and picking the last one that's appropriate for module compilation
(see `PlatformDarwin::GetSDKDirectoryForModules`). That means if we have
multiple platform SDKs installed (e.g., a public and internal one), we
may pick the wrong one by chance.

On Darwin platforms we emit the SDK path that a object
file was compiled against into DWARF (using `DW_AT_LLVM_sysroot`
and `DW_AT_APPLE_sdk`). For Swift debugging, we already parse the SDK
path from debug-info if we can.

This patch mimicks the Swift behaviour for non-Swift languages. I.e.,
if we can get the SDK path from debug-info, do so. Otherwise, fall back
to the old heuristic.

rdar://110407148

Differential Revision: https://reviews.llvm.org/D156020
2023-07-26 18:26:08 +01:00
Jacek Caban
48feef277a [lldb] Treat ARM64X images as ARM64.
With D149091, ARM64X binaries are no longer reported as ARM64. This broke
lldb tests as Windows 11 system DLLs are mostly ARM64X binaries and lldb
doesn't know how to handle them. Ideally lldb would understand a bit more
about ARM64X and handle them as AMD64 in x64 processes, but this is
enough to preserve previous behavior and fix tests.

Reviewed By: mstorsjo
Differential Revision: https://reviews.llvm.org/D156268
2023-07-26 14:45:48 +02:00
David Spickett
efa43d785e [lldb][AArch64] Add the tpidr2 TLS register that comes with SME
This changes the TLS regset to not only be dynamic in that it could
exist or not (though it always does) but also of a dynamic size.

If SME is present then the regset is 16 bytes and contains both tpidr
and tpidr2.

Testing is the same as tpidr. Write from assembly, read from lldb and
vice versa since we have no way to predict what its value should be
by just running a program.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D154930
2023-07-26 10:34:13 +01:00
David Spickett
03d8cd1d72 [lldb][AArch64] Add support for SME's SVE streaming mode registers
The Scalable Matrix Extension (SME) adds a new Scalable Vector mode
called "streaming SVE mode".

In this mode a lot of things change, but my understanding overall
is that this mode assumes you are not going to move data out of
the vector unit very often or read flags.

Based on "E1.3" of "Arm® Architecture Reference Manual Supplement,
The Scalable Matrix Extension (SME), for Armv9-A".

https://developer.arm.com/documentation/ddi0616/latest/

The important details for debug are that this adds another set
of SVE registers. This set is only active when we are in streaming
mode and is read from a new ptrace regset NT_ARM_SSVE.
We are able to read the header of either mode at all times but
only one will be active and contain register data.

For this reason, I have reused the existing SVE state. Streaming
mode is just another mode value attached to that state.

The streaming mode registers do not have different names in the
architecture, so I do not plan to allow users to read or write the
inactive mode's registers. "z0" will always mean "z0" of the active
mode.

Ptrace does allow reading inactive modes, but the data is of little
use. Writing to inactive modes will switch to that mode which would
not be what a debugger user would expect. So lldb will do neither.

Existing SVE tests have been updated to check streaming mode and
mode switches. However, we are limited in what we can check given
that state for the other mode is invalidated on mode switch.

The only way to know what mode you are in for testing purposes would
be to execute a streaming only, or non-streaming only instruction in
the opposite mode. However, the CPU feature smefa64 actually allows
all non-streaming mode instructions in streaming mode.

This is enabled by default in QEMU emulation and rather than mess
about trying to disable it I'm just going to use the pseduo streaming
control register added in a later patch to make these tests more
robust.

A new test has been added to check SIMD read/write from all the modes
as there is a subtlety there that needs noting, though lldb
doesn't have to make extra effort to do so.

If you are in streaming mode and write to v0, when you later exit
streaming mode that value may not be in the non-streaming state.
This can depend on how the core works but is a valid behaviour.

For example, say I am stopped here:
mov x0, v0.d[0]

And I want to update v0 in lldb. "register write v0 ..." should update
the v0 that this instruction is about to see. Not the potential other
copy of v0 in the non-streaming state (which is what I attempted in
earlier versions of this patch).

Not to mention, switching out of streaming mode here would be unexpected
and difficult to signal to the user.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D154926
2023-07-26 09:36:50 +01:00
Jonas Devlieghere
94e8fefe38
[lldb] Increase the default timeouts when running under ASan
Increase the default timeouts when running under ASan. We had something
similar before we adopted tablegen, but the larger timeouts got lost in
the transition, possibly because tablegen's preprocessor support is very
limited. This patch passes a new define (LLDB_SANITIZED) to
lldb-tablegen on which we can base the default value.

Differential revision: https://reviews.llvm.org/D156279
2023-07-25 17:45:19 -07:00
Alex Langford
a809720102 [lldb][NFCI] Change logic to find clang resource dir in standalone builds
As of 0beffb8542 there is a CMake
function to actually calculate the relative path to the clang resource
directory. Currently we have some bespoke logic that looks in a few
places, but with this new function we should be able to eliminate some
complexity here.

Also, I moved the functionality from LLDBConfig to LLDBStandalone since
it is only used in standalone builds.

Differential Revision: https://reviews.llvm.org/D156270
2023-07-25 15:52:33 -07:00
John Harrison
3ab73a3984 [lldb-vsocde] Add a 'continued' event for programmatic continue events.
When the process is contiuned using an lldb command expression the thread state in VS Code is never informed and will be out of sync with the current state of the process. The new event will fire whenever the process is continued and keeps the debugger in sync with the dap client.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D154989
2023-07-25 14:46:17 -04:00
Kazuki Sakamoto
8c61c9b02b [lldb][LocateModuleCallback] Call locate module callback in Platform too
This is an enhancement for the locate module callback.
https://discourse.llvm.org/t/rfc-python-callback-for-target-get-module/71580/6

On Android remote platform, module UUID is resolved by
Platform::GetRemoteSharedModule. Which means the current
Target::CallLocateModuleCallbackIfSet() call undesirably is not able to pass the
module UUID to the locate module callback.

This diff moves the CallLocateModuleCallbackIfSet() implementation from Target
to Platform to allows both Target and Platform can call it. One is from the
current Target call site, and second is from Platform after resolving the module
UUID.

As the result of this change, the locate module callback may be called twice
for a same module on remote platforms. And it should be ok.

- First, without UUID.
  - The locate module callback is allowed to return an error
    if the callback requires UUID.
- Second, with UUID, if the first callback call did not return a module.

Differential Revision: https://reviews.llvm.org/D156066
2023-07-25 10:57:50 -07:00
Alex Langford
5876eee1ff [lldb][NFCI] Add some missing SB class forward declarations
I noticed these were missing.

Differential Revision: https://reviews.llvm.org/D155653
2023-07-24 10:33:30 -07:00
David Spickett
cf2f433458 [lldb] Remove Windows XFAIL for TestDollarInVariable.py
Since 5d66f9fd8e this test has
been upassing on Linaro's Windows on Arm lldb bot:
https://lab.llvm.org/buildbot/#/builders/219/builds/4320

I can't explain exactly how that happened, but I do see a bunch
of QEnvironment packets going by in that test. It is very likely
that the order would have been different on Windows.

Indeed, when it was xfailed back in df9051e7cf
the reason was not known either.
2023-07-24 13:25:34 +00:00
Fangrui Song
e126fa27c0 [unittest] Fix HighlighterTest.cpp after D151683
:: is now parsed as tok::coloncolon even in C mode.
2023-07-22 18:30:02 -07:00
Fangrui Song
5d66f9fd8e [gdb-remote] Sort entries in QEnvironment*
Similar to ae316ac66f for
QEMU_(UN)SET_ENV.
The iteration order of StringMap is not guaranteed to be deterministic.
Sort the entries to give deterministic packets for the tests added by
D108018.
2023-07-22 16:45:32 -07:00
Nikolas Klauser
874217f99b [clang] Enable C++11-style attributes in all language modes
This also ignores and deprecates the `-fdouble-square-bracket-attributes` command line flag, which seems to not be used anywhere. At least a code search exclusively found mentions of it in documentation: https://sourcegraph.com/search?q=context:global+-fdouble-square-bracket-attributes+-file:clang/*+-file:test/Sema/*+-file:test/Parser/*+-file:test/AST/*+-file:test/Preprocessor/*+-file:test/Misc/*+archived:yes&patternType=standard&sm=0&groupBy=repo

RFC: https://discourse.llvm.org/t/rfc-enable-c-11-c2x-attributes-in-all-standard-modes-as-an-extension-and-remove-fdouble-square-bracket-attributes

This enables `[[]]` attributes in all C and C++ language modes without warning by default. `-Wc++-extensions` does warn. GCC has enabled this extension in all C modes since GCC 10.

Reviewed By: aaron.ballman, MaskRay

Spies: #clang-vendors, beanz, JDevlieghere, Michael137, MaskRay, sstefan1, jplehr, cfe-commits, lldb-commits, dmgreen, jdoerfert, wenlei, wlei

Differential Revision: https://reviews.llvm.org/D151683
2023-07-22 09:34:15 -07:00
Med Ismail Bennani
57bd882343 [lldb] Convert script native types to StructuredData counterpart
This patch adds the ability to pass native types from the script
interpreter to methods that use a {SB,}StructuredData argument.

To do so, this patch changes the `ScriptedObject` struture that holds
the pointer to the script object as well as the originating script
interpreter language. It also exposes that to the SB API via a new class
called `SBScriptObject`.

This structure allows the debugger to parse the script object and
convert it to a StructuredData object. If the type is not compatible
with the StructuredData types, we will store its pointer in a
`StructuredData::Generic` object.

This patch also adds some SWIG typemaps that checks the input argument to
ensure it's either an SBStructuredData object, in which case it just
passes it throught, or a python object that is NOT another SB type, to
provide some guardrails for the user.

rdar://111467140

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

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-07-21 18:47:46 -07:00
Felipe de Azevedo Piovezan
f09f0a6b10 [lldb] Consider OP_addrx in DWARFExpression::Update_DW_OP_addr
This rewrites DW_OP_addrx inside DWARFExpression as an DW_OP_addr so
that we can update addresses that are originally located in the
debug_addr section.

The full discussion behind this can be found in
https://discourse.llvm.org/t/dwarfexpression-and-dw-op-addrx/71627/12, but a
summary follows.

When SymbolFileDWARF::ParseVariableDIE creates DWARFExpressions for
variables whose location is an OP_addr, it knows how to remap
addresses appropriately in the DebugMap case. It then calls
DWARFExpression::Update_DW_OP_addr, which updates the value associated
with OP_addr.

However, when we have an OP_addrx, the update function does
nothing. This makes sense, as the DWARFExpression does not have a
mutable view of the debug_addr section. In non-DebugMap flows this is
not an issue, as the debug_addr contains the correct addresses of
variables. In DebugMap flows, this is problematic because the work
done by RelinkOSOAddress is lost. By updating the OP to OP_addr, we
can also update the address as required,

We also explored the alternative of relinking the debug_addr section
when we are initializing OSOs (InitOSO). However, this creates an
inconsistent story for users of
DWARFExpression::GetLocation_DW_OP_addr. This function returns an
address without telling callers whether that address came from an
OP_addr or an OP_addrx. If we preemptively relink OP_addrx results
without doing the same for OP_addr results, then callers can’t know
whether the address they got was an executable address or an object
file address. In other words, they can’t know whether they need to
call LinkOSOFileAddress on those results or not.

This patch addresses the majority of test failures when enabling DWARF
5 for MachO (over 200 test failures).

Differential Revision: https://reviews.llvm.org/D155198
2023-07-21 16:42:16 -07:00
Jie Fu
8a45a54d59 [lldb] Fix -Wreturn-type in RegisterInfos_x86_64_with_base_shared.cpp (NFC)
/data/llvm-project/lldb/source/Plugins/Process/Utility/RegisterInfos_x86_64_with_base_shared.cpp:319:1: error: non-void function does
not return a value in all control paths [-Werror,-Wreturn-type]
}
^
1 error generated.
2023-07-21 11:42:42 +08:00
Dave Lee
a6ff60ecdd [lldb] Delete unused LibcxxOptionalSummaryProvider (NFC)
No longer needed following refactoring in D115178.
2023-07-20 19:32:58 -07:00
Dave Lee
e19339f5f8 [lldb] Identify Swift-implemented ObjC classes
Classes implemented in Swift can be exposed to ObjC. For those classes, the ObjC
metadata is incomplete. Specifically, the encoded types of the ivars are incomplete. As
one might expect, the Swift metadata _is_ complete. In such cases, the Swift runtime
should be consulted when determining the dynamic type of a value.

Differential Revision: https://reviews.llvm.org/D152837
2023-07-20 19:32:12 -07:00
Jeffrey Tan
49b3c3355f [lldb][x86_64] Support fs_base/gs_base register in Linux
Summary:
[lldb][x86_64] This patch adds fs_base/gs_base support for Linux x86_64.

Originally, I plan to split the diff into two parts, one to refactoring lldb_xxx_x86_64 => x86_64::lldb_xxx across code base and the other one for adding fs_base/gs_base, but it turns out to be a non-trivial effort to split and very error prone so I decided to keep a single diff to get feedback.

GDB supports fs_base/gs_base registers while LLDB does not. Since both linux coredump note section and ptrace
supports them it is a missing feature.

For context, this is a required feature to support getting pthread pointer on linux from both live and dump debugging.
See thread below for details:
https://discourse.llvm.org/t/how-to-get-pthread-pointer-from-lldb/70542/2?u=jeffreytan81

Implementation wise, we have initially tried `#ifdef` approach to reuse the code but it is introducing very tricky bugs and proves
hard to maintain. Instead the diff completely separates the registers between x86_64 and x86_64_with_base so that non-linux related
implementations can use x86_64 registers while linux uses x86_64_with_base.
Here are the list of changes done in the patch:
* Registers in lldb-x86-register-enums.h are separated into two: x86_64 and x86_64_with_base
* fs_base/gs_base are added into x86_64_with_base
* All linux files are change to use x86_64::lldb_xxx => x86_64_with_base::lldb_xxx
* Support linux elf-core:
	* A new RegisterContextLinuxCore_x86_64 class is added for ThreadElfCore
	* RegisterContextLinuxCore_x86_64 overrides and uses its own register set supports fs_base/gs_base
	* RegisterInfos_x86_64_with_base/RegisterInfos_x86_64_with_base_shared ared added to provide g_contained_XXX/g_invalidate_XXX and RegInfo related code sharing.
* `RegisterContextPOSIX_x86 ::m_gpr_x86_64` seems to be unused so I removed it.
* `NativeRegisterContextDBReg_x86::GetDR()` is overridden in `NativeRegisterContextLinux_x86_64` to make watchpoint work.

Reviewers:clayborg,labath,jingham,jdoerfert,JDevlieghere,kusmour,GeorgeHuyubo

Subscribers:

Tasks:

Tags:

Differential Revision: https://reviews.llvm.org/D155256
2023-07-20 16:32:47 -07:00
Jason Molenda
259e3f2a4f Remove IncrementFalseAlarmsAndReviseHitCount, unused ivars
Reading through the Watchpoint class, I found this method
that wasn't being used properly, and a couple of ivars that
weren't used at all.  Cleanup.

Differential Revision: https://reviews.llvm.org/D155768
2023-07-20 15:16:02 -07:00
Jonas Devlieghere
bbffda645a
[lldb] Skip unsupported CTF types
This ensures we we don't crash when parsing a type that references an
unsupported type.
2023-07-20 10:21:33 -07:00
Yaxun (Sam) Liu
8ef04488d1 Reland "[CUDA][HIP] Use the same default language std as C++""
Reland after fixing regression in lldb.

Differential Revision: https://reviews.llvm.org/D155539
2023-07-20 12:02:33 -04:00
Felipe de Azevedo Piovezan
8b19d13fde [lldb] Make frame var --regex always search globals
Currently frame var --regex sometimes searches globals, sometimes it doesn't.
This happens because `StackFrame::GetVariableList` always returns the biggest
list it has, regardless of whether only globals were requested or not. In other
words, if a previous call to `GetVariableList` requested globals, all subsequent
calls will see them.

The implication here is that users of `StackFrame::GetVariableList` are expected
to filter the results of this function. This is what we do for a vanilla
`frame var` command. But it is not what we do when `--regex` is used. This
commit solves the issue by:

1. Making `--regex` imply `--globals`. This matches the behavior of `frame var
<some_name>`, which will also search the global scope.
2. Making the `--regex` search respect the command object options.

See the added test for an example of the oddities this patch addresses. Without
the patch, the test fails. However it could be made to pass by calling a plain
`frame var` before calling `frame var --regex A::`.

Differential Revision: https://reviews.llvm.org/D155334
2023-07-19 17:11:21 -04:00
John Harrison
3d1f89c2e3 [lldb-vscode] Creating a new flag for adjusting the behavior of evaluation repl expressions to allow users to more easily invoke lldb commands.
This adds a new flag and lldb runtime command to allow users to manage the behavior of the lldb-vscode evaluate repl request.

When evaluating a repl context this now has runtime managed flag for control how the repl behaviors with the follow values:

* `variable` - the existing behavior, with this mode requests are evaluted in the current frame context as variable expressions. To trigger a lldb command prefix an expression with ` and it will be evaluted as an lldb command.
* `command` - all expressions are evaluated as lldb commands.
* `auto` - An alternative mode that will attempt to determine if the expression is an lldb command or a variable expression. Based off the intepreted results the expression will be evaluted either as a command or an expression.

Additionally, I enabled completions and ensured they work with the new repl expression behavior to provide auto-completes.

This commit includes updates to the tests to verify the new behavior after the previous failures from submitting https://reviews.llvm.org/D154030.

Differential Revision: https://reviews.llvm.org/D155248
2023-07-19 21:04:12 +00:00
Felipe de Azevedo Piovezan
00c6049677 [lldb][NFC] Refactor test to enable subsequent reuse
On a subsequent commit, I intend to update the expression and call the evaluate
function more times. This refactors enables reusing some of the existing code
for that.

Differential Revision: https://reviews.llvm.org/D155197
2023-07-19 09:15:48 -04:00
Felipe de Azevedo Piovezan
8bc97a3ee4 [lldb][NFC] Factor out CommandObject code filtering results based on scope
We will need this code in a subsequent commit.

Differential Revision: https://reviews.llvm.org/D155332
2023-07-19 09:14:02 -04:00
David Spickett
865b1190e6 [lldb] XFAIL command-disassemble-mixed.c on Windows
Either clang-cl has different assembly output or we're not mapping
source to assembly properly on Windows. We (Linaro) will find out which.

https://lab.llvm.org/buildbot/#/builders/219/builds/4195
2023-07-19 09:04:56 +00:00
Pavel Labath
b71ac7eea4 [lldb/test] Fix command-disassemble-mixed.c
Add it to lit.local.cfg so that it's actually run, and change it to
(properly) use the %clang_host substitution.
2023-07-18 10:17:09 +02:00
Alex Langford
1b29a848ff [lldb][NFCI] Avoid construction of temporary std::strings in RegisterValue
Differential Revision: https://reviews.llvm.org/D155030
2023-07-17 12:53:34 -07:00
Jim Ingham
b9541b6707 Fix the root directory completion test.
It was implicitly assumning that "/" would have no files in it, only
directories.  That's not true, for instance on macOS if you've navigated
to the root directory in the Finder...

Since we're assuming everything we check against is a directory, then we
need to filter the completion for that coming in.
2023-07-17 10:52:29 -07:00
David Spickett
3ebd6f65cb [lldb][AArch64] Add test predicate for systems with SME enabled
"sme" is just one of many cpuinfo features for SME but it's the
only one we need for testing.

The rest are related to the use of certain instructions and
don't change the register state available.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D154823
2023-07-17 09:27:12 +01:00
David Spickett
fdf36c3d4b [lldb][AArch64] Fix flakiness in TestSVEThreadedDynamic
This test runs to a breakpoint on thread 0. Thread 0 then starts
thread 2 and 3, which both have breakpoints in them.

In https://lab.llvm.org/buildbot/#/builders/96/builds/41674
I think that we managed to do the first check on thread 2 before
thread 3 had started. Therefore "thread continue 3" failed.

So wait for all three to startup before we check their status.

I considered putting a timeout on the while like the wait_for... methods,
but the test itself already has a global timeout. Plus, I'd rather
not be tuning a timeout per piece of hardware this runs on.

99% of the time we will already have 3 threads when the check is done.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D154705
2023-07-17 08:11:15 +00:00
Kazuki Sakamoto
39299f0d36 [lldb][LocateModuleCallback] Fix LocateModuleCallbackTest
ModuleList unexpectedly caches module beyond test.
Tear it down.

- https://green.lab.llvm.org/green/view/LLDB/job/as-lldb-cmake/2260/testReport/junit/lldb-unit/Target___TargetTests_LocateModuleCallbackTest/GetOrCreateModuleWithCachedModule/
- https://green.lab.llvm.org/green/view/LLDB/job/as-lldb-cmake/2260/testReport/junit/lldb-unit/Target___TargetTests_LocateModuleCallbackTest/GetOrCreateModuleWithCachedModuleAndSymbol/

Differential Revision: https://reviews.llvm.org/D155333
2023-07-15 11:53:06 -07:00
Alex Langford
7ee633a24b [lldb][NFCI] Remove unneeded temporary std::string allocations in SBAPI
This uses some friend class trickery to avoid some unneeded temporary
std::string allocations.

Differential Revision: https://reviews.llvm.org/D155035
2023-07-14 10:46:42 -07:00
Shubham Sandeep Rastogi
ce225982af Disable GetOrCreateModuleWithCachedModule and GetOrCreateModuleWithCachedModuleAndSymbol tests on arm64, because of test failures 2023-07-14 13:41:27 -04:00
Kazuki Sakamoto
43b9d62018 [lldb][Windows] Fix TestLocateModuleCallback
D153735 added the tests but it is failing due to POSIX path vs Windows path.
https://lab.llvm.org/buildbot/#/builders/219/builds/4084

Fix it.
- MODULE_PLATFORM_PATH is POSIX path.
- Normalize self.input_dir, FileSpec and SymbolFileSpec fullpath.

Differential Revision: https://reviews.llvm.org/D155124
2023-07-14 10:36:57 -07:00
Shubham Sandeep Rastogi
a76b3bec6c Revert "Revert "[lldb][LocateModuleCallback] Fix LocateModuleCallbackTest""
This reverts commit 668a3efd42.

Reverting because of build errors:

In file included from /Users/buildslave/jenkins/workspace/as-lldb-cmake/llvm-project/lldb/source/API/SBPlatform.cpp:19:
/Users/buildslave/jenkins/workspace/as-lldb-cmake/llvm-project/lldb/include/lldb/Target/Target.h:1035:18: warning: parameter 'merged' not found in the function declaration [-Wdocumentation]
2023-07-14 11:19:16 -04:00
Shubham Sandeep Rastogi
55147ceb62 Revert "Revert "[lldb][LocateModuleCallback] Call locate module callback""
This reverts commit df054499c3.

Reverting because of build errors

In file included from /Users/buildslave/jenkins/workspace/as-lldb-cmake/llvm-project/lldb/source/API/SBPlatform.cpp:19:
/Users/buildslave/jenkins/workspace/as-lldb-cmake/llvm-project/lldb/include/lldb/Target/Target.h:1035:18: warning: parameter 'merged' not found in the function declaration [-Wdocumentation]
2023-07-14 11:19:16 -04:00
Shubham Sandeep Rastogi
df054499c3 Revert "[lldb][LocateModuleCallback] Call locate module callback"
This reverts commit 7f1028e9df.

This is because test failures

lldb-unit.Target/_/TargetTests/LocateModuleCallbackTest.GetOrCreateModuleWithCachedModule
lldb-unit.Target/_/TargetTests/LocateModuleCallbackTest.GetOrCreateModuleWithCachedModuleAndBreakpadSymbol
2023-07-14 11:05:01 -04:00
Shubham Sandeep Rastogi
668a3efd42 Revert "[lldb][LocateModuleCallback] Fix LocateModuleCallbackTest"
This reverts commit fb087c17c8.

This is because of test failures:

lldb-unit.Target/_/TargetTests/LocateModuleCallbackTest.GetOrCreateModuleWithCachedModule
lldb-unit.Target/_/TargetTests/LocateModuleCallbackTest.GetOrCreateModuleWithCachedModuleAndBreakpadSymbol
2023-07-14 11:05:01 -04:00
Sterling Augustine
28c33805d4 Remove unnecessary std::moves [NFC]
These trigger the following error:

error: moving a temporary object prevents copy elision [-Werror,-Wpessimizing-move]
2023-07-13 19:24:01 -07:00
Jonas Devlieghere
b716d4e585
[lldb] Move decorators to test method
Make sure TestCTF only run on Darwin when ctfconvert and llvm-objdump
are available.
2023-07-13 15:43:59 -07:00
Jonas Devlieghere
0e285a13eb
[lldb] Support compressed CTF
Add support for compressed CTF data. The flags in the header can
indicate whether the CTF body is compressed with zlib deflate. This
patch supports inflating the data before parsing.

Differential revision: https://reviews.llvm.org/D155221
2023-07-13 15:10:25 -07:00
Elliot Goodrich
3ff3af3086 [lldb] Add missing StringExtras.h includes
In preparation for removing the #include "llvm/ADT/StringExtras.h"
from the header to source file of llvm/Support/Error.h, first add in
all the missing includes that were previously included transitively
through this header.

This is fixing all files missed in b0abd4893f, 39d8e6e22c,
a11efd4926, 5551657b31, and 90bfe2df25.

Differential Revision: https://reviews.llvm.org/D155178
2023-07-13 21:06:25 +01:00
Jonas Devlieghere
ee44310a48
[lldb] Support Compact C Type Format (CTF)
Add support for the Compact C Type Format (CTF) in LLDB. The format
describes the layout and sizes of C types. It is most commonly consumed
by dtrace.

We generate CTF for the XNU kernel and want to be able to use this in
LLDB to debug kernels for which we don't have dSYMs (anymore). CTF is a
much more limited debug format than DWARF which allows is to be an order
of magnitude smaller: a 1GB dSYM can be converted to a handful of
megabytes of CTF. For XNU, the goal is not to replace DWARF, but rather
to have CTF serve as a "better than nothing" debug info format when
DWARF is not available.

It's worth noting that the LLVM toolchain does not support emitting CTF.
XNU uses ctfconvert to generate CTF from DWARF which is used for
testing.

Differential revision: https://reviews.llvm.org/D154862
2023-07-13 11:30:52 -07:00
Jonas Devlieghere
e5aa4cff43
[lldb] Support Compact C Type Format (CTF) section
Teach LLDB about the ctf (Compact C Type Format) section.

Differential revision: https://reviews.llvm.org/D154668
2023-07-13 11:30:35 -07:00
Alex Langford
c25e48c5d7 [lldb] Move CommandOverrideCallbackWithResult to lldb_private namespace
This has an `lldb_private` type in its parameter, it should be in
`lldb-private-types.h`

Differential Revision: https://reviews.llvm.org/D155129
2023-07-13 11:21:35 -07:00
Alex Langford
1d7a3dcff7 [lldb] Forward declare SBPlatform and SBTypeMember in SBDefines
Differential Revision: https://reviews.llvm.org/D155137
2023-07-13 10:51:48 -07:00
Felipe de Azevedo Piovezan
85c2e420c8 [lldb][NFC] Factor out code linking OSO addr of uninitialized GVs
This code was introduced in 2fc93eabf7.
In order to improve readability of ParseVariableDIE, we move this code into a
helper function. The issue this code attempted to address was fixed between
Clangs 9 and 11; as such, if we ever want to delete this code, it is a lot
easier to do so after the refactor.

Differential Revision: https://reviews.llvm.org/D155100
2023-07-13 08:27:29 -04:00
Elliot Goodrich
90bfe2df25 [lldb] Add missing StringExtras.h includes
In preparation for removing the #include "llvm/ADT/StringExtras.h"
from the header to source file of llvm/Support/Error.h, first add in
all the missing includes that were previously included transitively
through this header.

This is fixing all files missed in b0abd4893f, 39d8e6e22c,
a11efd4926, and 5551657b31.

Differential Revision: https://reviews.llvm.org/D155018
2023-07-13 08:39:59 +01:00
Kazuki Sakamoto
fb087c17c8 [lldb][LocateModuleCallback] Fix LocateModuleCallbackTest
D153734 forgot to call `Platform::SetHostPlatform` before
`Debugger::CreateInstance`. Copy similar code.
5007c78ce0/lldb/unittests/Expression/DWARFExpressionTest.cpp (L371-L374)

Differential Revision: https://reviews.llvm.org/D155135
2023-07-12 16:49:45 -07:00
Jason Molenda
71548de4d8 Improve error msg in DNBProcessAttach if we can't stop inferior
When we attach to a process, we task_for_pid(), ptrace(), and then
we try to halt execution of the process and time out after thirty
seconds if we cannot interrupt it.  At this point, we must assume
we have no control of the inferior process and the attach has failed.
The error message we return currently is "operation timed out"; this
change improves on that error message to make it more clear what is
going on.  Thanks to Jim for pointing this out.

rdar://101152233
2023-07-12 16:03:57 -07:00
Jason Molenda
bb136f5b39 Improve error messaging when debugserver fails to complete attaching
When debugserver is attaching to a process, it first task_for_pid()'s
and then ptrace(PT_ATTACHEXC)'s.  When that ptrace() fails to complete,
we are in a semi-attached state that we need to give up from, and
our error reporting isn't ideal -- we can even claim that the process
is already being debugged (by ourselves).

Differential Revision: https://reviews.llvm.org/D155037
rdar://101152233
2023-07-12 15:01:39 -07:00
Kazuki Sakamoto
f03dbdb70a [lldb][LocateModuleCallback] Implement API, Python interface
RFC https://discourse.llvm.org/t/rfc-python-callback-for-target-get-module/71580

Use SWIG for the locate module callback the same as other Python callbacks.
TestLocateModuleCallback.py verifies the functionalities.

Differential Revision: https://reviews.llvm.org/D153735
2023-07-12 11:33:51 -07:00
Kazuki Sakamoto
7f1028e9df [lldb][LocateModuleCallback] Call locate module callback
RFC https://discourse.llvm.org/t/rfc-python-callback-for-target-get-module/71580

Updated Target::GetOrCreateModule to call locate module callback if set.

- include/lldb/Target/Platform.h, source/Target/Platform.cpp
  - Implemented SetLocateModuleCallback and GetLocateModuleCallback*

- include/lldb/Target/Target.h, source/Target/Target.cpp
  - Implemented CallLocateModuleCallbackIfSet.

- unittests/Target/LocateModuleCallbackTest.cpp
  - Added comprehensive GetOrCreateModule tests.

Differential Revision: https://reviews.llvm.org/D153734
2023-07-12 11:19:51 -07:00
Kazuki Sakamoto
c4fa6fafc4 [lldb][LocateModuleCallback] Update SBFileSpec/SBModuleSpec
RFC https://discourse.llvm.org/t/rfc-python-callback-for-target-get-module/71580

SBFileSpec and SBModuleSpec will be used for locate module callback as Python
function arguments. This diff allows these things.
- Can be instantiated from SBPlatform.
- Can be passed to/from Python.
- Can be accessed for object offset and size.

Differential Revision: https://reviews.llvm.org/D153733
2023-07-12 11:11:18 -07:00
Ted Woodward
ded1bad64a Fix mixed disassembly showing source lines for "line 0"
"line 0" in a DWARF linetable means something that doesn't have associated
source. The code for mixed disassembly has a comment indicating that
"line 0" should be skipped, but the wrong value was returned. Fix the return
value and add a test to check that we don't incorrectly show source lines
from the beginning of the file.

Reviewed By: jasonmolenda

Differential Revision: https://reviews.llvm.org/D112931
2023-07-12 11:39:11 -05:00
Shubham Sandeep Rastogi
78af051ff0 Revert "[lldb-vscode] Creating a new flag for adjusting the behavior of evaluation repl expressions to allow users to more easily invoke lldb commands."
This reverts commit 16317f1ced.

Reverting because of test failures:

******************** TEST 'lldb-api :: tools/lldb-vscode/console/TestVSCode_console.py' FAILED ********************
Script:
--
/usr/local/Frameworks/Python.framework/Versions/3.10/bin/python3.10 /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/test/API/dotest.py -u CXXFLAGS -u CFLAGS --codesign-identity lldb_codesign --env LLVM_LIBS_DIR=/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/./lib --env LLVM_INCLUDE_DIR=/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/include --env LLVM_TOOLS_DIR=/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/./bin --libcxx-include-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/include/c++/v1 --libcxx-library-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lib --arch x86_64 --build-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lldb-test-build.noindex --lldb-module-cache-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lldb-test-build.noindex/module-cache-lldb/lldb-api --clang-module-cache-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lldb-test-build.noindex/module-cache-clang/lldb-api --executable /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/./bin/lldb --compiler /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/./bin/clang --dsymutil /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/./bin/dsymutil --llvm-tools-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/./bin --lldb-libs-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/./lib --build-dir /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lldb-test-build.noindex -t --env TERM=vt100 /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/test/API/tools/lldb-vscode/console -p TestVSCode_console.py

https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/57586/
2023-07-11 15:16:03 -07:00
John Harrison
16317f1ced [lldb-vscode] Creating a new flag for adjusting the behavior of evaluation repl expressions to allow users to more easily invoke lldb commands.
This adds a new flag and lldb runtime command to allow users to manage the behavior of the lldb-vscode evaluate repl request.

When evaluating a repl context this now has runtime managed flag for control how the repl behaviors with the follow values:

* `variable` - the existing behavior, with this mode requests are evaluted in the current frame context as variable expressions. To trigger a lldb command prefix an expression with ` and it will be evaluted as an lldb command.
* `command` - all expressions are evaluated as lldb commands.
* `auto` - An alternative mode that will attempt to determine if the expression is an lldb command or a variable expression. Based off the intepreted results the expression will be evaluted either as a command or an expression.

Additionally, I enabled completions and ensured they work with the new repl expression behavior to provide auto-completes.

RFC Discussion: https://discourse.llvm.org/t/rfc-lldb-vscode-evaluate-repl-behavior-and-improvements/71667

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D154030
2023-07-11 16:37:25 -04:00
Jim Ingham
8402ad2310 Add a generic Process method to dump plugin history.
I need to call this to figure out why the assert in
StopInfoMachException::CreateStopReasonWithMachException is triggering, but
it isn't appropriate to directly access the GDBRemoteCommunication there.  And
dumping whatever history the process plugin has collected during the run isn't
gdb-remote specific...

Differential Revision: https://reviews.llvm.org/D154992
2023-07-11 12:33:22 -07:00
Alex Langford
1d796b48e4 [lldb][NFCI] Methods to load scripting resources should take a Stream by reference
These methods all take a `Stream *` to get feedback about what's going
on. By default, it's a nullptr, but we always feed it with a valid
pointer. It would therefore make more sense to have this take a
reference.

Differential Revision: https://reviews.llvm.org/D154883
2023-07-11 10:36:11 -07:00
Alex Langford
e7c48ffde1 [lldb][NFCI] Avoid construction of temporary std::strings in Variable
A common thing to do is to call `str().c_str()` to get a null-terminated
string out of an existing StringRef. Most of the time this is to be able
to use a printf-style format string. However, llvm::formatv can handle
StringRefs without the need for the additional allocation. Using that
makes more sense.

Differential Revision: https://reviews.llvm.org/D154890
2023-07-11 10:22:02 -07:00
Caroline Tice
3885ceafa9 [LLDB] Fix buffer overflow problem in DWARFExpression::Evaluate
In two calls to ReadMemory in DWARFExpression.cpp, the buffer size
passed to ReadMemory is not checked and can be bigger than the actual
size of the buffer. This caused a buffer overflow bug, which we
found through Address Sanitizer. This patch fixes the problem by
checking the address size when it is first read out of the DWARF, and
setting an error and returning immediatley if the size is invalid.

This is the second attempt to fix this issue; I reverted the first one,
as it was not quite correct.

Differential Revision: https://reviews.llvm.org/D154907
2023-07-10 19:47:38 -07:00
Caroline Tice
5f6c55836f Revert "[LLDB] Fix buffer overflow problem in DWARFExpression::Evaluate."
This reverts commit ee476996be.

That commit was not the right way to fix the issue (it could result in
reading too many bytes).  A better fix is in the works.

Original review: https://reviews.llvm.org/D153840
2023-07-10 16:24:31 -07:00
Jonas Devlieghere
fb10b01cca
[lldb] Prevent crash when completing ambiguous subcommands
Fix a crash when trying to complete an ambiguous subcommand. Take `set s
tar` for example: for the subcommand `s` there's ambiguity between set
and show. Pressing TAB after this input currently crashes LLDB. The
problem is that we're trying to complete `tar` but give up at `s`
because of the ambiguity. LLDB doesn't expect the completed string to be
shorter than the current string and crashes when trying to eliminate the
common prefix.

rdar://111848598

Differential revision: https://reviews.llvm.org/D154643
2023-07-10 14:50:40 -07:00
Jim Ingham
c1885d2dfa "settings set -g target.load-script-from-symbol-file" shouldn't crash.
-g is specified by passing in nullptr ExecutionContext, but in some
load-script-from-symbol-file specific code, the ExecutionContext was
asked for its Target w/o checking whether the pointer was null.

Fix that and add a test.
2023-07-10 14:40:18 -07:00
Alex Langford
1e7101a3d9 [lldb][NFCI] TestEmulation should take a Stream ref
`Instruction::TestEmulation` takes a `Stream *` and checks it for validity.
However, this is unnecessary as we can always ensure that we never pass
`nullptr` for the `Stream` argument. The only use of
`Instruction::TestEmulation` currently is `SBInstruction::TestEmulation`
which gets the `Stream` from an `SBStream`, and `SBStream::ref` can
return a `Stream &` guaranteed.

Differential Revision: https://reviews.llvm.org/D154757
2023-07-10 11:17:25 -07:00
Felipe de Azevedo Piovezan
6890ad3f41 [lldb] Disable TestNamespaceLookup in DWARF 5 + dSYM setting
The ordering in which functions are presented to the expression evaluator in
this test setting triggers a known bug in LLDB.

Differential Revision: https://reviews.llvm.org/D154843
2023-07-10 10:10:15 -04:00
Elliot Goodrich
5551657b31 [lldb] Add missing StringExtras.h includes
In preparation for removing the `#include "llvm/ADT/StringExtras.h"`
from the header to source file of `llvm/Support/Error.h`, first add in
all the missing includes that were previously included transitively
through this header.

This is fixing all files missed in b0abd4893f, 39d8e6e22c, and
a11efd4926.

Differential Revision: https://reviews.llvm.org/D154775
2023-07-09 14:09:21 +01:00
Elliot Goodrich
a11efd4926 Add missing StringExtras.h includes
In preparation for removing the `#include "llvm/ADT/StringExtras.h"`
from the header to source file of `llvm/Support/Error.h`, first add in
all the missing includes that were previously included transitively
through this header.

This is fixing all files missed in b0abd4893f and
39d8e6e22c.

Differential Revision: https://reviews.llvm.org/D154763
2023-07-08 20:06:21 +01:00
Felipe de Azevedo Piovezan
cec33fc87c [lldb] Consider TAG_imported_declaration in DebugNamesIndex
In order to recognize namespace aliases as a namespace, the
DW_TAG_imported_declaration has to be taken into account. The name of these DIEs
is already included in all accelerator tables as of D143397.

Two of the three Index classes already handle this correctly:

1. ManualDWARFIndex (as of D143398)
2. AppleDWARFIndex works by default with D143397, since apple has a table
dedicated to namespaces.

This commit updates the third index class, DWARF 5's DebugNamesDWARFIndex.
As a result, it fixes the following test with DWARF 5:
commands/expression/namespace-alias/TestInlineNamespaceAlias.py

Differential Revision: https://reviews.llvm.org/D154730
2023-07-08 09:16:11 -04:00
Jim Ingham
01e3393b94 Split up the runCmd trace printing to print the command before running.
That way if the command crashes you still know what it was.

Differential Revision: https://reviews.llvm.org/D154752
2023-07-07 19:09:18 -07:00
Jason Molenda
ec360faeb3 Change the dyld notification function that lldb puts a breakpoint in
dyld has two notification functions - a native one, and one that
it rewrites its arguments for, for lldb.  We currently use the
latter, _dyld_debugger_notification.  The native notification
function, lldb_image_notifier (and on older systems, gdb_image_notifier)
we can find by name, or if libdyld shows no dyld loaded in the
process currently, we can get it from the dyld_all_image_infos
object in memory which we can find with a system call.  When we do
a "waitfor attach" to a process on a modern darwin system, there
is a transition early in launch from the launch dyld to the
shared-cache-dyld, and when we attach in the middle of that transition,
libdyld will say there is no dyld present.  But we can still find
the in-memory dyld_all_image_infos which has the address of the
shared cache notifier function that will be registered in the
process soon.

This change will result in a much more reliable waitfor-attach.

This is the third landing of this patch.  We have an Intel mac
CI bot that is running an older (c. 2019) macOS 10.15, I had to
reproduce that environment and found the name of the notifier
function had changed which was the cause of those failures.

Differential Revision: https://reviews.llvm.org/D139453
rdar://101194149
2023-07-07 14:48:32 -07:00
Alex Langford
564ff8ffe7 [lldb][NFCI] Remove use of Stream * from TypeSystem
We always assume these streams are valid, might as well take references
instead of raw pointers.

Differential Revision: https://reviews.llvm.org/D154549
2023-07-07 10:09:43 -07:00
Felipe de Azevedo Piovezan
dc04b18ad7 [lldb][NFC] Factor out code from SymbolFileDWARF::ParseVariableDIE
This function does a _lot_ of different things:

1. Parses a DIE,
2. Builds an ExpressionList
3. Figures out lifetime of variable
4. Remaps addresses for debug maps
5. Handles external variables
6. Figures out scope of variables

A lot of this functionality is coded in a complex nest of conditions, variables
that are declared and then initialized much later, variables that are updated in
multiple code paths. All of this makes the code really hard to follow.

This commit attempts to improve the state of things by factoring out (3), adding
documentation on how the expression list is built, and by reducing the scope of
variables.

Differential Revision: https://reviews.llvm.org/D154513
2023-07-07 08:44:59 -04:00
Fangrui Song
7319d7dbcf [lldb] Fix -Wunused-variable in -DLLVM_ENABLE_ASSERTIONS=off builds after D154542 2023-07-06 20:33:09 -07:00
Fangrui Song
61d8da327c [lldb] Replace countPopulation with popcount after D153686 2023-07-06 20:26:23 -07:00
Jason Molenda
9895c8979a Revert "Change the dyld notification function that lldb puts a breakpoint in"
This reverts commit c3192196ae.

Reverting my second attempt at https://reviews.llvm.org/D139453
changing which dyld notification method is being used.
The Intel macOS CI bot is still failing with this
rewrite at https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/
I'll need to set up an Intel macOS system running a matching
OS version to debug this directly I think.
2023-07-06 18:23:54 -07:00
Jason Molenda
c3192196ae Change the dyld notification function that lldb puts a breakpoint in
On Darwin systems, the dynamic linker dyld has an empty function
it calls when binaries are added/removed from the process.  lldb puts
a breakpoint on this dyld function to catch the notifications.  The
function arguments are used by lldb to tell what is happening.

The linker has a natural representation when the addresses of
binaries being added/removed are in the pointer size of the process.
There is then a second function where the addresses of the binaries
are in a uint64_t array, which the debugger has been using before -
dyld allocates memory for the array, copies the values in to it,
and calls it for lldb's benefit.

This changes to using the native notifier function, with pointer-sized
addresses.

This is the second time landing this change; this time correct the
size of the image_count argument, and add a fallback if the
notification function "lldb_image_notifier" can't be found.

Differential Revision: https://reviews.llvm.org/D139453
2023-07-06 18:00:09 -07:00
Jim Ingham
2b0c886542 Refine the reporting mechanism for interruption.
Also, make it possible for new Targets which haven't been added to
the TargetList yet to check for interruption, and add a few more
places in building modules where we can check for interruption.

Differential Revision: https://reviews.llvm.org/D154542
2023-07-06 16:19:19 -07:00
Med Ismail Bennani
1f5f4169c4 [lldb] Fix dead lock issue when loading modules in Scripted Process
This patch attempts to fix a dead lock when loading modules in a Scripted
Process.

This issue was triggered by loading the modules after the process did resume,
but before the process actually stop, causing the language runtime mutex to
be locked by a separate thread, responsible to unwind the stack (using
the runtime unwind plan), while the module loading thread was trying to
notify the runtimes of the newly loaded module.

To address that, this patch moves the module loading logic to be done before
sending the stop event, to prevent the dead lock situation described above.

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

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-07-06 14:33:52 -07:00
Felipe de Azevedo Piovezan
032de3ee0d [lldb][DebugNamesDWARF] Also use mangled name when matching regex
When LLDB queries the debug names index with a regex, we should use the
`Mangled` class wrapper, which attempts to match regex first against the mangled
name and then against the demangled name. It is important to do so, otherwise
queries like `frame var --regex A::` would never work. This is what is done for
the Apple index as well.

This fixes test/API/lang/cpp/class_static/main.cpp when compiled with DWARF 5.

Differential Revision: https://reviews.llvm.org/D154617
2023-07-06 17:15:06 -04:00
Felipe de Azevedo Piovezan
2c3bb6a590 [lldb][NFC] Remove unused parameter from DebugNames::ProcessEntry
Differential Revision: https://reviews.llvm.org/D154610
2023-07-06 17:14:14 -04:00
John Harrison
da59370b09 [lldb-vscode] Adding support for column break points.
Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D154029
2023-07-06 16:33:22 -04:00
Alex Langford
8f7e41d040 [lldb][NFCI] Minor cleanups to StructuredData::GetObjectForDotSeparatedPath
This accomplishes a few minor things:
- Removed unnecessary uses of `this->`
- Removed an unnecessary std::string allocation.
- Removed some nesting to improve readability using early returns where
  it makes sense.
- Replaced `strtoul` with `llvm::to_integer` which avoids another
  std::string allocation.
- Removed braces from single statement conditions, removed
  else-after-returns.

Differential Revision: https://reviews.llvm.org/D154534
2023-07-06 08:51:54 -07:00
Alex Langford
fc55b0b384 [lldb][NFCI] Remove use of ConstString from OptionValue
Summary: No need to create a ConstString, `GetName` already returns a StringRef.

Reviewers: JDevlieghere, mib, jasonmolenda

Subscribers:

Differential Revision: https://reviews.llvm.org/D154386
2023-07-06 08:49:07 -07:00
Felipe de Azevedo Piovezan
7cea22c0be [lldb][NFC] Remove code duplication in InitOSO
Two identical loops were iterating over different ranges, leading to code
duplication. We replace this by a loop over the concatenation of the ranges.

We also use early returns to avoid deeply nested code and explicitly check for a
condition mentioned in comments.

Differential Revision: https://reviews.llvm.org/D154505
2023-07-06 08:20:31 -04:00
David Spickett
fd8929904d [lldb] Fix crash when completing register names after program exit
Previously the following would crash:
(lldb) run
Process 2594053 launched: '/tmp/test.o' (aarch64)
Process 2594053 exited with status = 0 (0x00000000)
(lldb) register read <tab>

As the completer assumed that the execution context would always
have a register context. After a program has finished, it does not.

Split out the generic parts of the test from the x86 specific tests,
and added "register info" to both.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D154413
2023-07-06 08:35:04 +00:00
Jason Molenda
58370eef67 Revert "Change the dyld notification function that lldb puts a breakpoint in"
We're seeing a lot of test failures on the lldb incremental x86 CI bot
since I landed https://reviews.llvm.org/D139453 - revert it while I
investigate.

This reverts commit 624813a4f4.
2023-07-05 12:52:21 -07:00
Jonas Devlieghere
520681e56d
[lldb] Fix incorrect uses of formatv specifiers in LLDB_LOG
Fix incorrect uses of formatv specifiers in LLDB_LOG. Unlike Python,
arguments must be numbered. All the affected log statements take
llvm:Errors so use the LLDB_LOG_ERROR macro instead.

Differential revision: https://reviews.llvm.org/D154532
2023-07-05 11:27:52 -07:00
Jonas Devlieghere
e0e36e3725
[lldb] Fix incorrect uses of LLDB_LOG_ERROR
Fix incorrect uses of LLDB_LOG_ERROR. The macro doesn't automatically
inject the error in the log message: it merely passes the error as the
first argument to formatv and therefore must be referenced with {0}.

Thanks to Nicholas Allegra for collecting a list of places where the
macro was misused.

rdar://111581655

Differential revision: https://reviews.llvm.org/D154530
2023-07-05 11:27:52 -07:00
Alex Langford
fd5748cb5a [lldb][NFCI] Minor cleanup of default OptionValue::GetSubValue implementation
This does 2 things:
- Corrects a minor typo (`value subvalue` -> `valid subvalue`)
- Removes an unnecessary instance of `str().c_str()` (creating a
  temporary std::string from a StringRef just to get a valid
  null-terminated string).

Differential Revision: https://reviews.llvm.org/D154387
2023-07-05 09:00:59 -07:00
Alex Langford
20f99278db [lldb][NFCI] Deprecate SBValue::GetOpaqueType
This method, as far as I can ascertain, is non-trivial to actually use
to work with (if not impossible). It doesn't make sense to use from
Python and you do not have access to the accompanying TypeSystem, so it
doesn't really do anything useful.

A possible follow-up is to gut the implementation and have it return `nullptr`.

Differential Revision: https://reviews.llvm.org/D153918
2023-07-05 08:52:32 -07:00
Alex Langford
1c7c997037 [lldb] Deprecate SBHostOS threading functionality
For some context, Raphael tried to this before: https://reviews.llvm.org/D104231

These methods are not tested at all, and in some cases, are not even fully
implemented (e.g. SBHostOS::ThreadCreated). I'm not convinced it's
possible to use these correctly from Python, and I'm not aware of any
users of these methods. It's difficult to remove these methods
wholesale, but we can start with deprecating them.

A possible follow-up to this change (which may require an RFC to get
more buy in from the community) is to gut these functions entirely. That
is, remove the implementations and replace them either with nothing or
have them dump out a message to stderr saying not to use these.

Differential Revision: https://reviews.llvm.org/D153900
2023-07-05 08:46:48 -07:00
David Spickett
9b37bfa15e [lldb][AArch64] Handle different default vector length in SVE testing
This test previously ran on QEMU or A64FX both of which can/do have
512 bit SVE by default.

Graviton 3 has 256 bit SVE so the first part of the test failed.

To fix this, probe the supported vector lengths before starting
the test. The first check will use the default vector length and
the rest use either 256 or 128 bit.

Therefore this test will be skipped on a machine with only 128 bit SVE.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D154208
2023-07-04 11:17:54 +01:00
David Spickett
8e76093ae8 [lldb][AArch64] Fix tagged watch test on Graviton 3
During __do_global_dtors_aux glibc sets a flag that is right
next to the global variable. This is done using a store byte.

On QEMU the watchpoints are handled with a finer granularity
than real hardware, so this wasn't a problem. On Graviton 3
(and Mountain Jade, though this test won't run there) watchpoints
look at larger chunks of memory.

This means that the final continue actually stops in  __do_global_dtors_aux
instead of exiting.

We could fix this by padding the global to be away from the flag,
but that is fiddly and it is easier just to remove the watchpoint
before the final continue. We have already verified it worked by that
point.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D154201
2023-07-04 11:16:07 +01:00
David Spickett
518320fd98 [lldb][AArch64] Account for extra libc frames in PAC unwind test
Running this on Amazon Ubuntu the final backtrace is:
```
(lldb) thread backtrace
* thread #1, name = 'a.out', stop reason = breakpoint 1.1
  * frame #0: 0x0000aaaaaaaa07d0 a.out`func_c at main.c:10:3
    frame #1: 0x0000aaaaaaaa07c4 a.out`func_b at main.c:14:3
    frame #2: 0x0000aaaaaaaa07b4 a.out`func_a at main.c:18:3
    frame #3: 0x0000aaaaaaaa07a4 a.out`main(argc=<unavailable>, argv=<unavailable>) at main.c:22:3
    frame #4: 0x0000fffff7b373fc libc.so.6`___lldb_unnamed_symbol2962 + 108
    frame #5: 0x0000fffff7b374cc libc.so.6`__libc_start_main + 152
    frame #6: 0x0000aaaaaaaa06b0 a.out`_start + 48
```
This causes the test to fail because of the extra ___lldb_unnamed_symbol2962 frame
(an inlined function?).

To fix this, strictly check all the frames in main.c then for the rest
just check we find __libc_start_main and _start in that order regardless
of other frames in between.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D154204
2023-07-04 11:15:18 +01:00
Haojian Wu
2a579db32a [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.
Differential Revision: https://reviews.llvm.org/D154329
2023-07-04 08:52:45 +02:00
Dave Lee
6977c1caf4 [lldb] Remove old commented out code (NFC)
Move to `DumpAddress` in c4a8a76048.
2023-07-03 14:41:03 -07:00
Jonas Devlieghere
cec93c6589
[lldb] SymbolFileJSON: Update outdates Text -> JSON (NFC)
Originally the symbol file format was going to textual, before we
decided to use JSON. Updated the plugin name and the header guard.
2023-07-03 14:28:02 -07:00
Jonas Devlieghere
51944e78bb
[lldb] Add two-level caching in the source manager
We recently saw an uptick in internal reports complaining that LLDB is
slow when sources on network file systems are inaccessible. I looked at
the SourceManger and its cache and I think there’s some room for
improvement in terms of reducing file system accesses:

 1. We always resolve the path.
 2. We always check the timestamp.
 3. We always recheck the file system for negative cache hits.

D153726 fixes (1) but (2) and (3) are necessary because of the cache’s
current design. Source files are cached at the debugger level which
means that the source file cache can span multiple targets and
processes. It wouldn't be correct to not reload a modified or new file
from disk.

We can however significantly reduce the number of file system accesses
by using a two level cache design: one cache at the debugger level and
one at the process level:

 - The cache at the debugger level works the way it does today. There is
   no negative cache: if we can't find the file on disk, we'll try again
   next time the cache is queried. If a cached file's timestamp changes
   or if its path remapping changes, the cached file is evicted and we
   reload it from disk.
 - The cache at the process level is design to avoid accessing the file
   system. It doesn't check the file's modification time. It caches
   negative results, so if a file didn't exist, it doesn't try to reread
   it from disk. Checking if the path remapping changed is cheap
   (doesn't involve checking the file system) and is the only way for a
   file to get evicted from the process cache.

The result of this patch is that LLDB will not show you new content if a
file is modified or created while a process is running. I would argue
that this is what most people would expect, but it is a change from how
LLDB behaves today.

For an average stop, we query the source cache 4 times. With the current
implementation, that's 4 stats to get the modification time, If the file
doesn't exist on disk, that's an additional 4 stats. Before D153726, if
the path starts with a ~ there are another additional 4 calls to
realpath. When debugging sources on a slow (network) file system, this
quickly adds up.

In addition to the two level caching, this patch also adds a source
logging channel and synchronization to the source file cache. The
logging was helpful during development and hopefully will help us triage
issues in the future. The synchronization isn't a new requirement: as
the cache is shared across targets, there is no guarantees that it can't
be accessed concurrently. The patch also fixes a bug where we would only
set the source remapping ID if the un-remapped file didn't exist, which
led to the file getting evicted from the cache on every access.

rdar://110787562

Differential revision: https://reviews.llvm.org/D153834
2023-07-03 14:12:39 -07:00
Felipe de Azevedo Piovezan
f470ab734c [lldb][nfc] Remove redundant nullptr check
The make_shared function never returns a nullptr, as such the test for nullptr
is not needed. We also move the empty string check earlier in the if
("oso_object"), as this is cheaper than loading the object file.

Differential Revision: https://reviews.llvm.org/D154365
2023-07-03 17:12:06 -04:00
Med Ismail Bennani
9987646057 [lldb] Fix data race when interacting with python scripts
This patch should fix some data races when a python script (i.e. a
Scripted Process) has a nested call to another python script (i.e. a
OperatingSystem Plugin), which can cause concurrent writes to the python
lock count.

This patch also fixes a data race happening when resetting the operating
system unique pointer.

To address these issues, both accesses is guarded by a mutex.

rdar://109413039

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

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2023-07-03 11:49:11 -07:00
Alex Langford
b709149b76 [lldb][NFCI] Target::StopHook::GetDescription should take a Stream ref instead of pointer
We always assume that this is valid anyway, might as well take a
reference.

Differential Revision: https://reviews.llvm.org/D153917
2023-07-03 11:39:38 -07:00
Alex Langford
ebec53e2d7 [lldb] Introduce a macro to mark methods as unsupported with no replacement
We already have LLDB_DEPRECATED which is used to mark methods as
deprecated with a message and an alternative to use instead. This is
expresses an intent of "We recognize this functionality is useful but
there are some pitfalls with the interface we have exposed."

In other cases, there are no "alternative" methods to use and the code should be
refactored to avoid using a method entirely. For example,
`SBValue::Cast` should be avoided in favor of using the expression
evaluator to perform a cast. There isn't a mechanical solution, the
recommendation is to instead refactor your code.

This commit renames the existing `LLDB_DEPRECATED` to
`LLDB_DEPRECATED_FIXME`, and adds a `LLDB_DEPRECATED` macro to cover the
second scenario.

Differential Revision: https://reviews.llvm.org/D153928
2023-07-03 11:17:48 -07:00
Alex Langford
e3921b8bff [lldb][NFCI] Remove use of ConstString from ProcessElfCore
I'm not convinced that it makes sense for the paths to be ConstStrings. We're
going to be putting them into FileSpecs (which are backed by
ConstStrings, for now) but otherwise there's no need to store them as
ConstStrings upfront.

Differential Revision: https://reviews.llvm.org/D153827
2023-07-03 11:13:50 -07:00
Alex Langford
1b102886c0 [lldb][NFCI] Change return type of GetProcessPluginName
Instead of just returning a raw `const char *`, I think llvm::StringRef
would make more sense. Most of the time that we use the return value of
`GetProcessPluginName` we're passing it to `CreateProcess` which takes a
StringRef anyway.

Differential Revision: https://reviews.llvm.org/D153825
2023-07-03 10:03:49 -07:00
Alex Langford
a2ff2921e8 [lldb][NFCI] TypeSystemClang::CreateStructForIdentifier should take a StringRef
This doesn't really use fast comparison or string uniqueness. In fact,
all of the current callers pass an empty string for type_name. The only
reason I don't remove it is because it looks like it is used downstream
for swift.

Differential Revision: https://reviews.llvm.org/D153810
2023-07-03 09:35:24 -07:00
Alex Langford
673f91055a [lldb][NFCI] Remove unneeded use of ConstString in ASTResultSynthesizer
2/3 of the ConstStrings in this class were just to be able to log
something. Putting something in the StringPool just to log it doesn't
make a lot of sense, so let's remove them.

The remaining use is for `RegisterPersistentDecl` which is fine for now.

Differential Revision: https://reviews.llvm.org/D153905
2023-07-03 09:31:10 -07:00
Felipe de Azevedo Piovezan
f292ca1362 [lldb][NFC] Simplify GetLocation_DW_OP_addr function
A very old commit (9422dd64f8) changed the signature of this function in a
number of ways. This patch aims to improve it:

1. Reword the documentation, which still mentions old parameters that no longer
exist, and to elaborate upon the behavior of this function.
2. Remove the unnecessary parameter `op_addr_idx`. This parameter is odd in a
couple of ways: we never use it with a value that is non-zero, and the matching
`Update_DW_OP_addr` function doesn't use a similar parameter. We also document
that this new behavior. If we ever decide to handle multiple "DW_OP_addr", we
can introduce the complexity again.

Differential Revision: https://reviews.llvm.org/D154265
2023-07-03 08:36:57 -04:00
Felipe de Azevedo Piovezan
379b59d1b0 [lldb] Skip apple accelerator table test in DWARF 5 mode
D68678 added a test that ensures an Apple accelerator lookup is done
efficiently. Since these tables are not used for DWARF 5, we should decorate the
test appropriately.

Differential Revision: https://reviews.llvm.org/D154268
2023-07-03 08:35:55 -04:00