Make sure to generate proper header and allow to read invalid ones

Upstream: https://codereview.appspot.com/99050043/

Fixes #4402 #5594