diff options
Diffstat (limited to 'lldb')
50 files changed, 534 insertions, 175 deletions
diff --git a/lldb/bindings/python/python-typemaps.swig b/lldb/bindings/python/python-typemaps.swig index 88b6cd9..715914f 100644 --- a/lldb/bindings/python/python-typemaps.swig +++ b/lldb/bindings/python/python-typemaps.swig @@ -233,6 +233,11 @@ AND call SWIG_fail at the same time, because it will result in a double free. } +// For lldb::SBFileSpec::GetPath +%typemap(in) (char *dst_path, size_t dst_len) = (char *dst_or_null, size_t dst_len); +%typemap(argout) (char *dst_path, size_t dst_len) = (char *dst_or_null, size_t dst_len); + + // typemap for an outgoing buffer // See also SBEvent::SBEvent(uint32_t event, const char *cstr, uint32_t cstr_len). // Ditto for SBProcess::PutSTDIN(const char *src, size_t src_len). diff --git a/lldb/cmake/modules/LLDBFramework.cmake b/lldb/cmake/modules/LLDBFramework.cmake index c6f00ed..23d9d49 100644 --- a/lldb/cmake/modules/LLDBFramework.cmake +++ b/lldb/cmake/modules/LLDBFramework.cmake @@ -68,8 +68,6 @@ if(NOT APPLE_EMBEDDED) ) endif() -find_program(unifdef_EXECUTABLE unifdef) - # Wrap output in a target, so lldb-framework can depend on it. add_custom_target(liblldb-resource-headers DEPENDS lldb-sbapi-dwarf-enums ${lldb_staged_headers}) set_target_properties(liblldb-resource-headers PROPERTIES FOLDER "LLDB/Resources") diff --git a/lldb/examples/python/lldbtk.py b/lldb/examples/python/lldbtk.py index f1685c0..72fe91e 100644 --- a/lldb/examples/python/lldbtk.py +++ b/lldb/examples/python/lldbtk.py @@ -4,12 +4,8 @@ import lldb import shlex import sys -try: - from tkinter import * - import tkinter.ttk as ttk -except ImportError: - from Tkinter import * - import ttk +from tkinter import * +import tkinter.ttk as ttk class ValueTreeItemDelegate(object): diff --git a/lldb/include/lldb/Core/Debugger.h b/lldb/include/lldb/Core/Debugger.h index 06136ed..ead2ed3 100644 --- a/lldb/include/lldb/Core/Debugger.h +++ b/lldb/include/lldb/Core/Debugger.h @@ -682,6 +682,7 @@ protected: lldb::LockableStreamFileSP GetErrorStreamSP() { return m_error_stream_sp; } /// @} + bool IsEscapeCodeCapableTTY(); bool StatuslineSupported(); void PushIOHandler(const lldb::IOHandlerSP &reader_sp, diff --git a/lldb/include/lldb/Utility/AnsiTerminal.h b/lldb/include/lldb/Utility/AnsiTerminal.h index 7db184a..41acac7 100644 --- a/lldb/include/lldb/Utility/AnsiTerminal.h +++ b/lldb/include/lldb/Utility/AnsiTerminal.h @@ -72,6 +72,17 @@ #define ANSI_ESC_START_LEN 2 +// OSC (Operating System Commands) +// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html +#define OSC_ESCAPE_START "\033" +#define OSC_ESCAPE_END "\x07" + +// https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC +#define OSC_PROGRESS_REMOVE OSC_ESCAPE_START "]9;4;0;0" OSC_ESCAPE_END +#define OSC_PROGRESS_SHOW OSC_ESCAPE_START "]9;4;1;%u" OSC_ESCAPE_END +#define OSC_PROGRESS_ERROR OSC_ESCAPE_START "]9;4;2;%u" OSC_ESCAPE_END +#define OSC_PROGRESS_INDETERMINATE OSC_ESCAPE_START "]9;4;3;%u" OSC_ESCAPE_END + #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" diff --git a/lldb/include/lldb/lldb-enumerations.h b/lldb/include/lldb/lldb-enumerations.h index fec9fde..1a7db8f 100644 --- a/lldb/include/lldb/lldb-enumerations.h +++ b/lldb/include/lldb/lldb-enumerations.h @@ -130,6 +130,8 @@ FLAGS_ENUM(LaunchFlags){ eLaunchFlagInheritTCCFromParent = (1u << 12), ///< Don't make the inferior responsible for its own TCC ///< permissions but instead inherit them from its parent. + eLaunchFlagMemoryTagging = + (1u << 13), ///< Launch process with memory tagging explicitly enabled. }; /// Thread Run Modes. diff --git a/lldb/packages/Python/lldbsuite/support/seven.py b/lldb/packages/Python/lldbsuite/support/seven.py index 1b96658..8e621ba 100644 --- a/lldb/packages/Python/lldbsuite/support/seven.py +++ b/lldb/packages/Python/lldbsuite/support/seven.py @@ -1,5 +1,4 @@ import binascii -import shlex import subprocess @@ -38,8 +37,3 @@ def unhexlify(hexstr): def hexlify(data): """Hex-encode string data. The result if always a string.""" return bitcast_to_string(binascii.hexlify(bitcast_to_bytes(data))) - - -# TODO: Replace this with `shlex.join` when minimum Python version is >= 3.8 -def join_for_shell(split_command): - return " ".join([shlex.quote(part) for part in split_command]) diff --git a/lldb/packages/Python/lldbsuite/test/gdbclientutils.py b/lldb/packages/Python/lldbsuite/test/gdbclientutils.py index 53e991a..1a2860a 100644 --- a/lldb/packages/Python/lldbsuite/test/gdbclientutils.py +++ b/lldb/packages/Python/lldbsuite/test/gdbclientutils.py @@ -1,3 +1,4 @@ +from abc import ABC, abstractmethod import ctypes import errno import io @@ -5,6 +6,7 @@ import threading import socket import traceback from lldbsuite.support import seven +from typing import Optional, List, Tuple def checksum(message): @@ -86,7 +88,7 @@ class MockGDBServerResponder: handles any packet not recognized in the common packet handling code. """ - registerCount = 40 + registerCount: int = 40 class RESPONSE_DISCONNECT: pass @@ -95,7 +97,7 @@ class MockGDBServerResponder: pass def __init__(self): - self.packetLog = [] + self.packetLog: List[str] = [] def respond(self, packet): """ @@ -241,7 +243,7 @@ class MockGDBServerResponder: def qHostInfo(self): return "ptrsize:8;endian:little;" - def qEcho(self): + def qEcho(self, num: int): return "E04" def qQueryGDBServer(self): @@ -262,10 +264,10 @@ class MockGDBServerResponder: def D(self, packet): return "OK" - def readRegisters(self): + def readRegisters(self) -> str: return "00000000" * self.registerCount - def readRegister(self, register): + def readRegister(self, register: int) -> str: return "00000000" def writeRegisters(self, registers_hex): @@ -305,7 +307,9 @@ class MockGDBServerResponder: # SIGINT is 2, return type is 2 digit hex string return "S02" - def qXferRead(self, obj, annex, offset, length): + def qXferRead( + self, obj: str, annex: str, offset: int, length: int + ) -> Tuple[Optional[str], bool]: return None, False def _qXferResponse(self, data, has_more): @@ -373,15 +377,17 @@ class MockGDBServerResponder: pass -class ServerChannel: +class ServerChannel(ABC): """ A wrapper class for TCP or pty-based server. """ - def get_connect_address(self): + @abstractmethod + def get_connect_address(self) -> str: """Get address for the client to connect to.""" - def get_connect_url(self): + @abstractmethod + def get_connect_url(self) -> str: """Get URL suitable for process connect command.""" def close_server(self): @@ -393,10 +399,12 @@ class ServerChannel: def close_connection(self): """Close all resources used by the accepted connection.""" - def recv(self): + @abstractmethod + def recv(self) -> bytes: """Receive a data packet from the connected client.""" - def sendall(self, data): + @abstractmethod + def sendall(self, data: bytes) -> None: """Send the data to the connected client.""" @@ -427,11 +435,11 @@ class ServerSocket(ServerChannel): self._connection.close() self._connection = None - def recv(self): + def recv(self) -> bytes: assert self._connection is not None return self._connection.recv(4096) - def sendall(self, data): + def sendall(self, data: bytes) -> None: assert self._connection is not None return self._connection.sendall(data) @@ -443,10 +451,10 @@ class TCPServerSocket(ServerSocket): )[0] super().__init__(family, type, proto, addr) - def get_connect_address(self): + def get_connect_address(self) -> str: return "[{}]:{}".format(*self._server_socket.getsockname()) - def get_connect_url(self): + def get_connect_url(self) -> str: return "connect://" + self.get_connect_address() @@ -454,10 +462,10 @@ class UnixServerSocket(ServerSocket): def __init__(self, addr): super().__init__(socket.AF_UNIX, socket.SOCK_STREAM, 0, addr) - def get_connect_address(self): + def get_connect_address(self) -> str: return self._server_socket.getsockname() - def get_connect_url(self): + def get_connect_url(self) -> str: return "unix-connect://" + self.get_connect_address() @@ -471,7 +479,7 @@ class PtyServerSocket(ServerChannel): self._primary = io.FileIO(primary, "r+b") self._secondary = io.FileIO(secondary, "r+b") - def get_connect_address(self): + def get_connect_address(self) -> str: libc = ctypes.CDLL(None) libc.ptsname.argtypes = (ctypes.c_int,) libc.ptsname.restype = ctypes.c_char_p @@ -484,7 +492,7 @@ class PtyServerSocket(ServerChannel): self._secondary.close() self._primary.close() - def recv(self): + def recv(self) -> bytes: try: return self._primary.read(4096) except OSError as e: @@ -493,8 +501,8 @@ class PtyServerSocket(ServerChannel): return b"" raise - def sendall(self, data): - return self._primary.write(data) + def sendall(self, data: bytes) -> None: + self._primary.write(data) class MockGDBServer: @@ -527,18 +535,21 @@ class MockGDBServer: self._thread.join() self._thread = None - def get_connect_address(self): + def get_connect_address(self) -> str: + assert self._socket is not None return self._socket.get_connect_address() - def get_connect_url(self): + def get_connect_url(self) -> str: + assert self._socket is not None return self._socket.get_connect_url() def run(self): + assert self._socket is not None # For testing purposes, we only need to worry about one client # connecting just one time. try: self._socket.accept() - except: + except Exception: traceback.print_exc() return self._shouldSendAck = True @@ -553,7 +564,7 @@ class MockGDBServer: self._receive(data) except self.TerminateConnectionException: pass - except Exception as e: + except Exception: print( "An exception happened when receiving the response from the gdb server. Closing the client..." ) @@ -586,7 +597,9 @@ class MockGDBServer: Once a complete packet is found at the front of self._receivedData, its data is removed form self._receivedData. """ + assert self._receivedData is not None data = self._receivedData + assert self._receivedDataOffset is not None i = self._receivedDataOffset data_len = len(data) if data_len == 0: @@ -639,10 +652,13 @@ class MockGDBServer: self._receivedDataOffset = 0 return packet - def _sendPacket(self, packet): - self._socket.sendall(seven.bitcast_to_bytes(frame_packet(packet))) + def _sendPacket(self, packet: str): + assert self._socket is not None + framed_packet = seven.bitcast_to_bytes(frame_packet(packet)) + self._socket.sendall(framed_packet) def _handlePacket(self, packet): + assert self._socket is not None if packet is self.PACKET_ACK: # Ignore ACKs from the client. For the future, we can consider # adding validation code to make sure the client only sends ACKs diff --git a/lldb/packages/Python/lldbsuite/test/lldbtest.py b/lldb/packages/Python/lldbsuite/test/lldbtest.py index 8074922..b92de94 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbtest.py +++ b/lldb/packages/Python/lldbsuite/test/lldbtest.py @@ -36,6 +36,7 @@ import json import os.path import re import shutil +import shlex import signal from subprocess import * import sys @@ -56,7 +57,6 @@ from . import lldbutil from . import test_categories from lldbsuite.support import encoded_file from lldbsuite.support import funcutils -from lldbsuite.support import seven from lldbsuite.test_event import build_exception # See also dotest.parseOptionsAndInitTestdirs(), where the environment variables @@ -1508,7 +1508,7 @@ class Base(unittest.TestCase): self.runBuildCommand(command) def runBuildCommand(self, command): - self.trace(seven.join_for_shell(command)) + self.trace(shlex.join(command)) try: output = check_output(command, stderr=STDOUT, errors="replace") except CalledProcessError as cpe: diff --git a/lldb/packages/Python/lldbsuite/test_event/build_exception.py b/lldb/packages/Python/lldbsuite/test_event/build_exception.py index 931c15d..c3ae2cd 100644 --- a/lldb/packages/Python/lldbsuite/test_event/build_exception.py +++ b/lldb/packages/Python/lldbsuite/test_event/build_exception.py @@ -1,10 +1,10 @@ -from lldbsuite.support import seven +import shlex class BuildError(Exception): def __init__(self, called_process_error): super(BuildError, self).__init__("Error when building test subject") - self.command = seven.join_for_shell(called_process_error.cmd) + self.command = shlex.join(called_process_error.cmd) self.build_error = called_process_error.output def __str__(self): diff --git a/lldb/source/Commands/CommandOptionsProcessLaunch.cpp b/lldb/source/Commands/CommandOptionsProcessLaunch.cpp index 21d94d6..8ae20bd 100644 --- a/lldb/source/Commands/CommandOptionsProcessLaunch.cpp +++ b/lldb/source/Commands/CommandOptionsProcessLaunch.cpp @@ -127,6 +127,10 @@ Status CommandOptionsProcessLaunch::SetOptionValue( break; } + case 'M': + launch_info.GetFlags().Set(eLaunchFlagMemoryTagging); + break; + case 'c': if (!option_arg.empty()) launch_info.SetShell(FileSpec(option_arg)); diff --git a/lldb/source/Commands/Options.td b/lldb/source/Commands/Options.td index 595b3d0..a9f054e 100644 --- a/lldb/source/Commands/Options.td +++ b/lldb/source/Commands/Options.td @@ -1173,6 +1173,11 @@ let Command = "process launch" in { Arg<"Boolean">, Desc<"Set whether to shell expand arguments to the process when " "launching.">; + def process_launch_memory_tagging + : Option<"memory-tagging", "M">, + Desc<"Set whether to explicitly enable memory tagging when launching " + "the process. Requires hardware support. " + "(Only supported on Darwin.)">; } let Command = "process attach" in { diff --git a/lldb/source/Core/CoreProperties.td b/lldb/source/Core/CoreProperties.td index fda34a8..1be911c 100644 --- a/lldb/source/Core/CoreProperties.td +++ b/lldb/source/Core/CoreProperties.td @@ -162,10 +162,12 @@ let Definition = "debugger" in { Global, DefaultTrue, Desc<"Whether to use Ansi color codes or not.">; - def ShowProgress: Property<"show-progress", "Boolean">, - Global, - DefaultTrue, - Desc<"Whether to show progress or not if the debugger's output is an interactive color-enabled terminal.">; + def ShowProgress + : Property<"show-progress", "Boolean">, + Global, + DefaultFalse, + Desc<"Whether to show progress using Operating System Command (OSC) " + "Sequences in supporting terminal emulators.">; def ShowProgressAnsiPrefix: Property<"show-progress-ansi-prefix", "String">, Global, DefaultStringValue<"${ansi.faint}">, diff --git a/lldb/source/Core/Debugger.cpp b/lldb/source/Core/Debugger.cpp index 568cd9d..b37d9d3 100644 --- a/lldb/source/Core/Debugger.cpp +++ b/lldb/source/Core/Debugger.cpp @@ -2066,19 +2066,23 @@ void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) { m_forward_listener_sp.reset(); } +bool Debugger::IsEscapeCodeCapableTTY() { + if (lldb::LockableStreamFileSP stream_sp = GetOutputStreamSP()) { + File &file = stream_sp->GetUnlockedFile(); + return file.GetIsInteractive() && file.GetIsRealTerminal() && + file.GetIsTerminalWithColors(); + } + return false; +} + bool Debugger::StatuslineSupported() { // We have trouble with the contol codes on Windows, see // https://github.com/llvm/llvm-project/issues/134846. #ifndef _WIN32 - if (GetShowStatusline()) { - if (lldb::LockableStreamFileSP stream_sp = GetOutputStreamSP()) { - File &file = stream_sp->GetUnlockedFile(); - return file.GetIsInteractive() && file.GetIsRealTerminal() && - file.GetIsTerminalWithColors(); - } - } -#endif + return GetShowStatusline() && IsEscapeCodeCapableTTY(); +#else return false; +#endif } static bool RequiresFollowChildWorkaround(const Process &process) { @@ -2271,10 +2275,11 @@ void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) { ProgressReport progress_report{data->GetID(), data->GetCompleted(), data->GetTotal(), data->GetMessage()}; - // Do some bookkeeping regardless of whether we're going to display - // progress reports. { std::lock_guard<std::mutex> guard(m_progress_reports_mutex); + + // Do some bookkeeping regardless of whether we're going to display + // progress reports. auto it = llvm::find_if(m_progress_reports, [&](const auto &report) { return report.id == progress_report.id; }); @@ -2287,6 +2292,30 @@ void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) { } else { m_progress_reports.push_back(progress_report); } + + // Show progress using Operating System Command (OSC) sequences. + if (GetShowProgress() && IsEscapeCodeCapableTTY()) { + if (lldb::LockableStreamFileSP stream_sp = GetOutputStreamSP()) { + + // Clear progress if this was the last progress event. + if (m_progress_reports.empty()) { + stream_sp->Lock() << OSC_PROGRESS_REMOVE; + return; + } + + const ProgressReport &report = m_progress_reports.back(); + + // Show indeterminate progress. + if (report.total == UINT64_MAX) { + stream_sp->Lock() << OSC_PROGRESS_INDETERMINATE; + return; + } + + // Compute and show the progress value (0-100). + const unsigned value = (report.completed / report.total) * 100; + stream_sp->Lock().Printf(OSC_PROGRESS_SHOW, value); + } + } } } diff --git a/lldb/source/Host/freebsd/Host.cpp b/lldb/source/Host/freebsd/Host.cpp index fa7efad..dfdbfea 100644 --- a/lldb/source/Host/freebsd/Host.cpp +++ b/lldb/source/Host/freebsd/Host.cpp @@ -18,8 +18,6 @@ #include <dlfcn.h> #include <execinfo.h> -#include "llvm/Object/ELF.h" - #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" @@ -32,6 +30,7 @@ #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" +#include "llvm/Object/ELF.h" #include "llvm/TargetParser/Host.h" namespace lldb_private { diff --git a/lldb/source/Host/macosx/objcxx/Host.mm b/lldb/source/Host/macosx/objcxx/Host.mm index 3c1d117..7120892 100644 --- a/lldb/source/Host/macosx/objcxx/Host.mm +++ b/lldb/source/Host/macosx/objcxx/Host.mm @@ -1210,6 +1210,39 @@ static Status LaunchProcessPosixSpawn(const char *exe_path, } } + if (launch_info.GetFlags().Test(eLaunchFlagMemoryTagging)) { + // The following function configures the spawn attributes to launch the + // process with memory tagging explicitly enabled. We look it up + // dynamically since it is only available on newer OS. Does nothing on + // hardware which does not support MTE. + // + // int posix_spawnattr_set_use_sec_transition_shims_np( + // posix_spawnattr_t *attr, uint32_t flags); + // + using posix_spawnattr_set_use_sec_transition_shims_np_t = + int (*)(posix_spawnattr_t *attr, uint32_t flags); + auto posix_spawnattr_set_use_sec_transition_shims_np_fn = + (posix_spawnattr_set_use_sec_transition_shims_np_t)dlsym( + RTLD_DEFAULT, "posix_spawnattr_set_use_sec_transition_shims_np"); + if (posix_spawnattr_set_use_sec_transition_shims_np_fn) { + error = + Status(posix_spawnattr_set_use_sec_transition_shims_np_fn(&attr, 0), + eErrorTypePOSIX); + if (error.Fail()) { + LLDB_LOG(log, + "error: {0}, " + "posix_spawnattr_set_use_sec_transition_shims_np(&attr, 0)", + error); + return error; + } + } else { + LLDB_LOG(log, + "error: posix_spawnattr_set_use_sec_transition_shims_np not " + "available", + error); + } + } + // Don't set the binpref if a shell was provided. After all, that's only // going to affect what version of the shell is launched, not what fork of // the binary is launched. We insert "arch --arch <ARCH> as part of the diff --git a/lldb/source/Host/windows/MainLoopWindows.cpp b/lldb/source/Host/windows/MainLoopWindows.cpp index c0b1079..9b7df10 100644 --- a/lldb/source/Host/windows/MainLoopWindows.cpp +++ b/lldb/source/Host/windows/MainLoopWindows.cpp @@ -55,11 +55,7 @@ public: if (m_monitor_thread.joinable()) { m_stopped = true; SetEvent(m_ready); - // Keep trying to cancel ReadFile() until the thread exits. - do { - CancelIoEx(m_handle, /*lpOverlapped=*/NULL); - } while (WaitForSingleObject(m_monitor_thread.native_handle(), 1) == - WAIT_TIMEOUT); + CancelIoEx(m_handle, /*lpOverlapped=*/NULL); m_monitor_thread.join(); } CloseHandle(m_event); diff --git a/lldb/source/Interpreter/CommandInterpreter.cpp b/lldb/source/Interpreter/CommandInterpreter.cpp index d909c56..ffcc9ce 100644 --- a/lldb/source/Interpreter/CommandInterpreter.cpp +++ b/lldb/source/Interpreter/CommandInterpreter.cpp @@ -2591,7 +2591,7 @@ void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) { llvm::sys::path::parent_path(home_init_file.GetPath())) { result.SetStatus(eReturnStatusSuccessFinishNoResult); } else { - result.AppendError(InitFileWarning); + result.AppendWarning(InitFileWarning); } } } diff --git a/lldb/source/Interpreter/embedded_interpreter.py b/lldb/source/Interpreter/embedded_interpreter.py index a487592..cdf166a 100644 --- a/lldb/source/Interpreter/embedded_interpreter.py +++ b/lldb/source/Interpreter/embedded_interpreter.py @@ -1,9 +1,5 @@ import sys - -if sys.version_info[0] < 3: - import __builtin__ as builtins -else: - import builtins +import builtins import code import lldb import traceback diff --git a/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp b/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp index 606f951..e20dd31 100644 --- a/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp +++ b/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.cpp @@ -142,7 +142,13 @@ lldb_private::formatters::LibcxxStdAtomicSyntheticFrontEnd:: SyntheticChildrenFrontEnd * lldb_private::formatters::LibcxxAtomicSyntheticFrontEndCreator( CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) { - if (valobj_sp) + if (valobj_sp && IsLibCxxAtomic(*valobj_sp)) return new LibcxxStdAtomicSyntheticFrontEnd(valobj_sp); return nullptr; } + +bool lldb_private::formatters::IsLibCxxAtomic(ValueObject &valobj) { + if (auto valobj_sp = valobj.GetNonSyntheticValue()) + return valobj_sp->GetChildMemberWithName("__a_") != nullptr; + return false; +} diff --git a/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h b/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h index 9327446..7005950 100644 --- a/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h +++ b/lldb/source/Plugins/Language/CPlusPlus/LibCxxAtomic.h @@ -18,6 +18,8 @@ namespace lldb_private { namespace formatters { +bool IsLibCxxAtomic(ValueObject &valobj); + lldb::ValueObjectSP GetLibCxxAtomicValue(ValueObject &valobj); bool LibCxxAtomicSummaryProvider(ValueObject &valobj, Stream &stream, diff --git a/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp b/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp index 4b183a8..5588208 100644 --- a/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp +++ b/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp @@ -52,7 +52,7 @@ private: ValueObject *m_tree = nullptr; size_t m_num_elements = 0; ValueObject *m_next_element = nullptr; - std::vector<std::pair<ValueObject *, uint64_t>> m_elements_cache; + std::vector<ValueObject *> m_elements_cache; }; class LibCxxUnorderedMapIteratorSyntheticFrontEnd @@ -192,26 +192,25 @@ lldb::ValueObjectSP lldb_private::formatters:: return nullptr; } } - m_elements_cache.push_back( - {value_sp.get(), hash_sp->GetValueAsUnsigned(0)}); + m_elements_cache.push_back(value_sp.get()); m_next_element = node_sp->GetChildMemberWithName("__next_").get(); if (!m_next_element || m_next_element->GetValueAsUnsigned(0) == 0) m_next_element = nullptr; } - std::pair<ValueObject *, uint64_t> val_hash = m_elements_cache[idx]; - if (!val_hash.first) + ValueObject *val_hash = m_elements_cache[idx]; + if (!val_hash) return lldb::ValueObjectSP(); StreamString stream; stream.Printf("[%" PRIu64 "]", (uint64_t)idx); DataExtractor data; Status error; - val_hash.first->GetData(data, error); + val_hash->GetData(data, error); if (error.Fail()) return lldb::ValueObjectSP(); const bool thread_and_frame_only_if_stopped = true; - ExecutionContext exe_ctx = val_hash.first->GetExecutionContextRef().Lock( - thread_and_frame_only_if_stopped); + ExecutionContext exe_ctx = + val_hash->GetExecutionContextRef().Lock(thread_and_frame_only_if_stopped); return CreateValueObjectFromData(stream.GetString(), data, exe_ctx, m_element_type); } diff --git a/lldb/source/Plugins/Language/CPlusPlus/MsvcStl.h b/lldb/source/Plugins/Language/CPlusPlus/MsvcStl.h index 8a49181..e818b88 100644 --- a/lldb/source/Plugins/Language/CPlusPlus/MsvcStl.h +++ b/lldb/source/Plugins/Language/CPlusPlus/MsvcStl.h @@ -89,6 +89,7 @@ MsvcStlVariantSyntheticFrontEndCreator(CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp); // MSVC STL std::atomic<> +bool IsMsvcStlAtomic(ValueObject &valobj); bool MsvcStlAtomicSummaryProvider(ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options); SyntheticChildrenFrontEnd * diff --git a/lldb/source/Plugins/Language/CPlusPlus/MsvcStlAtomic.cpp b/lldb/source/Plugins/Language/CPlusPlus/MsvcStlAtomic.cpp index 3ec3245..c871861 100644 --- a/lldb/source/Plugins/Language/CPlusPlus/MsvcStlAtomic.cpp +++ b/lldb/source/Plugins/Language/CPlusPlus/MsvcStlAtomic.cpp @@ -83,7 +83,9 @@ llvm::Expected<size_t> lldb_private::formatters:: lldb_private::SyntheticChildrenFrontEnd * lldb_private::formatters::MsvcStlAtomicSyntheticFrontEndCreator( CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) { - return new MsvcStlAtomicSyntheticFrontEnd(valobj_sp); + if (valobj_sp && IsMsvcStlAtomic(*valobj_sp)) + return new MsvcStlAtomicSyntheticFrontEnd(valobj_sp); + return nullptr; } bool lldb_private::formatters::MsvcStlAtomicSummaryProvider( @@ -100,3 +102,9 @@ bool lldb_private::formatters::MsvcStlAtomicSummaryProvider( } return false; } + +bool lldb_private::formatters::IsMsvcStlAtomic(ValueObject &valobj) { + if (auto valobj_sp = valobj.GetNonSyntheticValue()) + return valobj_sp->GetChildMemberWithName("_Storage") != nullptr; + return false; +} diff --git a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp index cc0c9e7..6d8f41a 100644 --- a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp +++ b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp @@ -14,6 +14,7 @@ #include "lldb/Utility/LLDBLog.h" #include "lldb/Utility/Log.h" #include "lldb/lldb-enumerations.h" +#include "llvm/ADT/Sequence.h" using namespace lldb; using namespace lldb_private; @@ -266,22 +267,47 @@ bool ClassDescriptorV2::method_list_t::Read(Process *process, return true; } -bool ClassDescriptorV2::method_t::Read(Process *process, lldb::addr_t addr, - lldb::addr_t relative_selector_base_addr, - bool is_small, bool has_direct_sel) { - size_t ptr_size = process->GetAddressByteSize(); - size_t size = GetSize(process, is_small); +llvm::SmallVector<ClassDescriptorV2::method_t, 0> +ClassDescriptorV2::ReadMethods(llvm::ArrayRef<lldb::addr_t> addresses, + lldb::addr_t relative_selector_base_addr, + bool is_small, bool has_direct_sel) const { + lldb_private::Process *process = m_runtime.GetProcess(); + if (!process) + return {}; - DataBufferHeap buffer(size, '\0'); - Status error; + const size_t size = method_t::GetSize(process, is_small); + const size_t num_methods = addresses.size(); - process->ReadMemory(addr, buffer.GetBytes(), size, error); - if (error.Fail()) { - return false; + llvm::SmallVector<uint8_t, 0> buffer(num_methods * size, 0); + llvm::DenseSet<uint32_t> failed_indices; + + for (auto [idx, addr] : llvm::enumerate(addresses)) { + Status error; + process->ReadMemory(addr, buffer.data() + idx * size, size, error); + if (error.Fail()) + failed_indices.insert(idx); } - DataExtractor extractor(buffer.GetBytes(), size, process->GetByteOrder(), - ptr_size); + llvm::SmallVector<method_t, 0> methods; + methods.reserve(num_methods); + for (auto [idx, addr] : llvm::enumerate(addresses)) { + if (failed_indices.contains(idx)) + continue; + DataExtractor extractor(buffer.data() + idx * size, size, + process->GetByteOrder(), + process->GetAddressByteSize()); + methods.push_back(method_t()); + methods.back().Read(extractor, process, addr, relative_selector_base_addr, + is_small, has_direct_sel); + } + + return methods; +} + +bool ClassDescriptorV2::method_t::Read(DataExtractor &extractor, + Process *process, lldb::addr_t addr, + lldb::addr_t relative_selector_base_addr, + bool is_small, bool has_direct_sel) { lldb::offset_t cursor = 0; if (is_small) { @@ -291,11 +317,11 @@ bool ClassDescriptorV2::method_t::Read(Process *process, lldb::addr_t addr, m_name_ptr = addr + nameref_offset; + Status error; if (!has_direct_sel) { // The SEL offset points to a SELRef. We need to dereference twice. - m_name_ptr = process->ReadUnsignedIntegerFromMemory(m_name_ptr, ptr_size, - 0, error); - if (!error.Success()) + m_name_ptr = process->ReadPointerFromMemory(m_name_ptr, error); + if (error.Fail()) return false; } else if (relative_selector_base_addr != LLDB_INVALID_ADDRESS) { m_name_ptr = relative_selector_base_addr + nameref_offset; @@ -308,13 +334,13 @@ bool ClassDescriptorV2::method_t::Read(Process *process, lldb::addr_t addr, m_imp_ptr = extractor.GetAddress_unchecked(&cursor); } + Status error; process->ReadCStringFromMemory(m_name_ptr, m_name, error); - if (error.Fail()) { + if (error.Fail()) return false; - } process->ReadCStringFromMemory(m_types_ptr, m_types, error); - return !error.Fail(); + return error.Success(); } bool ClassDescriptorV2::ivar_list_t::Read(Process *process, lldb::addr_t addr) { @@ -447,17 +473,19 @@ ClassDescriptorV2::GetMethodList(Process *process, bool ClassDescriptorV2::ProcessMethodList( std::function<bool(const char *, const char *)> const &instance_method_func, ClassDescriptorV2::method_list_t &method_list) const { - lldb_private::Process *process = m_runtime.GetProcess(); - auto method = std::make_unique<method_t>(); - lldb::addr_t relative_selector_base_addr = - m_runtime.GetRelativeSelectorBaseAddr(); - for (uint32_t i = 0, e = method_list.m_count; i < e; ++i) { - method->Read(process, method_list.m_first_ptr + (i * method_list.m_entsize), - relative_selector_base_addr, method_list.m_is_small, - method_list.m_has_direct_selector); - if (instance_method_func(method->m_name.c_str(), method->m_types.c_str())) + auto idx_to_method_addr = [&](uint32_t idx) { + return method_list.m_first_ptr + (idx * method_list.m_entsize); + }; + llvm::SmallVector<addr_t> addresses = llvm::to_vector(llvm::map_range( + llvm::seq<uint32_t>(method_list.m_count), idx_to_method_addr)); + + llvm::SmallVector<method_t, 0> methods = + ReadMethods(addresses, m_runtime.GetRelativeSelectorBaseAddr(), + method_list.m_is_small, method_list.m_has_direct_selector); + + for (const auto &method : methods) + if (instance_method_func(method.m_name.c_str(), method.m_types.c_str())) break; - } return true; } diff --git a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h index 920a5eb..78b3311 100644 --- a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h +++ b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.h @@ -172,11 +172,16 @@ private: + field_size; // IMP imp; } - bool Read(Process *process, lldb::addr_t addr, + bool Read(DataExtractor &extractor, Process *process, lldb::addr_t addr, lldb::addr_t relative_selector_base_addr, bool is_small, bool has_direct_sel); }; + llvm::SmallVector<method_t, 0> + ReadMethods(llvm::ArrayRef<lldb::addr_t> addresses, + lldb::addr_t relative_selector_base_addr, bool is_small, + bool has_direct_sel) const; + struct ivar_list_t { uint32_t m_entsize; uint32_t m_count; diff --git a/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp b/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp index f538fc6..57d88f6 100644 --- a/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp +++ b/lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp @@ -9,6 +9,7 @@ #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" +#include "lldb/Host/HostInfo.h" #include "lldb/Utility/LLDBLog.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/UriParser.h" diff --git a/lldb/source/Plugins/Process/wasm/RegisterContextWasm.cpp b/lldb/source/Plugins/Process/wasm/RegisterContextWasm.cpp index b468171..2e02076 100644 --- a/lldb/source/Plugins/Process/wasm/RegisterContextWasm.cpp +++ b/lldb/source/Plugins/Process/wasm/RegisterContextWasm.cpp @@ -22,7 +22,7 @@ using namespace lldb_private::process_gdb_remote; using namespace lldb_private::wasm; RegisterContextWasm::RegisterContextWasm( - wasm::ThreadWasm &thread, uint32_t concrete_frame_idx, + ThreadGDBRemote &thread, uint32_t concrete_frame_idx, GDBRemoteDynamicRegisterInfoSP reg_info_sp) : GDBRemoteRegisterContext(thread, concrete_frame_idx, reg_info_sp, false, false) {} diff --git a/lldb/source/Plugins/Process/wasm/RegisterContextWasm.h b/lldb/source/Plugins/Process/wasm/RegisterContextWasm.h index 7e63eb8..6ca31e5 100644 --- a/lldb/source/Plugins/Process/wasm/RegisterContextWasm.h +++ b/lldb/source/Plugins/Process/wasm/RegisterContextWasm.h @@ -10,6 +10,7 @@ #define LLDB_SOURCE_PLUGINS_PROCESS_WASM_REGISTERCONTEXTWASM_H #include "Plugins/Process/gdb-remote/GDBRemoteRegisterContext.h" +#include "Plugins/Process/gdb-remote/ThreadGDBRemote.h" #include "ThreadWasm.h" #include "Utility/WasmVirtualRegisters.h" #include "lldb/lldb-private-types.h" @@ -34,7 +35,7 @@ class RegisterContextWasm : public process_gdb_remote::GDBRemoteRegisterContext { public: RegisterContextWasm( - wasm::ThreadWasm &thread, uint32_t concrete_frame_idx, + process_gdb_remote::ThreadGDBRemote &thread, uint32_t concrete_frame_idx, process_gdb_remote::GDBRemoteDynamicRegisterInfoSP reg_info_sp); ~RegisterContextWasm() override; diff --git a/lldb/source/Plugins/Process/wasm/UnwindWasm.cpp b/lldb/source/Plugins/Process/wasm/UnwindWasm.cpp index 99845dd..319c5e2 100644 --- a/lldb/source/Plugins/Process/wasm/UnwindWasm.cpp +++ b/lldb/source/Plugins/Process/wasm/UnwindWasm.cpp @@ -9,6 +9,7 @@ #include "UnwindWasm.h" #include "Plugins/Process/gdb-remote/ThreadGDBRemote.h" #include "ProcessWasm.h" +#include "RegisterContextWasm.h" #include "ThreadWasm.h" #include "lldb/Utility/LLDBLog.h" #include "lldb/Utility/Log.h" @@ -18,21 +19,6 @@ using namespace lldb_private; using namespace process_gdb_remote; using namespace wasm; -class WasmGDBRemoteRegisterContext : public GDBRemoteRegisterContext { -public: - WasmGDBRemoteRegisterContext(ThreadGDBRemote &thread, - uint32_t concrete_frame_idx, - GDBRemoteDynamicRegisterInfoSP ®_info_sp, - uint64_t pc) - : GDBRemoteRegisterContext(thread, concrete_frame_idx, reg_info_sp, false, - false) { - // Wasm does not have a fixed set of registers but relies on a mechanism - // named local and global variables to store information such as the stack - // pointer. The only actual register is the PC. - PrivateSetRegisterValue(0, pc); - } -}; - lldb::RegisterContextSP UnwindWasm::DoCreateRegisterContextForFrame(lldb_private::StackFrame *frame) { if (m_frames.size() <= frame->GetFrameIndex()) @@ -43,9 +29,9 @@ UnwindWasm::DoCreateRegisterContextForFrame(lldb_private::StackFrame *frame) { ProcessWasm *wasm_process = static_cast<ProcessWasm *>(thread->GetProcess().get()); - return std::make_shared<WasmGDBRemoteRegisterContext>( - *gdb_thread, frame->GetConcreteFrameIndex(), - wasm_process->GetRegisterInfo(), m_frames[frame->GetFrameIndex()]); + return std::make_shared<RegisterContextWasm>(*gdb_thread, + frame->GetConcreteFrameIndex(), + wasm_process->GetRegisterInfo()); } uint32_t UnwindWasm::DoGetFrameCount() { diff --git a/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp b/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp index 75a8189..7e275f1 100644 --- a/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp +++ b/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp @@ -2141,14 +2141,17 @@ TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) { if (!ts) return nullptr; - ts->GetNativePDBParser()->GetOrCreateTypedefDecl(id); + auto *typedef_decl = ts->GetNativePDBParser()->GetOrCreateTypedefDecl(id); + + CompilerType ct = target_type->GetForwardCompilerType(); + if (auto *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get())) + ct = clang->GetType(clang->getASTContext().getTypeDeclType(typedef_decl)); Declaration decl; return MakeType(toOpaqueUid(id), ConstString(udt.Name), llvm::expectedToOptional(target_type->GetByteSize(nullptr)), nullptr, target_type->GetID(), - lldb_private::Type::eEncodingIsTypedefUID, decl, - target_type->GetForwardCompilerType(), + lldb_private::Type::eEncodingIsTypedefUID, decl, ct, lldb_private::Type::ResolveState::Forward); } diff --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp index 21c265e..12cabff 100644 --- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp +++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp @@ -849,8 +849,20 @@ lldb::BasicType TypeSystemClang::GetBasicTypeEnumeration(llvm::StringRef name) { {"unsigned long long int", eBasicTypeUnsignedLongLong}, // "int128" + // + // The following two lines are here only + // for the sake of backward-compatibility. + // Neither "__int128_t", nor "__uint128_t" are basic-types. + // They are typedefs. {"__int128_t", eBasicTypeInt128}, {"__uint128_t", eBasicTypeUnsignedInt128}, + // In order to be consistent with: + // - gcc's C programming language extension related to 128-bit integers + // https://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html + // - the "BuiltinType::getName" method in LLVM + // the following two lines must be present: + {"__int128", eBasicTypeInt128}, + {"unsigned __int128", eBasicTypeUnsignedInt128}, // "bool" {"bool", eBasicTypeBool}, diff --git a/lldb/source/Target/RegisterContextUnwind.cpp b/lldb/source/Target/RegisterContextUnwind.cpp index c6d15fc..252bee2 100644 --- a/lldb/source/Target/RegisterContextUnwind.cpp +++ b/lldb/source/Target/RegisterContextUnwind.cpp @@ -52,6 +52,14 @@ static ConstString GetSymbolOrFunctionName(const SymbolContext &sym_ctx) { return ConstString(); } +static bool CallFrameAddressIsValid(ABISP abi_sp, lldb::addr_t cfa) { + if (cfa == LLDB_INVALID_ADDRESS) + return false; + if (abi_sp) + return abi_sp->CallFrameAddressIsValid(cfa); + return cfa != 0 && cfa != 1; +} + RegisterContextUnwind::RegisterContextUnwind(Thread &thread, const SharedPtr &next_frame, SymbolContext &sym_ctx, @@ -448,7 +456,7 @@ void RegisterContextUnwind::InitializeNonZerothFrame() { ReadFrameAddress(row_register_kind, row->GetAFAValue(), m_afa); // A couple of sanity checks.. - if (m_cfa == LLDB_INVALID_ADDRESS || m_cfa == 0 || m_cfa == 1) { + if (!CallFrameAddressIsValid(abi_sp, m_cfa)) { UnwindLogMsg("could not find a valid cfa address"); m_frame_type = eNotAValidFrame; return; @@ -1847,9 +1855,11 @@ bool RegisterContextUnwind::TryFallbackUnwindPlan() { active_row->GetCFAValue().GetValueType() != UnwindPlan::Row::FAValue::unspecified) { addr_t new_cfa; + ProcessSP process_sp = m_thread.GetProcess(); + ABISP abi_sp = process_sp ? process_sp->GetABI() : nullptr; if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(), - active_row->GetCFAValue(), new_cfa) || - new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) { + active_row->GetCFAValue(), new_cfa) || + !CallFrameAddressIsValid(abi_sp, new_cfa)) { UnwindLogMsg("failed to get cfa with fallback unwindplan"); m_fallback_unwind_plan_sp.reset(); m_full_unwind_plan_sp = original_full_unwind_plan_sp; @@ -1870,10 +1880,9 @@ bool RegisterContextUnwind::TryFallbackUnwindPlan() { if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) { new_caller_pc_value = reg_value.GetAsUInt64(); - if (ProcessSP process_sp = m_thread.GetProcess()) { - if (ABISP abi_sp = process_sp->GetABI()) - new_caller_pc_value = abi_sp->FixCodeAddress(new_caller_pc_value); - } + if (process_sp) + new_caller_pc_value = + process_sp->FixCodeAddress(new_caller_pc_value); } } } @@ -1932,9 +1941,11 @@ bool RegisterContextUnwind::ForceSwitchToFallbackUnwindPlan() { active_row->GetCFAValue().GetValueType() != UnwindPlan::Row::FAValue::unspecified) { addr_t new_cfa; + ProcessSP process_sp = m_thread.GetProcess(); + ABISP abi_sp = process_sp ? process_sp->GetABI() : nullptr; if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(), - active_row->GetCFAValue(), new_cfa) || - new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) { + active_row->GetCFAValue(), new_cfa) || + !CallFrameAddressIsValid(abi_sp, new_cfa)) { UnwindLogMsg("failed to get cfa with fallback unwindplan"); m_fallback_unwind_plan_sp.reset(); return false; @@ -2055,8 +2066,7 @@ bool RegisterContextUnwind::ReadFrameAddress( RegisterNumber cfa_reg(m_thread, row_register_kind, fa.GetRegisterNumber()); if (ReadGPRValue(cfa_reg, cfa_reg_contents)) { - if (cfa_reg_contents == LLDB_INVALID_ADDRESS || cfa_reg_contents == 0 || - cfa_reg_contents == 1) { + if (!CallFrameAddressIsValid(abi_sp, cfa_reg_contents)) { UnwindLogMsg( "Got an invalid CFA register value - reg %s (%d), value 0x%" PRIx64, cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB), diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/Makefile b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/Makefile new file mode 100644 index 0000000..99998b2 --- /dev/null +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/TestDataFormatterInvalidAtomic.py b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/TestDataFormatterInvalidAtomic.py new file mode 100644 index 0000000..76b8e7b --- /dev/null +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/TestDataFormatterInvalidAtomic.py @@ -0,0 +1,45 @@ +""" +Test formatting of `std::atomic`s not from any STL +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class InvalidAtomicDataFormatterTestCase(TestBase): + def test(self): + self.build() + lldbutil.run_to_source_breakpoint( + self, "Set break point at this line.", lldb.SBFileSpec("main.cpp") + ) + + self.expect_expr( + "a", + result_children=[ + ValueCheck(name="foo", value="1"), + ValueCheck(name="bar", value="2"), + ], + ) + self.expect_expr( + "b", + result_children=[ + ValueCheck(name="foo", value="3"), + ValueCheck(name="bar", value="4"), + ], + ) + + self.expect_expr( + "c", + result_children=[ + ValueCheck(name="foo", value="5"), + ValueCheck(name="bar", value="6"), + ], + ) + self.expect_expr( + "d", + result_children=[ + ValueCheck(name="foo", value="7"), + ValueCheck(name="bar", value="8"), + ], + ) diff --git a/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/main.cpp b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/main.cpp new file mode 100644 index 0000000..7b4c51c --- /dev/null +++ b/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic-simulators/invalid-atomic/main.cpp @@ -0,0 +1,23 @@ +namespace std { +template <typename T> struct atomic { + int foo; + int bar; +}; + +namespace __1 { +template <typename T> struct atomic { + int foo; + int bar; +}; +} // namespace __1 +} // namespace std + +int main() { + std::atomic<int> a{1, 2}; + std::atomic<void> b{3, 4}; + + std::__1::atomic<int> c{5, 6}; + std::__1::atomic<void> d{7, 8}; + + return 0; // Set break point at this line. +} diff --git a/lldb/test/API/functionalities/unwind/cortex-m-exception/TestCortexMExceptionUnwind.py b/lldb/test/API/functionalities/unwind/cortex-m-exception/TestCortexMExceptionUnwind.py index 10cbd26..50ea173 100644 --- a/lldb/test/API/functionalities/unwind/cortex-m-exception/TestCortexMExceptionUnwind.py +++ b/lldb/test/API/functionalities/unwind/cortex-m-exception/TestCortexMExceptionUnwind.py @@ -12,7 +12,7 @@ from lldbsuite.test import lldbutil class TestCortexMExceptionUnwind(TestBase): NO_DEBUG_INFO_TESTCASE = True - @skipIfRemote + @skipIfLLVMTargetMissing("ARM") def test_no_fpu(self): """Test that we can backtrace correctly through an ARM Cortex-M Exception return stack""" @@ -44,10 +44,6 @@ class TestCortexMExceptionUnwind(TestBase): thread = process.GetThreadAtIndex(0) self.assertTrue(thread.IsValid()) - # We have 4 named stack frames and two unnamed - # frames above that. The topmost two stack frames - # were not interesting for this test, so I didn't - # create symbols for them. self.assertEqual(thread.GetNumFrames(), 3) stackframe_names = [ "exception_catcher", diff --git a/lldb/test/API/macosx/mte/Makefile b/lldb/test/API/macosx/mte/Makefile index cb20942..d614e0f 100644 --- a/lldb/test/API/macosx/mte/Makefile +++ b/lldb/test/API/macosx/mte/Makefile @@ -1,12 +1,15 @@ C_SOURCES := main.c -EXE := uaf_mte +EXE := uaf -all: uaf_mte sign +binary-plain: uaf +binary-entitled: uaf sign + +all: binary-entitled include Makefile.rules -sign: mte-entitlements.plist uaf_mte +sign: mte-entitlements.plist uaf ifeq ($(OS),Darwin) codesign -s - -f --entitlements $^ endif diff --git a/lldb/test/API/macosx/mte/TestDarwinMTE.py b/lldb/test/API/macosx/mte/TestDarwinMTE.py index ef858b1..a70b4b4 100644 --- a/lldb/test/API/macosx/mte/TestDarwinMTE.py +++ b/lldb/test/API/macosx/mte/TestDarwinMTE.py @@ -7,13 +7,25 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil import lldbsuite.test.cpu_feature as cpu_feature -exe_name = "uaf_mte" # Must match Makefile +exe_name = "uaf" # Must match Makefile class TestDarwinMTE(TestBase): NO_DEBUG_INFO_TESTCASE = True @skipUnlessFeature(cpu_feature.AArch64.MTE) + def test_process_launch_memory_tagging(self): + self.build(make_targets=["binary-plain"]) + self.createTestTarget(self.getBuildArtifact(exe_name)) + + self.expect("process launch", substrs=["exited with status = 0"]) + + self.expect( + "process launch --memory-tagging", + substrs=["stopped", "stop reason = EXC_ARM_MTE_TAG_FAULT"], + ) + + @skipUnlessFeature(cpu_feature.AArch64.MTE) def test_tag_fault(self): self.build() exe = self.getBuildArtifact(exe_name) @@ -47,7 +59,7 @@ class TestDarwinMTE(TestBase): self.expect("memory region ptr", substrs=["memory tagging: enabled"]) @skipUnlessFeature(cpu_feature.AArch64.MTE) - def test_memory_read_with_tags(self): + def test_memory_read_show_tags(self): self.build() lldbutil.run_to_source_breakpoint( self, "// before free", lldb.SBFileSpec("main.c"), exe_name=exe_name diff --git a/lldb/test/API/python_api/default-constructor/sb_filespec.py b/lldb/test/API/python_api/default-constructor/sb_filespec.py index 4ab5c49..5dd78b1 100644 --- a/lldb/test/API/python_api/default-constructor/sb_filespec.py +++ b/lldb/test/API/python_api/default-constructor/sb_filespec.py @@ -10,5 +10,5 @@ def fuzz_obj(obj): obj.ResolveExecutableLocation() obj.GetFilename() obj.GetDirectory() - obj.GetPath(None, 0) + obj.GetPath(1) obj.GetDescription(lldb.SBStream()) diff --git a/lldb/test/API/python_api/sbtype_basic_type/TestSBTypeBasicType.py b/lldb/test/API/python_api/sbtype_basic_type/TestSBTypeBasicType.py index 535d8b9..f8594df 100644 --- a/lldb/test/API/python_api/sbtype_basic_type/TestSBTypeBasicType.py +++ b/lldb/test/API/python_api/sbtype_basic_type/TestSBTypeBasicType.py @@ -28,3 +28,11 @@ class TestCase(TestBase): self.assertEqual(b.GetType().GetBasicType(), int_basic_type) self.assertEqual(c.GetType().GetBasicType(), int_basic_type) self.assertEqual(d.GetType().GetBasicType(), int_basic_type) + + # Check the size of the chosen basic types. + self.assertEqual(self.target().FindFirstType("__int128").size, 16) + self.assertEqual(self.target().FindFirstType("unsigned __int128").size, 16) + + # Check the size of the chosen aliases of basic types. + self.assertEqual(self.target().FindFirstType("__int128_t").size, 16) + self.assertEqual(self.target().FindFirstType("__uint128_t").size, 16) diff --git a/lldb/test/API/tools/lldb-server/TestGdbRemoteFork.py b/lldb/test/API/tools/lldb-server/TestGdbRemoteFork.py index 13c4a85..ef1d546 100644 --- a/lldb/test/API/tools/lldb-server/TestGdbRemoteFork.py +++ b/lldb/test/API/tools/lldb-server/TestGdbRemoteFork.py @@ -2,6 +2,7 @@ import random from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * +from lldbsuite.support import seven from fork_testbase import GdbRemoteForkTestBase diff --git a/lldb/test/Shell/Driver/LocalLLDBInit.test b/lldb/test/Shell/Driver/LocalLLDBInit.test index 5db545e..2aa8c52 100644 --- a/lldb/test/Shell/Driver/LocalLLDBInit.test +++ b/lldb/test/Shell/Driver/LocalLLDBInit.test @@ -9,7 +9,7 @@ # RUN: env HOME=%t.home %lldb-init -local-lldbinit -o 'settings show frame-format' 2>&1 | FileCheck %s --check-prefix=ALLOWINIT --check-prefix=NOINIT # RUN: %lldb -o 'settings show frame-format' 2>&1 | FileCheck %s --check-prefix=NOINIT --check-prefix=CHECK -# WARNINIT: There is a .lldbinit file in the current directory which is not being read. +# WARNINIT: warning: There is a .lldbinit file in the current directory which is not being read. # NOINIT-NOT: There is a .lldbinit file in the current directory which is not being read. # CHECK-NOT: bogus # ALLOWINIT: name 'prlnt' is not defined diff --git a/lldb/test/Shell/Expr/TestExprLanguageNote.test b/lldb/test/Shell/Expr/TestExprLanguageNote.test index 7d8c702..e8e4e13 100644 --- a/lldb/test/Shell/Expr/TestExprLanguageNote.test +++ b/lldb/test/Shell/Expr/TestExprLanguageNote.test @@ -1,5 +1,3 @@ -# REQUIRES: (system-windows && lld) || !system-windows - # RUN: split-file %s %t # RUN: %clang_host -g %t/main.cpp -o %t.out # @@ -29,7 +27,7 @@ run expr blah # CHECK-TARGET: (lldb) expr -# CHECK-TARGET: note: Ran expression as 'C++{{.*}}' +# CHECK-TARGET: note: Ran expression as '{{(ISO )?}}C++{{.*}}' expr -l objc -- blah diff --git a/lldb/test/Shell/SymbolFile/NativePDB/simple-types.cpp b/lldb/test/Shell/SymbolFile/NativePDB/simple-types.cpp new file mode 100644 index 0000000..403cd29 --- /dev/null +++ b/lldb/test/Shell/SymbolFile/NativePDB/simple-types.cpp @@ -0,0 +1,127 @@ +// REQUIRES: lld + +// Test that simple types can be found +// RUN: %build --std=c++20 --nodefaultlib --compiler=clang-cl --arch=64 -o %t.exe -- %s +// RUN: lldb-test symbols %t.exe | FileCheck %s +// RUN: lldb-test symbols %t.exe | FileCheck --check-prefix=FUNC-PARAMS %s + +bool *PB; +bool &RB = *PB; +bool *&RPB = PB; +const bool &CRB = RB; +bool *const BC = 0; +const bool *const CBC = 0; + +long AL[2]; + +const volatile short CVS = 0; +const short CS = 0; +volatile short VS; + +struct ReturnedStruct1 {}; +struct ReturnedStruct2 {}; + +struct MyStruct { + static ReturnedStruct1 static_fn(char *) { return {}; } + ReturnedStruct2 const_member_fn(char *) const { return {}; } + void volatile_member_fn() volatile {}; + void member_fn() {}; +}; + +void (*PF)(int, bool *, const float, double, ...); + +using Func = void(char16_t, MyStruct &); +Func *PF2; + +using SomeTypedef = long; +SomeTypedef ST; + +int main() { + bool b; + char c; + unsigned char uc; + char8_t c8; + + short s; + unsigned short us; + wchar_t wc; + char16_t c16; + + int i; + unsigned int ui; + long l; + unsigned long ul; + char32_t c32; + + long long ll; + unsigned long long ull; + + MyStruct my_struct; + + decltype(nullptr) np; +} + +// CHECK-DAG: Type{{.*}} , name = "std::nullptr_t", size = 0, compiler_type = 0x{{[0-9a-f]+}} nullptr_t + +// CHECK-DAG: Type{{.*}} , name = "bool", size = 1, compiler_type = 0x{{[0-9a-f]+}} _Bool +// CHECK-DAG: Type{{.*}} , name = "char", size = 1, compiler_type = 0x{{[0-9a-f]+}} char +// CHECK-DAG: Type{{.*}} , name = "unsigned char", size = 1, compiler_type = 0x{{[0-9a-f]+}} unsigned char +// CHECK-DAG: Type{{.*}} , name = "char8_t", size = 1, compiler_type = 0x{{[0-9a-f]+}} char8_t + +// CHECK-DAG: Type{{.*}} , size = 2, compiler_type = 0x{{[0-9a-f]+}} short +// CHECK-DAG: Type{{.*}} , name = "const volatile ", size = 2, compiler_type = 0x{{[0-9a-f]+}} const volatile short +// CHECK-DAG: Type{{.*}} , name = "const ", size = 2, compiler_type = 0x{{[0-9a-f]+}} const short +// CHECK-DAG: Type{{.*}} , name = "volatile ", size = 2, compiler_type = 0x{{[0-9a-f]+}} volatile short + +// CHECK-DAG: Type{{.*}} , name = "unsigned short", size = 2, compiler_type = 0x{{[0-9a-f]+}} unsigned short +// CHECK-DAG: Type{{.*}} , name = "wchar_t", size = 2, compiler_type = 0x{{[0-9a-f]+}} wchar_t +// CHECK-DAG: Type{{.*}} , name = "char16_t", size = 2, compiler_type = 0x{{[0-9a-f]+}} char16_t + +// CHECK-DAG: Type{{.*}} , name = "int", size = 4, compiler_type = 0x{{[0-9a-f]+}} int +// CHECK-DAG: Type{{.*}} , name = "unsigned", size = 4, compiler_type = 0x{{[0-9a-f]+}} unsigned int +// CHECK-DAG: Type{{.*}} , name = "long", size = 4, compiler_type = 0x{{[0-9a-f]+}} long +// CHECK-DAG: Type{{.*}} , name = "unsigned long", size = 4, compiler_type = 0x{{[0-9a-f]+}} unsigned long +// CHECK-DAG: Type{{.*}} , name = "char32_t", size = 4, compiler_type = 0x{{[0-9a-f]+}} char32_t + +// CHECK-DAG: Type{{.*}} , name = "int64_t", size = 8, compiler_type = 0x{{[0-9a-f]+}} long long +// CHECK-DAG: Type{{.*}} , name = "uint64_t", size = 8, compiler_type = 0x{{[0-9a-f]+}} unsigned long long + +// CHECK-DAG: Type{{.*}} , name = "float", size = 4, compiler_type = 0x{{[0-9a-f]+}} float +// CHECK-DAG: Type{{.*}} , name = "const float", size = 4, compiler_type = 0x{{[0-9a-f]+}} const float + +// CHECK-DAG: Type{{.*}} , name = "ReturnedStruct1", size = 1, decl = simple-types.cpp:21, compiler_type = 0x{{[0-9a-f]+}} struct ReturnedStruct1 { +// CHECK-DAG: Type{{.*}} , name = "ReturnedStruct2", size = 1, decl = simple-types.cpp:22, compiler_type = 0x{{[0-9a-f]+}} struct ReturnedStruct2 { +// CHECK-DAG: Type{{.*}} , name = "MyStruct", size = 1, decl = simple-types.cpp:24, compiler_type = 0x{{[0-9a-f]+}} struct MyStruct { + +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} struct MyStruct *const +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} const struct MyStruct *const +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} volatile struct MyStruct *const +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} struct MyStruct & + +// CHECK-DAG: Type{{.*}} , name = "const bool", size = 1, compiler_type = 0x{{[0-9a-f]+}} const _Bool +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} _Bool & +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} _Bool * +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} _Bool *& +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} const _Bool & +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} _Bool *const +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} const _Bool *const + +// CHECK-DAG: Type{{.*}} , name = "SomeTypedef", size = 4, compiler_type = 0x{{[0-9a-f]+}} typedef SomeTypedef +// CHECK-DAG: Type{{.*}} , name = "Func", size = 0, compiler_type = 0x{{[0-9a-f]+}} typedef Func + +// CHECK-DAG: Type{{.*}} , size = 0, compiler_type = 0x{{[0-9a-f]+}} int (void) +// CHECK-DAG: Type{{.*}} , size = 0, compiler_type = 0x{{[0-9a-f]+}} void (void) + +// CHECK-DAG: Type{{.*}} , size = 0, compiler_type = 0x{{[0-9a-f]+}} void (int, _Bool *, const float, double, ...) +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} void (*)(int, _Bool *, const float, double, ...) + +// CHECK-DAG: Type{{.*}} , size = 0, compiler_type = 0x{{[0-9a-f]+}} void (char16_t, struct MyStruct &) +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} void (*)(char16_t, struct MyStruct &) + +// CHECK-DAG: Type{{.*}} , size = 0, compiler_type = 0x{{[0-9a-f]+}} struct ReturnedStruct1 (char *) +// CHECK-DAG: Type{{.*}} , size = 0, compiler_type = 0x{{[0-9a-f]+}} struct ReturnedStruct2 (char *) + +// CHECK-DAG: Type{{.*}} , size = 8, compiler_type = 0x{{[0-9a-f]+}} long[2] + +// double is used as a parameter to `PF`, but not created as an LLDB type +// FUNC-PARAMS-NOT: Type{{.*}} , name = "double" diff --git a/lldb/test/Shell/helper/build.py b/lldb/test/Shell/helper/build.py index caaa14f..a5a7e99 100755 --- a/lldb/test/Shell/helper/build.py +++ b/lldb/test/Shell/helper/build.py @@ -9,12 +9,8 @@ import subprocess import sys if sys.platform == "win32": - # This module was renamed in Python 3. Make sure to import it using a - # consistent name regardless of python version. - try: - import winreg - except: - import _winreg as winreg + import winreg + if __name__ != "__main__": raise RuntimeError("Do not import this script, run it instead") diff --git a/lldb/tools/lldb-mcp/lldb-mcp.cpp b/lldb/tools/lldb-mcp/lldb-mcp.cpp index 68e9872..3fc3622 100644 --- a/lldb/tools/lldb-mcp/lldb-mcp.cpp +++ b/lldb/tools/lldb-mcp/lldb-mcp.cpp @@ -85,6 +85,8 @@ FileSpec driverPath() { llvm::Error launch() { FileSpec lldb_exec = driverPath(); lldb_private::ProcessLaunchInfo info; + info.SetMonitorProcessCallback( + &lldb_private::ProcessLaunchInfo::NoOpMonitorCallback); info.SetExecutableFile(lldb_exec, /*add_exe_file_as_first_arg=*/true); info.GetArguments().AppendArgument("-O"); diff --git a/lldb/unittests/Symbol/TestTypeSystemClang.cpp b/lldb/unittests/Symbol/TestTypeSystemClang.cpp index f673cce..1981e91 100644 --- a/lldb/unittests/Symbol/TestTypeSystemClang.cpp +++ b/lldb/unittests/Symbol/TestTypeSystemClang.cpp @@ -162,6 +162,9 @@ TEST_F(TestTypeSystemClang, TestGetBasicTypeFromName) { EXPECT_EQ(GetBasicQualType(eBasicTypeInt128), GetBasicQualType("__int128_t")); EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt128), GetBasicQualType("__uint128_t")); + EXPECT_EQ(GetBasicQualType(eBasicTypeInt128), GetBasicQualType("__int128")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt128), + GetBasicQualType("unsigned __int128")); EXPECT_EQ(GetBasicQualType(eBasicTypeVoid), GetBasicQualType("void")); EXPECT_EQ(GetBasicQualType(eBasicTypeBool), GetBasicQualType("bool")); EXPECT_EQ(GetBasicQualType(eBasicTypeFloat), GetBasicQualType("float")); diff --git a/lldb/utils/lui/lui.py b/lldb/utils/lui/lui.py index 42ea3c6..27ed8f3 100755 --- a/lldb/utils/lui/lui.py +++ b/lldb/utils/lui/lui.py @@ -17,11 +17,7 @@ from optparse import OptionParser import os import signal import sys - -try: - import queue -except ImportError: - import Queue as queue +import queue import debuggerdriver import cui diff --git a/lldb/utils/lui/sandbox.py b/lldb/utils/lui/sandbox.py index 3bcf3d5..d05c268 100755 --- a/lldb/utils/lui/sandbox.py +++ b/lldb/utils/lui/sandbox.py @@ -14,10 +14,7 @@ import os import signal import sys -try: - import queue -except ImportError: - import Queue as queue +import queue import cui |