tsan: fix flags parsing

- running_on_valgrind was not parsed in some contexts
- refactor code a bit
- add comprehensive tests for flags parsing