[llvm-branch-commits] [lldb] [LLDB] Support enabling/disabling InstrumentationRuntime plugins in a debug session (PR #238464)

Dan Liew via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Tue Nov 10 18:01:23 PST 2026


https://github.com/delcypher updated https://github.com/llvm/llvm-project/pull/238464

>From f4e57bfdd0db5299f6736088eeb8c44efdcfd18f Mon Sep 17 00:00:00 2001
From: Dan Liew <dan at su-root.co.uk>
Date: Mon, 20 Apr 2026 21:11:44 -0700
Subject: [PATCH] [LLDB] Support enabling/disabling InstrumentationRuntime
 plugins in a debug session

This patch is the fourth part in a patch series that will allow
enabling/disabling InstrumentationRuntime plugins in a running debug
session.

This is a rework of an older now abandoned patch:
https://github.com/llvm/llvm-project/pull/193334

Previously enabling/disabling an instrumentation runtime plugin via the
`plugin enable/disable instrumentation-runtime.<name>` command was only
supported using the `global` domain. This only toggled the plugin's
enablement state in the PluginManager. This would affect the enablement
in newly launched processes but not in any existing processes. In
practice what this meant is that:

1. If the plugin was activated when the inferior process was launched it
   could not be disabled even if requested. This meant it was impossible
   to prevent LLDB from stopping at the breakpoint set by an
   instrumentation runtime plugin because the breakpoints used are
   typically internal breakpoints (cannot be controlled by the user).
   While stopping at these breakpoints is usually desirable there are
   use cases where the developer may wish to not automatically stop and
   instead have finer grained control.

2. If the plugin was disabled before the inferior process was launched
   (e.g. `plugin disable instrumentation-runtime.<name>` in
   `~/.lldbinit`) it could not be enabled even if requested (the plugin
   was not activated). While this is a niche use case it is still very
   odd from a user perspective that the `plugin enable
   instrumentation-runtime.<name>` command did nothing during a debug
   session.

This patch builds on the previous patches in this series by making
the `global` domain also update processes that are alive and by adding
support for the `debugger` and `target` domains to the `enable`,
`disable`, and `list` sub-commands when using InstrumentationRuntime
plugins. Previously the sub-commands accepted the `--domain` flag with
these domains but would error on all domains except `global`.

In the future we may want to generalize this to support other plugin
types but for now it makes sense to restrict to just
InstrumentationRuntime plugins.

When using the `enable` and `disable` sub-commands with
InstrumentationRuntime plugins the behavior for the different domains
is as follows:

* `global` (the default) - The global enablement flag (stored in the
  relevant `InstrumentationRuntimeInstance` in the PluginManager) is
  updated. This flag decides whether the plugin is used in processes
  that are launched later. The plugin is also enabled/disabled in every
  alive process in every debugger.
* `debugger` - The plugin is enabled/disabled in every alive process in the
  current debugger. The global enablement flag is not changed. It is an error
  if the debugger has no targets or no alive processes.
* `target` - The plugin is enabled/disabled in the process of the
  currently selected target. The global enablement flag is not changed.
  It is an error if there is no selected target or its process is not
  alive.

When using the `list` sub-command with InstrumentationRuntime plugins
the behavior for the different domains is as follows:

* `global` (the default) - Lists the global enablement flags. This
  preserves the existing behavior.
* `debugger` - The command is disallowed because there's currently no
  enablement state stored per debugger.
* `target` - Lists whether the plugin is enabled in the process of the
  currently selected target.

Other plugin namespaces still only support the `global` domain.

The enablement of a plugin in a process is represented by whether the
process has an instance of the plugin in its `m_instrumentation_runtimes`
map:

* Disabling a plugin in a process destroys the instance. The plugin
  destructors call `Deactivate()` (which removes their breakpoints) so
  destroying the instance deactivates the plugin. A null entry is stored in the map rather
  than removing the entry because `InstrumentationRuntime::ModulesDidLoad()`
  creates instances of globally enabled plugins that have no entry in the
  map. Without the null entry a plugin that is disabled in a process (but
  still enabled globally) would be re-created the next time a module is
  loaded (e.g. via `dlopen()`).
* Enabling a plugin in a process creates a new instance (if one doesn't
  already exist) and gives it the modules that are currently loaded so
  it can activate. If its runtime library isn't loaded yet the plugin
  will try to activate again when more modules are loaded.

`SBThread::GetStopReasonExtendedBacktraces()` now checks that the
process has an instance of the instrumentation runtime because the
plugin may have been disabled since the process stopped.

This design is **not** ideal. Using the `debugger` or `target` domains
only affects processes that are alive when the command is run. The
change isn't remembered for processes launched later (e.g. creating a
new target in the debugger). This is a direct result of trying to keep
the notion of a global domain around to avoid changing too much in one
patch set.

I think the directions we should take in future patches are:

* Move default enablement of InstrumentationRuntime plugins into
  `Debugger` instances.
* Enabling/disabling InstrumentationRuntime plugins in the `debugger`
  domain would then modify the "default enablement" of the plugins for
  that debugger instance as well as enabling/disabling the plugins in
  any alive processes.
* Remove support for the `global` domain for InstrumentationRuntime
  plugins because it would then have no meaning.
* Add a distinction between changing the plugin enablement for next
  process launch vs currently alive targets.

Test cases for the UBSan and BoundsSafety instrumentation plugins are
included. BoundsSafety is included because fixing the behavior for this
plugin is my primary goal. However, because Clang support for
`-fbounds-safety` is not fully upstream yet those tests don't run
upstream. The UBSan instrumentation plugin tests do run upstream so they
have been added to ensure there is upstream coverage of the new
behavior in this patch.

rdar://167725878

Assisted-by: Claude Code
---
 lldb/include/lldb/Core/PluginManager.h        |  28 +-
 .../Interpreter/CommandOptionArgumentTable.h  |   6 +-
 lldb/include/lldb/Target/Process.h            |  18 +
 .../Python/lldbsuite/test/lldbtest.py         |  38 ++
 lldb/source/API/SBThread.cpp                  |   9 +-
 lldb/source/Commands/CommandObjectPlugin.cpp  |  73 ++-
 lldb/source/Commands/Options.td               |  10 +-
 lldb/source/Core/PluginManager.cpp            | 198 +++++-
 lldb/source/Target/Process.cpp                |  75 ++-
 .../ubsan/plugin_enable_disable/Makefile      |  18 +
 .../TestUbsanPluginEnableDisable.py           | 575 ++++++++++++++++++
 .../ubsan/plugin_enable_disable/dylib.c       |   9 +
 .../ubsan/plugin_enable_disable/main.c        |  61 ++
 .../API/lang/BoundsSafety/soft_trap/Makefile  |  14 +
 .../TestBoundsSafetyInstrumentationPlugin.py  | 561 ++++++++++++++++-
 .../API/lang/BoundsSafety/soft_trap/dylib.c   |  14 +
 .../API/lang/BoundsSafety/soft_trap/main.c    |  59 +-
 ...enable-disable-domain-flag-one-target.test | 119 ++++
 ...nable-disable-domain-flag-two-targets.test | 171 ++++++
 ...and-plugin-enable-disable-domain-flag.test |  25 +-
 .../command-plugin-list-domain-flag.test      |  61 +-
 21 files changed, 2073 insertions(+), 69 deletions(-)
 create mode 100644 lldb/test/API/functionalities/ubsan/plugin_enable_disable/Makefile
 create mode 100644 lldb/test/API/functionalities/ubsan/plugin_enable_disable/TestUbsanPluginEnableDisable.py
 create mode 100644 lldb/test/API/functionalities/ubsan/plugin_enable_disable/dylib.c
 create mode 100644 lldb/test/API/functionalities/ubsan/plugin_enable_disable/main.c
 create mode 100644 lldb/test/API/lang/BoundsSafety/soft_trap/dylib.c
 create mode 100644 lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-one-target.test
 create mode 100644 lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-two-targets.test

