cherrypicking db48bee3c75016c289f5b30ca01f167d316d53e2 and e7b302029462ac6c698b69d89805020f5f3fab1f from cc branch