Pearls are formed inside certain species of mollusks, such as oysters and mussels, as a defence mechanism against irritants. When a foreign object, such as a grain of sand or parasite, enters the mollusk, it secretes layers of nacre (a combination of calcium carbonate and protein) around the irritant, gradually forming a pearl.
You can read more about how pearls are made here.