tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

1081 lignes · 39732 octetsBrut · Historique
1//! The codec against `docs/wire-format.md`: round trips of every kind,
2//! sharing, pids and subjects across three simulated nodes, the worked
3//! example, the decoder's refusals, and random and mutated payloads.
4//!
5//! Values are built outside any actor (null context), as the transport
6//! does; each test that allocates holds the scheduler tests' turn, so the
7//! leak oracle's count is its own, and checks it is back where it started.
8
9use std::sync::RwLock;
10
11use num_bigint::BigInt;
12
13use super::*;
14use crate::abi::{Block, Value, int, int_get, is_ptr};
15use crate::dist::{Node, Nodes, remote};
16use crate::heap::{drop_detached, dup_value, stats};
17use crate::values::{bytes_from, bytes_of, cell, list, string};
18
19/// Every kind: a list, an option, `docs/wire-format.md`'s example, a
20/// regular recursive type through another, a snoc list (deep at its first
21/// field), an empty type, a binary DAG, and a record of every leaf.
22const TABLE: &str = concat!(
23 "Dstd/prelude.List;1CNil;CCons;F;$0F;Nstd/prelude.List;1$0",
24 "Dstd/prelude.Option;1CNone;CSome;F;$0",
25 "Ddemo.Task;1CDone;CStep;Fpayload;$0Freply;SiFnext;Ndemo.Task;1$0",
26 "Ddemo.Tree;1CLeaf;CNode;F;Nstd/prelude.List;1T2$0Ndemo.Tree;1$0",
27 "Ddemo.Snoc;0CEmpty;CSnoc;Finit;Ndemo.Snoc;0Flast;i",
28 "Ddemo.Never;0",
29 "Ddemo.Pair;0CEnd;CPair;Fleft;Ndemo.Pair;0Fright;Ndemo.Pair;0",
30 "Ddemo.All;0CAll;Fint;iFfloat;fFstring;sFbytes;bFu64;wFdec;dFpid;pFunit;u",
31 "Fsubject;SNdemo.All;0Farray;AiFpair;T2isFopt;Nstd/prelude.Option;1s",
32);
33
34fn null() -> *mut crate::abi::Ctx {
35 std::ptr::null_mut()
36}
37
38/// A simulated node: its name and incarnation, and its node table.
39struct Side {
40 me: Node,
41 nodes: RwLock<Nodes>,
42}
43
44fn side(name: &str, incarnation: u64) -> Side {
45 Side {
46 me: Node {
47 name: name.into(),
48 incarnation,
49 },
50 nodes: RwLock::default(),
51 }
52}
53
54impl Side {
55 /// The index of `other` in this node's table.
56 fn index_of(&self, other: &Side) -> u16 {
57 let mut nodes = self.nodes.write().unwrap();
58 nodes
59 .index(&other.me.name, other.me.incarnation)
60 .expect("room")
61 }
62}
63
64fn registry() -> Registry {
65 Registry::new(TABLE).expect("the test table")
66}
67
68/// Run `f` under the scheduler tests' turn; the live blocks after are as
69/// many as before.
70fn no_leak(f: impl FnOnce()) {
71 let _turn = crate::sched::test_turn();
72 let before = stats::tl_stats_live_blocks();
73 f();
74 assert_eq!(stats::tl_stats_live_blocks(), before, "live blocks");
75}
76
77fn enc(reg: &Registry, desc: &str, v: Value, on: &Side) -> Result<Vec<u8>, EncodeError> {
78 let wire = reg.register(desc).expect("registered").index;
79 // SAFETY: the tests pass live values of `desc`.
80 unsafe { encode(reg, wire, v, &on.me, &on.nodes) }
81}
82
83fn dec(reg: &Registry, desc: &str, payload: &[u8], on: &Side) -> Result<Value, DecodeError> {
84 let hash = reg.register(desc).expect("registered").hash;
85 decode(
86 reg,
87 hash,
88 payload,
89 &on.me,
90 &on.nodes,
91 &mut PEER_NODES.clone(),
92 None,
93 )
94}
95
96/// `v` (owned, released) sent from `from` to `to`: the payload and the
97/// value `to` decodes, owned.
98fn send(reg: &Registry, desc: &str, v: Value, from: &Side, to: &Side) -> (Vec<u8>, Value) {
99 let payload = enc(reg, desc, v, from).expect("encodes");
100 // SAFETY: owned.
101 unsafe { drop_detached(v) };
102 let got = dec(reg, desc, &payload, to).expect("decodes");
103 (payload, got)
104}
105
106/// `v` (owned, released) through the codec on one node: decoded, it
107/// encodes to the same bytes, sharing included.
108fn round_trip(reg: &Registry, desc: &str, v: Value) -> Vec<u8> {
109 let a = side("a.example", 1);
110 let (payload, got) = send(reg, desc, v, &a, &a);
111 assert_eq!(enc(reg, desc, got, &a).expect("encodes"), payload, "{desc}");
112 // SAFETY: owned.
113 unsafe { drop_detached(got) };
114 payload
115}
116
117/// Field `i` of a block (borrowed).
118fn field(v: Value, i: usize) -> Value {
119 assert!(is_ptr(v));
120 // SAFETY: the tests read fields their values have.
121 unsafe { *Block::fields_ptr(v as *mut Block).add(i) }
122}
123
124fn tag(v: Value) -> u16 {
125 // SAFETY: a live block.
126 unsafe { (*(v as *mut Block)).header.tag }
127}
128
129fn rc(v: Value) -> i32 {
130 // SAFETY: a live block.
131 unsafe { (*(v as *mut Block)).header.rc }
132}
133
134fn text(v: Value) -> String {
135 // SAFETY: a live string.
136 String::from_utf8(unsafe { bytes_of(v) }.to_vec()).unwrap()
137}
138
139fn big(n: &BigInt) -> Value {
140 crate::int::from_big(null(), n)
141}
142
143/// `docs/wire-format.md`'s worked example payload.
144fn example_payload() -> Vec<u8> {
145 let doc = include_str!("../../../../docs/wire-format.md");
146 let dump = doc
147 .split("```\nheader")
148 .nth(1)
149 .and_then(|rest| rest.split("```").next())
150 .expect("the example's dump");
151 let bytes: Vec<u8> = dump
152 .lines()
153 .flat_map(|line| {
154 line.split_whitespace()
155 .skip_while(|t| matches!(*t, "header" | "payload"))
156 .take_while(|t| t.len() == 2 && t.bytes().all(|b| b.is_ascii_hexdigit()))
157 .map(|t| u8::from_str_radix(t, 16).expect("hex"))
158 .collect::<Vec<_>>()
159 })
160 .collect();
161 bytes[louise_rt_prims::wire::HEADER_LEN..].to_vec()
162}
163
164// ---- the registry ----------------------------------------------------------------
165
166#[test]
167fn hashes_are_the_documents_and_subjects_register_their_messages() {
168 let reg = registry();
169 let int = reg.register("i").unwrap();
170 assert_eq!(int.hash, 0xa1f9_0d70_e682_6ce8);
171 assert_eq!(reg.register("i").unwrap(), int, "registered once");
172 let task = reg.register("Ndemo.Task;1s").unwrap();
173 assert_eq!(task.hash, 0x9949_47b8_73cb_1aa7);
174 assert_eq!(reg.by_hash(task.hash), Some(task.index));
175 assert_eq!(reg.hash(task.index), Some(task.hash));
176 // `Subject<Int>`'s messages, and a subject's own message type: known
177 // before any is encoded.
178 let all = reg.register("Ndemo.All;0").unwrap();
179 assert_eq!(reg.by_hash(all.hash), Some(all.index));
180 let hash = |d: &str| {
181 reg.table
182 .type_hash(&reg.table.parse_desc(d).unwrap())
183 .unwrap()
184 };
185 assert_eq!(reg.by_hash(hash("Ss")), None);
186 reg.register("SSs").unwrap();
187 assert!(reg.by_hash(hash("Ss")).is_some() && reg.by_hash(hash("s")).is_some());
188 assert_eq!(reg.hash(99), None);
189 assert!(matches!(
190 reg.register("Nnope;0"),
191 Err(RegisterError::Desc(_))
192 ));
193}
194
195#[test]
196fn nested_types_are_refused() {
197 let nest = "Ddemo.Nest;1CNil;CCons;F;$0F;Ndemo.Nest;1T2$0$0";
198 let err = Registry::new(nest).err().expect("refused");
199 assert_eq!(
200 err.what, "a recursive reference is not regular (a nested type)",
201 "{err:?}"
202 );
203 // The same definition, regular: accepted.
204 assert!(Registry::new("Ddemo.Nest;1CNil;CCons;F;$0F;Ndemo.Nest;1$0").is_ok());
205}
206
207#[test]
208fn collisions_are_refused_and_change_nothing() {
209 let mut reg = registry();
210 reg.hash = |_| 42;
211 let int = reg.register("i").unwrap();
212 assert_eq!(reg.register("i").unwrap(), int);
213 let before = reg.read().insts.len();
214 let err = reg.register("Ndemo.Task;1s").unwrap_err();
215 assert!(
216 matches!(&err, RegisterError::Collision { hash: 42, known, new }
217 if known == "i" && new == "Ndemo.Task;1s"),
218 "{err}"
219 );
220 assert_eq!(reg.read().insts.len(), before, "rolled back");
221 assert_eq!(reg.read().entries.len(), 1);
222 // Two new types in one registration collide with each other too.
223 reg.hash = |c| u64::from(c.windows(4).any(|w| w == b"List") || c.ends_with(b"\ns\n"));
224 let err = reg.register("Nstd/prelude.List;1Ss").unwrap_err();
225 assert!(
226 matches!(err, RegisterError::Collision { hash: 1, .. }),
227 "{err}"
228 );
229}
230
231#[test]
232fn the_registry_is_shared_between_threads() {
233 let reg = registry();
234 let a = side("a.example", 1);
235 let descs = ["i", "Ndemo.Task;1s", "Nstd/prelude.Option;1i", "T2ip", "Ai"];
236 let results: Vec<Vec<Registered>> = std::thread::scope(|s| {
237 let handles: Vec<_> = (0..4)
238 .map(|k| {
239 let (reg, a) = (&reg, &a);
240 s.spawn(move || {
241 descs
242 .iter()
243 .cycle()
244 .skip(k)
245 .take(50)
246 .map(|d| {
247 let r = reg.register(d).unwrap();
248 if *d == "i" {
249 // SAFETY: a small Int.
250 let p =
251 unsafe { encode(reg, r.index, int(k as i64), &a.me, &a.nodes) };
252 assert_eq!(p.unwrap().len(), 2);
253 }
254 r
255 })
256 .collect()
257 })
258 })
259 .collect();
260 handles.into_iter().map(|h| h.join().unwrap()).collect()
261 });
262 for d in descs {
263 let r = reg.register(d).unwrap();
264 assert!(
265 results
266 .iter()
267 .flatten()
268 .filter(|x| x.hash == r.hash)
269 .all(|x| *x == r)
270 );
271 }
272}
273
274// ---- round trips ----------------------------------------------------------------------
275
276#[test]
277fn the_worked_example_encodes_and_decodes() {
278 no_leak(|| {
279 let reg = registry();
280 let sender = side("a.example", 0x0123_4567_89AB_CDEF);
281 let receiver = side("b.example", 0xFEDC_BA98_7654_3210);
282 // Step("hi", r, Step("hi", r, Done)), the string and r shared.
283 let hi = string(null(), "hi");
284 let r = cell(null(), 0, &[int(7), int(3)]);
285 // SAFETY: live.
286 unsafe { (dup_value(hi), dup_value(r)) };
287 let inner = cell(null(), 1, &[hi, r, int(0)]);
288 let v = cell(null(), 1, &[hi, r, inner]);
289 let (payload, got) = send(&reg, "Ndemo.Task;1s", v, &sender, &receiver);
290 assert_eq!(payload, example_payload());
291 // Decoded on the receiver: the subject is `Remote`, its `wire` the
292 // registry index of its messages, and sharing is kept.
293 let r = field(got, 1);
294 assert_eq!((tag(got), tag(r)), (1, 1));
295 let a = receiver.index_of(&sender);
296 assert_eq!(int_get(field(r, 0)), remote(a, 7).unwrap());
297 assert_eq!(int_get(field(r, 1)), 3);
298 let ints = reg.register("i").unwrap().index;
299 assert_eq!(int_get(field(r, 2)), i64::from(ints));
300 let next = field(got, 2);
301 assert_eq!(text(field(got, 0)), "hi");
302 assert_eq!(field(next, 0), field(got, 0), "the string is shared");
303 assert_eq!(field(next, 1), r, "the subject is shared");
304 assert_eq!((rc(field(got, 0)), rc(r)), (2, 2));
305 assert_eq!(field(next, 2), int(0), "Done");
306 // SAFETY: owned.
307 unsafe { drop_detached(got) };
308 });
309}
310
311#[test]
312fn every_kind_round_trips() {
313 no_leak(|| {
314 let reg = registry();
315 let unicode = "héllo, wörld — ✓";
316 let all = |i: i64, s: &str| {
317 let subject = cell(null(), 0, &[int(4), int(5)]);
318 let array = {
319 let items: Vec<Value> = (0..3).map(int).collect();
320 let l = list(null(), items.into_iter());
321 // SAFETY: a live list, released after.
322 let a = unsafe { crate::array::tl_array_from_list(null(), l) };
323 // SAFETY: owned.
324 unsafe { drop_detached(l) };
325 a
326 };
327 let pair = cell(null(), 0, &[int(i), string(null(), s)]);
328 let opt = cell(null(), 1, &[string(null(), s)]);
329 cell(
330 null(),
331 0,
332 &[
333 int(i),
334 crate::prims::tl_float_from(null(), -0.5),
335 string(null(), s),
336 bytes_from(null(), &[0, 255, 7]),
337 crate::u64::u64_value(null(), u64::MAX),
338 crate::dec::dec_value(null(), i128::MIN),
339 int(12),
340 int(0),
341 subject,
342 array,
343 pair,
344 opt,
345 ],
346 )
347 };
348 round_trip(&reg, "Ndemo.All;0", all(-3, unicode));
349 round_trip(&reg, "Ndemo.All;0", all(1 << 40, ""));
350 // Leaves.
351 let a = side("a.example", 1);
352 for x in [
353 0.0,
354 -0.0,
355 f64::INFINITY,
356 f64::MIN_POSITIVE,
357 f64::from_bits(0x7ff8_dead_beef_0001),
358 ] {
359 let v = crate::prims::tl_float_from(null(), x);
360 let (p, got) = send(&reg, "f", v, &a, &a);
361 assert_eq!(p.len(), 9);
362 // SAFETY: a live Float.
363 let back = unsafe { crate::prims::tl_float_get(got) };
364 assert_eq!(back.to_bits(), x.to_bits());
365 // SAFETY: owned.
366 unsafe { drop_detached(got) };
367 }
368 for x in [0, 1, u64::MAX, 1 << 63] {
369 round_trip(&reg, "w", crate::u64::u64_value(null(), x));
370 }
371 for x in [0, -1, i128::MAX, i128::MIN, 10_i128.pow(18)] {
372 let p = round_trip(&reg, "d", crate::dec::dec_value(null(), x));
373 assert!(p.len() <= 1 + 19);
374 }
375 round_trip(&reg, "u", int(0));
376 assert_eq!(round_trip(&reg, "s", string(null(), "")), [0, 0]);
377 assert_eq!(round_trip(&reg, "b", bytes_from(null(), &[])), [0, 0]);
378 let large = "x".repeat(1 << 20);
379 // The node list, a head of 4 bytes (2^21), the bytes.
380 assert_eq!(
381 round_trip(&reg, "s", string(null(), &large)).len(),
382 1 + 4 + (1 << 20)
383 );
384 round_trip(&reg, "Nstd/prelude.Option;1i", int(0));
385 round_trip(&reg, "Nstd/prelude.Option;1i", cell(null(), 1, &[int(-9)]));
386 round_trip(
387 &reg,
388 "T2ib",
389 cell(null(), 0, &[int(2), bytes_from(null(), b"z")]),
390 );
391 // Arrays: empty, and of strings.
392 let empty = list(null(), std::iter::empty());
393 // SAFETY: a live list.
394 let a = unsafe { crate::array::tl_array_from_list(null(), empty) };
395 assert_eq!(round_trip(&reg, "As", a), [0, 0]);
396 let strings = list(null(), (0..1000).map(|i| string(null(), &i.to_string())));
397 // SAFETY: a live list, released after.
398 let a = unsafe { crate::array::tl_array_from_list(null(), strings) };
399 // SAFETY: owned.
400 unsafe { drop_detached(strings) };
401 round_trip(&reg, "As", a);
402 });
403}
404
405#[test]
406fn big_ints_round_trip_canonically() {
407 no_leak(|| {
408 let reg = registry();
409 let a = side("a.example", 1);
410 let two = BigInt::from(2);
411 let mut cases: Vec<BigInt> = Vec::new();
412 for e in [61u32, 62, 63, 64, 65, 124, 125, 126, 127, 128, 129, 1000] {
413 let p = two.pow(e);
414 for d in [-1, 0, 1].map(BigInt::from) {
415 let n: BigInt = &p + d;
416 cases.push(-&n);
417 cases.push(n);
418 }
419 }
420 cases.extend([0, 1, -1].map(BigInt::from));
421 for n in cases {
422 let v = big(&n);
423 let payload = enc(&reg, "i", v, &a).unwrap();
424 // SAFETY: owned.
425 unsafe { drop_detached(v) };
426 let got = dec(&reg, "i", &payload, &a).unwrap();
427 // SAFETY: a live Int.
428 assert_eq!(unsafe { crate::int::to_big(got) }, n);
429 let small = (-(BigInt::from(1) << 62u32)..(BigInt::from(1) << 62u32)).contains(&n);
430 assert_eq!(!is_ptr(got), small, "canonical: {n}");
431 // SAFETY: owned.
432 unsafe { drop_detached(got) };
433 }
434 // A shared big integer is written once.
435 let n = big(&two.pow(200));
436 // SAFETY: live.
437 unsafe { dup_value(n) };
438 let p = round_trip(&reg, "T2ii", cell(null(), 0, &[n, n]));
439 assert_eq!(p.last(), Some(&3), "a back-reference to node 1");
440 });
441}
442
443#[test]
444fn deep_lists_and_recursive_types_round_trip() {
445 no_leak(|| {
446 let reg = registry();
447 let ints = list(null(), (0..100_000).map(int));
448 let p = round_trip(&reg, "Nstd/prelude.List;1i", ints);
449 assert!(p.len() < 100_000 * 5);
450 let strings = list(
451 null(),
452 (0..100_000).map(|i| string(null(), &format!("{i}"))),
453 );
454 round_trip(&reg, "Nstd/prelude.List;1s", strings);
455 // Tree<Int>: Node([(1, Leaf), (2, Node([(3, Leaf)]))]).
456 let pair = |n, t| cell(null(), 0, &[int(n), t]);
457 let inner = cell(null(), 1, &[list(null(), [pair(3, int(0))].into_iter())]);
458 let tree = cell(
459 null(),
460 1,
461 &[list(null(), [pair(1, int(0)), pair(2, inner)].into_iter())],
462 );
463 round_trip(&reg, "Ndemo.Tree;1i", tree);
464 });
465}
466
467#[test]
468fn shared_dags_stay_linear() {
469 no_leak(|| {
470 let reg = registry();
471 // 64 levels of Pair(x, x): 2^64 paths, 64 nodes.
472 let mut v = int(0);
473 for _ in 0..64 {
474 // SAFETY: live.
475 unsafe { dup_value(v) };
476 v = cell(null(), 1, &[v, v]);
477 }
478 let a = side("a.example", 1);
479 let (p, got) = send(&reg, "Ndemo.Pair;0", v, &a, &a);
480 assert!(p.len() < 64 * 4, "{} bytes", p.len());
481 assert_eq!(field(got, 0), field(got, 1), "sharing is kept");
482 assert_eq!(enc(&reg, "Ndemo.Pair;0", got, &a).unwrap(), p);
483 // SAFETY: owned.
484 unsafe { drop_detached(got) };
485 // Reached twice at one type: a back-reference.
486 let one = cell(null(), 1, &[int(1)]);
487 // SAFETY: live.
488 unsafe { dup_value(one) };
489 let both = cell(null(), 0, &[one, one]);
490 let p = round_trip(&reg, "T2Nstd/prelude.Option;1iNstd/prelude.Option;1i", both);
491 assert_eq!(p.last(), Some(&3), "same type: a back-reference");
492 });
493}
494
495#[test]
496fn one_block_at_two_types_is_two_nodes() {
497 no_leak(|| {
498 // `(Some(1), Err(1))`: codegen interns constant blocks by content
499 // across types, so one block may stand at two types.
500 let table = format!("{TABLE}Ddemo.Res;0COk;F;iCErr;F;i");
501 let reg = Registry::new(&table).unwrap();
502 let one = cell(null(), 1, &[int(1)]);
503 // SAFETY: live.
504 unsafe { dup_value(one) };
505 let both = cell(null(), 0, &[one, one]);
506 let p = round_trip(&reg, "T2Nstd/prelude.Option;1iNdemo.Res;0", both);
507 // node 0 the tuple, node 1 Some(1), node 2 Err(1): no back-reference.
508 assert_eq!(p, [0, 0, 2, 4, 2, 4]);
509 });
510}
511
512// ---- pids and subjects ----------------------------------------------------------------
513
514#[test]
515fn pids_cross_nodes() {
516 no_leak(|| {
517 let reg = registry();
518 let (a, b, c) = (
519 side("a.example", 1),
520 side("b.example", 2),
521 side("c.example", 3),
522 );
523 let c_on_a = a.index_of(&c);
524 let b_on_a = a.index_of(&b);
525 let desc = "T3ppp";
526 // A's own pid 7, C's pid 9, B's pid 11, as A names them.
527 let v = cell(
528 null(),
529 0,
530 &[
531 int(7),
532 int(remote(c_on_a, 9).unwrap()),
533 int(remote(b_on_a, 11).unwrap()),
534 ],
535 );
536 let (payload, got) = send(&reg, desc, v, &a, &b);
537 assert_eq!(payload[0], 3, "three nodes listed");
538 let a_on_b = b.index_of(&a);
539 let c_on_b = b.index_of(&c);
540 assert_eq!(int_get(field(got, 0)), remote(a_on_b, 7).unwrap());
541 assert_eq!(int_get(field(got, 1)), remote(c_on_b, 9).unwrap());
542 assert_eq!(int_get(field(got, 2)), 11, "B's own pid is local on B");
543 // And back: A's pid is local again, C's the same remote pid.
544 let (_, back) = send(&reg, desc, got, &b, &a);
545 assert_eq!(int_get(field(back, 0)), 7);
546 assert_eq!(int_get(field(back, 1)), remote(c_on_a, 9).unwrap());
547 assert_eq!(int_get(field(back, 2)), remote(b_on_a, 11).unwrap());
548 // SAFETY: owned.
549 unsafe { drop_detached(back) };
550 // A local pid past 46 bits cannot be named elsewhere.
551 assert_eq!(
552 enc(&reg, "p", int(1 << 46), &a),
553 Err(EncodeError::PidSerial(1 << 46))
554 );
555 assert!(enc(&reg, "p", int((1 << 46) - 1), &a).is_ok());
556 });
557}
558
559#[test]
560fn subjects_cross_nodes() {
561 no_leak(|| {
562 let reg = registry();
563 let (a, b) = (side("a.example", 1), side("b.example", 2));
564 let strings = reg.register("s").unwrap().index;
565 // A local subject arrives as `Remote`, its `wire` the index of its
566 // messages' type.
567 let v = cell(null(), 0, &[int(5), int(9)]);
568 let (_, got) = send(&reg, "Ss", v, &a, &b);
569 assert_eq!(tag(got), 1);
570 let a_on_b = b.index_of(&a);
571 assert_eq!(int_get(field(got, 0)), remote(a_on_b, 5).unwrap());
572 assert_eq!(int_get(field(got, 1)), 9);
573 assert_eq!(int_get(field(got, 2)), i64::from(strings));
574 // Sent back to its owner, it is a `Subject` again.
575 let (_, back) = send(&reg, "Ss", got, &b, &a);
576 assert_eq!(tag(back), 0);
577 assert_eq!((int_get(field(back, 0)), int_get(field(back, 1))), (5, 9));
578 // SAFETY: owned.
579 unsafe { drop_detached(back) };
580 // Tags are non-negative small Ints below 2^62.
581 let bad = cell(null(), 0, &[int(5), int(-1)]);
582 assert_eq!(enc(&reg, "Ss", bad, &a), Err(EncodeError::Tag(-1)));
583 // SAFETY: owned.
584 unsafe { drop_detached(bad) };
585 });
586}
587
588/// A peer that names the node's spawner's subject in a payload, its own
589/// (reflected) or forged, would reach the dispatcher with a `Request` of
590/// its making (#404's security review, SEC-7): the decoder refuses it.
591#[test]
592fn no_payload_names_the_reserved_subject() {
593 no_leak(|| {
594 let reg = registry();
595 let (a, b) = (side("a.example", 1), side("b.example", 2));
596 // a's actor 5 receives requests on tag 9; b reflects that subject.
597 let v = cell(null(), 0, &[int(5), int(9)]);
598 let (_, on_b) = send(&reg, "Ss", v, &a, &b);
599 let payload = enc(&reg, "Ss", on_b, &b).unwrap();
600 // SAFETY: owned.
601 unsafe { drop_detached(on_b) };
602 let hash = reg.register("Ss").unwrap().hash;
603 let decode_on_a =
604 |reserved| decode(&reg, hash, &payload, &a.me, &a.nodes, &mut 0, reserved);
605 assert!(
606 matches!(decode_on_a(Some((5, 9))), Err(DecodeError::Malformed(e)) if e.what == "subject of the node's spawner")
607 );
608 // Another tag of the same actor, or no reservation, decodes.
609 for reserved in [Some((5, 8)), None] {
610 let got = decode_on_a(reserved).unwrap();
611 assert_eq!((int_get(field(got, 0)), int_get(field(got, 1))), (5, 9));
612 // SAFETY: owned.
613 unsafe { drop_detached(got) };
614 }
615 });
616}
617
618#[test]
619fn a_peer_adds_a_bounded_number_of_nodes() {
620 no_leak(|| {
621 let reg = registry();
622 let (a, b) = (side("a.example", 1), side("b.example", 2));
623 let others: Vec<Side> = (0..3).map(|i| side(&format!("n{i}.example"), 1)).collect();
624 let pids: Vec<Value> = others
625 .iter()
626 .map(|o| int(remote(a.index_of(o), 1).unwrap()))
627 .collect();
628 let v = cell(null(), 0, &pids);
629 let payload = enc(&reg, "T3ppp", v, &a).unwrap();
630 // SAFETY: owned.
631 unsafe { drop_detached(v) };
632 let hash = reg.register("T3ppp").unwrap().hash;
633 let mut left = 2;
634 let err = decode(&reg, hash, &payload, &b.me, &b.nodes, &mut left, None);
635 assert_eq!(err, Err(DecodeError::PeerNodes));
636 assert_eq!(left, 2);
637 assert!(b.nodes.read().unwrap().get(0).is_none(), "nothing added");
638 let mut left = 3;
639 let got = decode(&reg, hash, &payload, &b.me, &b.nodes, &mut left, None).unwrap();
640 assert_eq!(left, 0);
641 // SAFETY: owned.
642 unsafe { drop_detached(got) };
643 let got = decode(&reg, hash, &payload, &b.me, &b.nodes, &mut left, None).unwrap();
644 // SAFETY: owned.
645 unsafe { drop_detached(got) };
646 });
647}
648
649// ---- limits and refusals ----------------------------------------------------------------
650
651/// A snoc list of `n` cells, from the empty one: as deep as it is long.
652fn snoc(n: usize) -> Value {
653 (0..n).fold(int(0), |init, _| cell(null(), 1, &[init, int(0)]))
654}
655
656/// Its payload, written by hand.
657fn snoc_payload(n: usize) -> Vec<u8> {
658 let mut p = vec![0];
659 p.extend(std::iter::repeat_n(2, n));
660 p.push(0);
661 p.extend(std::iter::repeat_n(0, n));
662 p
663}
664
665#[test]
666fn depth_is_limited_both_ways() {
667 no_leak(|| {
668 let reg = registry();
669 let a = side("a.example", 1);
670 let max = MAX_VALUE_DEPTH as usize;
671 let v = snoc(max);
672 assert_eq!(enc(&reg, "Ndemo.Snoc;0", v, &a).unwrap(), snoc_payload(max));
673 // SAFETY: owned.
674 unsafe { drop_detached(v) };
675 let v = snoc(max + 1);
676 assert_eq!(enc(&reg, "Ndemo.Snoc;0", v, &a), Err(EncodeError::TooDeep));
677 // SAFETY: owned.
678 unsafe { drop_detached(v) };
679 let got = dec(&reg, "Ndemo.Snoc;0", &snoc_payload(max), &a).unwrap();
680 // SAFETY: owned.
681 unsafe { drop_detached(got) };
682 let err = dec(&reg, "Ndemo.Snoc;0", &snoc_payload(max + 1), &a);
683 assert!(
684 matches!(
685 err,
686 Err(DecodeError::Malformed(WireError {
687 what: "value nested too deeply",
688 ..
689 }))
690 ),
691 "{err:?}"
692 );
693 });
694}
695
696#[test]
697fn the_decoder_refuses_what_the_format_does() {
698 no_leak(|| {
699 let reg = registry();
700 let a = side("a.example", 1);
701 let refused = |desc: &str, payload: &[u8], why: &str| match dec(&reg, desc, payload, &a) {
702 Err(DecodeError::Malformed(e)) => assert_eq!(e.what, why, "{desc} {payload:?}"),
703 other => panic!("{desc} {payload:?}: {other:?}"),
704 };
705 refused("u", &[0, 1], "unit is not 00");
706 refused("u", &[0, 0, 0], "bytes left after the value");
707 refused("u", &[0], "payload ends early");
708 refused("i", &[0, 0x80, 0], "varint not in shortest form");
709 refused("s", &[0, 4, 0xff, 0xfe], "string not UTF-8");
710 refused("s", &[0, 8, b'a'], "length past the end of the payload");
711 refused("Ai", &[0, 8, 0], "count past the end of the payload");
712 refused(
713 "Nstd/prelude.Option;1i",
714 &[0, 4],
715 "constructor out of range",
716 );
717 refused("Ndemo.Never;0", &[0, 0], "constructor out of range");
718 refused("T2ii", &[0, 2, 0, 0], "tuple head not 0");
719 refused("T3iii", &[0, 0, 0], "fields past the end of the payload");
720 refused("Ss", &[0, 2, 0, 0, 0], "subject head not 0");
721 // A back-reference: forward, to an enclosing node, at another type.
722 refused(
723 "T2ss",
724 &[0, 0, 3, 0],
725 "back-reference to a node not read yet",
726 );
727 refused(
728 "Nstd/prelude.List;1i",
729 &[0, 2, 4, 1],
730 "back-reference to an enclosing node",
731 );
732 refused(
733 "T2sb",
734 &[0, 0, 4, b'h', b'i', 3],
735 "back-reference to a node of another type",
736 );
737 // Pids and the node list.
738 let mut entry = vec![1, 9];
739 entry.extend_from_slice(b"a.example");
740 entry.extend_from_slice(&5u64.to_le_bytes());
741 let with = |rest: &[u8]| [&entry[..], rest].concat();
742 refused("p", &with(&[1, 0]), "pid of no node list entry");
743 refused(
744 "p",
745 &[&with(&[0])[..], &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40]].concat(),
746 "pid serial out of range",
747 );
748 let mut two = entry.clone();
749 two[0] = 2;
750 two.extend_from_slice(&entry[1..]);
751 refused(
752 "p",
753 &[&two[..], &[0, 0]].concat(),
754 "node list entry repeated",
755 );
756 let mut upper = entry.clone();
757 upper[2] = b'A';
758 refused("p", &[&upper[..], &[0, 0]].concat(), "bad node name");
759 refused("p", &[3, 0], "count past the end of the payload");
760 let mut tag = with(&[0, 0, 0]);
761 tag.extend([0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40]);
762 refused("Ss", &tag, "subject tag out of range");
763 // A hash nobody registered.
764 assert_eq!(
765 decode(&reg, 7, &[0, 0], &a.me, &a.nodes, &mut 0, None),
766 Err(DecodeError::UnknownType(7))
767 );
768 });
769}
770
771#[test]
772fn a_node_is_complete_once_its_tail_is_read() {
773 no_leak(|| {
774 let reg = registry();
775 let a = side("a.example", 1);
776 // (Cons(Cons("a", Nil), Nil), _): node 0 the pair, 1 and 2 the
777 // cells, 3 the string. The outer cell's frame is popped at its tail.
778 let desc = "T2Nstd/prelude.List;1Nstd/prelude.List;1sNstd/prelude.List;1s";
779 let value = |second: u8| vec![0, 0, 2, 2, 2, b'a', 0, 0, second];
780 // The inner list (node 2) is complete: shared.
781 let got = dec(&reg, desc, &value(5), &a).unwrap();
782 assert_eq!(field(field(got, 0), 0), field(got, 1));
783 assert_eq!(rc(field(got, 1)), 2);
784 // SAFETY: owned.
785 unsafe { drop_detached(got) };
786 // The outer list is complete too, but of another type.
787 assert!(matches!(
788 dec(&reg, desc, &value(3), &a),
789 Err(DecodeError::Malformed(WireError {
790 what: "back-reference to a node of another type",
791 ..
792 }))
793 ));
794 // In the outer list's tail, the outer list is not complete.
795 let p = [0, 2, 2, 2, b'a', 0, 1];
796 let err = dec(&reg, "Nstd/prelude.List;1Nstd/prelude.List;1s", &p, &a);
797 assert!(matches!(
798 err,
799 Err(DecodeError::Malformed(WireError {
800 what: "back-reference to an enclosing node",
801 ..
802 }))
803 ));
804 });
805}
806
807#[test]
808fn encoding_checks_the_representation() {
809 no_leak(|| {
810 let reg = registry();
811 let a = side("a.example", 1);
812 let s = string(null(), "x");
813 let bad = [
814 ("i", s),
815 ("Nstd/prelude.Option;1i", int(1)),
816 ("Nstd/prelude.Option;1i", int(-1)),
817 ("T3iii", cell(null(), 0, &[int(1), int(2)])),
818 ("Nstd/prelude.Option;1i", cell(null(), 1, &[int(1), int(2)])),
819 ("Ss", cell(null(), 0, &[int(1), int(2), int(3)])),
820 ("p", s),
821 ];
822 for (desc, v) in bad {
823 assert!(
824 matches!(enc(&reg, desc, v, &a), Err(EncodeError::Malformed(_))),
825 "{desc}"
826 );
827 if v != s {
828 // SAFETY: owned.
829 unsafe { drop_detached(v) };
830 }
831 }
832 // SAFETY: owned.
833 unsafe { drop_detached(s) };
834 assert_eq!(
835 // SAFETY: a small Int.
836 unsafe { encode(&reg, 1000, int(0), &a.me, &a.nodes) },
837 Err(EncodeError::UnknownType(1000))
838 );
839 });
840}
841
842#[test]
843fn a_payload_over_the_limit_is_not_encoded() {
844 no_leak(|| {
845 let reg = registry();
846 let a = side("a.example", 1);
847 let len = MAX_PAYLOAD as usize - 5;
848 let (s, raw) = crate::values::string_uninit(null(), len);
849 // SAFETY: `raw` has room for `len` bytes.
850 unsafe { std::ptr::write_bytes(raw, b'x', len) };
851 // The node list's count, a head of 4 bytes, the bytes: at the limit.
852 assert_eq!(enc(&reg, "s", s, &a).map(|p| p.len()), Ok(1 + 4 + len));
853 // A byte more, in a pair: refused.
854 let pair = cell(null(), 0, &[s, bytes_from(null(), b"z")]);
855 assert_eq!(enc(&reg, "T2sb", pair, &a), Err(EncodeError::TooLarge));
856 // SAFETY: owned.
857 unsafe { drop_detached(pair) };
858 });
859}
860
861// ---- random and mutated payloads -------------------------------------------------------------
862
863/// xorshift64*: deterministic, so a failure reproduces.
864struct Rng(u64);
865
866impl Rng {
867 fn next(&mut self) -> u64 {
868 self.0 ^= self.0 >> 12;
869 self.0 ^= self.0 << 25;
870 self.0 ^= self.0 >> 27;
871 self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
872 }
873
874 fn below(&mut self, n: usize) -> usize {
875 (self.next() % n.max(1) as u64) as usize
876 }
877}
878
879fn mutate(rng: &mut Rng, p: &mut Vec<u8>) {
880 let at = rng.below(p.len() + 1);
881 let last = p.len().saturating_sub(1);
882 match rng.below(7) {
883 0 if !p.is_empty() => p[at.min(last)] ^= 1 << rng.below(8),
884 1 if !p.is_empty() => p[at.min(last)] = rng.next() as u8,
885 2 => p.insert(at, rng.next() as u8),
886 3 if at < p.len() => {
887 p.remove(at);
888 }
889 4 => p.truncate(at),
890 5 if !p.is_empty() => {
891 let from = rng.below(p.len());
892 let len = rng.below((p.len() - from).min(16)) + 1;
893 let chunk = p[from..from + len].to_vec();
894 p.splice(at..at, chunk);
895 }
896 _ => {
897 let len = rng.below(48);
898 *p = (0..len).map(|_| rng.next() as u8).collect();
899 }
900 }
901}
902
903#[test]
904fn random_and_mutated_payloads_are_refused_or_decoded_without_leaks() {
905 no_leak(|| {
906 let reg = registry();
907 let (a, b) = (side("a.example", 1), side("b.example", 2));
908 let c_on_a = a.index_of(&side("c.example", 3));
909 // Seeds: one valid payload of each kind.
910 let hi = string(null(), "hi");
911 let r = cell(null(), 0, &[int(7), int(3)]);
912 // SAFETY: live.
913 unsafe { (dup_value(hi), dup_value(r)) };
914 let task = cell(null(), 1, &[hi, r, cell(null(), 1, &[hi, r, int(0)])]);
915 let mut dag = int(0);
916 for _ in 0..8 {
917 // SAFETY: live.
918 unsafe { dup_value(dag) };
919 dag = cell(null(), 1, &[dag, dag]);
920 }
921 let all = cell(
922 null(),
923 0,
924 &[
925 big(&(BigInt::from(1) << 100u32)),
926 crate::prims::tl_float_from(null(), 1.5),
927 string(null(), "ü"),
928 bytes_from(null(), b"\x00\x01"),
929 crate::u64::u64_value(null(), 3),
930 crate::dec::dec_value(null(), -7),
931 int(remote(c_on_a, 4).unwrap()),
932 int(0),
933 cell(null(), 0, &[int(1), int(2)]),
934 {
935 let l = list(null(), (0..4).map(int));
936 // SAFETY: a live list, released after.
937 let arr = unsafe { crate::array::tl_array_from_list(null(), l) };
938 // SAFETY: owned.
939 unsafe { drop_detached(l) };
940 arr
941 },
942 cell(null(), 0, &[int(-1), string(null(), "t")]),
943 int(0),
944 ],
945 );
946 let seeds_values = [
947 ("Ndemo.Task;1s", task),
948 ("Ndemo.Pair;0", dag),
949 ("Ndemo.All;0", all),
950 ("Nstd/prelude.List;1i", list(null(), (0..20).map(int))),
951 ("Ndemo.Snoc;0", snoc(10)),
952 (
953 "Ndemo.Tree;1s",
954 cell(
955 null(),
956 1,
957 &[list(
958 null(),
959 [cell(null(), 0, &[string(null(), "x"), int(0)])].into_iter(),
960 )],
961 ),
962 ),
963 ("As", {
964 let l = list(null(), (0..5).map(|i| string(null(), &i.to_string())));
965 // SAFETY: a live list, released after.
966 let arr = unsafe { crate::array::tl_array_from_list(null(), l) };
967 // SAFETY: owned.
968 unsafe { drop_detached(l) };
969 arr
970 }),
971 ];
972 let mut seeds = Vec::new();
973 for (desc, v) in seeds_values {
974 seeds.push((
975 reg.register(desc).unwrap().hash,
976 enc(&reg, desc, v, &a).unwrap(),
977 ));
978 // SAFETY: owned.
979 unsafe { drop_detached(v) };
980 }
981 let hashes: Vec<u64> = seeds.iter().map(|s| s.0).collect();
982 let mut rng = Rng(0x5eed_1234_abcd_ef01);
983 let (mut decoded, mut cases) = (0, 0);
984 for _ in 0..40_000 {
985 let (mut hash, seed) = seeds[rng.below(seeds.len())].clone();
986 let mut p = seed.clone();
987 for _ in 0..=rng.below(3) {
988 mutate(&mut rng, &mut p);
989 }
990 if rng.below(8) == 0 {
991 hash = hashes[rng.below(hashes.len())];
992 }
993 let (live, allocs) = (stats::tl_stats_live_blocks(), stats::tl_stats_allocations());
994 let got = decode(
995 &reg,
996 hash,
997 &p,
998 &b.me,
999 &b.nodes,
1000 &mut PEER_NODES.clone(),
1001 None,
1002 );
1003 // Every block costs a byte of the payload at least.
1004 let made = stats::tl_stats_allocations() - allocs;
1005 assert!(
1006 made <= p.len() as i64,
1007 "{made} blocks from {} bytes",
1008 p.len()
1009 );
1010 if let Ok(v) = got {
1011 decoded += 1;
1012 // SAFETY: owned.
1013 unsafe { drop_detached(v) };
1014 }
1015 assert_eq!(stats::tl_stats_live_blocks(), live, "{p:?}");
1016 cases += 1;
1017 }
1018 // Some mutations keep a payload valid; most do not.
1019 assert!(
1020 decoded > 100 && decoded < cases / 2,
1021 "{decoded} of {cases} decoded"
1022 );
1023 });
1024}
1025
1026// ---- speed ----------------------------------------------------------------------------
1027
1028/// `cargo test -p louise_rt --release wire::tests::speed -- --ignored --nocapture`
1029#[test]
1030#[ignore = "a measurement"]
1031fn speed() {
1032 no_leak(|| {
1033 let reg = registry();
1034 let (a, b) = (side("a.example", 1), side("b.example", 2));
1035 let r = cell(null(), 0, &[int(7), int(3)]);
1036 let mut task = int(0);
1037 for i in 0..40 {
1038 // SAFETY: live.
1039 unsafe { dup_value(r) };
1040 task = cell(
1041 null(),
1042 1,
1043 &[string(null(), &format!("payload number {i:04}")), r, task],
1044 );
1045 }
1046 // SAFETY: owned; the cells hold their own references.
1047 unsafe { drop_detached(r) };
1048 let p = enc(&reg, "Ndemo.Task;1s", task, &a).unwrap();
1049 let wire = reg.register("Ndemo.Task;1s").unwrap();
1050 let n = 100_000;
1051 let t = std::time::Instant::now();
1052 for _ in 0..n {
1053 // SAFETY: live.
1054 let q = unsafe { encode(&reg, wire.index, task, &a.me, &a.nodes) }.unwrap();
1055 assert_eq!(q.len(), p.len());
1056 }
1057 let encode_ns = t.elapsed().as_nanos() / n;
1058 let t = std::time::Instant::now();
1059 for _ in 0..n {
1060 let v = decode(
1061 &reg,
1062 wire.hash,
1063 &p,
1064 &b.me,
1065 &b.nodes,
1066 &mut PEER_NODES.clone(),
1067 None,
1068 )
1069 .unwrap();
1070 // SAFETY: owned.
1071 unsafe { drop_detached(v) };
1072 }
1073 let decode_ns = t.elapsed().as_nanos() / n;
1074 eprintln!(
1075 "{} bytes: encode {encode_ns} ns, decode {decode_ns} ns",
1076 p.len()
1077 );
1078 // SAFETY: owned.
1079 unsafe { drop_detached(task) };
1080 });
1081}