How should a glider pilot handle inadvertently entering a foreign country?
How can the pilot make their arrival formal, their stay legal and eventually return to the origin country without problems?

Let others know your plans beforehand. If worst comes to worst you need someone on the other side to try and resolve the issue.

Is there any law protecting pilots in such cases?

Internationally agreed upon law? Not to my knowledge since laws are typically sovereign in nature. (Better ask on Law.SE; someone did ask a related but more specific question, but no answer as of yet.)

All I know is what ICAO recommends in SARPs Annex 9:


  3.72 Recommended Practice.— Contracting States should establish measures for authorizing temporary entry for a passenger or crew member who does not possess the required entry visa prior to arrival, due to diversion or delay of a flight for reasons of force majeure.


Also to my knowledge force majeure cases are few and far between, and handled according to the specific situation. You can't have a law that can be used as a loophole to fake a situation (ideally).


If such law existed, ICAO wouldn't have needed to make a recommendation to its member countries.


Or will they be treated as illegal immigrants?

Could be worse if the diplomatic relations of said two countries are not ideal. The pilot could be treated as a spy, hence, let others know of your flying plans.



I couldn't find a glider story, but balloons are similar, and 1995 saw a tragic incident:


  In an incident recalling the most violent excesses of the cold war, Belarussian combat aircraft have shot down a sport balloon that flew over the border from Poland while competing in a race.


Not just balloons, even jogging can land you in trouble:


  A visitor from France says she was jogging along the beach south of White Rock, B.C., when she crossed the U.S. border without realizing it. So began a two-week nightmare that landed her in a prison jumpsuit.