fdt-edit 0.1.2

A high-level library for creating, editing, and encoding Flattened Device Tree (FDT) structures
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
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
# fdt-edit Project Context for LLMs

## Project Overview

fdt-edit is a high-level Rust library for creating, editing, and encoding Flattened Device Tree (FDT) structures. It is part of the fdt-parser workspace and provides comprehensive functionality for device tree manipulation with full `no_std` compatibility.

## Key Information

- **Project Name**: fdt-edit
- **Version**: 0.1.1
- **Language**: Rust (edition 2024)
- **License**: MIT OR Apache-2.0
- **Repository**: https://github.com/drivercraft/fdt-parser
- **Dependencies**: fdt-raw (low-level parsing), log, enum_dispatch
- **Target**: Embedded and no_std environments
- **Features**: Complete device tree parsing, editing, and encoding

## Complete Architecture

### Main Components

1. **Fdt Structure** (`src/fdt.rs`) - Main device tree container
   - Parses from raw DTB bytes using `fdt_raw::Fdt`
   - Encodes back to DTB format via `FdtEncoder`
   - Manages node tree, memory reservations, and phandle cache
   - Provides Display trait for complete DTS output
   - Support for overlay application (`apply_overlay`, `apply_overlay_with_delete`)
   - Alias resolution (`resolve_alias`, `aliases`)
   - phandle-based node lookup (`find_by_phandle`)

2. **Node System** (`src/node/`) - Hierarchical node structure
   - **mod.rs**: Core `Node` struct with property and child management
   - **iter.rs**: Node iteration and references (`NodeRef`, `NodeMut`, `NodeKind`)
   - **gerneric.rs**: Generic node operations and context handling
   - **display.rs**: Formatted node display with configurable options
   - Specialized modules: memory.rs, clock.rs, pci.rs, interrupt_controller.rs

3. **Property System** (`src/prop/mod.rs`) - Device tree properties
   - Type-safe property access (u32, u64, strings, byte arrays)
   - Property value encoding/decoding with proper endianness
   - Support for common property types (reg, ranges, compatible)

4. **Encoding System** (`src/encode.rs`) - DTB generation
   - `FdtEncoder` converts in-memory structures to DTB format
   - `FdtData` wrapper for encoded data with access methods

5. **Context Management** (`src/ctx.rs`) - Tree traversal context
   - Maintains current path and inheritance context
   - Manages `#address-cells`, `#size-cells` propagation
   - Tracks interrupt parent relationships

### Key Data Types and Enums

```rust
// Core types
pub struct Fdt { /* device tree container */ }
pub struct Node { /* tree node with properties and children */ }
pub struct Property { /* device tree property */ }

// Node references (mutable and immutable)
pub enum NodeRef<'a> {
    Clock(NodeRefClock<'a>),
    Pci(NodeRefPci<'a>),
    InterruptController(NodeRefInterruptController<'a>),
    Memory(NodeRefMemory<'a>),
    Generic(NodeRefGen<'a>),
}

pub enum NodeMut<'a> { /* mutable variants */ }

// Specialized node types
pub struct NodeRefMemory<'a> { /* memory-specific operations */ }
pub struct NodeRefClock<'a> { /* clock-specific operations */ }
pub struct NodeRefPci<'a> { /* PCI-specific operations */ }
pub struct NodeRefInterruptController<'a> { /* interrupt controller operations */ }

// Supporting types
pub struct MemoryReservation { /* memory reservation entry */ }
pub struct Context<'a> { /* traversal context */ }
pub struct RegInfo { /* register information */ }
pub struct RangesEntry { /* address translation entry */ }
pub enum Status { /* node status (okay/disabled) */ }
```

## Complete API Reference

