Skip to content

Source Generator: x:Key values not escaped in generated C# string literals #34726

@StephaneDelcroix

Description

@StephaneDelcroix

Description

In SetPropertyHelpers.cs, resource dictionary key values from x:Key are interpolated directly into generated C# string literals without escaping special characters (quotes, backslashes, newlines).

Affected Code

SetPropertyHelpers.cs line 147AddToResourceDictionary:

writer.WriteLine($"{parentVar.ValueAccessor}[\"{key}\"] = ...");

SetPropertyHelpers.cs line 217AddLazyResourceToResourceDictionary:

writer.WriteLine($"{parentVar.ValueAccessor}.AddFactory(\"{key}\", () =>");

Impact

If an x:Key contains a double quote ("), backslash (\), or control character, the generated C# will be syntactically invalid:

<!-- XAML -->
<Color x:Key="My&quot;Key">Red</Color>
// Generated (broken):
resources["My"Key"] = ...;

In practice this is very unlikely since x:Key values are almost always simple identifiers, but it is technically a codegen injection risk.

Suggested Fix

Use SymbolDisplay.FormatLiteral(key, quote: false) or a shared string-escaping helper when emitting x:Key values into generated code, e.g.:

var escapedKey = key.Replace("\\", "\\\\").Replace("\"", "\\\"");
writer.WriteLine($"{parentVar.ValueAccessor}[\"{escapedKey}\"] = ...");

The UC codegen (UpdateComponentCodeWriter) already has an EscapeString() helper that handles this correctly for resource keys emitted during hot reload patches.

Context

Found during multi-model code review of the XIHR (XAML Incremental Hot Reload) feature branch.

Metadata

Metadata

Labels

s/triagedIssue has been reviewedt/bugSomething isn't workingxsgXaml sourceGen

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions