save/restore context fixes

Both commits are independent. e124e87 should probably be back-ported to stable-2.5.