diff --git a/CHANGELOG.md b/CHANGELOG.md index df5b3511..1bea1523 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## [unreleased] +### Fixed + +- `bb build` and `bb test` could crash with exit code 139 (SIGSEGV) right after "Build done" on Linux and macOS when + the project uses TypeScript running in V8. Pooled JavaScript engines were disposed on a background thread while the + process was already exiting, and V8 keeps running background tasks even after the engines are disposed, while exit + tears down V8's native global state. Both commands now wait until the engines are disposed, and bb ends the + process without running native static destructors. A type check failing with an exception now always returns its + compiler to the pool, and the CSS processor used for bundling is disposed. + ## 7.1.4 ### Fixed diff --git a/Lib/Composition/BuildCtx.cs b/Lib/Composition/BuildCtx.cs index 725db2fa..31645f24 100644 --- a/Lib/Composition/BuildCtx.cs +++ b/Lib/Composition/BuildCtx.cs @@ -288,13 +288,21 @@ void DoTypeCheck(TypeCheckChange type) } _typeChecker = CreateTypeChecker(); - if (_nativeTypeScriptDirectory != null) - ShowNativeTypeChecker(_typeChecker.GetTSVersion()); - _typeChecker.ClearDiagnostics(); - _typeChecker.CheckProgram(_currentDirectory, MakeSourceListArray()); - _lastSemantics = _typeChecker.GetDiagnostics().ToList(); - ReleaseTypeChecker(_typeChecker); - _typeChecker = null; + try + { + if (_nativeTypeScriptDirectory != null) + ShowNativeTypeChecker(_typeChecker.GetTSVersion()); + _typeChecker.ClearDiagnostics(); + _typeChecker.CheckProgram(_currentDirectory, MakeSourceListArray()); + _lastSemantics = _typeChecker.GetDiagnostics().ToList(); + } + finally + { + // Always return it to the pool, CompilerPool.FreeMemory waits for all borrowed compilers + ReleaseTypeChecker(_typeChecker); + _typeChecker = null; + } + return; } diff --git a/Lib/Composition/Composition.cs b/Lib/Composition/Composition.cs index fa195787..8bcfeb8b 100644 --- a/Lib/Composition/Composition.cs +++ b/Lib/Composition/Composition.cs @@ -732,6 +732,7 @@ void RunBuild(BuildCommand bCommand) var errors = 0; var warnings = 0; var messages = new List(); + Task? freeMemory = null; try { _logger.WriteLine("Build started " + proj.Owner.Owner.FullPath, ConsoleColor.Blue); @@ -751,7 +752,7 @@ void RunBuild(BuildCommand bCommand) bCommand.UpdateTranslations.Value ? "no" : bCommand.TypeCheck.Value!); ctx.Build(proj, true, buildResult, _mainBuildResult, 1, includeTestSourcesInBuild: false); ctx.BuildSubProjects(proj, true, buildResult, _mainBuildResult, 1); - _compilerPool.FreeMemory().GetAwaiter(); + freeMemory = _compilerPool.FreeMemory(); if (!ctx.OnlyTypeCheck) proj.FillOutputByAdditionalResourcesDirectory(buildResult.Modules, _mainBuildResult); IncludeMessages(proj, buildResult, ref errors, ref warnings, messages); @@ -812,9 +813,24 @@ void RunBuild(BuildCommand bCommand) $"Build done in {duration.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)}s with {Plural(errors, "error")} and {Plural(warnings, "warning")} and has {Plural(_mainBuildResult.FilesContent.Count, "file")}{_mainBuildResult.TranspileStats}", color); + WaitForJsEnginesDisposal(freeMemory); Environment.ExitCode = errors != 0 ? 1 : 0; } + // FreeMemory disposes pooled V8 engines once the background type check returns its compiler. Process exit must + // not race with that disposal (or with a still running type check), otherwise ClearScript crashes with SIGSEGV. + void WaitForJsEnginesDisposal(Task? freeMemory) + { + try + { + (freeMemory ?? _compilerPool.FreeMemory()).Wait(); + } + catch (Exception ex) + { + _logger.Error("Failed to dispose JavaScript engines: " + ex); + } + } + void PrintMessages(IList messages, bool onlySemantic = false) { foreach (var message in messages) @@ -892,6 +908,7 @@ void RunTest(TestCommand testCommand) var incompleteTest = false; var messages = new List(); var totalFiles = 0; + Task? freeMemory = null; try { _logger.WriteLine("Test build started " + proj.Owner.Owner.FullPath, ConsoleColor.Blue); @@ -914,7 +931,7 @@ void RunTest(TestCommand testCommand) proj.FillOutputByAdditionalResourcesDirectory(testBuildResult.Modules, _mainBuildResult); fastBundle.Build("bb/base", true); fastBundle.BuildHtml(true); - _compilerPool.FreeMemory().GetAwaiter(); + freeMemory = _compilerPool.FreeMemory(); if (testCommand.Dir.Value != null) { var startWrite = DateTime.UtcNow; @@ -1075,6 +1092,7 @@ void RunTest(TestCommand testCommand) } } + WaitForJsEnginesDisposal(freeMemory); Environment.ExitCode = errors + testFailures != 0 || incompleteTest ? 1 : 0; _logger.Info("Exiting with code " + Environment.ExitCode); } diff --git a/Lib/TSCompiler/NjsastBundleBundler.cs b/Lib/TSCompiler/NjsastBundleBundler.cs index 617e0419..b8357a55 100644 --- a/Lib/TSCompiler/NjsastBundleBundler.cs +++ b/Lib/TSCompiler/NjsastBundleBundler.cs @@ -80,7 +80,7 @@ public void Build(bool compress, bool mangle, bool beautify, bool buildSourceMap if (cssToBundle.Count > 0) { string cssPath = _mainBuildResult.AllocateName("bundle.css"); - var cssProcessor = new CssProcessor(_project.Tools); + using var cssProcessor = new CssProcessor(_project.Tools); cssProcessor.ForceNativeCss = _project.Future; var cssContent = cssProcessor.ConcatenateAndMinifyCss(cssToBundle, (string url, string from) => { diff --git a/bb/Program.cs b/bb/Program.cs index 1e2e9779..f0b9a847 100644 --- a/bb/Program.cs +++ b/bb/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.InteropServices; using System.Threading.Tasks; using Lib.DiskCache; using Lib.Utils.Logger; @@ -16,5 +17,25 @@ static async Task Main(string[] args) composition.ParseCommandLine(args); await composition.RunCommand(); + SkipNativeDestructorsOnExit(); } -} \ No newline at end of file + + // V8 (ClearScript) runs its background tasks on .NET thread pool threads and frees pooled heap pages asynchronously + // after an engine is disposed. Regular exit() runs C++ static destructors of ClearScriptV8 while such a task can + // still be running, which crashes the process with SIGSEGV (exit code 139) after successful build. Registered last, + // so all other ProcessExit handlers already ran, it ends the process without running native destructors. + static void SkipNativeDestructorsOnExit() + { + if (OperatingSystem.IsWindows()) + return; + AppDomain.CurrentDomain.ProcessExit += (_, _) => + { + Console.Out.Flush(); + Console.Error.Flush(); + SysExit(Environment.ExitCode); + }; + } + + [DllImport("libc", EntryPoint = "_exit")] + static extern void SysExit(int status); +}