From 714336cce4fc9101988b88c758332b84aa7ca240 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 29 Nov 2026 01:07:44 +0000 Subject: [PATCH 1/2] -mm=own: a string put into one tuple twice is copied, not freed twice; fixes for the Debug-compiler suite - -mm=own: `<[V, V]>[value, value]` yielded by a generator (two reads of its state's slot) and `const p = <[string, string]>[s, s]` gave the tuple two owners of one string, and its release gave it back twice: the program hung or crashed at exit (a Set's entries()). After the analysis each repeat of a string in a tuple - the same value, or a read of the same place with nothing stored between - is a copy of its own (copyRepeatedTupleStrings). - Debug compiler, 153 of 10,139 tests failed on the rebuilt Debug LLVM: - a generator's return() result literal had no source span (its `.obj` name from an empty one): the body's span now; ~80 generator tests stopped on `loc_->pos != loc_->_end`; - a cast of an interface, or of `null | V` of a @value V, to `null` reached castLLVMTypes' "review usage": a value seen as `null` is the null pointer; - a closure's function type had its captures compared with the other's first parameter: they are skipped, as a receiver is; - `const { 0: a } = t` called IntegerAttr::getInt() on an `si32` key; - resolveModuleFile assigned a path its own parent, a view into itself (UB in Release too); - `x.w ??= v` of a @weak field read its view after storing the right side erased it; - `tsbindgen -o -` closed stdout, which its stream does not own. Test 00tuple_repeated_string (all models). Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/LowerToLLVM/CastLogicHelper.h | 8 +++ .../TypeScript/MLIRLogic/MLIRTypeHelper.h | 13 ++++- tslang/lib/TypeScript/MLIRGenClasses.cpp | 12 ++-- tslang/lib/TypeScript/MLIRGenFunctions.cpp | 10 +++- tslang/lib/TypeScript/MLIRGenImpl.h | 21 +++++-- tslang/lib/TypeScript/MLIRGenVariables.cpp | 3 +- .../lib/TypeScript/OwnershipInferencePass.cpp | 51 +++++++++++++++++ tslang/test/tester/CMakeLists.txt | 6 ++ .../tester/tests/00tuple_repeated_string.ts | 56 +++++++++++++++++++ tslang/tsbindgen/tsbindgen.cpp | 11 +++- 10 files changed, 174 insertions(+), 17 deletions(-) create mode 100644 tslang/test/tester/tests/00tuple_repeated_string.ts diff --git a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h index 34bf36b59..c073c931d 100644 --- a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h @@ -152,6 +152,14 @@ class CastLogicHelper return in; } + // A value seen as `null` (a narrowing to the null side: an interface, `null | V` of a @value V) is the null + // pointer, whatever it was. Not a cast of its bytes: an interface's two words or a union's tag and payload + // reached castLLVMTypes as a struct to a pointer, its "review usage" stop in a debug compiler + if (isa(resType) && isa(resLLVMType)) + { + return rewriter.create(loc, resLLVMType); + } + // `unknown` is the box `any` is (MLIRGenImpl::cast boxes into it and unboxes out of it) if ((isa(inType) && isa(resType)) || (isa(inType) && isa(resType))) diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h index dae5447fe..0fb6019c0 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h @@ -1543,9 +1543,16 @@ class MLIRTypeHelper LLVM_DEBUG(llvm::dbgs() << "\n!!" << "@ TestFunctionTypesMatchWithObjectMethods:" << inFuncType << " -> " << resFuncType << "\n";); - // TODO: seems capture function with wrong function type - assert(startParamIn > 0 || inFuncType.getNumInputs() == 0 - || startParamIn == 0 && inFuncType.getNumInputs() > 0 && !isRefTuple(inFuncType.getInput(0))); + // A function of a closure takes its captures first, a reference to their tuple (`ref>`): no parameter + // a caller gives, so it is skipped as a receiver is below (generic_arrow_any: an arrow given where a function of + // `any` is expected, asserted in a debug compiler and compared the captures with the first parameter) + // (the same captures on both sides are compared as they are, as any parameters) + auto inCaptures = startParamIn == 0 && inFuncType.getNumInputs() > 0 && isRefTuple(inFuncType.getInput(0)); + auto resCaptures = startParamRes == 0 && resFuncType.getNumInputs() > 0 && isRefTuple(resFuncType.getInput(0)); + if (inCaptures && !resCaptures) + { + startParamIn = 1; + } // 1 we need to skip opaque and objects // TODO: we need to refactor func types the way that we can understand if this is func with "captured var", bound to object etc diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index 705918f66..61ff42cba 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -3092,25 +3092,25 @@ namespace mlirgen return viewOp->getAttrOfType(WEAK_FIELD_VIEW_ATTR_NAME); } - mlir::Value MLIRGenImpl::weakFieldReread(mlir::Location location, mlir_ts::SafeCastOp viewOp, mlir::Value loaded, - const GenContext &genContext) + mlir::Value MLIRGenImpl::weakFieldReread(mlir::Location location, mlir::Type viewType, mlir::StringAttr name, + mlir::Value loaded, const GenContext &genContext) { auto weakRefType = mlir::cast(loaded.getType()); auto derefOp = builder.create(location, weakRefType.getElementType(), loaded); derefOp.setChecked(true); - if (auto name = weakFieldNameOf(viewOp)) + if (name) { derefOp.setWeakFieldAttr(name); } - auto castValue = weakFieldValue(location, derefOp.getResult(), viewOp.getType(), genContext); + auto castValue = weakFieldValue(location, derefOp.getResult(), viewType, genContext); if (!castValue) { return mlir::Value(); } - auto rereadOp = builder.create(location, viewOp.getType(), castValue, loaded); - if (auto name = weakFieldNameOf(viewOp)) + auto rereadOp = builder.create(location, viewType, castValue, loaded); + if (name) { rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, name); } diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index a1dc7226f..7e59eeefe 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1515,7 +1515,15 @@ namespace mlirgen NodeArray statements; statements.push_back(nf.createIfStatement(paused(), nf.createBlock(resume, false), undefined)); statements.push_back(finished()); - statements.push_back(nf.createReturnStatement(nf.createObjectLiteralExpression(resultProperties, false))); + // (its storage is named after its location: the body's span, which no other literal of the generator has - the + // generator object takes the function's. With none, the name came from an empty span, which a debug + // compiler stopped on, and two generators at one position would have shared it) + auto result = nf.createObjectLiteralExpression(resultProperties, false); + auto spanOf = functionLikeDeclarationBaseAST->body ? static_cast(functionLikeDeclarationBaseAST->body) + : static_cast(functionLikeDeclarationBaseAST); + result->pos = spanOf->pos; + result->_end = spanOf->_end; + statements.push_back(nf.createReturnStatement(result)); addMethod("return", parameters, statements); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 80b2fed09..45f7405ca 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -8575,6 +8575,15 @@ class MLIRGenImpl auto result = mlirGen(leftExpression, genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) auto leftExpressionValue = V(result); + // a @weak field's view (own spec 93), taken now: storing the right side drops the view once nothing uses + // it (dropWeakFieldView), and asking it afterwards read the erased op + mlir::Type weakViewType; + mlir::StringAttr weakViewName; + if (auto viewOp = weakFieldView(leftExpressionValue)) + { + weakViewType = viewOp.getType(); + weakViewName = viewOp->getAttrOfType(WEAK_FIELD_VIEW_ATTR_NAME); + } // only a place read by a load is read again (through a test's narrowing of it); an accessor's // getter is not run twice: it is stored the merge, as before @@ -8651,9 +8660,9 @@ class MLIRGenImpl auto reloaded = builder.create(location, leftLoad.getType(), reference); // a @weak field (own spec 93): read again as its declared type, checked - if (auto viewOp = weakFieldView(leftExpressionValue)) + if (weakViewType) { - return V(weakFieldReread(location, viewOp, reloaded, genContext)); + return V(weakFieldReread(location, weakViewType, weakViewName, reloaded, genContext)); } return V(reloaded); @@ -21331,8 +21340,9 @@ class MLIRGenImpl mlir::Value loaded, const GenContext &genContext); mlir::Value weakFieldValue(mlir::Location location, mlir::Value pointer, mlir::Type declaredType, const GenContext &genContext); - // own spec 93: `loaded`, the slot read again, as the checked read `viewOp` is - mlir::Value weakFieldReread(mlir::Location location, mlir_ts::SafeCastOp viewOp, mlir::Value loaded, + // own spec 93: `loaded`, the slot read again, as the checked read of the view of type `viewType` (naming the + // field `name`, when it has one) is. The view's type and name, not the view: it may be gone by then + mlir::Value weakFieldReread(mlir::Location location, mlir::Type viewType, mlir::StringAttr name, mlir::Value loaded, const GenContext &genContext); // own spec 93: the view weakFieldRead made, if `value` is one (or a test's narrowing of one) mlir_ts::SafeCastOp weakFieldView(mlir::Value value); @@ -23400,7 +23410,8 @@ class MLIRGenImpl break; } - folder = parent; + // (`parent` points into `folder`, a prefix of it: assigning it read the buffer being written) + folder.resize(parent.size()); } return std::nullopt; diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index 6c929bd55..4f3121467 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -1099,7 +1099,8 @@ namespace mlirgen // an index past a tuple's elements (`const { 3: d } = t` of a `[boolean, string, number]`) failed without // an error auto checkIndex = [&](auto tupleType) { - auto index = mlir::cast(fieldName).getInt(); + // (a literal key is an `si32` constant: getInt() asserts on a signed type, getValue() reads any) + auto index = mlir::cast(fieldName).getValue().getSExtValue(); if (tupleType.getIndex(fieldName) < 0 && (index < 0 || static_cast(index) >= tupleType.size())) { emitError(location) << "a tuple of type '" << to_print(type) << "' has no element at index " diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 9e602991e..5566d00a5 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -198,8 +198,59 @@ namespace own_inference } } + // A string put into one tuple twice (`<[V, V]>[value, value]`, a generator's `yield [v, v]` reading its state's slot + // twice): the tuple owns each of its fields, and its release gave the one string back twice - a double free (a + // set's entries() under -mm=own, TSLANG 225). Each repeat is a copy of its own, as a string given a second owner + // is. A repeat is the same value, or a read of the same place (two loads through one reference, nothing stored in + // between). An object given twice is refused by the move checks (a use after its move) and stays so. + static void copyRepeatedTupleStrings(mlir::Operation *function) + { + llvm::SmallVector tuples; + function->walk([&](mlir_ts::CreateTupleOp createTupleOp) { tuples.push_back(createTupleOp); }); + for (auto createTupleOp : tuples) + { + llvm::SmallDenseMap seen; + for (auto &operand : createTupleOp->getOpOperands()) + { + auto value = operand.get(); + if (!isCopyableString(value.getType())) + { + continue; + } + + auto key = value; + if (auto loadOp = value.getDefiningOp(); loadOp && loadOp->getBlock() == createTupleOp->getBlock()) + { + // (a store through the same reference between the two reads gives the second a value of its own) + auto storedBetween = false; + for (auto *op = loadOp->getNextNode(); op && op != createTupleOp.getOperation(); op = op->getNextNode()) + { + if (auto storeOp = mlir::dyn_cast(op); storeOp && storeOp.getReference() == loadOp.getReference()) + { + storedBetween = true; + } + } + + key = storedBetween ? value : loadOp.getReference(); + } + + if (seen.try_emplace(key, operand.getOperandNumber()).second) + { + continue; + } + + mlir::OpBuilder builder(createTupleOp); + auto copy = builder.create(createTupleOp->getLoc(), value.getType(), value); + operand.set(copy); + } + } + } + void OwnershipInferencePass::runOnFunction() { + // (after the analysis has decided rc's ops: the copy is then the repeat's own reference, which nothing else gives it) + auto copyRepeats = llvm::make_scope_exit([&]() { copyRepeatedTupleStrings(getFunction()); }); + // what the real run may do that the dry run did not: only where the dry run failed, so a // function today's analysis accepts is decided as it was localLetCandidates.clear(); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 2e6c07d70..4d6ad4275 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2678,6 +2678,12 @@ foreach(issue224_mm gc rc none own) tslang_add_test(NAME test-jit-00tslang_issue_224-${issue224_mm} COMMAND test-runner -jit -mm=${issue224_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_224.ts") tslang_add_test(NAME test-compile-00tslang_issue_224-${issue224_mm} COMMAND test-runner -mm=${issue224_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_224.ts") endforeach() +# TSLANG 225: a string put into one tuple twice (a generator's `yield [v, v]`, a Set's entries()) - under -mm=own its +# release gave it back twice +foreach(tuple_repeat_mm gc rc none own) + tslang_add_test(NAME test-jit-00tuple_repeated_string-${tuple_repeat_mm} COMMAND test-runner -jit -mm=${tuple_repeat_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_repeated_string.ts") + tslang_add_test(NAME test-compile-00tuple_repeated_string-${tuple_repeat_mm} COMMAND test-runner -mm=${tuple_repeat_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_repeated_string.ts") +endforeach() # ...and what was refused for it, accepted since TSLANG 219 (USER RULING 11-27): an argument and a borrow neither of # which this function owns (two parameters, `this` and a parameter), the array a loop reads emptied by the call, a # field given a value it does not make - the borrowing local takes a reference of its own diff --git a/tslang/test/tester/tests/00tuple_repeated_string.ts b/tslang/test/tester/tests/00tuple_repeated_string.ts new file mode 100644 index 000000000..faa986788 --- /dev/null +++ b/tslang/test/tester/tests/00tuple_repeated_string.ts @@ -0,0 +1,56 @@ +// TSLANG 225: one string put into a tuple twice, in every memory model. Under -mm=own the tuple owns each of its fields, +// and its release gave the one string back twice - a double free: a generator yielding `<[V, V]>[value, value]` (a +// Set's entries()) hung or crashed at exit, and `const p = <[string, string]>[s, s]` freed `s` twice. Each repeat is +// a copy of its own now. +class Bag { + items: string[] = []; + + @borrows("this") + *pairs() { + for (let i = 0; i < this.items.length; i++) { + const value = this.items[i]; + yield <[string, string]>[value, value]; + } + } +} + +class Junk { + constructor(public s: string) {} +} + +function churn() { + const junk: Junk[] = []; + for (let i = 0; i < 64; i++) { + junk.push(new Junk("j" + i)); + } +} + +function twice(k: number): number { + const s = "s" + k; + const p = <[string, string]>[s, s]; + churn(); + return p[0].length + p[1].length; +} + +function main() { + let total: number = 0; + for (let k = 0; k < 100; k++) { + const b = new Bag(); + b.items.push("a" + k); + b.items.push("b" + k); + for (const [x, y] of b.pairs()) { + assert(x == y, "the same value"); + total += x.length + y.length; + } + + for (const e of b.pairs()) { + total += e[0].length + e[1].length; + } + + total += twice(k); + } + + print(total); + assert(total == 2900, "the total"); + print("done."); +} diff --git a/tslang/tsbindgen/tsbindgen.cpp b/tslang/tsbindgen/tsbindgen.cpp index 4684ae152..de34c95f7 100644 --- a/tslang/tsbindgen/tsbindgen.cpp +++ b/tslang/tsbindgen/tsbindgen.cpp @@ -261,7 +261,16 @@ int main(int argc, char **argv) } out << printed->text; - out.close(); + // (`-o -` is stdout, which the stream does not own: close() asserts there, so it is flushed instead) + if (outputFile.getValue() == "-") + { + out.flush(); + } + else + { + out.close(); + } + if (out.has_error()) { llvm::WithColor::error(llvm::errs(), "tsbindgen") << "cannot write '" << outputFile << "'\n"; From 26e8576a36de0bf0432e0849f8c8d30af909b718 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 29 Nov 2026 01:07:44 +0000 Subject: [PATCH 2/2] TSLANG 226: issues entry and what's new Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 32 ++++++++++++++++++++++++++++++++ docs/whats-new.md | 1 + 2 files changed, 33 insertions(+) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 9d1e2ae93..260582f2a 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -4385,3 +4385,35 @@ Test `00tslang_issue_224.ts` (all models); `own_counted_let_without_value`, `own field's type (one only), so the object is counted with both owners, as rc counts it. Tests `own_counted_global_read_overwritten`, `own_fallback_constructor_kept_second_owner`. + +226. The Debug-compiler suite, and a double free under -mm=own (2026-11-29). +- **-mm=own: one string put into a tuple twice was freed twice.** `<[V, V]>[value, value]` yielded by a generator + (it reads its state's slot twice) and `const p = <[string, string]>[s, s]` gave the tuple two owners of one string, + and its release gave it back twice: the program hung or crashed at exit (a Set's entries() made so). After the + analysis each repeat of a string in a tuple - the same value, or a read of the same place - is a copy of its own + (an object given twice is still refused as a use after its move). +- **The Debug-compiler suite on the rebuilt Debug LLVM: 153 of 10,139 failed.** Fixed here: + - a generator's return() result literal had no source span, and its storage name came from an empty span: about + 80 generator tests (and callee_non_null, iterable_string_for_of, 217) stopped on `loc_->pos != loc_->_end`. It + takes the body's span (the generator object has the function's); + - a cast of an interface, or of `null | V` of a @value V, to `null` reached castLLVMTypes' "review usage" stop + (class_to_interface_null, value_missing_niche): a value seen as `null` is the null pointer; + - a closure's function type compared with a function type had its captures compared with the first parameter + (generic_arrow_any): they are skipped, as a receiver is; + - `const { 0: a } = t` read its key with IntegerAttr::getInt() on an `si32` (declarationsAndAssignments); + - `resolveModuleFile` assigned a path its own parent, a view into itself (ambient_module_import; undefined + behaviour in Release too); + - `x.w ??= v` of a @weak field read its view after storing the right side had erased it (own_weak_field_logical). + - `tsbindgen -o -` closed stdout, which its stream does not own (LLVM's `ShouldClose` assert): it is flushed. + Rerun by name on the Debug compiler, 139 of the 153 pass. Still open: under a Debug compiler's JIT + own_counted_list_cut_in_step crashes before it prints (its exe, and the Release compiler's JIT, print 2; the + IR the two compilers make is the same); crash-errors huge-object-type-from-any times out (300 s) in a Debug + compiler; and in a Debug build tree the tests that build an optimized exe link the tree's debug-CRT runtime + (`_CrtDbgReport` unresolved, LNK2038: gc-opt-uncaught-throw_*, atomic-rc, foreign-thread-gc, + borrow-facts-defaultlib), as on 11-13. The Debug tree's CMake cache also named MSVC 14.51's lib.exe and link.exe + (borrow-facts-*): cleared and reconfigured locally. +- `Map.entries()` yields `[k, v]` tuples and `Set.entries()` `[v, v]`, as in JavaScript (DefaultLib #125). +- Re-checked, not a leak: an rc async function with a catch and a finally that awaits. Its peak grows in 32 MB steps + of the allocator and falls back while it runs (34-98 MB over 2M-6M calls), with or without the catch. + +Test `00tuple_repeated_string` (all models). diff --git a/docs/whats-new.md b/docs/whats-new.md index 1888fdec6..bf4afefd0 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,6 @@ # What's new +- `Map.entries()` gives `[key, value]` tuples and `Set.entries()` `[value, value]`, as in JavaScript (`JSON.stringify` writes them as arrays); under -mm=own a string put into one tuple twice is no longer freed twice; a debug compiler no longer stops on generators, a cast of an interface to `null`, or a closure given where a function of `any` is expected - -mm=own: a local holding a global's value can be used after the global is given another one (`const n = G; G = mk(); print(n.x)`, or after a call that assigns `G`): it takes a reference of its own where own can't prove the borrow; the debug compiler no longer asserts on `"2.5"` or `"7"` - -mm=own: `c ? e : new B(1)` of a borrow `e` compiles (the merge takes a reference of its own to the borrow), and so does `let x: C;` declared without a value and given one later, a field's or a global's value too (it owns what it is given, counted where own can't prove the move) - `{ ...src, k: 3 }` has the `k` written after the spread (it kept src's); under -mm=own a spread of a literal holding a new string no longer leaks it, and `<{ code: number }>a` of an `any` can be cast more than once, and of a box holding `{ code: 7 }`