1use alloc::vec;
2
3use jvm::{ClassInstanceRef, Jvm, Result};
4use jvm_class_proto::{JavaFieldProto, JavaMethodProto};
5use jvm_types::{ClassAccessFlags, FieldAccessFlags, MethodAccessFlags};
6
7use crate::{
8 RuntimeClassProto, RuntimeContext,
9 classes::java::util::{Date, TimerTask, TimerTaskQueue, TimerThread},
10};
11
12pub struct Timer;
14
15impl Timer {
16 pub fn as_proto() -> RuntimeClassProto {
17 RuntimeClassProto {
18 name: "java/util/Timer",
19 parent_class: Some("java/lang/Object"),
20 interfaces: vec![],
21 methods: vec![
22 JavaMethodProto::new("<init>", "()V", Self::init, MethodAccessFlags::PUBLIC),
23 JavaMethodProto::new("schedule", "(Ljava/util/TimerTask;J)V", Self::schedule_once, MethodAccessFlags::PUBLIC),
24 JavaMethodProto::new(
25 "schedule",
26 "(Ljava/util/TimerTask;Ljava/util/Date;)V",
27 Self::schedule_date,
28 MethodAccessFlags::PUBLIC,
29 ),
30 JavaMethodProto::new(
31 "schedule",
32 "(Ljava/util/TimerTask;JJ)V",
33 Self::schedule_repeated,
34 MethodAccessFlags::PUBLIC,
35 ),
36 JavaMethodProto::new(
37 "schedule",
38 "(Ljava/util/TimerTask;Ljava/util/Date;J)V",
39 Self::schedule_date_repeated,
40 MethodAccessFlags::PUBLIC,
41 ),
42 JavaMethodProto::new(
43 "scheduleAtFixedRate",
44 "(Ljava/util/TimerTask;JJ)V",
45 Self::schedule_at_fixed_rate,
46 MethodAccessFlags::PUBLIC,
47 ),
48 JavaMethodProto::new("cancel", "()V", Self::cancel, MethodAccessFlags::PUBLIC),
49 ],
50 fields: vec![JavaFieldProto::new(
51 "thread",
52 "Ljava/util/Timer$TimerThread;",
53 FieldAccessFlags::PRIVATE | FieldAccessFlags::FINAL,
54 )],
55 access_flags: ClassAccessFlags::PUBLIC,
56 }
57 }
58
59 async fn init(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>) -> Result<()> {
60 tracing::debug!("java.util.Timer::<init>({this:?})");
61
62 let _: () = jvm.invoke_special(&this, "java/lang/Object", "<init>", "()V", ()).await?;
63 let queue = jvm.new_class("java/util/Timer$TaskQueue", "()V", ()).await?;
64 let timer_thread = jvm
65 .new_class("java/util/Timer$TimerThread", "(Ljava/util/Timer$TaskQueue;)V", (queue,))
66 .await?;
67 jvm.put_field(
68 &mut this,
69 "java/util/Timer",
70 "thread",
71 "Ljava/util/Timer$TimerThread;",
72 timer_thread.clone(),
73 )
74 .await?;
75 let _: () = jvm
76 .invoke_virtual(&timer_thread, "java/util/Timer$TimerThread", "start", "()V", ())
77 .await?;
78 Ok(())
79 }
80
81 async fn schedule_once(
82 jvm: &Jvm,
83 context: &mut RuntimeContext,
84 this: ClassInstanceRef<Self>,
85 task: ClassInstanceRef<TimerTask>,
86 delay: i64,
87 ) -> Result<()> {
88 tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {delay:?})");
89
90 if task.is_null() {
91 return Err(jvm.exception("java/lang/NullPointerException", "task").await);
92 }
93 if delay < 0 {
94 return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
95 }
96 let Some(time) = (context.now() as i64).checked_add(delay) else {
97 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
98 };
99 if time < 0 {
100 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
101 }
102 Self::sched(jvm, this, task, time, 0).await
103 }
104
105 async fn schedule_date(
106 jvm: &Jvm,
107 _: &mut RuntimeContext,
108 this: ClassInstanceRef<Self>,
109 task: ClassInstanceRef<TimerTask>,
110 date: ClassInstanceRef<Date>,
111 ) -> Result<()> {
112 tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {date:?})");
113
114 if task.is_null() {
115 return Err(jvm.exception("java/lang/NullPointerException", "task").await);
116 }
117 if date.is_null() {
118 return Err(jvm.exception("java/lang/NullPointerException", "time").await);
119 }
120 let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
121 if time < 0 {
122 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
123 }
124 Self::sched(jvm, this, task, time, 0).await
125 }
126
127 async fn schedule_repeated(
128 jvm: &Jvm,
129 context: &mut RuntimeContext,
130 this: ClassInstanceRef<Self>,
131 task: ClassInstanceRef<TimerTask>,
132 delay: i64,
133 period: i64,
134 ) -> Result<()> {
135 tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {delay:?}, {period:?})");
136
137 if task.is_null() {
138 return Err(jvm.exception("java/lang/NullPointerException", "task").await);
139 }
140 if delay < 0 {
141 return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
142 }
143 if period <= 0 {
144 return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
145 }
146 let Some(time) = (context.now() as i64).checked_add(delay) else {
147 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
148 };
149 if time < 0 {
150 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
151 }
152 Self::sched(jvm, this, task, time, -period).await
153 }
154
155 async fn schedule_date_repeated(
156 jvm: &Jvm,
157 _: &mut RuntimeContext,
158 this: ClassInstanceRef<Self>,
159 task: ClassInstanceRef<TimerTask>,
160 date: ClassInstanceRef<Date>,
161 period: i64,
162 ) -> Result<()> {
163 tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {date:?}, {period:?})");
164
165 if task.is_null() {
166 return Err(jvm.exception("java/lang/NullPointerException", "task").await);
167 }
168 if date.is_null() {
169 return Err(jvm.exception("java/lang/NullPointerException", "time").await);
170 }
171 if period <= 0 {
172 return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
173 }
174 let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
175 if time < 0 {
176 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
177 }
178 Self::sched(jvm, this, task, time, -period).await
179 }
180
181 async fn schedule_at_fixed_rate(
182 jvm: &Jvm,
183 context: &mut RuntimeContext,
184 this: ClassInstanceRef<Self>,
185 task: ClassInstanceRef<TimerTask>,
186 delay: i64,
187 period: i64,
188 ) -> Result<()> {
189 tracing::debug!("java.util.Timer::scheduleAtFixedRate({this:?}, {task:?}, {delay:?}, {period:?})");
190
191 if task.is_null() {
192 return Err(jvm.exception("java/lang/NullPointerException", "task").await);
193 }
194 if delay < 0 {
195 return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
196 }
197 if period <= 0 {
198 return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
199 }
200 let Some(time) = (context.now() as i64).checked_add(delay) else {
201 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
202 };
203 if time < 0 {
204 return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
205 }
206 Self::sched(jvm, this, task, time, period).await
207 }
208
209 async fn sched(jvm: &Jvm, this: ClassInstanceRef<Self>, mut task: ClassInstanceRef<TimerTask>, time: i64, period: i64) -> Result<()> {
210 let period = if !(-(i64::MAX >> 1)..=(i64::MAX >> 1)).contains(&period) {
211 period >> 1
212 } else {
213 period
214 };
215 if period != 0 {
216 let period_magnitude = if period < 0 {
217 let Some(period_magnitude) = period.checked_neg() else {
218 return Err(jvm.exception("java/lang/IllegalArgumentException", "period overflow").await);
219 };
220 period_magnitude
221 } else {
222 period
223 };
224 if time.checked_add(period_magnitude).is_none() {
225 return Err(jvm.exception("java/lang/IllegalArgumentException", "period overflow").await);
226 }
227 }
228
229 let thread: ClassInstanceRef<TimerThread> = jvm.get_field(&this, "java/util/Timer", "thread", "Ljava/util/Timer$TimerThread;").await?;
230 let mut queue: ClassInstanceRef<TimerTaskQueue> = jvm
231 .get_field(&thread, "java/util/Timer$TimerThread", "queue", "Ljava/util/Timer$TaskQueue;")
232 .await?;
233 let lock: ClassInstanceRef<crate::classes::java::lang::Object> =
234 jvm.get_field(&task, "java/util/TimerTask", "lock", "Ljava/lang/Object;").await?;
235
236 jvm.monitor_enter(&queue).await?;
237 let schedule_result = async {
238 if !jvm
239 .get_field::<bool>(&thread, "java/util/Timer$TimerThread", "newTasksMayBeScheduled", "Z")
240 .await?
241 {
242 return Err(jvm.exception("java/lang/IllegalStateException", "timer already cancelled").await);
243 }
244
245 jvm.monitor_enter(&lock).await?;
246 let task_result = async {
247 if jvm.get_field::<i32>(&task, "java/util/TimerTask", "state", "I").await? != TimerTask::VIRGIN {
248 return Err(jvm
249 .exception("java/lang/IllegalStateException", "task already scheduled or cancelled")
250 .await);
251 }
252 jvm.put_field(&mut task, "java/util/TimerTask", "nextExecutionTime", "J", time).await?;
253 jvm.put_field(&mut task, "java/util/TimerTask", "period", "J", period).await?;
254 jvm.put_field(&mut task, "java/util/TimerTask", "state", "I", TimerTask::SCHEDULED)
255 .await?;
256 TimerTaskQueue::add(jvm, &mut queue, task.clone()).await
257 }
258 .await;
259 let task_exit_result = jvm.monitor_exit(&lock).await;
260 let new_first = match task_result {
261 Ok(new_first) => {
262 task_exit_result?;
263 new_first
264 }
265 Err(error) => {
266 task_exit_result?;
267 return Err(error);
268 }
269 };
270 if new_first {
271 jvm.object_notify(&queue, 1).await?;
272 }
273 Ok(())
274 }
275 .await;
276 let queue_exit_result = jvm.monitor_exit(&queue).await;
277 match schedule_result {
278 Ok(()) => queue_exit_result,
279 Err(error) => {
280 queue_exit_result?;
281 Err(error)
282 }
283 }
284 }
285
286 async fn cancel(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
287 tracing::debug!("java.util.Timer::cancel({this:?})");
288
289 let mut thread: ClassInstanceRef<TimerThread> = jvm.get_field(&this, "java/util/Timer", "thread", "Ljava/util/Timer$TimerThread;").await?;
290 let mut queue: ClassInstanceRef<TimerTaskQueue> = jvm
291 .get_field(&thread, "java/util/Timer$TimerThread", "queue", "Ljava/util/Timer$TaskQueue;")
292 .await?;
293 jvm.monitor_enter(&queue).await?;
294 let cancel_result = async {
295 jvm.put_field(&mut thread, "java/util/Timer$TimerThread", "newTasksMayBeScheduled", "Z", false)
296 .await?;
297 TimerTaskQueue::clear(jvm, &mut queue).await?;
298 jvm.object_notify(&queue, usize::MAX).await
299 }
300 .await;
301 let exit_result = jvm.monitor_exit(&queue).await;
302 match cancel_result {
303 Ok(()) => exit_result,
304 Err(error) => {
305 exit_result?;
306 Err(error)
307 }
308 }
309 }
310}