Skip to content

Copy tag directives in Emitter#start_document - #831

Open
ninjapanzer wants to merge 1 commit into
ruby:masterfrom
ninjapanzer:fix-start-document-tag-aliasing
Open

ninjapanzer wants to merge 1 commit into
ruby:masterfrom
ninjapanzer:fix-start-document-tag-aliasing

Conversation

@ninjapanzer

@ninjapanzer ninjapanzer commented Nov 17, 2026 •

Copy link
Copy Markdown

Fix #812

Psych::Emitter#start_document stored raw pointers into the handle and prefix Strings of each tag directive, but libyaml copies those bytes only in yaml_document_start_event_initialize, after the whole loop has run. In between:

  • a String exported from a non-UTF-8 encoding is referenced only by a C local that the next iteration overwrites, so it can be collected;
  • a UTF-8 String is still referenced from the tags array, but can be moved by compaction.

Either way libyaml could read freed or relocated memory.

This copies the bytes with ruby_strdup and frees the copies in start_document_ensure, as proposed in the issue. Following the review comment there, the counter is named n_tags and is initialized to 0. It is set to the allocated length right after xcalloc, so the ensure handler frees every slot: slots the loop did not reach are still NULL, and a handle is not leaked if copying its prefix raises.

Two regression tests are added to test/psych/test_emitter.rb, one per mechanism: handles in ISO-8859-1 emitted under GC.stress, and a handle whose to_str compacts the heap. Both fail on master (duplicate %TAG directive and tag handle must not be empty) and pass with this change. The two reproductions from the issue also pass.

The compaction test is omitted on the libfyaml backend: psych_emitter_fy.c keeps the exported Strings alive in a guard array but still records pointers into them, and this pull request does not change that file.

Tested with Ruby 3.4.8 and libyaml 0.2.5 on x86_64-linux; not run on the libfyaml backend, JRuby or TruffleRuby.

start_document stored raw pointers into the handle and prefix Strings
of each tag directive, but libyaml copies those bytes only after the
whole loop has run. Nothing kept an exported String alive once the next
iteration reassigned the local, and a String still referenced from the
tags array could be moved by compaction, so libyaml could read freed or
relocated memory.

Copy the bytes with ruby_strdup and free the copies in
start_document_ensure.

Fix ruby#812

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Psych::Emitter#start_document: tag-directive handles and prefixes are aliased as raw char *, and the Strings die inside the loop

1 participant