ported from upstream / in-tree commits 91c527a55664ddf4bee26673a35f91748dae4142 and 45693bcb00cbd379c373ab22ccd9a9d4755cc7ed