Skip to main content

jvm_bytecode/
class_definition.rs

1use alloc::{
2    borrow::Cow,
3    boxed::Box,
4    string::{String, ToString},
5    sync::Arc,
6    vec::Vec,
7};
8use core::{
9    fmt::{self, Debug, Formatter},
10    ops::{Deref, DerefMut},
11};
12
13use parking_lot::RwLock;
14
15use classfile::{AttributeInfo, ClassInfo, ConstantPoolReference};
16use jvm::{ClassDefinition, ClassInstance, Field, JavaValue, Jvm, Method, Result};
17use jvm_class_proto::JavaClassProto;
18use jvm_types::{ClassAccessFlags, FieldAccessFlags, JavaType, MethodAccessFlags};
19
20use crate::{ClassDefinitionError, class_instance::ClassInstanceImpl, field::FieldImpl, method::MethodImpl, verifier};
21
22struct ClassDefinitionInner {
23    name: String,
24    super_class_name: Option<String>,
25    interfaces: Vec<String>,
26    access_flags: ClassAccessFlags,
27    methods: Vec<MethodImpl>,
28    fields: Vec<FieldImpl>,
29    constant_values: Vec<(FieldImpl, ConstantPoolReference)>,
30    // one slot per declared field, in declaration order
31    storage: RwLock<Box<[JavaValue]>>,
32    // instance fields of the whole class hierarchy with their default values; needs the superclasses, so laid out at preparation
33    instance_layout: RwLock<InstanceLayout>,
34}
35
36pub(crate) type InstanceLayout = (Arc<[FieldImpl]>, Box<[JavaValue]>);
37
38#[derive(Clone)]
39pub struct ClassDefinitionImpl {
40    inner: Arc<ClassDefinitionInner>,
41}
42
43impl ClassDefinitionImpl {
44    pub fn new(
45        name: &str,
46        super_class_name: Option<String>,
47        interfaces: Vec<String>,
48        access_flags: ClassAccessFlags,
49        methods: Vec<MethodImpl>,
50        fields: Vec<FieldImpl>,
51    ) -> Self {
52        Self::with_constant_values(name, super_class_name, interfaces, access_flags, methods, fields, Vec::new())
53    }
54
55    #[allow(clippy::too_many_arguments)]
56    fn with_constant_values(
57        name: &str,
58        super_class_name: Option<String>,
59        interfaces: Vec<String>,
60        access_flags: ClassAccessFlags,
61        methods: Vec<MethodImpl>,
62        fields: Vec<FieldImpl>,
63        constant_values: Vec<(FieldImpl, ConstantPoolReference)>,
64    ) -> Self {
65        let storage = fields
66            .iter()
67            .map(|field| JavaValue::default_of(&JavaType::parse(&field.descriptor())))
68            .collect();
69
70        Self {
71            inner: Arc::new(ClassDefinitionInner {
72                name: name.to_string(),
73                super_class_name,
74                interfaces,
75                access_flags,
76                methods,
77                fields,
78                constant_values,
79                storage: RwLock::new(storage),
80                instance_layout: RwLock::new(InstanceLayout::default()),
81            }),
82        }
83    }
84
85    pub fn from_class_proto<C, Context>(proto: JavaClassProto<C>, context: Context) -> Self
86    where
87        C: ?Sized + 'static + Send,
88        Context: Sync + Send + DerefMut + Deref<Target = C> + Clone + 'static,
89    {
90        let methods = proto
91            .methods
92            .into_iter()
93            .map(|x| MethodImpl::from_method_proto(x, context.clone()))
94            .collect::<Vec<_>>();
95
96        let fields = proto
97            .fields
98            .into_iter()
99            .map(|field| FieldImpl::from_field_proto(proto.name, field))
100            .collect::<Vec<_>>();
101
102        let interfaces = proto.interfaces.into_iter().map(|x| x.to_string()).collect();
103
104        Self::new(
105            proto.name,
106            proto.parent_class.map(|x| x.to_string()),
107            interfaces,
108            proto.access_flags,
109            methods,
110            fields,
111        )
112    }
113
114    pub fn from_classfile(data: &[u8]) -> core::result::Result<Self, ClassDefinitionError> {
115        let class = ClassInfo::parse(data)?;
116        verifier::verify(&class)?;
117
118        let mut constant_values = Vec::new();
119        let fields = class
120            .fields
121            .into_iter()
122            .map(|field_info| {
123                let constant = field_info.attributes.iter().find_map(|x| match x {
124                    AttributeInfo::ConstantValue(value) => Some(value.clone()),
125                    _ => None,
126                });
127
128                let field = FieldImpl::from_field_info(&class.this_class, field_info);
129                if let Some(x) = constant
130                    && field.access_flags().contains(FieldAccessFlags::STATIC)
131                {
132                    constant_values.push((field.clone(), x));
133                }
134
135                field
136            })
137            .collect::<Vec<_>>();
138
139        let methods = class.methods.into_iter().map(MethodImpl::from_method_info).collect::<Vec<_>>();
140
141        let interfaces = class.interfaces.into_iter().map(|x| x.to_string()).collect();
142
143        Ok(Self::with_constant_values(
144            &class.this_class,
145            class.super_class.map(|x| x.to_string()),
146            interfaces,
147            class.access_flags,
148            methods,
149            fields,
150            constant_values,
151        ))
152    }
153
154    pub fn fields(&self) -> &[FieldImpl] {
155        &self.inner.fields
156    }
157
158    pub(crate) fn instance_layout(&self) -> InstanceLayout {
159        self.inner.instance_layout.read().clone()
160    }
161}
162
163#[async_trait::async_trait]
164impl ClassDefinition for ClassDefinitionImpl {
165    fn name(&self) -> Cow<'_, str> {
166        (&self.inner.name).into()
167    }
168
169    fn super_class_name(&self) -> Option<String> {
170        self.inner.super_class_name.as_ref().map(|x| x.to_string())
171    }
172
173    fn interface_names(&self) -> Vec<String> {
174        self.inner.interfaces.clone()
175    }
176
177    fn access_flags(&self) -> ClassAccessFlags {
178        self.inner.access_flags
179    }
180
181    async fn instantiate(&self, _: &Jvm) -> Result<Box<dyn ClassInstance>> {
182        Ok(Box::new(ClassInstanceImpl::new(self)))
183    }
184
185    async fn prepare(&self, jvm: &Jvm) -> Result<()> {
186        let mut fields = Vec::new();
187        let mut class = Some(Box::new(self.clone()) as Box<dyn ClassDefinition>);
188        while let Some(x) = class {
189            // fields of other ClassDefinition implementations cannot be stored in a ClassInstanceImpl
190            fields.extend(
191                x.fields()
192                    .iter()
193                    .filter(|field| !field.access_flags().contains(FieldAccessFlags::STATIC))
194                    .filter_map(|field| field.as_any().downcast_ref::<FieldImpl>().cloned()),
195            );
196            class = x.super_class_name().map(|name| jvm.get_class(&name).unwrap().definition);
197        }
198        let defaults = fields
199            .iter()
200            .map(|field| JavaValue::default_of(&JavaType::parse(&field.descriptor())))
201            .collect();
202
203        *self.inner.instance_layout.write() = (fields.into(), defaults);
204
205        for (field, constant) in &self.inner.constant_values {
206            let value = match constant {
207                ConstantPoolReference::Integer(x) => match field.descriptor().as_ref() {
208                    "Z" => JavaValue::Boolean(*x != 0),
209                    "B" => JavaValue::Byte(*x as i8),
210                    "C" => JavaValue::Char(*x as u16),
211                    "S" => JavaValue::Short(*x as i16),
212                    _ => JavaValue::Int(*x),
213                },
214                ConstantPoolReference::Long(x) => JavaValue::Long(*x),
215                ConstantPoolReference::Float(x) => JavaValue::Float(*x),
216                ConstantPoolReference::Double(x) => JavaValue::Double(*x),
217                ConstantPoolReference::String(x) => JavaValue::Object(Some(jvm.intern_string(x).await?)),
218                _ => continue,
219            };
220
221            let slot = self.inner.fields.iter().position(|x| x == field).unwrap();
222            self.inner.storage.write()[slot] = value;
223        }
224
225        Ok(())
226    }
227
228    fn method(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Method>> {
229        self.inner
230            .methods
231            .iter()
232            .find(|&method| {
233                method.name() == name && method.descriptor() == descriptor && method.access_flags().contains(MethodAccessFlags::STATIC) == is_static
234            })
235            .map(|x| Box::new(x.clone()) as Box<dyn Method>)
236    }
237
238    fn field(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Field>> {
239        self.inner
240            .fields
241            .iter()
242            .find(|&field| {
243                field.name() == name && field.descriptor() == descriptor && field.access_flags().contains(FieldAccessFlags::STATIC) == is_static
244            })
245            .map(|x| Box::new(x.clone()) as Box<dyn Field>)
246    }
247
248    fn fields(&self) -> Vec<Box<dyn Field>> {
249        self.inner.fields.iter().map(|x| Box::new(x.clone()) as Box<dyn Field>).collect()
250    }
251
252    fn get_static_field(&self, field: &dyn Field) -> Result<JavaValue> {
253        let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();
254
255        let slot = self.inner.fields.iter().position(|x| x == field).unwrap();
256
257        Ok(self.inner.storage.read()[slot].clone())
258    }
259
260    fn put_static_field(&mut self, field: &dyn Field, value: JavaValue) -> Result<()> {
261        let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();
262
263        let slot = self.inner.fields.iter().position(|x| x == field).unwrap();
264        self.inner.storage.write()[slot] = value;
265
266        Ok(())
267    }
268}
269
270impl Debug for ClassDefinitionImpl {
271    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
272        write!(f, "Class({})", self.name())
273    }
274}