Cherry-picked #6753 and added missing functions to make it work