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.fields.into_iter().map(FieldImpl::from_field_proto).collect::<Vec<_>>();
87
88 let interfaces = proto.interfaces.into_iter().map(|x| x.to_string()).collect();
89
90 Self::new(
91 proto.name,
92 proto.parent_class.map(|x| x.to_string()),
93 interfaces,
94 proto.access_flags,
95 methods,
96 fields,
97 )
98 }
99
100 pub fn from_classfile(data: &[u8]) -> core::result::Result<Self, ClassDefinitionError> {
101 let class = ClassInfo::parse(data)?;
102 verifier::verify(&class)?;
103
104 let mut constant_values = Vec::new();
105 let fields = class
106 .fields
107 .into_iter()
108 .map(|field_info| {
109 let constant = field_info.attributes.iter().find_map(|x| match x {
110 AttributeInfo::ConstantValue(value) => Some(value.clone()),
111 _ => None,
112 });
113
114 let field = FieldImpl::from_field_info(field_info);
115 if let Some(x) = constant
116 && field.access_flags().contains(FieldAccessFlags::STATIC)
117 {
118 constant_values.push((field.clone(), x));
119 }
120
121 field
122 })
123 .collect::<Vec<_>>();
124
125 let methods = class.methods.into_iter().map(MethodImpl::from_method_info).collect::<Vec<_>>();
126
127 let interfaces = class.interfaces.into_iter().map(|x| x.to_string()).collect();
128
129 Ok(Self::with_constant_values(
130 &class.this_class,
131 class.super_class.map(|x| x.to_string()),
132 interfaces,
133 class.access_flags,
134 methods,
135 fields,
136 constant_values,
137 ))
138 }
139
140 pub fn fields(&self) -> &[FieldImpl] {
141 &self.inner.fields
142 }
143}
144
145#[async_trait::async_trait]
146impl ClassDefinition for ClassDefinitionImpl {
147 fn name(&self) -> Cow<'_, str> {
148 (&self.inner.name).into()
149 }
150
151 fn super_class_name(&self) -> Option<String> {
152 self.inner.super_class_name.as_ref().map(|x| x.to_string())
153 }
154
155 fn interface_names(&self) -> Vec<String> {
156 self.inner.interfaces.clone()
157 }
158
159 fn access_flags(&self) -> ClassAccessFlags {
160 self.inner.access_flags
161 }
162
163 async fn instantiate(&self, _: &Jvm) -> Result<Box<dyn ClassInstance>> {
164 Ok(Box::new(ClassInstanceImpl::new(self)))
165 }
166
167 async fn prepare(&self, jvm: &Jvm) -> Result<()> {
168 for (field, constant) in &self.inner.constant_values {
169 let value = match constant {
170 ConstantPoolReference::Integer(x) => match field.descriptor().as_ref() {
171 "Z" => JavaValue::Boolean(*x != 0),
172 "B" => JavaValue::Byte(*x as i8),
173 "C" => JavaValue::Char(*x as u16),
174 "S" => JavaValue::Short(*x as i16),
175 _ => JavaValue::Int(*x),
176 },
177 ConstantPoolReference::Long(x) => JavaValue::Long(*x),
178 ConstantPoolReference::Float(x) => JavaValue::Float(*x),
179 ConstantPoolReference::Double(x) => JavaValue::Double(*x),
180 ConstantPoolReference::String(x) => JavaValue::Object(Some(jvm.intern_string(x).await?)),
181 _ => continue,
182 };
183
184 self.inner.storage.write().insert(field.clone(), value);
185 }
186
187 Ok(())
188 }
189
190 fn method(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Method>> {
191 self.inner
192 .methods
193 .iter()
194 .find(|&method| {
195 method.name() == name && method.descriptor() == descriptor && method.access_flags().contains(MethodAccessFlags::STATIC) == is_static
196 })
197 .map(|x| Box::new(x.clone()) as Box<dyn Method>)
198 }
199
200 fn field(&self, name: &str, descriptor: &str, is_static: bool) -> Option<Box<dyn Field>> {
201 self.inner
202 .fields
203 .iter()
204 .find(|&field| {
205 field.name() == name && field.descriptor() == descriptor && field.access_flags().contains(FieldAccessFlags::STATIC) == is_static
206 })
207 .map(|x| Box::new(x.clone()) as Box<dyn Field>)
208 }
209
210 fn fields(&self) -> Vec<Box<dyn Field>> {
211 self.inner.fields.iter().map(|x| Box::new(x.clone()) as Box<dyn Field>).collect()
212 }
213
214 fn get_static_field(&self, field: &dyn Field) -> Result<JavaValue> {
215 let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();
216
217 let storage = self.inner.storage.read();
218 let value = storage.get(field);
219
220 if let Some(x) = value {
221 Ok(x.clone())
222 } else {
223 Ok(JavaType::parse(&field.descriptor()).default())
224 }
225 }
226
227 fn put_static_field(&mut self, field: &dyn Field, value: JavaValue) -> Result<()> {
228 let field = field.as_any().downcast_ref::<FieldImpl>().unwrap();
229
230 self.inner.storage.write().insert(field.clone(), value);
231
232 Ok(())
233 }
234}
235
236impl Debug for ClassDefinitionImpl {
237 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
238 write!(f, "Class({})", self.name())
239 }
240}