From 25fc297edb10221e321f51addc5fff40023b0dcc Mon Sep 17 00:00:00 2001 From: Charles Giessen Date: Thu, 27 Oct 2022 14:03:15 -0600 Subject: vulkaninfo: Escape strings in JSON output JSON output breaks if escape sequences are in the various strings output by drivers but aren't properly handles. This commit scans over each string and inserts backslashes when necessary. --- vulkaninfo/outputprinter.h | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/vulkaninfo/outputprinter.h b/vulkaninfo/outputprinter.h index 26dd2a29..4dc36ef2 100644 --- a/vulkaninfo/outputprinter.h +++ b/vulkaninfo/outputprinter.h @@ -582,7 +582,7 @@ class Printer { break; case (OutputType::json): case (OutputType::vkconfig_output): - PrintElement("\"" + string + "\"", value_description); + PrintElement("\"" + EscapeJSONCString(string) + "\""); default: break; } @@ -709,6 +709,46 @@ class Printer { get_top().set_next_subheader = false; } } + + // Replace special characters in strings with their escaped versions. + // + std::string EscapeJSONCString(std::string string) { + if (output_type != OutputType::json) return string; + std::string out{}; + for (size_t i = 0; i < string.size(); i++) { + char c = string[i]; + char out_c = c; + switch (c) { + case '\"': + case '\\': + out.push_back('\\'); + break; + case '\b': + out.push_back('\\'); + out_c = 'b'; + break; + case '\f': + out.push_back('\\'); + out_c = 'f'; + break; + case '\n': + out.push_back('\\'); + out_c = 'n'; + break; + case '\r': + out.push_back('\\'); + out_c = 'r'; + break; + case '\t': + out.push_back('\\'); + out_c = 't'; + break; + } + out.push_back(out_c); + } + + return out; + } }; // Purpose: When a Printer starts an object or array it will automatically indent the output. This isn't // always desired, requiring a manual decrease of indention. This wrapper facilitates that while also @@ -745,4 +785,4 @@ class ArrayWrapper { private: Printer &p; -}; \ No newline at end of file +}; -- cgit v1.2.3