Explorar el Código

Crash guard for hosted plugins on Linux and macOS

A plugin that faulted inside its audio processing took LYNX down on Linux and macOS (round 190dj, issue #155):
crashguard::call was SEH on Windows and a plain call elsewhere, so the existing switch-off path (bypass / silence,
the "Plugin crashed" prompt, Reload) never ran there.

crashguard::call now arms a thread-local jump buffer (sigsetjmp without the signal mask, ~12 ns per call) for the
length of the call. A SIGSEGV / SIGBUS / SIGILL / SIGFPE handler, installed on top of JUCE's crash handler, jumps
back only for a kernel-raised fault on an armed thread whose first frame outside the C/C++ runtime and system
libraries is in a module other than LYNX's executable (a plugin's memcpy from null is the plugin's). Faults in
LYNX's or JUCE's own code, faults on unarmed threads and anything the frames can't attribute go on to the crash
handler as before. C++ exceptions leaving a plugin call are caught too. Limits are documented in CrashGuard.h.

A plugin that crashes while its saved state is loaded (project open, undo, reload) is now guarded on every
platform: it is left out, the slot keeps its settings for the save, and the prompt offers no Reload.

Tests: tools/testplugin/lynx_test_crash.c (now Linux/macOS too, memcpy and state modes) and the new
lynx_test_crash_vst3.cpp; LYNX --crashguardtest checks the switch-off, the other inserts, save, reopen and Reload,
the state crash, and that LYNX's own faults inside a guarded call still crash (--faulttest guarded /
guarded-libc, also run by --selftest on Linux / macOS). CI: "Crashing plugin guard" (Linux CLAP + VST3, macOS CLAP).
Ka1-S hace 3 semanas
padre
commit
ee533e5189

+ 33 - 0
.github/workflows/tests.yml

@@ -196,3 +196,36 @@ jobs:
           LYNX_PROFILE_DIR="$PWD/crash-profile" xvfb-run -a build/LYNX_artefacts/Release/LYNX --scantest "$PWD/crash-plugin" "$PWD/crash.txt" || true
           cat crash.txt
           grep -q 'blacklisted: .*crash.clap' crash.txt
+
+      # Round 190dt: a hosted plugin that crashes in its audio processing (a null write, and a memcpy from null as in
+      # issue #155) is switched off and LYNX keeps playing, saves and reloads it; a plugin that crashes on its saved state
+      # is left out as the project opens; LYNX's own faults inside a plugin call still end in the crash handler.
+      # Linux: CLAP + VST3; macOS: CLAP.
+      - name: Crashing plugin guard
+        shell: bash
+        run: |
+          if [[ "$RUNNER_OS" == Linux ]]; then
+            bin=build/LYNX_artefacts/Release/LYNX; run=(xvfb-run -a)
+          else
+            bin=build/LYNX_artefacts/Release/LYNX.app/Contents/MacOS/LYNX; run=()
+          fi
+          mkdir -p cg-plugins
+          cc -shared -fPIC -O2 -Ithird_party/clap/include tools/testplugin/lynx_test_crash.c -o "cg-plugins/LYNX Test Crash.clap"
+          plugins=("LYNX Test Crash.clap" "LYNX Test Crash.clap")
+          modes=(process memcpy)
+          if [[ "$RUNNER_OS" == Linux ]]; then
+            V="$RUNNER_TEMP/juce/modules/juce_audio_processors/format_types/VST3_SDK"
+            B="cg-plugins/LYNX Test Crash.vst3/Contents/x86_64-linux"
+            mkdir -p "$B"
+            c++ -shared -fPIC -O2 -std=c++17 -I"$V" tools/testplugin/lynx_test_crash_vst3.cpp "$V/pluginterfaces/base/funknown.cpp" -o "$B/LYNX Test Crash.so"
+            plugins+=("LYNX Test Crash.vst3" "LYNX Test Crash.vst3")
+            modes+=(process memcpy)
+          fi
+          status=0
+          for i in "${!plugins[@]}"; do
+            report="$PWD/crashguard-$i.txt"
+            LYNX_PROFILE_DIR="$PWD/cg-profile-$i" perl -e 'alarm shift; exec @ARGV' 600 "${run[@]}" "$bin" --crashguardtest "$PWD/cg-plugins/${plugins[$i]}" "$report" "${modes[$i]}" || true
+            echo "--- ${plugins[$i]} (${modes[$i]})"; cat "$report" || true
+            grep -q '^result=OK' "$report" || status=1
+          done
+          exit $status

+ 206 - 5
src/Main.cpp

@@ -550,6 +550,14 @@ public:
             const auto i = args.indexOf ("--faulttest");
             crashFolderForTest = juce::File (args[i + 2].unquoted());
             lynx::crashguard::quietCrashReports();
+            // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
+            // reach the crash handler like any other; a return means the guard swallowed it
+            if (args[i + 1].startsWith ("guarded"))
+            {
+                const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
+                crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
+                lynx::crashguard::exitNow (4);
+            }
             lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
         }
         lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
@@ -1211,6 +1219,18 @@ public:
             return;
         }
 
+        if (args.contains ("--crashguardtest"))
+        {
+            // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
+            // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
+            // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
+            // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
+            const auto i = args.indexOf ("--crashguardtest");
+            runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
+                               i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
+            return;
+        }
+
         if (args.contains ("--claprestarttest"))
         {
             // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
@@ -2682,14 +2702,23 @@ private:
     // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
     // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
     // "crash <time>.txt" with the access violation in the folder it is given.
+    // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
+    // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
+    // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
     static juce::String faultReportSelfTest()
     {
-       #if JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))
+       #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
+           || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
         const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
         const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
                               .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
         juce::StringArray problems;
-        for (const auto* kind : { "plain", "unwalkable" })
+       #if JUCE_WINDOWS
+        const char* const kinds[] = { "plain", "unwalkable" };
+       #else
+        const char* const kinds[] = { "plain", "guarded", "guarded-libc" };
+       #endif
+        for (const auto* kind : kinds)
         {
             const auto folder = root.getChildFile (kind);
             folder.createDirectory();
@@ -2704,14 +2733,22 @@ private:
             juce::String text;
             for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
                 text = file.loadFileAsString();
-            if (! text.contains ("0xc0000005"))
-                problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the access violation")
+           #if JUCE_WINDOWS
+            const auto found = text.contains ("0xc0000005");
+           #else
+            const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
+           #endif
+            if (folder.getChildFile ("swallowed.txt").existsAsFile())
+                problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
+                              + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
+            else if (! found)
+                problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
                               + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
         }
         root.deleteRecursively();
         return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
        #else
-        return "SKIPPED (Windows x64 only)";
+        return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
        #endif
     }
 
@@ -6437,6 +6474,170 @@ private:
         quit();
     }
 
+    // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
+    void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
+    {
+        juce::String report;
+        bool ok = true;
+        const auto expect = [&] (const char* name, bool value) {
+            report << name << "=" << (value ? 1 : 0) << "\n";
+            ok = ok && value;
+        };
+        const auto setEnv = [] (const char* name, const char* value) {
+           #if JUCE_WINDOWS
+            _putenv_s (name, value);
+           #else
+            setenv (name, value, 1);
+           #endif
+        };
+        // renders without the plugin warm-up (its silent blocks would count towards the crash)
+        const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
+            lynx::AudioEngine::RenderOptions o;
+            o.seconds = seconds;
+            o.sampleRate = 48000.0;
+            o.pluginWarmUp = false;
+            o.capture = capture;
+            return engine.renderOffline (o);
+        };
+        const auto peakOf = [] (float& peak) {
+            return [&peak] (const float* l, const float* r, int n) {
+                for (int k = 0; k < n; ++k)
+                    peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
+            };
+        };
+        report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
+        setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
+        setEnv ("LYNX_TEST_CRASH_AFTER", "40");
+        const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
+                             .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
+        tmp.createDirectory();
+        std::optional<lynx::Song> saved;
+        std::string savedState;
+        {
+            lynx::AudioEngine offline (false);
+            auto& host = offline.getPluginHost();
+            host.addPluginFile (juce::File (pluginPath));
+            juce::PluginDescription effect;
+            bool found = false;
+            for (const auto& type : host.getKnownPlugins().getTypes())
+                if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
+                {
+                    effect = type;
+                    found = true;
+                }
+            expect ("plugin_found", found);
+
+            // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
+            auto song = lynx::Song::makeDefault();
+            lynx::EffectSlot slot;
+            slot.kind = lynx::EffectKind::plugin;
+            slot.plugin.id = effect.createIdentifierString().toStdString();
+            slot.plugin.name = effect.name.toStdString();
+            song.mixer[1].effects.push_back (slot);
+            offline.setSong (song);
+            const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
+
+            // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
+            // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
+            render (offline, 0.05, {}); // (a few blocks, far from the 40th)
+            offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
+            render (offline, 0.05, {});
+            auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
+            expect ("plugin_loaded", first != nullptr);
+            offline.capturePluginStates();
+            savedState = offline.getSong().mixer[1].effects[0].plugin.state;
+            expect ("state_captured", ! savedState.empty());
+
+            // the crash: 3 s, the plugin faults in its 40th block
+            const auto crashesBefore = lynx::pluginCrashCount();
+            juce::int64 position = 0, crashAt = -1;
+            float peakAfter = 0.0f;
+            const auto afterPeak = peakOf (peakAfter);
+            const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
+                if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
+                    crashAt = position;
+                else if (crashAt >= 0)
+                    afterPeak (l, r, n);
+                position += n;
+            });
+            report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
+            const auto crashes = lynx::pluginCrashes();
+            expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
+            if (! crashes.empty())
+                report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
+            expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
+            const auto down = offline.downHostedPlugins();
+            expect ("slot_down", down.size() == 1 && down[0] == where);
+            expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
+
+            // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
+            offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
+            float othersPeak = 0.0f;
+            render (offline, 1.0, peakOf (othersPeak));
+            report << "other_inserts_peak=" << othersPeak << "\n";
+            expect ("other_inserts_play", othersPeak > 0.01f);
+            expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
+            offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
+
+            // the project saves with the settings the plugin had before it crashed, and opens again
+            offline.capturePluginStates();
+            expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
+            const auto file = tmp.getChildFile ("crashed.lynx");
+            juce::String error;
+            expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
+            saved = lynx::ProjectFile::load (file, error);
+            expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
+                                           && saved->mixer[1].effects[0].plugin.state == savedState);
+
+            // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
+            const auto running = offline.reloadHostedPlugins (down);
+            auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
+            expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
+            float reloadedPeak = 0.0f;
+            render (offline, 1.0, peakOf (reloadedPeak));
+            report << "reloaded_peak=" << reloadedPeak << "\n";
+            expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
+        }
+
+        // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
+        // settings stay in the project
+        setEnv ("LYNX_TEST_CRASH", "state");
+        if (saved.has_value())
+        {
+            lynx::AudioEngine reopened (false);
+            reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
+            const auto before = lynx::pluginCrashCount();
+            reopened.setSong (*saved);
+            float reopenedPeak = 0.0f;
+            render (reopened, 1.0, peakOf (reopenedPeak));
+            const auto crashes = lynx::pluginCrashes();
+            report << "reopened_peak=" << reopenedPeak << "\n";
+            if (reopened.getPluginHost().getLoadFailures().size() > 0)
+                report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
+            expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
+            expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
+            expect ("state_crash_project_plays", reopenedPeak > 0.01f);
+            reopened.capturePluginStates();
+            expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
+                                                     && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
+        }
+        setEnv ("LYNX_TEST_CRASH", "");
+
+        // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
+        const auto own = faultReportSelfTest();
+        report << "own_faults=" << own << "\n";
+        ok = ok && ! own.startsWith ("ERROR");
+
+        report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
+        for (const auto& c : lynx::pluginCrashes())
+            report << "  crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
+        tmp.deleteRecursively();
+        report << "result=" << (ok ? "OK" : "FAILED") << "\n";
+        juce::File (reportPath).replaceWithText (report);
+        setApplicationReturnValue (ok ? 0 : 1);
+        quit();
+    }
+
     // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
     // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
     // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression

+ 20 - 3
src/engine/PluginHost.cpp

@@ -208,11 +208,12 @@ struct CrashSlot
 {
     char name[128] {};
     std::uint32_t code = 0;
+    bool onLoad = false;
 };
 CrashSlot crashLog[crashSlots];
 std::atomic<int> crashCount { 0 };
 
-void recordCrash (const std::string& name, std::uint32_t code) noexcept
+void recordCrash (const std::string& name, std::uint32_t code, bool onLoad = false) noexcept
 {
     const auto index = crashCount.load (std::memory_order_relaxed);
     auto& slot = crashLog[index % crashSlots];
@@ -221,6 +222,7 @@ void recordCrash (const std::string& name, std::uint32_t code) noexcept
         slot.name[i] = name[i];
     slot.name[i] = 0;
     slot.code = code;
+    slot.onLoad = onLoad;
     crashCount.store (index + 1, std::memory_order_release); // (two plugins crashing in the same instant may share a slot)
 }
 
@@ -251,7 +253,7 @@ std::vector<PluginCrash> pluginCrashes()
     std::vector<PluginCrash> list;
     const auto count = pluginCrashCount();
     for (int i = std::max (0, count - crashSlots); i < count; ++i)
-        list.push_back ({ crashLog[i % crashSlots].name, crashLog[i % crashSlots].code });
+        list.push_back ({ crashLog[i % crashSlots].name, crashLog[i % crashSlots].code, crashLog[i % crashSlots].onLoad });
     return list;
 }
 
@@ -3009,7 +3011,22 @@ std::unique_ptr<juce::AudioPluginInstance> PluginHost::createInstance (const Plu
         juce::MemoryBlock state;
 
         if (state.fromBase64Encoding (juce::String::fromUTF8 (ref.state.c_str())))
-            instance->setStateInformation (state.getData(), (int) state.getSize());
+        {
+            // round 190dt: guarded like the audio calls (a plugin that crashes on its own saved settings took LYNX down
+            // while the project opened). It is left out: the slot keeps those settings, so the project saves them.
+            auto* raw = instance.get();
+            if (const auto code = crashguard::run ([raw, &state] { raw->setStateInformation (state.getData(), (int) state.getSize()); }); code != 0)
+            {
+                (void) instance.release(); // never called again, not even to delete it (as after a crash in process)
+                recordCrash (description->name.toStdString(), code, true);
+                crashguard::note (("plugin " + description->name + " crashed while loading its saved settings (" + crashguard::describe (code)
+                                   + "): left out").toStdString());
+                if (error != nullptr)
+                    *error = tr ("{0} crashed and was switched off.", { juce::String::fromUTF8 (ref.name.c_str()) }) + " ("
+                             + crashguard::describe (code) + ")";
+                return nullptr;
+            }
+        }
     }
 
     return instance;

+ 3 - 0
src/engine/PluginHost.h

@@ -48,6 +48,9 @@ struct PluginCrash
 {
     std::string plugin;
     std::uint32_t code = 0;
+    // round 190dt: it crashed while its saved settings were being loaded into it (a project opening, an undo, a
+    // reload): it was left out (the slot keeps those settings for the save) and reloading it would do the same again
+    bool onLoad = false;
 };
 int pluginCrashCount() noexcept;
 std::vector<PluginCrash> pluginCrashes();

