driver-updater

Windows app that checks Windows Update and hardware vendors for newer drivers and silently installs the driver.
git clone https://dittus.dev/git/driver-updater.git
Log | Files | Refs | README | Download

Unpack.cs (4758B)


      1 using System.Diagnostics;
      2 using System.IO;
      3 using System.Runtime.InteropServices;
      4 using Microsoft.Win32;
      5 using Microsoft.Win32.SafeHandles;
      6 
      7 namespace DriverUpdater;
      8 
      9 // Runs the tools that unpack vendor packages, so the app can install the drivers inside without
     10 // running the vendor's setup.
     11 static class Unpack
     12 {
     13     // A tool that's still running after this long is treated as hung.
     14     static readonly TimeSpan Timeout = TimeSpan.FromMinutes(10);
     15 
     16     // The tar.exe built into Windows reads 7z archives, including the ones behind a small exe like
     17     // NVIDIA's and AMD's graphics packages.
     18     public static Task WithTarAsync(string package, string folder)
     19     {
     20         Directory.CreateDirectory(folder);
     21         string tar = Path.Combine(Environment.SystemDirectory, "tar.exe");
     22         return RunAsync(tar, $"-xf \"{package}\" -C \"{folder}\"");
     23     }
     24 
     25     // 7-Zip is optional. Only AMD's chipset package needs it.
     26     public static string? SevenZipPath()
     27     {
     28         using var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
     29         using var key = hklm.OpenSubKey(@"SOFTWARE\7-Zip");
     30         if ((key?.GetValue("Path64") ?? key?.GetValue("Path")) is not string folder)
     31             return null;
     32 
     33         string sevenZip = Path.Combine(folder, "7z.exe");
     34         return File.Exists(sevenZip) ? sevenZip : null;
     35     }
     36 
     37     // Runs a tool with no window, waits for it and every process it starts, and throws with its error
     38     // output if it fails. Both output streams are read at once, so a tool that fills one can't stall
     39     // waiting on the other.
     40     public static async Task RunAsync(string exe, string arguments)
     41     {
     42         var start = new ProcessStartInfo(exe, arguments)
     43         {
     44             UseShellExecute = false,
     45             CreateNoWindow = true,
     46             RedirectStandardOutput = true,
     47             RedirectStandardError = true,
     48         };
     49 
     50         // AMD's chipset setup hands its work to a second copy of itself and exits right away, so
     51         // waiting on the first process isn't enough. A job object holds every process the tool
     52         // starts. The tool joins it a moment after it starts, which is long before a setup program
     53         // gets around to starting anything.
     54         using var job = CreateJobObjectW(IntPtr.Zero, null);
     55         using var process = Process.Start(start)!;
     56         if (job.IsInvalid || !AssignProcessToJobObject(job, process.Handle))
     57             throw new InvalidOperationException($"Couldn't track the processes {Path.GetFileName(exe)} starts");
     58 
     59         var output = process.StandardOutput.ReadToEndAsync();
     60         string errors = await process.StandardError.ReadToEndAsync();
     61         await output;
     62         await process.WaitForExitAsync();
     63         await WaitUntilEmptyAsync(job, Path.GetFileName(exe));
     64 
     65         if (process.ExitCode != 0)
     66             throw new InvalidOperationException(
     67                 $"{Path.GetFileName(exe)} failed with exit code {process.ExitCode}. {errors.Trim()}".Trim());
     68     }
     69 
     70     static async Task WaitUntilEmptyAsync(SafeFileHandle job, string tool)
     71     {
     72         var watch = Stopwatch.StartNew();
     73         while (ActiveProcesses(job) > 0)
     74         {
     75             if (watch.Elapsed > Timeout)
     76                 throw new TimeoutException($"{tool} was still running after {Timeout.TotalMinutes} minutes");
     77             await Task.Delay(250);
     78         }
     79     }
     80 
     81     static uint ActiveProcesses(SafeFileHandle job)
     82     {
     83         if (!QueryInformationJobObject(job, JobObjectBasicAccountingInformation, out var info,
     84                 Marshal.SizeOf<JobAccounting>(), IntPtr.Zero))
     85             throw new InvalidOperationException("Couldn't read the tool's process list");
     86         return info.ActiveProcesses;
     87     }
     88 
     89     const int JobObjectBasicAccountingInformation = 1;
     90 
     91     [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
     92     static extern SafeFileHandle CreateJobObjectW(IntPtr attributes, string? name);
     93 
     94     [DllImport("kernel32.dll", SetLastError = true)]
     95     static extern bool AssignProcessToJobObject(SafeFileHandle job, IntPtr process);
     96 
     97     [DllImport("kernel32.dll", SetLastError = true)]
     98     static extern bool QueryInformationJobObject(
     99         SafeFileHandle job, int infoClass, out JobAccounting info, int length, IntPtr returnLength);
    100 
    101     // JOBOBJECT_BASIC_ACCOUNTING_INFORMATION
    102     [StructLayout(LayoutKind.Sequential)]
    103     struct JobAccounting
    104     {
    105         public long TotalUserTime;
    106         public long TotalKernelTime;
    107         public long ThisPeriodTotalUserTime;
    108         public long ThisPeriodTotalKernelTime;
    109         public uint TotalPageFaultCount;
    110         public uint TotalProcesses;
    111         public uint ActiveProcesses;
    112         public uint TotalTerminatedProcesses;
    113     }
    114 }