In addition to the stock market, at least in the US, there is another market in borrowing securities between brokers.
Brokers who have customers who are long (i.e. not short) the security (e.g. mutual funds) often have arrangements with the customers that they may lend out their securities to other customers or other brokers. As shares become more and more scarce to short, the borrowing cost for such shares increases. However eventually there may simply be none available.
This can happen quite frequently, such as when the company puts out a tender offer to buy back shares (people who want to submit their shares to the tender need them back first). Also, this happens when dividends are paid - the tax treatment of dividends versus "payments in lieu of dividend" can be slightly different (these are the payments made by the short seller to the owner of the stock when the dividend is paid).
The rule however is that before you can short the stock, you have to have a 'locate' - i.e. shares that you have located that you can sell short. As the availability of shares to locate dries up the borrowing costs increase.
Sometimes this is enough to make more people make shares available to sell (e.g. one could just buy the long stock and lend it out as a trading strategy).
However eventually a buy-in may occur, and you are notified that within a few days, you either have to close out your position or locate some other shares. If you don't, your broker will do that for you (and they're obviously not interested in you making a profit). As long as there is a price in the market, that is possible.
If the stock is not that liquid, then the broker will not make it available for shorting (this could happen while you have a short position).