### Fdt Operations
```rust
// Creation and parsing
let fdt = Fdt::new();  // Create empty device tree
let fdt = Fdt::from_bytes(&dtb_data)?;  // Parse from DTB
let fdt = unsafe { Fdt::from_ptr(ptr)? };  // Parse from pointer

// Access and modification
let root = fdt.root();  // Get root node
let mut root_mut = fdt.root_mut();  // Get mutable root
let fdt_data = fdt.encode();  // Encode to DTB format
println!("{}", fdt);  // Display as DTS

// Overlay support
fdt.apply_overlay(&overlay_fdt)?;  // Apply overlay
fdt.apply_overlay_with_delete(&overlay, Some(delete_fdt))?;  // Apply with delete

// Memory reservations
for reservation in &fdt.memory_reservations {
    println!("Reserved: 0x{:x}-0x{:x}", reservation.address, reservation.address + reservation.size);
}
```

### Node Navigation and Search
```rust
// Path-based access
let node = fdt.get_by_path("/chosen");  // Exact path match
let mut node_mut = fdt.get_by_path_mut("/soc");  // Mutable access

// Pattern-based search
let virtio_nodes: Vec<_> = fdt.find_by_path("/virtio_mmio").collect();
let compatible_nodes = fdt.find_compatible(&["vendor,device"]);

// Global iteration
for node in fdt.all_nodes() { /* iterate all nodes */ }
for node in fdt.all_nodes_mut() { /* mutable iteration */ }

// phandle-based lookup
let node = fdt.find_by_phandle(phandle)?;  // Find by phandle
let mut node_mut = fdt.find_by_phandle_mut(phandle)?;  // Mutable version
```

### Node Manipulation
```rust
// Create nodes
let mut node = Node::new("test-device@12340000");
let node = Node::new("soc");  // Creates empty node

// Property management
node.set_property(Property::new("compatible", b"vendor,test\0"));
node.set_property(Property::new("reg", &[0x12340000u32, 0x1000u32]));

// Tree structure
node.add_child(child_node);
let removed_child = node.remove_child("child-name");

// Property access
let prop = node.get_property("compatible");
let mut prop_mut = node.get_property_mut("reg");
let removed_prop = node.remove_property("status");

// Node hierarchy
let child = node.get_child("child-name");
let mut child_mut = node.get_child_mut("child-name");
for child in node.children() { /* iterate children */ }
for child in node.children_mut() { /* mutable iteration */ }
```

### Property Operations
```rust
// Create properties
let prop = Property::new("reg", data);  // From raw bytes
let prop = Property::new("compatible", b"vendor,test\0");

// Type-safe access
let value = prop.get_u32()?;  // Get 32-bit value
let values = prop.get_u32_iter().collect::<Vec<_>>();  // Multiple u32 values
let value = prop.get_u64()?;  // Get 64-bit value
let string = prop.as_str()?;  // Get string
let strings = prop.as_str_iter().collect::<Vec<_>>();  // Multiple strings
let reader = prop.as_reader();  // Raw data access

// Property modification
prop.set_u32_ls(&[0x12345678]);  // Set multiple u32 values (little-endian)
prop.set_u64(0x123456789abcdef0);
prop.set_string("test-value");
prop.set_string_ls(&["value1", "value2"]);
```

### Specialized Node Operations

#### Memory Nodes
```rust
for node in fdt.all_nodes() {
    if let NodeKind::Memory(mem) = node.as_ref() {
        println!("Memory node: {}", mem.name());
        for region in mem.regions() {
            println!("  Region: 0x{:x}-0x{:x}", region.address, region.address + region.size);
        }
        if let Some(device_type) = mem.device_type() {
            println!("  Type: {}", device_type);
        }
    }
}
```

#### Clock Nodes
```rust
for node in fdt.all_nodes() {
    if let NodeKind::Clock(clock) = node.as_ref() {
        println!("Clock: {}", clock.name());
        println!("  #clock-cells: {}", clock.clock_cells);

        // Clock output names
        for (i, name) in clock.clock_output_names.iter().enumerate() {
            println!("  Output {}: {}", i, name);
        }

        // Clock references
        for clock_ref in clock.clocks() {
            println!("  Clock ref: phandle={}, cells={}", clock_ref.phandle, clock_ref.cells);
        }

        // Clock type
        match &clock.kind {
            ClockType::Fixed(fixed) => {
                println!("  Fixed clock: {}", fixed.clock_output_names.first().unwrap_or(&""));
            }
        }
    }
}
```

