1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use crate::error::*;
use crate::mutf8;
use crate::reader::attributes::code;
use crate::reader::attributes::FromAttribute;
use crate::reader::cpool;
use crate::reader::decoding::*;
use crate::MStr;
use std::fmt;
use std::iter::FusedIterator;

#[derive(Clone)]
pub struct StackMapTable<'input> {
    iter: StackMapIter<'input>,
}

impl<'input> StackMapTable<'input> {
    #[must_use]
    pub fn iter(&self) -> StackMapIter<'input> {
        self.iter.clone()
    }
}

impl<'input> DecodeInto<'input> for StackMapTable<'input> {
    fn decode_into(mut decoder: Decoder<'input>) -> Result<Self, DecodeError> {
        let count = decoder.read()?;
        Ok(StackMapTable {
            iter: StackMapIter {
                decoder,
                remaining: count,
                current_offset: 0,
            },
        })
    }
}

impl<'input> FromAttribute<'input> for StackMapTable<'input> {
    const NAME: &'static MStr = mutf8!("StackMapTable");
}

impl<'input> fmt::Debug for StackMapTable<'input> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StackMapTable").finish()
    }
}

#[derive(Clone)]
pub struct StackMapIter<'input> {
    decoder: Decoder<'input>,
    remaining: u16,
    current_offset: u32,
}

impl<'input> Iterator for StackMapIter<'input> {
    type Item = Result<(code::Index, StackMapFrame<'input>), DecodeError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            None
        } else {
            self.remaining -= 1;
            let bytes_remaining = self.decoder.bytes_remaining() as u32;
            let stack_map_frame = decode_stack_map_frame(&mut self.decoder, self.current_offset);
            self.current_offset += bytes_remaining - self.decoder.bytes_remaining() as u32;
            Some(stack_map_frame)
        }
    }
}

impl<'input> FusedIterator for StackMapIter<'input> {}

impl<'input> fmt::Debug for StackMapIter<'input> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StackMapIter").finish()
    }
}

#[derive(Debug, Clone)]
pub enum StackMapFrame<'input> {
    Same,
    SameExtended,
    Same1 {
        stack: VerificationType<'input>,
    },
    Same1Extended {
        stack: VerificationType<'input>,
    },
    Chop {
        to_chop: u8,
    },
    Append {
        locals: VerificationTypeIter<'input>,
    },
    Full {
        locals: VerificationTypeIter<'input>,
        stack: VerificationTypeIter<'input>,
    },
}

fn decode_stack_map_frame<'input>(
    decoder: &mut Decoder<'input>,
    current_offset: u32,
) -> Result<(code::Index, StackMapFrame<'input>), DecodeError> {
    let frame_type: u8 = decoder.read()?;
    match frame_type {
        0..=63 => {
            let index = code::Index::new(frame_type.into());
            Ok((index, StackMapFrame::Same))
        }
        64..=127 => {
            let index = code::Index::new(u32::from(frame_type - 64) + current_offset);
            let stack = decode_verification_type(decoder, current_offset)?;
            Ok((index, StackMapFrame::Same1 { stack }))
        }
        247 => {
            let index = code::Index::new(u32::from(decoder.read::<u16>()?) + current_offset);
            let stack = decode_verification_type(decoder, current_offset)?;
            Ok((index, StackMapFrame::Same1 { stack }))
        }
        248..=250 => {
            let to_chop = 251 - frame_type;
            let index = code::Index::new(u32::from(decoder.read::<u16>()?) + current_offset);
            Ok((index, StackMapFrame::Chop { to_chop }))
        }
        251 => {
            let index = code::Index::new(u32::from(decoder.read::<u16>()?) + current_offset);
            Ok((index, StackMapFrame::SameExtended))
        }
        252..=254 => {
            let index = code::Index::new(u32::from(decoder.read::<u16>()?) + current_offset);
            let locals = VerificationTypeIter::new(decoder, (frame_type - 251).into(), current_offset)?;
            Ok((index, StackMapFrame::Append { locals }))
        }
        255 => {
            let index = code::Index::new(u32::from(decoder.read::<u16>()?) + current_offset);

            let local_count = decoder.read()?;
            let locals = VerificationTypeIter::new(decoder, local_count, current_offset)?;

            let stack_count = decoder.read()?;
            let stack = VerificationTypeIter::new(decoder, stack_count, current_offset)?;

            Ok((index, StackMapFrame::Full { locals, stack }))
        }
        _ => Err(DecodeError::from_decoder(DecodeErrorKind::TagReserved, decoder)),
    }
}

#[derive(Debug, Copy, Clone)]
pub enum VerificationType<'input> {
    Top,
    Null,
    UninitializedThis,
    Object(cpool::Index<cpool::Class<'input>>),
    UninitializedVariable(code::Index),
    Integer,
    Long,
    Float,
    Double,
}

fn decode_verification_type<'input>(
    decoder: &mut Decoder<'input>,
    current_offset: u32,
) -> Result<VerificationType<'input>, DecodeError> {
    let tag: u8 = decoder.read()?;
    match tag {
        0x00 => Ok(VerificationType::Top),
        0x01 => Ok(VerificationType::Integer),
        0x02 => Ok(VerificationType::Float),
        0x03 => Ok(VerificationType::Double),
        0x04 => Ok(VerificationType::Long),
        0x05 => Ok(VerificationType::Null),
        0x06 => Ok(VerificationType::UninitializedThis),
        0x07 => Ok(VerificationType::Object(decoder.read()?)),
        0x08 => {
            let index = code::Index::new(current_offset + u32::from(decoder.read::<u16>()?));
            Ok(VerificationType::UninitializedVariable(index))
        }
        _ => Err(DecodeError::from_decoder(DecodeErrorKind::InvalidTag, decoder)),
    }
}

fn skip_verification_type<'input>(decoder: &mut Decoder<'input>) -> Result<(), DecodeError> {
    let tag: u8 = decoder.read()?;
    match tag {
        0x07 => {
            decoder.read::<cpool::Index<cpool::Class<'input>>>()?;
            Ok(())
        }
        0x08 => {
            decoder.read::<u16>()?;
            Ok(())
        }
        _ if tag < 0x07 => Ok(()),
        _ => Err(DecodeError::from_decoder(DecodeErrorKind::InvalidTag, decoder)),
    }
}

#[derive(Clone)]
pub struct VerificationTypeIter<'input> {
    decoder: Decoder<'input>,
    remaining: u16,
    current_offset: u32,
}

impl<'input> VerificationTypeIter<'input> {
    fn new(
        decoder: &mut Decoder<'input>,
        count: u16,
        current_offset: u32,
    ) -> Result<VerificationTypeIter<'input>, DecodeError> {
        let old_decoder = decoder.clone();
        for _ in 0..count {
            skip_verification_type(decoder)?;
        }
        Ok(VerificationTypeIter {
            decoder: old_decoder,
            remaining: count,
            current_offset,
        })
    }
}

impl<'input> Iterator for VerificationTypeIter<'input> {
    type Item = Result<VerificationType<'input>, DecodeError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            None
        } else {
            self.remaining -= 1;
            let bytes_remaining = self.decoder.bytes_remaining() as u32;
            let verification_type = decode_verification_type(&mut self.decoder, self.current_offset);
            self.current_offset += bytes_remaining - self.decoder.bytes_remaining() as u32;
            Some(verification_type)
        }
    }
}

impl<'input> fmt::Debug for VerificationTypeIter<'input> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VerificationTypeIter").finish()
    }
}