Backport fix from https://bugs.ruby-lang.org/issues/9657