Skip to main content

jvm_bytecode/
method.rs

1use alloc::{
2    boxed::Box,
3    string::{String, ToString},
4    sync::Arc,
5    vec::Vec,
6};
7use core::{
8    fmt::{self, Debug, Formatter},
9    ops::{Deref, DerefMut},
10};
11
12use classfile::{AttributeInfo, AttributeInfoCode, MethodInfo};
13use jvm::{JavaError, JavaType, JavaValue, Jvm, JvmCallback, Method, Result};
14use jvm_class_proto::JavaMethodProto;
15use jvm_types::MethodAccessFlags;
16
17use crate::interpreter::Interpreter;
18
19pub enum MethodBody {
20    ByteCode(AttributeInfoCode),
21    Rust(Box<dyn JvmCallback>),
22}
23
24impl MethodBody {
25    pub fn from_rust(callback: Box<dyn JvmCallback>) -> Self {
26        Self::Rust(callback)
27    }
28}
29
30impl Debug for MethodBody {
31    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32        match self {
33            MethodBody::ByteCode(_) => write!(f, "ByteCode"),
34            MethodBody::Rust(_) => write!(f, "Rust"),
35        }
36    }
37}
38
39#[derive(Debug)]
40struct MethodInner {
41    name: String,
42    descriptor: String,
43    body: Option<MethodBody>,
44    access_flags: MethodAccessFlags,
45}
46
47#[derive(Clone, Debug)]
48pub struct MethodImpl {
49    inner: Arc<MethodInner>,
50}
51
52impl MethodImpl {
53    pub fn new(name: &str, descriptor: &str, body: MethodBody, access_flags: MethodAccessFlags) -> Self {
54        Self {
55            inner: Arc::new(MethodInner {
56                name: name.to_string(),
57                descriptor: descriptor.to_string(),
58                body: Some(body),
59                access_flags,
60            }),
61        }
62    }
63
64    pub fn from_method_proto<C, Context>(proto: JavaMethodProto<C>, context: Context) -> Self
65    where
66        C: ?Sized + 'static + Send,
67        Context: Sync + Send + DerefMut + Deref<Target = C> + Clone + 'static,
68    {
69        struct MethodProxy<C, Context>
70        where
71            C: ?Sized,
72            Context: Sync + Send + DerefMut + Deref<Target = C> + Clone,
73        {
74            body: Box<dyn jvm_class_proto::MethodBody<JavaError, C>>,
75            context: Context,
76        }
77
78        #[async_trait::async_trait]
79        impl<C, Context> JvmCallback for MethodProxy<C, Context>
80        where
81            C: ?Sized + Send,
82            Context: Sync + Send + DerefMut + Deref<Target = C> + Clone,
83        {
84            async fn call(&self, jvm: &Jvm, args: Box<[JavaValue]>) -> Result<JavaValue> {
85                let mut context = self.context.clone();
86
87                self.body.call(jvm, &mut context, args).await
88            }
89        }
90
91        Self::new(
92            &proto.name,
93            &proto.descriptor,
94            MethodBody::Rust(Box::new(MethodProxy { body: proto.body, context })),
95            proto.access_flags,
96        )
97    }
98
99    pub fn from_method_info(method_info: MethodInfo) -> Self {
100        Self {
101            inner: Arc::new(MethodInner {
102                name: method_info.name.to_string(),
103                descriptor: method_info.descriptor.to_string(),
104                body: Self::extract_body(method_info.attributes).map(MethodBody::ByteCode),
105                access_flags: method_info.access_flags,
106            }),
107        }
108    }
109
110    fn extract_body(attributes: Vec<AttributeInfo>) -> Option<AttributeInfoCode> {
111        for attribute in attributes {
112            if let AttributeInfo::Code(x) = attribute {
113                return Some(x);
114            }
115        }
116
117        None
118    }
119}
120
121#[async_trait::async_trait]
122impl Method for MethodImpl {
123    fn name(&self) -> String {
124        self.inner.name.clone()
125    }
126
127    fn descriptor(&self) -> String {
128        self.inner.descriptor.clone()
129    }
130
131    fn access_flags(&self) -> MethodAccessFlags {
132        self.inner.access_flags
133    }
134
135    async fn run(&self, jvm: &Jvm, args: Box<[JavaValue]>) -> Result<JavaValue> {
136        let Some(body) = self.inner.body.as_ref() else {
137            if self.inner.access_flags.contains(MethodAccessFlags::NATIVE) {
138                return Err(jvm.exception("java/lang/UnsatisfiedLinkError", &self.inner.name).await);
139            }
140            return Err(jvm.exception("java/lang/AbstractMethodError", &self.inner.name).await);
141        };
142
143        Ok(match body {
144            MethodBody::ByteCode(x) => {
145                let r#type = JavaType::parse(&self.inner.descriptor);
146                Interpreter::run(jvm, x, args, r#type.as_method().1).await?
147            }
148            MethodBody::Rust(x) => x.call(jvm, args).await?,
149        })
150    }
151}