sim-codec-classfile 0.1.0

Bounded, lossless Java Virtual Machine classfile codec for SIM
Documentation
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/// A stable structured-attribute failure category.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AttributeErrorKind {
    /// The bounded byte lane rejected the input or output.
    Bytes,
    /// A reserved stack-map frame tag or verification-type tag was encountered.
    ReservedTag,
    /// An attribute body contained trailing bytes.
    TrailingBytes,
    /// A collection cannot be represented by its classfile count field.
    CountOverflow,
    /// A locally checkable attribute constraint is invalid.
    StaticConstraint,
    /// A nested annotation value exceeded the caller's structural budget.
    NestingBudgetExceeded,
}
/// A located structured-attribute format error.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttributeError {
    /// Stable machine-matchable failure category.
    pub kind: AttributeErrorKind,
    /// Absolute byte offset at which the failure was detected.
    pub offset: usize,
    /// Human-readable context.
    pub message: String,
}

impl fmt::Display for AttributeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} at byte {}", self.message, self.offset)
    }
}

impl std::error::Error for AttributeError {}

impl From<ByteError> for AttributeError {
    fn from(value: ByteError) -> Self {
        Self {
            kind: AttributeErrorKind::Bytes,
            offset: value.offset,
            message: value.message,
        }
    }
}

fn error(kind: AttributeErrorKind, offset: usize, message: impl Into<String>) -> AttributeError {
    AttributeError {
        kind,
        offset,
        message: message.into(),
    }
}

fn finish(reader: &ByteReader<'_>) -> Result<(), AttributeError> {
    if reader.remaining() == 0 {
        Ok(())
    } else {
        Err(error(
            AttributeErrorKind::TrailingBytes,
            reader.offset(),
            format!("{} trailing attribute bytes", reader.remaining()),
        ))
    }
}

fn count(value: usize, what: &str) -> Result<u16, AttributeError> {
    u16::try_from(value).map_err(|_| {
        error(
            AttributeErrorKind::CountOverflow,
            0,
            format!("too many {what}"),
        )
    })
}

fn read_u2s(reader: &mut ByteReader<'_>, what: &str) -> Result<Vec<u16>, AttributeError> {
    let n = usize::from(reader.read_u2()?);
    reader.preflight_allocation(n)?;
    let mut values = Vec::with_capacity(n);
    for _ in 0..n {
        values.push(reader.read_u2()?);
    }
    finish(reader)?;
    let _ = what;
    Ok(values)
}

fn write_u2s(values: &[u16], budget: usize, what: &str) -> Result<Vec<u8>, AttributeError> {
    let mut out = ByteWriter::new(budget);
    out.write_u2(count(values.len(), what)?)?;
    for value in values {
        out.write_u2(*value)?;
    }
    Ok(out.into_bytes())
}

/// A standard attribute whose payload is exactly one unresolved constant-pool index.
///
/// This represents `ConstantValue`, `Signature`, `SourceFile`, `NestHost`, and
/// `ModuleMainClass` metadata.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct IndexAttribute {
    /// The unresolved constant-pool index.
    pub index: u16,
}

impl IndexAttribute {
    /// Decode the exact two-byte payload.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        let index = reader.read_u2()?;
        finish(reader)?;
        Ok(Self { index })
    }

    /// Encode the index without inspecting its target.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        let mut out = ByteWriter::new(budget);
        out.write_u2(self.index)?;
        Ok(out.into_bytes())
    }
}

/// A marker attribute (`Synthetic` or `Deprecated`), whose payload must be empty.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct MarkerAttribute;

impl MarkerAttribute {
    /// Accept only an empty bounded payload.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        finish(reader)?;
        Ok(Self)
    }

    /// Encode the empty payload.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        Ok(ByteWriter::new(budget).into_bytes())
    }
}

/// An opaque byte payload, used by `SourceDebugExtension`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ByteAttribute {
    /// Exact bytes, without text decoding or newline normalization.
    pub bytes: Vec<u8>,
}

impl ByteAttribute {
    /// Retain all remaining bytes.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        let bytes = reader.take(reader.remaining())?.to_vec();
        Ok(Self { bytes })
    }

    /// Encode the retained bytes exactly.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        let mut out = ByteWriter::new(budget);
        out.write_bytes(&self.bytes)?;
        Ok(out.into_bytes())
    }
}

/// An ordered list of unresolved indices (`Exceptions`, `NestMembers`,
/// `PermittedSubclasses`, or `ModulePackages`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IndexListAttribute {
    /// Indices in classfile order.
    pub indices: Vec<u16>,
}

impl IndexListAttribute {
    /// Decode an unsigned-short-counted index list.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        Ok(Self {
            indices: read_u2s(reader, "indices")?,
        })
    }

    /// Encode the list without sorting or deduplication.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        write_u2s(&self.indices, budget, "indices")
    }
}

/// One `InnerClasses` table row.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InnerClass {
    /// Class index for the nested class.
    pub inner_class_index: u16,
    /// Enclosing class index, or zero.
    pub outer_class_index: u16,
    /// Simple-name index, or zero for anonymous classes.
    pub inner_name_index: u16,
    /// Raw inner-class access flags.
    pub access_flags: u16,
}

/// The ordered `InnerClasses` payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InnerClassesAttribute {
    /// Rows in declaration order.
    pub classes: Vec<InnerClass>,
}

