Depending on what you are using the defect density for, you can answer both questions with yes or no.
If you are interested in measuring the defect density of different teams - I would hope that you would be measuring defect density per team as a baseline so that each team knew where they needed to improve and how much. In this situation you would look at only the code each team writes.
If you are looking for defect density of the entire system - In this situation you would probably include all code that makes up the system, including utility libraries your organization has written.
If you are trying to minimize defects and using defect density as a way to measure progress towards a quality goal - You may want to include unit test failures and errors, since a failing unit test means either the code is not doing what it used to do or the test is faulty.
If you are measuring each application/major module separately - If you're calculating defect density for the API vs the Mobile App vs the Web App, then you probably want to calculate defect density for your libraries separately, because the libraries are likely used by all three applications.
One of the "interesting" aspects of testing is that there often isn't a single best answer so much as there are answers which are good for your organization and others which are not so good. This means that you often have to decide how best (and whether) to use specific practices in your workplace.