jvm-bytecode 0.5.0

JVM class and bytecode support for the jvm crate
Documentation
use alloc::{
    borrow::Cow,
    boxed::Box,
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};
use core::{
    fmt::{self, Debug, Formatter},
    ops::{Deref, DerefMut},
};

use parking_lot::RwLock;

use classfile::{AttributeInfo, ClassInfo, ConstantPoolReference};
use jvm::{ClassDefinition, ClassInstance, Field, JavaValue, Jvm, Method, Result};
use jvm_class_proto::JavaClassProto;
use jvm_types::{ClassAccessFlags, FieldAccessFlags, JavaType, MethodAccessFlags};

use crate::{ClassDefinitionError, class_instance::ClassInstanceImpl, field::FieldImpl, method::MethodImpl, verifier};

struct ClassDefinitionInner {
    name: String,
    super_class_name: Option<String>,
    interfaces: Vec<String>,
    access_flags: ClassAccessFlags,
    methods: Vec<MethodImpl>,
    fields: Vec<FieldImpl>,
    constant_values: Vec<(FieldImpl, ConstantPoolReference)>,
    // one slot per declared field, in declaration order
    storage: RwLock<Box<[JavaValue]>>,
    // instance fields of the whole class hierarchy with their default values; needs the superclasses, so laid out at preparation
    instance_layout: RwLock<InstanceLayout>,
}

pub(crate) type InstanceLayout = (Arc<[FieldImpl]>, Box<[JavaValue]>);

#[derive(Clone)]
pub struct ClassDefinitionImpl {
    inner: Arc<ClassDefinitionInner>,
}

impl ClassDefinitionImpl {
    pub fn new(
        name: &str,
        super_class_name: Option<String>,
        interfaces: Vec<String>,
        access_flags: ClassAccessFlags,
        methods: Vec<MethodImpl>,
        fields: Vec<FieldImpl>,
    ) -> Self {
        Self::with_constant_values(name, super_class_name, interfaces, access_flags, methods, fields, Vec::new())
    }

    #[allow(clippy::too_many_arguments)]
    fn with_constant_values(
        name: &str,
        super_class_name: Option<String>,
        interfaces: Vec<String>,
        access_flags: ClassAccessFlags,
        methods: Vec<MethodImpl>,
        fields: Vec<FieldImpl>,
        constant_values: Vec<(FieldImpl, ConstantPoolReference)>,
    ) -> Self {
        let storage = fields
            .iter()
            .map(|field| JavaValue::default_of(&JavaType::parse(&field.descriptor())))
            .collect();

        Self {
            inner: Arc::new(ClassDefinitionInner {
                name: name.to_string(),
                super_class_name,
                interfaces,
                access_flags,
                methods,
                fields,
                constant_values,
                storage: RwLock::new(storage),
                instance_layout: RwLock::new(InstanceLayout::default()),
            }),
        }
    }

    pub fn from_class_proto<C, Context>(proto: JavaClassProto<C>, context: Context) -> Self
    where
        C: ?Sized + 'static + Send,
        Context: Sync + Send + DerefMut + Deref<Target = C> + Clone + 'static,
    {
        let methods = proto
            .methods
            .into_iter()
            .map(|x| MethodImpl::from_method_proto(x, context.clone()))
            .collect::<Vec<_>>();

        let fields = proto
            .fields
            .into_iter()
            .map(|field| FieldImpl::from_field_proto(proto.name, field))
            .collect::<Vec<_>>();

        let interfaces = proto.interfaces.into_iter().map(|x| x.to_string()).collect();

        Self::new(
            proto.name,
            proto.parent_class.map(|x| x.to_string()),
            interfaces,
            proto.access_flags,
            methods,
            fields,
        )
    }

    pub fn from_classfile(data: &[u8]) -> core::result::Result<Self, ClassDefinitionError> {
        let class = ClassInfo::parse(data)?;
        verifier::verify(&class)?;

        let mut constant_values = Vec::new();
        let fields = class
            .fields
            .into_iter()
            .map(|field_info| {
                let constant = field_info.attributes.iter().find_map(|x| match x {
                    AttributeInfo::ConstantValue(value) => Some(value.clone()),
                    _ => None,
                });

                let field = FieldImpl::from_field_info(&class.this_class, field_info);
                if let Some(x) = constant
                    && field.access_flags().contains(FieldAccessFlags::STATIC)
                {
                    constant_values.push((field.clone(), x));
                }

                field
            })
            .collect::<Vec<_>>();

        let methods = class.methods.into_iter().map(MethodImpl::from_method_info).collect::<Vec<_>>();

        let interfaces = class.interfaces.into_iter().map(|x| x.to_string()).collect();

        Ok(Self::with_constant_values(
            &class.this_class,
            class.super_class.map(|x| x.to_string()),
            interfaces,
            class.access_flags,
            methods,
            fields,
            constant_values,
        ))
    }

