chipset_enable: Fix use-after-free of LPC PCI device

We ran pci_free_dev() too early,  after some code moved around
in enable_flash_amd_spi100(). Instead of trying to ensure that
we free the device handle on all paths, only use it early, and
free it right away.

Change-Id: Ie71cdd2f98f67bc5016067404bb911f5629d0f03
Signed-off-by: Nico Huber <nico.huber@secunet.com>
Reviewed-on: https://review.sourcearcade.org/c/flashprog/+/352
Reviewed-by: Arthur Heymans <arthur@aheymans.xyz>
Tested-by: Nico Huber <nico.h@gmx.de>
Reviewed-by: Nico Huber <nico.h@gmx.de>
diff --git a/chipset_enable.c b/chipset_enable.c
index 24555d9..9b50a05 100644
--- a/chipset_enable.c
+++ b/chipset_enable.c
@@ -1487,9 +1487,11 @@
 	}
 
 	const uint32_t spibar = pci_read_long(lpc, 0xa0);
+	const uint32_t rom_range2 = pci_read_long(lpc, 0x6c);
+	pci_free_dev(lpc);
+
 	if (spibar == 0xffffffff) {
 		msg_perr("SPI100 BAR reads all `ff', aborting.\n");
-		pci_free_dev(lpc);
 		return ERROR_FATAL;
 	}
 
@@ -1497,8 +1499,6 @@
 	msg_pdbg(", AbortEnable=%u, RouteTpm2Spi=%u", spibar >> 2 & 1, spibar >> 3 & 1);
 	msg_pdbg(", PspSpiMmioSel=%u\n", spibar >> 4 & 1);
 
-	pci_free_dev(lpc);
-
 	const bool spirom_enable = spibar & BIT(1);
 	if (spirom_enable) {
 		/* If SPI ROM is memory mapped, nothing else can be */
@@ -1520,7 +1520,6 @@
 		return ERROR_FATAL;
 
 	/* RomRange2 is supposed to be used for the mapping directly below 4G. */
-	const uint32_t rom_range2 = pci_read_long(lpc, 0x6c);
 	const uint32_t rom_range_end = rom_range2 | 0xffff;
 	const uint32_t rom_range_start = (rom_range2 & 0xffff) << 16;
 	const size_t mapped_len = rom_range_end > rom_range_start ? rom_range_end - rom_range_start + 1 : 0;