Backport fixes for Bug#5390 and Bug#5694 from trunk.