    pub fn fields(&self) -> &[FieldImpl] {
        &self.inner.fields
    }

    pub(crate) fn instance_layout(&self) -> InstanceLayout {
        self.inner.instance_layout.read().clone()
    }
}

#[async_trait::async_trait]
impl ClassDefinition for ClassDefinitionImpl {
    fn name(&self) -> Cow<'_, str> {
        (&self.inner.name).into()
    }

    fn super_class_name(&self) -> Option<String> {
        self.inner.super_class_name.as_ref().map(|x| x.to_string())
    }

    fn interface_names(&self) -> Vec<String> {
        self.inner.interfaces.clone()
    }

    fn access_flags(&self) -> ClassAccessFlags {
        self.inner.access_flags
    }

    async fn instantiate(&self, _: &Jvm) -> Result<Box<dyn ClassInstance>> {
        Ok(Box::new(ClassInstanceImpl::new(self)))
    }

    async fn prepare(&self, jvm: &Jvm) -> Result<()> {
        let mut fields = Vec::new();
        let mut class = Some(Box::new(self.clone()) as Box<dyn ClassDefinition>);
        while let Some(x) = class {
            // fields of other ClassDefinition implementations cannot be stored in a ClassInstanceImpl
            fields.extend(
                x.fields()
                    .iter()
                    .filter(|field| !field.access_flags().contains(FieldAccessFlags::STATIC))
                    .filter_map(|field| field.as_any().downcast_ref::<FieldImpl>().cloned()),
            );
            class = x.super_class_name().map(|name| jvm.get_class(&name).unwrap().definition);
        }
        let defaults = fields
            .iter()
            .map(|field| JavaValue::default_of(&JavaType::parse(&field.descriptor())))
            .collect();

        *self.inner.instance_layout.write() = (fields.into(), defaults);

        for (field, constant) in &self.inner.constant_values {
            let value = match constant {
                ConstantPoolReference::Integer(x) => match field.descriptor().as_ref() {
                    "Z" => JavaValue::Boolean(*x != 0),
                    "B" => JavaValue::Byte(*x as i8),
                    "C" => JavaValue::Char(*x as u16),
                    "S" => JavaValue::Short(*x as i16),
                    _ => JavaValue::Int(*x),
                },
                ConstantPoolReference::Long(x) => JavaValue::Long(*x),
                ConstantPoolReference::Float(x) => JavaValue::Float(*x),
                ConstantPoolReference::Double(x) => JavaValue::Double(*x),
                ConstantPoolReference::String(x) => JavaValue::Object(Some(jvm.intern_string(x).await?)),
                _ => continue,
            };

            let slot = self.inner.fields.iter().position(|x| x == field).unwrap();
            self.inner.storage.write()[slot] = value;
        }

        Ok(())
    }

    fn method(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Method>> {
        self.inner
            .methods
            .iter()
            .find(|&method| {
                method.name() == name && method.descriptor() == descriptor && method.access_flags().contains(MethodAccessFlags::STATIC) == is_static
            })
            .map(|x| Box::new(x.clone()) as Box<dyn Method>)
    }

    fn field(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Field>> {
        self.inner
            .fields
            .iter()
            .find(|&field| {
                field.name() == name && field.descriptor() == descriptor && field.access_flags().contains(FieldAccessFlags::STATIC) == is_static
            })
            .map(|x| Box::new(x.clone()) as Box<dyn Field>)
    }

    fn fields(&self) -> Vec<Box<dyn Field>> {
        self.inner.fields.iter().map(|x| Box::new(x.clone()) as Box<dyn Field>).collect()
    }

    fn get_static_field(&self, field: &dyn Field) -> Result<JavaValue> {
        let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();

        let slot = self.inner.fields.iter().position(|x| x == field).unwrap();

        Ok(self.inner.storage.read()[slot].clone())
    }

    fn put_static_field(&mut self, field: &dyn Field, value: JavaValue) -> Result<()> {
        let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();

        let slot = self.inner.fields.iter().position(|x| x == field).unwrap();
        self.inner.storage.write()[slot] = value;

        Ok(())
    }
}

impl Debug for ClassDefinitionImpl {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "Class({})", self.name())
    }
}