Backported changes from master.