Cherrypicked 1bc5f2dab3 8b9deb0772 and 40cce970c0