| @@ -0,0 +1,372 @@ |
| 1 | +//! Handing a value to another actor: move, share or copy (ADR 0002, |
| 2 | +//! Revision 1). |
| 3 | +//! |
| 4 | +//! Each actor's counts are non-atomic, so a message must not leave any |
| 5 | +//! block reachable from two actors with a local count. [`transfer`] walks |
| 6 | +//! the message once, iteratively, and decides per block: |
| 7 | +//! |
| 8 | +//! | Block | What happens | |
| 9 | +//! |---|---| |
| 10 | +//! | immortal (rc 0) or already shared (rc < 0) | kept: the reference changes owner | |
| 11 | +//! | unique (rc 1) | **moved**: kept, and its fields are walked | |
| 12 | +//! | also reachable from the sender (rc > 1), small | **copied**, with a forwarding table so sharing inside the message is kept | |
| 13 | +//! | also reachable from the sender, large | **promoted** with everything it reaches: negative (atomic) counts | |
| 14 | +//! |
| 15 | +//! A `Ref`, a region, a handler frame or a pinned (not `thread_safe`) |
| 16 | +//! resource cannot be sent. The walk then stops with an error, leaving a |
| 17 | +//! well-formed value for the caller to drop; the sender crashes. |
| 18 | +//! |
| 19 | +//! Every step keeps the value well formed and the counts exact: the leak |
| 20 | +//! oracle reads 0 whatever the walk decides. |
| 21 | + |
| 22 | +use std::collections::HashMap; |
| 23 | +use std::ffi::CStr; |
| 24 | + |
| 25 | +use crate::abi::{ |
| 26 | + Block, Ctx, FLAG_PINNED, TAG_BYTES, TAG_FRAME, TAG_REF, TAG_REGION, TAG_RESOURCE, TAG_STRING, |
| 27 | + Value, is_ptr, |
| 28 | +}; |
| 29 | +use crate::heap::{block_size, drop_value, dup_value, scanned_fields}; |
| 30 | + |
| 31 | +/// A shared subgraph of more blocks than this is promoted, not copied. |
| 32 | +const COPY_MAX_BLOCKS: usize = 64; |
| 33 | +/// A shared string or byte string longer than this is promoted, not copied |
| 34 | +/// (Erlang's off-heap binaries). |
| 35 | +const COPY_MAX_BYTES: usize = 4096; |
| 36 | + |
| 37 | +/// Why a value cannot be sent. |
| 38 | +#[derive(Debug, PartialEq, Eq)] |
| 39 | +pub(crate) struct NotSendable(pub &'static CStr); |
| 40 | + |
| 41 | +/// Make `v` (owned by the running actor) safe to own by another actor. |
| 42 | +/// Returns the value to hand over, which may differ from `v` when the |
| 43 | +/// outermost block is copied. |
| 44 | +/// |
| 45 | +/// # Safety |
| 46 | +/// `ctx` must be the running actor's context and `v` an owned value. On |
| 47 | +/// error, the returned value is still owned by the caller. |
| 48 | +pub(crate) unsafe fn transfer(ctx: *mut Ctx, v: Value) -> Result<Value, (NotSendable, Value)> { |
| 49 | + let mut root = v; |
| 50 | + let mut walk = Walk { |
| 51 | + ctx, |
| 52 | + slots: vec![&raw mut root], |
| 53 | + copies: HashMap::new(), |
| 54 | + dead: Vec::new(), |
| 55 | + }; |
| 56 | + // SAFETY: forwarded caller guarantee; every slot pushed is a field of |
| 57 | + // a block this walk owns (or `root`). |
| 58 | + let result = unsafe { walk.run() }; |
| 59 | + for v in walk.dead { |
| 60 | + // SAFETY: the walk held these last references. |
| 61 | + unsafe { drop_value(ctx, v) }; |
| 62 | + } |
| 63 | + match result { |
| 64 | + Ok(()) => Ok(root), |
| 65 | + Err(e) => Err((e, root)), |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +struct Walk { |
| 70 | + ctx: *mut Ctx, |
| 71 | + /// Fields still to visit. Each holds one owned reference. |
| 72 | + slots: Vec<*mut Value>, |
| 73 | + /// Shared blocks already copied, and their copies. |
| 74 | + copies: HashMap<*mut Block, *mut Block>, |
| 75 | + /// Originals whose last reference the walk replaced by their copy. |
| 76 | + dead: Vec<Value>, |
| 77 | +} |
| 78 | + |
| 79 | +impl Walk { |
| 80 | + /// # Safety |
| 81 | + /// See [`transfer`]. |
| 82 | + unsafe fn run(&mut self) -> Result<(), NotSendable> { |
| 83 | + while let Some(slot) = self.slots.pop() { |
| 84 | + // SAFETY: slots point at live fields owned by the walk. |
| 85 | + unsafe { |
| 86 | + let v = *slot; |
| 87 | + if !is_ptr(v) { |
| 88 | + continue; |
| 89 | + } |
| 90 | + let b = v as *mut Block; |
| 91 | + check_sendable(b)?; |
| 92 | + // Reached again after being copied: share the copy. |
| 93 | + if let Some(©) = self.copies.get(&b) { |
| 94 | + (*copy).header.rc += 1; |
| 95 | + *slot = copy as Value; |
| 96 | + if (*b).header.rc == 1 { |
| 97 | + // The last reference: the original dies after the |
| 98 | + // walk, so no address in `copies` is reused. |
| 99 | + self.dead.push(v); |
| 100 | + } else { |
| 101 | + (*b).header.rc -= 1; |
| 102 | + } |
| 103 | + continue; |
| 104 | + } |
| 105 | + let rc = (*b).header.rc; |
| 106 | + if rc <= 0 { |
| 107 | + continue; // immortal, or shared with all it reaches |
| 108 | + } |
| 109 | + if rc == 1 { |
| 110 | + self.push_fields(b); // moved |
| 111 | + continue; |
| 112 | + } |
| 113 | + if is_large(b) { |
| 114 | + promote(b)?; |
| 115 | + } else { |
| 116 | + let copy = self.copy(b); |
| 117 | + *slot = copy as Value; |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + Ok(()) |
| 122 | + } |
| 123 | + |
| 124 | + /// # Safety |
| 125 | + /// `b` must be live and owned by the walk. |
| 126 | + unsafe fn push_fields(&mut self, b: *mut Block) { |
| 127 | + // SAFETY: forwarded caller guarantee. |
| 128 | + let (fields, n) = unsafe { scanned_fields(b) }; |
| 129 | + for i in 0..n { |
| 130 | + // SAFETY: `i` is within the scanned fields. |
| 131 | + self.slots.push(unsafe { fields.add(i) }); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + /// Copy `b` (rc > 1), giving up one of the walk's references to it. |
| 136 | + /// The copy's fields are new references to `b`'s children, walked in |
| 137 | + /// turn (they are shared with `b`, so they are copied as well). |
| 138 | + /// |
| 139 | + /// # Safety |
| 140 | + /// `b` must be live, with rc > 1, and not a resource. |
| 141 | + unsafe fn copy(&mut self, b: *mut Block) -> *mut Block { |
| 142 | + // SAFETY: forwarded caller guarantee; the copy has `b`'s layout. |
| 143 | + unsafe { |
| 144 | + let size = block_size(b); |
| 145 | + let copy = crate::heap::alloc_bytes(self.ctx, size); |
| 146 | + std::ptr::copy_nonoverlapping(b.cast::<u8>(), copy.cast::<u8>(), size); |
| 147 | + (*copy).header.rc = 1; |
| 148 | + let (fields, n) = scanned_fields(copy); |
| 149 | + for i in 0..n { |
| 150 | + dup_value(*fields.add(i)); |
| 151 | + } |
| 152 | + (*b).header.rc -= 1; |
| 153 | + self.copies.insert(b, copy); |
| 154 | + self.push_fields(copy); |
| 155 | + copy |
| 156 | + } |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +/// # Safety |
| 161 | +/// `b` must be live. |
| 162 | +unsafe fn check_sendable(b: *mut Block) -> Result<(), NotSendable> { |
| 163 | + // SAFETY: caller guarantees `b` is live. |
| 164 | + let header = unsafe { &(*b).header }; |
| 165 | + match header.tag { |
| 166 | + TAG_REF => Err(NotSendable(c"cannot send a mutable reference")), |
| 167 | + TAG_REGION | TAG_FRAME => Err(NotSendable(c"cannot send a region or a handler")), |
| 168 | + TAG_RESOURCE if header.flags & FLAG_PINNED != 0 => Err(NotSendable( |
| 169 | + c"cannot send a resource that is not thread_safe", |
| 170 | + )), |
| 171 | + _ => Ok(()), |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +/// Whether the subgraph from `b` is too large to copy. Resources are |
| 176 | +/// never copied (their finalizer would run twice). |
| 177 | +/// |
| 178 | +/// # Safety |
| 179 | +/// `b` must be live. |
| 180 | +unsafe fn is_large(b: *mut Block) -> bool { |
| 181 | + let mut seen = 0; |
| 182 | + let mut todo = vec![b]; |
| 183 | + while let Some(b) = todo.pop() { |
| 184 | + // SAFETY: blocks reachable from a live block are live. |
| 185 | + unsafe { |
| 186 | + let tag = (*b).header.tag; |
| 187 | + if tag == TAG_RESOURCE { |
| 188 | + return true; |
| 189 | + } |
| 190 | + if (tag == TAG_STRING || tag == TAG_BYTES) && block_size(b) > COPY_MAX_BYTES { |
| 191 | + return true; |
| 192 | + } |
| 193 | + seen += 1; |
| 194 | + if seen > COPY_MAX_BLOCKS { |
| 195 | + return true; |
| 196 | + } |
| 197 | + let (fields, n) = scanned_fields(b); |
| 198 | + for i in 0..n { |
| 199 | + let v = *fields.add(i); |
| 200 | + if is_ptr(v) && (*(v as *mut Block)).header.rc > 0 { |
| 201 | + todo.push(v as *mut Block); |
| 202 | + } |
| 203 | + } |
| 204 | + } |
| 205 | + } |
| 206 | + false |
| 207 | +} |
| 208 | + |
| 209 | +/// Make `b` and every block it reaches shared: their counts become |
| 210 | +/// negative and are updated atomically from now on. The counts themselves |
| 211 | +/// are unchanged, so every existing reference stays valid. |
| 212 | +/// |
| 213 | +/// Invariant: a shared block only reaches shared or immortal blocks, so |
| 214 | +/// the walk stops at them. Nothing changes unless the whole subgraph can |
| 215 | +/// be sent. Runs before the message is published, so plain writes are |
| 216 | +/// enough. |
| 217 | +/// |
| 218 | +/// # Safety |
| 219 | +/// `b` must be live and owned by the running actor. |
| 220 | +unsafe fn promote(b: *mut Block) -> Result<(), NotSendable> { |
| 221 | + let mut local = vec![b]; |
| 222 | + let mut seen = std::collections::HashSet::from([b]); |
| 223 | + let mut i = 0; |
| 224 | + while i < local.len() { |
| 225 | + let b = local[i]; |
| 226 | + i += 1; |
| 227 | + // SAFETY: blocks reachable from a live block are live. |
| 228 | + unsafe { |
| 229 | + check_sendable(b)?; |
| 230 | + let (fields, n) = scanned_fields(b); |
| 231 | + for j in 0..n { |
| 232 | + let v = *fields.add(j); |
| 233 | + if is_ptr(v) { |
| 234 | + let child = v as *mut Block; |
| 235 | + if (*child).header.rc > 0 && seen.insert(child) { |
| 236 | + local.push(child); |
| 237 | + } |
| 238 | + } |
| 239 | + } |
| 240 | + } |
| 241 | + } |
| 242 | + for b in local { |
| 243 | + // SAFETY: as above. |
| 244 | + unsafe { (*b).header.rc = -(*b).header.rc }; |
| 245 | + } |
| 246 | + Ok(()) |
| 247 | +} |
| 248 | + |
| 249 | +#[cfg(test)] |
| 250 | +mod tests { |
| 251 | + use super::*; |
| 252 | + use crate::abi::{UNIT, int}; |
| 253 | + use crate::heap::tl_alloc; |
| 254 | + |
| 255 | + /// A constructor cell with `fields` (owned). |
| 256 | + fn cell(ctx: *mut Ctx, fields: &[Value]) -> Value { |
| 257 | + let b = tl_alloc(ctx, 0, fields.len() as u8, 0); |
| 258 | + // SAFETY: a fresh block with `fields.len()` fields. |
| 259 | + unsafe { |
| 260 | + for (i, f) in fields.iter().enumerate() { |
| 261 | + Block::fields_ptr(b).add(i).write(*f); |
| 262 | + } |
| 263 | + } |
| 264 | + b as Value |
| 265 | + } |
| 266 | + |
| 267 | + fn rc(v: Value) -> i32 { |
| 268 | + // SAFETY: tests only pass live blocks. |
| 269 | + unsafe { (*(v as *mut Block)).header.rc } |
| 270 | + } |
| 271 | + |
| 272 | + fn field(v: Value, i: usize) -> Value { |
| 273 | + // SAFETY: tests only pass live blocks with at least `i + 1` fields. |
| 274 | + unsafe { *Block::fields_ptr(v as *mut Block).add(i) } |
| 275 | + } |
| 276 | + |
| 277 | + fn sent(ctx: *mut Ctx, v: Value) -> Value { |
| 278 | + // SAFETY: `ctx` is the root actor's; `v` is owned. |
| 279 | + unsafe { transfer(ctx, v) }.expect("sendable") |
| 280 | + } |
| 281 | + |
| 282 | + fn drop(ctx: *mut Ctx, v: Value) { |
| 283 | + // SAFETY: `v` is owned. |
| 284 | + unsafe { drop_value(ctx, v) } |
| 285 | + } |
| 286 | + |
| 287 | + /// The scenarios run as one root actor, so `drop_value` has a context. |
| 288 | + unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value { |
| 289 | + // A unique message is moved as is. |
| 290 | + let leaf = cell(ctx, &[int(1)]); |
| 291 | + let unique = cell(ctx, &[leaf, int(2)]); |
| 292 | + assert_eq!(sent(ctx, unique), unique); |
| 293 | + assert_eq!(field(unique, 0), leaf); |
| 294 | + drop(ctx, unique); |
| 295 | + |
| 296 | + // A part the sender keeps is copied; the rest is moved. |
| 297 | + let kept = cell(ctx, &[int(1)]); |
| 298 | + // SAFETY: `kept` is live. |
| 299 | + unsafe { crate::heap::dup_value(kept) }; |
| 300 | + let message = cell(ctx, &[kept, int(2)]); |
| 301 | + let received = sent(ctx, message); |
| 302 | + assert_eq!(received, message); |
| 303 | + let copy = field(received, 0); |
| 304 | + assert_ne!(copy, kept); |
| 305 | + assert_eq!((rc(kept), rc(copy)), (1, 1)); |
| 306 | + drop(ctx, received); |
| 307 | + drop(ctx, kept); |
| 308 | + |
| 309 | + // Sharing inside the message survives the copy: (x, x). |
| 310 | + let x = cell(ctx, &[int(7)]); |
| 311 | + // SAFETY: `x` is live. |
| 312 | + unsafe { crate::heap::dup_value(x) }; |
| 313 | + // SAFETY: `x` is live. |
| 314 | + unsafe { crate::heap::dup_value(x) }; |
| 315 | + let pair = cell(ctx, &[x, x]); // x: rc 3 (sender + both fields) |
| 316 | + let received = sent(ctx, pair); |
| 317 | + let (a, b) = (field(received, 0), field(received, 1)); |
| 318 | + assert_eq!(a, b); |
| 319 | + assert_ne!(a, x); |
| 320 | + assert_eq!((rc(a), rc(x)), (2, 1)); |
| 321 | + drop(ctx, received); |
| 322 | + drop(ctx, x); |
| 323 | + |
| 324 | + // An original reached only through the message, twice, is |
| 325 | + // replaced by one copy and freed: (y, y) where the sender keeps |
| 326 | + // nothing but the pair is itself shared. |
| 327 | + let y = cell(ctx, &[int(8)]); |
| 328 | + // SAFETY: `y` is live. |
| 329 | + unsafe { crate::heap::dup_value(y) }; |
| 330 | + let shared_pair = cell(ctx, &[y, y]); |
| 331 | + // SAFETY: `shared_pair` is live. |
| 332 | + unsafe { crate::heap::dup_value(shared_pair) }; |
| 333 | + let received = sent(ctx, shared_pair); |
| 334 | + assert_ne!(received, shared_pair); |
| 335 | + assert_eq!(field(received, 0), field(received, 1)); |
| 336 | + drop(ctx, received); |
| 337 | + drop(ctx, shared_pair); |
| 338 | + |
| 339 | + // A large shared list is promoted, not copied. |
| 340 | + let mut list = int(0); |
| 341 | + for i in 0..(COPY_MAX_BLOCKS as i64 + 10) { |
| 342 | + list = cell(ctx, &[int(i), list]); |
| 343 | + } |
| 344 | + // SAFETY: `list` is live. |
| 345 | + unsafe { crate::heap::dup_value(list) }; |
| 346 | + let received = sent(ctx, list); |
| 347 | + assert_eq!(received, list); |
| 348 | + assert_eq!(rc(list), -2); |
| 349 | + assert_eq!(rc(field(field(list, 1), 1)), -1); |
| 350 | + drop(ctx, received); |
| 351 | + drop(ctx, list); |
| 352 | + |
| 353 | + // A mutable reference cannot be sent, even inside a closure's |
| 354 | + // environment; nothing is promoted when it is found. |
| 355 | + let r = tl_alloc(ctx, TAG_REF, 1, 0) as Value; |
| 356 | + let message = cell(ctx, &[int(1), r]); |
| 357 | + // SAFETY: as above. |
| 358 | + let (NotSendable(reason), message) = unsafe { transfer(ctx, message) }.unwrap_err(); |
| 359 | + assert_eq!(reason, c"cannot send a mutable reference"); |
| 360 | + assert_eq!(rc(message), 1); |
| 361 | + drop(ctx, message); |
| 362 | + |
| 363 | + assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); |
| 364 | + UNIT |
| 365 | + } |
| 366 | + |
| 367 | + #[test] |
| 368 | + fn move_copy_and_promote() { |
| 369 | + // SAFETY: `scenarios` follows the generated-code convention. |
| 370 | + assert_eq!(unsafe { crate::sched::tl_main(scenarios) }, 0); |
| 371 | + } |
| 372 | +} |