1#![allow(
4 clippy::empty_enums,
5 reason = "zerocopy derives generate uninhabited helper types"
6)]
7
8use alloc::{string::ToString, sync::Arc, vec::Vec};
9use core::{alloc::Layout, ptr::NonNull};
10
11use miden_assembly_syntax::ast::DebugVarLocation;
12use miden_core::{
13 Felt, Word,
14 mast::MastNodeId,
15 serde::{
16 ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
17 read_bounded_len,
18 },
19};
20use miden_debug_types::{ColumnIndex, LineIndex};
21use miden_utils_indexing::IndexVec;
22use zerocopy::{Immutable, IntoBytes, KnownLayout};
23
24use super::{
25 DEBUG_INFO_VERSION, DebugErrorMessage, DebugFieldInfo, DebugFileIdx, DebugFileInfo,
26 DebugFunctionIdx, DebugFunctionInfo, DebugLoc, DebugLocIdx, DebugPrimitiveType,
27 DebugSourceAsmOp, DebugSourceInlineCall, DebugSourceNode, DebugSourceNodeId, DebugSourceVar,
28 DebugStringIdx, DebugTypeIdx, DebugTypeInfo, DebugVariantInfo, MAX_DEBUG_INFO_PAYLOAD_SIZE,
29 MAX_DEBUG_INFO_STRING_ROWS, MAX_DEBUG_INFO_STRING_SIZE, MAX_DEBUG_INFO_TYPE_ROWS,
30 OptionalIndex, PackageDebugInfo,
31};
32
33const POD_BUFFER_ALIGNMENT: usize = align_of::<u64>();
36
37const _: () = {
38 assert!(align_of::<DebugFileInfo>() <= POD_BUFFER_ALIGNMENT);
39 assert!(align_of::<DebugLoc>() <= POD_BUFFER_ALIGNMENT);
40 assert!(align_of::<WireDebugFunctionInfo>() <= POD_BUFFER_ALIGNMENT);
41 assert!(align_of::<DebugSourceNodeId>() <= POD_BUFFER_ALIGNMENT);
42 assert!(align_of::<DebugErrorMessage>() <= POD_BUFFER_ALIGNMENT);
43 assert!(align_of::<DebugSourceAsmOp>() <= POD_BUFFER_ALIGNMENT);
44};
45
46#[repr(C, align(8))]
49#[derive(Clone, Copy, zerocopy::FromBytes, Immutable, IntoBytes, KnownLayout)]
50struct WireDebugFunctionInfo {
51 mast_root: [u64; 4],
52 source_node: OptionalIndex<DebugSourceNodeId>,
53 type_idx: OptionalIndex<DebugTypeIdx>,
54 linkage_name_idx: OptionalIndex<DebugStringIdx>,
55 name_idx: DebugStringIdx,
56 file_idx: DebugFileIdx,
57 line: LineIndex,
58 column: ColumnIndex,
59}
60
61#[derive(Clone, Copy)]
62struct PackageDebugInfoDecodeLimits {
63 payload_size: usize,
64 string_rows: usize,
65 string_size: usize,
66 type_rows: usize,
67}
68
69impl PackageDebugInfoDecodeLimits {
70 const BOUNDED: Self = Self {
71 payload_size: MAX_DEBUG_INFO_PAYLOAD_SIZE,
72 string_rows: MAX_DEBUG_INFO_STRING_ROWS,
73 string_size: MAX_DEBUG_INFO_STRING_SIZE,
74 type_rows: MAX_DEBUG_INFO_TYPE_ROWS,
75 };
76
77 const UNMETERED: Self = Self {
78 payload_size: usize::MAX,
79 string_rows: usize::MAX,
80 string_size: usize::MAX,
81 type_rows: usize::MAX,
82 };
83}
84
85fn check_decode_limit(
86 resource: &'static str,
87 actual: usize,
88 limit: usize,
89) -> Result<(), super::DebugInfoEncodingError> {
90 if actual > limit {
91 return Err(super::DebugInfoEncodingError::LimitExceeded { resource, size: actual, limit });
92 }
93 Ok(())
94}
95
96#[cfg(target_endian = "little")]
104impl Serializable for PackageDebugInfo {
105 fn write_into<W: ByteWriter>(&self, target: &mut W) {
106 let mut output = Vec::<u8>::with_capacity(16 * 1024);
107
108 self.strings.write_into(&mut output);
109
110 output.write_u32(self.files().len().try_into().unwrap());
111 write_pod_slice(self.files().as_slice(), &mut output);
112
113 output.write_u32(self.locations().len().try_into().unwrap());
114 write_pod_slice(self.locations().as_slice(), &mut output);
115
116 self.types.write_into(&mut output);
117
118 output.write_u32(self.functions().len().try_into().unwrap());
119 pad_to_align::<WireDebugFunctionInfo>(&mut output);
120 write_pod_rows(
121 self.functions().iter().map(|row| {
122 let mast_root = row.mast_root.into_elements().map(|felt| felt.as_canonical_u64());
123 WireDebugFunctionInfo {
124 mast_root,
125 source_node: row.source_node,
126 type_idx: row.type_idx,
127 linkage_name_idx: row.linkage_name_idx,
128 name_idx: row.name_idx,
129 file_idx: row.file_idx,
130 line: row.line,
131 column: row.column,
132 }
133 }),
134 &mut output,
135 );
136
137 self.nodes.write_into(&mut output);
138
139 output.write_u32(self.roots().len().try_into().unwrap());
140 write_pod_slice(self.roots(), &mut output);
141
142 output.write_u32(self.error_messages().len().try_into().unwrap());
143 write_pod_slice(self.error_messages(), &mut output);
144
145 target.write_u8(self.version());
146 target.write_usize(output.len());
147 target.write_bytes(&output);
148 }
149}
150
151#[cfg(target_endian = "little")]
152impl PackageDebugInfo {
153 pub fn to_bytes_with_standard_limits(&self) -> Result<Vec<u8>, super::DebugInfoEncodingError> {
159 self.to_bytes_with_limits(PackageDebugInfoDecodeLimits::BOUNDED)
160 }
161
162 fn to_bytes_with_limits(
163 &self,
164 limits: PackageDebugInfoDecodeLimits,
165 ) -> Result<Vec<u8>, super::DebugInfoEncodingError> {
166 for (label, actual, limit) in [
167 ("debug_info strings count", self.strings.len(), limits.string_rows),
168 ("debug_info types count", self.types.len(), limits.type_rows),
169 ] {
170 check_decode_limit(label, actual, limit)?;
171 }
172 for string in self.strings.iter() {
173 check_decode_limit("debug string size", string.len(), limits.string_size)?;
174 }
175
176 let bytes = self.to_bytes();
177 let mut header = miden_core::serde::SliceReader::new(&bytes);
178 header.read_u8()?;
179 let payload_size = header.read_usize()?;
180 check_decode_limit("package debug info payload size", payload_size, limits.payload_size)?;
181 Ok(bytes)
182 }
183
184 pub fn read_from_unmetered<R: ByteReader>(
192 source: &mut R,
193 ) -> Result<Self, DeserializationError> {
194 Self::read_from_with_limits(source, PackageDebugInfoDecodeLimits::UNMETERED)
195 }
196
197 pub fn read_from_bytes_unmetered(bytes: &[u8]) -> Result<Self, DeserializationError> {
204 Self::read_from_unmetered(&mut miden_core::serde::SliceReader::new(bytes))
205 }
206
207 fn read_from_with_limits<R: ByteReader>(
208 source: &mut R,
209 limits: PackageDebugInfoDecodeLimits,
210 ) -> Result<Self, DeserializationError> {
211 use alloc::string::ToString;
212
213 let version = source.read_u8()?;
214 if version != DEBUG_INFO_VERSION {
215 return Err(DeserializationError::InvalidValue(format!(
216 "unsupported debug_info version: {version}, expected {DEBUG_INFO_VERSION}"
217 )));
218 }
219
220 let data_len = read_bounded_len(source, "package debug info", 1)?;
221 check_decode_limit("package debug info payload size", data_len, limits.payload_size)
222 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
223 let data = source.read_slice(data_len)?;
224 let aligned = AlignedBytes::copy_from_slice(data, POD_BUFFER_ALIGNMENT)?;
225 let mut source = PodSliceReader::new(aligned.as_slice());
226
227 let strings_len = read_bounded_len(&mut source, "debug_info strings", 1)?;
228 check_decode_limit("debug_info strings count", strings_len, limits.string_rows)
229 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
230 let mut strings = Vec::new();
231 for _ in 0..strings_len {
232 strings.push(read_string(&mut source, limits.string_size)?);
233 }
234 let strings = IndexVec::try_from(strings).map_err(|_| {
235 DeserializationError::InvalidValue(
236 "debug_info strings count exceeds the u32 index range".into(),
237 )
238 })?;
239
240 let files_len = source.read_u32()?;
241 let files = source.read_pod_rows::<DebugFileInfo>(files_len as usize, "debug files")?;
242
243 let locations_len = source.read_u32()?;
244 let locations =
245 source.read_pod_rows::<DebugLoc>(locations_len as usize, "debug locations")?;
246
247 let types_len = read_bounded_len(
248 &mut source,
249 "debug_info types",
250 DebugTypeInfo::min_serialized_size(),
251 )?;
252 check_decode_limit("debug_info types count", types_len, limits.type_rows)
253 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
254 let types = source.read_many_iter(types_len)?.collect::<Result<Vec<DebugTypeInfo>, _>>()?;
255 let types = IndexVec::try_from(types).map_err(|_| {
256 DeserializationError::InvalidValue(
257 "debug_info types count exceeds the u32 index range".into(),
258 )
259 })?;
260
261 let functions_len = source.read_u32()?;
262 let functions = source.read_pod_rows_with::<WireDebugFunctionInfo, _, _>(
263 functions_len as usize,
264 "debug functions",
265 |row| {
266 Ok(DebugFunctionInfo {
267 mast_root: Word::new([
268 read_wire_felt(row.mast_root[0])?,
269 read_wire_felt(row.mast_root[1])?,
270 read_wire_felt(row.mast_root[2])?,
271 read_wire_felt(row.mast_root[3])?,
272 ]),
273 source_node: row.source_node,
274 type_idx: row.type_idx,
275 linkage_name_idx: row.linkage_name_idx,
276 name_idx: row.name_idx,
277 file_idx: row.file_idx,
278 line: row.line,
279 column: row.column,
280 })
281 },
282 )?;
283
284 let nodes = IndexVec::read_from_bounded(&mut source, "debug_info nodes")?;
285
286 let roots_len = source.read_u32()? as usize;
287 let roots = source.read_pod_rows::<DebugSourceNodeId>(roots_len, "debug source roots")?;
288
289 let error_messages_len = source.read_u32()? as usize;
290 let error_messages = source
291 .read_pod_rows::<DebugErrorMessage>(error_messages_len, "debug error messages")?;
292
293 let remaining_len = source.remaining_len();
294 if remaining_len != 0 {
295 return Err(DeserializationError::InvalidValue(format!(
296 "expected {data_len} bytes to have been read, but {remaining_len} remain in the buffer"
297 )));
298 }
299
300 Ok(PackageDebugInfo {
301 version,
302 strings,
303 files: IndexVec::try_from(files).unwrap(),
304 locations: IndexVec::try_from(locations).unwrap(),
305 types,
306 functions: IndexVec::try_from(functions).unwrap(),
307 nodes,
308 roots,
309 error_messages,
310 })
311 }
312}
313
314#[cfg(target_endian = "little")]
315impl Deserializable for PackageDebugInfo {
316 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
323 Self::read_from_with_limits(source, PackageDebugInfoDecodeLimits::BOUNDED)
324 }
325
326 fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
333 Self::read_from(&mut miden_core::serde::SliceReader::new(bytes))
334 }
335}
336
337#[cfg(target_endian = "little")]
343impl Serializable for DebugSourceNode {
344 fn write_into<W: ByteWriter>(&self, target: &mut W) {
345 let mut output = Vec::<u8>::with_capacity(
346 size_of::<DebugSourceNode>()
347 + (self.asm_ops.len() * size_of::<DebugSourceAsmOp>())
348 + (self.debug_vars.len() * size_of::<DebugSourceVar>())
349 + (self.inline_calls.len() * size_of::<DebugSourceInlineCall>()),
350 );
351
352 output.write_u32(self.exec_node.into());
353
354 output.write_u32(self.children.len().try_into().unwrap());
355 write_pod_slice(self.children.as_slice(), &mut output);
356
357 output.write_u32(self.op_start);
358 output.write_u32(self.op_end);
359
360 output.write_u32(self.asm_ops.len().try_into().unwrap());
361 write_pod_slice(self.asm_ops.as_slice(), &mut output);
362
363 self.debug_vars.write_into(&mut output);
364 self.inline_calls.write_into(&mut output);
365
366 target.write_usize(output.len());
367 target.write_bytes(&output);
368 }
369}
370
371#[cfg(target_endian = "little")]
372impl Deserializable for DebugSourceNode {
373 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
374 let data_len = read_bounded_len(source, "debug source node", 1)?;
375 let data = source.read_slice(data_len)?;
376 let aligned = AlignedBytes::copy_from_slice(data, POD_BUFFER_ALIGNMENT)?;
377 let mut source = PodSliceReader::new(aligned.as_slice());
378
379 let exec_node = MastNodeId::new_unchecked(source.read_u32()?);
380
381 let children_len = source.read_u32()? as usize;
382 let children =
383 source.read_pod_rows::<DebugSourceNodeId>(children_len, "debug source children")?;
384
385 let op_start = source.read_u32()?;
386 let op_end = source.read_u32()?;
387
388 let asm_ops_len = source.read_u32()? as usize;
389 let asm_ops =
390 source.read_pod_rows::<DebugSourceAsmOp>(asm_ops_len, "debug assembly operations")?;
391 if let Some(rows) = asm_ops.windows(2).find(|rows| rows[0].op_idx >= rows[1].op_idx) {
392 return Err(DeserializationError::InvalidValue(format!(
393 "debug assembly operation indices are not strictly increasing at {} and {}",
394 rows[0].op_idx, rows[1].op_idx,
395 )));
396 }
397
398 let debug_vars = Vec::read_from(&mut source)?;
399 let inline_calls = Vec::read_from(&mut source)?;
400
401 let remaining_len = source.remaining_len();
402 if remaining_len != 0 {
403 return Err(DeserializationError::InvalidValue(format!(
404 "expected {data_len} bytes to have been read, but {remaining_len} remain in the buffer"
405 )));
406 }
407
408 Ok(Self {
409 exec_node,
410 children,
411 op_start,
412 op_end,
413 asm_ops,
414 debug_vars,
415 inline_calls,
416 })
417 }
418
419 fn min_serialized_size() -> usize {
420 1 + DebugSourceNodeId::min_serialized_size()
421 + Vec::<DebugSourceNodeId>::min_serialized_size()
422 + 8
423 + 1
424 + Vec::<DebugSourceVar>::min_serialized_size()
425 + Vec::<DebugSourceInlineCall>::min_serialized_size()
426 }
427}
428
429impl Serializable for DebugSourceVar {
433 fn write_into<W: ByteWriter>(&self, target: &mut W) {
434 target.write_u32(self.op_idx);
435 self.name_idx.write_into(target);
436 self.type_id.write_into(target);
437 target.write_u32(self.arg_idx.map(core::num::NonZeroU32::get).unwrap_or_default());
438 self.location_idx.write_into(target);
439 self.value_location.write_into(target);
440 }
441}
442
443impl Deserializable for DebugSourceVar {
444 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
445 let op_idx = source.read_u32()?;
446 let name_idx = DebugStringIdx::read_from(source)?;
447 let type_id = Option::<DebugTypeIdx>::read_from(source)?;
448 let arg_idx = core::num::NonZeroU32::new(source.read_u32()?);
449 let location_idx = Option::<DebugLocIdx>::read_from(source)?;
450 let value_location = DebugVarLocation::read_from(source)?;
451 Ok(Self {
452 op_idx,
453 name_idx,
454 type_id,
455 arg_idx,
456 location_idx,
457 value_location,
458 })
459 }
460
461 fn min_serialized_size() -> usize {
462 4 + DebugStringIdx::min_serialized_size()
463 + 1
464 + 4
465 + 1
466 + DebugVarLocation::min_serialized_size()
467 }
468}
469
470impl Serializable for DebugSourceInlineCall {
474 fn write_into<W: ByteWriter>(&self, target: &mut W) {
475 target.write_u32(self.op_idx);
476 target.write_u32(self.op_end);
477 self.callee_idx.write_into(target);
478 self.loc_idx.write_into(target);
479 }
480}
481
482impl Deserializable for DebugSourceInlineCall {
483 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
484 let op_idx = source.read_u32()?;
485 let op_end = source.read_u32()?;
486 if op_end < op_idx {
487 return Err(DeserializationError::InvalidValue(
488 "debug inline-call range ends before its start".into(),
489 ));
490 }
491 let callee_idx = DebugFunctionIdx::read_from(source)?;
492 let loc_idx = DebugLocIdx::read_from(source)?;
493 Ok(DebugSourceInlineCall { op_idx, op_end, callee_idx, loc_idx })
494 }
495
496 fn min_serialized_size() -> usize {
497 8 + DebugFunctionIdx::min_serialized_size() + DebugLocIdx::min_serialized_size()
498 }
499}
500
501const TYPE_TAG_PRIMITIVE: u8 = 0;
506const TYPE_TAG_POINTER: u8 = 1;
507const TYPE_TAG_ARRAY: u8 = 2;
508const TYPE_TAG_STRUCT: u8 = 3;
509const TYPE_TAG_FUNCTION: u8 = 4;
510const TYPE_TAG_UNKNOWN: u8 = 5;
511const TYPE_TAG_ENUM: u8 = 6;
512const TYPE_TAG_VARIADIC: u8 = 7;
513
514impl Serializable for DebugTypeInfo {
515 fn write_into<W: ByteWriter>(&self, target: &mut W) {
516 match self {
517 Self::Primitive(prim) => {
518 target.write_u8(TYPE_TAG_PRIMITIVE);
519 target.write_u8(*prim as u8);
520 },
521 Self::Pointer { pointee_type_idx } => {
522 target.write_u8(TYPE_TAG_POINTER);
523 pointee_type_idx.write_into(target);
524 },
525 Self::Array { element_type_idx, count } => {
526 target.write_u8(TYPE_TAG_ARRAY);
527 element_type_idx.write_into(target);
528 target.write_bool(count.is_some());
529 if let Some(count) = count {
530 target.write_u32(*count);
531 }
532 },
533 Self::Struct { name_idx, size, fields } => {
534 target.write_u8(TYPE_TAG_STRUCT);
535 name_idx.write_into(target);
536 target.write_u32(*size);
537 target.write_usize(fields.len());
538 for field in fields {
539 field.write_into(target);
540 }
541 },
542 Self::Function { return_type_idx, param_type_indices } => {
543 target.write_u8(TYPE_TAG_FUNCTION);
544 target.write_bool(return_type_idx.is_some());
545 if let Some(idx) = return_type_idx {
546 idx.write_into(target);
547 }
548 target.write_usize(param_type_indices.len());
549 for idx in param_type_indices {
550 idx.write_into(target);
551 }
552 },
553 Self::Enum {
554 name_idx,
555 size,
556 discriminant_type_idx,
557 variants,
558 } => {
559 target.write_u8(TYPE_TAG_ENUM);
560 name_idx.write_into(target);
561 target.write_u32(*size);
562 discriminant_type_idx.write_into(target);
563 target.write_usize(variants.len());
564 for variant in variants {
565 variant.write_into(target);
566 }
567 },
568 Self::Unknown => {
569 target.write_u8(TYPE_TAG_UNKNOWN);
570 },
571 Self::Variadic => {
572 target.write_u8(TYPE_TAG_VARIADIC);
573 },
574 }
575 }
576}
577
578impl Deserializable for DebugTypeInfo {
579 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
580 let tag = source.read_u8()?;
581 match tag {
582 TYPE_TAG_PRIMITIVE => {
583 let prim_tag = source.read_u8()?;
584 let prim = DebugPrimitiveType::from_discriminant(prim_tag).ok_or_else(|| {
585 DeserializationError::InvalidValue(alloc::format!(
586 "invalid primitive type tag: {prim_tag}"
587 ))
588 })?;
589 Ok(Self::Primitive(prim))
590 },
591 TYPE_TAG_POINTER => {
592 let pointee_type_idx = DebugTypeIdx::from(source.read_u32()?);
593 Ok(Self::Pointer { pointee_type_idx })
594 },
595 TYPE_TAG_ARRAY => {
596 let element_type_idx = DebugTypeIdx::from(source.read_u32()?);
597 let has_count = source.read_bool()?;
598 let count = if has_count { Some(source.read_u32()?) } else { None };
599 Ok(Self::Array { element_type_idx, count })
600 },
601 TYPE_TAG_STRUCT => {
602 let name_idx = DebugStringIdx::read_from(source)?;
603 let size = source.read_u32()?;
604 let fields_len = read_bounded_len(source, "debug struct fields", 1)?;
605 let fields = source.read_many_iter(fields_len)?.collect::<Result<_, _>>()?;
606 Ok(Self::Struct { name_idx, size, fields })
607 },
608 TYPE_TAG_FUNCTION => {
609 let has_return = source.read_bool()?;
610 let return_type_idx = if has_return {
611 Some(DebugTypeIdx::from(source.read_u32()?))
612 } else {
613 None
614 };
615 let param_type_indices =
616 read_debug_type_indices(source, "debug function parameters")?;
617 Ok(Self::Function { return_type_idx, param_type_indices })
618 },
619 TYPE_TAG_ENUM => {
620 let name_idx = DebugStringIdx::read_from(source)?;
621 let size = source.read_u32()?;
622 let discriminant_type_idx = DebugTypeIdx::from(source.read_u32()?);
623 let variants_len = read_bounded_len(source, "debug enum variants", 1)?;
624 let variants = source.read_many_iter(variants_len)?.collect::<Result<_, _>>()?;
625 Ok(Self::Enum {
626 name_idx,
627 size,
628 discriminant_type_idx,
629 variants,
630 })
631 },
632 TYPE_TAG_UNKNOWN => Ok(Self::Unknown),
633 TYPE_TAG_VARIADIC => Ok(Self::Variadic),
634 _ => Err(DeserializationError::InvalidValue(alloc::format!("invalid type tag: {tag}"))),
635 }
636 }
637
638 fn min_serialized_size() -> usize {
639 1
641 }
642}
643
644impl Serializable for DebugFieldInfo {
648 fn write_into<W: ByteWriter>(&self, target: &mut W) {
649 self.name_idx.write_into(target);
650 self.type_idx.write_into(target);
651 target.write_u32(self.offset);
652 }
653}
654
655impl Deserializable for DebugFieldInfo {
656 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
657 let name_idx = DebugStringIdx::read_from(source)?;
658 let type_idx = DebugTypeIdx::from(source.read_u32()?);
659 let offset = source.read_u32()?;
660 Ok(Self { name_idx, type_idx, offset })
661 }
662}
663
664impl Serializable for DebugVariantInfo {
668 fn write_into<W: ByteWriter>(&self, target: &mut W) {
669 self.name_idx.write_into(target);
670 target.write_bool(self.type_idx.is_some());
671 if let Some(type_idx) = self.type_idx {
672 type_idx.write_into(target);
673 }
674 target.write_bool(self.payload_offset.is_some());
675 if let Some(payload_offset) = self.payload_offset {
676 target.write_u32(payload_offset);
677 }
678 target.write_u64((self.discriminant >> 64) as u64);
679 target.write_u64(self.discriminant as u64);
680 }
681}
682
683impl Deserializable for DebugVariantInfo {
684 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
685 let name_idx = DebugStringIdx::read_from(source)?;
686 let type_idx = if source.read_bool()? {
687 Some(DebugTypeIdx::from(source.read_u32()?))
688 } else {
689 None
690 };
691 let payload_offset = if source.read_bool()? {
692 Some(source.read_u32()?)
693 } else {
694 None
695 };
696 let hi = source.read_u64()? as u128;
697 let lo = source.read_u64()? as u128;
698 Ok(Self {
699 name_idx,
700 type_idx,
701 payload_offset,
702 discriminant: (hi << 64) | lo,
703 })
704 }
705
706 fn min_serialized_size() -> usize {
707 DebugStringIdx::min_serialized_size()
710 + 2 * u8::min_serialized_size()
711 + 2 * u64::min_serialized_size()
712 }
713}
714
715impl Serializable for DebugFileInfo {
719 fn write_into<W: ByteWriter>(&self, target: &mut W) {
720 self.path_idx.write_into(target);
721 self.checksum.write_into(target);
722 }
723}
724
725impl Deserializable for DebugFileInfo {
726 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
727 let path_idx = DebugStringIdx::read_from(source)?;
728
729 let bytes = source.read_slice(32)?;
730 let mut checksum = [0u8; 32];
731 checksum.copy_from_slice(bytes);
732
733 Ok(Self { path_idx, checksum })
734 }
735
736 fn min_serialized_size() -> usize {
737 DebugStringIdx::min_serialized_size() + size_of::<[u8; 32]>()
738 }
739}
740
741struct AlignedBytes {
746 ptr: Option<NonNull<u8>>,
747 layout: Layout,
748}
749
750impl AlignedBytes {
751 fn copy_from_slice(source: &[u8], alignment: usize) -> Result<Self, DeserializationError> {
752 let layout = Layout::from_size_align(source.len(), alignment).map_err(|_| {
753 DeserializationError::InvalidValue(format!(
754 "debug info payload size {} is too large",
755 source.len()
756 ))
757 })?;
758 if source.is_empty() {
759 return Ok(Self { ptr: None, layout });
760 }
761
762 let ptr = unsafe { alloc::alloc::alloc(layout) };
764 let Some(ptr) = NonNull::new(ptr) else {
765 alloc::alloc::handle_alloc_error(layout)
766 };
767 unsafe {
769 ptr.as_ptr().copy_from_nonoverlapping(source.as_ptr(), source.len());
770 }
771 Ok(Self { ptr: Some(ptr), layout })
772 }
773
774 fn as_slice(&self) -> &[u8] {
775 let Some(ptr) = self.ptr else {
776 return &[];
777 };
778 unsafe { core::slice::from_raw_parts(ptr.as_ptr(), self.layout.size()) }
781 }
782}
783
784impl Drop for AlignedBytes {
785 fn drop(&mut self) {
786 if let Some(ptr) = self.ptr {
787 unsafe {
789 alloc::alloc::dealloc(ptr.as_ptr(), self.layout);
790 }
791 }
792 }
793}
794
795struct PodSliceReader<'a> {
796 source: &'a [u8],
797 pos: usize,
798}
799
800impl<'a> PodSliceReader<'a> {
801 fn new(source: &'a [u8]) -> Self {
802 Self { source, pos: 0 }
803 }
804
805 fn remaining_len(&self) -> usize {
806 self.source.len() - self.pos
807 }
808
809 fn read_pod_rows<T>(&mut self, len: usize, label: &str) -> Result<Vec<T>, DeserializationError>
810 where
811 T: Copy + zerocopy::FromBytes + Immutable + KnownLayout,
812 {
813 self.skip_alignment_padding::<T>()?;
814 let byte_len = len.checked_mul(size_of::<T>()).ok_or_else(|| {
815 DeserializationError::InvalidValue(alloc::format!(
816 "{label} row count {len} overflows row size {}",
817 size_of::<T>()
818 ))
819 })?;
820 let bytes = self.read_slice(byte_len)?;
821 let rows: &[T] = <[T] as zerocopy::FromBytes>::ref_from_bytes(bytes).map_err(|_| {
822 DeserializationError::InvalidValue(alloc::format!(
823 "{label} bytes do not form aligned POD rows"
824 ))
825 })?;
826 Ok(rows.to_vec())
827 }
828
829 fn read_pod_rows_with<T, U, F>(
830 &mut self,
831 len: usize,
832 label: &str,
833 map: F,
834 ) -> Result<Vec<U>, DeserializationError>
835 where
836 T: Copy + zerocopy::FromBytes + Immutable + KnownLayout,
837 F: FnMut(T) -> Result<U, DeserializationError>,
838 {
839 self.skip_alignment_padding::<T>()?;
840 let byte_len = len.checked_mul(size_of::<T>()).ok_or_else(|| {
841 DeserializationError::InvalidValue(alloc::format!(
842 "{label} row count {len} overflows row size {}",
843 size_of::<T>()
844 ))
845 })?;
846 let bytes = self.read_slice(byte_len)?;
847 let rows: &[T] = <[T] as zerocopy::FromBytes>::ref_from_bytes(bytes).map_err(|_| {
848 DeserializationError::InvalidValue(alloc::format!(
849 "{label} bytes do not form aligned POD rows"
850 ))
851 })?;
852 rows.iter().copied().map(map).collect()
853 }
854
855 fn skip_alignment_padding<T>(&mut self) -> Result<(), DeserializationError> {
856 let padding_required = self.pos.next_multiple_of(align_of::<T>()) - self.pos;
857 self.pos += padding_required;
858 if self.pos > self.source.len() {
859 Err(DeserializationError::UnexpectedEOF)
860 } else {
861 Ok(())
862 }
863 }
864}
865
866impl ByteReader for PodSliceReader<'_> {
867 fn max_alloc(&self, element_size: usize) -> usize {
868 self.remaining_len().checked_div(element_size).unwrap_or(usize::MAX)
869 }
870
871 fn read_u8(&mut self) -> Result<u8, DeserializationError> {
872 self.check_eor(1)?;
873 let result = self.source[self.pos];
874 self.pos += 1;
875 Ok(result)
876 }
877
878 fn peek_u8(&self) -> Result<u8, DeserializationError> {
879 self.check_eor(1)?;
880 Ok(self.source[self.pos])
881 }
882
883 fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> {
884 self.check_eor(len)?;
885 let result = &self.source[self.pos..self.pos + len];
886 self.pos += len;
887 Ok(result)
888 }
889
890 fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> {
891 self.check_eor(N)?;
892 let mut result = [0_u8; N];
893 result.copy_from_slice(&self.source[self.pos..self.pos + N]);
894 self.pos += N;
895 Ok(result)
896 }
897
898 fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> {
899 self.pos
900 .checked_add(num_bytes)
901 .filter(|end| *end <= self.source.len())
902 .map(|_| ())
903 .ok_or(DeserializationError::UnexpectedEOF)
904 }
905
906 fn has_more_bytes(&self) -> bool {
907 self.remaining_len() != 0
908 }
909}
910
911fn pad_to_align<T>(output: &mut Vec<u8>) {
912 let padding_required = output.len().next_multiple_of(align_of::<T>()) - output.len();
913 output.resize(output.len() + padding_required, 0);
914}
915
916fn write_pod_slice<T: IntoBytes + Immutable>(slice: &[T], target: &mut Vec<u8>) {
917 pad_to_align::<T>(target);
918 target.write_bytes(slice.as_bytes());
919}
920
921fn write_pod_rows<T, I>(rows: I, target: &mut Vec<u8>)
922where
923 T: IntoBytes + Immutable,
924 I: IntoIterator<Item = T>,
925{
926 let rows: Vec<T> = rows.into_iter().collect();
927 target.write_bytes(rows.as_bytes());
928}
929
930fn read_wire_felt(value: u64) -> Result<Felt, DeserializationError> {
931 Felt::new(value).map_err(|err| {
932 DeserializationError::InvalidValue(alloc::format!(
933 "invalid field element in debug function MAST root: {err}"
934 ))
935 })
936}
937
938fn read_string<R: ByteReader>(
939 source: &mut R,
940 max_size: usize,
941) -> Result<Arc<str>, DeserializationError> {
942 let len = read_bounded_len(source, "debug string bytes", 1)?;
943 check_decode_limit("debug string size", len, max_size)
944 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
945 let bytes = source.read_slice(len)?;
946 let s = core::str::from_utf8(bytes).map_err(|err| {
947 DeserializationError::InvalidValue(alloc::format!("invalid utf-8 in string: {err}"))
948 })?;
949 Ok(Arc::from(s))
950}
951
952fn read_debug_type_indices<R: ByteReader>(
953 source: &mut R,
954 label: &str,
955) -> Result<Vec<DebugTypeIdx>, DeserializationError> {
956 let len = read_bounded_len(source, label, DebugTypeIdx::min_serialized_size())?;
957 source.read_many_iter(len)?.collect::<Result<_, _>>()
958}
959
960#[cfg(test)]
961mod tests {
962 use alloc::string::ToString;
963 use core::{assert_matches, cell::Cell};
964
965 use miden_assembly_syntax::ast::DebugVarLocation;
966 use miden_core::{Felt, Word};
967 use miden_debug_types::{ByteIndex, ColumnNumber, LineNumber, Location, Uri};
968
969 use super::*;
970 use crate::debug_info::{DebugFileIdx, PackageDebugInfoBuilder};
971
972 struct FixedBudgetReader<'a> {
973 inner: miden_core::serde::SliceReader<'a>,
974 max_bytes: usize,
975 largest_requested_element_size: Cell<usize>,
976 }
977
978 impl<'a> FixedBudgetReader<'a> {
979 fn new(bytes: &'a [u8], max_bytes: usize) -> Self {
980 Self {
981 inner: miden_core::serde::SliceReader::new(bytes),
982 max_bytes,
983 largest_requested_element_size: Cell::new(0),
984 }
985 }
986 }
987
988 impl<'a> ByteReader for FixedBudgetReader<'a> {
989 fn read_u8(&mut self) -> Result<u8, DeserializationError> {
990 self.inner.read_u8()
991 }
992
993 fn peek_u8(&self) -> Result<u8, DeserializationError> {
994 self.inner.peek_u8()
995 }
996
997 fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> {
998 self.inner.read_slice(len)
999 }
1000
1001 fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> {
1002 self.inner.read_array()
1003 }
1004
1005 fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> {
1006 self.inner.check_eor(num_bytes)
1007 }
1008
1009 fn has_more_bytes(&self) -> bool {
1010 self.inner.has_more_bytes()
1011 }
1012
1013 fn max_alloc(&self, element_size: usize) -> usize {
1014 self.largest_requested_element_size
1015 .set(self.largest_requested_element_size.get().max(element_size));
1016 if element_size == 0 {
1017 usize::MAX
1018 } else {
1019 self.max_bytes.checked_div(element_size).unwrap_or(0)
1020 }
1021 }
1022 }
1023
1024 fn function_type_bytes(params_len: usize) -> Vec<u8> {
1025 let mut bytes = Vec::new();
1026 bytes.write_u8(TYPE_TAG_FUNCTION);
1027 bytes.write_bool(false);
1028 bytes.write_usize(params_len);
1029 for _ in 0..params_len {
1030 bytes.write_u32(0);
1031 }
1032 bytes
1033 }
1034
1035 fn roundtrip<T: Serializable + Deserializable + PartialEq + core::fmt::Debug>(value: &T) {
1036 let mut bytes = Vec::new();
1037 value.write_into(&mut bytes);
1038 let result = T::read_from(&mut miden_core::serde::SliceReader::new(&bytes)).unwrap();
1039 assert_eq!(value, &result);
1040 }
1041
1042 #[test]
1043 fn pod_row_reader_rejects_byte_length_overflow() {
1044 let mut reader = PodSliceReader::new(&[]);
1045 let result = reader.read_pod_rows::<DebugErrorMessage>(usize::MAX, "test error messages");
1046 let error = result.unwrap_err();
1047
1048 let DeserializationError::InvalidValue(message) = error else {
1049 panic!("expected InvalidValue error");
1050 };
1051 assert!(message.contains("overflows row size"));
1052 }
1053
1054 #[test]
1055 fn pod_row_reader_decodes_certified_rows() {
1056 let expected = DebugErrorMessage::new(42, DebugStringIdx::from(7));
1057 let mut aligned = [0_u64; 2];
1058 aligned.as_mut_bytes()[..size_of::<DebugErrorMessage>()]
1059 .copy_from_slice(expected.as_bytes());
1060 let mut reader = PodSliceReader::new(aligned.as_bytes());
1061 let decoded = reader.read_pod_rows::<DebugErrorMessage>(1, "test error messages").unwrap();
1062
1063 assert_eq!(decoded, [expected]);
1064 }
1065
1066 #[test]
1067 fn debug_variant_min_serialized_size_is_accepted_by_slice_reader() {
1068 let variant = DebugVariantInfo {
1069 name_idx: DebugStringIdx::from(0),
1070 type_idx: None,
1071 payload_offset: None,
1072 discriminant: 0,
1073 };
1074 let mut bytes = Vec::new();
1075 variant.write_into(&mut bytes);
1076
1077 assert_eq!(bytes.len(), DebugVariantInfo::min_serialized_size());
1078
1079 let mut reader = miden_core::serde::SliceReader::new(&bytes);
1080 let mut variants = reader.read_many_iter::<DebugVariantInfo>(1).unwrap();
1081 assert_eq!(variants.next().unwrap().unwrap(), variant);
1082 assert!(variants.next().is_none());
1083 }
1084
1085 #[test]
1086 fn debug_type_initial_capacity_is_bounded_by_in_memory_size() {
1087 const PAYLOAD_BYTES: usize = 256;
1088
1089 let mut bytes = Vec::new();
1090 bytes.write_usize(PAYLOAD_BYTES);
1091 bytes.resize(bytes.len() + PAYLOAD_BYTES, u8::MAX);
1092 let mut reader = FixedBudgetReader::new(&bytes, PAYLOAD_BYTES);
1093
1094 let result =
1095 IndexVec::<DebugTypeIdx, DebugTypeInfo>::read_from_bounded(&mut reader, "debug types");
1096
1097 assert!(result.is_err(), "the first invalid type tag should stop decoding");
1098 assert_eq!(
1099 reader.largest_requested_element_size.get(),
1100 size_of::<DebugTypeInfo>(),
1101 "the speculative capacity must be bounded using the in-memory row size",
1102 );
1103 }
1104
1105 #[test]
1106 fn package_debug_info_trailing_data_error_reports_remaining_bytes() {
1107 const TRAILING: &[u8] = &[0xaa, 0xbb, 0xcc];
1108
1109 let serialized = PackageDebugInfo::default().to_bytes();
1110 let mut reader = miden_core::serde::SliceReader::new(&serialized);
1111 let version = reader.read_u8().unwrap();
1112 let data_len = reader.read_usize().unwrap();
1113 let data = reader.read_slice(data_len).unwrap().to_vec();
1114 assert!(!reader.has_more_bytes());
1115
1116 let mut malformed = Vec::new();
1117 malformed.write_u8(version);
1118 malformed.write_usize(data_len + TRAILING.len());
1119 malformed.write_bytes(&data);
1120 malformed.write_bytes(TRAILING);
1121
1122 let error =
1123 PackageDebugInfo::read_from(&mut miden_core::serde::SliceReader::new(&malformed))
1124 .unwrap_err();
1125 let DeserializationError::InvalidValue(message) = error else {
1126 panic!("expected InvalidValue error");
1127 };
1128 assert!(message.contains("but 3 remain in the buffer"), "{message}");
1129 }
1130
1131 #[test]
1132 fn debug_source_node_trailing_data_error_reports_remaining_bytes() {
1133 const TRAILING: &[u8] = &[0xaa, 0xbb];
1134
1135 let source_node = DebugSourceNode {
1136 exec_node: MastNodeId::new_unchecked(0),
1137 children: Vec::new(),
1138 op_start: 0,
1139 op_end: 0,
1140 asm_ops: Vec::new(),
1141 debug_vars: Vec::new(),
1142 inline_calls: Vec::new(),
1143 };
1144 let serialized = source_node.to_bytes();
1145 let mut reader = miden_core::serde::SliceReader::new(&serialized);
1146 let data_len = reader.read_usize().unwrap();
1147 let data = reader.read_slice(data_len).unwrap().to_vec();
1148 assert!(!reader.has_more_bytes());
1149
1150 let mut malformed = Vec::new();
1151 malformed.write_usize(data_len + TRAILING.len());
1152 malformed.write_bytes(&data);
1153 malformed.write_bytes(TRAILING);
1154
1155 let error =
1156 DebugSourceNode::read_from(&mut miden_core::serde::SliceReader::new(&malformed))
1157 .unwrap_err();
1158 let DeserializationError::InvalidValue(message) = error else {
1159 panic!("expected InvalidValue error");
1160 };
1161 assert!(message.contains("but 2 remain in the buffer"), "{message}");
1162 }
1163
1164 fn roundtrip_debug_info(value: &PackageDebugInfo) -> PackageDebugInfo {
1165 let bytes = value.to_bytes();
1166 let result =
1167 PackageDebugInfo::read_from(&mut miden_core::serde::SliceReader::new(bytes.as_slice()))
1168 .unwrap();
1169 assert_eq!(result.version(), value.version());
1170 assert_eq!(result.strings(), value.strings());
1171 assert_eq!(result.files(), value.files());
1172 assert_eq!(result.locations(), value.locations());
1173 assert_eq!(result.types(), value.types());
1174 assert_eq!(result.functions(), value.functions());
1175 assert_eq!(result.nodes().as_slice(), value.nodes().as_slice());
1176 assert_eq!(result.roots(), value.roots());
1177 assert_eq!(result.error_messages(), value.error_messages());
1178 result
1179 }
1180
1181 #[test]
1182 fn test_debug_types_roundtrip() {
1183 let mut builder = PackageDebugInfoBuilder::default();
1184
1185 let i32_type_idx = builder.add_type(DebugTypeInfo::Primitive(DebugPrimitiveType::I32));
1186 let felt_type_idx = builder.add_type(DebugTypeInfo::Primitive(DebugPrimitiveType::Felt));
1187 builder.add_type(DebugTypeInfo::Pointer { pointee_type_idx: i32_type_idx });
1188 builder.add_type(DebugTypeInfo::Array {
1189 element_type_idx: felt_type_idx,
1190 count: Some(4),
1191 });
1192
1193 let x_idx = builder.add_string("x");
1194 let y_idx = builder.add_string("y");
1195 let point_idx = builder.add_string("Point");
1196 builder.add_type(DebugTypeInfo::Struct {
1197 name_idx: point_idx,
1198 size: 16,
1199 fields: alloc::vec![
1200 DebugFieldInfo {
1201 name_idx: x_idx,
1202 type_idx: felt_type_idx,
1203 offset: 0,
1204 },
1205 DebugFieldInfo {
1206 name_idx: y_idx,
1207 type_idx: felt_type_idx,
1208 offset: 8,
1209 },
1210 ],
1211 });
1212
1213 let status_idx = builder.add_string("Status");
1214 let ok_idx = builder.add_string("Ok");
1215 let err_idx = builder.add_string("Err");
1216 builder.add_type(DebugTypeInfo::Enum {
1217 name_idx: status_idx,
1218 size: 8,
1219 discriminant_type_idx: i32_type_idx,
1220 variants: alloc::vec![
1221 DebugVariantInfo {
1222 name_idx: ok_idx,
1223 type_idx: None,
1224 payload_offset: None,
1225 discriminant: 0,
1226 },
1227 DebugVariantInfo {
1228 name_idx: err_idx,
1229 type_idx: Some(felt_type_idx),
1230 payload_offset: Some(8),
1231 discriminant: 1,
1232 },
1233 ],
1234 });
1235
1236 let debug_info = *builder.build();
1237 let result = roundtrip_debug_info(&debug_info);
1238 assert_eq!(result.strings(), debug_info.strings());
1239 assert_eq!(result.types(), debug_info.types());
1240 }
1241
1242 #[test]
1243 fn test_debug_sources_roundtrip() {
1244 let mut builder = PackageDebugInfoBuilder::default();
1245 builder.add_file(Uri::new("test.rs"), None);
1246 builder.add_file(Uri::new("main.rs"), Some([42u8; 32]));
1247
1248 let debug_info = *builder.build();
1249 let result = roundtrip_debug_info(&debug_info);
1250 assert_eq!(result.strings(), debug_info.strings());
1251 assert_eq!(result.files(), debug_info.files());
1252 assert_eq!(result.files()[DebugFileIdx::from(1)].checksum(), Some(&[42u8; 32]));
1253 }
1254
1255 #[test]
1256 fn test_debug_functions_roundtrip() {
1257 let mut builder = PackageDebugInfoBuilder::default();
1258 let name_idx = builder.add_string("test_function");
1259 let file_idx = builder.add_file(Uri::new("test.masm"), None);
1260 let line = LineNumber::new(10).unwrap();
1261 let column = ColumnNumber::new(1).unwrap();
1262 builder.add_function(DebugFunctionInfo::new(
1263 None,
1264 name_idx,
1265 file_idx,
1266 line,
1267 column,
1268 Word::default(),
1269 ));
1270
1271 let debug_info = *builder.build();
1272 let result = roundtrip_debug_info(&debug_info);
1273 assert_eq!(result.functions(), debug_info.functions());
1274 }
1275
1276 #[test]
1277 fn debug_function_v4_wire_bytes_are_stable() {
1278 const EXPECTED_ROW: [u8; size_of::<WireDebugFunctionInfo>()] = [
1279 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0,
1280 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 9, 0, 0, 0, 1, 0, 0, 0, 11, 0, 0, 0, 13,
1281 0, 0, 0, 15, 0, 0, 0, 17, 0, 0, 0, 19, 0, 0, 0,
1282 ];
1283
1284 let function = DebugFunctionInfo {
1285 mast_root: Word::new([
1286 Felt::new(1).unwrap(),
1287 Felt::new(2).unwrap(),
1288 Felt::new(3).unwrap(),
1289 Felt::new(4).unwrap(),
1290 ]),
1291 source_node: Some(DebugSourceNodeId::from(7)).into(),
1292 type_idx: Some(DebugTypeIdx::from(9)).into(),
1293 linkage_name_idx: Some(DebugStringIdx::from(11)).into(),
1294 name_idx: DebugStringIdx::from(13),
1295 file_idx: DebugFileIdx::from(15),
1296 line: LineIndex::from(17),
1297 column: ColumnIndex::from(19),
1298 };
1299 let mut builder = PackageDebugInfoBuilder::default();
1300 builder.add_function(function);
1301 let debug_info = builder.build();
1302
1303 let bytes = debug_info.to_bytes();
1304 assert_eq!(bytes[0], 4);
1305 assert!(
1306 bytes.windows(EXPECTED_ROW.len()).any(|window| window == EXPECTED_ROW),
1307 "serialized debug info did not contain the expected function row",
1308 );
1309
1310 let decoded =
1311 PackageDebugInfo::read_from(&mut miden_core::serde::SliceReader::new(&bytes)).unwrap();
1312 assert_eq!(decoded.functions(), [function]);
1313 }
1314
1315 #[test]
1316 fn test_debug_source_graph_roundtrip() {
1317 let mut builder = PackageDebugInfoBuilder::default();
1318 let child = builder
1319 .add_node(DebugSourceNode {
1320 exec_node: MastNodeId::new_unchecked(0),
1321 children: alloc::vec![],
1322 op_start: 0,
1323 op_end: 1,
1324 asm_ops: alloc::vec![],
1325 debug_vars: alloc::vec![],
1326 inline_calls: alloc::vec![],
1327 })
1328 .unwrap();
1329 let root = builder
1330 .add_node(DebugSourceNode {
1331 exec_node: MastNodeId::new_unchecked(1),
1332 children: alloc::vec![child],
1333 op_start: 1,
1334 op_end: 3,
1335 asm_ops: alloc::vec![],
1336 debug_vars: alloc::vec![],
1337 inline_calls: alloc::vec![],
1338 })
1339 .unwrap();
1340 builder.add_root(root);
1341
1342 let debug_info = *builder.build();
1343 let result = roundtrip_debug_info(&debug_info);
1344 assert_eq!(result.nodes().as_slice(), debug_info.nodes().as_slice());
1345 assert_eq!(result.roots(), debug_info.roots());
1346 }
1347
1348 #[test]
1349 fn test_debug_source_metadata_roundtrip() {
1350 let mut builder = PackageDebugInfoBuilder::default();
1351 let location =
1352 Location::new(Uri::new("file://test.masm"), ByteIndex::new(10), ByteIndex::new(14));
1353 let location_idx = builder.add_location(location);
1354 let file_idx = builder.debug_info().locations()[location_idx].file_idx;
1355 let context_name_idx = builder.add_string("test::ctx");
1356 let op_name_idx = builder.add_string("add");
1357 let var_name_idx = builder.add_string("x");
1358 let function_name_idx = builder.add_string("callee");
1359 let function_idx = builder.add_function(DebugFunctionInfo::new(
1360 None,
1361 function_name_idx,
1362 file_idx,
1363 LineNumber::new(10).unwrap(),
1364 ColumnNumber::new(5).unwrap(),
1365 Word::default(),
1366 ));
1367
1368 let root = builder
1369 .add_node(DebugSourceNode {
1370 exec_node: MastNodeId::new_unchecked(0),
1371 children: alloc::vec![],
1372 op_start: 0,
1373 op_end: 3,
1374 asm_ops: alloc::vec![DebugSourceAsmOp::new(
1375 2,
1376 Some(location_idx),
1377 context_name_idx,
1378 op_name_idx,
1379 1,
1380 )],
1381 debug_vars: alloc::vec![DebugSourceVar {
1382 op_idx: 2,
1383 name_idx: var_name_idx,
1384 type_id: None,
1385 arg_idx: None,
1386 location_idx: None,
1387 value_location: DebugVarLocation::Stack(0),
1388 }],
1389 inline_calls: alloc::vec![DebugSourceInlineCall {
1390 op_idx: 2,
1391 op_end: 3,
1392 callee_idx: function_idx,
1393 loc_idx: location_idx,
1394 }],
1395 })
1396 .unwrap();
1397 builder.add_root(root);
1398
1399 let debug_info = *builder.build();
1400 let result = roundtrip_debug_info(&debug_info);
1401 assert_eq!(result.nodes().as_slice(), debug_info.nodes().as_slice());
1402 assert_eq!(result.locations(), debug_info.locations());
1403 assert_eq!(result.functions(), debug_info.functions());
1404 assert_eq!(result.get_string(context_name_idx).as_deref(), Some("test::ctx"));
1405 assert_eq!(result.get_location(location_idx), debug_info.get_location(location_idx));
1406 }
1407
1408 #[test]
1409 fn test_debug_source_locations_are_deduplicated() {
1410 let mut builder = PackageDebugInfoBuilder::default();
1411 let location =
1412 Location::new(Uri::new("file://test.masm"), ByteIndex::new(10), ByteIndex::new(14));
1413 let first_location_idx = builder.add_location(location.clone());
1414 let second_location_idx = builder.add_location(location);
1415 assert_eq!(first_location_idx, second_location_idx);
1416 assert_eq!(builder.debug_info().locations().len(), 1);
1417
1418 let context_name_idx = builder.add_string("test::ctx");
1419 let push_name_idx = builder.add_string("push.1");
1420 let add_name_idx = builder.add_string("add");
1421 let root = builder
1422 .add_node(DebugSourceNode {
1423 exec_node: MastNodeId::new_unchecked(0),
1424 children: alloc::vec![],
1425 op_start: 0,
1426 op_end: 2,
1427 asm_ops: alloc::vec![
1428 DebugSourceAsmOp::new(
1429 0,
1430 Some(first_location_idx),
1431 context_name_idx,
1432 push_name_idx,
1433 1,
1434 ),
1435 DebugSourceAsmOp::new(
1436 1,
1437 Some(second_location_idx),
1438 context_name_idx,
1439 add_name_idx,
1440 1,
1441 ),
1442 ],
1443 debug_vars: alloc::vec![],
1444 inline_calls: alloc::vec![],
1445 })
1446 .unwrap();
1447 builder.add_root(root);
1448
1449 let debug_info = *builder.build();
1450 let result = roundtrip_debug_info(&debug_info);
1451 assert_eq!(result.locations().len(), 1);
1452 assert_eq!(
1453 result.source_node(root).unwrap().asm_ops,
1454 debug_info.source_node(root).unwrap().asm_ops
1455 );
1456 }
1457
1458 #[test]
1459 fn test_debug_source_strings_are_deduplicated() {
1460 let mut builder = PackageDebugInfoBuilder::default();
1461 let context_name_idx = builder.add_string("test::ctx");
1462 let same_context_name_idx = builder.add_string("test::ctx");
1463 let add_name_idx = builder.add_string("add");
1464 let same_add_name_idx = builder.add_string("add");
1465 let mul_name_idx = builder.add_string("mul");
1466 let other_context_idx = builder.add_string("test::other");
1467 assert_eq!(context_name_idx, same_context_name_idx);
1468 assert_eq!(add_name_idx, same_add_name_idx);
1469
1470 let root = builder
1471 .add_node(DebugSourceNode {
1472 exec_node: MastNodeId::new_unchecked(0),
1473 children: alloc::vec![],
1474 op_start: 0,
1475 op_end: 3,
1476 asm_ops: alloc::vec![
1477 DebugSourceAsmOp::new(0, None, context_name_idx, add_name_idx, 1,),
1478 DebugSourceAsmOp::new(1, None, same_context_name_idx, mul_name_idx, 1,),
1479 DebugSourceAsmOp::new(2, None, other_context_idx, same_add_name_idx, 1,),
1480 ],
1481 debug_vars: alloc::vec![],
1482 inline_calls: alloc::vec![],
1483 })
1484 .unwrap();
1485 builder.add_root(root);
1486
1487 let debug_info = *builder.build();
1488 let result = roundtrip_debug_info(&debug_info);
1489 assert_eq!(result.strings(), debug_info.strings());
1490 assert_eq!(
1491 result.source_node(root).unwrap().asm_ops,
1492 debug_info.source_node(root).unwrap().asm_ops
1493 );
1494 }
1495
1496 #[test]
1497 fn test_debug_error_messages_roundtrip() {
1498 let mut builder = PackageDebugInfoBuilder::default();
1499 assert!(builder.add_error_message(42, Arc::from("assertion message")));
1500
1501 let debug_info = *builder.build();
1502 let result = roundtrip_debug_info(&debug_info);
1503 assert_eq!(result.error_messages(), debug_info.error_messages());
1504 assert_eq!(result.error_message(42).as_deref(), Some("assertion message"));
1505 }
1506
1507 #[test]
1508 fn test_empty_debug_info_roundtrip() {
1509 let debug_info = PackageDebugInfo::default();
1510 let result = roundtrip_debug_info(&debug_info);
1511 assert!(result.strings().is_empty());
1512 assert!(result.files().is_empty());
1513 assert!(result.locations().is_empty());
1514 assert!(result.types().is_empty());
1515 assert!(result.functions().is_empty());
1516 assert!(result.nodes().is_empty());
1517 assert!(result.roots().is_empty());
1518 assert!(result.error_messages().is_empty());
1519 }
1520
1521 #[test]
1522 fn test_all_primitive_types_roundtrip() {
1523 let mut builder = PackageDebugInfoBuilder::default();
1524
1525 for primitive in [
1526 DebugPrimitiveType::Void,
1527 DebugPrimitiveType::Bool,
1528 DebugPrimitiveType::I8,
1529 DebugPrimitiveType::U8,
1530 DebugPrimitiveType::I16,
1531 DebugPrimitiveType::U16,
1532 DebugPrimitiveType::I32,
1533 DebugPrimitiveType::U32,
1534 DebugPrimitiveType::I64,
1535 DebugPrimitiveType::U64,
1536 DebugPrimitiveType::I128,
1537 DebugPrimitiveType::U128,
1538 DebugPrimitiveType::F32,
1539 DebugPrimitiveType::F64,
1540 DebugPrimitiveType::Felt,
1541 DebugPrimitiveType::Word,
1542 DebugPrimitiveType::U256,
1543 ] {
1544 builder.add_type(DebugTypeInfo::Primitive(primitive));
1545 }
1546
1547 let debug_info = *builder.build();
1548 let result = roundtrip_debug_info(&debug_info);
1549 assert_eq!(result.types(), debug_info.types());
1550 }
1551
1552 #[test]
1553 fn test_function_type_roundtrip() {
1554 let ty = DebugTypeInfo::Function {
1555 return_type_idx: Some(DebugTypeIdx::from(0)),
1556 param_type_indices: alloc::vec![
1557 DebugTypeIdx::from(1),
1558 DebugTypeIdx::from(2),
1559 DebugTypeIdx::from(3)
1560 ],
1561 };
1562 roundtrip(&ty);
1563
1564 let void_fn = DebugTypeInfo::Function {
1565 return_type_idx: None,
1566 param_type_indices: alloc::vec![],
1567 };
1568 roundtrip(&void_fn);
1569 }
1570
1571 #[test]
1572 fn test_file_info_with_checksum_roundtrip() {
1573 let file = DebugFileInfo::new(DebugStringIdx::from(0)).with_checksum([42u8; 32]);
1574 roundtrip(&file);
1575 }
1576
1577 #[test]
1578 fn test_debug_info_v2_is_rejected() {
1579 let bytes = [2];
1580 let mut reader = miden_core::serde::SliceReader::new(&bytes);
1581 let error = PackageDebugInfo::read_from(&mut reader).unwrap_err();
1582 let DeserializationError::InvalidValue(message) = error else {
1583 panic!("expected InvalidValue error");
1584 };
1585 assert!(message.contains("unsupported debug_info version: 2"));
1586 }
1587
1588 #[test]
1589 fn inline_range_wire_bytes_are_stable_and_reversed_ranges_are_rejected() {
1590 let row = DebugSourceInlineCall {
1591 op_idx: 2,
1592 op_end: 100_000,
1593 callee_idx: DebugFunctionIdx::from(3),
1594 loc_idx: DebugLocIdx::from(4),
1595 };
1596 let bytes = row.to_bytes();
1597 assert_eq!(bytes, [2, 0, 0, 0, 160, 134, 1, 0, 3, 0, 0, 0, 4, 0, 0, 0]);
1598 assert_eq!(DebugSourceInlineCall::read_from_bytes(&bytes).unwrap(), row);
1599 assert!(row.contains_operation(2));
1600 assert!(row.contains_operation(99_999));
1601 assert!(!row.contains_operation(100_000));
1602 let mut invalid = bytes;
1603 invalid[4..8].copy_from_slice(&1u32.to_le_bytes());
1604 assert!(DebugSourceInlineCall::read_from_bytes(&invalid).is_err());
1605 assert!(PackageDebugInfo::read_from_bytes(&[3]).is_err());
1606 }
1607
1608 #[test]
1609 fn long_inline_ranges_roundtrip_without_expanding_into_operation_rows() {
1610 let mut builder = PackageDebugInfoBuilder::default();
1611 let source_id = builder
1612 .add_node(DebugSourceNode {
1613 exec_node: MastNodeId::new_unchecked(0),
1614 children: Vec::new(),
1615 op_start: 0,
1616 op_end: 1_000_000,
1617 asm_ops: Vec::new(),
1618 debug_vars: Vec::new(),
1619 inline_calls: (0..7)
1620 .map(|index| DebugSourceInlineCall {
1621 op_idx: 0,
1622 op_end: 1_000_000,
1623 callee_idx: DebugFunctionIdx::from(index),
1624 loc_idx: DebugLocIdx::from(index),
1625 })
1626 .collect(),
1627 })
1628 .unwrap();
1629 let bytes = builder.build().to_bytes();
1630 assert!(bytes.len() < 256);
1631 let decoded = PackageDebugInfo::read_from_bytes(&bytes).unwrap();
1632 assert_eq!(decoded.source_node(source_id).unwrap().inline_calls.len(), 7);
1633 assert_eq!(decoded.inline_calls_for_operation(source_id, 999_999).count(), 7);
1634 assert_eq!(decoded.inline_calls_for_operation(source_id, 1_000_000).count(), 0);
1635 }
1636
1637 #[test]
1638 fn test_debug_info_payload_bounds() {
1639 let bytes = PackageDebugInfo::default().to_bytes();
1640
1641 let mut reader = FixedBudgetReader::new(&bytes, 1);
1642 let error = PackageDebugInfo::read_from(&mut reader).unwrap_err();
1643 let DeserializationError::InvalidValue(message) = error else {
1644 panic!("expected InvalidValue error");
1645 };
1646 assert!(message.contains("package debug info"));
1647 assert!(message.contains("exceeds budget"));
1648
1649 let mut reader = FixedBudgetReader::new(&bytes, 1);
1650 let error = PackageDebugInfo::read_from_unmetered(&mut reader).unwrap_err();
1651 let DeserializationError::InvalidValue(message) = error else {
1652 panic!("expected InvalidValue error");
1653 };
1654 assert!(message.contains("package debug info"));
1655 assert!(message.contains("exceeds budget"));
1656
1657 let mut reader = FixedBudgetReader::new(&bytes, bytes.len());
1658 let result = PackageDebugInfo::read_from(&mut reader).unwrap();
1659 assert!(result.nodes().is_empty());
1660 }
1661
1662 #[test]
1663 fn checked_encoding_matches_standard_decoder_limits() {
1664 let mut builder = PackageDebugInfoBuilder::default();
1665 builder.add_string("hello");
1666 builder.add_type(DebugTypeInfo::Primitive(DebugPrimitiveType::Felt));
1667 let debug = builder.build();
1668 let bytes = debug.to_bytes_with_standard_limits().unwrap();
1669 assert_eq!(bytes, debug.to_bytes());
1670 assert_eq!(PackageDebugInfo::read_from_bytes(&bytes).unwrap(), *debug);
1671
1672 for limits in [
1673 PackageDebugInfoDecodeLimits {
1674 payload_size: 0,
1675 ..PackageDebugInfoDecodeLimits::BOUNDED
1676 },
1677 PackageDebugInfoDecodeLimits {
1678 string_rows: 0,
1679 ..PackageDebugInfoDecodeLimits::BOUNDED
1680 },
1681 PackageDebugInfoDecodeLimits {
1682 string_size: 0,
1683 ..PackageDebugInfoDecodeLimits::BOUNDED
1684 },
1685 PackageDebugInfoDecodeLimits {
1686 type_rows: 0,
1687 ..PackageDebugInfoDecodeLimits::BOUNDED
1688 },
1689 ] {
1690 let encode_error = DeserializationError::InvalidValue(
1691 debug.to_bytes_with_limits(limits).unwrap_err().to_string(),
1692 );
1693 let mut reader = miden_core::serde::SliceReader::new(&bytes);
1694 let decode_error =
1695 PackageDebugInfo::read_from_with_limits(&mut reader, limits).unwrap_err();
1696 assert_eq!(encode_error.to_string(), decode_error.to_string());
1697 }
1698 }
1699
1700 #[test]
1701 fn package_debug_info_decodes_merged_dependency_tables() {
1702 const STRING_SIZE: usize = 4096;
1705 const STRING_COUNT: usize = 18 * 1024 * 1024 / STRING_SIZE;
1706 let mut merged = PackageDebugInfoBuilder::default();
1707 for dependency in ['a', 'b'] {
1708 let mut builder = PackageDebugInfoBuilder::default();
1709 for index in 0..STRING_COUNT {
1710 let mut prefix = alloc::format!("{dependency}:{index:04}");
1711 let padding = "x".repeat(STRING_SIZE - prefix.len());
1712 prefix.push_str(&padding);
1713 builder.add_string(prefix);
1714 }
1715 let bytes = builder.build().to_bytes();
1716 let debug = PackageDebugInfo::read_from_bytes(&bytes)
1717 .expect("each dependency's debug tables must be readable");
1718 debug.merge_tables_into(&mut merged).unwrap();
1719 }
1720 let merged = merged.build();
1721 let bytes = merged.to_bytes();
1722 let decoded = PackageDebugInfo::read_from_bytes(&bytes)
1723 .expect("merged dependency debug tables must remain readable");
1724 assert_eq!(decoded.strings().len(), 2 * STRING_COUNT);
1725 assert_eq!(decoded, *merged);
1726 }
1727
1728 #[test]
1729 fn package_debug_info_decodes_merged_dependency_string_rows() {
1730 let mut merged = PackageDebugInfoBuilder::default();
1731 for dependency in ['a', 'b'] {
1732 let mut builder = PackageDebugInfoBuilder::default();
1733 for index in 0..60_000 {
1734 builder.add_string(alloc::format!("{dependency}:{index}"));
1735 }
1736 let bytes = builder.build().to_bytes();
1737 let debug = PackageDebugInfo::read_from_bytes(&bytes).unwrap();
1738 debug.merge_tables_into(&mut merged).unwrap();
1739 }
1740 let merged = merged.build();
1741 let decoded = PackageDebugInfo::read_from_bytes(&merged.to_bytes())
1742 .expect("merged string tables from readable dependencies must remain readable");
1743 assert_eq!(decoded.strings().len(), 120_000);
1744 assert_eq!(decoded, *merged);
1745 }
1746
1747 #[test]
1748 fn package_debug_info_rejects_payload_over_standard_limit() {
1749 let payload_size = MAX_DEBUG_INFO_PAYLOAD_SIZE + 1;
1750 let mut bytes = Vec::new();
1751 bytes.write_u8(DEBUG_INFO_VERSION);
1752 bytes.write_usize(payload_size);
1753 bytes.resize(bytes.len() + payload_size, 0);
1754
1755 let error = PackageDebugInfo::read_from_bytes(&bytes).unwrap_err();
1756 let DeserializationError::InvalidValue(message) = error else {
1757 panic!("expected InvalidValue error");
1758 };
1759 assert!(message.contains("package debug info payload size"), "{message}");
1760 assert!(message.contains("exceeds limit"), "{message}");
1761 }
1762
1763 #[test]
1764 fn unmetered_package_debug_info_decode_ignores_fixed_limits() {
1765 let oversized_string = "x".repeat(MAX_DEBUG_INFO_STRING_SIZE + 1);
1766 let mut builder = PackageDebugInfoBuilder::default();
1767 builder.add_string(oversized_string.clone());
1768 let bytes = builder.build().to_bytes();
1769
1770 let error = PackageDebugInfo::read_from_bytes(&bytes).unwrap_err();
1771 let DeserializationError::InvalidValue(message) = error else {
1772 panic!("expected InvalidValue error");
1773 };
1774 assert!(message.contains("debug string size"));
1775 assert!(message.contains("exceeds limit"));
1776
1777 let decoded = PackageDebugInfo::read_from_bytes_unmetered(&bytes).unwrap();
1778 assert_eq!(decoded.strings().len(), 1);
1779 assert_eq!(decoded.strings()[DebugStringIdx::from(0)].as_ref(), oversized_string);
1780 }
1781
1782 #[test]
1783 fn checked_debug_encoding_matches_normal_encoding_for_readable_data() {
1784 let mut builder = PackageDebugInfoBuilder::default();
1785 builder.add_string("source.rs");
1786 let info = builder.build();
1787 let bytes = info.to_bytes_with_standard_limits().unwrap();
1788 assert_eq!(bytes, info.to_bytes());
1789 assert!(PackageDebugInfo::read_from_bytes(&bytes).is_ok());
1790 }
1791
1792 #[test]
1793 fn checked_debug_encoding_rejects_oversized_strings() {
1794 let mut builder = PackageDebugInfoBuilder::default();
1795 builder.add_string("x".repeat(MAX_DEBUG_INFO_STRING_SIZE + 1));
1796 assert_matches!(
1797 builder.build().to_bytes_with_standard_limits(),
1798 Err(super::super::DebugInfoEncodingError::LimitExceeded {
1799 resource: "debug string size",
1800 ..
1801 })
1802 );
1803 }
1804
1805 #[test]
1806 fn checked_debug_encoding_rejects_oversized_payloads() {
1807 let mut builder = PackageDebugInfoBuilder::default();
1808 for index in 0..((MAX_DEBUG_INFO_PAYLOAD_SIZE / MAX_DEBUG_INFO_STRING_SIZE) + 1) {
1809 let mut string = format!("{index:08}");
1810 string.push_str(&"x".repeat(MAX_DEBUG_INFO_STRING_SIZE - string.len()));
1811 builder.add_string(string);
1812 }
1813 let info = builder.build();
1814 assert_matches!(
1815 info.to_bytes_with_standard_limits(),
1816 Err(super::super::DebugInfoEncodingError::LimitExceeded {
1817 resource: "package debug info payload size",
1818 ..
1819 })
1820 );
1821 assert!(PackageDebugInfo::read_from_bytes(&info.to_bytes()).is_err());
1822 }
1823
1824 #[test]
1825 fn test_debug_info_rejects_truncated_string_table() {
1826 let mut payload = Vec::new();
1827 payload.write_usize(2);
1828
1829 let mut bytes = Vec::new();
1830 bytes.write_u8(DEBUG_INFO_VERSION);
1831 bytes.write_usize(payload.len());
1832 bytes.write_bytes(&payload);
1833
1834 let mut reader = miden_core::serde::SliceReader::new(&bytes);
1835 let error = PackageDebugInfo::read_from(&mut reader).unwrap_err();
1836 let DeserializationError::InvalidValue(message) = error else {
1837 panic!("expected InvalidValue error");
1838 };
1839 assert!(message.contains("debug_info strings count 2"));
1840 assert!(message.contains("exceeds budget"));
1841 }
1842
1843 #[test]
1844 fn test_function_params_bounds() {
1845 let too_many = function_type_bytes(2);
1846 let mut reader = FixedBudgetReader::new(&too_many, 4);
1847 let error = DebugTypeInfo::read_from(&mut reader).unwrap_err();
1848 assert!(matches!(error, DeserializationError::InvalidValue(_)));
1849
1850 let ok = function_type_bytes(1);
1851 let mut reader = FixedBudgetReader::new(&ok, 4);
1852 let ty = DebugTypeInfo::read_from(&mut reader).unwrap();
1853 match ty {
1854 DebugTypeInfo::Function { param_type_indices, .. } => {
1855 assert_eq!(param_type_indices.len(), 1);
1856 },
1857 _ => panic!("expected function type"),
1858 }
1859 }
1860}