backported from 3.4 and other fixes