How does Magento2 generate the specific ExtensionFactory and ExtensionAttributeInterface?

First of all autogeneration is happening based on class name suffix, e.g. Factory, ExtensionInterface (see \Magento\Framework\Api\Code\Generator\ExtensionAttributesInterfaceGenerator::EXTENSION_INTERFACE_SUFFIX) or Extension (see \Magento\Framework\Api\Code\Generator\ExtensionAttributesGenerator::EXTENSION_SUFFIX).

Proper generator is selected based on suffix here \Magento\Framework\Code\Generator::generateClass.

Let's assume Magento mode is developer and missing classes can be generated on fly (similar process will happen when compiler is used). When object manager tries to instantiate let's say Magento\Quote\Api\Data\CartItemExtensionFactory and it does not exist, the following happens:

  1. Autoloader fails to instantiate class and initiates code generation here \Magento\Framework\Code\Generator\Autoloader::load
  2. Then class suffix is determined as Factory (list of all declared suffixes can be found here \Magento\Framework\ObjectManager\DefinitionFactory::getCodeGenerator) and corresponding Factory generator class (Magento\Framework\ObjectManager\Code\Generator\Factory) is used to generate missing factory
  3. All autogenerated classes are always based on another classes, in case of factory, source class name is calculated just by removing Factory suffix, it will be Magento\Quote\Api\Data\CartItemExtension. This class does not exist and autogeneration is invoked once again by autoloader, but this time for Extension class
  4. Now suffix is Extension and \Magento\Framework\Api\Code\Generator\ExtensionAttributesGenerator will be used to generate this class
  5. Source class for Extension class generation is calculated as Magento\Quote\Api\Data\CartItemInterface, it exists and Extension class is successfully generated. However, on the attempt to include Extension class file, autogeneration is triggered once again because Magento\Quote\Api\Data\CartItemExtension implements Magento\Quote\Api\Data\CartItemExtensionInterface, which does not exist
  6. Suffix is ExtensionInterface and \Magento\Framework\Api\Code\Generator\ExtensionAttributesInterfaceGenerator will be used for generation
  7. ExtensionInterface and Extension classes are generated based on information from extension_attributes.xml, accessible via \Magento\Framework\Api\ExtensionAttribute\Config, then Factory gets generated

One important note is that there is no preference for ExtensionInterface in di.xml because both Extension and ExtensionInterface are autogenerated. This is not a problem because ExtentionInterface is not expected to be injected via construct directly.