Extract helper functions from main link loop

This is necessary for whatever for of library rescanning we decide on (--Wl,--start-group, --rescan-libs, etc).

Context: https://groups.google.com/forum/#!topic/emscripten-discuss/n1qfKPPAy08

Tested:

python -u tests/runner.py sanity

Please advise on what's a good set of tests to run.