Ported from a7c4537a729929f6670349f67d248ffb6ff800da. (cherry picked from commit c8db49f0a939ce2219b41f8d3993268ceeef05f1)