Skip to content

Commit 696d5c5

Browse files
committed
SIL: fix a memory corruption bug in AllocStackInst
The `numOperands` field needs to be set before any trailing objects are initialized. Otherwise they are initialized at the wrong address.
1 parent 1084d89 commit 696d5c5

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

lib/SIL/IR/SILInstructions.cpp

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -199,15 +199,23 @@ AllocStackInst::AllocStackInst(SILDebugLocation Loc, SILType elementType,
199199
Var ? Var->Type.hasValue() : false,
200200
Var ? Var->Loc.hasValue() : false,
201201
Var ? Var->Scope != nullptr : false),
202-
VarInfo(Var, getTrailingObjects<char>(),
203-
getTrailingObjects<SILType>(),
204-
getTrailingObjects<SILLocation>(),
205-
getTrailingObjects<const SILDebugScope *>(),
206-
getTrailingObjects<SILDIExprElement>()) {
202+
// Initialize VarInfo with a temporary raw value of 0. The real
203+
// initialization can only be done after `numOperands` is set (see below).
204+
VarInfo(0) {
207205
sharedUInt8().AllocStackInst.dynamicLifetime = hasDynamicLifetime;
208206
sharedUInt8().AllocStackInst.lexical = isLexical;
209207
sharedUInt8().AllocStackInst.wasMoved = wasMoved;
210208
sharedUInt32().AllocStackInst.numOperands = TypeDependentOperands.size();
209+
210+
// VarInfo must be initialized after `sharedUInt32().AllocStackInst.numOperands`!
211+
// Otherwise the trailing object addresses are wrong.
212+
VarInfo = TailAllocatedDebugVariable(Var,
213+
getTrailingObjects<char>(),
214+
getTrailingObjects<SILType>(),
215+
getTrailingObjects<SILLocation>(),
216+
getTrailingObjects<const SILDebugScope *>(),
217+
getTrailingObjects<SILDIExprElement>());
218+
211219
assert(sharedUInt32().AllocStackInst.numOperands ==
212220
TypeDependentOperands.size() && "Truncation");
213221
auto *VD = Loc.getLocation().getAsASTNode<VarDecl>();

0 commit comments

Comments
 (0)