Validity of Non-matched Patterns

Abierto
#587 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
25/100
Tipo de issue
Documentación
Claridad
Necesita aclaración
Estado de actividad
Estancado
Stack tecnológico
rust
Área
compilers

Línea de trabajo

Start with the foo() pattern and bar() entry point in the issue, focusing on whether a failed discriminant check can avoid reading invalid fields or padding. Done means establishing and documenting the validity rules for non-matching patterns, including the proposed union-of-struct option representation.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

I was wondering what the rules are on binding pattern validity, namely when a pattern does not succesfully match.

The main example I can think of are custom ADTs (ADTs using union-of-struct definitions, rather than enum)

Using that example, the specific question I want to ask whether the following code (with bar() as the entry point) is guaranteed to be well-defined (or if it is UB, or might be UB depending on match lowering):

#[repr(C)]
pub union FakeEnum {
     pub fake_variant: FakeVariant,
     pub other_variant: OtherVariant,
     // other fields
}

pub struct OtherVariant {
    pub discriminant: u32,
    pub blank: u32,
}

pub struct FakeVariant {
     pub discriminant: u32,
     pub value: NonZeroU32,
}


pub unsafe fn foo(x: FakeEnum) {
     unsafe {
           match x {
               FakeEnum{fake_variant: val @ FakeVariant{discriminant: 0, ..}} => println!("{}", val.value),
               _ => {}
     }
}

pub fn bar() {
     foo(FakeEnum{other_variant: OtherVariant{discriminant: 1, blank: 0})
}

Because FakeVariant is matched by binding, one might expect that it eagerly requires validity (which causes UB on reading 0 bytes for value). However, since when discriminant is checked, the pattern match fails, possibly preventing value from being read at all.

For context of this, in the OS I'm working on, there is a concept of an "Option" (not in the optional sense like std::option::Option, but in the sense of "A list of options"), which roughly follows the union-of-struct pattern for two main reasons:

  • The "discriminant" of the option is actually a UUID (#[repr(Uuid)] does not exist in Rust), and
  • There is no fixed list of the set of options that may be passed to the kernel (explicit functionality exists for "If you don't know what this option is, ignore it").

(There is also a header of common fields that carries more data than just the discriminant, notably a flags field).

It would be nice, for ergonomics reasons (and to make correctness easier) if I could write matches that check if the type matches an expected value, and if so, bind the whole union field, which would use a form similar to the above. However, I worry about validity, considering that while all option types of a given group have a fixed upper size (32 or 64 bytes for the data after the header is common), there is no guarantee that any given option type uses the whole payload (and thus might have tail padding, or interior padding after the header).

Lenguaje dominante
Sin datos de lenguaje
Estrellas
760
Forks
68
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de rust-lang/unsafe-code-guidelines

Todos los issues de rust-lang/unsafe-code-guidelines

Issues similares

Más issues de Compilers

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.