Repository: rust
Issue: Could not compile driver (build script) - DefKind Code 131
Labels: S-needs-repro

### Code
#### build.rs
```Rust
use std::path::PathBuf;
use thiserror::Error;
use winreg::RegKey;
use winreg::enums::HKEY_LOCAL_MACHINE;

#[derive(Debug, Error)]
pub enum Error {
    #[error(transparent)]
    IoError(#[from] std::io::Error),
    #[error("cannot find the directory")]
    DirectoryNotFound,
}

/// Retrieves the path to the Windows Kits directory. The default should be
/// `C:\Program Files (x86)\Windows Kits\10`.
pub fn get_windows_kits_dir() -> Result<PathBuf, Error> {
    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
    let key = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots";
    let dir: String = hklm.open_subkey(key)?.get_value("KitsRoot10")?;

    Ok(dir.into())
}

pub enum DirectoryType {
    Include,
    Library,
}

/// Retrieves the path to the kernel mode libraries. The path may look something like:
/// `C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\km`.
pub fn get_km_dir(dir_type: DirectoryType) -> Result<PathBuf, Error> {
    // We first append lib to the path and read the directory..
    let dir = get_windows_kits_dir()?
        .join(match dir_type {
            DirectoryType::Include => "Include",
            DirectoryType::Library => "Lib",
        })
        .read_dir()?;

    // In the lib directory we may have one or more directories named after the version of Windows,
    // we will be looking for the highest version number.
    let dir = dir
        .filter_map(|dir| dir.ok())
        .map(|dir| dir.path())
        .filter(|dir| {
            dir.components()
                .last()
                .and_then(|c| c.as_os_str().to_str())
                .map(|c| c.starts_with("10.") && dir.join("km").is_dir())
                .unwrap_or(false)
        })
        .max()
        .ok_or_else(|| Error::DirectoryNotFound)?;

    // Finally append km to the path to get the path to the kernel mode libraries.
    Ok(dir.join("km"))
}

fn generate_base() {
    // Tell Cargo to re-run this if src/wrapper.h gets changed.
    println!("cargo:rerun-if-changed=src/wrapper.h");

    // Find the include directory containing the kernel headers.
    let include_dir = get_km_dir(DirectoryType::Include).unwrap();

    // Get the build directory.
    let out_path = PathBuf::from(
        std::env::var_os("OUT_DIR")
            .expect("the environment variable OUT_DIR is undefined")
    );

    // Generate the bindings
    bindgen::Builder::default()
        .header("src/wrapper.h")
        .use_core()
        .derive_debug(false)
        .layout_tests(false)
        .ctypes_prefix("cty")
        .default_enum_style(bindgen::EnumVariation::ModuleConsts)
        .clang_arg(format!("-I{}", include_dir.to_str().unwrap()))
        .parse_callbacks(Box::new(bindgen::CargoCallbacks))
        .ignore_functions()
        .generate()
        .unwrap()
        .write_to_file(out_path.join("base.rs"))
        .unwrap();
}

fn main() {
    generate_base();
}
```


### Meta
`rustc --version --verbose`:
```
rustc 1.75.0-nightly (a2f5f9691 2023-11-02)
binary: rustc
commit-hash: a2f5f9691b6ce64c1703feaf9363710dfd7a56cf
commit-date: 2023-11-02
host: x86_64-pc-windows-msvc
release: 1.75.0-nightly
LLVM version: 17.0.4
[rustc-ice-2023-11-03T17_58_06-11024.txt](https://github.com/rust-lang/rust/files/13253358/rustc-ice-2023-11-03T17_58_06-11024.txt)

```

### Error output
*E: is an USB-Device*

