Core patch for 1.23.

Not very well tested; I'm not sure if I even got this right. In any case,
we should fix this stuff so that we don't need a core patch in the first
place.

This is r2545 from ShoutWiki's SVN, without the SW-specific unrelated
changes.

Bug: 55640
Change-Id: I28fc6f306cdd739d86287c51830ed2b20c1f7735