1use super::*;
8use crate::os_lib::ecma::bigint::BigInt;
9
10#[derive(Clone, Copy)]
11enum AtomicOp {
12 Add,
13 And,
14 Exchange,
15 Or,
16 Sub,
17 Xor,
18}
19
20fn validate_integer_ta(
24 it: &mut Interp,
25 val: &Value,
26 waitable: bool,
27 require_shared: bool,
28) -> Result<(ByteStore, bool), Value> {
29 let Value::Object(o) = val else {
30 return Err(it.type_error("Atomics argument must be an integer TypedArray"));
31 };
32 let (store, is_ta, buf_val) = {
33 let b = o.borrow();
34 let st = match &b.kind {
35 ObjKind::Bytes(st) => Some(st.clone()),
36 _ => None,
37 };
38 (st, b.props.contains_key("_ta_kind"), b.props.get("_ta_buf").cloned())
39 };
40 let Some(st) = store else {
41 return Err(it.type_error("Atomics argument must be an integer TypedArray"));
42 };
43 if !is_ta {
44 return Err(it.type_error("Atomics argument must be an integer TypedArray"));
45 }
46 let rk = st.raw_kind();
47 let ok_kind = if waitable {
48 matches!(rk, 5 | 10)
49 } else {
50 matches!(rk, 0 | 1 | 3 | 4 | 5 | 6 | 10 | 11)
51 };
52 if !ok_kind {
53 return Err(it.type_error("Invalid TypedArray type for Atomics operation"));
54 }
55 let is_shared = match &buf_val {
56 Some(Value::Object(bo)) => {
57 if is_detached_buffer(bo) {
58 return Err(it.type_error("TypedArray buffer is detached"));
59 }
60 is_shared_ab(bo)
61 }
62 _ => false,
63 };
64 if require_shared && !is_shared {
65 return Err(it.type_error("Atomics.wait requires a SharedArrayBuffer"));
66 }
67 Ok((*st, is_shared))
68}
69
70fn validate_atomic_access(it: &mut Interp, st: &ByteStore, idx_val: &Value) -> Result<usize, Value> {
72 let len = st.effective_len();
73 let idx = to_index_raw(it, idx_val)?;
74 if idx >= len {
75 return Err(it.range_error("Atomics index out of range"));
76 }
77 Ok(idx)
78}
79
80fn to_integer_or_infinity_f64(it: &mut Interp, v: &Value) -> Result<f64, Value> {
82 let n = it.num_of(v)?;
83 if n.is_nan() || n == 0.0 {
84 Ok(0.0)
85 } else if n.is_infinite() {
86 Ok(n)
87 } else {
88 Ok(libm::trunc(n))
89 }
90}
91
92fn to_bigint_val(it: &mut Interp, v: &Value) -> Result<BigInt, Value> {
94 let pv = if matches!(v, Value::Object(_)) {
95 it.to_primitive(v.clone(), "number")?
96 } else {
97 v.clone()
98 };
99 match &pv {
100 Value::BigInt(b) => Ok((**b).clone()),
101 Value::Bool(true) => Ok(BigInt::from_i64(1)),
102 Value::Bool(false) => Ok(BigInt::zero()),
103 Value::Str(s) => {
104 if s.len() > 8 && s.starts_with("Symbol(") && s.ends_with(')') {
105 return Err(it.type_error("Cannot convert a Symbol value to a BigInt"));
106 }
107 BigInt::parse_str(s).ok_or_else(|| it.syntax_error("Cannot convert string to a BigInt"))
108 }
109 _ => Err(it.type_error("Cannot convert value to a BigInt")),
110 }
111}
112
113fn read_u64_elem(st: &ByteStore, idx: usize) -> u64 {
114 let es = st.elem_size();
115 let at = st.off + idx * es;
116 let b = st.buf.borrow();
117 let Some(s) = b.get(at..at + es) else {
118 return 0;
119 };
120 match st.raw_kind() {
121 0 | 1 => s[0] as u64,
122 3 | 4 => u16::from_le_bytes([s[0], s[1]]) as u64,
123 5 | 6 => u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as u64,
124 10 | 11 => u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]),
125 _ => 0,
126 }
127}
128
129fn write_u64_elem(st: &ByteStore, idx: usize, val: u64) {
130 let es = st.elem_size();
131 let at = st.off + idx * es;
132 let mut b = st.buf.borrow_mut();
133 let Some(s) = b.get_mut(at..at + es) else {
134 return;
135 };
136 match st.raw_kind() {
137 0 | 1 => s[0] = (val & 0xFF) as u8,
138 3 | 4 => s.copy_from_slice(&(val as u16).to_le_bytes()),
139 5 | 6 => s.copy_from_slice(&(val as u32).to_le_bytes()),
140 10 | 11 => s.copy_from_slice(&val.to_le_bytes()),
141 _ => {}
142 }
143}
144
145fn elem_bits_to_value(kind: u8, bits: u64) -> Value {
146 match kind {
147 0 => Value::Number((bits as u8) as f64),
148 1 => Value::Number((bits as u8 as i8) as f64),
149 3 => Value::Number((bits as u16 as i16) as f64),
150 4 => Value::Number((bits as u16) as f64),
151 5 => Value::Number((bits as u32 as i32) as f64),
152 6 => Value::Number((bits as u32) as f64),
153 10 => Value::bigint(BigInt::from_i64(bits as i64)),
154 11 => Value::bigint(BigInt::from_u64(bits)),
155 _ => Value::Undefined,
156 }
157}
158
159fn coerce_atomic_arg(it: &mut Interp, kind: u8, v: &Value) -> Result<(u64, Value), Value> {
160 if ByteStore::is_bigint_kind(kind) {
161 let bi = to_bigint_val(it, v)?;
162 let u = bi.to_u64_truncated();
163 Ok((u, Value::bigint(bi)))
164 } else {
165 let int = to_integer_or_infinity_f64(it, v)?;
166 let bits = if int.is_finite() {
167 crate::os_lib::ecma::value::wrap_f64_to_u64(int)
168 } else {
169 0
170 };
171 Ok((bits, Value::Number(int)))
172 }
173}
174
175fn apply_rmw(old: u64, arg: u64, op: AtomicOp) -> u64 {
176 match op {
177 AtomicOp::Add => old.wrapping_add(arg),
178 AtomicOp::And => old & arg,
179 AtomicOp::Exchange => arg,
180 AtomicOp::Or => old | arg,
181 AtomicOp::Sub => old.wrapping_sub(arg),
182 AtomicOp::Xor => old ^ arg,
183 }
184}
185
186fn atomics_rmw(it: &mut Interp, a: &[Value], op: AtomicOp) -> Result<Value, Value> {
187 let (st, _) = validate_integer_ta(it, &arg(a, 0), false, false)?;
188 let idx = validate_atomic_access(it, &st, &arg(a, 1))?;
189 let rk = st.raw_kind();
190 let (arg_bits, _) = coerce_atomic_arg(it, rk, &arg(a, 2))?;
191 let old = read_u64_elem(&st, idx);
192 let new = apply_rmw(old, arg_bits, op);
193 write_u64_elem(&st, idx, new);
194 Ok(elem_bits_to_value(rk, old))
195}
196
197pub(crate) fn atomics_add(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
198 atomics_rmw(it, a, AtomicOp::Add)
199}
200
201pub(crate) fn atomics_and(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
202 atomics_rmw(it, a, AtomicOp::And)
203}
204
205pub(crate) fn atomics_exchange(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
206 atomics_rmw(it, a, AtomicOp::Exchange)
207}
208
209pub(crate) fn atomics_or(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
210 atomics_rmw(it, a, AtomicOp::Or)
211}
212
213pub(crate) fn atomics_sub(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
214 atomics_rmw(it, a, AtomicOp::Sub)
215}
216
217pub(crate) fn atomics_xor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
218 atomics_rmw(it, a, AtomicOp::Xor)
219}
220
221pub(crate) fn atomics_compare_exchange(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
222 let (st, _) = validate_integer_ta(it, &arg(a, 0), false, false)?;
223 let idx = validate_atomic_access(it, &st, &arg(a, 1))?;
224 let rk = st.raw_kind();
225 let (expected_bits, _) = coerce_atomic_arg(it, rk, &arg(a, 2))?;
226 let (replacement_bits, _) = coerce_atomic_arg(it, rk, &arg(a, 3))?;
227 let old = read_u64_elem(&st, idx);
228 let mask = match rk {
229 0 | 1 => 0xFFu64,
230 3 | 4 => 0xFFFFu64,
231 5 | 6 => 0xFFFF_FFFFu64,
232 _ => u64::MAX,
233 };
234 if (old & mask) == (expected_bits & mask) {
235 write_u64_elem(&st, idx, replacement_bits);
236 }
237 Ok(elem_bits_to_value(rk, old))
238}
239
240pub(crate) fn atomics_load(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
241 let (st, _) = validate_integer_ta(it, &arg(a, 0), false, false)?;
242 let idx = validate_atomic_access(it, &st, &arg(a, 1))?;
243 let old = read_u64_elem(&st, idx);
244 Ok(elem_bits_to_value(st.raw_kind(), old))
245}
246
247pub(crate) fn atomics_store(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
248 let (st, _) = validate_integer_ta(it, &arg(a, 0), false, false)?;
249 let idx = validate_atomic_access(it, &st, &arg(a, 1))?;
250 let (bits, ret_val) = coerce_atomic_arg(it, st.raw_kind(), &arg(a, 2))?;
251 write_u64_elem(&st, idx, bits);
252 Ok(ret_val)
253}
254
255pub(crate) fn atomics_is_lock_free(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
256 let n = to_integer_or_infinity_f64(it, &arg(a, 0))?;
257 Ok(Value::Bool(n == 1.0 || n == 2.0 || n == 4.0 || n == 8.0))
258}
259
260pub(crate) fn atomics_wait(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
262 let (st, _) = validate_integer_ta(it, &arg(a, 0), true, true)?;
263 let idx = validate_atomic_access(it, &st, &arg(a, 1))?;
264 let rk = st.raw_kind();
265 let (expected_bits, _) = coerce_atomic_arg(it, rk, &arg(a, 2))?;
266 let t_arg = arg(a, 3);
267 if !matches!(t_arg, Value::Undefined) {
268 let _ = it.num_of(&t_arg)?;
269 }
270 let current = read_u64_elem(&st, idx);
271 let mask = if rk == 5 { 0xFFFF_FFFFu64 } else { u64::MAX };
272 if (current & mask) != (expected_bits & mask) {
273 Ok(Value::str("not-equal"))
274 } else {
275 Ok(Value::str("timed-out"))
276 }
277}
278
279pub(crate) fn atomics_notify(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
281 let (st, _) = validate_integer_ta(it, &arg(a, 0), true, false)?;
282 let _idx = validate_atomic_access(it, &st, &arg(a, 1))?;
283 let count_arg = arg(a, 2);
284 if !matches!(count_arg, Value::Undefined) {
285 let _ = to_integer_or_infinity_f64(it, &count_arg)?;
286 }
287 Ok(Value::Number(0.0))
288}
289
290pub(crate) fn atomics_pause(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
292 let v = arg(a, 0);
293 if !matches!(v, Value::Undefined) {
294 let ok = matches!(v, Value::Number(n) if n.is_finite() && libm::trunc(n) == n);
295 if !ok {
296 return Err(it.type_error("Atomics.pause iterationNumber must be an integral number"));
297 }
298 }
299 Ok(Value::Undefined)
300}