diff --git a/lldb/include/lldb/Core/PluginManager.h b/lldb/include/lldb/Core/PluginManager.h
index bda18f0edadf70..81cb71e74622fe 100644
--- a/lldb/include/lldb/Core/PluginManager.h
+++ b/lldb/include/lldb/Core/PluginManager.h
@@ -81,7 +81,7 @@ struct RegisteredPluginInfo {
 using GetPluginInfo = std::function<llvm::SmallVector<RegisteredPluginInfo>()>;
 using SetPluginEnabledGlobalDomain = std::function<bool(llvm::StringRef, bool)>;
 using SetPluginEnabledAllDomains = std::function<llvm::Error(
-    llvm::StringRef, bool, Debugger &, lldb::PluginDomainKind)>;
+    llvm::StringRef, bool, Debugger &, lldb::TargetSP, lldb::PluginDomainKind)>;
 class PluginNamespace {
 public:
   static constexpr uint8_t kAllDomains = lldb::ePluginDomainKindGlobal |
@@ -232,10 +232,19 @@ class PluginManager {
   //       ...
   //    }
   //
+  // If querying the enablement of a plugin in \p domain fails then the
+  // plugin's entry has an "error" key containing the error message instead
+  // of the "enabled" key.
+  //
   // If pattern is given it will be used to filter the plugins that are
   // are returned. The pattern filters the plugin names using the
   // PluginManager::MatchPluginName() function.
-  static llvm::json::Object GetJSON(llvm::StringRef pattern = "");
+  static llvm::json::Object
+  GetJSON(llvm::StringRef pattern = "",
+          lldb::DebuggerSP requesting_debugger = nullptr,
+          lldb::TargetSP selected_target = nullptr,
+          lldb::PluginDomainKind domain =
+              lldb::PluginDomainKind::ePluginDomainKindGlobal);
 
   // Return true if the pattern matches the plugin name.
   //
@@ -248,6 +257,10 @@ class PluginManager {
                               const PluginNamespace &plugin_ns,
                               const RegisteredPluginInfo &plugin);
 
+  static llvm::Expected<bool> IsPluginEnabled(
+      const PluginNamespace &plugin_ns, const RegisteredPluginInfo &plugin,
+      lldb::TargetSP selected_target, lldb::PluginDomainKind domain);
+
   // ABI
   static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description,
                              ABICreateInstance create_callback);
@@ -881,10 +894,13 @@ class PluginManager {
   static llvm::SmallVector<RegisteredPluginInfo>
   GetInstrumentationRuntimePluginInfo();
   static llvm::StringRef PluginDomainKindToStr(lldb::PluginDomainKind kind);
-  static llvm::Error
-  SetInstrumentationRuntimePluginEnabled(llvm::StringRef name, bool enable,
-                                         Debugger &requesting_debugger,
-                                         lldb::PluginDomainKind domain);
+  static llvm::Error SetInstrumentationRuntimePluginEnabled(
+      llvm::StringRef name, bool enable, Debugger &requesting_debugger,
+      lldb::TargetSP selected_target, lldb::PluginDomainKind domain);
+  static llvm::Expected<bool>
+  IsInstrumentationRuntimePluginEnabled(llvm::StringRef name,
+                                        lldb::TargetSP target,
+                                        lldb::PluginDomainKind domain);
 
   static llvm::SmallVector<RegisteredPluginInfo> GetJITLoaderPluginInfo();
   static bool SetJITLoaderPluginEnabled(llvm::StringRef name, bool enable);
diff --git a/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h b/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h
index 3f1a122f967cd8..a0a4b1c47a7dd0 100644
--- a/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h
+++ b/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h
@@ -179,8 +179,10 @@ static constexpr OptionEnumValueElement g_plugin_domain_values[] = {
     {lldb::ePluginDomainKindGlobal, "global",
      "Apply to all debugger instances."},
     {lldb::ePluginDomainKindDebugger, "debugger",
-     "Apply to the current debugger instance."},
-    {lldb::ePluginDomainKindTarget, "target", "Apply to the current target."},
+     "Apply to the processes that are alive in the current debugger "
+     "instance."},
+    {lldb::ePluginDomainKindTarget, "target",
+     "Apply to the process of the current target."},
 };
 
 static constexpr OptionEnumValueElement g_resolver_mask_values[] = {
diff --git a/lldb/include/lldb/Target/Process.h b/lldb/include/lldb/Target/Process.h
index 226c58034dd655..06cae7070e1dc0 100644
--- a/lldb/include/lldb/Target/Process.h
+++ b/lldb/include/lldb/Target/Process.h
@@ -2731,6 +2731,21 @@ void PruneThreadPlans();
   lldb::InstrumentationRuntimeSP
   GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
 
+  /// Enable or disable the instrumentation runtime plugin \p irt in this
+  /// process.
+  ///
+  /// Disabling destroys this process's instance of the plugin, which
+  /// deactivates it. Enabling creates a new instance of the plugin (if one
+  /// doesn't already exist) and gives it a chance to activate using the
+  /// modules that are currently loaded.
+  llvm::Error
+  SetInstrumentationRuntimeEnabled(lldb::InstrumentationRuntimeType irt,
+                                   bool enabled);
+
+  /// \return true if this process has an instance of the instrumentation
+  /// runtime plugin \p irt.
+  bool InstrumentationRuntimeIsEnabled(lldb::InstrumentationRuntimeType irt);
+
   /// Try to fetch the module specification for a module with the given file
   /// name and architecture. Process sub-classes have to override this method
   /// if they support platforms where the Platform object can't get the module
@@ -3561,6 +3576,9 @@ void PruneThreadPlans();
                         /// with an explicit call to Kill or Detach?
   LanguageRuntimeCollection m_language_runtimes;
   std::recursive_mutex m_language_runtimes_mutex;
+  /// The instrumentation runtime plugin instances for this process. A null
+  /// entry means the plugin has been disabled in this process. The entry is
+  /// kept so that a new instance isn't created when modules are loaded.
   InstrumentationRuntimeCollection m_instrumentation_runtimes;
   std::unique_ptr<NextEventAction> m_next_event_action_up;
   std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
diff --git a/lldb/packages/Python/lldbsuite/test/lldbtest.py b/lldb/packages/Python/lldbsuite/test/lldbtest.py
index eb40bef63a5b00..2e29c1e3a53553 100644
--- a/lldb/packages/Python/lldbsuite/test/lldbtest.py
+++ b/lldb/packages/Python/lldbsuite/test/lldbtest.py
@@ -1986,6 +1986,44 @@ def get_stats(self, options=None):
         metrics_json = return_obj.GetOutput()
         return json.loads(metrics_json)
 
+    def plugin_is_enabled(
+        self, namespace: str, name: str, domain: str = "global", debugger=None
+    ):
+        assert domain in {"global", "debugger", "target"}
+        if debugger is None:
+            debugger = self.dbg
+        interp = debugger.GetCommandInterpreter()
+        result = lldb.SBCommandReturnObject()
+        cmd = f"plugin list --json --domain {domain} {namespace}.{name}"
+        interp.HandleCommand(cmd, result)
+        if not result.Succeeded():
+            raise Exception(f'Failed to run "{cmd}": {result.GetError()}')
+        output = result.GetOutput()
+        # Parse output like
+        # {
+        #   "instrumentation-runtime": [
+        #     {
+        #       "enabled": true,
+        #       "name": "BoundsSafety"
+        #     }
+        #   ]
+        # }
+        parsed_json = json.loads(output)
+        if not isinstance(parsed_json, dict):
+            raise TypeError(f"{parsed_json} is not a dict")
+        namespace_data = parsed_json.get(namespace)
+        if not isinstance(namespace_data, list):
+            raise TypeError(f"{namespace_data} is not a list")
+        for entry in namespace_data:
+            if not isinstance(entry, dict):
+                continue
+            if entry.get("name") == name:
+                enabled = entry.get("enabled")
+                if not isinstance(enabled, bool):
+                    raise TypeError("not bool")
+                return enabled
+        raise Exception(f'Plugin "{namespace}.{name}" not found in output of "{cmd}"')
+
 
 # Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
 # We change the test methods to create a new test method for each test for each debug info we are
diff --git a/lldb/source/API/SBThread.cpp b/lldb/source/API/SBThread.cpp
index e8699d81b3658c..e4d9190c5dd909 100644
--- a/lldb/source/API/SBThread.cpp
+++ b/lldb/source/API/SBThread.cpp
@@ -235,8 +235,13 @@ SBThread::GetStopReasonExtendedBacktraces(InstrumentationRuntimeType type) {
   if (!info)
     return threads;
 
-  threads = process_sp->GetInstrumentationRuntime(type)
-                ->GetBacktracesFromExtendedStopInfo(info);
+  // The instrumentation runtime might have been disabled since the stop.
+  InstrumentationRuntimeSP runtime_sp =
+      process_sp->GetInstrumentationRuntime(type);
+  if (!runtime_sp)
+    return threads;
+
+  threads = runtime_sp->GetBacktracesFromExtendedStopInfo(info);
   return threads;
 }
 
diff --git a/lldb/source/Commands/CommandObjectPlugin.cpp b/lldb/source/Commands/CommandObjectPlugin.cpp
index 396910abfb8b8c..ca3fbb2914d170 100644
--- a/lldb/source/Commands/CommandObjectPlugin.cpp
+++ b/lldb/source/Commands/CommandObjectPlugin.cpp
@@ -87,6 +87,7 @@ static int ActOnMatchingPlugins(
 int SetEnableOnMatchingPlugins(const llvm::StringRef &pattern,
                                CommandReturnObject &result, bool enabled,
                                Debugger &requesting_debugger,
+                               lldb::TargetSP selected_target,
                                PluginDomainKind domain) {
   return ActOnMatchingPlugins(
       pattern, [&](const PluginNamespace &plugin_namespace,
@@ -136,7 +137,8 @@ int SetEnableOnMatchingPlugins(const llvm::StringRef &pattern,
           }
           assert(plugin_namespace.GetSetEnabledAllDomainsFn().has_value());
           llvm::Error error = (*plugin_namespace.GetSetEnabledAllDomainsFn())(
-              plugin.name, enabled, requesting_debugger, domain);
+              plugin.name, enabled, requesting_debugger, selected_target,
+              domain);
 
           if (error) {
             result.AppendErrorWithFormatv("failed to {} plugin {}.{}: {}",
@@ -274,34 +276,55 @@ List only the plugin 'foo' matching a fully qualified name exactly
       for (size_t i = 0; i < argc; ++i)
         patterns.push_back(command[i].ref());
 
+    Debugger &requesting_debugger = GetDebugger();
+    TargetSP selected_target = GetCommandInterpreter().GetSelectedTarget();
     if (m_options.m_json_format)
-      OutputJsonFormat(patterns, result, GetDebugger(), m_options.m_domain);
+      OutputJsonFormat(patterns, result, requesting_debugger, selected_target,
+                       m_options.m_domain);
     else
-      OutputTextFormat(patterns, result, GetDebugger(), m_options.m_domain);
+      OutputTextFormat(patterns, result, requesting_debugger, selected_target,
+                       m_options.m_domain);
   }
 
 private:
   void OutputJsonFormat(const std::vector<llvm::StringRef> &patterns,
                         CommandReturnObject &result,
                         Debugger &requesting_debugger,
+                        lldb::TargetSP selected_target,
                         PluginDomainKind domain) {
-    if (domain != PluginDomainKind::ePluginDomainKindGlobal) {
-      result.AppendErrorWithFormatv(
-          "{} domain is not supported",
-          PluginManager::PluginDomainKindToStr(domain));
-      return;
-    }
-
     llvm::json::Object obj;
     bool found_empty = false;
     for (const llvm::StringRef pattern : patterns) {
-      llvm::json::Object pat_obj = PluginManager::GetJSON(pattern);
+      llvm::json::Object pat_obj = PluginManager::GetJSON(
+          pattern, requesting_debugger.shared_from_this(), selected_target,
+          domain);
       if (pat_obj.empty()) {
         found_empty = true;
         result.AppendErrorWithFormat(
             "Found no matching plugins for pattern '%s'", pattern.data());
         break;
       }
+
+      // Report any errors querying plugin enablement as command errors. These
+      // are reported in the same order and format as the text output. The
+      // errors are also kept in the JSON output.
+      for (const PluginNamespace &plugin_ns :
+           PluginManager::GetPluginNamespaces()) {
+        const llvm::json::Array *plugins = pat_obj.getArray(plugin_ns.name);
+        if (!plugins)
+          continue;
+        for (const llvm::json::Value &plugin : *plugins) {
+          const llvm::json::Object *plugin_obj = plugin.getAsObject();
+          if (!plugin_obj)
+            continue;
+          if (std::optional<llvm::StringRef> error =
+                  plugin_obj->getString("error"))
+            result.AppendErrorWithFormatv(
+                "{0}.{1}: {2}", plugin_ns.name,
+                plugin_obj->getString("name").value_or("<missing>"), *error);
+        }
+      }
+
       for (auto &entry : pat_obj) {
         obj[entry.first] = std::move(entry.second);
       }
@@ -314,22 +337,27 @@ List only the plugin 'foo' matching a fully qualified name exactly
   void OutputTextFormat(const std::vector<llvm::StringRef> &patterns,
                         CommandReturnObject &result,
                         Debugger &requesting_debugger,
+                        lldb::TargetSP selected_target,
                         PluginDomainKind domain) {
-    if (domain != PluginDomainKind::ePluginDomainKindGlobal) {
-      result.AppendErrorWithFormatv(
-          "{} domain is not supported",
-          PluginManager::PluginDomainKindToStr(domain));
-      return;
-    }
-
     for (const llvm::StringRef pattern : patterns) {
       int num_matching = ActOnMatchingPlugins(
           pattern, [&](const PluginNamespace &plugin_namespace,
                        const std::vector<RegisteredPluginInfo> &plugins) {
             result.AppendMessage(plugin_namespace.name);
             for (auto &plugin : plugins) {
+              auto enabled = PluginManager::IsPluginEnabled(
+                  plugin_namespace, plugin, selected_target, domain);
+              if (llvm::Error E = enabled.takeError()) {
+                // Report the error and carry on so that the enablement of the
+                // other plugins is still reported. This uses the same format
+                // as the errors reported by `OutputJsonFormat()`.
+                result.AppendErrorWithFormatv(
+                    "{0}.{1}: {2}", plugin_namespace.name, plugin.name,
+                    llvm::toString(std::move(E)));
+                continue;
+              }
               result.AppendMessageWithFormatv("  {0} {1, -30} {2}",
-                                              plugin.enabled ? "[+]" : "[-]",
+                                              *enabled ? "[+]" : "[-]",
                                               plugin.name, plugin.description);
             }
           });
@@ -346,6 +374,7 @@ List only the plugin 'foo' matching a fully qualified name exactly
 
 static void DoPluginEnableDisable(Args &command, CommandReturnObject &result,
                                   bool enable, Debugger &requesting_debugger,
+                                  lldb::TargetSP selected_target,
                                   PluginDomainKind domain) {
   const char *name = enable ? "enable" : "disable";
   size_t argc = command.GetArgumentCount();
@@ -358,8 +387,8 @@ static void DoPluginEnableDisable(Args &command, CommandReturnObject &result,
 
   for (size_t i = 0; i < argc; ++i) {
     llvm::StringRef pattern = command[i].ref();
-    int num_matching = SetEnableOnMatchingPlugins(pattern, result, enable,
-                                                  requesting_debugger, domain);
+    int num_matching = SetEnableOnMatchingPlugins(
+        pattern, result, enable, requesting_debugger, selected_target, domain);
 
     if (num_matching == 0) {
       result.AppendErrorWithFormat(
@@ -440,6 +469,7 @@ class CommandObjectPluginEnable : public CommandObjectParsed {
 protected:
   void DoExecute(Args &command, CommandReturnObject &result) override {
     DoPluginEnableDisable(command, result, /*enable=*/true, GetDebugger(),
+                          GetCommandInterpreter().GetSelectedTarget(),
                           m_options.m_domain);
   }
 
@@ -470,6 +500,7 @@ class CommandObjectPluginDisable : public CommandObjectParsed {
 protected:
   void DoExecute(Args &command, CommandReturnObject &result) override {
     DoPluginEnableDisable(command, result, /*enable=*/false, GetDebugger(),
+                          GetCommandInterpreter().GetSelectedTarget(),
                           m_options.m_domain);
   }
 
diff --git a/lldb/source/Commands/Options.td b/lldb/source/Commands/Options.td
index 8c1944716b391e..4e8e64f7acdb5f 100644
--- a/lldb/source/Commands/Options.td
+++ b/lldb/source/Commands/Options.td
@@ -1282,14 +1282,20 @@ let Command = "plugin enable" in {
   def plugin_enable_domain : Option<"domain", "d">,
                              EnumArg<"PluginDomain">,
                              Desc<"The ${d}omain in which to enable the "
-                                  "matching plugins. Defaults to 'global'.">;
+                                  "matching plugins. Defaults to 'global'. "
+                                  "The 'debugger' and 'target' domains only "
+                                  "affect processes that are currently "
+                                  "alive.">;
 }
 
 let Command = "plugin disable" in {
   def plugin_disable_domain : Option<"domain", "d">,
                               EnumArg<"PluginDomain">,
                               Desc<"The ${d}omain in which to disable the "
-                                   "matching plugins. Defaults to 'global'.">;
+                                   "matching plugins. Defaults to 'global'. "
+                                   "The 'debugger' and 'target' domains only "
+                                   "affect processes that are currently "
+                                   "alive.">;
 }
 
 let Command = "process launch" in {
diff --git a/lldb/source/Core/PluginManager.cpp b/lldb/source/Core/PluginManager.cpp
index 92e70960338b5a..979d09d3a5c21e 100644
--- a/lldb/source/Core/PluginManager.cpp
+++ b/lldb/source/Core/PluginManager.cpp
@@ -16,6 +16,7 @@
 #include "lldb/Interpreter/ScriptInterpreter.h"
 #include "lldb/Symbol/SaveCoreOptions.h"
 #include "lldb/Target/Process.h"
+#include "lldb/Target/Target.h"
 #include "lldb/Utility/FileSpec.h"
 #include "lldb/Utility/Status.h"
 #include "lldb/Utility/StringList.h"
@@ -24,6 +25,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/DynamicLibrary.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorExtras.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/raw_ostream.h"
@@ -483,20 +485,33 @@ llvm::ArrayRef<PluginNamespace> PluginManager::GetPluginNamespaces() {
   return PluginNamespaces;
 }
 
-llvm::json::Object PluginManager::GetJSON(llvm::StringRef pattern) {
+llvm::json::Object PluginManager::GetJSON(llvm::StringRef pattern,
+                                          lldb::DebuggerSP requesting_debugger,
+                                          lldb::TargetSP selected_target,
+                                          lldb::PluginDomainKind domain) {
   llvm::json::Object plugin_stats;
 
   for (const PluginNamespace &plugin_ns : GetPluginNamespaces()) {
     llvm::json::Array namespace_stats;
 
     for (const RegisteredPluginInfo &plugin : plugin_ns.get_info()) {
-      if (MatchPluginName(pattern, plugin_ns, plugin)) {
-        llvm::json::Object plugin_json;
-        plugin_json.try_emplace("name", plugin.name);
-        plugin_json.try_emplace("enabled", plugin.enabled);
-        namespace_stats.emplace_back(std::move(plugin_json));
+      if (!MatchPluginName(pattern, plugin_ns, plugin))
+        continue;
+
+      llvm::json::Object plugin_json;
+      plugin_json.try_emplace("name", plugin.name);
+      llvm::Expected<bool> enabled =
+          IsPluginEnabled(plugin_ns, plugin, selected_target, domain);
+      if (enabled) {
+        plugin_json.try_emplace("enabled", *enabled);
+      } else {
+        // Record the error and carry on so that the enablement of the other
+        // plugins is still reported.
+        plugin_json.try_emplace("error", llvm::toString(enabled.takeError()));
       }
+      namespace_stats.emplace_back(std::move(plugin_json));
     }
+
     if (!namespace_stats.empty())
       plugin_stats.try_emplace(plugin_ns.name, std::move(namespace_stats));
   }
@@ -520,6 +535,31 @@ bool PluginManager::MatchPluginName(llvm::StringRef pattern,
   return pattern == qualified_name;
 }
 
+llvm::Expected<bool> PluginManager::IsPluginEnabled(
+    const PluginNamespace &plugin_ns, const RegisteredPluginInfo &plugin,
+    lldb::TargetSP selected_target, lldb::PluginDomainKind domain) {
+  switch (domain) {
+  case lldb::ePluginDomainKindGlobal:
+    return plugin.enabled;
+  case lldb::ePluginDomainKindDebugger:
+    return llvm::createStringErrorV(
+        "plugin namespace {0} does not support querying "
+        "enablement in the debugger domain",
+        plugin_ns.name);
+  case lldb::ePluginDomainKindTarget:
+    if (!plugin_ns.SupportsDomain(lldb::ePluginDomainKindTarget))
+      return llvm::createStringErrorV(
+          "plugin namespace {0} does not support querying "
+          "enablement in the target domain",
+          plugin_ns.name);
+    // Currently only instrumentation-runtime plugins support this domain.
+    assert(plugin_ns.name == "instrumentation-runtime");
+    return IsInstrumentationRuntimePluginEnabled(plugin.name, selected_target,
+                                                 domain);
+  }
+  llvm_unreachable("Unhandled domain");
+}
+
 template <typename Instance> class PluginInstances {
 public:
   ~PluginInstances() {
@@ -2641,16 +2681,146 @@ llvm::StringRef PluginManager::PluginDomainKindToStr(PluginDomainKind kind) {
   llvm_unreachable("unhandled PluginDomainKind");
 }
 
+/// Enable/disable the instrumentation runtime \p irt in every alive process in
+/// \p debugger. If \p report_missing_processes is true then an error is
+/// returned if \p debugger has no targets or no alive processes.
+static llvm::Error SetInstrumentationRuntimeEnabledInDebugger(
+    Debugger &debugger, lldb::InstrumentationRuntimeType irt, bool enable,
+    bool report_missing_processes) {
+  llvm::Error errors = llvm::Error::success();
+  bool found_targets = false;
+  bool found_alive_process = false;
+  for (const auto &target_sp : debugger.GetTargetList().Targets()) {
+    found_targets = true;
+    ProcessSP process_sp = target_sp->GetProcessSP();
+    if (!process_sp || !process_sp->IsAlive())
+      continue;
+    found_alive_process = true;
+    errors = llvm::joinErrors(
+        std::move(errors),
+        process_sp->SetInstrumentationRuntimeEnabled(irt, enable));
+  }
+
+  if (!report_missing_processes)
+    return errors;
+
+  if (!found_targets)
+    errors = llvm::joinErrors(
+        std::move(errors), llvm::createStringError("debugger has no targets"));
+  else if (!found_alive_process)
+    errors = llvm::joinErrors(
+        std::move(errors),
+        llvm::createStringError("no alive processes in debugger"));
+
+  return errors;
+}
+
 llvm::Error PluginManager::SetInstrumentationRuntimePluginEnabled(
     llvm::StringRef name, bool enable, Debugger &requesting_debugger,
-    PluginDomainKind domain) {
-  if (domain != lldb::ePluginDomainKindGlobal)
-    return llvm::createStringErrorV("{} domain is not supported",
-                                    PluginDomainKindToStr(domain));
-  if (!GetInstrumentationRuntimeInstances().SetInstanceEnabled(name, enable))
-    return llvm::createStringError("plugin could not be found");
-
-  return llvm::Error::success();
+    lldb::TargetSP selected_target, PluginDomainKind domain) {
+
+  auto GetInstrumentationRuntimeTy =
+      [&]() -> llvm::Expected<lldb::InstrumentationRuntimeType> {
+    auto type_cb = GetInstrumentationRuntimeInstances().GetTypeCallbackForName(
+        name, /*enabled_only=*/false);
+    if (!type_cb)
+      return llvm::createStringErrorV(
+          "Could not get InstrumentationRuntimeType for plugin {}", name);
+    return type_cb();
+  };
+
+  switch (domain) {
+  case lldb::ePluginDomainKindGlobal: {
+    // Update the global enablement flag
+    if (!GetInstrumentationRuntimeInstances().SetInstanceEnabled(name, enable))
+      return llvm::createStringErrorV("could not find plugin {}", name);
+    auto instrumentation_runtime_ty = GetInstrumentationRuntimeTy();
+    if (auto E = instrumentation_runtime_ty.takeError())
+      return E;
+
+    // Copy the list of debuggers so the debugger list mutex isn't held while
+    // enabling/disabling the plugin. Holding it can cause deadlock because
+    // activating a plugin may create a breakpoint which might call
+    // `Debugger::ReportProgress` which also tries to lock the mutex. Debuggers
+    // destroyed after the copy is made are kept alive by the copy. Debuggers
+    // created after the copy is made are not updated but the global enablement
+    // flag applies to any processes they create.
+    Debugger::DebuggerList debuggers;
+    for (const DebuggerSP &debugger_sp : Debugger::Debuggers())
+      debuggers.push_back(debugger_sp);
+
+    // Enable/disable the plugin in every alive process in every debugger.
+    llvm::Error errors = llvm::Error::success();
+    for (const DebuggerSP &debugger_sp : debuggers)
+      errors = llvm::joinErrors(std::move(errors),
+                                SetInstrumentationRuntimeEnabledInDebugger(
+                                    *debugger_sp, *instrumentation_runtime_ty,
+                                    enable,
+                                    /*report_missing_processes=*/false));
+    return errors;
+  }
+  case lldb::ePluginDomainKindDebugger: {
+    // Deliberately don't update the global enablement flag here.
+    auto instrumentation_runtime_ty = GetInstrumentationRuntimeTy();
+    if (auto E = instrumentation_runtime_ty.takeError())
+      return E;
+
+    // Enable/disable the plugin in every alive process in the requesting
+    // debugger.
+    return SetInstrumentationRuntimeEnabledInDebugger(
+        requesting_debugger, *instrumentation_runtime_ty, enable,
+        /*report_missing_processes=*/true);
+  }
+  case lldb::ePluginDomainKindTarget: {
+    // Deliberately don't update the global enablement flag here.
+    auto instrumentation_runtime_ty = GetInstrumentationRuntimeTy();
+    if (auto E = instrumentation_runtime_ty.takeError())
+      return E;
+
+    if (!selected_target)
+      return llvm::createStringError("no target is selected");
+    ProcessSP process_sp = selected_target->GetProcessSP();
+    if (!process_sp || !process_sp->IsAlive())
+      return llvm::createStringError(
+          "failed to find alive process for selected target");
+    return process_sp->SetInstrumentationRuntimeEnabled(
+        *instrumentation_runtime_ty, enable);
+  }
+  }
+  llvm_unreachable("Unhandled domain");
+}
+
+llvm::Expected<bool> PluginManager::IsInstrumentationRuntimePluginEnabled(
+    llvm::StringRef name, lldb::TargetSP target,
+    lldb::PluginDomainKind domain) {
+
+  switch (domain) {
+
+  case lldb::ePluginDomainKindGlobal:
+    if (auto instance = GetInstrumentationRuntimeInstances().GetInstanceForName(
+            name, /*enabled_only=*/false)) {
+      return instance->enabled;
+    }
+    return llvm::createStringErrorV("cannot find plugin {}", name);
+  case lldb::ePluginDomainKindDebugger:
+    // Not supported. Each process could have a different enablement setting
+    // so it doesn't make sense to return anything.
+    return llvm::createStringError("debugger domain is not supported");
+  case lldb::ePluginDomainKindTarget:
+    if (!target)
+      return llvm::createStringError("target not available");
+    ProcessSP process = target->GetProcessSP();
+    if (!process)
+      return llvm::createStringError("process not available");
+    auto type_cb = GetInstrumentationRuntimeInstances().GetTypeCallbackForName(
+        name, /*enabled_only=*/false);
+    if (!type_cb)
+      return llvm::createStringErrorV("cannot find plugin {} in process", name);
+    lldb::InstrumentationRuntimeType irt = type_cb();
+
+    return process->InstrumentationRuntimeIsEnabled(irt);
+  }
+  llvm_unreachable("Unhandled domain");
 }
 
 llvm::SmallVector<RegisteredPluginInfo>
diff --git a/lldb/source/Target/Process.cpp b/lldb/source/Target/Process.cpp
index ad2ae1a5b682f9..02318ab8d7ddae 100644
--- a/lldb/source/Target/Process.cpp
+++ b/lldb/source/Target/Process.cpp
@@ -6434,8 +6434,11 @@ void Process::ModulesDidLoad(ModuleList &module_list) {
   // them of the modified modules.
   InstrumentationRuntime::ModulesDidLoad(module_list, this,
                                          m_instrumentation_runtimes);
-  for (auto &runtime : m_instrumentation_runtimes)
-    runtime.second->ModulesDidLoad(module_list);
+  for (auto &runtime : m_instrumentation_runtimes) {
+    // A null entry means the plugin is disabled in this process.
+    if (runtime.second)
+      runtime.second->ModulesDidLoad(module_list);
+  }
 
   // Give the language runtimes a chance to be created before informing them of
   // the modified modules.
@@ -6522,6 +6525,74 @@ Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
     return (*pos).second;
 }
 
+llvm::Error
+Process::SetInstrumentationRuntimeEnabled(InstrumentationRuntimeType irt,
+                                          bool enabled) {
+  if (!IsAlive())
+    return llvm::createStringErrorV("process {} is not alive", GetID());
+
+  if (!enabled) {
+    InstrumentationRuntimeSP &runtime_sp = m_instrumentation_runtimes[irt];
+    // Destroy any instance of this plugin. We rely on the plugin's destructor
+    // being implicitly called here to deactivate the plugin (e.g. remove its
+    // breakpoints). That only happens if this map holds the only reference to
+    // the plugin.
+    assert((!runtime_sp || runtime_sp.use_count() == 1) &&
+           "instrumentation runtime plugin unexpectedly still referenced");
+    // FIXME: The plugins pass a raw `this` pointer as the baton for their
+    // breakpoint callbacks. If one of this plugin's breakpoint callbacks is
+    // running on another thread (e.g. the thread handling the stop event) when
+    // the plugin is disabled, destroying the plugin here causes a
+    // use-after-free.
+    //
+    // A null entry is stored rather than removing the entry so that
+    // `InstrumentationRuntime::ModulesDidLoad` doesn't create a new instance
+    // (e.g. after dlopen) if the plugin is still enabled globally.
+    runtime_sp = nullptr;
+    return llvm::Error::success();
+  }
+
+  // This process already has an instance of this plugin so it is already
+  // enabled.
+  if (GetInstrumentationRuntime(irt))
+    return llvm::Error::success();
+
+  // There's no instance of this plugin for this process so create one. This
+  // can happen if the plugin was disabled in this process or if the plugin was
+  // never instantiated for this process because it was disabled globally (e.g.
+  // `plugin disable instrumentation-runtime.*` in .lldbinit).
+
+  // Create the plugin by finding its create callback and calling it.
+  lldb::InstrumentationRuntimeSP new_plugin = nullptr;
+  for (auto &cbs : PluginManager::GetInstrumentationRuntimeCallbacks(
+           /*enabled_only=*/false)) {
+    InstrumentationRuntimeType other_irt = cbs.get_type_callback();
+    if (other_irt != irt)
+      continue;
+
+    new_plugin = cbs.create_callback(shared_from_this());
+    break;
+  }
+  if (!new_plugin)
+    return llvm::createStringError("failed to create new instance of plugin");
+
+  m_instrumentation_runtimes[irt] = new_plugin;
+
+  // Pretend the modules currently loaded in the target were just loaded to
+  // give the new plugin a chance to activate. If the plugin's runtime isn't
+  // loaded yet the plugin will try to activate again when more modules are
+  // loaded.
+  ModuleList module_list(GetTarget().GetImages());
+  new_plugin->ModulesDidLoad(module_list);
+  return llvm::Error::success();
+}
+
+bool Process::InstrumentationRuntimeIsEnabled(
+    lldb::InstrumentationRuntimeType irt) {
+  // The plugin is enabled if and only if this process has an instance of it.
+  return GetInstrumentationRuntime(irt) != nullptr;
+}
+
 bool Process::GetModuleSpec(const FileSpec &module_file_spec,
                             const ArchSpec &arch, ModuleSpec &module_spec) {
   module_spec.Clear();
diff --git a/lldb/test/API/functionalities/ubsan/plugin_enable_disable/Makefile b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/Makefile
new file mode 100644
index 00000000000000..dda6c56a0b8895
--- /dev/null
+++ b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/Makefile
@@ -0,0 +1,18 @@
+C_SOURCES := main.c
+CFLAGS_EXTRAS := -fsanitize=undefined -g
+
+a.out: lib_dylib_with_ubsan_issue
+
+include Makefile.rules
+
+# Compile the directory containing the dylib into the executable so that
+# dlopen() can find the dylib regardless of the working directory. This isn't
+# needed on Windows which searches the executable's directory for DLLs.
+ifneq "$(OS)" "Windows_NT"
+CFLAGS += -DDYLIB_DIR='"$(BUILDDIR)"'
+endif
+
+lib_dylib_with_ubsan_issue:
+	"$(MAKE)" -f $(MAKEFILE_RULES) \
+		DYLIB_ONLY=YES DYLIB_C_SOURCES=dylib.c DYLIB_NAME=dylib_with_ubsan_issue \
+		CFLAGS_EXTRAS="-fsanitize=undefined -g"
diff --git a/lldb/test/API/functionalities/ubsan/plugin_enable_disable/TestUbsanPluginEnableDisable.py b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/TestUbsanPluginEnableDisable.py
new file mode 100644
index 00000000000000..8f18169efa16be
--- /dev/null
+++ b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/TestUbsanPluginEnableDisable.py
@@ -0,0 +1,575 @@
+"""
+Tests enabling and disabling the UndefinedBehaviorSanitizer instrumentation
+runtime plugin during a debug session.
+"""
+
+import lldb
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test.decorators import *
+import lldbsuite.test.lldbutil as lldbutil
+
+
+class UbsanPluginEnableDisableTestCase(TestBase):
+    def setUp(self):
+        TestBase.setUp(self)
+        self.line_first_ubsan_issue = line_number("main.c", "// first ubsan issue")
+        self.line_second_ubsan_issue = line_number("main.c", "// second ubsan issue")
+        self.line_third_ubsan_issue = line_number("main.c", "// third ubsan issue")
+        self.line_fourth_ubsan_issue = line_number("main.c", "// fourth ubsan issue")
+
+    def ubsan_plugin_is_enabled(self, domain: str, debugger=None):
+        return self.plugin_is_enabled(
+            "instrumentation-runtime",
+            "UndefinedBehaviorSanitizer",
+            domain=domain,
+            debugger=debugger,
+        )
+
+    def check_stopped_at_ubsan_issue(self, line_num, process=None):
+        if process is None:
+            process = self.dbg.GetSelectedTarget().process
+        thread = process.GetSelectedThread()
+        stop_reason = thread.GetStopReason()
+        self.assertStopReason(stop_reason, lldb.eStopReasonInstrumentation)
+        self.assertIn("__ubsan_on_report", thread.GetFrameAtIndex(0).GetFunctionName())
+        backtraces = thread.GetStopReasonExtendedBacktraces(
+            lldb.eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer
+        )
+        self.assertEqual(backtraces.GetSize(), 1)
+
+        # Check that we stopped at the expected line somewhere in the stacktrace
+        found = False
+        for i in range(thread.GetNumFrames()):
+            frame = thread.GetFrameAtIndex(i)
+            if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c":
+                if frame.GetLineEntry().GetLine() == line_num:
+                    found = True
+        self.assertTrue(found)
+
+    def check_stopped_at_breakpoint(self, func_name: str, process=None):
+        if process is None:
+            process = self.dbg.GetSelectedTarget().process
+        thread = process.GetSelectedThread()
+        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+        self.assertEqual(thread.GetSelectedFrame().GetFunctionName(), func_name)
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @no_debug_info_test
+    def test_disable_plugin_after_hit(self):
+        """Test that disabling the UBSan plugin mid-session prevents further
+        instrumentation stops."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+
+        self.runCmd("run")
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+        process = self.dbg.GetSelectedTarget().process
+
+        # We should have stopped on the first UBSan issue.
+        self.check_stopped_at_ubsan_issue(self.line_first_ubsan_issue)
+
+        # Disable the UBSan plugin for this target
+        self.runCmd(
+            "plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+        )
+        self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+        # Globally the plugin is still marked as enabled
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+        # Continue. The remaining UBSan issues should not cause
+        # instrumentation stops and the process should exit cleanly.
+        process.Continue()
+        self.assertEqual(process.GetState(), lldb.eStateExited)
+        self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @no_debug_info_test
+    def test_enable_plugin_after_disable(self):
+        """Test that disabling the UBSan plugin before launch prevents
+        instrumentation stops, and re-enabling it mid-session restores them."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+
+        try:
+            # Disable the UBSan plugin globally before launching the process so
+            # that it isn't loaded when the process starts.
+            self.runCmd(
+                "plugin disable instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="global"))
+
+            # Set a breakpoint on test_breakpoint which is called just before
+            # the third UBSan issue.
+            bp = target.BreakpointCreateByName("test_breakpoint")
+            self.assertTrue(bp.GetNumLocations() > 0)
+
+            self.runCmd("run")
+
+            process = self.dbg.GetSelectedTarget().process
+            thread = process.GetSelectedThread()
+            frame = thread.GetSelectedFrame()
+
+            # We should have skipped the first two UBSan issues and stopped at
+            # the test_breakpoint function.
+            stop_reason = thread.GetStopReason()
+            self.assertStopReason(stop_reason, lldb.eStopReasonBreakpoint)
+            self.assertIn("test_breakpoint", frame.GetFunctionName())
+
+            # Re-enable the UBSan plugin for the target
+            self.runCmd(
+                "plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="global"))
+
+            # Continue
+            process.Continue()
+
+            # We should now hit the third UBSan issue.
+            self.check_stopped_at_ubsan_issue(self.line_third_ubsan_issue)
+
+            # Continue. The plugin is still enabled so we should hit the fourth
+            # UBSan issue.
+            process.Continue()
+            self.check_stopped_at_ubsan_issue(self.line_fourth_ubsan_issue)
+
+            # Continue. The process should exit cleanly.
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+        finally:
+            # Now restore the global state to avoid affecting other tests.
+            self.runCmd(
+                "plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @no_debug_info_test
+    def test_enable_disable_enable(self):
+        """Test that the UBSan plugin can be toggled enable -> disable -> enable
+        in a single session."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+
+        # Set breakpoints on both breakpoint functions.
+        bp1 = target.BreakpointCreateByName("test_breakpoint")
+        self.assertTrue(bp1.GetNumLocations() > 0)
+        bp2 = target.BreakpointCreateByName("test_breakpoint_2")
+        self.assertTrue(bp2.GetNumLocations() > 0)
+
+        self.runCmd("run")
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+        process = self.dbg.GetSelectedTarget().process
+
+        # Step 1: ENABLED - we should hit the first UBSan issue.
+        self.check_stopped_at_ubsan_issue(self.line_first_ubsan_issue)
+
+        # Step 2: DISABLE the plugin for this target.
+        self.runCmd(
+            "plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+        )
+        self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+        # Continue. Should skip the second UBSan issue and hit the breakpoint.
+        process.Continue()
+        thread = process.GetSelectedThread()
+        frame = thread.GetSelectedFrame()
+        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+        self.assertIn("test_breakpoint", frame.GetFunctionName())
+
+        # Step 3: RE-ENABLE the plugin for this target.
+        self.runCmd(
+            "plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+        )
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+
+        # Continue. Should hit the third UBSan issue.
+        process.Continue()
+        self.check_stopped_at_ubsan_issue(self.line_third_ubsan_issue)
+
+        # Continue. Should hit test_breakpoint_2.
+        process.Continue()
+        thread = process.GetSelectedThread()
+        frame = thread.GetSelectedFrame()
+        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+        self.assertIn("test_breakpoint_2", frame.GetFunctionName())
+
+        # Continue. Should hit the fourth UBSan issue.
+        process.Continue()
+        self.check_stopped_at_ubsan_issue(self.line_fourth_ubsan_issue)
+
+        # Continue. The process should exit cleanly.
+        process.Continue()
+        self.assertEqual(process.GetState(), lldb.eStateExited)
+        self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @no_debug_info_test
+    def test_disable_enable_disable(self):
+        """Test that the UBSan plugin can be toggled disable -> enable -> disable
+        in a single session."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+
+        try:
+            # Disable the UBSan plugin globally before launching the process.
+            self.runCmd(
+                "plugin disable instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="global"))
+
+            # Set breakpoints on both breakpoint functions.
+            bp1 = target.BreakpointCreateByName("test_breakpoint")
+            self.assertTrue(bp1.GetNumLocations() > 0)
+            bp2 = target.BreakpointCreateByName("test_breakpoint_2")
+            self.assertTrue(bp2.GetNumLocations() > 0)
+
+            self.runCmd("run")
+
+            process = self.dbg.GetSelectedTarget().process
+            thread = process.GetSelectedThread()
+            frame = thread.GetSelectedFrame()
+
+            # Step 1: DISABLED - should skip issues 1 and 2, hit the breakpoint.
+            self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+            self.assertIn("test_breakpoint", frame.GetFunctionName())
+
+            # Step 2: ENABLE the plugin for this target.
+            self.runCmd(
+                "plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="global"))
+
+            # Continue. Should hit the third UBSan issue.
+            process.Continue()
+            self.check_stopped_at_ubsan_issue(self.line_third_ubsan_issue)
+
+            # Continue. Should hit test_breakpoint_2.
+            process.Continue()
+            thread = process.GetSelectedThread()
+            frame = thread.GetSelectedFrame()
+            self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+            self.assertIn("test_breakpoint_2", frame.GetFunctionName())
+
+            # Step 3: DISABLE the plugin again.
+            self.runCmd(
+                "plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+
+            # Continue. Should skip the fourth UBSan issue and exit cleanly.
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+        finally:
+            # Restore the global state to avoid affecting other tests.
+            self.runCmd(
+                "plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @skipIfRemote  # The dylib's directory compiled into a.out is a host path.
+    @no_debug_info_test
+    def test_disabled_plugin_stays_disabled_after_dlopen(self):
+        """Test that a disabled UBSan plugin is not re-activated when a new
+        shared library is loaded via dlopen (which triggers ModulesDidLoad)."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+
+        # Set a breakpoint on test_breakpoint_dlopen which is called just
+        # before the dlopen call.
+        bp = target.BreakpointCreateByName("test_breakpoint_dlopen")
+        self.assertTrue(bp.GetNumLocations() > 0)
+
+        # Set a breakpoint on test_breakpoint_after_dlopen which is called
+        # after calling into the dylib.
+        bp_after_dlopen = target.BreakpointCreateByName("test_breakpoint_after_dlopen")
+        self.assertTrue(bp_after_dlopen.GetNumLocations() > 0)
+
+        # Enable the dlopen test path via environment variable.
+        self.runCmd("settings set target.env-vars DO_DLOPEN=1")
+
+        self.runCmd("run")
+        self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+
+        process = self.dbg.GetSelectedTarget().process
+
+        # We should have stopped on the first UBSan issue.
+        self.check_stopped_at_ubsan_issue(self.line_first_ubsan_issue)
+
+        # Disable the UBSan plugin for this target.
+        self.runCmd(
+            "plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+        )
+        self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+
+        # Continue. The plugin is disabled so we should skip remaining ubsan
+        # issues and hit the breakpoint before dlopen.
+        process.Continue()
+        thread = process.GetSelectedThread()
+        frame = thread.GetSelectedFrame()
+        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+        self.assertIn("test_breakpoint_dlopen", frame.GetFunctionName())
+
+        # The plugin should still be disabled before dlopen.
+        self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+
+        # Continue past dlopen. Loading a new shared library triggers
+        # ModulesDidLoad which must not re-create the disabled plugin.
+        process.Continue()
+        thread = process.GetSelectedThread()
+        frame = thread.GetSelectedFrame()
+        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+        self.assertEqual(frame.GetFunctionName(), "test_breakpoint_after_dlopen")
+        self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+
+        # Make sure the dylib was actually loaded, otherwise this test isn't
+        # testing anything.
+        self.assertTrue(
+            any(
+                "dylib_with_ubsan_issue" in module.GetFileSpec().GetFilename()
+                for module in target.module_iter()
+            ),
+            "dylib was not loaded",
+        )
+
+        # Continue. The process should exit cleanly.
+        process.Continue()
+        self.assertEqual(process.GetState(), lldb.eStateExited)
+        self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @no_debug_info_test
+    def test_extended_backtraces_after_disable(self):
+        """Test that asking for the extended backtraces of an instrumentation
+        stop after the UBSan plugin has been disabled doesn't crash."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+
+        self.runCmd("run")
+        process = target.GetProcess()
+
+        # We should have stopped on the first UBSan issue. This also checks that
+        # the extended backtraces are available while the plugin is enabled.
+        self.check_stopped_at_ubsan_issue(self.line_first_ubsan_issue)
+
+        # Disable the UBSan plugin for this target. The thread is still stopped
+        # with the UBSan stop reason but the plugin instance that provides the
+        # extended backtraces no longer exists.
+        self.runCmd(
+            "plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer"
+        )
+        self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+
+        thread = process.GetSelectedThread()
+        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonInstrumentation)
+        backtraces = thread.GetStopReasonExtendedBacktraces(
+            lldb.eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer
+        )
+        self.assertEqual(backtraces.GetSize(), 0)
+
+        # Continue. The process should exit cleanly.
+        process.Continue()
+        self.assertEqual(process.GetState(), lldb.eStateExited)
+        self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @skipIfRemote  # The second debugger isn't connected to the remote platform.
+    @no_debug_info_test
+    def test_global_domain_affects_all_debuggers(self):
+        """Test that enabling/disabling the UBSan plugin in the global domain
+        affects alive processes in all debuggers, not just the one running the
+        command."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+        bp = target.BreakpointCreateByName("test_breakpoint_2")
+        self.assertTrue(bp.GetNumLocations() > 0)
+
+        other_dbg = lldb.SBDebugger.Create(False)
+        other_dbg.SetAsync(False)
+        other_process = None
+        try:
+            other_target = other_dbg.CreateTarget(exe)
+            self.assertTrue(other_target, VALID_TARGET)
+            self.registerSanitizerLibrariesWithTarget(other_target)
+            other_bp = other_target.BreakpointCreateByName("test_breakpoint_2")
+            self.assertTrue(other_bp.GetNumLocations() > 0)
+
+            # Launch a process in each debugger. Both should stop on the first
+            # UBSan issue.
+            self.runCmd("run")
+            self.check_stopped_at_ubsan_issue(self.line_first_ubsan_issue)
+            process = target.GetProcess()
+
+            other_process = other_target.LaunchSimple(
+                None, None, self.get_process_working_directory()
+            )
+            self.assertTrue(other_process, PROCESS_IS_VALID)
+            self.check_stopped_at_ubsan_issue(
+                self.line_first_ubsan_issue, process=other_process
+            )
+
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.ubsan_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Disable the plugin globally from the first debugger.
+            self.runCmd(
+                "plugin disable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="global"))
+
+            # The plugin should be disabled in the alive processes of both
+            # debuggers.
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+            self.assertFalse(
+                self.ubsan_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Continue both processes. The second and third UBSan issues should
+            # not cause instrumentation stops so both processes should stop at
+            # test_breakpoint_2.
+            process.Continue()
+            self.check_stopped_at_breakpoint("test_breakpoint_2")
+            other_process.Continue()
+            self.check_stopped_at_breakpoint("test_breakpoint_2", process=other_process)
+
+            # Enable the plugin globally from the first debugger. This creates
+            # and activates the plugin in the alive processes of both debuggers.
+            self.runCmd(
+                "plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.ubsan_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Continue both processes. Both should stop on the fourth UBSan
+            # issue.
+            process.Continue()
+            self.check_stopped_at_ubsan_issue(self.line_fourth_ubsan_issue)
+            other_process.Continue()
+            self.check_stopped_at_ubsan_issue(
+                self.line_fourth_ubsan_issue, process=other_process
+            )
+
+            # Continue both processes. They should exit cleanly.
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+
+            other_process.Continue()
+            self.assertEqual(other_process.GetState(), lldb.eStateExited)
+            self.assertEqual(other_process.GetExitStatus(), 0)
+        finally:
+            if other_process and other_process.IsValid():
+                other_process.Kill()
+            lldb.SBDebugger.Destroy(other_dbg)
+            # Restore the global state to avoid affecting other tests.
+            self.runCmd(
+                "plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+    @skipUnlessUndefinedBehaviorSanitizer
+    @skipIfRemote  # The second debugger isn't connected to the remote platform.
+    @no_debug_info_test
+    def test_debugger_domain_only_affects_requesting_debugger(self):
+        """Test that disabling the UBSan plugin in the debugger domain only
+        affects alive processes in the debugger running the command."""
+        self.build()
+        exe = self.getBuildArtifact("a.out")
+
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.registerSanitizerLibrariesWithTarget(target)
+
+        other_dbg = lldb.SBDebugger.Create(False)
+        other_dbg.SetAsync(False)
+        other_process = None
+        try:
+            other_target = other_dbg.CreateTarget(exe)
+            self.assertTrue(other_target, VALID_TARGET)
+            self.registerSanitizerLibrariesWithTarget(other_target)
+
+            # Launch a process in each debugger. Both should stop on the first
+            # UBSan issue.
+            self.runCmd("run")
+            self.check_stopped_at_ubsan_issue(self.line_first_ubsan_issue)
+            process = target.GetProcess()
+
+            other_process = other_target.LaunchSimple(
+                None, None, self.get_process_working_directory()
+            )
+            self.assertTrue(other_process, PROCESS_IS_VALID)
+            self.check_stopped_at_ubsan_issue(
+                self.line_first_ubsan_issue, process=other_process
+            )
+
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.ubsan_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Disable the plugin in the debugger domain of the first debugger.
+            self.runCmd(
+                "plugin disable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer"
+            )
+
+            # The plugin should only be disabled in the first debugger. The
+            # global enablement flag is not changed.
+            self.assertFalse(self.ubsan_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.ubsan_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+            self.assertTrue(self.ubsan_plugin_is_enabled(domain="global"))
+
+            # Continue the first debugger's process. The remaining UBSan issues
+            # should not cause instrumentation stops and the process should
+            # exit cleanly.
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+
+            # Continue the other debugger's process. The plugin is still
+            # enabled there so it should stop on the next UBSan issue.
+            other_process.Continue()
+            self.check_stopped_at_ubsan_issue(
+                self.line_second_ubsan_issue, process=other_process
+            )
+        finally:
+            if other_process and other_process.IsValid():
+                other_process.Kill()
+            lldb.SBDebugger.Destroy(other_dbg)
diff --git a/lldb/test/API/functionalities/ubsan/plugin_enable_disable/dylib.c b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/dylib.c
new file mode 100644
index 00000000000000..7130c053c5bab5
--- /dev/null
+++ b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/dylib.c
@@ -0,0 +1,9 @@
+#include <stdint.h>
+
+__attribute__((noinline, optnone)) int dylib_shift(void) { return 33; }
+
+int LLDB_DYLIB_EXPORT dylib_ubsan_issue(void) {
+  uint32_t x = 0;
+  x = x << dylib_shift(); // dylib ubsan issue
+  return x;
+}
diff --git a/lldb/test/API/functionalities/ubsan/plugin_enable_disable/main.c b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/main.c
new file mode 100644
index 00000000000000..d75a055d034906
--- /dev/null
+++ b/lldb/test/API/functionalities/ubsan/plugin_enable_disable/main.c
@@ -0,0 +1,61 @@
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef _WIN32
+#include <Windows.h>
+#define DLOPEN(name) LoadLibraryA(name)
+#define DLSYM(handle, name) GetProcAddress((HMODULE)handle, name)
+#define DLCLOSE(handle) FreeLibrary((HMODULE)handle)
+#define DYLIB_NAME "dylib_with_ubsan_issue.dll"
+#else
+#include <dlfcn.h>
+#define DLOPEN(name) dlopen(name, RTLD_NOW)
+#define DLSYM(handle, name) dlsym(handle, name)
+#define DLCLOSE(handle) dlclose(handle)
+#ifdef __APPLE__
+#define DYLIB_NAME "libdylib_with_ubsan_issue.dylib"
+#else
+#define DYLIB_NAME "libdylib_with_ubsan_issue.so"
+#endif
+#endif
+
+#ifdef _WIN32
+// Windows searches the executable's directory for DLLs.
+#define DYLIB_PATH DYLIB_NAME
+#else
+#define DYLIB_PATH DYLIB_DIR "/" DYLIB_NAME
+#endif
+
+__attribute__((noinline, optnone)) void test_breakpoint(void) {}
+__attribute__((noinline, optnone)) void test_breakpoint_2(void) {}
+__attribute__((noinline, optnone)) void test_breakpoint_dlopen(void) {}
+__attribute__((noinline, optnone)) void test_breakpoint_after_dlopen(void) {}
+
+__attribute__((noinline, optnone)) int shift(void) { return 33; }
+
+int main() {
+  uint32_t x = 0;
+
+  x = x << shift(); // first ubsan issue
+  x = x << shift(); // second ubsan issue
+  test_breakpoint();
+  x = x << shift(); // third ubsan issue
+  test_breakpoint_2();
+  x = x << shift(); // fourth ubsan issue
+
+  if (getenv("DO_DLOPEN")) {
+    // dlopen a shared library. This triggers ModulesDidLoad which could
+    // re-activate a disabled plugin.
+    test_breakpoint_dlopen();
+    void *handle = DLOPEN(DYLIB_PATH);
+    if (handle) {
+      int (*func)(void) = (int (*)(void))DLSYM(handle, "dylib_ubsan_issue");
+      if (func)
+        x += func(); // ubsan issue inside dylib
+      test_breakpoint_after_dlopen();
+      DLCLOSE(handle);
+    }
+  }
+
+  return 0;
+}
diff --git a/lldb/test/API/lang/BoundsSafety/soft_trap/Makefile b/lldb/test/API/lang/BoundsSafety/soft_trap/Makefile
index 5e83e7ac6d93f2..9ce35ae8bfe573 100644
--- a/lldb/test/API/lang/BoundsSafety/soft_trap/Makefile
+++ b/lldb/test/API/lang/BoundsSafety/soft_trap/Makefile
@@ -7,4 +7,18 @@ soft-trap-test-minimal: all
 soft-trap-test-with-str: CFLAGS_EXTRAS := -fbounds-safety -fbounds-safety-soft-traps=call-with-str
 soft-trap-test-with-str: all
 
+a.out: lib_dylib_with_soft_trap
+
 include Makefile.rules
+
+# Compile the directory containing the dylib into the executable so that
+# dlopen() can find the dylib regardless of the working directory. This isn't
+# needed on Windows which searches the executable's directory for DLLs.
+ifneq "$(OS)" "Windows_NT"
+CFLAGS += -DDYLIB_DIR='"$(BUILDDIR)"'
+endif
+
+lib_dylib_with_soft_trap:
+	"$(MAKE)" -f $(MAKEFILE_RULES) \
+		DYLIB_ONLY=YES DYLIB_C_SOURCES=dylib.c DYLIB_NAME=dylib_with_soft_trap \
+		CFLAGS_EXTRAS="$(CFLAGS_EXTRAS)"
diff --git a/lldb/test/API/lang/BoundsSafety/soft_trap/TestBoundsSafetyInstrumentationPlugin.py b/lldb/test/API/lang/BoundsSafety/soft_trap/TestBoundsSafetyInstrumentationPlugin.py
index 0f4150400e69ef..004cad65713282 100644
--- a/lldb/test/API/lang/BoundsSafety/soft_trap/TestBoundsSafetyInstrumentationPlugin.py
+++ b/lldb/test/API/lang/BoundsSafety/soft_trap/TestBoundsSafetyInstrumentationPlugin.py
@@ -15,6 +15,13 @@
 class BoundsSafetyTestSoftTrapPlugin(TestBase):
     SHARED_BUILD_TESTCASE = False
 
+    def setUp(self):
+        TestBase.setUp(self)
+        self.line_first_soft_trap = line_number("main.c", "// first soft trap:")
+        self.line_second_soft_trap = line_number("main.c", "// second soft trap:")
+        self.line_third_soft_trap = line_number("main.c", "// third soft trap:")
+        self.line_fourth_soft_trap = line_number("main.c", "// fourth soft trap:")
+
     def _check_stop_reason_impl(
         self,
         expected_soft_trap_func: str,
@@ -22,8 +29,10 @@ def _check_stop_reason_impl(
         expected_func_name: str,
         expected_file_name: str,
         expected_line_num: int,
+        process=None,
     ):
-        process = self.test_target.process
+        if process is None:
+            process = self.test_target.process
         thread = process.GetSelectedThread()
         self.assertEqual(
             thread.GetStopReason(),
@@ -47,7 +56,12 @@ def _check_stop_reason_impl(
         self.assertEqual(line, expected_line_num)
 
     def check_state_soft_trap_minimal(
-        self, stop_reason: str, func_name: str, file_name: str, line_num: int
+        self,
+        stop_reason: str,
+        func_name: str,
+        file_name: str,
+        line_num: int,
+        process=None,
     ):
         """
         Check the program state is as expected when hitting
@@ -59,6 +73,7 @@ def check_state_soft_trap_minimal(
             expected_func_name=func_name,
             expected_file_name=file_name,
             expected_line_num=line_num,
+            process=process,
         )
 
     def check_state_soft_trap_with_str(
@@ -76,6 +91,18 @@ def check_state_soft_trap_with_str(
             expected_line_num=line_num,
         )
 
+    def check_stopped_at_breakpoint(self, func_name: str, process=None):
+        if process is None:
+            process = self.test_target.process
+        thread = process.GetSelectedThread()
+        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+        self.assertEqual(thread.GetSelectedFrame().GetFunctionName(), func_name)
+
+    def bs_plugin_is_enabled(self, domain: str, debugger=None):
+        return self.plugin_is_enabled(
+            "instrumentation-runtime", "BoundsSafety", domain=domain, debugger=debugger
+        )
+
     # Skip the tests on Windows because they fail due to the stop reason
     # being `eStopReasonNon` instead of the expected
     # `eStopReasonInstrumentation`.
@@ -91,13 +118,15 @@ def test_call_minimal(self):
         self.runCmd("run")
 
         process = self.test_target.process
+        self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+        self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
 
         # First soft trap hit
         self.check_state_soft_trap_minimal(
             "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
             "main",
             "main.c",
-            7,
+            self.line_first_soft_trap,
         )
 
         process.Continue()
@@ -107,7 +136,7 @@ def test_call_minimal(self):
             "Soft Bounds check failed: indexing below lower bound in 'buffer[-1]'",
             "main",
             "main.c",
-            8,
+            self.line_second_soft_trap,
         )
 
         process.Continue()
@@ -126,13 +155,15 @@ def test_call_with_str(self):
         self.runCmd("run")
 
         process = self.test_target.process
+        self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+        self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
 
         # First soft trap hit
         self.check_state_soft_trap_with_str(
             "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
             "main",
             "main.c",
-            7,
+            self.line_first_soft_trap,
         )
 
         process.Continue()
@@ -142,9 +173,527 @@ def test_call_with_str(self):
             "Soft Bounds check failed: indexing below lower bound in 'buffer[-1]'",
             "main",
             "main.c",
-            8,
+            self.line_second_soft_trap,
         )
 
         process.Continue()
         self.assertEqual(process.GetState(), lldb.eStateExited)
         self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipIfWindows
+    @skipUnlessBoundsSafety
+    @no_debug_info_test
+    def test_call_minimal_enable_then_disable_plugin(self):
+        """
+        Test starting with the plugin enabled on code built with
+        -fbounds-safety-soft-traps=call-minimal and then later disable the
+        plugin
+        """
+        self.build(make_targets=["soft-trap-test-minimal"])
+        self.test_target = self.createTestTarget()
+
+        # Check the plugin is enabled before we run
+        self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+        self.runCmd("run")
+
+        process = self.test_target.process
+
+        # First soft trap hit
+        self.check_state_soft_trap_minimal(
+            "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
+            "main",
+            "main.c",
+            self.line_first_soft_trap,
+        )
+
+        # Disable the plugin on the target so we do not stop at the second soft trap
+        self.runCmd(
+            "plugin disable --domain target instrumentation-runtime.BoundsSafety"
+        )
+        self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+        self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+
+        process.Continue()
+        self.assertEqual(process.GetState(), lldb.eStateExited)
+        self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipIfWindows
+    @skipUnlessBoundsSafety
+    @no_debug_info_test
+    def test_call_minimal_disable_then_enable_plugin(self):
+        """
+        Test starting with the plugin disabled on code built with
+        -fbounds-safety-soft-traps=call-minimal and then later enable the
+        plugin
+        """
+        self.build(make_targets=["soft-trap-test-minimal"])
+        self.test_target = self.createTestTarget()
+
+        try:
+            # Disable the plugin so we do not stop at the first soft trap
+            self.runCmd("plugin disable instrumentation-runtime.BoundsSafety")
+            self.assertFalse(self.bs_plugin_is_enabled(domain="global"))
+
+            # Set a breakpoint on test_breakpoint which is called just before
+            # the last soft trap
+            bp = self.test_target.BreakpointCreateByName("test_breakpoint")
+            self.assertTrue(bp.GetNumLocations() > 0)
+            self.runCmd("run")
+            self.assertFalse(self.bs_plugin_is_enabled(domain="global"))
+            self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+
+            process = self.test_target.process
+            thread = process.GetSelectedThread()
+            frame = thread.GetSelectedFrame()
+
+            # We should have skipped the first soft trap and stopped at the
+            # test_breakpoint function.
+            stop_reason = thread.GetStopReason()
+            self.assertStopReason(stop_reason, lldb.eStopReasonBreakpoint)
+            self.assertIn("test_breakpoint", frame.GetFunctionName())
+
+            # Enable the plugin so we stop at the second soft trap
+            self.runCmd(
+                "plugin enable --domain target instrumentation-runtime.BoundsSafety"
+            )
+            self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+            self.assertFalse(self.bs_plugin_is_enabled(domain="global"))
+            process.Continue()
+
+            # Second soft trap hit
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing below lower bound in 'buffer[-1]'",
+                "main",
+                "main.c",
+                self.line_second_soft_trap,
+            )
+
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+        finally:
+            # Restore the global state to avoid affecting other tests
+            self.runCmd("plugin enable instrumentation-runtime.BoundsSafety")
+            self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+
+    @skipIfWindows
+    @skipUnlessBoundsSafety
+    @no_debug_info_test
+    def test_call_minimal_enable_disable_enable(self):
+        """
+        Test that the plugin can be toggled enable -> disable -> enable in a
+        single session on code built with
+        -fbounds-safety-soft-traps=call-minimal
+        """
+        self.build(make_targets=["soft-trap-test-minimal"])
+        self.test_target = self.createTestTarget()
+        self.runCmd("settings set target.env-vars DO_EXTRA_SOFT_TRAPS=1")
+
+        bp1 = self.test_target.BreakpointCreateByName("test_breakpoint")
+        self.assertTrue(bp1.GetNumLocations() > 0)
+        bp2 = self.test_target.BreakpointCreateByName("test_breakpoint_2")
+        self.assertTrue(bp2.GetNumLocations() > 0)
+
+        self.runCmd("run")
+        self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+        self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+
+        process = self.test_target.process
+
+        # Step 1: ENABLED - we should hit the first soft trap.
+        self.check_state_soft_trap_minimal(
+            "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
+            "main",
+            "main.c",
+            self.line_first_soft_trap,
+        )
+
+        # Continue. Should hit test_breakpoint.
+        process.Continue()
+        self.check_stopped_at_breakpoint("test_breakpoint")
+
+        # Step 2: DISABLE the plugin for this target.
+        self.runCmd(
+            "plugin disable --domain target instrumentation-runtime.BoundsSafety"
+        )
+        self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+        self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+
+        # Continue. Should skip the second and third soft traps and hit
+        # test_breakpoint_2.
+        process.Continue()
+        self.check_stopped_at_breakpoint("test_breakpoint_2")
+
+        # Step 3: RE-ENABLE the plugin for this target.
+        self.runCmd(
+            "plugin enable --domain target instrumentation-runtime.BoundsSafety"
+        )
+        self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+
+        # Continue. Should hit the fourth soft trap.
+        process.Continue()
+        self.check_state_soft_trap_minimal(
+            "Soft Bounds check failed: indexing below lower bound in 'buffer[-2]'",
+            "main",
+            "main.c",
+            self.line_fourth_soft_trap,
+        )
+
+        # Continue. The process should exit cleanly.
+        process.Continue()
+        self.assertEqual(process.GetState(), lldb.eStateExited)
+        self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipIfWindows
+    @skipUnlessBoundsSafety
+    @no_debug_info_test
+    def test_call_minimal_disable_enable_disable(self):
+        """
+        Test that the plugin can be toggled disable -> enable -> disable in a
+        single session on code built with
+        -fbounds-safety-soft-traps=call-minimal
+        """
+        self.build(make_targets=["soft-trap-test-minimal"])
+        self.test_target = self.createTestTarget()
+        self.runCmd("settings set target.env-vars DO_EXTRA_SOFT_TRAPS=1")
+
+        try:
+            # Disable the plugin globally before launching the process.
+            self.runCmd("plugin disable instrumentation-runtime.BoundsSafety")
+            self.assertFalse(self.bs_plugin_is_enabled(domain="global"))
+
+            bp1 = self.test_target.BreakpointCreateByName("test_breakpoint")
+            self.assertTrue(bp1.GetNumLocations() > 0)
+            bp2 = self.test_target.BreakpointCreateByName("test_breakpoint_2")
+            self.assertTrue(bp2.GetNumLocations() > 0)
+
+            self.runCmd("run")
+
+            process = self.test_target.process
+
+            # Step 1: DISABLED - should skip the first soft trap and hit
+            # test_breakpoint.
+            self.check_stopped_at_breakpoint("test_breakpoint")
+            self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+
+            # Step 2: ENABLE the plugin for this target.
+            self.runCmd(
+                "plugin enable --domain target instrumentation-runtime.BoundsSafety"
+            )
+            self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+            self.assertFalse(self.bs_plugin_is_enabled(domain="global"))
+
+            # Continue. Should hit the second soft trap.
+            process.Continue()
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing below lower bound in 'buffer[-1]'",
+                "main",
+                "main.c",
+                self.line_second_soft_trap,
+            )
+
+            # Continue. Should hit the third soft trap.
+            process.Continue()
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing above upper bound in 'buffer[3]'",
+                "main",
+                "main.c",
+                self.line_third_soft_trap,
+            )
+
+            # Continue. Should hit test_breakpoint_2.
+            process.Continue()
+            self.check_stopped_at_breakpoint("test_breakpoint_2")
+
+            # Step 3: DISABLE the plugin again.
+            self.runCmd(
+                "plugin disable --domain target instrumentation-runtime.BoundsSafety"
+            )
+            self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+
+            # Continue. Should skip the fourth soft trap and exit cleanly.
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+        finally:
+            # Restore the global state to avoid affecting other tests
+            self.runCmd("plugin enable instrumentation-runtime.BoundsSafety")
+            self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+
+    @skipIfWindows
+    @skipUnlessBoundsSafety
+    @skipIfRemote  # The dylib's directory compiled into a.out is a host path.
+    @no_debug_info_test
+    def test_call_minimal_disabled_plugin_stays_disabled_after_dlopen(self):
+        """
+        Test that a disabled plugin is not re-activated when a shared library
+        containing the soft trap runtime functions is loaded via dlopen (which
+        triggers ModulesDidLoad) on code built with
+        -fbounds-safety-soft-traps=call-minimal
+        """
+        self.build(make_targets=["soft-trap-test-minimal"])
+        self.test_target = self.createTestTarget()
+        self.runCmd("settings set target.env-vars DO_DLOPEN=1")
+
+        bp_dlopen = self.test_target.BreakpointCreateByName("test_breakpoint_dlopen")
+        self.assertTrue(bp_dlopen.GetNumLocations() > 0)
+        bp_after_dlopen = self.test_target.BreakpointCreateByName(
+            "test_breakpoint_after_dlopen"
+        )
+        self.assertTrue(bp_after_dlopen.GetNumLocations() > 0)
+
+        self.runCmd("run")
+        self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+
+        process = self.test_target.process
+
+        # First soft trap hit
+        self.check_state_soft_trap_minimal(
+            "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
+            "main",
+            "main.c",
+            self.line_first_soft_trap,
+        )
+
+        # Disable the plugin for this target.
+        self.runCmd(
+            "plugin disable --domain target instrumentation-runtime.BoundsSafety"
+        )
+        self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+
+        # Continue. The plugin is disabled so we should skip the second soft
+        # trap and hit the breakpoint before dlopen.
+        process.Continue()
+        self.check_stopped_at_breakpoint("test_breakpoint_dlopen")
+        self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+
+        # Continue past dlopen. Loading a shared library that contains the soft
+        # trap runtime functions triggers ModulesDidLoad. The plugin must stay
+        # disabled and not re-activate. If the plugin re-activates, we would
+        # stop on the soft trap inside the dylib instead of the breakpoint.
+        process.Continue()
+        self.check_stopped_at_breakpoint("test_breakpoint_after_dlopen")
+        self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+
+        # Make sure the dylib was actually loaded, otherwise this test isn't
+        # testing anything.
+        self.assertTrue(
+            any(
+                "dylib_with_soft_trap" in module.GetFileSpec().GetFilename()
+                for module in self.test_target.module_iter()
+            ),
+            "dylib was not loaded",
+        )
+
+        # Continue. The process should exit cleanly.
+        process.Continue()
+        self.assertEqual(process.GetState(), lldb.eStateExited)
+        self.assertEqual(process.GetExitStatus(), 0)
+
+    @skipIfWindows
+    @skipUnlessBoundsSafety
+    @skipIfRemote  # The second debugger isn't connected to the remote platform.
+    @no_debug_info_test
+    def test_call_minimal_global_domain_affects_all_debuggers(self):
+        """
+        Test that enabling/disabling the plugin in the global domain affects
+        alive processes in all debuggers, not just the one running the command,
+        on code built with -fbounds-safety-soft-traps=call-minimal
+        """
+        self.build(make_targets=["soft-trap-test-minimal"])
+        self.test_target = self.createTestTarget()
+        self.runCmd("settings set target.env-vars DO_EXTRA_SOFT_TRAPS=1")
+        bp = self.test_target.BreakpointCreateByName("test_breakpoint_2")
+        self.assertTrue(bp.GetNumLocations() > 0)
+        exe = self.getBuildArtifact("a.out")
+
+        other_dbg = lldb.SBDebugger.Create(False)
+        other_dbg.SetAsync(False)
+        other_process = None
+        try:
+            other_dbg.HandleCommand(
+                "settings set target.env-vars DO_EXTRA_SOFT_TRAPS=1"
+            )
+            other_target = other_dbg.CreateTarget(exe)
+            self.assertTrue(other_target, VALID_TARGET)
+            other_bp = other_target.BreakpointCreateByName("test_breakpoint_2")
+            self.assertTrue(other_bp.GetNumLocations() > 0)
+
+            # Launch a process in each debugger. Both should stop on the first
+            # soft trap.
+            self.runCmd("run")
+            process = self.test_target.process
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
+                "main",
+                "main.c",
+                self.line_first_soft_trap,
+            )
+
+            other_process = other_target.LaunchSimple(
+                None, None, self.get_process_working_directory()
+            )
+            self.assertTrue(other_process, PROCESS_IS_VALID)
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
+                "main",
+                "main.c",
+                self.line_first_soft_trap,
+                process=other_process,
+            )
+
+            self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.bs_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Disable the plugin globally from the first debugger.
+            self.runCmd(
+                "plugin disable --domain global instrumentation-runtime.BoundsSafety"
+            )
+            self.assertFalse(self.bs_plugin_is_enabled(domain="global"))
+
+            # The plugin should be disabled in the alive processes of both
+            # debuggers.
+            self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+            self.assertFalse(
+                self.bs_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Continue both processes. The second and third soft traps should
+            # not cause instrumentation stops so both processes should stop at
+            # test_breakpoint_2.
+            process.Continue()
+            self.check_stopped_at_breakpoint("test_breakpoint_2")
+            other_process.Continue()
+            self.check_stopped_at_breakpoint("test_breakpoint_2", process=other_process)
+
+            # Enable the plugin globally from the first debugger. This creates
+            # and activates the plugin in the alive processes of both debuggers.
+            self.runCmd(
+                "plugin enable --domain global instrumentation-runtime.BoundsSafety"
+            )
+            self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+            self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.bs_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Continue both processes. Both should stop on the fourth soft trap.
+            process.Continue()
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing below lower bound in 'buffer[-2]'",
+                "main",
+                "main.c",
+                self.line_fourth_soft_trap,
+            )
+            other_process.Continue()
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing below lower bound in 'buffer[-2]'",
+                "main",
+                "main.c",
+                self.line_fourth_soft_trap,
+                process=other_process,
+            )
+
+            # Continue both processes. They should exit cleanly.
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+
+            other_process.Continue()
+            self.assertEqual(other_process.GetState(), lldb.eStateExited)
+            self.assertEqual(other_process.GetExitStatus(), 0)
+        finally:
+            if other_process and other_process.IsValid():
+                other_process.Kill()
+            lldb.SBDebugger.Destroy(other_dbg)
+            # Restore the global state to avoid affecting other tests.
+            self.runCmd(
+                "plugin enable --domain global instrumentation-runtime.BoundsSafety"
+            )
+            self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+
+    @skipIfWindows
+    @skipUnlessBoundsSafety
+    @skipIfRemote  # The second debugger isn't connected to the remote platform.
+    @no_debug_info_test
+    def test_call_minimal_debugger_domain_only_affects_requesting_debugger(self):
+        """
+        Test that disabling the plugin in the debugger domain only affects
+        alive processes in the debugger running the command on code built with
+        -fbounds-safety-soft-traps=call-minimal
+        """
+        self.build(make_targets=["soft-trap-test-minimal"])
+        self.test_target = self.createTestTarget()
+        exe = self.getBuildArtifact("a.out")
+
+        other_dbg = lldb.SBDebugger.Create(False)
+        other_dbg.SetAsync(False)
+        other_process = None
+        try:
+            other_target = other_dbg.CreateTarget(exe)
+            self.assertTrue(other_target, VALID_TARGET)
+
+            # Launch a process in each debugger. Both should stop on the first
+            # soft trap.
+            self.runCmd("run")
+            process = self.test_target.process
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
+                "main",
+                "main.c",
+                self.line_first_soft_trap,
+            )
+
+            other_process = other_target.LaunchSimple(
+                None, None, self.get_process_working_directory()
+            )
+            self.assertTrue(other_process, PROCESS_IS_VALID)
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing above upper bound in 'buffer[2]'",
+                "main",
+                "main.c",
+                self.line_first_soft_trap,
+                process=other_process,
+            )
+
+            self.assertTrue(self.bs_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.bs_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+
+            # Disable the plugin in the debugger domain of the first debugger.
+            self.runCmd(
+                "plugin disable --domain debugger instrumentation-runtime.BoundsSafety"
+            )
+
+            # The plugin should only be disabled in the first debugger. The
+            # global enablement flag is not changed.
+            self.assertFalse(self.bs_plugin_is_enabled(domain="target"))
+            self.assertTrue(
+                self.bs_plugin_is_enabled(domain="target", debugger=other_dbg)
+            )
+            self.assertTrue(self.bs_plugin_is_enabled(domain="global"))
+
+            # Continue the first debugger's process. The second soft trap
+            # should not cause an instrumentation stop and the process should
+            # exit cleanly.
+            process.Continue()
+            self.assertEqual(process.GetState(), lldb.eStateExited)
+            self.assertEqual(process.GetExitStatus(), 0)
+
+            # Continue the other debugger's process. The plugin is still
+            # enabled there so it should stop on the second soft trap.
+            other_process.Continue()
+            self.check_state_soft_trap_minimal(
+                "Soft Bounds check failed: indexing below lower bound in 'buffer[-1]'",
+                "main",
+                "main.c",
+                self.line_second_soft_trap,
+                process=other_process,
+            )
+        finally:
+            if other_process and other_process.IsValid():
+                other_process.Kill()
+            lldb.SBDebugger.Destroy(other_dbg)
diff --git a/lldb/test/API/lang/BoundsSafety/soft_trap/dylib.c b/lldb/test/API/lang/BoundsSafety/soft_trap/dylib.c
new file mode 100644
index 00000000000000..3f58fece3a418d
--- /dev/null
+++ b/lldb/test/API/lang/BoundsSafety/soft_trap/dylib.c
@@ -0,0 +1,14 @@
+#include <ptrcheck.h>
+
+// The dylib can't link against the soft trap runtime functions in a.out so
+// give it its own copy. This also means that if a disabled BoundsSafety plugin
+// is wrongly re-created when this dylib is loaded, the new instance (which only
+// sees the newly loaded modules) finds a runtime here and activates.
+#include "mockSoftTrapRuntime.c"
+
+int LLDB_DYLIB_EXPORT dylib_soft_trap(void) {
+  int pad;
+  int buffer[] = {0, 1};
+  int pad2;
+  return buffer[2]; // dylib soft trap: access past upper bound
+}
diff --git a/lldb/test/API/lang/BoundsSafety/soft_trap/main.c b/lldb/test/API/lang/BoundsSafety/soft_trap/main.c
index 518afaaa02e8ca..7410e6337d057c 100644
--- a/lldb/test/API/lang/BoundsSafety/soft_trap/main.c
+++ b/lldb/test/API/lang/BoundsSafety/soft_trap/main.c
@@ -1,10 +1,65 @@
 #include <ptrcheck.h>
+#include <stdlib.h>
+
+#ifdef _WIN32
+#include <Windows.h>
+#define DLOPEN(name) LoadLibraryA(name)
+#define DLSYM(handle, name) GetProcAddress((HMODULE)handle, name)
+#define DLCLOSE(handle) FreeLibrary((HMODULE)handle)
+#define DYLIB_NAME "dylib_with_soft_trap.dll"
+#else
+#include <dlfcn.h>
+#define DLOPEN(name) dlopen(name, RTLD_NOW)
+#define DLSYM(handle, name) dlsym(handle, name)
+#define DLCLOSE(handle) dlclose(handle)
+#ifdef __APPLE__
+#define DYLIB_NAME "libdylib_with_soft_trap.dylib"
+#else
+#define DYLIB_NAME "libdylib_with_soft_trap.so"
+#endif
+#endif
+
+#ifdef _WIN32
+// Windows searches the executable's directory for DLLs.
+#define DYLIB_PATH DYLIB_NAME
+#else
+#define DYLIB_PATH DYLIB_DIR "/" DYLIB_NAME
+#endif
+
+__attribute__((noinline, optnone)) void test_breakpoint(void) {}
+__attribute__((noinline, optnone)) void test_breakpoint_2(void) {}
+__attribute__((noinline, optnone)) void test_breakpoint_dlopen(void) {}
+__attribute__((noinline, optnone)) void test_breakpoint_after_dlopen(void) {}
 
 int main(void) {
   int pad;
   int buffer[] = {0, 1};
   int pad2;
-  int tmp = buffer[2]; // access past upper bound
-  tmp = buffer[-1];    // access below lower bound
+  int tmp = buffer[2]; // first soft trap: access past upper bound
+  test_breakpoint();
+  tmp = buffer[-1]; // second soft trap: access below lower bound
+
+  if (getenv("DO_EXTRA_SOFT_TRAPS")) {
+    tmp = buffer[3]; // third soft trap: access past upper bound
+    test_breakpoint_2();
+    tmp = buffer[-2]; // fourth soft trap: access below lower bound
+  }
+
+  if (getenv("DO_DLOPEN")) {
+    // dlopen a shared library that contains the soft trap runtime functions.
+    // This triggers ModulesDidLoad which could re-activate a disabled plugin.
+    test_breakpoint_dlopen();
+    void *__unsafe_indexable handle = DLOPEN(DYLIB_PATH);
+    if (handle) {
+      typedef int (*dylib_func_t)(void);
+      dylib_func_t func =
+          __unsafe_forge_single(dylib_func_t, DLSYM(handle, "dylib_soft_trap"));
+      if (func)
+        tmp += func(); // soft trap inside dylib
+      test_breakpoint_after_dlopen();
+      DLCLOSE(handle);
+    }
+  }
+
   return 0;
 }
diff --git a/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-one-target.test b/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-one-target.test
new file mode 100644
index 00000000000000..e4b332fccf3280
--- /dev/null
+++ b/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-one-target.test
@@ -0,0 +1,119 @@
+# This test validates the --domain flag on the plugin enable and disable
+# commands when one target with an alive process exists.
+
+# RUN: %clang_host -g %S/Inputs/main.c -o %t
+# RUN: %lldb -o "target create %t" -o "b main" -o "run" \
+# RUN:   -s %s -o exit 2>&1 | FileCheck %s
+
+# Verify that the plugin is enabled globally and per-target by default.
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Disable via --domain target.
+plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify disabled per-target but still enabled globally.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Re-enable via --domain target.
+plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify re-enabled per-target and still enabled globally.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Disable via --domain debugger.
+plugin disable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin disable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify disabled per-target but still enabled globally.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Re-enable via --domain debugger.
+plugin enable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin enable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify re-enabled per-target and still enabled globally.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Disable via --domain global.
+plugin disable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin disable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify disabled both globally and per-target.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Re-enable via --domain global.
+plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify re-enabled both globally and per-target.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
diff --git a/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-two-targets.test b/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-two-targets.test
new file mode 100644
index 00000000000000..059e22101a5ddd
--- /dev/null
+++ b/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag-two-targets.test
@@ -0,0 +1,171 @@
+# This test validates the --domain flag on the plugin enable and disable
+# commands when two targets with alive processes exist. It verifies that
+# --domain target only affects the selected target while --domain debugger and
+# --domain global affect both targets.
+
+# RUN: %clang_host -g %S/Inputs/main.c -o %t
+# RUN: %lldb \
+# RUN:   -o "target create %t" -o "b main" -o "run" \
+# RUN:   -o "target create %t" -o "b main" -o "run" \
+# RUN:   -s %s -o exit 2>&1 | FileCheck %s
+
+# Verify initial state: global and target 1 (selected) are enabled.
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# --- Test --domain target only affects the selected target ---
+
+# Disable the plugin for target 1 (currently selected).
+plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify target 1 shows disabled.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify global is still enabled.
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Switch to target 0 and verify it is still enabled (unaffected).
+target select 0
+# CHECK-LABEL: target select 0
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Re-enable target 1.
+target select 1
+# CHECK-LABEL: target select 1
+plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify target 1 is re-enabled.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# --- Test --domain debugger affects both targets ---
+
+# Disable the plugin for all targets via debugger domain.
+plugin disable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin disable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify target 1 (selected) shows disabled.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify global is still enabled.
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Switch to target 0 and verify it is also disabled.
+target select 0
+# CHECK-LABEL: target select 0
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Re-enable both targets via debugger domain.
+plugin enable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin enable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify target 0 (selected) shows re-enabled.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Switch to target 1 and verify it is also re-enabled.
+target select 1
+# CHECK-LABEL: target select 1
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify global is still enabled.
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# --- Test --domain global affects both targets ---
+
+# Disable the plugin globally.
+plugin disable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin disable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify global is disabled.
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Verify target 1 (selected) shows disabled.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Switch to target 0 and verify it is also disabled.
+target select 0
+# CHECK-LABEL: target select 0
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [-] UndefinedBehaviorSanitizer
+
+# Re-enable the plugin globally.
+plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify global is re-enabled.
+plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Verify target 0 (selected) shows re-enabled.
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
+
+# Switch to target 1 and verify it is also re-enabled.
+target select 1
+# CHECK-LABEL: target select 1
+plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK-LABEL: plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer
+# CHECK: instrumentation-runtime
+# CHECK:  [+] UndefinedBehaviorSanitizer
diff --git a/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag.test b/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag.test
index 6cdc900c261c10..1ee022bbd26211 100644
--- a/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag.test
+++ b/lldb/test/Shell/Commands/command-plugin-enable-disable-domain-flag.test
@@ -46,13 +46,30 @@ plugin enable --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
 # (instrumentation-runtime.UndefinedBehaviorSanitizer).
 
 # RUN: %lldb -o "plugin enable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_ENABLE_IR_DEBUGGER
-# ERROR_ENABLE_IR_DEBUGGER: error: failed to enable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: debugger domain is not supported
+# ERROR_ENABLE_IR_DEBUGGER: error: failed to enable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: debugger has no targets
 
 # RUN: %lldb -o "plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_ENABLE_IR_TARGET
-# ERROR_ENABLE_IR_TARGET: error: failed to enable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: target domain is not supported
+# ERROR_ENABLE_IR_TARGET: error: failed to enable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: no target is selected
 
 # RUN: %lldb -o "plugin disable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_DISABLE_IR_DEBUGGER
-# ERROR_DISABLE_IR_DEBUGGER: error: failed to disable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: debugger domain is not supported
+# ERROR_DISABLE_IR_DEBUGGER: error: failed to disable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: debugger has no targets
 
 # RUN: %lldb -o "plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_DISABLE_IR_TARGET
-# ERROR_DISABLE_IR_TARGET: error: failed to disable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: target domain is not supported
+# ERROR_DISABLE_IR_TARGET: error: failed to disable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: no target is selected
+
+# Error cases for plugin that supports all domains when a target exists but
+# has no alive process.
+
+# RUN: %clang_host %S/Inputs/main.c -o %t
+
+# RUN: %lldb -o "target create %t" -o "plugin enable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer" -o exit 2>&1 | FileCheck %s --check-prefix=ERROR_ENABLE_IR_TARGET_NO_PROCESS
+# ERROR_ENABLE_IR_TARGET_NO_PROCESS: error: failed to enable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: failed to find alive process for selected target
+
+# RUN: %lldb -o "target create %t" -o "plugin disable --domain target instrumentation-runtime.UndefinedBehaviorSanitizer" -o exit 2>&1 | FileCheck %s --check-prefix=ERROR_DISABLE_IR_TARGET_NO_PROCESS
+# ERROR_DISABLE_IR_TARGET_NO_PROCESS: error: failed to disable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: failed to find alive process for selected target
+
+# RUN: %lldb -o "target create %t" -o "plugin enable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer" -o exit 2>&1 | FileCheck %s --check-prefix=ERROR_ENABLE_IR_DEBUGGER_NO_PROCESS
+# ERROR_ENABLE_IR_DEBUGGER_NO_PROCESS: error: failed to enable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: no alive processes in debugger
+
+# RUN: %lldb -o "target create %t" -o "plugin disable --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer" -o exit 2>&1 | FileCheck %s --check-prefix=ERROR_DISABLE_IR_DEBUGGER_NO_PROCESS
+# ERROR_DISABLE_IR_DEBUGGER_NO_PROCESS: error: failed to disable plugin instrumentation-runtime.UndefinedBehaviorSanitizer: no alive processes in debugger
diff --git a/lldb/test/Shell/Commands/command-plugin-list-domain-flag.test b/lldb/test/Shell/Commands/command-plugin-list-domain-flag.test
index 7aacb522843c7f..7a810d5760ce09 100644
--- a/lldb/test/Shell/Commands/command-plugin-list-domain-flag.test
+++ b/lldb/test/Shell/Commands/command-plugin-list-domain-flag.test
@@ -23,34 +23,79 @@ plugin list --domain global instrumentation-runtime.UndefinedBehaviorSanitizer
 
 # Test plugin list --domain debugger returns an error (text format).
 # RUN: %lldb -o "plugin list --domain debugger language.cplusplus" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_DEBUGGER
-# ERROR_LIST_DEBUGGER: error: debugger domain is not supported
+# ERROR_LIST_DEBUGGER: error: language.cplusplus: plugin namespace language does not support querying enablement in the debugger domain
 
 # Test plugin list --domain target returns an error (text format).
 # RUN: %lldb -o "plugin list --domain target language.cplusplus" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_TARGET
-# ERROR_LIST_TARGET: error: target domain is not supported
+# ERROR_LIST_TARGET: error: language.cplusplus: plugin namespace language does not support querying enablement in the target domain
 
 # Test plugin list --domain debugger --json returns an error (json format).
 # RUN: %lldb -o "plugin list --domain debugger --json language.cplusplus" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_JSON_DEBUGGER
-# ERROR_LIST_JSON_DEBUGGER: error: debugger domain is not supported
+# ERROR_LIST_JSON_DEBUGGER: error: language.cplusplus: plugin namespace language does not support querying enablement in the debugger domain
 
 # Test plugin list --domain target --json returns an error (json format).
 # RUN: %lldb -o "plugin list --domain target --json language.cplusplus" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_JSON_TARGET
-# ERROR_LIST_JSON_TARGET: error: target domain is not supported
+# ERROR_LIST_JSON_TARGET: error: language.cplusplus: plugin namespace language does not support querying enablement in the target domain
 
 # Error cases with on a plugin that supports all domains.
 
 # Test plugin list --domain debugger returns an error for instrumentation-runtime plugin (text format).
 # RUN: %lldb -o "plugin list --domain debugger instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_DEBUGGER_IR
-# ERROR_LIST_DEBUGGER_IR: error: debugger domain is not supported
+# ERROR_LIST_DEBUGGER_IR: error: instrumentation-runtime.UndefinedBehaviorSanitizer: plugin namespace instrumentation-runtime does not support querying enablement in the debugger domain
 
 # Test plugin list --domain target returns an error for instrumentation-runtime plugin (text format).
 # RUN: %lldb -o "plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_TARGET_IR
-# ERROR_LIST_TARGET_IR: error: target domain is not supported
+# ERROR_LIST_TARGET_IR: error: instrumentation-runtime.UndefinedBehaviorSanitizer: target not available
 
 # Test plugin list --domain debugger --json returns an error for instrumentation-runtime plugin (json format).
 # RUN: %lldb -o "plugin list --domain debugger --json instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_JSON_DEBUGGER_IR
-# ERROR_LIST_JSON_DEBUGGER_IR: error: debugger domain is not supported
+# ERROR_LIST_JSON_DEBUGGER_IR: error: instrumentation-runtime.UndefinedBehaviorSanitizer: plugin namespace instrumentation-runtime does not support querying enablement in the debugger domain
 
 # Test plugin list --domain target --json returns an error for instrumentation-runtime plugin (json format).
 # RUN: %lldb -o "plugin list --domain target --json instrumentation-runtime.UndefinedBehaviorSanitizer" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_JSON_TARGET_IR
-# ERROR_LIST_JSON_TARGET_IR: error: target domain is not supported
+# ERROR_LIST_JSON_TARGET_IR: error: instrumentation-runtime.UndefinedBehaviorSanitizer: target not available
+
+# Errors are accumulated rather than stopping at the first error. With no
+# target, querying the enablement of each instrumentation-runtime plugin in the
+# target domain fails, so an error is reported for each plugin. The text and
+# JSON formats report the same errors.
+
+# RUN: %lldb -o "plugin list --domain target instrumentation-runtime" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_TARGET_ALL_IR
+# RUN: %lldb -o "plugin list --domain target --json instrumentation-runtime" 2>&1 | FileCheck %s --check-prefix=ERROR_LIST_TARGET_ALL_IR
+# ERROR_LIST_TARGET_ALL_IR: error: instrumentation-runtime.AddressSanitizer: target not available
+# ERROR_LIST_TARGET_ALL_IR: error: instrumentation-runtime.UndefinedBehaviorSanitizer: target not available
+
+# The enablement of plugins that can be queried is still listed when querying
+# the enablement of other plugins fails. The results are written to stdout and
+# the errors to stderr so they are checked separately.
+
+# RUN: %clang_host -g %S/Inputs/main.c -o %t
+# RUN: %lldb -o "target create %t" -o "b main" -o "run" -o "plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer language.cplusplus" 2>%t.text.stderr | FileCheck %s --check-prefix=LIST_TARGET_PARTIAL
+# RUN: FileCheck %s --check-prefix=LIST_TARGET_PARTIAL_ERR --input-file=%t.text.stderr
+# LIST_TARGET_PARTIAL: (lldb) plugin list --domain target instrumentation-runtime.UndefinedBehaviorSanitizer language.cplusplus
+# LIST_TARGET_PARTIAL-NEXT: instrumentation-runtime
+# LIST_TARGET_PARTIAL-NEXT:  [+] UndefinedBehaviorSanitizer
+# LIST_TARGET_PARTIAL-NEXT: language
+# LIST_TARGET_PARTIAL-NOT: cplusplus
+# LIST_TARGET_PARTIAL_ERR: error: language.cplusplus: plugin namespace language does not support querying enablement in the target domain
+
+# In the JSON format the error is also stored in the plugin's entry instead of
+# its enablement.
+# RUN: %lldb -o "target create %t" -o "b main" -o "run" -o "plugin list --domain target --json instrumentation-runtime.UndefinedBehaviorSanitizer language.cplusplus" 2>%t.json.stderr | FileCheck %s --check-prefix=LIST_JSON_TARGET_PARTIAL
+# RUN: FileCheck %s --check-prefix=LIST_JSON_TARGET_PARTIAL_ERR --input-file=%t.json.stderr
+# LIST_JSON_TARGET_PARTIAL: (lldb) plugin list --domain target --json instrumentation-runtime.UndefinedBehaviorSanitizer language.cplusplus
+# LIST_JSON_TARGET_PARTIAL-NEXT: {
+# LIST_JSON_TARGET_PARTIAL-NEXT:   "instrumentation-runtime": [
+# LIST_JSON_TARGET_PARTIAL-NEXT:     {
+# LIST_JSON_TARGET_PARTIAL-NEXT:       "enabled": true,
+# LIST_JSON_TARGET_PARTIAL-NEXT:       "name": "UndefinedBehaviorSanitizer"
+# LIST_JSON_TARGET_PARTIAL-NEXT:     }
+# LIST_JSON_TARGET_PARTIAL-NEXT:   ],
+# LIST_JSON_TARGET_PARTIAL-NEXT:   "language": [
+# LIST_JSON_TARGET_PARTIAL-NEXT:     {
+# LIST_JSON_TARGET_PARTIAL-NEXT:       "error": "plugin namespace language does not support querying enablement in the target domain",
+# LIST_JSON_TARGET_PARTIAL-NEXT:       "name": "cplusplus"
+# LIST_JSON_TARGET_PARTIAL-NEXT:     }
+# LIST_JSON_TARGET_PARTIAL-NEXT:   ]
+# LIST_JSON_TARGET_PARTIAL-NEXT: }
+# LIST_JSON_TARGET_PARTIAL_ERR: error: language.cplusplus: plugin namespace language does not support querying enablement in the target domain



More information about the llvm-branch-commits mailing list