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