Cherry picked commit 6e04d7b from #370.