Skip to content

Commit

Permalink
fix: SAX::ParserContext keeps a reference to the input (backport of #…
Browse files Browse the repository at this point in the history
…3395 to v1.18.x) (#3396)

backport #3395 to v1.18.x
  • Loading branch information
flavorjones authored Dec 29, 2024
2 parents fdfb6df + 1c9b8f1 commit 6344147
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ Nokogiri follows [Semantic Versioning](https://semver.org/), please see the [REA

---

## v1.18.1 / unreleased

### Fixed

* [CRuby] XML::SAX::ParserContext keeps a reference to the input to avoid a potential use-after-free issue that's existed since v1.4.0 (2009). (#3395) @flavorjones


## v1.18.0 / 2024-12-25

### Notable Changes
Expand Down
10 changes: 8 additions & 2 deletions ext/nokogiri/xml_sax_parser_context.c
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,10 @@ noko_xml_sax_parser_context_s_native_io(VALUE rb_class, VALUE rb_io, VALUE rb_en
c_context->sax = NULL;
}

return noko_xml_sax_parser_context_wrap(rb_class, c_context);
VALUE rb_context = noko_xml_sax_parser_context_wrap(rb_class, c_context);
rb_iv_set(rb_context, "@input", rb_io);

return rb_context;
}

/* :nodoc: */
Expand Down Expand Up @@ -154,7 +157,10 @@ noko_xml_sax_parser_context_s_native_memory(VALUE rb_class, VALUE rb_input, VALU
c_context->sax = NULL;
}

return noko_xml_sax_parser_context_wrap(rb_class, c_context);
VALUE rb_context = noko_xml_sax_parser_context_wrap(rb_class, c_context);
rb_iv_set(rb_context, "@input", rb_input);

return rb_context;
}

/*
Expand Down
24 changes: 24 additions & 0 deletions test/test_memory_usage.rb
Original file line number Diff line number Diff line change
Expand Up @@ -313,5 +313,29 @@ def start_element(name, attrs = [])
# Expected error. This comment makes rubocop happy.
end
end

it "XML::SAX::ParserContext.io holds a reference to IO input" do
content = File.read(XML_ATOM_FILE)

memwatch(__method__) do
pc = Nokogiri::XML::SAX::ParserContext.io(StringIO.new(content), "ISO-8859-1")
parser = Nokogiri::XML::SAX::Parser.new(Nokogiri::SAX::TestCase::Doc.new)
GC.stress
pc.parse_with(parser)

assert_equal(472, parser.document.data.length)
end
end

it "XML::SAX::ParserContext.memory holds a reference to string input" do
memwatch(__method__) do
pc = Nokogiri::XML::SAX::ParserContext.memory(File.read(XML_ATOM_FILE), "ISO-8859-1")
parser = Nokogiri::XML::SAX::Parser.new(Nokogiri::SAX::TestCase::Doc.new)
GC.stress
pc.parse_with(parser)

assert_equal(472, parser.document.data.length)
end
end
end if ENV["NOKOGIRI_MEMORY_SUITE"] && Nokogiri.uses_libxml?
end

0 comments on commit 6344147

Please sign in to comment.