Skip to content

Commit 016f8ef

Browse files
committed
[Macros] Fix memory leak in expandMacroExpr
The result of `swift_ASTGen_lookupMacro` needs to be deallocated.
1 parent 4a8ce3a commit 016f8ef

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

lib/Sema/TypeCheckMacros.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,9 @@ StructDecl *MacroContextRequest::evaluate(Evaluator &evaluator,
107107
swift_ASTGen_getMacroEvaluationContext(
108108
(const void *)start, (void *)(DeclContext *)macroSourceFile,
109109
(void *)&ctx, builtinMacro, &context);
110-
ctx.addCleanup([builtinMacro]() { swift_ASTGen_destroyMacro(builtinMacro); });
110+
ctx.addCleanup([builtinMacro]() {
111+
swift_ASTGen_destroyMacro(builtinMacro);
112+
});
111113
return dyn_cast<StructDecl>((Decl *)context);
112114
} else {
113115
Parser parser(macroBufferID, *macroSourceFile, &ctx.Diags, nullptr,
@@ -145,7 +147,7 @@ Expr *swift::expandMacroExpr(
145147

146148
// Built-in macros go through `MacroSystem` in Swift Syntax linked to this
147149
// compiler.
148-
if (swift_ASTGen_lookupMacro(macroName.str().c_str())) {
150+
if (auto *macro = swift_ASTGen_lookupMacro(macroName.str().c_str())) {
149151
auto astGenSourceFile = sourceFile->exportedSourceFile;
150152
if (!astGenSourceFile)
151153
return nullptr;
@@ -159,6 +161,7 @@ Expr *swift::expandMacroExpr(
159161
return nullptr;
160162
evaluatedSource = NullTerminatedStringRef(evaluatedSourceAddress,
161163
(size_t)evaluatedSourceLength);
164+
free(macro);
162165
}
163166
// Other macros go through a compiler plugin.
164167
else {

test/Macros/macro_plugin_exec.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
// RUN: %empty-directory(%t)
22
// RUN: %target-build-swift -Xfrontend -disable-availability-checking -I%platform-module-dir/../.. -L%platform-dylib-dir/../.. -emit-library -emit-library-path=%t/%target-library-name(MacroDefinition) -working-directory=%t -module-name=MacroDefinition %S/Inputs/macro_definition.swift
33
// RUN: %target-build-swift -L%platform-module-dir/../.. -enable-experimental-feature Macros -load-plugin-library %t/%target-library-name(MacroDefinition) %s -o %t/main
4-
// RUN: %target-run %t/main
4+
// RUN: %target-run %t/main | %FileCheck %s
55
// REQUIRES: executable_test
66

77
// FIXME: Swift parser is not enabled on Linux CI yet.
88
// REQUIRES: OS=macosx
99

1010
print(#customStringify(3 + 2 - 1))
11+
// CHECK: (4, "3 + 2 - 1")
1112

1213
print(#customStringify(1.0.truncatingRemainder(dividingBy: 1.0) + 3.0))
14+
// CHECK-NEXT: (3.0, "1.0.truncatingRemainder(dividingBy: 1.0) + 3.0")
1315

1416
print(#customStringify(["a", "b", "c"] + ["d", "e", "f"]))
17+
// CHECK-NEXT: (["a", "b", "c", "d", "e", "f"], "[\"a\", \"b\", \"c\"] + [\"d\", \"e\", \"f\"]")

0 commit comments

Comments
 (0)