+ 338 - 0
src/platform/CrashGuard.cpp

@@ -24,9 +24,16 @@
  #include <mmsystem.h>
 #else
  #include <signal.h>
+ #include <setjmp.h>
  #include <unistd.h>
  #include <pthread.h>
  #include <dlfcn.h>
+ #include <unwind.h>
+ #if defined(__APPLE__)
+  #include <sys/ucontext.h>
+ #else
+  #include <ucontext.h>
+ #endif
  #if defined(__GLIBC__) || defined(__APPLE__)
   #include <execinfo.h>
   #define LYNX_EXECINFO 1
@@ -59,6 +66,290 @@ std::uint32_t call (void (*fn) (void*), void* context) noexcept
         return code != 0 ? code : 1u;
     }
 }
+#elif ! defined(_WIN32)
+// Round 190dt (issue #155 follow-up): Linux / macOS. A fault is a signal there; see CrashGuard.h for what is caught,
+// what is not, and why.
+namespace
+{
+constexpr std::uint32_t cppExceptionCode = 0xE06D7363u; // (Windows' code for a C++ exception: describe() names it)
+constexpr std::uint32_t signalCodeBase = 0x4C590000u;   // | the signal number ("LY" + signal: describe() names it)
+constexpr int guardedSignals[] = { SIGSEGV, SIGBUS, SIGILL, SIGFPE };
+constexpr int guardedCount = (int) (sizeof (guardedSignals) / sizeof (guardedSignals[0]));
+
+// One armed call on this thread (a stack of them when a guarded call makes another one)
+struct GuardFrame
+{
+    sigjmp_buf env;
+    GuardFrame* prev = nullptr;
+    volatile std::uint32_t code = 0;     // written by the handler before it jumps back
+    volatile sig_atomic_t handling = 0;  // the handler is looking at a fault of this frame (a fault inside it is not caught)
+};
+
+// The armed frame of this thread. The handler reads it, so it must not allocate on first use: Linux' thread_local
+// pointer in the executable is static TLS (initial-exec); macOS' thread_local may allocate lazily, so a pthread key.
+#if defined(__APPLE__)
+pthread_key_t frameKey;
+GuardFrame* currentFrame() noexcept { return static_cast<GuardFrame*> (pthread_getspecific (frameKey)); }
+void setCurrentFrame (GuardFrame* f) noexcept { pthread_setspecific (frameKey, f); }
+#else
+__attribute__ ((tls_model ("initial-exec"))) thread_local GuardFrame* tlsFrame = nullptr;
+GuardFrame* currentFrame() noexcept { return tlsFrame; }
+void setCurrentFrame (GuardFrame* f) noexcept { tlsFrame = f; }
+#endif
+
+std::atomic<int> guardState { 0 }; // 0 = not installed, 1 = being installed, 2 = installed
+struct sigaction previousAction[guardedCount];
+const void* ownImage = nullptr; // where LYNX's executable (LYNX's and JUCE's code) is loaded
+
+// A fault the kernel raised for an instruction of this thread (not a signal sent by kill / raise / sigqueue)
+bool synchronousFault (const siginfo_t* info) noexcept
+{
+#if defined(__APPLE__)
+    return info != nullptr && info->si_code > 0 && info->si_code < 0x10000; // (SI_USER and friends are 0x1000x)
+#else
+    return info != nullptr && info->si_code > 0; // (SI_USER 0, SI_TKILL / SI_QUEUE negative; SI_KERNEL 0x80 is a fault)
+#endif
+}
+
+std::uintptr_t programCounter (const void* context) noexcept
+{
+    const auto* uc = static_cast<const ucontext_t*> (context);
+#if defined(__APPLE__) && defined(__x86_64__)
+    return (std::uintptr_t) uc->uc_mcontext->__ss.__rip;
+#elif defined(__APPLE__) && defined(__aarch64__)
+    return (std::uintptr_t) __darwin_arm_thread_state64_get_pc (uc->uc_mcontext->__ss);
+#elif defined(__linux__) && defined(__x86_64__)
+    return (std::uintptr_t) uc->uc_mcontext.gregs[REG_RIP];
+#elif defined(__linux__) && defined(__aarch64__)
+    return (std::uintptr_t) uc->uc_mcontext.pc;
+#else
+    (void) uc;
+    return 0; // (unknown: nothing is caught)
+#endif
+}
+
+// Where the faulting function was called from, when the faulting address is in no module (a call through a null or
+// stale function pointer): x86-64 has just pushed the return address, ARM64 holds it in the link register.
+std::uintptr_t callerOfUnknownCode (const void* context) noexcept
+{
+    const auto* uc = static_cast<const ucontext_t*> (context);
+#if defined(__APPLE__) && defined(__x86_64__)
+    return *reinterpret_cast<const std::uintptr_t*> (uc->uc_mcontext->__ss.__rsp);
+#elif defined(__APPLE__) && defined(__aarch64__)
+    return (std::uintptr_t) __darwin_arm_thread_state64_get_lr (uc->uc_mcontext->__ss);
+#elif defined(__linux__) && defined(__x86_64__)
+    return *reinterpret_cast<const std::uintptr_t*> (uc->uc_mcontext.gregs[REG_RSP]);
+#elif defined(__linux__) && defined(__aarch64__)
+    return (std::uintptr_t) uc->uc_mcontext.regs[30];
+#else
+    (void) uc;
+    return 0;
+#endif
+}
+
+// The C / C++ runtime and the system's own libraries: a fault inside them belongs to whoever called them (a plugin's
+// memcpy from a null pointer faults in libc), so the walk goes on to their caller.
+bool runtimeLibrary (const char* path) noexcept
+{
+    if (path == nullptr)
+        return false;
+    const char* name = path;
+    for (const char* p = path; *p != 0; ++p)
+        if (*p == '/')
+            name = p + 1;
+    static const char* const prefixes[] = { "libc.so", "libc-", "libm.so", "libm-", "libmvec", "libstdc++", "libgcc_s", "ld-linux",
+                                            "ld64.so", "libpthread", "libdl.so", "libdl-", "librt.so", "librt-", "libc++", "libunwind",
+                                            "libsystem_", "libdyld", "libobjc", "libSystem" };
+    for (const auto* prefix : prefixes)
+        if (std::strncmp (name, prefix, std::strlen (prefix)) == 0)
+            return true;
+    return false;
+}
+
+enum class Owner { unknown, lynx, runtime, other };
+
+Owner ownerOf (std::uintptr_t address) noexcept
+{
+    Dl_info info {};
+    if (address == 0 || dladdr (reinterpret_cast<const void*> (address), &info) == 0 || info.dli_fbase == nullptr)
+        return Owner::unknown;
+    if (info.dli_fbase == ownImage)
+        return Owner::lynx;
+    return runtimeLibrary (info.dli_fname) ? Owner::runtime : Owner::other;
+}
+
+struct Walk
+{
+    std::uintptr_t frames[64];
+    int count = 0;
+};
+
+_Unwind_Reason_Code collectFrame (_Unwind_Context* context, void* arg)
+{
+    auto& walk = *static_cast<Walk*> (arg);
+    if (walk.count >= 64)
+        return _URC_END_OF_STACK;
+    int beforeInstruction = 0;
+    const auto ip = (std::uintptr_t) _Unwind_GetIPInfo (context, &beforeInstruction);
+    if (ip == 0)
+        return _URC_END_OF_STACK;
+    // a return address points after its call: one byte back is inside the call (the faulting frame's is exact)
+    walk.frames[walk.count++] = beforeInstruction != 0 ? ip : ip - 1;
+    return _URC_NO_REASON;
+}
+
+// Whose fault it is: the first frame, from the faulting instruction outwards, that is neither the system's runtime
+// nor code outside every module decides. A plugin's module (or anything else LYNX did not build) = the plugin's;
+// LYNX's executable, or no frame that tells = LYNX's own (never caught).
+bool faultIsAPlugins (std::uintptr_t pc, const void* context) noexcept
+{
+    if (ownImage == nullptr)
+        return false;
+    Walk walk; // (the unwinder walks through the signal frame into the interrupted code)
+    if (pc != 0) // (a call through a null pointer: the unwinder stops there; its caller below)
+        _Unwind_Backtrace (collectFrame, &walk);
+    int start = -1;
+    for (int i = 0; i < walk.count && start < 0; ++i)
+        if (walk.frames[i] == pc || walk.frames[i] == pc - 1)
+            start = i;
+    std::uintptr_t fallback[2] = { pc, 0 };
+    const std::uintptr_t* frames = fallback;
+    int count = 1;
+    if (start >= 0)
+    {
+        frames = walk.frames + start;
+        count = walk.count - start;
+    }
+    else if (ownerOf (pc) == Owner::unknown || ownerOf (pc) == Owner::runtime)
+    {
+        // the unwinder did not find the faulting frame: its caller only (a leaf: the return address)
+        fallback[1] = callerOfUnknownCode (context);
+        count = 2;
+    }
+    for (int i = 0; i < count; ++i)
+        switch (ownerOf (frames[i]))
+        {
+            case Owner::lynx: return false;
+            case Owner::other: return true;
+            case Owner::unknown:
+            case Owner::runtime: break;
+        }
+    return false;
+}
+
+// The handlers that were there before (JUCE's crash handler: the crash file and the emergency save)
+void passOn (int sig, siginfo_t* info, void* context) noexcept
+{
+    int index = 0;
+    while (index < guardedCount && guardedSignals[index] != sig)
+        ++index;
+    if (index < guardedCount)
+    {
+        const auto& previous = previousAction[index];
+        if ((previous.sa_flags & SA_SIGINFO) != 0)
+        {
+            if (previous.sa_sigaction != nullptr)
+                previous.sa_sigaction (sig, info, context);
+        }
+        else if (previous.sa_handler == SIG_IGN && ! synchronousFault (info))
+            return;
+        else if (previous.sa_handler != SIG_DFL && previous.sa_handler != SIG_IGN)
+            previous.sa_handler (sig);
+    }
+    // it came back (or there was none): the default action, by the fault happening again on return
+    struct sigaction fallback {};
+    fallback.sa_handler = SIG_DFL;
+    sigemptyset (&fallback.sa_mask);
+    sigaction (sig, &fallback, nullptr);
+    if (! synchronousFault (info))
+        raise (sig);
+}
+
+void onFault (int sig, siginfo_t* info, void* context)
+{
+    const auto savedErrno = errno;
+    if (auto* frame = currentFrame(); frame != nullptr && frame->handling == 0 && synchronousFault (info))
+    {
+        frame->handling = 1; // (a fault while looking at this one, e.g. in the unwinder, goes on to the crash handler)
+        if (faultIsAPlugins (programCounter (context), context))
+        {
+            frame->code = signalCodeBase | (std::uint32_t) sig;
+            // the thread's signal mask as it was before the fault (sigsetjmp did not save it: that costs a system
+            // call on every guarded call), then back to the guarded call
+            pthread_sigmask (SIG_SETMASK, &static_cast<ucontext_t*> (context)->uc_sigmask, nullptr);
+            siglongjmp (frame->env, 1);
+        }
+        // (handling stays set: the crash handler below ends the process, and a fault inside it is not caught either)
+    }
+    errno = savedErrno;
+    passOn (sig, info, context);
+}
+
+void installFaultGuard() noexcept
+{
+    auto expected = 0;
+    if (! guardState.compare_exchange_strong (expected, 1))
+    {
+        while (guardState.load() == 1)
+            sched_yield();
+        return;
+    }
+    Dl_info self {};
+    if (dladdr (reinterpret_cast<const void*> (&installFaultGuard), &self) != 0)
+        ownImage = self.dli_fbase;
+#if defined(__APPLE__)
+    pthread_key_create (&frameKey, nullptr);
+#endif
+    {
+        Walk warm; // (the unwinder's first use loads and sets up its tables: here, not inside a signal handler)
+        _Unwind_Backtrace (collectFrame, &warm);
+    }
+    for (int i = 0; i < guardedCount; ++i)
+    {
+        struct sigaction action {};
+        action.sa_sigaction = onFault;
+        sigemptyset (&action.sa_mask);
+        // SA_NODEFER: a fault inside the handler reaches it again (and goes on to the crash handler) instead of the
+        // kernel ending the process at once; SA_ONSTACK: the alternate stack where the thread has one (hardenSignals)
+        action.sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK;
+        sigaction (guardedSignals[i], &action, &previousAction[i]);
+    }
+    guardState.store (2, std::memory_order_release);
+}
+
+// The call itself, in a frame of its own: C++ exceptions leaving the plugin are caught here
+__attribute__ ((noinline)) bool callCatching (void (*fn) (void*), void* context) noexcept
+{
+    try
+    {
+        fn (context);
+        return false;
+    }
+    catch (...)
+    {
+        return true;
+    }
+}
+} // namespace
+
+std::uint32_t call (void (*fn) (void*), void* context) noexcept
+{
+    if (guardState.load (std::memory_order_acquire) != 2)
+        installFaultGuard();
+    GuardFrame frame;
+    frame.prev = currentFrame();
+    // (no signal mask saved: see onFault)
+    if (sigsetjmp (frame.env, 0) != 0)
+    {
+        setCurrentFrame (frame.prev); // the plugin faulted: back here from onFault
+        const std::uint32_t code = frame.code;
+        return code != 0 ? code : 1u;
+    }
+    setCurrentFrame (&frame);
+    const auto threw = callCatching (fn, context);
+    setCurrentFrame (frame.prev);
+    return threw ? cppExceptionCode : 0u;
+}
 #else
 std::uint32_t call (void (*fn) (void*), void* context) noexcept
 {
@@ -291,6 +582,14 @@ bool processRunning (std::uint32_t pid, std::uint64_t startTime) noexcept
 
 const char* describe (std::uint32_t code) noexcept
 {
+#if ! defined(_WIN32)
+    if ((code & 0xFFFF0000u) == 0x4C590000u) // a signal caught by call() on Linux / macOS (round 190dt)
+    {
+        const auto sig = (int) (code & 0xFFu);
+        return sig == SIGSEGV ? "segmentation fault" : sig == SIGBUS ? "bus error" : sig == SIGILL ? "illegal instruction"
+             : sig == SIGFPE ? "floating-point exception" : "signal";
+    }
+#endif
     switch (code)
     {
         case 0xC0000005u: return "access violation";
@@ -762,6 +1061,43 @@ void faultForTest (bool unwalkable) noexcept
     std::_Exit (3); // (not reached)
 }
 
+namespace
+{
+#if defined(__GNUC__) || defined(__clang__)
+__attribute__ ((noinline))
+#endif
+void copyFromNullForTest() noexcept
+{
+    // what nih-plug did in issue #155 (memcpy from a null pointer: the fault is in the C library), but called by LYNX
+    char to[64];
+    const char* volatile from = nullptr;
+    volatile std::size_t size = sizeof (to); // (a size the compiler can't see: a real call into the C library)
+    std::memcpy (to, (const char*) from, size);
+    std::fprintf (stderr, "%c", to[0]);
+}
+} // namespace
+
+std::uint32_t faultInGuardedCallForTest (bool inCLibrary) noexcept
+{
+    return run ([inCLibrary] {
+        if (inCLibrary)
+            copyFromNullForTest();
+        else
+            faultForTest (false);
+    });
+}
+
+bool pluginFaultsCaught() noexcept
+{
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__clang__))
+    return true; // SEH
+#elif (defined(__linux__) || defined(__APPLE__)) && (defined(__x86_64__) || defined(__aarch64__))
+    return true; // signals (programCounter knows these)
+#else
+    return false;
+#endif
+}
+
 void setUnwalkableFaultHandler (void (*handler) (void*)) noexcept
 {
 #if defined(LYNX_UNWIND)
@@ -939,6 +1275,8 @@ void hardenSignals() noexcept
                     sigaction (sig, &action, nullptr);
                 }
             }
+        // round 190dt: the plugin-call guard (call()), on top of the crash handler it passes LYNX's own faults to
+        installFaultGuard();
 
         if (endSignalPipe[0] < 0 && ::pipe (endSignalPipe) == 0)
         {

+ 32 - 1
src/platform/CrashGuard.h

@@ -3,7 +3,31 @@
 // Calls into code LYNX does not control (hosted VST3 / CLAP / VST2 plugins) behind a structured-exception guard, so a
 // plugin that crashes (access violation, division by zero, a C++ exception escaping it) is caught at the call instead
 // of taking the whole app down. On Windows this is SEH (__try / __except in CrashGuard.cpp, the only unit built with
-// -fms-extensions); elsewhere the call is made directly.
+// -fms-extensions).
+//
+// Linux / macOS (round 190dt; x86-64 and ARM64): a fault is a signal. call() arms a jump buffer of this thread
+// (sigsetjmp, no system call) for the length of the call; a handler for SIGSEGV / SIGBUS / SIGILL / SIGFPE, installed
+// on top of the crash handler (hardenSignals, or the first call), jumps back to call() (siglongjmp) only when ALL of:
+//   - this thread is inside an armed call (other threads, and every fault outside a guarded call, go to the crash
+//     handler as before: the crash file and the emergency save);
+//   - the kernel raised it for an instruction (not a signal sent by kill / raise);
+//   - the first frame from the faulting instruction outwards that is not the C / C++ runtime or the system's own
+//     libraries (libc, libstdc++, libgcc_s, ld.so, libsystem_*, libobjc...) belongs to a module that is not LYNX's
+//     executable: a plugin's memcpy from a null pointer faults in libc but is the plugin's; a fault in LYNX's or
+//     JUCE's code (a host callback the plugin made, JUCE's VST3 wrapper) is LYNX's own and is never caught, nor is
+//     one whose frames cannot tell (code outside every module called from LYNX, an unwinder that finds nothing).
+// C++ exceptions leaving the call are caught there too (code 0xE06D7363, as on Windows).
+// What it cannot make safe (as with SEH, the caller then never touches that instance again, and LYNX goes on):
+//   - the jump skips the destructors of the frames between call() and the fault: what they held stays held (JUCE's
+//     per-instance VST3 process lock, LYNX's per-instance CLAP gate; both only guard that dead instance), and what
+//     the plugin held stays held (its own locks; a lock of the C library, e.g. malloc's when it faulted inside
+//     malloc: then a later allocation of another thread may block, as the heap may be damaged anyway);
+//   - finding out whose fault it is runs in the signal handler (dladdr, the unwinder): not async-signal-safe by the
+//     letter of POSIX; a fault there is passed on to the crash handler (SA_NODEFER), never caught;
+//   - not caught: aborts (SIGABRT: the C library's heap checks, assertions, Rust's panic=abort), stack overflows
+//     (no alternate stack on the audio thread), faults on the plugin's own threads, faults inside its editor's event
+//     handling (see the window guard below). "Run in a separate process" (engine/PluginSandbox.h) is the complete
+//     protection: there the plugin dies alone.
 //
 // A caught crash leaves the plugin in an unknown state: the caller must never call that instance again (PluginEffect /
 // PluginInstrument switch to bypass / silence and report it, engine/PluginHost.h).
@@ -23,6 +47,8 @@ std::uint32_t run (Fn&& fn) noexcept
 {
     return call ([] (void* c) { (*static_cast<std::remove_reference_t<Fn>*> (c)) (); }, &fn);
 }
+// This build catches a plugin's faults in call() (Windows SEH; Linux / macOS on x86-64 / ARM64 signals)
+bool pluginFaultsCaught() noexcept;
 
 // Plugin editor windows (issue #32, round 174a; Windows x64 only, elsewhere these do nothing). A hosted plugin's own
 // window procedure runs outside every LYNX call (DispatchMessageW calls it from the message loop), so a fault in it
@@ -115,6 +141,10 @@ void setUnwalkableFaultHandler (void (*handler) (void* exceptionPointers)) noexc
 // `unwalkable` = with the thread's stack above the fault overwritten first, so that it cannot be walked (Windows x64;
 // elsewhere a plain fault).
 [[noreturn]] void faultForTest (bool unwalkable) noexcept;
+// --faulttest guarded / guarded-libc (round 190dt): a fault in LYNX's own code inside a guarded call (`inCLibrary`:
+// a memcpy from a null pointer that LYNX makes, so the faulting instruction is in the C library). It must NOT be
+// caught: the process ends through the crash handler; a return (with the code) means it was swallowed.
+std::uint32_t faultInGuardedCallForTest (bool inCLibrary) noexcept;
 // "module+0xoffset" of one code address ("" when unknown)
 std::string describeAddress (const void* address);
 
@@ -132,6 +162,7 @@ void startHangWatch (const std::string& folderUtf8, int stallMs = 2000) noexcept
 //   message thread still writes its crash file;
 // - SIGTERM / SIGHUP (the session logging out, the terminal that started LYNX closed, `kill`) leave a session step
 //   ("ended by SIGTERM ...") before LYNX ends as it did before. Without them the report could only say "closed".
+// - round 190dt: the plugin-call guard of call() (see the top of this file), on top of the crash handler.
 void hardenSignals() noexcept;
 void heartbeat() noexcept;
 void stopHangWatch() noexcept;

+ 15 - 11
src/ui/MainComponent.cpp

@@ -5429,17 +5429,21 @@ void MainComponent::timerCallback()
         // round 190ao: "Reload" starts it again without reopening the project (only on request: a plugin that crashes
         // again shows this again)
         const auto crashedName = names[names.size() - 1];
-        juce::AlertWindow::showAsync (juce::MessageBoxOptions()
-                                          .withIconType (juce::MessageBoxIconType::WarningIcon)
-                                          .withTitle (tr ("Plugin crashed"))
-                                          .withMessage (tr ("{0} crashed and was switched off.", { crashedName }) + "\n\n"
-                                                        + tr ("LYNX SHARE and your project kept running (an effect is bypassed, an instrument "
-                                                              "stays silent). Save your project.")
-                                                        + " " + tr ("Reload starts it again with the settings from the last save or backup."))
-                                          .withButton (tr ("Reload"))
-                                          .withButton (tr ("Close")),
-                                      [safe = juce::Component::SafePointer<MainComponent> (this), crashedName] (int result) {
-                                          if (safe != nullptr && result == 1)
+        // round 190dt: it crashed on its saved settings (it was left out as the project opened): the same settings would
+        // crash it again, so no Reload; the project keeps them for the save
+        const auto all = pluginCrashes();
+        const auto onLoad = ! all.empty() && all.back().onLoad;
+        auto message = tr ("{0} crashed and was switched off.", { crashedName }) + "\n\n"
+                       + tr ("LYNX SHARE and your project kept running (an effect is bypassed, an instrument stays silent). Save your project.");
+        auto options = juce::MessageBoxOptions().withIconType (juce::MessageBoxIconType::WarningIcon).withTitle (tr ("Plugin crashed"));
+        if (! onLoad)
+            options = options.withMessage (message + " " + tr ("Reload starts it again with the settings from the last save or backup."))
+                          .withButton (tr ("Reload"));
+        else
+            options = options.withMessage (message);
+        juce::AlertWindow::showAsync (options.withButton (tr ("Close")),
+                                      [safe = juce::Component::SafePointer<MainComponent> (this), crashedName, onLoad] (int result) {
+                                          if (safe != nullptr && result == 1 && ! onLoad)
                                               safe->reloadCrashedPlugins (crashedName);
                                       });
     }

+ 81 - 13
tools/testplugin/lynx_test_crash.c

@@ -1,18 +1,26 @@
-/* A CLAP effect that crashes on purpose, for testing LYNX's crash protection (round 111):
- *   zig cc -shared -O2 -target x86_64-windows-gnu -Ithird_party/clap/include tools/testplugin/lynx_test_crash.c -luser32 -lgdi32 \
- *       -o "LYNX Test Crash.clap"
+/* A CLAP effect that crashes on purpose, for testing LYNX's crash protection (round 111; Linux / macOS: round 190dt):
+ *   Windows: zig cc -shared -O2 -target x86_64-windows-gnu -Ithird_party/clap/include tools/testplugin/lynx_test_crash.c -luser32 -lgdi32 \
+ *                -o "LYNX Test Crash.clap"
+ *   Linux / macOS: cc -shared -fPIC -O2 -Ithird_party/clap/include tools/testplugin/lynx_test_crash.c -o "LYNX Test Crash.clap"
+ * Otherwise a 0.5 gain (in -> out), with a 4-byte state ("LXC1").
  * Environment variable LYNX_TEST_CRASH:
- *   "process" - an access violation in the 20th process() call (LYNX.exe --plugintest: the slot must be switched off,
- *               the render must finish)
- *   "exit"    - a fail-fast (0xC0000409) when the DLL is unloaded at process exit, like the Waves shell whose teardown
- *               crashed LYNX's scan child (LYNX.exe --scantest: the plugin must be found, not blacklisted)
- *   "editor"  - (issue #32, round 174a) an access violation in its own editor window's procedure, on the window's
- *               first WM_TIMER (~0.3 s after it opens), like the synth editor that took LYNX down
+ *   "process" - a null-pointer write (access violation / SIGSEGV) in the Nth process() call, N = LYNX_TEST_CRASH_AFTER
+ *               (default 20); counted per loaded module, so an instance made again later does not crash again
+ *               (LYNX --plugintest / --crashguardtest: the slot must be switched off, the render must finish)
+ *   "memcpy"  - the same, but as a memcpy from a null pointer (the fault is inside the C library, issue #155)
+ *   "state"   - a null-pointer write when a saved state is loaded into it (state extension load)
+ *   "exit"    - (Windows) a fail-fast (0xC0000409) when the DLL is unloaded at process exit, like the Waves shell whose
+ *               teardown crashed LYNX's scan child (LYNX.exe --scantest: the plugin must be found, not blacklisted)
+ *   "editor"  - (Windows; issue #32, round 174a) an access violation in its own editor window's procedure, on the
+ *               window's first WM_TIMER (~0.3 s after it opens), like the synth editor that took LYNX down
  *               (LYNX.exe --editorcrashtest: the editor must be closed, LYNX must keep running)
- * Its editor (CLAP gui, Win32 child window) is a plain grey 240x120 window.
+ * Its editor (CLAP gui, Win32 child window; Windows only) is a plain grey 240x120 window.
  */
-#include <windows.h>
+#if defined(_WIN32)
+ #include <windows.h>
+#endif
 #include <clap/clap.h>
+#include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
 
@@ -48,21 +56,57 @@ static void p_stop (const clap_plugin_t* p) { (void) p; }
 static void p_reset (const clap_plugin_t* p) { (void) p; }
 static int crash_mode (const char* what)
 {
+#if defined(_WIN32)
     char value[32] = { 0 };
     return GetEnvironmentVariableA ("LYNX_TEST_CRASH", value, sizeof (value)) > 0 && strcmp (value, what) == 0;
+#else
+    const char* value = getenv ("LYNX_TEST_CRASH");
+    return value != NULL && strcmp (value, what) == 0;
+#endif
+}
+static int crash_after (void)
+{
+#if defined(_WIN32)
+    char value[32] = { 0 };
+    const int n = GetEnvironmentVariableA ("LYNX_TEST_CRASH_AFTER", value, sizeof (value)) > 0 ? atoi (value) : 0;
+#else
+    const char* value = getenv ("LYNX_TEST_CRASH_AFTER");
+    const int n = value != NULL ? atoi (value) : 0;
+#endif
+    return n > 0 ? n : 20;
+}
+static volatile int sink = 0;
+static void null_write (void)
+{
+    volatile uintptr_t address = 0; /* (opaque: a compiler may drop a write to a constant null) */
+    *(volatile int*) address = 1;
+}
+static void null_copy (void)
+{
+    char to[64];
+    const char* volatile from = NULL;
+    volatile size_t size = sizeof (to); /* (a real call into the C library) */
+    memcpy (to, (const char*) from, size);
+    sink = to[0];
 }
 static clap_process_status p_process (const clap_plugin_t* p, const clap_process_t* proc)
 {
     static int calls = 0;
     (void) p;
-    if (++calls == 20 && crash_mode ("process"))
-        *(volatile int*) (uintptr_t) 0 = 1;
+    if (++calls == crash_after())
+    {
+        if (crash_mode ("process"))
+            null_write();
+        if (crash_mode ("memcpy"))
+            null_copy();
+    }
     if (proc->audio_inputs_count < 1 || proc->audio_outputs_count < 1) return CLAP_PROCESS_CONTINUE;
     for (uint32_t c = 0; c < 2 && c < proc->audio_inputs[0].channel_count && c < proc->audio_outputs[0].channel_count; ++c)
         for (uint32_t i = 0; i < proc->frames_count; ++i)
             proc->audio_outputs[0].data32[c][i] = 0.5f * proc->audio_inputs[0].data32[c][i];
     return CLAP_PROCESS_CONTINUE;
 }
+#if defined(_WIN32)
 /* the editor: one child window; "editor" mode crashes in its window procedure */
 static HWND editor_window = NULL;
 static LRESULT CALLBACK editor_proc (HWND h, UINT m, WPARAM w, LPARAM l)
@@ -121,11 +165,33 @@ static bool g_hide (const clap_plugin_t* p) { (void) p; if (editor_window != NUL
 static const clap_plugin_gui_t gui = { g_api, g_preferred, g_create, g_destroy, g_scale, g_size, g_can_resize, g_hints, g_adjust,
                                        g_set_size, g_parent, g_transient, g_title, g_show, g_hide };
 
+#endif
+
+/* state: 4 bytes; "state" mode crashes when one is loaded */
+static bool s_save (const clap_plugin_t* p, const clap_ostream_t* stream)
+{
+    (void) p;
+    return stream->write (stream, "LXC1", 4) == 4;
+}
+static bool s_load (const clap_plugin_t* p, const clap_istream_t* stream)
+{
+    char data[4];
+    (void) p;
+    if (crash_mode ("state"))
+        null_write();
+    return stream->read (stream, data, 4) == 4;
+}
+static const clap_plugin_state_t state_ext = { s_save, s_load };
+
 static const void* p_extension (const clap_plugin_t* p, const char* id)
 {
     (void) p;
+#if defined(_WIN32)
     if (strcmp (id, CLAP_EXT_GUI) == 0)
         return &gui;
+#endif
+    if (strcmp (id, CLAP_EXT_STATE) == 0)
+        return &state_ext;
     return strcmp (id, CLAP_EXT_AUDIO_PORTS) == 0 ? &audio_ports : NULL;
 }
 static void p_main_thread (const clap_plugin_t* p) { (void) p; }
@@ -151,6 +217,7 @@ static const void* e_factory (const char* id) { return strcmp (id, CLAP_PLUGIN_F
 
 CLAP_EXPORT const clap_plugin_entry_t clap_entry = { CLAP_VERSION_INIT, e_init, e_deinit, e_factory };
 
+#if defined(_WIN32)
 BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID reserved)
 {
     (void) instance;
@@ -158,3 +225,4 @@ BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID reserved)
         __fastfail (7);
     return TRUE;
 }
+#endif

+ 323 - 0
tools/testplugin/lynx_test_crash_vst3.cpp

@@ -0,0 +1,323 @@
+// A VST3 effect that crashes on purpose (round 190dt: LYNX's plugin crash guard on Linux / macOS, and Windows' SEH
+// guard through JUCE's VST3 host). Main stereo in -> out at 0.5 gain, a 4-byte state ("LXV1"); no parameters, no
+// editor. Built only against the VST3 SDK's pluginterfaces (no SDK helper classes), like lynx_test_sidechain_vst3.cpp.
+// Environment variable LYNX_TEST_CRASH:
+//   "process" - a null-pointer write (SIGSEGV / access violation) in the Nth process() call with audio,
+//               N = LYNX_TEST_CRASH_AFTER (default 20); counted per loaded module, so an instance made again later
+//               (LYNX's Reload) does not crash again
+//   "memcpy"  - the same as a memcpy from a null pointer: the fault is inside the C library (what nih-plug did, #155)
+//   "state"   - a null-pointer write when a saved state is loaded into it (IComponent::setState)
+//
+//   V=<JUCE>/modules/juce_audio_processors/format_types/VST3_SDK
+//   Linux:   B="LYNX Test Crash.vst3/Contents/x86_64-linux"; mkdir -p "$B"
+//            c++ -shared -fPIC -O2 -std=c++17 -I$V tools/testplugin/lynx_test_crash_vst3.cpp
+//                $V/pluginterfaces/base/funknown.cpp -o "$B/LYNX Test Crash.so"                 (one line)
+//   Windows: zig c++ -shared -O2 -std=c++17 -target x86_64-windows-gnu -I$V tools/testplugin/lynx_test_crash_vst3.cpp
+//                $V/pluginterfaces/base/funknown.cpp -lole32 -o "LYNX Test Crash.vst3"          (one line)
+//   then:    LYNX_TEST_CRASH=process LYNX --crashguardtest "LYNX Test Crash.vst3" report.txt
+#define INIT_CLASS_IID
+#include "pluginterfaces/base/funknown.h"
+#include "pluginterfaces/base/ipluginbase.h"
+#include "pluginterfaces/base/ibstream.h"
+#include "pluginterfaces/vst/ivstaudioprocessor.h"
+#include "pluginterfaces/vst/ivstcomponent.h"
+#include "pluginterfaces/vst/ivsteditcontroller.h"
+#include "pluginterfaces/gui/iplugview.h"
+
+#include <atomic>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+
+#if defined(_WIN32)
+ #include <windows.h>
+ #define LYNX_TEST_EXPORT __declspec (dllexport)
+#else
+ #define LYNX_TEST_EXPORT __attribute__ ((visibility ("default")))
+#endif
+
+using namespace Steinberg;
+using namespace Steinberg::Vst;
+
+namespace
+{
+const FUID effectUid (0x4C594E58, 0x43524153, 0x48313930, 0x44545633); // "LYNXCRASH190DTV3"
+
+// (read at every use: the host may change them between calls; on Windows from the process, not this DLL's C runtime)
+const char* environment (const char* name, char (&buffer)[32])
+{
+#if defined(_WIN32)
+    return GetEnvironmentVariableA (name, buffer, sizeof (buffer)) > 0 ? buffer : nullptr;
+#else
+    (void) buffer;
+    return std::getenv (name);
+#endif
+}
+
+bool crashMode (const char* what)
+{
+    char buffer[32] {};
+    const char* value = environment ("LYNX_TEST_CRASH", buffer);
+    return value != nullptr && std::strcmp (value, what) == 0;
+}
+
+int crashAfter()
+{
+    char buffer[32] {};
+    const char* value = environment ("LYNX_TEST_CRASH_AFTER", buffer);
+    const auto n = value != nullptr ? std::atoi (value) : 0;
+    return n > 0 ? n : 20;
+}
+
+volatile int sink = 0;
+std::atomic<int> processCalls { 0 }; // (per module)
+
+#if defined(__GNUC__) || defined(__clang__)
+__attribute__ ((noinline))
+#endif
+void nullWrite()
+{
+    volatile std::uintptr_t address = 0; // (opaque: a write to a constant null is undefined, and g++ drops the whole path)
+    *reinterpret_cast<volatile int*> (address) = 1;
+}
+
+#if defined(__GNUC__) || defined(__clang__)
+__attribute__ ((noinline))
+#endif
+void nullCopy()
+{
+    char to[64];
+    const char* volatile from = nullptr;
+    volatile std::size_t size = sizeof (to); // (a real call into the C library)
+    std::memcpy (to, (const char*) from, size);
+    sink = to[0];
+}
+
+void copyString (String128 to, const char* from)
+{
+    int i = 0;
+    for (; from[i] != 0 && i < 127; ++i)
+        to[i] = (char16) from[i];
+    to[i] = 0;
+}
+
+class TestCrash final : public IComponent, public IAudioProcessor, public IEditController
+{
+public:
+    // FUnknown
+    tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
+    {
+        if (FUnknownPrivate::iidEqual (iid, FUnknown::iid) || FUnknownPrivate::iidEqual (iid, IPluginBase::iid)
+            || FUnknownPrivate::iidEqual (iid, IComponent::iid))
+        {
+            addRef();
+            *obj = static_cast<IComponent*> (this);
+            return kResultOk;
+        }
+        if (FUnknownPrivate::iidEqual (iid, IAudioProcessor::iid))
+        {
+            addRef();
+            *obj = static_cast<IAudioProcessor*> (this);
+            return kResultOk;
+        }
+        if (FUnknownPrivate::iidEqual (iid, IEditController::iid))
+        {
+            addRef();
+            *obj = static_cast<IEditController*> (this);
+            return kResultOk;
+        }
+        *obj = nullptr;
+        return kNoInterface;
+    }
+    uint32 PLUGIN_API addRef() override { return ++refs; }
+    uint32 PLUGIN_API release() override
+    {
+        const auto r = --refs;
+        if (r == 0)
+            delete this;
+        return r;
+    }
+
+    // IPluginBase
+    tresult PLUGIN_API initialize (FUnknown*) override { return kResultOk; }
+    tresult PLUGIN_API terminate() override { return kResultOk; }
+
+    // IComponent: one stereo main input and output
+    tresult PLUGIN_API getControllerClassId (TUID) override { return kNotImplemented; } // single component
+    tresult PLUGIN_API setIoMode (IoMode) override { return kResultOk; }
+    int32 PLUGIN_API getBusCount (MediaType type, BusDirection) override { return type == kAudio ? 1 : 0; }
+    tresult PLUGIN_API getBusInfo (MediaType type, BusDirection dir, int32 index, BusInfo& bus) override
+    {
+        if (type != kAudio || index != 0)
+            return kInvalidArgument;
+        std::memset (&bus, 0, sizeof (bus));
+        bus.mediaType = type;
+        bus.direction = dir;
+        bus.channelCount = 2;
+        bus.busType = kMain;
+        bus.flags = BusInfo::kDefaultActive;
+        copyString (bus.name, dir == kOutput ? "Output" : "Input");
+        return kResultOk;
+    }
+    tresult PLUGIN_API getRoutingInfo (RoutingInfo&, RoutingInfo&) override { return kNotImplemented; }
+    tresult PLUGIN_API activateBus (MediaType, BusDirection, int32, TBool) override { return kResultOk; }
+    tresult PLUGIN_API setActive (TBool) override { return kResultOk; }
+    tresult PLUGIN_API setState (IBStream* stream) override
+    {
+        if (crashMode ("state"))
+            nullWrite();
+        char data[4] {};
+        int32 read = 0;
+        if (stream != nullptr)
+            stream->read (data, 4, &read);
+        return kResultOk;
+    }
+    tresult PLUGIN_API getState (IBStream* stream) override
+    {
+        int32 written = 0;
+        return stream != nullptr ? stream->write (const_cast<char*> ("LXV1"), 4, &written) : kInvalidArgument;
+    }
+
+    // IAudioProcessor
+    tresult PLUGIN_API setBusArrangements (SpeakerArrangement* ins, int32 numIns, SpeakerArrangement* outs, int32 numOuts) override
+    {
+        return numIns == 1 && numOuts == 1 && ins[0] == SpeakerArr::kStereo && outs[0] == SpeakerArr::kStereo ? kResultTrue : kResultFalse;
+    }
+    tresult PLUGIN_API getBusArrangement (BusDirection, int32 index, SpeakerArrangement& arr) override
+    {
+        if (index != 0)
+            return kInvalidArgument;
+        arr = SpeakerArr::kStereo;
+        return kResultOk;
+    }
+    tresult PLUGIN_API canProcessSampleSize (int32 size) override { return size == kSample32 ? kResultTrue : kResultFalse; }
+    uint32 PLUGIN_API getLatencySamples() override { return 0; }
+    tresult PLUGIN_API setupProcessing (ProcessSetup&) override { return kResultOk; }
+    tresult PLUGIN_API setProcessing (TBool) override { return kResultOk; }
+    uint32 PLUGIN_API getTailSamples() override { return 0; }
+
+    tresult PLUGIN_API process (ProcessData& data) override
+    {
+        const auto n = data.numSamples;
+        if (n <= 0 || data.numOutputs < 1 || data.outputs == nullptr || data.outputs[0].numChannels < 2)
+            return kResultOk; // (a parameter flush)
+        if (++processCalls == crashAfter())
+        {
+            if (crashMode ("process"))
+                nullWrite();
+            if (crashMode ("memcpy"))
+                nullCopy();
+        }
+        auto& out = data.outputs[0];
+        for (int c = 0; c < 2; ++c)
+        {
+            auto* to = out.channelBuffers32[c];
+            const auto* from = data.numInputs > 0 && data.inputs != nullptr && data.inputs[0].numChannels > c
+                                       && data.inputs[0].channelBuffers32 != nullptr
+                                   ? data.inputs[0].channelBuffers32[c]
+                                   : nullptr;
+            if (to == nullptr)
+                continue;
+            for (int32 s = 0; s < n; ++s)
+                to[s] = from != nullptr ? 0.5f * from[s] : 0.0f;
+        }
+        return kResultOk;
+    }
+
+    // IEditController (no parameters, no editor)
+    tresult PLUGIN_API setComponentState (IBStream*) override { return kResultOk; }
+    int32 PLUGIN_API getParameterCount() override { return 0; }
+    tresult PLUGIN_API getParameterInfo (int32, ParameterInfo&) override { return kInvalidArgument; }
+    tresult PLUGIN_API getParamStringByValue (ParamID, ParamValue, String128) override { return kInvalidArgument; }
+    tresult PLUGIN_API getParamValueByString (ParamID, TChar*, ParamValue&) override { return kInvalidArgument; }
+    ParamValue PLUGIN_API normalizedParamToPlain (ParamID, ParamValue v) override { return v; }
+    ParamValue PLUGIN_API plainParamToNormalized (ParamID, ParamValue v) override { return v; }
+    ParamValue PLUGIN_API getParamNormalized (ParamID) override { return 0.0; }
+    tresult PLUGIN_API setParamNormalized (ParamID, ParamValue) override { return kResultOk; }
+    tresult PLUGIN_API setComponentHandler (IComponentHandler*) override { return kResultOk; }
+    IPlugView* PLUGIN_API createView (FIDString) override { return nullptr; }
+
+private:
+    std::atomic<uint32> refs { 1 };
+};
+
+class Factory final : public IPluginFactory2
+{
+public:
+    tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
+    {
+        if (FUnknownPrivate::iidEqual (iid, FUnknown::iid) || FUnknownPrivate::iidEqual (iid, IPluginFactory::iid)
+            || FUnknownPrivate::iidEqual (iid, IPluginFactory2::iid))
+        {
+            *obj = static_cast<IPluginFactory2*> (this);
+            return kResultOk;
+        }
+        *obj = nullptr;
+        return kNoInterface;
+    }
+    uint32 PLUGIN_API addRef() override { return 1; }
+    uint32 PLUGIN_API release() override { return 1; }
+
+    tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
+    {
+        std::memset (static_cast<void*> (info), 0, sizeof (*info));
+        std::strcpy (info->vendor, "LYNX");
+        std::strcpy (info->url, "https://github.com/Ka1-S/LYNX-SHARE");
+        info->flags = PFactoryInfo::kUnicode;
+        return kResultOk;
+    }
+    int32 PLUGIN_API countClasses() override { return 1; }
+    tresult PLUGIN_API getClassInfo (int32 index, PClassInfo* info) override
+    {
+        if (index != 0)
+            return kInvalidArgument;
+        std::memset (static_cast<void*> (info), 0, sizeof (*info));
+        effectUid.toTUID (info->cid);
+        info->cardinality = PClassInfo::kManyInstances;
+        std::strcpy (info->category, kVstAudioEffectClass);
+        std::strcpy (info->name, "LYNX Test Crash VST3");
+        return kResultOk;
+    }
+    tresult PLUGIN_API getClassInfo2 (int32 index, PClassInfo2* info) override
+    {
+        if (index != 0)
+            return kInvalidArgument;
+        std::memset (static_cast<void*> (info), 0, sizeof (*info));
+        effectUid.toTUID (info->cid);
+        info->cardinality = PClassInfo::kManyInstances;
+        std::strcpy (info->category, kVstAudioEffectClass);
+        std::strcpy (info->name, "LYNX Test Crash VST3");
+        std::strcpy (info->subCategories, "Fx");
+        std::strcpy (info->vendor, "LYNX");
+        std::strcpy (info->version, "1.0.0");
+        std::strcpy (info->sdkVersion, "VST 3.7");
+        return kResultOk;
+    }
+    tresult PLUGIN_API createInstance (FIDString cid, FIDString iid, void** obj) override
+    {
+        if (! FUnknownPrivate::iidEqual (cid, effectUid.toTUID()))
+        {
+            *obj = nullptr;
+            return kNoInterface;
+        }
+        auto* effect = new TestCrash();
+        const auto result = effect->queryInterface (iid, obj);
+        effect->release();
+        return result;
+    }
+};
+
+Factory factory;
+} // namespace
+
+extern "C"
+{
+LYNX_TEST_EXPORT IPluginFactory* PLUGIN_API GetPluginFactory() { return static_cast<IPluginFactory2*> (&factory); }
+#if defined(_WIN32)
+LYNX_TEST_EXPORT bool InitDll() { return true; }
+LYNX_TEST_EXPORT bool ExitDll() { return true; }
+#else
+LYNX_TEST_EXPORT bool ModuleEntry (void*) { return true; }
+LYNX_TEST_EXPORT bool ModuleExit() { return true; }
+#endif
+}