#### PCI Nodes
```rust
for node in fdt.all_nodes() {
    if let NodeKind::Pci(pci) = node.as_ref() {
        println!("PCI node: {}", pci.name());

        // Bus range
        if let Some(range) = pci.bus_range() {
            println!("  Bus range: {}-{}", range.start, range.end);
        }

        // Address ranges
        if let Some(ranges) = pci.ranges() {
            for range in ranges {
                println!("  Range: {:x?}", range);
            }
        }

        // Interrupt mapping
        if let Ok(interrupt_map) = pci.interrupt_map() {
            for entry in interrupt_map {
                println!("  Interrupt map: {:x?}", entry);
            }
        }

        // Child interrupts
        for child_irq in pci.child_interrupts() {
            println!("  Child interrupt: {:x?}", child_irq);
        }
    }
}
```

#### Interrupt Controllers
```rust
for node in fdt.all_nodes() {
    if let NodeKind::InterruptController(ic) = node.as_ref() {
        println!("Interrupt controller: {}", ic.name());

        if let Some(cells) = ic.interrupt_cells() {
            println!("  #interrupt-cells: {}", cells);
        }

        if let Some(addr_cells) = ic.interrupt_address_cells() {
            println!("  #address-cells: {}", addr_cells);
        }

        println!("  Is controller: {}", ic.is_interrupt_controller());

        for compatible in ic.compatibles() {
            println!("  Compatible: {}", compatible);
        }
    }
}
```

### Register and Range Operations
```rust
// Reg property access
for node in fdt.all_nodes() {
    if let Some(regs) = node.regs() {
        for reg in regs {
            println!("Reg: addr=0x{:x}, child_addr=0x{:x}, size={:?}",
                     reg.address, reg.child_bus_address, reg.size);
        }
    }
}

// Ranges property (address translation)
for node in fdt.all_nodes() {
    if let Some(ranges) = node.ranges(node.address_cells().unwrap_or(2)) {
        for range in ranges {
            println!("Range: child={:x}-{:x}, parent={:x}-{:x}, size={:x}",
                     range.child_bus_address, range.child_bus_address + range.size,
                     range.parent_bus_address, range.parent_bus_address + range.size,
                     range.size);
        }
    }
}
```

### Display and Formatting
```rust
// FDT display (complete DTS)
println!("{}", fdt);

// Node display with options
use fdt_edit::NodeDisplay;
let display = NodeDisplay::new(&node)
    .indent(4)
    .show_address(true)
    .show_size(true);
println!("{}", display);

// NodeRef display
use fdt_edit::NodeRefDisplay;
let ref_display = NodeRefDisplay::new(&node_ref)
    .indent(2)
    .show_details(true);
println!("{}", ref_display);
```

## Testing Framework

### Test Organization
- `tests/edit.rs` - Round-trip parsing and encoding validation
- `tests/memory.rs` - Memory node functionality
- `tests/clock.rs` - Clock node detection and properties
- `tests/pci.rs` - PCI node operations
- `tests/irq.rs` - Interrupt controller handling
- `tests/range.rs` - Register and range property testing
- `tests/remove_node.rs` - Node removal operations
- `tests/display_debug.rs` - Display and debug formatting
- `tests/find2.rs` - Advanced search operations

### Test Data Sources
- QEMU device trees (ARM virtio)
- Raspberry Pi 4B device trees
- Phytium platform device trees
- Custom test device trees

### Test Validation Methods
- Round-trip compatibility (parse → modify → encode → compare)
- DTC tool comparison (`dtc -I dtb -O dts`)
- Property value validation
- Tree structure integrity checks

## Advanced Features

