Apparently onomatopoeic and believed to have first appeared in comic strips. Compare gag (“to choke; to retch”) and hack (“to cough noisily”).
The "cocaine" and "meth" senses apparently comes from the fact that snorting the drugs often activates a person's gag reflex.