what do undercover cops do when forced to do something illegal?

No. Doctor Who provides a cite for the taking of drugs, and as for sex:

So the sex itself (for money) is a crime.

I think we’re referring to the same dude.

Not an undercover officer, and therefore not the OP’s situation, but DEA has turned a blind eye in the past to its paid informants committing murders if it was thought they could thereby acquire more information. Google House of Death, Juarez, and Santillan for the gory details.

I’d like to think that an undercover officer would not be allowed to commit murders just for the sake of getting better information. (and wasn’t Joseph Pistone removed because he was ordered to kill another Mafia official?) The House of Death affair makes me wonder a little, though.

Removed.

Somehow I doubt there are too many undercover cops running solo Donnie Brosco style. And I would hardly look at shows like The Shield as reference material.

My WAG is that when cops go undercover, they typically have a team supporting them in a van down the street listening and watching through the hidden mics and cameras in whatever shitbox motel they set up the sting operation.

Plus I don’t think the “yo! kill this fool and show us you ain’t a cop!” scenario is too common. That’s sort of like “watch me commit this felony and not arrest me to prove you ain’t a cop!”