Move file locking into the RTS, fixing #629, #1109