```
$LIBCLANG_PATH='(my-system-path)\VS-BuildTools\AppData\Common7\IDE\VC\vcpackages'
cargo build
    Updating crates.io index
   Compiling driverv0.1.0 (E:\driver)
thread 'rustc' panicked at compiler\rustc_metadata\src\rmeta\table.rs:140:1:
Unexpected DefKind code: 131
stack backtrace:
   0:     0x7ffc32713963 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h904bc0c04ce5a549
   1:     0x7ffc32747c0d - core::fmt::write::hcffc85a6c0319a3e
   2:     0x7ffc3270a301 - <std::io::IoSliceMut as core::fmt::Debug>::fmt::hd77ff255c1f30258
   3:     0x7ffc3271376a - std::sys_common::backtrace::lock::h6530a8577ea6442e
   4:     0x7ffc32716c39 - std::panicking::default_hook::h80560cea359df8ed
   5:     0x7ffc327168fb - std::panicking::default_hook::h80560cea359df8ed
   6:     0x7ffc29ad075f - <tracing_subscriber[348ee398b193517f]::fmt::format::Writer>::write_fmt
   7:     0x7ffc32717213 - std::panicking::rust_panic_with_hook::h3155420840ff1d0e
   8:     0x7ffc327170b5 - <std::panicking::begin_panic_handler::StaticStrPayload as core::panic::PanicPayload>::take_box::h431b1dfd98712151
   9:     0x7ffc32714259 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h904bc0c04ce5a549
  10:     0x7ffc32716dc4 - rust_begin_unwind
  11:     0x7ffc3277b7c7 - core::panicking::panic_fmt::h61dffb131f6e9923
  12:     0x7ffc29506795 - <rustc_metadata[88dd6ab9ae3c6330]::creader::CStore>::def_kind_untracked
  13:     0x7ffc290a91f9 - <rustc_ast_lowering[201af491a11ab4de]::index::NodeCollector as rustc_hir[3a40cb97853f56da]::intravisit::Visitor>::visit_trait_ref
  14:     0x7ffc2911efcf - <<rustc_resolve[f04156e10fad7049]::late::LateResolutionVisitor>::find_lifetime_for_self::SelfVisitor as rustc_ast[b6e260e1ed6edfd8]::visit::Visitor>::visit_ty
  15:     0x7ffc290d0df8 - <rustc_resolve[f04156e10fad7049]::Segment as core[f8fea1319500e153]::convert::From<&rustc_ast[b6e260e1ed6edfd8]::ast::PathSegment>>::from
  16:     0x7ffc290b8a5f - <rustc_ast_lowering[201af491a11ab4de]::index::NodeCollector as rustc_hir[3a40cb97853f56da]::intravisit::Visitor>::visit_trait_ref
  17:     0x7ffc290bbb23 - <rustc_resolve[f04156e10fad7049]::Resolver as rustc_expand[16a018f586d05fde]::base::ResolverExpand>::resolve_imports
  18:     0x7ffc2959e6be - <rustc_expand[16a018f586d05fde]::expand::MacroExpander>::fully_expand_fragment
  19:     0x7ffc2888c64c - <rustc_expand[16a018f586d05fde]::expand::MacroExpander>::expand_crate
  20:     0x7ffc25c80e21 - rustc_interface[389250caa294c4dd]::interface::parse_check_cfg
  21:     0x7ffc25c8f913 - rustc_interface[389250caa294c4dd]::passes::resolver_for_lowering
  22:     0x7ffc286c17ed - rustc_query_impl[cb10d16ec2d5e911]::profiling_support::alloc_self_profile_query_strings
  23:     0x7ffc286fed69 - rustc_query_impl[cb10d16ec2d5e911]::profiling_support::alloc_self_profile_query_strings
  24:     0x7ffc286fc5dc - rustc_query_impl[cb10d16ec2d5e911]::profiling_support::alloc_self_profile_query_strings
  25:     0x7ffc2872ec94 - rustc_query_impl[cb10d16ec2d5e911]::profiling_support::alloc_self_profile_query_strings
  26:     0x7ffc28700371 - rustc_query_impl[cb10d16ec2d5e911]::profiling_support::alloc_self_profile_query_strings
  27:     0x7ffc25c39ca6 - rustc_driver_impl[fd9e39ab138d307a]::main
  28:     0x7ffc25c4ac8f - <rustc_middle[c7980097819ed664]::ty::SymbolName as core[f8fea1319500e153]::fmt::Debug>::fmt
  29:     0x7ffc25c402db - rustc_driver_impl[fd9e39ab138d307a]::args::arg_expand_all
  30:     0x7ffc25c5f609 - <rustc_middle[c7980097819ed664]::ty::SymbolName as core[f8fea1319500e153]::fmt::Debug>::fmt
  31:     0x7ffc25c431d1 - rustc_driver_impl[fd9e39ab138d307a]::args::arg_expand_all
  32:     0x7ffc3272a41c - std::sys::windows::thread::Thread::new::hf36a95c7576122b9
  33:     0x7ffc91ab257d - BaseThreadInitThunk
  34:     0x7ffc92a8aa58 - RtlUserThreadStart

error: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md

note: please attach the file at `E:\driver\rustc-ice-2023-11-03T17_58_06-11024.txt` to your bug report

note: compiler flags: --crate-type bin -C embed-bitcode=no -C debuginfo=2 -C incremental=[REDACTED]

note: some of the compiler flags provided by cargo are hidden

query stack during panic:
#0 [resolver_for_lowering] getting the resolver for lowering
end of query stack
error: could not compile `driver` (build script)
```