impl InnerClassesAttribute {
    /// Decode all rows without resolving their indices.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        let n = usize::from(reader.read_u2()?);
        reader.preflight_allocation(n)?;
        let mut classes = Vec::with_capacity(n);
        for _ in 0..n {
            classes.push(InnerClass {
                inner_class_index: reader.read_u2()?,
                outer_class_index: reader.read_u2()?,
                inner_name_index: reader.read_u2()?,
                access_flags: reader.read_u2()?,
            });
        }
        finish(reader)?;
        Ok(Self { classes })
    }
    /// Encode rows exactly as stored.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        let mut out = ByteWriter::new(budget);
        out.write_u2(count(self.classes.len(), "inner classes")?)?;
        for v in &self.classes {
            out.write_u2(v.inner_class_index)?;
            out.write_u2(v.outer_class_index)?;
            out.write_u2(v.inner_name_index)?;
            out.write_u2(v.access_flags)?;
        }
        Ok(out.into_bytes())
    }
}

/// The `EnclosingMethod` payload; a zero method index denotes no specific method.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EnclosingMethodAttribute {
    /// Enclosing class index.
    pub class_index: u16,
    /// Name-and-type index, or zero.
    pub method_index: u16,
}

impl EnclosingMethodAttribute {
    /// Decode the two unresolved indices.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        let class_index = reader.read_u2()?;
        let method_index = reader.read_u2()?;
        finish(reader)?;
        Ok(Self {
            class_index,
            method_index,
        })
    }
    /// Encode the two indices.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        let mut out = ByteWriter::new(budget);
        out.write_u2(self.class_index)?;
        out.write_u2(self.method_index)?;
        Ok(out.into_bytes())
    }
}

/// One source line mapping in a `LineNumberTable`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LineNumber {
    /// Code-array start offset.
    pub start_pc: u16,
    /// Source line number.
    pub line_number: u16,
}

/// An ordered `LineNumberTable` payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LineNumberTableAttribute {
    /// Mappings in encoded order.
    pub lines: Vec<LineNumber>,
}

impl LineNumberTableAttribute {
    /// Decode mappings without validating instruction boundaries.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        let n = usize::from(reader.read_u2()?);
        reader.preflight_allocation(n)?;
        let mut lines = Vec::with_capacity(n);
        for _ in 0..n {
            lines.push(LineNumber {
                start_pc: reader.read_u2()?,
                line_number: reader.read_u2()?,
            });
        }
        finish(reader)?;
        Ok(Self { lines })
    }
    /// Encode mappings exactly as stored.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        let mut out = ByteWriter::new(budget);
        out.write_u2(count(self.lines.len(), "line numbers")?)?;
        for v in &self.lines {
            out.write_u2(v.start_pc)?;
            out.write_u2(v.line_number)?;
        }
        Ok(out.into_bytes())
    }
}

/// One local-variable range, shared by `LocalVariableTable` and `LocalVariableTypeTable`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LocalVariable {
    /// Code-array start offset.
    pub start_pc: u16,
    /// Range length.
    pub length: u16,
    /// Name index.
    pub name_index: u16,
    /// Descriptor or signature index.
    pub type_index: u16,
    /// Local-variable slot.
    pub slot: u16,
}

/// An ordered local-variable table payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LocalVariablesAttribute {
    /// Ranges in encoded order.
    pub variables: Vec<LocalVariable>,
}

impl LocalVariablesAttribute {
    /// Decode ranges without resolving names or checking code offsets.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        let n = usize::from(reader.read_u2()?);
        reader.preflight_allocation(n)?;
        let mut variables = Vec::with_capacity(n);
        for _ in 0..n {
            variables.push(LocalVariable {
                start_pc: reader.read_u2()?,
                length: reader.read_u2()?,
                name_index: reader.read_u2()?,
                type_index: reader.read_u2()?,
                slot: reader.read_u2()?,
            });
        }
        finish(reader)?;
        Ok(Self { variables })
    }
    /// Encode ranges exactly as stored.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        let mut out = ByteWriter::new(budget);
        out.write_u2(count(self.variables.len(), "local variables")?)?;
        for v in &self.variables {
            out.write_u2(v.start_pc)?;
            out.write_u2(v.length)?;
            out.write_u2(v.name_index)?;
            out.write_u2(v.type_index)?;
            out.write_u2(v.slot)?;
        }
        Ok(out.into_bytes())
    }
}

/// One `MethodParameters` row.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MethodParameter {
    /// Name index, or zero.
    pub name_index: u16,
    /// Raw parameter access flags.
    pub access_flags: u16,
}

/// The ordered `MethodParameters` payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MethodParametersAttribute {
    /// Parameters in descriptor order.
    pub parameters: Vec<MethodParameter>,
}

impl MethodParametersAttribute {
    /// Decode the u1-counted parameter table.
    pub fn decode(reader: &mut ByteReader<'_>) -> Result<Self, AttributeError> {
        let n = usize::from(reader.read_u1()?);
        reader.preflight_allocation(n)?;
        let mut parameters = Vec::with_capacity(n);
        for _ in 0..n {
            parameters.push(MethodParameter {
                name_index: reader.read_u2()?,
                access_flags: reader.read_u2()?,
            });
        }
        finish(reader)?;
        Ok(Self { parameters })
    }
    /// Encode the parameter table.
    pub fn encode(&self, budget: usize) -> Result<Vec<u8>, AttributeError> {
        let mut out = ByteWriter::new(budget);
        out.write_u1(u8::try_from(self.parameters.len()).map_err(|_| {
            error(
                AttributeErrorKind::CountOverflow,
                0,
                "too many method parameters",
            )
        })?)?;
        for v in &self.parameters {
            out.write_u2(v.name_index)?;
            out.write_u2(v.access_flags)?;
        }
        Ok(out.into_bytes())
    }
}