Cherry picked 5fbc59e6a38a7eec1a08381b570aaff7c19dbfea and 2e9813ce1cdc02c6c340356d7f231efde64ac730 from ryanb's repo.