Skip to content

Commit

Permalink
Fixes #18726 by backslash escaping descriptor data containing # if …
Browse files Browse the repository at this point in the history
…the hashmark appears immediately before any of `$`, `{`, or `@`.

PiperOrigin-RevId: 729560636
  • Loading branch information
protobuf-github-bot authored and copybara-github committed Feb 21, 2025
1 parent 874de25 commit 4685338
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/google/protobuf/compiler/ruby/ruby_generator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,29 @@ std::string DumpImportList(const FileDescriptor* file) {
return ret;
}

// Escape a string for use in a Ruby string literal. This is a superset of
// absl::CEscape() that also includes handling of the following characters:
// - # (hashmark)
//
// This is needed because Ruby double-quoted string literals interpolate the
// contents of the string, and the hashmark character is used in the
// interpolation syntax. Informed by MRI Ruby's implementation of String#dump.
std::string RubyEscape(absl::string_view s) {
std::string c_escaped = absl::CHexEscape(s);
std::string result;
result.reserve(c_escaped.length());
for (size_t i = 0; i < c_escaped.length(); ++i) {
if (c_escaped[i] == '#' &&
(i + 1 < c_escaped.length() &&
(c_escaped[i + 1] == '{' || c_escaped[i + 1] == '$' ||
c_escaped[i + 1] == '@'))) {
result += '\\';
}
result += c_escaped[i];
}
return result;
}

void GenerateBinaryDescriptor(const FileDescriptor* file, io::Printer* printer,
std::string* error) {
printer->Print(R"(
Expand All @@ -259,9 +282,8 @@ pool = Google::Protobuf::DescriptorPool.generated_pool
pool.add_serialized_file(descriptor_data)
)",
"descriptor_data",
absl::CHexEscape(SerializedDescriptor(file)), "imports",
DumpImportList(file));
"descriptor_data", RubyEscape(SerializedDescriptor(file)),
"imports", DumpImportList(file));
}

bool GenerateFile(const FileDescriptor* file, io::Printer* printer,
Expand Down

0 comments on commit 4685338

Please sign in to comment.