diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index 5cfa0751f..b7bfe2caf 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -1505,7 +1505,9 @@ struct TryOpLowering : public TsPattern // unwinding, and terminates. Thrown from a catch it is a nested exception, which replaces the // first, as JavaScript's does. // Such a finally is entered through a catch-all pad instead, which rethrows at its end - // (see windowsFinallyCatches and linuxFinallyCatches). + // (see windowsFinallyCatches and linuxFinallyCatches). The cleanup region - a `using`'s + // `[Symbol.dispose]()` on the way out - throws the same way, and is entered the same way + // (windowsCleanupCatches). mlir::SmallVector escapingOpsFinally; auto finallyHasTry = false; auto finallyMayThrow = false; @@ -1529,6 +1531,9 @@ struct TryOpLowering : public TsPattern auto cleanupHasOps = llvm::any_of(tryOp.getCleanup(), [](auto &block) { return &block.front() != block.getTerminator(); }); + auto cleanupMayThrow = false; + tryOp.getCleanup().walk([&](Operation *op) { cleanupMayThrow |= unwindsToHandler(op); }); + auto windowsCleanupCatches = tsContext->compileOptions.isWindows && cleanupHasOps && cleanupMayThrow; // an empty `catch { }` still catches: HAS_CATCH_ATTR_NAME tells it from no catch clause auto catchHasOps = tryOp->hasAttr(HAS_CATCH_ATTR_NAME) || @@ -1546,14 +1551,54 @@ struct TryOpLowering : public TsPattern rewriter.create(loc, bodyBlock, ValueRange{}); // cleanup - auto linuxHasCleanups = cleanupHasOps && !tsContext->compileOptions.isWindows; + // On the Itanium path the cleanup shares its landing pad with this try's catch (or finally), + // and runs before it with nothing caught, so what a `[Symbol.dispose]()` throws there has no + // edge into that catch: it left the function, and with nothing outside to catch it the + // process terminated. A cleanup that may throw with a catch or a finally of its own is a + // catch-all of its own instead, which unwinds and rethrows to them (linuxCleanupCatches), + // and the catch and the finally lower as they do with no cleanup. + auto linuxCleanupCatches = cleanupHasOps && !tsContext->compileOptions.isWindows && cleanupMayThrow && + (catchHasOps || finallyHasOps); + auto linuxHasCleanups = cleanupHasOps && !tsContext->compileOptions.isWindows && !linuxCleanupCatches; + // A disposal that throws in the cleanup must not skip the rest of it: the releases after it + // were a leak on that path (the ownership verifier's report), and the resources still to + // dispose went undisposed. Its calls unwind to a copy of the cleanup instead (retryBlock), + // entered through a catch-all, which hands what was thrown on once it has run. The cleanup + // runs again safely: each disposal's flag is cleared before its call, so the copy skips the + // one that threw and those already done, and the releases come after every disposal. The + // copy's own calls are given no unwind edge here: a second disposal that throws is a nested + // exception there, and the rest of the copy is skipped (00using_dispose_throws.ts). + auto cleanupRetries = cleanupHasOps && cleanupMayThrow && (catchHasOps || finallyHasOps || enclosingHandler); mlir::Block * cleanupBlock = nullptr; mlir::Block * cleanupBlockLast = nullptr; + mlir::Block * retryBlock = nullptr; + mlir::Block * retryBlockLast = nullptr; if (cleanupHasOps) { - rewriter.inlineRegionBefore(tryOp.getCleanup(), continuation); + if (cleanupRetries) + { + mlir::IRMapping retryMapping; + rewriter.cloneRegionBefore(tryOp.getCleanup(), *continuation->getParent(), continuation->getIterator(), + retryMapping); + retryBlock = bodyBlockLast->getNextNode(); + retryBlockLast = continuation->getPrevNode(); + } + + rewriter.inlineRegionBefore(tryOp.getCleanup(), retryBlock ? retryBlock : continuation); cleanupBlock = bodyBlockLast->getNextNode(); - cleanupBlockLast = continuation->getPrevNode(); + cleanupBlockLast = (retryBlock ? retryBlock : continuation)->getPrevNode(); + + if (cleanupRetries) + { + // the copy's pad is nested in the cleanup's, and Win32ExceptionPass reads the nesting + // off the order of the code: the copy has to come before the cleanup's end. So the + // cleanup's terminator moves into a block of its own, after the copy. + auto *cleanupTail = rewriter.splitBlock(cleanupBlockLast, cleanupBlockLast->getTerminator()->getIterator()); + rewriter.moveBlockBefore(cleanupTail, continuation); + rewriter.setInsertionPointToEnd(cleanupBlockLast); + rewriter.create(loc, cleanupTail, ValueRange{}); + cleanupBlockLast = cleanupTail; + } } else { @@ -1915,6 +1960,35 @@ struct TryOpLowering : public TsPattern auto landingBlock = cleanupHasOps ? cleanupBlock : catchHasOps ? catchesBlock : finallyBlock; tsContext->landingBlockOf[tryOp.getOperation()] = landingBlock; + // the cleanup's calls unwind to `dest` (its copy, see cleanupRetries): nothing else gives + // them an unwind edge, as the body's walk below skips the region + auto unwindCleanupTo = [&](mlir::Block *dest) { + for (auto it = cleanupBlock;; it = it->getNextNode()) + { + // the copy sits inside the cleanup's blocks (see cleanupRetries), and its calls stay plain + if (it == retryBlock) + { + it = retryBlockLast; + continue; + } + + it->walk([&](Operation *op) { + if (unwindsToHandler(op)) + { + tsContext->unwind[op] = dest; + } + else if (mayCallInterfaceAccessor(op)) + { + tsFuncContext->accessorUnwinds.push_back({op, dest}); + } + }); + if (it == cleanupBlockLast) + { + break; + } + } + }; + if (landingBlock) { // TODO: check for nested ops for example in if block @@ -1989,11 +2063,38 @@ struct TryOpLowering : public TsPattern mlir::Value catchAll; if (enclosingHandler && finallyHasOps || linuxHasCleanups && rttih.hasType() || linuxCleanupOnlyChainsToParent || linuxTypedCatchChains || windowsFinallyCatches || - linuxFinallyCatches) + windowsCleanupCatches || linuxCleanupCatches || linuxFinallyCatches) { catchAll = (mlir::Value)rewriter.create(loc, mth.getNullType()); } + // see cleanupRetries: the cleanup's calls unwind to its copy, a catch-all inside the + // cleanup's own (cleanupPadId, Windows), which ends by rethrowing to `dest` + auto retryCleanupTo = [&](mlir::Block *dest, int cleanupPadId) { + unwindCleanupTo(retryBlock); + + rewriter.setInsertionPointToStart(retryBlock); + auto retryPadOp = rewriter.create(loc, rttih.getLandingPadType(), + rewriter.getBoolAttr(false), ValueRange{catchAll}); + rewriter.create(loc, mth.getOpaqueType(), retryPadOp); + + rewriter.setInsertionPoint(retryBlockLast->getTerminator()); + auto resultOpRetry = cast(retryBlockLast->getTerminator()); + if (tsContext->compileOptions.isWindows) + { + retryPadOp->setAttr(EH_PAD_ID_ATTR_NAME, rewriter.getI32IntegerAttr(++tsContext->nextCatchPadId)); + retryPadOp->setAttr(EH_PAD_PARENT_ATTR_NAME, rewriter.getI32IntegerAttr(cleanupPadId)); + rewriter.replaceOpWithNewOp(resultOpRetry, retryPadOp, + mlir::SmallVector{dest}); + } + else + { + auto nullVal = rewriter.create(loc, mth.getNullType()); + auto throwOp = rewriter.replaceOpWithNewOp(resultOpRetry, nullVal); + tsContext->unwind[throwOp] = dest; + } + }; + mlir::Value undefArrayValue; if (finallyHasOps || cleanupHasOps) { @@ -2019,10 +2120,25 @@ struct TryOpLowering : public TsPattern { rewriter.setInsertionPointToStart(cleanupBlock); - auto landingPadCleanupOp = rewriter.create( - loc, rttih.getLandingPadType(), rewriter.getBoolAttr(true), ValueRange{undefArrayValue}); - tagPad(landingPadCleanupOp, 0); - auto beginCleanupCallInfo = rewriter.create(loc); + // see windowsFinallyCatches: a cleanup that may throw is a catch-all, so that what it + // throws is a nested exception - which replaces the one unwinding - rather than one + // out of a cleanup funclet, which terminates + auto landingPadCleanupOp = + windowsCleanupCatches + ? rewriter.create(loc, rttih.getLandingPadType(), rewriter.getBoolAttr(false), + ValueRange{catchAll}) + : rewriter.create(loc, rttih.getLandingPadType(), rewriter.getBoolAttr(true), + ValueRange{undefArrayValue}); + auto cleanupPadId = windowsCleanupCatches ? ++tsContext->nextCatchPadId : 0; + tagPad(landingPadCleanupOp, cleanupPadId); + if (windowsCleanupCatches) + { + rewriter.create(loc, mth.getOpaqueType(), landingPadCleanupOp); + } + else + { + rewriter.create(loc); + } rewriter.setInsertionPoint(cleanupBlockLast->getTerminator()); mlir::SmallVector unwindDests; @@ -2045,6 +2161,12 @@ struct TryOpLowering : public TsPattern unwindDests.push_back(enclosingHandler); } + if (cleanupRetries) + { + retryCleanupTo(unwindDests.front(), cleanupPadId); + rewriter.setInsertionPoint(cleanupBlockLast->getTerminator()); + } + auto resultOpCleanup = cast(cleanupBlockLast->getTerminator()); rewriter.replaceOpWithNewOp(resultOpCleanup, landingPadCleanupOp, unwindDests); } @@ -2379,6 +2501,12 @@ struct TryOpLowering : public TsPattern loc, rttih.getLandingPadType(), rewriter.getBoolAttr(false), ValueRange{catchAll}); rewriter.create(loc, mth.getOpaqueType(), landingPadCleanupOp); + // and what a disposal throws goes there too, once the cleanup has run again + if (cleanupRetries) + { + retryCleanupTo(enclosingHandler, 0); + } + rewriter.setInsertionPoint(cleanupBlockLast->getTerminator()); auto nullVal = rewriter.create(loc, mth.getNullType()); @@ -2405,6 +2533,27 @@ struct TryOpLowering : public TsPattern mlir::SmallVector{}); } } + else if (linuxCleanupCatches) + { + // the linuxCleanupOnlyChainsToParent shape, with this try's own catch (or finally) for + // the parent: catch-all, the cleanup, then a rethrow that unwinds to it + auto *dest = catchHasOps ? catchesBlock : finallyBlock; + + rewriter.setInsertionPointToStart(cleanupBlock); + + auto landingPadCleanupOp = rewriter.create( + loc, rttih.getLandingPadType(), rewriter.getBoolAttr(false), ValueRange{catchAll}); + rewriter.create(loc, mth.getOpaqueType(), landingPadCleanupOp); + + retryCleanupTo(dest, 0); + + rewriter.setInsertionPoint(cleanupBlockLast->getTerminator()); + auto nullVal = rewriter.create(loc, mth.getNullType()); + + auto resultOpCleanup = cast(cleanupBlockLast->getTerminator()); + auto throwOp = rewriter.replaceOpWithNewOp(resultOpCleanup, nullVal); + tsContext->unwind[throwOp] = dest; + } rewriter.replaceOp(tryOp, continuation->getArguments()); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 0464e37b5..948730747 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -533,6 +533,7 @@ tslang_add_test(NAME test-compile-00-instanceof-namespace-narrowing COMMAND test tslang_add_test(NAME test-compile-00-global-initializer-branches COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00global_initializer_branches.ts") tslang_add_test(NAME test-compile-00-using-nested-scopes COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_nested_scopes.ts") tslang_add_test(NAME test-compile-00-using-unwind-progress COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_unwind_progress.ts") +tslang_add_test(NAME test-compile-00-using-dispose-throws COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_dispose_throws.ts") tslang_add_test(NAME test-compile-00-break-continue-scope-exit COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00break_continue_scope_exit.ts") tslang_add_test(NAME test-compile-00-owned-fields COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00owned_fields.ts") tslang_add_test(NAME test-compile-00-owned-elements COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00owned_elements.ts") @@ -1173,6 +1174,7 @@ tslang_add_test(NAME test-jit-00-instanceof-namespace-narrowing COMMAND test-run tslang_add_test(NAME test-jit-00-global-initializer-branches COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00global_initializer_branches.ts") tslang_add_test(NAME test-jit-00-using-nested-scopes COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_nested_scopes.ts") tslang_add_test(NAME test-jit-00-using-unwind-progress COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_unwind_progress.ts") +tslang_add_test(NAME test-jit-00-using-dispose-throws COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_dispose_throws.ts") tslang_add_test(NAME test-jit-00-break-continue-scope-exit COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00break_continue_scope_exit.ts") tslang_add_test(NAME test-jit-00-owned-fields COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00owned_fields.ts") tslang_add_test(NAME test-jit-00-owned-elements COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00owned_elements.ts") @@ -2580,6 +2582,7 @@ set(TSLANG_CORPUS 00union_to_any.ts 00union_type.ts 00using_nested_scopes.ts + 00using_dispose_throws.ts 00using_unwind_progress.ts 00var_bindings.ts 00vars.ts diff --git a/tslang/test/tester/tests/00nested_catch.ts b/tslang/test/tester/tests/00nested_catch.ts index fbb8e9ec9..1f5f5ec4e 100644 --- a/tslang/test/tester/tests/00nested_catch.ts +++ b/tslang/test/tester/tests/00nested_catch.ts @@ -13,12 +13,10 @@ // A try nested in a try *body* or in a `finally` always worked - only the catch clause was // affected, which is why nothing caught this. // -// These check which clause runs and in what order, and deliberately never read a catch -// variable's value. That is not squeamishness about the fix: reading one is broken on its own, -// with no nesting involved - `try { throw 2 } catch (v: int) { t = v }` in a module that throws -// only that one type reads 0 rather than 2, and reads correctly again once the module throws -// other types elsewhere. `00try_catch.ts` passes for that second reason. A separate bug, and -// nothing here should be made to depend on it. +// These check which clause runs and in what order, and never read a catch variable's value. +// When they were written, reading one was broken on its own under the JIT; that was item 5am +// (a type descriptor at the JIT image base read as `catch(...)`), since fixed and guarded by +// `00catch_value_minimal.ts`. // // See docs/reference-counting-evaluation.md section 9.29. diff --git a/tslang/test/tester/tests/00using_dispose_throws.ts b/tslang/test/tester/tests/00using_dispose_throws.ts new file mode 100644 index 000000000..0a070713e --- /dev/null +++ b/tslang/test/tester/tests/00using_dispose_throws.ts @@ -0,0 +1,227 @@ +// A `[Symbol.dispose]()` that throws while another exception is already unwinding through its +// `using`. It terminated the process, in every model, in both tiers, on both back ends. +// +// - Windows: the cleanup region ran in a cleanup funclet, and an exception out of a cleanup +// funclet is one thrown during unwinding to the MSVC personality, which terminates (0x80000003). +// A `finally` had the same problem and #733 entered it through a catch-all pad instead; the +// cleanup region is now entered the same way when it may throw (windowsCleanupCatches). +// - Linux: the cleanup shared its landing pad with the try's catch and ran before it, with +// nothing caught, and its dispose call had no unwind edge - so the new exception left the +// function, and with nothing outside to catch it the process terminated +// (linuxCleanupCatches). +// +// A disposal's throw sends the cleanup's calls to a copy of the cleanup (cleanupRetries), which +// runs the rest of it - the resources not yet disposed, and the releases, which the ownership +// verifier reported as skipped on that path - and then hands the new exception on. +// +// What the disposal throws REPLACES the exception it interrupted, as a throw in a `finally` +// does. That is not quite JavaScript: TC39's explicit resource management throws a +// `SuppressedError` carrying both. tslang has no `SuppressedError`; the remaining resources are +// disposed, as JavaScript does (`twoUsings`). +// +// A second disposal that throws, from the copy, is a nested exception there: it is not caught +// again in the copy, and the releases after it are skipped. Where it goes differs by back end - +// this try's catch on Windows, where the funclet's calls unwind with it; the caller on Linux - so +// `bothThrow` checks only what both do: nothing terminates, every resource is disposed, and the +// last exception thrown is the one that arrives. + +class Thrower { + [Symbol.dispose]() { + throw "from dispose"; + } +} + +let trail = ""; + +class Named { + constructor(private n: string) {} + [Symbol.dispose]() { + trail = trail + this.n; + } +} + +class NamedThrower { + constructor(private n: string) {} + [Symbol.dispose]() { + trail = trail + this.n; + throw "from " + this.n; + } +} + +// the plain shape: this try's own catch takes what the disposal throws +function inTryCatch() { + let s = ""; + try { + using d = new Thrower(); + throw "first"; + } catch (e: string) { + s = e; + } + + return s; +} + +// no catch on the try: its finally still runs, and the disposal's exception goes on outwards +function withFinallyOnly() { + let s = ""; + let fin = 0; + try { + try { + using d = new Thrower(); + throw "first"; + } finally { + fin = 1; + } + } catch (e: string) { + s = e; + } + + return s + fin; +} + +// a `using` in a block of its own inside the try: the block's cleanup hands on to the try around it +function inNestedBlock() { + let s = ""; + try { + { + using d = new Thrower(); + throw "first"; + } + } catch (e: string) { + s = e; + } + + return s; +} + +// nothing in the function catches: the caller does +function cleanupOnly() { + using d = new Thrower(); + throw "first"; +} + +function callerCatches() { + let s = ""; + try { + cleanupOnly(); + } catch (e: string) { + s = e; + } + + return s; +} + +// the inner catch takes a number, so the disposal's string goes on to the outer one +function innerCatchMismatch() { + let s = ""; + try { + try { + using d = new Thrower(); + throw 1; + } catch (e: number) { + s = "inner"; + } + } catch (e: string) { + s = e; + } + + return s; +} + +function inLoop() { + let s = ""; + for (let i = 0; i < 3; i++) { + try { + using d = new Thrower(); + if (i == 1) throw "first"; + } catch (e: string) { + s = s + i; + } + } + + return s; +} + +// on the way out of an exception, the cleanup goes on past a disposal that throws: `a` is disposed +function twoUsings() { + let s = ""; + trail = ""; + try { + using a = new Named("a"); + using b = new NamedThrower("B"); + throw "first"; + } catch (e: string) { + s = e; + } + + return s + "/" + trail; +} + +// both disposals throw: the second is thrown from the cleanup's copy (see the header) +function bothThrowInner() { + let s = ""; + try { + using a = new NamedThrower("A"); + using b = new NamedThrower("B"); + throw "first"; + } catch (e: string) { + s = e; + } + + return s; +} + +function bothThrow() { + let s = ""; + trail = ""; + try { + s = bothThrowInner(); + } catch (e: string) { + s = e; + } + + return s + "/" + trail; +} + +// on the normal path the same throw is from the body, so the cleanup still disposes `a` +function twoUsingsNormalPath() { + let s = ""; + trail = ""; + try { + using a = new Named("a"); + using b = new NamedThrower("B"); + } catch (e: string) { + s = e; + } + + return s + "/" + trail; +} + +// and a disposal that does not throw still lets the first exception through +function disposalDoesNotThrow() { + let s = ""; + trail = ""; + try { + using a = new Named("a"); + throw "first"; + } catch (e: string) { + s = e; + } + + return s + "/" + trail; +} + +function main() { + assert(inTryCatch() == "from dispose", "this try's catch takes the disposal's exception"); + assert(withFinallyOnly() == "from dispose1", "the finally runs and the disposal's exception goes on"); + assert(inNestedBlock() == "from dispose", "a nested block's cleanup hands on to the try around it"); + assert(callerCatches() == "from dispose", "the caller catches the disposal's exception"); + assert(innerCatchMismatch() == "from dispose", "a catch of another type passes it on"); + assert(inLoop() == "012", "every iteration's disposal is caught"); + assert(twoUsings() == "from B/Ba", "the disposal's exception replaces the first, and the rest is disposed"); + assert(bothThrow() == "from A/BA", "a second disposal that throws arrives, with everything disposed"); + assert(twoUsingsNormalPath() == "from B/Ba", "on the normal path the cleanup disposes the rest"); + assert(disposalDoesNotThrow() == "first/a", "a disposal that does not throw keeps the first exception"); + + print("done."); +}