Skip to main content

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