Amd.cs (10164B)
1 using System.Globalization; 2 using System.IO; 3 using System.Net.Http; 4 using System.Text.Json; 5 using System.Xml.Linq; 6 7 namespace DriverUpdater; 8 9 // Checks AMD for the latest Adrenalin graphics driver and the latest chipset drivers. These are the 10 // feeds AMD's own installer reads. drivers.amd.com redirects any request without an amd.com Referer to 11 // an error page, for the feeds and the packages alike. 12 static class Amd 13 { 14 static readonly Uri Referrer = new("https://www.amd.com/"); 15 const string Signer = "Advanced Micro Devices"; 16 17 const string GraphicsIndexUrl = "https://drivers.amd.com/drivers/installer/json/version.json"; 18 const string ChipsetInfoUrl = "https://drivers.amd.com/drivers/installer/chipset/VersionInfo.xml"; 19 static readonly Uri ChipsetPackageUrl = new("https://drivers.amd.com/drivers/installer/chipset/AMD_Chipset_Software.exe"); 20 21 // The graphics feeds, in the order to search them. AMD ships one driver branch for its newest 22 // GPUs, one for the generation before, and one for older Vega and Polaris parts. 23 static readonly string[] GraphicsFeeds = 24 ["Consumer_Whql_Win10_productionASICs", "Consumer_Maintenance_Win10", "Consumer_Legacy_Win10"]; 25 26 public static async Task<List<DriverUpdate>> CheckGraphicsAsync(IReadOnlyList<InstalledDevice> installed) 27 { 28 // AMD graphics still use ATI's old PCI vendor ID. 29 var gpus = installed.Where(d => d.DeviceClass == "DISPLAY" && d.IsFromVendor("1002")).ToList(); 30 if (gpus.Count == 0) 31 return []; 32 33 // The index names each feed's URL. The values that aren't feeds are skipped by name. 34 using var index = JsonDocument.Parse(await GetStringAsync(GraphicsIndexUrl)); 35 var releases = new List<GraphicsRelease>(); 36 foreach (string feed in GraphicsFeeds) 37 { 38 string feedUrl = OnDriversHost(index.RootElement.GetProperty(feed).GetProperty("url").GetString()!); 39 releases.AddRange(JsonSerializer.Deserialize<List<GraphicsRelease>>(await GetStringAsync(feedUrl), JsonSerializerOptions.Web)!); 40 } 41 42 var updates = new List<DriverUpdate>(); 43 foreach (var gpu in gpus) 44 { 45 // Feeds list the GPUs they support as "DEV-REV", like "13C0-C1". 46 string sku = $"{gpu.Field("DEV")}-{gpu.Field("REV")}"; 47 var release = releases.FirstOrDefault(r => r.Skus.Contains(sku, StringComparer.OrdinalIgnoreCase)); 48 if (release is null) 49 continue; 50 51 // The Windows driver version (32.0.21042.62) has no clean mapping to AMD's numbers, so 52 // compare AMD's internal build number (25.10.42) instead. The display INF writes it to the 53 // registry, so it stays right after a driver only install. 54 // ReleaseVersion looks like "25.10.42-260323a-200157C-Channel". 55 string? installedBuild = gpu.DriverKeyValue("ReleaseVersion") is string releaseVersion ? BuildNumber(releaseVersion) : null; 56 string availableBuild = BuildNumber(release.InternalBuildVersion); 57 bool isNewer = installedBuild is null || Version.Parse(availableBuild) > Version.Parse(installedBuild); 58 var packageUrl = new Uri(OnDriversHost(release.FullBuild)); 59 60 updates.Add(new DriverUpdate 61 { 62 Device = gpu.Name, 63 Source = "AMD", 64 InstalledVersion = installedBuild ?? gpu.DriverVersion, 65 AvailableVersion = $"{release.ExternalBuildVersion} ({availableBuild})", 66 ReleaseDate = DateTime.ParseExact(release.ReleaseDate, "MM/dd/yyyy", CultureInfo.InvariantCulture), 67 SizeBytes = (long)(double.Parse(release.FullBuildFileSize, CultureInfo.InvariantCulture) * 1_048_576), 68 NotesUrl = new Uri(release.ReleaseNotes), 69 Package = isNewer 70 ? new VendorPackage(packageUrl, Referrer, Signer, VendorPackage.TempFolderFor(packageUrl), Unpack.WithTarAsync) 71 : null, 72 TargetDevice = gpu, 73 Status = isNewer ? "Update available" : "Up to date", 74 }); 75 } 76 return updates; 77 } 78 79 // Chipset drivers are many small drivers in one package, so each device gets its own row. Only 80 // devices that already run an AMD driver are compared. Devices on Microsoft's drivers are left alone. 81 public static async Task<List<DriverUpdate>> CheckChipsetAsync(IReadOnlyList<InstalledDevice> installed) 82 { 83 // VEN_1022 is AMD's PCI vendor ID for CPUs and chipsets. 84 if (!installed.Any(d => d.IsFromVendor("1022"))) 85 return []; 86 87 var info = XDocument.Parse(await GetStringAsync(ChipsetInfoUrl)).Root!; 88 string packageVersion = info.Element("Version")!.Value; 89 var notes = new Uri(info.Element("ReleaseNotes")!.Value); 90 91 if (Unpack.SevenZipPath() is null) 92 { 93 return [new DriverUpdate 94 { 95 Device = "AMD chipset drivers", 96 Source = "AMD chipset", 97 AvailableVersion = packageVersion, 98 NotesUrl = notes, 99 Status = "Install 7-Zip to check these", 100 }]; 101 } 102 103 // The package is kept between runs, one folder per AMD release, so a scan only downloads it 104 // when AMD publishes a new one. 105 string cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DriverUpdater"); 106 string folder = Path.Combine(cache, $"amd-chipset-{packageVersion}"); 107 var package = new VendorPackage(ChipsetPackageUrl, Referrer, Signer, folder, UnpackChipsetAsync) 108 { 109 KeepAfterInstall = true, 110 }; 111 var infs = InfFiles.Load(await package.UnpackAsync(_ => { })); 112 DeleteOlderChipsetPackages(cache, folder); 113 114 var updates = new List<DriverUpdate>(); 115 var infsSeen = new HashSet<(string, string)>(); 116 foreach (var device in installed.Where(d => IsAmdDriver(d.DriverProvider))) 117 { 118 var inf = infs.FindFor(device); 119 if (inf is null || !inf.IsPreferredOver(device)) 120 continue; 121 122 // Installing by hardware ID updates every device with that ID, so list each pair once. 123 if (!infsSeen.Add((inf.HardwareId, inf.Path))) 124 continue; 125 126 updates.Add(new DriverUpdate 127 { 128 Device = device.Name, 129 Source = "AMD chipset", 130 InstalledVersion = device.DriverVersion, 131 AvailableVersion = inf.Version.ToString(), 132 ReleaseDate = inf.Date, 133 NotesUrl = notes, 134 Package = package, 135 TargetDevice = device, 136 Status = "Update available", 137 }); 138 } 139 140 if (updates.Count == 0) 141 { 142 updates.Add(new DriverUpdate 143 { 144 Device = "AMD chipset drivers", 145 Source = "AMD chipset", 146 AvailableVersion = packageVersion, 147 NotesUrl = notes, 148 Status = "Up to date", 149 }); 150 } 151 return updates; 152 } 153 154 static bool IsAmdDriver(string provider) => 155 provider.StartsWith("Advanced Micro Devices", StringComparison.OrdinalIgnoreCase) 156 || provider.Equals("AMD", StringComparison.OrdinalIgnoreCase); 157 158 // The chipset package is an NSIS installer holding an InstallShield setup that holds the drivers. 159 // 7-Zip opens the NSIS layer. The InstallShield layer unpacks itself through an MSI administrative 160 // install, which copies the files out and installs nothing. AMD's own installer unpacks it the 161 // same way. 162 static async Task UnpackChipsetAsync(string package, string folder) 163 { 164 string sevenZip = Unpack.SevenZipPath() ?? throw new InvalidOperationException("7-Zip isn't installed"); 165 Directory.CreateDirectory(folder); 166 await Unpack.RunAsync(sevenZip, $"e -y \"-o{folder}\" \"{package}\" AMD_Chipset_Drivers.exe"); 167 168 string setup = Path.Combine(folder, "AMD_Chipset_Drivers.exe"); 169 if (!Authenticode.IsSignedBy(setup, Signer)) 170 throw new InvalidOperationException($"AMD_Chipset_Drivers.exe isn't signed by {Signer}"); 171 172 // Comes out as: /s /a /v"/qn GONOGO=PUBLICGO TARGETDIR=\"C:\path\"" 173 // GONOGO=PUBLICGO is the property AMD's own installer passes. 174 await Unpack.RunAsync(setup, $"/s /a /v\"/qn GONOGO=PUBLICGO TARGETDIR=\\\"{folder}\\\"\""); 175 File.Delete(setup); 176 } 177 178 static void DeleteOlderChipsetPackages(string cache, string current) 179 { 180 foreach (string old in Directory.EnumerateDirectories(cache, "amd-chipset-*")) 181 { 182 if (!old.Equals(current, StringComparison.OrdinalIgnoreCase)) 183 Directory.Delete(old, recursive: true); 184 } 185 } 186 187 // "25.10.45.16-261009a-205305C-AMD-Software-Adrenalin-Edition" becomes "25.10.45". The installed 188 // build has only three fields, so both sides are cut to three. 189 static string BuildNumber(string release) => 190 string.Join('.', release.Split('-')[0].Split('.').Take(3)); 191 192 // The feeds name www2.ati.com, which only redirects to drivers.amd.com. 193 static string OnDriversHost(string url) => new UriBuilder(url) { Host = "drivers.amd.com" }.Uri.ToString(); 194 195 static async Task<string> GetStringAsync(string url) 196 { 197 using var request = new HttpRequestMessage(HttpMethod.Get, url) { Headers = { Referrer = Referrer } }; 198 using var response = await Web.Client.SendAsync(request); 199 response.EnsureSuccessStatusCode(); 200 return await response.Content.ReadAsStringAsync(); 201 } 202 203 // The parts of a graphics feed entry the app reads. The feed's keys are all lowercase, which 204 // JsonSerializerOptions.Web matches without regard to case. 205 record GraphicsRelease( 206 string ExternalBuildVersion, 207 string InternalBuildVersion, 208 string ReleaseDate, 209 string FullBuild, 210 string FullBuildFileSize, 211 string ReleaseNotes, 212 List<string> Skus); 213 }