In Giro d'Italia and other stage races such as the Tour de France and Vuelta a España, there is a maximum time to arrive at the end of the stage after which racers are disqualified.
How this maximum time is determined for each stage?
For the Tour de France, a rider has to finish within a set percentage of the time of the stage winner. This factor depends on two things:
The percentage can vary from 4% (for a slow, flat stage) to 18% (for a fast, mountainous stage), although the organisers are allowed to make exceptions if more than 20% of the field would be outside the time limit. (Details taken from Rules to Ride by at the Tour de France).
I couldn't find a direct reference to the rules for the Giro d'Italia or Vuelta a España, but I believe them to be based on the same principles.
The rules are defined by the race organizer. But regardless of the rules, the time limit can be adjusted by the race jury for extenuating circumstances. The obvious case is when too many riders would be eliminated, which is why the slower riders tend to group together at the back of the race. The hope is that if the group is big enough, the race jury won't throw them out. This tactic doesn't always work, however. In stage 18 of the 2003 Giro, 34 riders missed the time cut on a wet and freezing day and were tossed from the race. That was almost 25% of the field!
The race jury will also sometimes take pity on riders who have crashed, or had really bad luck, and still managed to finish.