Cherry-pick 9cc9f9fa07c2f9154b6c63494631420b8adbdadf and cad48bbec0b8ab7c5ca5f0d6821e1a9976632df2