Natural selection; survival to reproduce. Collections of genes (or more accurately a given gene variant) with better fitness, tend to survive to reproduce more often than those without. Basically harmful mutations tend to lower fitness, whereas beneficial mutations tend to increase it. Or rather technically speaking, it's actually the propensity to decrease or increase fitness that determines whether a mutation is harmful or beneficial. So it's all rather mechanical in a sense.