From 92b964cd9c669daab1f9e196b299c49de9da532f Mon Sep 17 00:00:00 2001 From: Katy Coe Date: Fri, 15 Nov 2019 05:14:49 +0100 Subject: [PATCH] Output: Escape special characters in C# strings properly --- Il2CppInspector/Reflection/Extensions.cs | 29 ++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/Il2CppInspector/Reflection/Extensions.cs b/Il2CppInspector/Reflection/Extensions.cs index b32abf1..514a601 100644 --- a/Il2CppInspector/Reflection/Extensions.cs +++ b/Il2CppInspector/Reflection/Extensions.cs @@ -31,12 +31,37 @@ namespace Il2CppInspector.Reflection public static string ToAddressString(this (ulong start, ulong end)? address) => ToAddressString(address?.start ?? 0) + "-" + ToAddressString(address?.end ?? 0); + // C# string literal escape characters + // Taken from: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#regular-and-verbatim-string-literals + private static Dictionary escapeChars = new Dictionary { + ['\''] = @"\'", + ['"'] = @"\""", + ['\\'] = @"\\", + ['\0'] = @"\0", + ['\a'] = @"\a", + ['\b'] = @"\b", + ['\f'] = @"\f", + ['\n'] = @"\n", + ['\r'] = @"\r", + ['\t'] = @"\t", + ['\v'] = @"\v" + }; + // Output a value in C#-friendly syntax public static string ToCSharpValue(this object value) { if (value is bool) return (bool) value ? "true" : "false"; - if (value is string) - return $"\"{value}\""; + if (value is string str) { + // Replace standard escape characters + var s = new StringBuilder(); + for (var i = 0; i < str.Length; i++) + // Standard escape characters + s.Append(escapeChars.ContainsKey(str[i]) ? escapeChars[str[i]] + // Replace everything else with UTF-16 Unicode + : str[i] < 32 || str[i] > 126 ? @"\u" + $"{str[i]:X4}" + : str[i].ToString()); + return $"\"{s}\""; + } if (!(value is char)) return (value?.ToString() ?? "null"); var cValue = (int) (char) value;