libstdc++'s std::regex matcher recurses about once per matched character, so '.*', 'a+' or '(a|b)*' on a line of a few tens of thousands of characters (minified JS/JSON) overflowed the 8 MiB stack and crashed the editor from the regex search prompt or regex replace. Regex search and regex replace now run their matching on a worker thread with a 1 GiB reserved stack (RunWithLargeStack; the caller waits, so nothing is shared concurrently). Renderers skip regex match highlighting on lines over 10,000 bytes. Catastrophic backtracking (e.g. (a*)*b) is still possible: std::regex has no time limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015rcVQiiWyTzoNrsvLSaAfB
52 lines
971 B
C++
52 lines
971 B
C++
#include "RegexGuard.h"
|
|
|
|
#include <exception>
|
|
#include <pthread.h>
|
|
|
|
namespace kte {
|
|
namespace {
|
|
// 1 GiB supports matches spanning several million characters.
|
|
constexpr std::size_t kLargeStackBytes = std::size_t{1} << 30;
|
|
|
|
struct Job {
|
|
const std::function<void()> *fn;
|
|
std::exception_ptr error;
|
|
};
|
|
|
|
|
|
void *
|
|
run_job(void *arg)
|
|
{
|
|
auto *job = static_cast<Job *>(arg);
|
|
try {
|
|
(*job->fn)();
|
|
} catch (...) {
|
|
job->error = std::current_exception();
|
|
}
|
|
return nullptr;
|
|
}
|
|
} // namespace
|
|
|
|
|
|
void
|
|
RunWithLargeStack(const std::function<void()> &fn)
|
|
{
|
|
Job job{&fn, nullptr};
|
|
pthread_attr_t attr;
|
|
bool started = false;
|
|
pthread_t tid{};
|
|
if (pthread_attr_init(&attr) == 0) {
|
|
if (pthread_attr_setstacksize(&attr, kLargeStackBytes) == 0)
|
|
started = pthread_create(&tid, &attr, run_job, &job) == 0;
|
|
pthread_attr_destroy(&attr);
|
|
}
|
|
if (!started) {
|
|
fn();
|
|
return;
|
|
}
|
|
pthread_join(tid, nullptr);
|
|
if (job.error)
|
|
std::rethrow_exception(job.error);
|
|
}
|
|
} // namespace kte
|