Backport the changes from e44864d2 (see #5683)