1use alloc::{
2 boxed::Box,
3 collections::BTreeMap,
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, JavaType, JavaValue, Jvm, Method, Result};
17use jvm_class_proto::JavaClassProto;
18use jvm_types::{ClassAccessFlags, FieldAccessFlags, 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 storage: RwLock<BTreeMap<FieldImpl, JavaValue>>, }
32
33#[derive(Clone)]
34pub struct ClassDefinitionImpl {
35 inner: Arc<ClassDefinitionInner>,
36}
37
38impl ClassDefinitionImpl {
39 pub fn new(
40 name: &str,
41 super_class_name: Option<String>,
42 interfaces: Vec<String>,
43 access_flags: ClassAccessFlags,
44 methods: Vec<MethodImpl>,
45 fields: Vec<FieldImpl>,
46 ) -> Self {
47 Self::with_constant_values(name, super_class_name, interfaces, access_flags, methods, fields, Vec::new())
48 }
49
50 #[allow(clippy::too_many_arguments)]
51 fn with_constant_values(
52 name: &str,
53 super_class_name: Option<String>,
54 interfaces: Vec<String>,
55 access_flags: ClassAccessFlags,
56 methods: Vec<MethodImpl>,
57 fields: Vec<FieldImpl>,
58 constant_values: Vec<(FieldImpl, ConstantPoolReference)>,
59 ) -> Self {
60 Self {
61 inner: Arc::new(ClassDefinitionInner {
62 name: name.to_string(),
63 super_class_name,
64 interfaces,
65 access_flags,
66 methods,
67 fields,
68 constant_values,
69 storage: RwLock::new(BTreeMap::new()),
70 }),
71 }
72 }
73
74 pub fn from_class_proto<C, Context>(proto: JavaClassProto<C>, context: Context) -> Self
75 where
76 C: ?Sized + 'static + Send,
77 Context: Sync + Send + DerefMut + Deref<Target = C> + Clone + 'static,
78 {
79 let methods = proto
80 .methods
81 .into_iter()
82 .map(|x| MethodImpl::from_method_proto(x, context.clone()))
83 .collect::<Vec<_>>();
84
85 let fields = proto.fields.into_iter().map(FieldImpl::from_field_proto).collect::<Vec<_>>();
86
87 let interfaces = proto.interfaces.into_iter().map(|x| x.to_string()).collect();
88
89 Self::new(
90 proto.name,
91 proto.parent_class.map(|x| x.to_string()),
92 interfaces,
93 proto.access_flags,
94 methods,
95 fields,
96 )
97 }
98
99 pub fn from_classfile(data: &[u8]) -> core::result::Result<Self, ClassDefinitionError> {
100 let class = ClassInfo::parse(data)?;
101 verifier::verify(&class)?;
102
103 let mut constant_values = Vec::new();
104 let fields = class
105 .fields
106 .into_iter()
107 .map(|field_info| {
108 let constant = field_info.attributes.iter().find_map(|x| match x {
109 AttributeInfo::ConstantValue(value) => Some(value.clone()),
110 _ => None,
111 });
112
113 let field = FieldImpl::from_field_info(field_info);
114 if let Some(x) = constant
115 && field.access_flags().contains(FieldAccessFlags::STATIC)
116 {
117 constant_values.push((field.clone(), x));
118 }
119
120 field
121 })
122 .collect::<Vec<_>>();
123
124 let methods = class.methods.into_iter().map(MethodImpl::from_method_info).collect::<Vec<_>>();
125
126 let interfaces = class.interfaces.into_iter().map(|x| x.to_string()).collect();
127
128 Ok(Self::with_constant_values(
129 &class.this_class,
130 class.super_class.map(|x| x.to_string()),
131 interfaces,
132 class.access_flags,
133 methods,
134 fields,
135 constant_values,
136 ))
137 }
138
139 pub fn fields(&self) -> &[FieldImpl] {
140 &self.inner.fields
141 }
142}
143
144#[async_trait::async_trait]
145impl ClassDefinition for ClassDefinitionImpl {
146 fn name(&self) -> String {
147 self.inner.name.clone()
148 }
149
150 fn super_class_name(&self) -> Option<String> {
151 self.inner.super_class_name.as_ref().map(|x| x.to_string())
152 }
153
154 fn interface_names(&self) -> Vec<String> {
155 self.inner.interfaces.clone()
156 }
157
158 fn access_flags(&self) -> ClassAccessFlags {
159 self.inner.access_flags
160 }
161
162 async fn instantiate(&self, _: &Jvm) -> Result<Box<dyn ClassInstance>> {
163 Ok(Box::new(ClassInstanceImpl::new(self)))
164 }
165
166 async fn prepare(&self, jvm: &Jvm) -> Result<()> {
167 for (field, constant) in &self.inner.constant_values {
168 let value = match constant {
169 ConstantPoolReference::Integer(x) => match field.descriptor().as_str() {
170 "Z" => JavaValue::Boolean(*x != 0),
171 "B" => JavaValue::Byte(*x as i8),
172 "C" => JavaValue::Char(*x as u16),
173 "S" => JavaValue::Short(*x as i16),
174 _ => JavaValue::Int(*x),
175 },
176 ConstantPoolReference::Long(x) => JavaValue::Long(*x),
177 ConstantPoolReference::Float(x) => JavaValue::Float(*x),
178 ConstantPoolReference::Double(x) => JavaValue::Double(*x),
179 ConstantPoolReference::String(x) => JavaValue::Object(Some(jvm.intern_string(x).await?)),
180 _ => continue,
181 };
182
183 self.inner.storage.write().insert(field.clone(), value);
184 }
185
186 Ok(())
187 }
188
189 fn method(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Method>> {
190 self.inner
191 .methods
192 .iter()
193 .find(|&method| {
194 method.name() == name && method.descriptor() == descriptor && method.access_flags().contains(MethodAccessFlags::STATIC) == is_static
195 })
196 .map(|x| Box::new(x.clone()) as Box<dyn Method>)
197 }
198
199 fn field(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Field>> {
200 self.inner
201 .fields
202 .iter()
203 .find(|&field| {
204 field.name() == name && field.descriptor() == descriptor && field.access_flags().contains(FieldAccessFlags::STATIC) == is_static
205 })
206 .map(|x| Box::new(x.clone()) as Box<dyn Field>)
207 }
208
209 fn fields(&self) -> Vec<Box<dyn Field>> {
210 self.inner.fields.iter().map(|x| Box::new(x.clone()) as Box<dyn Field>).collect()
211 }
212
213 fn get_static_field(&self, field: &dyn Field) -> Result<JavaValue> {
214 let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();
215
216 let storage = self.inner.storage.read();
217 let value = storage.get(field);
218
219 if let Some(x) = value {
220 Ok(x.clone())
221 } else {
222 Ok(JavaType::parse(&field.descriptor()).default())
223 }
224 }
225
226 fn put_static_field(&mut self, field: &dyn Field, value: JavaValue) -> Result<()> {
227 let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();
228
229 self.inner.storage.write().insert(field.clone(), value);
230
231 Ok(())
232 }
233}
234
235impl Debug for ClassDefinitionImpl {
236 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
237 write!(f, "Class({})", self.name())
238 }
239}