Foreigners who stay in Poland illegally cannot obtain a residence permit without leaving the country. However, there are some exceptional cases when it is possible.
Despite the illegal stay, a temporary residence permit may be granted to a spouse of a Polish citizen or a foreigner staying in Poland on the basis of a permanent residence permit or a long-term EU resident permit.
A temporary residence permit may be also granted to a foreign female who gave birth to a child being a Polish citizen by birth. Besides, in particularly justified cases, you can apply for an authorization to stay for humanitarian reasons or for a tolerated residence permit.