Skip to main content

foundry_evm_symbolic/runtime/
bytes.rs

1use super::{expr::hashcons::HashConsed, *};
2
3#[derive(Clone, PartialEq, Eq, Hash)]
4pub(crate) struct SymBytes {
5    pub(in crate::runtime) kind: HashConsed<SymBytesKind>,
6}
7
8impl fmt::Debug for SymBytes {
9    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10        self.kind().fmt(f)
11    }
12}
13
14#[derive(Debug, PartialEq, Eq, Hash)]
15pub(in crate::runtime) enum SymBytesKind {
16    Concrete(Vec<u8>),
17    Exprs(Vec<SymExpr>),
18    Word(SymExpr),
19    Concat(Vec<SymBytes>),
20    Slice { bytes: SymBytes, offset: SymExpr, len: usize },
21    Sized { bytes: SymBytes, size: SymExpr, max_size: usize },
22}
23
24impl SymBytes {
25    fn from_kind(cx: &mut SymCx, kind: SymBytesKind) -> Self {
26        cx.mk_bytes_kind(kind)
27    }
28
29    /// Returns the bytes a sized buffer was cut from, whose bytes past the size are not zeroed.
30    pub(crate) fn without_size(&self) -> Self {
31        match self.kind() {
32            SymBytesKind::Sized { bytes, .. } => bytes.without_size(),
33            _ => self.clone(),
34        }
35    }
36
37    fn kind(&self) -> &SymBytesKind {
38        self.kind.value()
39    }
40
41    pub(crate) fn empty(cx: &mut SymCx) -> Self {
42        Self::concrete(cx, Vec::new())
43    }
44
45    pub(crate) fn concrete(cx: &mut SymCx, bytes: Vec<u8>) -> Self {
46        Self::from_kind(cx, SymBytesKind::Concrete(bytes))
47    }
48
49    pub(crate) fn as_concrete_slice(&self) -> Option<&[u8]> {
50        match self.kind() {
51            SymBytesKind::Concrete(bytes) => Some(bytes),
52            _ => None,
53        }
54    }
55
56    pub(crate) fn exprs(cx: &mut SymCx, bytes: Vec<SymExpr>) -> Self {
57        if let Ok(concrete) = concrete_expr_bytes(&bytes, "symbolic bytes") {
58            Self::concrete(cx, concrete)
59        } else {
60            Self::from_kind(cx, SymBytesKind::Exprs(bytes))
61        }
62    }
63
64    pub(crate) fn word(cx: &mut SymCx, word: SymExpr) -> Self {
65        if let Some(word) = word.as_const() {
66            Self::concrete(cx, word.to_be_bytes::<32>().to_vec())
67        } else {
68            Self::from_kind(cx, SymBytesKind::Word(word))
69        }
70    }
71
72    pub(crate) fn concat(cx: &mut SymCx, bytes: impl IntoIterator<Item = Self>) -> Self {
73        let mut out = Vec::new();
74        for bytes in bytes {
75            match bytes.kind() {
76                SymBytesKind::Concrete(values) if values.is_empty() => {}
77                SymBytesKind::Concat(values) => out.extend(values.iter().cloned()),
78                _ => out.push(bytes),
79            }
80        }
81        match out.len() {
82            0 => Self::empty(cx),
83            1 => out.pop().expect("single item exists"),
84            _ => Self::from_kind(cx, SymBytesKind::Concat(out)),
85        }
86    }
87
88    pub(crate) fn slice(cx: &mut SymCx, bytes: Self, offset: SymExpr, len: usize) -> Self {
89        if len == 0 {
90            return Self::empty(cx);
91        }
92        if let Some(offset) = offset.eval() {
93            let Ok(offset) = usize::try_from(offset) else {
94                return Self::concrete(cx, vec![0; len]);
95            };
96            return bytes.slice_concrete(cx, offset, len);
97        }
98        Self::slice_node(cx, bytes, offset, len)
99    }
100
101    fn slice_node(cx: &mut SymCx, bytes: Self, offset: SymExpr, len: usize) -> Self {
102        Self::from_kind(cx, SymBytesKind::Slice { bytes, offset, len })
103    }
104
105    pub(crate) fn sized(cx: &mut SymCx, bytes: Self, size: SymExpr, max_size: usize) -> Self {
106        if max_size == 0 {
107            return Self::empty(cx);
108        }
109        if let Some(size) = size.eval() {
110            let size = usize::try_from(size).map_or(max_size, |size| size.min(max_size));
111            let bytes = bytes.slice_concrete(cx, 0, size);
112            let padding = Self::concrete(cx, vec![0; max_size - size]);
113            return Self::concat(cx, [bytes, padding]);
114        }
115        Self::from_kind(cx, SymBytesKind::Sized { bytes, size, max_size })
116    }
117
118    pub(crate) fn len(&self) -> usize {
119        match self.kind() {
120            SymBytesKind::Concrete(bytes) => bytes.len(),
121            SymBytesKind::Exprs(bytes) => bytes.len(),
122            SymBytesKind::Word(_) => 32,
123            SymBytesKind::Concat(values) => {
124                values.iter().fold(0usize, |len, bytes| len.saturating_add(bytes.len()))
125            }
126            SymBytesKind::Slice { len, .. } => *len,
127            SymBytesKind::Sized { max_size, .. } => *max_size,
128        }
129    }
130
131    pub(crate) fn is_empty(&self) -> bool {
132        self.len() == 0
133    }
134
135    pub(crate) fn byte(&self, cx: &mut SymCx, offset: usize) -> SymExpr {
136        match self.kind() {
137            SymBytesKind::Concrete(bytes) => bytes
138                .get(offset)
139                .copied()
140                .map(|byte| SymExpr::constant(cx, U256::from(byte)))
141                .unwrap_or_else(|| SymExpr::zero(cx)),
142            SymBytesKind::Exprs(bytes) => {
143                bytes.get(offset).cloned().unwrap_or_else(|| SymExpr::zero(cx))
144            }
145            SymBytesKind::Word(word) => {
146                if offset >= 32 {
147                    SymExpr::zero(cx)
148                } else if let Some(byte) = word.known_byte(offset) {
149                    SymExpr::constant(cx, U256::from(byte))
150                } else {
151                    word.extracted_byte(cx, offset)
152                }
153            }
154            SymBytesKind::Concat(values) => {
155                let mut offset = offset;
156                for bytes in values {
157                    if offset < bytes.len() {
158                        return bytes.byte(cx, offset);
159                    }
160                    offset = offset.saturating_sub(bytes.len());
161                }
162                SymExpr::zero(cx)
163            }
164            SymBytesKind::Slice { bytes, offset: base_offset, len } => {
165                if offset >= *len {
166                    SymExpr::zero(cx)
167                } else if let Some(base_offset) = base_offset.eval() {
168                    let Ok(base_offset) = usize::try_from(base_offset) else {
169                        return SymExpr::zero(cx);
170                    };
171                    let Some(offset) = base_offset.checked_add(offset) else {
172                        return SymExpr::zero(cx);
173                    };
174                    bytes.byte(cx, offset)
175                } else {
176                    bytes.byte_dynamic_with_delta(cx, base_offset, offset)
177                }
178            }
179            SymBytesKind::Sized { bytes, size, max_size } => {
180                if offset >= *max_size {
181                    return SymExpr::zero(cx);
182                }
183                let source = bytes.byte(cx, offset);
184                let offset = SymExpr::constant(cx, U256::from(offset));
185                let condition = SymBoolExpr::cmp(cx, SymCmpOp::Ult, offset, size.clone());
186                let zero = SymExpr::zero(cx);
187                SymExpr::ite(cx, condition, source, zero)
188            }
189        }
190    }
191
192    pub(crate) fn byte_dynamic_with_delta(
193        &self,
194        cx: &mut SymCx,
195        offset: &SymExpr,
196        delta: usize,
197    ) -> SymExpr {
198        let mut result = SymExpr::zero(cx);
199        for candidate in (delta..self.len()).rev() {
200            let candidate_offset = candidate - delta;
201            let candidate_expr = SymExpr::constant(cx, U256::from(candidate_offset));
202            let condition = SymBoolExpr::eq(cx, offset.clone(), candidate_expr);
203            let byte = self.byte(cx, candidate);
204            result = SymExpr::ite(cx, condition, byte, result);
205        }
206        result
207    }
208
209    pub(crate) fn slice_concrete(&self, cx: &mut SymCx, offset: usize, len: usize) -> Self {
210        if len == 0 {
211            return Self::empty(cx);
212        }
213        let self_len = self.len();
214        // Bytes past the end read as zero; this also keeps `offset + idx` below from overflowing.
215        if offset >= self_len {
216            return Self::concrete(cx, vec![0; len]);
217        }
218        if offset == 0 && len == self_len {
219            return self.clone();
220        }
221        match self.kind() {
222            SymBytesKind::Concrete(bytes) => {
223                let out = if offset.checked_add(len).is_some_and(|end| end <= bytes.len()) {
224                    bytes[offset..offset + len].to_vec()
225                } else {
226                    (0..len)
227                        .map(|idx| bytes.get(offset + idx).copied().unwrap_or_default())
228                        .collect()
229                };
230                Self::concrete(cx, out)
231            }
232            SymBytesKind::Exprs(bytes) => {
233                let bytes = (0..len)
234                    .map(|idx| {
235                        bytes.get(offset + idx).cloned().unwrap_or_else(|| SymExpr::zero(cx))
236                    })
237                    .collect();
238                Self::exprs(cx, bytes)
239            }
240            SymBytesKind::Word(word) if offset == 0 && len == 32 => Self::word(cx, word.clone()),
241            SymBytesKind::Word(_) | SymBytesKind::Sized { .. } => {
242                let offset = SymExpr::constant(cx, U256::from(offset));
243                Self::slice_node(cx, self.clone(), offset, len)
244            }
245            SymBytesKind::Slice { bytes, offset: base_offset, .. } => {
246                if let Some(base_offset) = base_offset.eval()
247                    && let Ok(base_offset) = usize::try_from(base_offset)
248                    && let Some(offset) = base_offset.checked_add(offset)
249                {
250                    bytes.slice_concrete(cx, offset, len)
251                } else {
252                    let offset = SymExpr::constant(cx, U256::from(offset));
253                    Self::slice_node(cx, self.clone(), offset, len)
254                }
255            }
256            SymBytesKind::Concat(values) => {
257                let mut offset = offset;
258                let mut len = len;
259                let mut out = Vec::new();
260                for bytes in values {
261                    if len == 0 {
262                        break;
263                    }
264
265                    let bytes_len = bytes.len();
266                    if offset >= bytes_len {
267                        offset -= bytes_len;
268                        continue;
269                    }
270
271                    let take = (bytes_len - offset).min(len);
272                    if offset == 0 && take == bytes_len {
273                        out.push(bytes.clone());
274                    } else {
275                        out.push(bytes.slice_concrete(cx, offset, take));
276                    }
277                    len -= take;
278                    offset = 0;
279                }
280
281                if len != 0 {
282                    out.push(Self::concrete(cx, vec![0; len]));
283                }
284                Self::concat(cx, out)
285            }
286        }
287    }
288
289    pub(crate) fn read_offset(&self, cx: &mut SymCx, offset: SymExpr, len: usize) -> Self {
290        Self::slice(cx, self.clone(), offset, len)
291    }
292
293    pub(crate) fn word_at(&self, cx: &mut SymCx, offset: usize) -> SymExpr {
294        if offset >= self.len() {
295            return SymExpr::zero(cx);
296        }
297        if let Some(word) = self.word_fragment_at(cx, offset, 32, 0) {
298            return word;
299        }
300
301        match self.kind() {
302            SymBytesKind::Concrete(bytes) => {
303                let mut word = [0u8; 32];
304                if offset < bytes.len() {
305                    let take = (bytes.len() - offset).min(32);
306                    word[..take].copy_from_slice(&bytes[offset..offset + take]);
307                }
308                SymExpr::constant(cx, U256::from_be_bytes(word))
309            }
310            SymBytesKind::Exprs(bytes) => {
311                let bytes = (0..32)
312                    .map(|idx| {
313                        bytes.get(offset + idx).cloned().unwrap_or_else(|| SymExpr::zero(cx))
314                    })
315                    .collect::<Vec<_>>();
316                SymExpr::from_bytes(cx, bytes)
317            }
318            SymBytesKind::Word(word) if offset == 0 => word.clone(),
319            SymBytesKind::Word(_) if offset >= 32 => SymExpr::zero(cx),
320            SymBytesKind::Slice { bytes, offset: base_offset, len } => {
321                if offset.checked_add(32).is_some_and(|end| end <= *len)
322                    && let Some(base_offset) = base_offset.eval()
323                    && let Ok(base_offset) = usize::try_from(base_offset)
324                    && let Some(base_offset) = base_offset.checked_add(offset)
325                {
326                    return bytes.word_at(cx, base_offset);
327                }
328                let bytes = (0..32).map(|idx| self.byte(cx, offset + idx)).collect::<Vec<_>>();
329                SymExpr::from_bytes(cx, bytes)
330            }
331            _ => {
332                let bytes = (0..32).map(|idx| self.byte(cx, offset + idx)).collect::<Vec<_>>();
333                SymExpr::from_bytes(cx, bytes)
334            }
335        }
336    }
337
338    pub(crate) fn right_aligned_word(&self, cx: &mut SymCx, offset: usize, len: usize) -> SymExpr {
339        debug_assert!(len <= 32);
340        let len = len.min(32);
341        if offset >= self.len() {
342            return SymExpr::zero(cx);
343        }
344        if let Some(word) = self.word_fragment_at(cx, offset, len, 32 - len) {
345            return word;
346        }
347
348        let mut bytes = Vec::with_capacity(32);
349        for _ in 0..32 - len {
350            bytes.push(SymExpr::zero(cx));
351        }
352        bytes.extend((0..len).map(|idx| self.byte(cx, offset + idx)));
353        SymExpr::from_bytes(cx, bytes)
354    }
355
356    fn word_fragment_at(
357        &self,
358        cx: &mut SymCx,
359        offset: usize,
360        len: usize,
361        out_offset: usize,
362    ) -> Option<SymExpr> {
363        debug_assert!(len <= 32);
364        debug_assert!(out_offset <= 32);
365        debug_assert!(out_offset + len <= 32);
366
367        if len == 0 {
368            return Some(SymExpr::zero(cx));
369        }
370
371        match self.kind() {
372            SymBytesKind::Concrete(bytes) => {
373                let mut word = [0u8; 32];
374                if offset < bytes.len() {
375                    let take = (bytes.len() - offset).min(len);
376                    word[out_offset..out_offset + take]
377                        .copy_from_slice(&bytes[offset..offset + take]);
378                }
379                Some(SymExpr::constant(cx, U256::from_be_bytes(word)))
380            }
381            SymBytesKind::Word(word) => {
382                Self::word_expr_fragment(cx, word.clone(), offset, len, out_offset)
383            }
384            SymBytesKind::Slice { bytes, offset: base_offset, len: slice_len } => {
385                let available = slice_len.saturating_sub(offset).min(len);
386                if available == 0 {
387                    return Some(SymExpr::zero(cx));
388                }
389                let base_offset =
390                    base_offset.eval().and_then(|offset| usize::try_from(offset).ok())?;
391                bytes.word_fragment_at(cx, base_offset.checked_add(offset)?, available, out_offset)
392            }
393            SymBytesKind::Concat(values) => {
394                let mut offset = offset;
395                let mut out_offset = out_offset;
396                let mut remaining = len;
397                let mut out = SymExpr::zero(cx);
398
399                for bytes in values {
400                    if remaining == 0 {
401                        break;
402                    }
403
404                    let bytes_len = bytes.len();
405                    if offset >= bytes_len {
406                        offset -= bytes_len;
407                        continue;
408                    }
409
410                    let take = (bytes_len - offset).min(remaining);
411                    let fragment = bytes.word_fragment_at(cx, offset, take, out_offset)?;
412                    out = SymExpr::binop(cx, SymBinOp::Or, out, fragment);
413                    out_offset += take;
414                    remaining -= take;
415                    offset = 0;
416                }
417
418                Some(out)
419            }
420            SymBytesKind::Exprs(_) | SymBytesKind::Sized { .. } => None,
421        }
422    }
423
424    fn word_expr_fragment(
425        cx: &mut SymCx,
426        word: SymExpr,
427        offset: usize,
428        len: usize,
429        out_offset: usize,
430    ) -> Option<SymExpr> {
431        let len = 32usize.checked_sub(offset)?.min(len);
432        if len == 0 {
433            return Some(SymExpr::zero(cx));
434        }
435        if offset == 0 && len == 32 && out_offset == 0 {
436            return Some(word);
437        }
438
439        let src_trailing_bits = (32 - (offset + len)) * 8;
440        let dst_trailing_bits = (32 - (out_offset + len)) * 8;
441        let mask = mask_bits(U256::MAX, len * 8);
442
443        let src_trailing_bits = SymExpr::constant(cx, U256::from(src_trailing_bits));
444        let expr = SymExpr::binop(cx, SymBinOp::Shr, word, src_trailing_bits);
445        let mask = SymExpr::constant(cx, mask);
446        let expr = SymExpr::binop(cx, SymBinOp::And, expr, mask);
447        let dst_trailing_bits = SymExpr::constant(cx, U256::from(dst_trailing_bits));
448        Some(SymExpr::binop(cx, SymBinOp::Shl, expr, dst_trailing_bits))
449    }
450
451    /// Returns `true` if the observable bytes depend on an unresolved `GAS` / `gasleft()` value.
452    ///
453    /// Only the represented byte range is inspected: bytes of a backing value that a slice or a
454    /// `max_size` bound excludes are never reachable and do not taint the result. A gas-dependent
455    /// slice offset or dynamic size always taints, because the byte layout itself would then
456    /// depend on gas.
457    pub(crate) fn contains_gasleft(&self, cx: &mut SymCx) -> bool {
458        if self.shape_depends_on_gasleft() {
459            return true;
460        }
461        // Fast structural pre-check: without a gas-dependent backing value nothing can be tainted.
462        if !self.backing_contains_gasleft() {
463            return false;
464        }
465        (0..self.len()).any(|offset| self.byte(cx, offset).contains_gasleft())
466    }
467
468    /// Returns `true` if a slice offset or dynamic size anywhere in the tree mentions `gasleft()`.
469    fn shape_depends_on_gasleft(&self) -> bool {
470        match self.kind() {
471            SymBytesKind::Concrete(_) | SymBytesKind::Exprs(_) | SymBytesKind::Word(_) => false,
472            SymBytesKind::Concat(parts) => parts.iter().any(Self::shape_depends_on_gasleft),
473            SymBytesKind::Slice { bytes, offset, .. } => {
474                offset.contains_gasleft() || bytes.shape_depends_on_gasleft()
475            }
476            SymBytesKind::Sized { bytes, size, .. } => {
477                size.contains_gasleft() || bytes.shape_depends_on_gasleft()
478            }
479        }
480    }
481
482    /// Returns `true` if any backing value, observable or not, mentions `gasleft()`.
483    fn backing_contains_gasleft(&self) -> bool {
484        match self.kind() {
485            SymBytesKind::Concrete(_) => false,
486            SymBytesKind::Exprs(bytes) => bytes.iter().any(SymExpr::contains_gasleft),
487            SymBytesKind::Word(word) => word.contains_gasleft(),
488            SymBytesKind::Concat(parts) => parts.iter().any(Self::backing_contains_gasleft),
489            SymBytesKind::Slice { bytes, .. } | SymBytesKind::Sized { bytes, .. } => {
490                bytes.backing_contains_gasleft()
491            }
492        }
493    }
494
495    pub(crate) fn materialize(&self, cx: &mut SymCx) -> Vec<SymExpr> {
496        (0..self.len()).map(|idx| self.byte(cx, idx)).collect()
497    }
498
499    pub(crate) fn same_bytes(&self, cx: &mut SymCx, other: &Self) -> bool {
500        self.len() == other.len()
501            && (0..self.len()).all(|idx| self.byte(cx, idx) == other.byte(cx, idx))
502    }
503
504    pub(crate) fn prefix_condition(&self, cx: &mut SymCx, prefix: &Self) -> Option<SymBoolExpr> {
505        if prefix.len() > self.len() {
506            return None;
507        }
508        let mut conditions = Vec::new();
509        for idx in 0..prefix.len() {
510            let actual = self.byte(cx, idx);
511            let expected = prefix.byte(cx, idx);
512            if actual == expected {
513                continue;
514            }
515            match (actual.as_const(), expected.as_const()) {
516                (Some(actual), Some(expected)) if actual.to::<u8>() == expected.to::<u8>() => {}
517                (Some(_), Some(_)) => return None,
518                _ => conditions.push(SymBoolExpr::eq(cx, actual, expected)),
519            }
520        }
521        Some(SymBoolExpr::and(cx, conditions))
522    }
523
524    pub(crate) fn eval_model<M: SymbolicModelLookup + ?Sized>(
525        &self,
526        cx: &mut SymCx,
527        model: &M,
528    ) -> Result<Vec<u8>, SymbolicError> {
529        match self.kind() {
530            SymBytesKind::Concrete(bytes) => Ok(bytes.clone()),
531            _ => (0..self.len())
532                .map(|idx| Ok(self.byte(cx, idx).eval_model(model)?.to::<u8>()))
533                .collect(),
534        }
535    }
536
537    pub(crate) fn concrete_bytes(
538        &self,
539        cx: &mut SymCx,
540        reason: &'static str,
541    ) -> Result<Vec<u8>, SymbolicError> {
542        let mut out = Vec::with_capacity(self.len());
543        self.append_concrete_range(cx, 0, self.len(), &mut out, reason)?;
544        Ok(out)
545    }
546
547    fn append_concrete_range(
548        &self,
549        cx: &mut SymCx,
550        mut offset: usize,
551        mut len: usize,
552        out: &mut Vec<u8>,
553        reason: &'static str,
554    ) -> Result<(), SymbolicError> {
555        if len == 0 {
556            return Ok(());
557        }
558
559        match self.kind() {
560            SymBytesKind::Concrete(bytes) => {
561                if offset >= bytes.len() {
562                    out.resize(out.len() + len, 0);
563                    return Ok(());
564                }
565
566                let take = (bytes.len() - offset).min(len);
567                out.extend_from_slice(&bytes[offset..offset + take]);
568                if len > take {
569                    out.resize(out.len() + len - take, 0);
570                }
571            }
572            SymBytesKind::Exprs(bytes) => {
573                for idx in 0..len {
574                    let Some(byte) = offset.checked_add(idx).and_then(|idx| bytes.get(idx)) else {
575                        out.push(0);
576                        continue;
577                    };
578                    let Some(byte) = byte.as_const() else {
579                        return Err(SymbolicError::Unsupported(reason));
580                    };
581                    out.push(byte.to::<u8>());
582                }
583            }
584            SymBytesKind::Concat(values) => {
585                for bytes in values {
586                    if len == 0 {
587                        break;
588                    }
589
590                    let bytes_len = bytes.len();
591                    if offset >= bytes_len {
592                        offset -= bytes_len;
593                        continue;
594                    }
595
596                    let take = (bytes_len - offset).min(len);
597                    bytes.append_concrete_range(cx, offset, take, out, reason)?;
598                    len -= take;
599                    offset = 0;
600                }
601
602                if len != 0 {
603                    out.resize(out.len() + len, 0);
604                }
605            }
606            SymBytesKind::Slice { bytes, offset: base_offset, len: slice_len } => {
607                if offset >= *slice_len {
608                    out.resize(out.len() + len, 0);
609                    return Ok(());
610                }
611
612                let take = (*slice_len - offset).min(len);
613                if let Some(base_offset) = base_offset.eval()
614                    && let Ok(base_offset) = usize::try_from(base_offset)
615                    && let Some(offset) = base_offset.checked_add(offset)
616                {
617                    bytes.append_concrete_range(cx, offset, take, out, reason)?;
618                    if len > take {
619                        out.resize(out.len() + len - take, 0);
620                    }
621                } else {
622                    let bytes = self.slice_concrete(cx, offset, len).materialize(cx);
623                    out.extend(concrete_expr_bytes(&bytes, reason)?);
624                }
625            }
626            _ => {
627                let bytes = self.slice_concrete(cx, offset, len).materialize(cx);
628                out.extend(concrete_expr_bytes(&bytes, reason)?);
629            }
630        }
631        Ok(())
632    }
633}