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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use crate::Error::IllegalAccessError;
use crate::{Result, Value};
use ristretto_classfile::attributes::Attribute;
use ristretto_classfile::{BaseType, ClassFile, ConstantPool, FieldAccessFlags, FieldType};
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::sync::Arc;
#[expect(clippy::struct_field_names)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Field {
offset: u16,
access_flags: FieldAccessFlags,
field_type: FieldType,
name: String,
attributes: Vec<Attribute>,
}
impl Field {
/// Create a new class field with the given parameters.
#[must_use]
pub fn new(
offset: u16,
access_flags: FieldAccessFlags,
field_type: FieldType,
name: String,
attributes: Vec<Attribute>,
) -> Self {
Self {
offset,
access_flags,
field_type,
name,
attributes,
}
}
/// Create a new class field with the given definition.
///
/// # Errors
///
/// if the field name cannot be read.
pub fn from(
class_file: &ClassFile,
offset: u16,
definition: &ristretto_classfile::Field,
) -> Result<Self> {
let constant_pool = &class_file.constant_pool;
let access_flags = definition.access_flags;
let name = constant_pool.try_get_utf8(definition.name_index)?;
let field_type = definition.field_type.clone();
Ok(Self {
offset,
access_flags,
field_type,
name: name.to_string(),
attributes: definition.attributes.clone(),
})
}
/// Get the field offset.
#[must_use]
pub fn offset(&self) -> u16 {
self.offset
}
/// Get the field access flags.
#[must_use]
pub fn access_flags(&self) -> &FieldAccessFlags {
&self.access_flags
}
/// Get the field type.
#[must_use]
pub fn field_type(&self) -> &FieldType {
&self.field_type
}
/// Get the field name.
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
/// Set the field value.
///
/// # Errors
///
/// - if the field is final.
/// - if the value is not permissible for the field type.
/// - if the lock is poisoned.
pub fn check_value(&self, value: &Value) -> Result<()> {
// TODO: Check that the field is not final
// if self.access_flags.contains(FieldAccessFlags::FINAL) && *guarded_value != Value::Unused {
// let error = format!("Cannot set final field: {}", self.name);
// return Err(IllegalAccessError(error));
// }
// Check that the value permissible for the field type
// See: https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-6.html#jvms-6.5.putstatic
match self.field_type {
FieldType::Base(
BaseType::Boolean
| BaseType::Byte
| BaseType::Char
| BaseType::Int
| BaseType::Short,
) => {
if !matches!(value, Value::Int(_)) {
return Err(IllegalAccessError(format!(
"Invalid value for {} field",
self.field_type
)));
}
}
FieldType::Base(BaseType::Double) => {
if !matches!(value, Value::Double(_)) {
return Err(IllegalAccessError(
"Invalid value for double field".to_string(),
));
}
}
FieldType::Base(BaseType::Float) => {
if !matches!(value, Value::Float(_)) {
return Err(IllegalAccessError(
"Invalid value for float field".to_string(),
));
}
}
FieldType::Base(BaseType::Long) => {
if !matches!(value, Value::Long(_)) {
return Err(IllegalAccessError(
"Invalid value for long field".to_string(),
));
}
}
FieldType::Object(_) | FieldType::Array(_) => {
// TODO: Check that the value is of the correct type
if !matches!(value, Value::Object(_)) {
return Err(IllegalAccessError(
"Invalid value for array field".to_string(),
));
}
}
}
Ok(())
}
/// Get the attributes.
#[must_use]
pub fn attributes(&self) -> &Vec<Attribute> {
&self.attributes
}
/// Get the default value for the field type.
#[must_use]
pub fn default_value(&self) -> Value {
match self.field_type {
FieldType::Base(
BaseType::Boolean
| BaseType::Byte
| BaseType::Char
| BaseType::Int
| BaseType::Short,
) => Value::Int(0),
FieldType::Base(BaseType::Double) => Value::Double(0.0),
FieldType::Base(BaseType::Float) => Value::Float(0.0),
FieldType::Base(BaseType::Long) => Value::Long(0),
FieldType::Object(_) | FieldType::Array(_) => Value::Object(None),
}
}
/// Get the default static value for the field type.
///
/// This method determines the initial value for a static field according to JVM specification:
///
/// # Static Field Initialization (JLS §12.4.2, JVMS §5.5)
///
/// Static fields are initialized in two phases:
/// 1. **Preparation phase**: All static fields are set to their default zero values
/// 2. **Initialization phase**: `<clinit>` runs, assigning compile-time constants and
/// executing static initializers
///
/// For fields with a `ConstantValue` attribute (compile-time constants for primitives
/// and String literals), the value is set directly from the constant pool during the
/// preparation phase, BEFORE `<clinit>` runs.
///
/// # Compile-Time Constants (JLS §15.28)
///
/// Per [JLS §12.4.1](https://docs.oracle.com/javase/specs/jls/se25/html/jls-12.html#jls-12.4.1),
/// accessing a compile-time constant does NOT trigger class initialization because:
/// - The compiler inlines the constant value at the access site
/// - The `ConstantValue` attribute ensures the value is available at preparation time
///
/// # Returns
///
/// - For primitive constants with `ConstantValue`: the constant value from the pool
/// - For String constants: `Value::Unused` (String objects require class initialization)
/// - For non-constant fields: the type's default zero value
///
/// # Errors
///
/// - if the index is out of bounds for the constant pool.
/// - if the value cannot be converted to the expected type.
pub fn default_static_value(&self, constant_pool: &ConstantPool) -> Result<Value> {
if self.access_flags.contains(FieldAccessFlags::STATIC) {
let constant_value_index = self.attributes.iter().find_map(|attribute| {
if let Attribute::ConstantValue {
constant_value_index,
..
} = attribute
{
Some(*constant_value_index)
} else {
None
}
});
if let Some(constant_value_index) = constant_value_index {
let value = match &self.field_type {
FieldType::Base(
BaseType::Boolean
| BaseType::Byte
| BaseType::Char
| BaseType::Int
| BaseType::Short,
) => {
let value = constant_pool.try_get_integer(constant_value_index)?;
Value::Int(*value)
}
FieldType::Base(BaseType::Double) => {
let value = constant_pool.try_get_double(constant_value_index)?;
Value::Double(*value)
}
FieldType::Base(BaseType::Float) => {
let value = constant_pool.try_get_float(constant_value_index)?;
Value::Float(*value)
}
FieldType::Base(BaseType::Long) => {
let value = constant_pool.try_get_long(constant_value_index)?;
Value::Long(*value)
}
FieldType::Object(_class_name) => {
// Objects are loaded through a class initializer
Value::Unused
}
FieldType::Array(_field_type) => {
// Arrays are loaded through a class initializer
Value::Unused
}
};
return Ok(value);
}
}
Ok(self.default_value())
}
}
/// Trait for getting a field by either the name, or the offset.
pub trait FieldKey: Display + Debug + Copy + Eq + Hash {
/// Check if the key is numeric (i.e., an offset).
fn is_numeric_key(&self) -> bool {
false
}
/// Check if the key matches the field.
fn matches_field(&self, field: &Field) -> bool;
/// Get the field by the key from the provided fields.
fn get_field<'a>(&self, fields: &'a [Arc<Field>]) -> Option<(usize, &'a Arc<Field>)>;
}
/// Implementation of `FieldKey` for the offset.
impl FieldKey for usize {
fn is_numeric_key(&self) -> bool {
true
}
fn matches_field(&self, field: &Field) -> bool {
field.offset as usize == *self
}
fn get_field<'a>(&self, fields: &'a [Arc<Field>]) -> Option<(usize, &'a Arc<Field>)> {
if let Some(field) = fields.get(*self) {
return Some((*self, field));
}
None
}
}
/// Implementation of `FieldKey` for field name.
impl FieldKey for &String {
fn matches_field(&self, field: &Field) -> bool {
self.as_str().matches_field(field)
}
fn get_field<'a>(&self, fields: &'a [Arc<Field>]) -> Option<(usize, &'a Arc<Field>)> {
self.as_str().get_field(fields)
}
}
/// Implementation of `FieldKey` for field name.
impl FieldKey for &str {
fn matches_field(&self, field: &Field) -> bool {
field.name == *self
}
fn get_field<'a>(&self, fields: &'a [Arc<Field>]) -> Option<(usize, &'a Arc<Field>)> {
fields
.iter()
.enumerate()
.find(|(_, field)| self.matches_field(field))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Reference;
use ristretto_classfile::FieldAccessFlags;
use ristretto_gc::GarbageCollector;
#[test]
fn test_field_new() {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Int),
"test".to_string(),
vec![],
);
assert_eq!(field.offset(), 0);
assert_eq!(field.access_flags(), &FieldAccessFlags::PUBLIC);
assert_eq!(field.field_type(), &FieldType::Base(BaseType::Int));
assert_eq!(field.name(), "test");
assert!(field.attributes.is_empty());
}
#[test]
fn test_check_value_boolean() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Boolean),
"test".to_string(),
vec![],
);
field.check_value(&Value::from(true))?;
Ok(())
}
#[test]
fn test_check_value_byte() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Byte),
"test".to_string(),
vec![],
);
field.check_value(&Value::Int(1))?;
Ok(())
}
#[test]
fn test_check_value_char() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Char),
"test".to_string(),
vec![],
);
field.check_value(&Value::Int(1))?;
Ok(())
}
#[test]
fn test_check_value_double() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Double),
"test".to_string(),
vec![],
);
field.check_value(&Value::Double(1.0))?;
Ok(())
}
#[test]
fn test_check_value_float() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Float),
"test".to_string(),
vec![],
);
field.check_value(&Value::Float(1.0))?;
Ok(())
}
#[test]
fn test_check_value_int() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Int),
"test".to_string(),
vec![],
);
field.check_value(&Value::Int(1))?;
Ok(())
}
#[test]
fn test_check_value_long() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Long),
"test".to_string(),
vec![],
);
field.check_value(&Value::Long(1))?;
Ok(())
}
#[test]
fn test_check_value_object() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Object("java/lang/Object".to_string()),
"test".to_string(),
vec![],
);
field.check_value(&Value::Object(None))?;
Ok(())
}
#[test]
fn test_check_value_array() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Array(Box::new(FieldType::Base(BaseType::Int))),
"test".to_string(),
vec![],
);
let collector = GarbageCollector::new();
let value = Value::new_object(&collector, Reference::from(vec![42i32]));
field.check_value(&value)?;
Ok(())
}
#[test]
fn test_check_value_short() -> Result<()> {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Short),
"test".to_string(),
vec![],
);
field.check_value(&Value::Int(1))?;
Ok(())
}
#[test]
fn test_check_value_invalid() {
let field = Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Int),
"test".to_string(),
vec![],
);
let result = field.check_value(&Value::Double(1.0));
assert!(result.is_err());
}
#[test]
fn test_field_key_get_by_offset() {
let fields = vec![
Arc::new(Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Int),
"field1".to_string(),
vec![],
)),
Arc::new(Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Int),
"field2".to_string(),
vec![],
)),
];
let key: usize = 1;
let expected = fields.get(key).map(|field| (key, field));
assert!(key.is_numeric_key());
assert_eq!(expected, key.get_field(&fields));
}
#[test]
fn test_field_key_get_by_name() {
let fields = vec![
Arc::new(Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Int),
"field1".to_string(),
vec![],
)),
Arc::new(Field::new(
0,
FieldAccessFlags::PUBLIC,
FieldType::Base(BaseType::Int),
"field2".to_string(),
vec![],
)),
];
let key = &"field2".to_string();
let expected = fields
.iter()
.enumerate()
.find(|(_, field)| field.name == key.as_str());
assert!(!key.is_numeric_key());
assert_eq!(expected, key.get_field(&fields));
let key = key.as_str();
let expected = fields
.iter()
.enumerate()
.find(|(_, field)| field.name == key);
assert!(!key.is_numeric_key());
assert_eq!(expected, key.get_field(&fields));
}
}