backport of #2674