Backport @antmanler 's patch.