While I can't speak for the specific algorithms they use, you pretty much hit the nail on the head of how they determine what ads to use. GMail is a little different in that Google knows a lot about you in terms of the content of the email and what your current conversations contain, they can then drive specific ads based on those conversations.
Facebook knows who you are, your age, your location, what you like, possibly what you dislike, your music tastes, movies, etc... They know who you interact with the most, who you interact with the least and can form patterns of what common interests between you and your friends. They combine all this data to determine what kind of ads will most likely appeal to you. The more you interact with Facebook, the more relevant the ads displayed to you will become.
Not sure exactly what else you are looking for here though based on your question. The specific algorithms/techniques they use are proprietary to them and what makes their technology worth the money advertisers will pay (along with the number of users on the platform) to place their ads in front of their users.