1use std::collections::TryReserveError;
14
15use unityrs_core::budget::{BudgetExceeded, Reservation};
16use unityrs_core::env::DerefError;
17use unityrs_core::limits::ChargeError;
18use unityrs_core::typetree::TreeError;
19use unityrs_core::walk::{ParseError, ReadDetail};
20use unityrs_core::{Error, LimitError, LimitKind, NotFound, RawStr};
21use unityrs_meshdecode::MeshError;
22use unityrs_texture::sprite::SpriteError;
23use unityrs_texture::{DecodeError, MAX_PIXELS};
24
25pub const CUT: usize = 1024;
27
28#[derive(Clone, Debug, PartialEq, Eq, Hash)]
32pub struct Reason {
33 pub reason: String,
35 pub detail: Option<String>,
37 pub cut: bool,
39}
40
41impl Reason {
42 #[must_use]
44 pub fn plain(reason: impl Into<String>) -> Self {
45 Self {
46 reason: reason.into(),
47 detail: None,
48 cut: false,
49 }
50 }
51
52 #[must_use]
54 pub fn decode_error(code: impl Into<String>) -> Self {
55 Self {
56 reason: "decode_error".to_owned(),
57 detail: Some(code.into()),
58 cut: false,
59 }
60 }
61}
62
63#[derive(Clone, Debug, PartialEq, Eq)]
65pub enum Class {
66 Skip(Reason),
69 Input(Reason),
72 Run(Reason),
74}
75
76#[must_use]
81pub fn text(bytes: &[u8]) -> (String, bool) {
82 let (n, _) = text_len(&[bytes]);
83 let mut out = String::with_capacity(n);
84 let cut = walk(&[bytes], |c| out.push(c));
85 (out, cut)
86}
87
88fn walk(parts: &[&[u8]], mut put: impl FnMut(char)) -> bool {
92 let mut used = 0usize;
93 for part in parts {
94 for chunk in part.utf8_chunks() {
95 for c in chunk.valid().chars() {
96 if used + c.len_utf8() > CUT {
97 return true;
98 }
99 used += c.len_utf8();
100 put(c);
101 }
102 for _ in chunk.invalid() {
103 if used + 1 > CUT {
104 return true;
105 }
106 used += 1;
107 put(char::REPLACEMENT_CHARACTER);
108 }
109 }
110 }
111 false
112}
113
114#[must_use]
118pub fn text_len(parts: &[&[u8]]) -> (usize, bool) {
119 let mut n = 0usize;
120 let cut = walk(parts, |c| n += c.len_utf8());
121 (n, cut)
122}
123
124pub fn try_text(parts: &[&[u8]]) -> Result<(String, bool), TryReserveError> {
131 let (n, _) = text_len(parts);
132 let mut out = String::new();
133 out.try_reserve_exact(n)?;
134 let cut = walk(parts, |c| out.push(c));
135 Ok((out, cut))
136}
137
138#[must_use]
140pub fn with_argument(name: &str, argument: &[u8]) -> Reason {
141 let (arg, cut) = text(argument);
142 Reason {
143 reason: format!("{name}({arg})"),
144 detail: None,
145 cut,
146 }
147}
148
149#[must_use]
151pub fn outside_view(name: &RawStr) -> Reason {
152 with_argument("outside_view", name.as_bytes())
153}
154
155#[must_use]
159pub fn outside_view_cab(path: &RawStr) -> Reason {
160 let p = path.as_bytes();
161 let start = p.iter().rposition(|&b| b == b'/').map_or(0, |i| i + 1);
162 with_argument("outside_view", p.get(start..).unwrap_or_default())
163}
164
165fn internal() -> Class {
166 Class::Run(Reason::plain("internal"))
167}
168
169#[must_use]
171pub fn limit_kind(kind: LimitKind) -> Option<&'static str> {
172 Some(match kind {
173 LimitKind::InputMemory => "input_memory",
174 LimitKind::InputBytes => "input_bytes",
175 LimitKind::DecodeWork => "decode_work",
176 LimitKind::BlockOutput => "block_output",
177 LimitKind::Inflate => "inflate",
178 LimitKind::ContainerDepth => "container_depth",
179 LimitKind::TreeDepth => "tree_depth",
180 LimitKind::ValueDepth => "value_depth",
181 LimitKind::ValuesPerObject => "values_per_object",
182 LimitKind::ZeroSizeElements => "zero_size_elements",
183 LimitKind::Count => "count",
184 _ => return None,
185 })
186}
187
188#[must_use]
191pub fn limit(l: &LimitError) -> Class {
192 match limit_kind(l.kind()) {
193 Some(kind) => Class::Skip(Reason::plain(format!("limit({kind}, {})", l.max()))),
194 None => internal(),
195 }
196}
197
198#[must_use]
202pub fn budget(b: &BudgetExceeded) -> Class {
203 match b.what {
204 Reservation::Input => Class::Skip(Reason::plain("budget(input)")),
205 Reservation::Dependency => Class::Input(Reason::plain("budget(dependency)")),
206 Reservation::Provider => Class::Run(Reason::plain("host_memory")),
207 }
208}
209
210#[must_use]
212pub fn charge(c: &ChargeError) -> Class {
213 match c {
214 ChargeError::Limit(l) => limit(l),
215 ChargeError::Budget(b) => budget(b),
216 ChargeError::Allocator(_) => Class::Run(Reason::plain("host_memory")),
217 _ => Class::Run(Reason::plain("internal")),
218 }
219}
220
221#[must_use]
224pub fn tree(t: &TreeError) -> Class {
225 match t {
226 TreeError::Empty | TreeError::LevelUnderflow { .. } | TreeError::TooManyNodes(_) => {
227 Class::Skip(Reason::decode_error("tree"))
228 }
229 TreeError::Limit(l) => limit(l),
230 TreeError::Charge(c) => charge(c),
231 _ => internal(),
232 }
233}
234
235#[must_use]
237pub fn parse(e: &ParseError) -> Class {
238 match e {
239 ParseError::Provider(p) if p.allocator.is_some() => {
240 Class::Run(Reason::plain("host_memory"))
241 }
242 ParseError::NoTypeTree { .. } | ParseError::CheckRead { .. } | ParseError::Provider(_) => {
243 Class::Skip(Reason::decode_error("asset_bundle"))
244 }
245 ParseError::Read(r) => match &r.detail {
246 ReadDetail::Limit(l) | ReadDetail::Tree(TreeError::Limit(l)) => limit(l),
250 ReadDetail::Charge(c) | ReadDetail::Tree(TreeError::Charge(c)) => charge(c),
251 ReadDetail::Eof { .. }
252 | ReadDetail::BoostEof { .. }
253 | ReadDetail::NegativeLength(_)
254 | ReadDetail::ArrayChildren
255 | ReadDetail::PairChildren
256 | ReadDetail::NoRefTypes { .. }
257 | ReadDetail::RefTypeNotFound
258 | ReadDetail::RefTypeNoTree
259 | ReadDetail::Python(_)
260 | ReadDetail::Stream(_)
261 | ReadDetail::Tree(
262 TreeError::Empty | TreeError::LevelUnderflow { .. } | TreeError::TooManyNodes(_),
263 ) => Class::Skip(Reason::decode_error("read")),
264 _ => internal(),
265 },
266 ParseError::Tree(t) => tree(t),
267 ParseError::Deref(d) => deref(d),
268 _ => internal(),
269 }
270}
271
272#[must_use]
274pub fn deref(e: &DerefError) -> Class {
275 match e {
276 DerefError::Null
277 | DerefError::FileIdPastEnd { .. }
278 | DerefError::FileIdBelowStart { .. }
279 | DerefError::RawTarget { .. }
280 | DerefError::MissingObject { .. } => Class::Skip(Reason::plain("bad_pointer")),
281 DerefError::NotFound { path } => Class::Skip(outside_view_cab(path)),
282 DerefError::Load(e) => error(e),
283 _ => internal(),
284 }
285}
286
287#[must_use]
289pub fn error(e: &Error) -> Class {
290 let code = match e {
291 Error::Entry { source, .. } => return error(source),
292 Error::AssetBundle(p) => return parse(p),
293 Error::Deref(d) => return deref(d),
294 Error::Tree(t) => return tree(t),
295 Error::Limit(l) => return limit(l),
296 Error::Budget(b) => return budget(b),
297 Error::Allocator(_) | Error::Detect(unityrs_core::detect::DetectError::Allocator(_)) => {
298 return Class::Run(Reason::plain("host_memory"));
299 }
300 Error::Io(_) => return Class::Run(Reason::plain("host_io")),
301 Error::Detect(_) => "detect",
302 Error::OutOfBounds { .. } => "out_of_bounds",
303 Error::Malformed { .. } | Error::UnityCnSignature | Error::UnityCnVectorLength { .. } => {
306 "malformed"
307 }
308 Error::UnityCnKeyMissing | Error::UnityCnKeyLength { .. } | Error::Unsupported(_) => {
310 "unsupported"
311 }
312 Error::Decompress { .. } => "decompress",
313 Error::Version(_) => "version",
314 Error::TypeIndex { .. } => "type_index",
315 Error::NotFound(_) => "not_found",
316 _ => return internal(),
317 };
318 Class::Skip(Reason::decode_error(code))
319}
320
321#[must_use]
324pub fn resource(e: &Error, path: &RawStr) -> Class {
325 match e {
326 Error::NotFound(NotFound::Resource(_)) => Class::Skip(outside_view(path)),
327 other => error(other),
328 }
329}
330
331#[must_use]
333pub fn decode(e: &DecodeError) -> Class {
334 let code = match e {
335 DecodeError::NoImageData => "no_image_data",
336 DecodeError::NegativeSize { .. } => "negative_size",
337 DecodeError::PillowMemoryError { .. } => "pillow_memory_error",
338 DecodeError::NotEnoughData { .. } => "not_enough_data",
339 DecodeError::DecompressionBomb { .. } => "decompression_bomb",
340 DecodeError::Crunch(_) => "crunch",
341 DecodeError::Hdr(_) => "malformed",
342 DecodeError::Platform(_) | DecodeError::PvrtcBlockCount => "read",
343 DecodeError::TooLarge { .. } => {
344 return Class::Skip(Reason::plain(format!(
345 "limit(texture_pixels, {MAX_PIXELS})"
346 )));
347 }
348 DecodeError::Charge(c) => return charge(c),
349 DecodeError::Panicked { payload } => return panicked(payload),
350 _ => return internal(),
351 };
352 Class::Skip(Reason::decode_error(code))
353}
354
355fn panicked(payload: &unityrs_texture::Payload) -> Class {
359 Class::Skip(Reason {
360 reason: "decoder_panic".to_owned(),
361 detail: Some(payload.message().to_owned()),
362 cut: payload.is_cut(),
363 })
364}
365
366#[must_use]
377pub fn render(e: &SpriteError) -> Class {
378 let code = match e {
379 SpriteError::DecompressionBomb { .. } => "decompression_bomb",
380 SpriteError::CIntOverflow { .. } | SpriteError::CLongOverflow => "crop_overflow",
381 SpriteError::ImageTooWide => "pillow_memory_error",
382 SpriteError::Malformed(_) => "read",
383 SpriteError::UnverifiedMode { .. } => "unsupported",
384 SpriteError::AtlasUnresolved => return Class::Skip(Reason::plain("bad_pointer")),
385 SpriteError::TooLarge { .. } => {
386 return Class::Skip(Reason::plain(format!(
387 "limit(texture_pixels, {MAX_PIXELS})"
388 )));
389 }
390 SpriteError::Charge(c) => return charge(c),
391 SpriteError::Panicked(payload) => return panicked(payload),
392 SpriteError::Mesh(m) => return mesh(m),
393 SpriteError::CropRightLeft
394 | SpriteError::CropLowerUpper
395 | SpriteError::RoundNan
396 | SpriteError::RoundInfinity
397 | SpriteError::SolveCast
398 | SpriteError::Rotation(_)
399 | SpriteError::AlphaSizeMismatch
400 | SpriteError::AlphaBandCount
401 | SpriteError::NoVertices
402 | SpriteError::Unpack { .. }
403 | SpriteError::Index { .. }
404 | SpriteError::Sprite3d
405 | SpriteError::NoTriangles
406 | SpriteError::NegativeSize
407 | SpriteError::NoAtlasData => "render",
408 _ => return internal(),
409 };
410 Class::Skip(Reason::decode_error(code))
411}
412
413fn mesh(e: &MeshError) -> Class {
418 let code = match e {
419 MeshError::Charge(c) => return charge(c),
420 MeshError::Resource(e) => return error(e),
421 MeshError::Unsupported(_) => "unsupported",
422 MeshError::Malformed(_) => "read",
423 MeshError::Assertion(_)
424 | MeshError::NoAttribute(_)
425 | MeshError::UnknownMeshType
426 | MeshError::VersionType(_)
427 | MeshError::InvalidFormat { .. }
428 | MeshError::UnknownChannel(_)
429 | MeshError::NoChannels
430 | MeshError::OutOfBounds
431 | MeshError::Struct(_)
432 | MeshError::Index(_)
433 | MeshError::Unpack { .. }
434 | MeshError::ByteRange
435 | MeshError::Topology
436 | MeshError::WrappedAccess => "render",
437 _ => return internal(),
438 };
439 Class::Skip(Reason::decode_error(code))
440}
441
442#[must_use]
449pub fn entry_error(e: &Error, path: &RawStr) -> Class {
450 match error(e) {
451 Class::Skip(r) if r.reason == "decode_error" => {
452 let code = r.detail.unwrap_or_default();
453 let parts = [code.as_bytes(), b" ".as_slice(), path.as_bytes()];
456 let Ok((detail, cut)) = try_text(&parts) else {
457 return Class::Run(Reason::plain("host_memory"));
458 };
459 Class::Input(Reason {
460 reason: "entry_error".to_owned(),
461 detail: Some(detail),
462 cut,
463 })
464 }
465 Class::Skip(r) => Class::Input(r),
466 other => other,
467 }
468}
469
470#[must_use]
472pub fn known_texture_format(name: &str) -> bool {
473 unityrs_texture::TEXTURE_FORMATS
474 .iter()
475 .any(|(_, n)| *n == name)
476}
477
478#[cfg(test)]
479mod tests {
480 use std::sync::Arc;
481
482 use unityrs_core::budget::{BudgetExceeded, Reservation};
483 use unityrs_core::env::DerefError;
484 use unityrs_core::typetree::TreeError;
485 use unityrs_core::walk::{ParseError, ReadDetail, ReadError, ReadErrorKind};
486 use unityrs_core::{Error, LimitError, LimitKind, NotFound, RawStr};
487 use unityrs_texture::DecodeError;
488
489 use super::{Class, Reason, entry_error, error, parse, resource, text, text_len, try_text};
490
491 fn skip(reason: &str, detail: Option<&str>) -> Class {
492 Class::Skip(Reason {
493 reason: reason.to_owned(),
494 detail: detail.map(str::to_owned),
495 cut: false,
496 })
497 }
498
499 fn read(detail: ReadDetail) -> ParseError {
500 ParseError::Read(ReadError {
501 kind: ReadErrorKind::Other,
502 at: 0,
503 detail,
504 })
505 }
506
507 #[test]
508 fn each_wrapper_reaches_the_innermost_code() {
509 let malformed = Error::Malformed {
510 what: "x",
511 detail: "y".into(),
512 };
513 let entry = Error::Entry {
514 name: RawStr::from(b"CAB-a".as_slice()),
515 source: Arc::new(malformed.clone()),
516 };
517 let load = Error::Deref(Arc::new(DerefError::Load(entry.clone())));
518 let in_parse =
519 Error::AssetBundle(Arc::new(ParseError::Deref(DerefError::Load(load.clone()))));
520 for e in [&malformed, &entry, &load, &in_parse] {
521 assert_eq!(error(e), skip("decode_error", Some("malformed")), "{e}");
522 }
523 let missing = DerefError::NotFound {
524 path: RawStr::from(b"archive:/CAB-z/CAB-z".as_slice()),
525 };
526 assert_eq!(
527 error(&Error::Deref(Arc::new(missing))),
528 skip("outside_view(CAB-z)", None)
529 );
530 assert_eq!(
531 error(&Error::Deref(Arc::new(DerefError::Null))),
532 skip("bad_pointer", None)
533 );
534 }
535
536 #[test]
537 fn parse_errors_take_their_codes_and_limits_their_kinds() {
538 let tree = TreeError::LevelUnderflow { row: 1, level: 3 };
539 assert_eq!(
540 parse(&ParseError::Tree(tree.clone())),
541 skip("decode_error", Some("tree"))
542 );
543 assert_eq!(
544 parse(&read(ReadDetail::Tree(tree))),
545 skip("decode_error", Some("read"))
546 );
547 assert_eq!(
548 parse(&read(ReadDetail::Eof {
549 need: 4,
550 exception: "EOFError"
551 })),
552 skip("decode_error", Some("read"))
553 );
554 assert_eq!(
555 parse(&read(ReadDetail::BoostEof {
556 method: "read_i32",
557 need: 4,
558 exception: "EOFError",
559 })),
560 skip("decode_error", Some("read"))
561 );
562 let depth = LimitError::refused(LimitKind::ValueDepth, 600, 512);
563 assert_eq!(
564 parse(&read(ReadDetail::Limit(depth))),
565 skip("limit(value_depth, 512)", None)
566 );
567 assert_eq!(
568 parse(&ParseError::NoTypeTree {
569 class_id: 28,
570 why: None
571 }),
572 skip("decode_error", Some("asset_bundle"))
573 );
574 let dep = BudgetExceeded {
575 requested: 1,
576 what: Reservation::Dependency,
577 };
578 assert_eq!(
579 error(&Error::Budget(dep)),
580 Class::Input(Reason::plain("budget(dependency)"))
581 );
582 let input = BudgetExceeded {
583 requested: 1,
584 what: Reservation::Input,
585 };
586 assert_eq!(error(&Error::Budget(input)), skip("budget(input)", None));
587 }
588
589 #[test]
590 fn a_missing_resource_names_its_path_and_a_decode_its_code() {
591 let path = RawStr::from(b"archive:/CAB-x/r.resS".as_slice());
592 let e = Error::NotFound(NotFound::Resource(RawStr::from(b"r.resS".as_slice())));
593 assert_eq!(
594 resource(&e, &path),
595 skip("outside_view(archive:/CAB-x/r.resS)", None)
596 );
597 assert_eq!(
598 super::decode(&DecodeError::TooLarge { pixels: 1, max: 1 }),
599 skip("limit(texture_pixels, 268435456)", None)
600 );
601 assert_eq!(
602 super::decode(&DecodeError::NegativeSize {
603 width: -1,
604 height: 1
605 }),
606 skip("decode_error", Some("negative_size"))
607 );
608 }
609
610 #[test]
611 fn malformed_crunch_is_an_object_decode_skip() {
612 let e = DecodeError::Crunch(unityrs_texture::CrunchError::Header("signature"));
613 assert_eq!(super::decode(&e), skip("decode_error", Some("crunch")));
614 }
615
616 #[test]
617 fn every_hdr_content_error_is_a_malformed_object_skip() {
618 use unityrs_texture::HdrError;
619
620 for error in [HdrError::ReservedMode, HdrError::InvalidBlock] {
621 assert_eq!(
622 super::decode(&DecodeError::Hdr(error)),
623 skip("decode_error", Some("malformed"))
624 );
625 }
626 }
627
628 #[test]
629 fn an_open_of_an_own_row_is_the_inputs_entry_error() {
630 let e = Error::Unsupported(unityrs_core::Unsupported::WebFile);
631 let got = entry_error(&e, &RawStr::from(b"web.data".as_slice()));
632 assert_eq!(
633 got,
634 Class::Input(Reason {
635 reason: "entry_error".to_owned(),
636 detail: Some("unsupported web.data".to_owned()),
637 cut: false,
638 })
639 );
640 let long = vec![b'a'; 2000];
641 let Class::Input(r) = entry_error(&e, &RawStr::from(long.as_slice())) else {
642 panic!("an input failure");
643 };
644 assert_eq!((r.detail.map(|d| d.len()), r.cut), (Some(1024), true));
645 }
646
647 #[test]
648 fn text_is_cut_by_its_bytes_then_each_invalid_byte_replaced() {
649 assert_eq!(text(b"\xe2\x82"), ("\u{fffd}\u{fffd}".to_owned(), false));
652 assert_eq!(text(b"a\xffb"), ("a\u{fffd}b".to_owned(), false));
653 let a = |n| vec![b'a'; n];
655 assert_eq!(text(&a(1024)), ("a".repeat(1024), false));
656 assert_eq!(text(&a(1025)), ("a".repeat(1024), true));
657 let mut split = a(1023);
659 split.extend_from_slice("é".as_bytes());
660 assert_eq!(text(&split), ("a".repeat(1023), true));
661 let (t, cut) = text(&[0xff; 500]);
664 assert_eq!((t.chars().count(), t.len(), cut), (500, 1500, false));
665 let (t, cut) = text(&[0xff; 1025]);
666 assert_eq!((t.chars().count(), cut), (1024, true));
667 }
668
669 #[test]
670 fn the_text_rule_is_measured_then_made_at_that_length() {
671 assert_eq!(text_len(&[&[0xff; 1100]]), (3072, true));
675 let (t, cut) = try_text(&[&[0xff; 1024]]).unwrap();
676 assert_eq!((t.len(), t.capacity(), cut), (3072, 3072, false));
677 let path = vec![b'p'; 30_000];
678 let parts: [&[u8]; 3] = [b"unsupported", b" ", &path];
679 assert_eq!(text_len(&parts), (1024, true));
680 let (t, cut) = try_text(&parts).unwrap();
681 assert_eq!((&t[..13], t.len(), cut), ("unsupported p", 1024, true));
682 let e = Error::Unsupported(unityrs_core::Unsupported::WebFile);
684 let path = RawStr::from(vec![b'q'; 30_000]);
685 let Class::Input(r) = entry_error(&e, &path) else {
686 panic!("an input failure");
687 };
688 assert_eq!(r.detail.map(|d| d.len()), Some(1024));
689 }
690
691 #[test]
692 fn an_outside_view_pointer_names_its_cabs_basename() {
693 let path = RawStr::from(b"archive:/CAB-x/CAB-x".as_slice());
694 let got = super::deref(&DerefError::NotFound { path });
695 assert_eq!(got, skip("outside_view(CAB-x)", None));
696 let long = RawStr::from(vec![b'p'; 1100]);
697 let Class::Skip(r) = super::deref(&DerefError::NotFound { path: long }) else {
698 panic!("a skip");
699 };
700 assert!(r.cut);
701 assert_eq!(r.reason.len(), "outside_view()".len() + 1024);
702 let path = RawStr::from(b"archive:/CAB-a\\b".as_slice());
705 let got = super::deref(&DerefError::NotFound { path });
706 assert_eq!(got, skip("outside_view(CAB-a\\b)", None));
707 let path = RawStr::from(b"CAB-c".as_slice());
708 let got = super::deref(&DerefError::NotFound { path });
709 assert_eq!(got, skip("outside_view(CAB-c)", None));
710 }
711
712 #[test]
713 fn a_contained_panic_is_decoder_panic_with_its_cut() {
714 let panicked = |f: fn()| {
717 let e = unityrs_texture::contain(|| -> Result<(), DecodeError> {
718 f();
719 Ok(())
720 })
721 .unwrap_err();
722 let Class::Skip(r) = super::decode(&e) else {
723 panic!("a skip");
724 };
725 assert_eq!(r.reason, "decoder_panic");
726 (r.detail.unwrap_or_default(), r.cut)
727 };
728 let short = panicked(|| panic!("short"));
729 let long = panicked(|| panic!("{}\u{e9}", "a".repeat(1023)));
730 let other = panicked(|| std::panic::panic_any(7u32));
731 assert_eq!(short, ("short".to_owned(), false));
732 assert_eq!(long, ("a".repeat(1023), true));
734 assert_eq!(
735 other,
736 (unityrs_texture::NON_STRING_PAYLOAD.to_owned(), false)
737 );
738 }
739
740 #[test]
741 fn a_tree_failure_inside_a_read_is_read_and_the_objects_own_is_tree() {
742 assert_eq!(
743 parse(&read(ReadDetail::Tree(TreeError::Empty))),
744 skip("decode_error", Some("read"))
745 );
746 assert_eq!(
747 parse(&ParseError::Tree(TreeError::Empty)),
748 skip("decode_error", Some("tree"))
749 );
750 }
751}