### Overlay Support
```rust
// Basic overlay application
let mut base_fdt = Fdt::from_bytes(&base_dtb)?;
let overlay_fdt = Fdt::from_bytes(&overlay_dtb)?;
base_fdt.apply_overlay(&overlay_fdt)?;

// Overlay with delete support
base_fdt.apply_overlay_with_delete(&overlay, Some(delete_fdt))?;
```

### phandle Management
```rust
// Rebuild phandle cache after modifications
fdt.rebuild_phandle_cache();

// Find nodes by phandle
let node = fdt.find_by_phandle(phandle)?;
let mut node_mut = fdt.find_by_phandle_mut(phandle)?;

// Node phandle access
if let Some(phandle) = node.phandle() {
    println!("Node phandle: {}", phandle);
}
```

### Alias Resolution
```rust
// Get all aliases
for (alias, target) in fdt.aliases() {
    println!("Alias: {} -> {}", alias, target);
}

// Resolve specific alias
if let Some(target) = fdt.resolve_alias("serial0") {
    let node = fdt.get_by_path(target);
}
```

## Performance Characteristics

### Memory Usage
- Efficient node storage with property caching
- Lazy iterator patterns for large trees
- Minimal allocation during traversal

### Parsing Performance
- Direct conversion from fdt_raw structures
- Zero-copy property access where possible
- Optimized tree reconstruction algorithms

### Encoding Performance
- Efficient DTB structure generation
- Proper alignment and padding handling
- Optimized property serialization

## Integration Examples

### Complete Device Tree Processing
```rust
use fdt_edit::*;

// Load and parse
let dtb_data = std::fs::read("device.dtb")?;
let mut fdt = Fdt::from_bytes(&dtb_data)?;

// Find and modify memory nodes
for node in fdt.all_nodes_mut() {
    if let NodeMut::Memory(mut mem) = node {
        // Modify memory regions
        for region in mem.regions() {
            // Access or modify regions
        }
    }
}

// Add new node
let mut new_node = Node::new("test-device");
new_node.set_property(Property::new("compatible", b"vendor,test\0"));
new_node.set_property(Property::new("reg", &[0x12340000u32, 0x1000u32]));
fdt.root_mut().add_child(new_node);

// Apply overlay
let overlay_fdt = Fdt::from_bytes(&overlay_data)?;
fdt.apply_overlay(&overlay_fdt)?;

// Save modified device tree
let modified_dtb = fdt.encode();
std::fs::write("modified.dtb", modified_dtb.as_bytes())?;

// Export as DTS
std::fs::write("modified.dts", format!("{}", fdt));
```

## Development and Testing

### Build Commands
```bash
# Build library
cargo build -p fdt-edit

# Run all tests
cargo test -p fdt-edit

# Format code
cargo fmt -p fdt-edit

# Run clippy
cargo clippy -p fdt-edit
```

### Test Execution
```bash
# Run specific test
cargo test -p fdt-edit test_memory_node_detection

# Run tests with logging
RUST_LOG=debug cargo test -p fdt-edit

# Round-trip test validation
cargo test -p fdt-edit test_parse_and_rebuild
```

## Error Handling

The library uses `FdtError` for comprehensive error reporting:
- Parse errors from invalid DTB data
- Node path resolution failures
- Property access errors
- Encoding validation errors

## Limitations and Constraints

### Current Limitations
- Property editing APIs are partially implemented
- Some specialized node types may need additional features
- Large device trees may have memory constraints in `no_std` environments

### Platform Considerations
- Designed for both `std` and `no_std` environments
- Uses `alloc` crate for dynamic memory when available
- Endianness handling for cross-platform compatibility

## Future Development Roadmap

### Planned Features
- Complete property CRUD operations
- Enhanced node manipulation APIs
- Additional specialized node types
- Performance optimizations for large trees
- Streaming parsing support for very large device trees
- Validation and linting tools

### Integration Opportunities
- Device tree validation tools
- Configuration generation utilities
- Hardware abstraction layer generators