@ship.zone/runner 3.0.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.smartconfig.json +19 -1
  2. package/changelog.md +43 -0
  3. package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
  4. package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +4 -4
  5. package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
  6. package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +4 -4
  7. package/dist_ts/00_commitinfo_data.js +3 -3
  8. package/dist_ts/api-client.d.ts +2 -1
  9. package/dist_ts/api-client.js +10 -2
  10. package/dist_ts/artifact-manager.js +1 -1
  11. package/dist_ts/attempt-state.js +1 -1
  12. package/dist_ts/cache-manager.js +1 -1
  13. package/dist_ts/cli-entry.js +17 -3
  14. package/dist_ts/cli.js +39 -11
  15. package/dist_ts/config.js +70 -20
  16. package/dist_ts/egress-proxy.d.ts +99 -0
  17. package/dist_ts/egress-proxy.js +607 -0
  18. package/dist_ts/errors.js +1 -1
  19. package/dist_ts/filesystem.js +1 -1
  20. package/dist_ts/index.d.ts +5 -1
  21. package/dist_ts/index.js +6 -2
  22. package/dist_ts/interfaces.d.ts +93 -22
  23. package/dist_ts/interfaces.js +1 -1
  24. package/dist_ts/log-sender.js +1 -1
  25. package/dist_ts/microvm-executor.d.ts +90 -0
  26. package/dist_ts/microvm-executor.js +1045 -0
  27. package/dist_ts/node-version.d.ts +11 -0
  28. package/dist_ts/node-version.js +43 -0
  29. package/dist_ts/npm-grants.d.ts +9 -0
  30. package/dist_ts/npm-grants.js +44 -0
  31. package/dist_ts/oci-registry.d.ts +73 -0
  32. package/dist_ts/oci-registry.js +508 -0
  33. package/dist_ts/plugins.d.ts +6 -2
  34. package/dist_ts/plugins.js +7 -3
  35. package/dist_ts/protocol-validator.d.ts +3 -3
  36. package/dist_ts/protocol-validator.js +26 -21
  37. package/dist_ts/redactor.js +1 -1
  38. package/dist_ts/registration-state.js +1 -1
  39. package/dist_ts/runner.d.ts +6 -5
  40. package/dist_ts/runner.js +48 -18
  41. package/dist_ts/source-workspace.js +1 -1
  42. package/dist_ts/spec-version.js +1 -1
  43. package/dist_ts/staging-scavenger.js +1 -1
  44. package/dist_ts/state-owner.js +4 -2
  45. package/dist_ts/transfer-archive.js +1 -1
  46. package/dist_ts/validation.js +1 -1
  47. package/dist_ts/vsock-protocol.d.ts +130 -0
  48. package/dist_ts/vsock-protocol.js +336 -0
  49. package/dist_ts/wire-schema.js +1 -1
  50. package/package.json +9 -6
  51. package/readme.md +72 -61
  52. package/rust/Cargo.lock +1 -0
  53. package/rust/Cargo.toml +2 -1
  54. package/rust/src/cpio.rs +147 -0
  55. package/rust/src/extfs.rs +747 -0
  56. package/rust/src/guest.rs +2411 -0
  57. package/rust/src/lib.rs +41 -0
  58. package/rust/src/main.rs +6 -1
  59. package/rust/src/oci_tar.rs +842 -0
  60. package/ts/00_commitinfo_data.ts +2 -2
  61. package/ts/api-client.ts +19 -1
  62. package/ts/cli-entry.ts +15 -2
  63. package/ts/cli.ts +33 -11
  64. package/ts/config.ts +96 -23
  65. package/ts/egress-proxy.ts +649 -0
  66. package/ts/index.ts +5 -1
  67. package/ts/interfaces.ts +103 -21
  68. package/ts/microvm-executor.ts +1265 -0
  69. package/ts/node-version.ts +49 -0
  70. package/ts/npm-grants.ts +49 -0
  71. package/ts/oci-registry.ts +649 -0
  72. package/ts/plugins.ts +6 -2
  73. package/ts/protocol-validator.ts +29 -25
  74. package/ts/runner.ts +51 -17
  75. package/ts/state-owner.ts +8 -1
  76. package/ts/vsock-protocol.ts +437 -0
  77. package/dist_ts/oci-executor.d.ts +0 -155
  78. package/dist_ts/oci-executor.js +0 -2238
  79. package/ts/oci-executor.ts +0 -2989
@@ -0,0 +1,747 @@
1
+ use crate::oci_tar::{FsNode, FsNodeKind};
2
+ use crate::Error;
3
+ use std::collections::HashMap;
4
+ use std::fs::OpenOptions;
5
+ use std::io::Write;
6
+ use std::os::unix::fs::OpenOptionsExt;
7
+ use std::path::Path;
8
+
9
+ const BLOCK_SIZE: usize = 4096;
10
+ const INODE_SIZE: usize = 128;
11
+ const INODES_PER_BLOCK: usize = BLOCK_SIZE / INODE_SIZE; // 32
12
+ const BLOCKS_PER_GROUP: usize = BLOCK_SIZE * 8; // 32768
13
+ const PTRS_PER_BLOCK: usize = BLOCK_SIZE / 4; // 1024
14
+ const FIRST_NON_RESERVED_INO: u32 = 11;
15
+ const ROOT_INO: u32 = 2;
16
+
17
+ const EXT2_SUPER_MAGIC: u16 = 0xEF53;
18
+ const EXT2_VALID_FS: u16 = 1;
19
+ const EXT2_ERRORS_CONTINUE: u16 = 1;
20
+ const EXT2_OS_LINUX: u32 = 0;
21
+ const EXT2_DYNAMIC_REV: u32 = 1;
22
+ const EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER: u32 = 0x0001;
23
+ const EXT2_FEATURE_RO_COMPAT_LARGE_FILE: u32 = 0x0002;
24
+ const EXT2_FEATURE_INCOMPAT_FILETYPE: u32 = 0x0002;
25
+
26
+ const EXT2_FT_REG_FILE: u8 = 1;
27
+ const EXT2_FT_DIR: u8 = 2;
28
+ const EXT2_FT_SYMLINK: u8 = 7;
29
+
30
+ const S_IFREG: u16 = 0x8000;
31
+ const S_IFDIR: u16 = 0x4000;
32
+ const S_IFLNK: u16 = 0xA000;
33
+
34
+ struct PlannedInode {
35
+ ino: u32,
36
+ mode: u16,
37
+ uid: u32,
38
+ gid: u32,
39
+ mtime: u32,
40
+ links: u16,
41
+ is_dir: bool,
42
+ payload: InodePayload,
43
+ }
44
+
45
+ enum InodePayload {
46
+ File(Vec<u8>),
47
+ Symlink(Vec<u8>),
48
+ Directory(Vec<(String, u32, u8)>),
49
+ }
50
+
51
+ fn is_power_of(mut n: usize, base: usize) -> bool {
52
+ if n < 1 {
53
+ return false;
54
+ }
55
+ while n > 1 {
56
+ if !n.is_multiple_of(base) {
57
+ return false;
58
+ }
59
+ n /= base;
60
+ }
61
+ true
62
+ }
63
+
64
+ fn has_superblock_backup(group: usize) -> bool {
65
+ group == 0
66
+ || group == 1
67
+ || is_power_of(group, 3)
68
+ || is_power_of(group, 5)
69
+ || is_power_of(group, 7)
70
+ }
71
+
72
+ fn div_ceil(a: usize, b: usize) -> usize {
73
+ if a == 0 {
74
+ 0
75
+ } else {
76
+ a.div_ceil(b)
77
+ }
78
+ }
79
+
80
+ fn data_blocks_for_len(len: usize) -> usize {
81
+ let direct = div_ceil(len, BLOCK_SIZE);
82
+ if direct <= 12 {
83
+ direct
84
+ } else if direct <= 12 + PTRS_PER_BLOCK {
85
+ direct + 1
86
+ } else {
87
+ let remaining = direct - 12 - PTRS_PER_BLOCK;
88
+ let second_level = div_ceil(remaining, PTRS_PER_BLOCK);
89
+ direct + 1 + 1 + second_level
90
+ }
91
+ }
92
+
93
+ fn build_dir_blocks(entries: &[(String, u32, u8)]) -> Vec<u8> {
94
+ let mut blocks: Vec<[u8; BLOCK_SIZE]> = Vec::new();
95
+ let mut current = [0u8; BLOCK_SIZE];
96
+ let mut offset: usize = 0;
97
+ let mut last_entry_offset: Option<usize> = None;
98
+
99
+ for (name, ino, file_type) in entries {
100
+ let name_bytes = name.as_bytes();
101
+ let raw_len = 8 + name_bytes.len();
102
+ let aligned_len = (raw_len + 3) & !3;
103
+
104
+ if offset + aligned_len > BLOCK_SIZE {
105
+ // Stretch previous entry in this block to the end of the block.
106
+ if let Some(prev) = last_entry_offset {
107
+ let stretched = (BLOCK_SIZE - prev) as u16;
108
+ current[prev + 4..prev + 6].copy_from_slice(&stretched.to_le_bytes());
109
+ }
110
+ blocks.push(current);
111
+ current = [0u8; BLOCK_SIZE];
112
+ offset = 0;
113
+ }
114
+
115
+ current[offset..offset + 4].copy_from_slice(&ino.to_le_bytes());
116
+ current[offset + 4..offset + 6].copy_from_slice(&(aligned_len as u16).to_le_bytes());
117
+ current[offset + 6] = name_bytes.len() as u8;
118
+ current[offset + 7] = *file_type;
119
+ current[offset + 8..offset + 8 + name_bytes.len()].copy_from_slice(name_bytes);
120
+ last_entry_offset = Some(offset);
121
+ offset += aligned_len;
122
+ }
123
+
124
+ if let Some(prev) = last_entry_offset {
125
+ let stretched = (BLOCK_SIZE - prev) as u16;
126
+ current[prev + 4..prev + 6].copy_from_slice(&stretched.to_le_bytes());
127
+ blocks.push(current);
128
+ } else if blocks.is_empty() {
129
+ blocks.push(current);
130
+ }
131
+
132
+ let mut flat = Vec::with_capacity(blocks.len() * BLOCK_SIZE);
133
+ for blk in blocks {
134
+ flat.extend_from_slice(&blk);
135
+ }
136
+ flat
137
+ }
138
+
139
+ fn collect_inodes(root: &FsNode) -> Result<Vec<PlannedInode>, Error> {
140
+ let mut inodes: Vec<PlannedInode> = Vec::new();
141
+ let mut hardlinks: HashMap<u64, usize> = HashMap::new();
142
+ let mut next_ino: u32 = FIRST_NON_RESERVED_INO;
143
+
144
+ // Reserve slot 0 for root inode (ino = 2).
145
+ inodes.push(PlannedInode {
146
+ ino: ROOT_INO,
147
+ mode: S_IFDIR | ((root.mode & 0o1777) as u16),
148
+ uid: root.uid,
149
+ gid: root.gid,
150
+ mtime: root.mtime.min(u64::from(u32::MAX)) as u32,
151
+ links: 2,
152
+ is_dir: true,
153
+ payload: InodePayload::Directory(Vec::new()),
154
+ });
155
+
156
+ fn walk(
157
+ node: &FsNode,
158
+ self_idx: usize,
159
+ parent_ino: u32,
160
+ inodes: &mut Vec<PlannedInode>,
161
+ hardlinks: &mut HashMap<u64, usize>,
162
+ next_ino: &mut u32,
163
+ ) -> Result<(), Error> {
164
+ let self_ino = inodes[self_idx].ino;
165
+ let FsNodeKind::Directory(children) = &node.kind else {
166
+ return Err(Error::new("expected directory node while building ext2 image"));
167
+ };
168
+
169
+ let mut dir_entries: Vec<(String, u32, u8)> = Vec::with_capacity(children.len() + 2);
170
+ dir_entries.push((".".to_owned(), self_ino, EXT2_FT_DIR));
171
+ dir_entries.push(("..".to_owned(), parent_ino, EXT2_FT_DIR));
172
+
173
+ let mut child_dirs: Vec<(&FsNode, usize)> = Vec::new();
174
+ let mut subdir_count: u16 = 0;
175
+
176
+ for (name, child) in children {
177
+ if name.len() > 255 {
178
+ return Err(Error::new("ext2 directory entry name exceeds 255 bytes"));
179
+ }
180
+ match &child.kind {
181
+ FsNodeKind::Directory(_) => {
182
+ let ino = *next_ino;
183
+ *next_ino = next_ino
184
+ .checked_add(1)
185
+ .ok_or_else(|| Error::new("inode count overflow"))?;
186
+ let idx = inodes.len();
187
+ inodes.push(PlannedInode {
188
+ ino,
189
+ mode: S_IFDIR | ((child.mode & 0o1777) as u16),
190
+ uid: child.uid,
191
+ gid: child.gid,
192
+ mtime: child.mtime.min(u64::from(u32::MAX)) as u32,
193
+ links: 2,
194
+ is_dir: true,
195
+ payload: InodePayload::Directory(Vec::new()),
196
+ });
197
+ dir_entries.push((name.clone(), ino, EXT2_FT_DIR));
198
+ child_dirs.push((child, idx));
199
+ subdir_count = subdir_count
200
+ .checked_add(1)
201
+ .ok_or_else(|| Error::new("directory link count overflow"))?;
202
+ }
203
+ FsNodeKind::File {
204
+ data,
205
+ hardlink_group,
206
+ } => {
207
+ if let Some(group) = hardlink_group
208
+ && let Some(&existing_idx) = hardlinks.get(group)
209
+ {
210
+ inodes[existing_idx].links = inodes[existing_idx]
211
+ .links
212
+ .checked_add(1)
213
+ .ok_or_else(|| Error::new("hardlink count overflow"))?;
214
+ dir_entries.push((name.clone(), inodes[existing_idx].ino, EXT2_FT_REG_FILE));
215
+ continue;
216
+ }
217
+ let ino = *next_ino;
218
+ *next_ino = next_ino
219
+ .checked_add(1)
220
+ .ok_or_else(|| Error::new("inode count overflow"))?;
221
+ let idx = inodes.len();
222
+ inodes.push(PlannedInode {
223
+ ino,
224
+ mode: S_IFREG | ((child.mode & 0o777) as u16),
225
+ uid: child.uid,
226
+ gid: child.gid,
227
+ mtime: child.mtime.min(u64::from(u32::MAX)) as u32,
228
+ links: 1,
229
+ is_dir: false,
230
+ payload: InodePayload::File(data.clone()),
231
+ });
232
+ if let Some(group) = hardlink_group {
233
+ hardlinks.insert(*group, idx);
234
+ }
235
+ dir_entries.push((name.clone(), ino, EXT2_FT_REG_FILE));
236
+ }
237
+ FsNodeKind::Symlink(target) => {
238
+ let ino = *next_ino;
239
+ *next_ino = next_ino
240
+ .checked_add(1)
241
+ .ok_or_else(|| Error::new("inode count overflow"))?;
242
+ inodes.push(PlannedInode {
243
+ ino,
244
+ mode: S_IFLNK | 0o777,
245
+ uid: child.uid,
246
+ gid: child.gid,
247
+ mtime: child.mtime.min(u64::from(u32::MAX)) as u32,
248
+ links: 1,
249
+ is_dir: false,
250
+ payload: InodePayload::Symlink(target.clone()),
251
+ });
252
+ dir_entries.push((name.clone(), ino, EXT2_FT_SYMLINK));
253
+ }
254
+ }
255
+ }
256
+
257
+ inodes[self_idx].links = inodes[self_idx]
258
+ .links
259
+ .checked_add(subdir_count)
260
+ .ok_or_else(|| Error::new("directory link count overflow"))?;
261
+ inodes[self_idx].payload = InodePayload::Directory(dir_entries);
262
+
263
+ for (child_node, child_idx) in child_dirs {
264
+ walk(child_node, child_idx, self_ino, inodes, hardlinks, next_ino)?;
265
+ }
266
+ Ok(())
267
+ }
268
+
269
+ walk(root, 0, ROOT_INO, &mut inodes, &mut hardlinks, &mut next_ino)?;
270
+ Ok(inodes)
271
+ }
272
+
273
+ /// Writes a deterministic read-only ext2 rev1 (ext4-compatible) filesystem image from `root` to
274
+ /// `output_path`. Mounted inside Linux guests with `mount -t ext4 -o ro,noload`.
275
+ pub fn write_ext2_image(root: &FsNode, output_path: &Path) -> Result<u64, Error> {
276
+ if !output_path.is_absolute() {
277
+ return Err(Error::new("ext2 output path must be absolute"));
278
+ }
279
+ let planned = collect_inodes(root)?;
280
+ let max_ino = planned.iter().map(|i| i.ino).max().unwrap_or(ROOT_INO) as usize;
281
+
282
+ // Pre-serialize directory blocks and compute total required data blocks.
283
+ let mut rendered_payloads: Vec<Vec<u8>> = Vec::with_capacity(planned.len());
284
+ let mut total_data_blocks: usize = 0;
285
+ for inode in &planned {
286
+ let bytes = match &inode.payload {
287
+ InodePayload::File(data) => data.clone(),
288
+ InodePayload::Symlink(target) => target.clone(),
289
+ InodePayload::Directory(entries) => build_dir_blocks(entries),
290
+ };
291
+ let needs_blocks = match &inode.payload {
292
+ InodePayload::Symlink(target) if target.len() <= 60 => false,
293
+ _ => !bytes.is_empty(),
294
+ };
295
+ if needs_blocks {
296
+ total_data_blocks += data_blocks_for_len(bytes.len());
297
+ }
298
+ rendered_payloads.push(bytes);
299
+ }
300
+
301
+ // Converge on group count, inodes_per_group, and total_blocks.
302
+ let mut num_groups: usize = 1;
303
+ let (inodes_per_group, inode_table_blocks, gdt_blocks, total_blocks) = loop {
304
+ let gdt_bytes = num_groups * 32;
305
+ let gdt_blocks = div_ceil(gdt_bytes, BLOCK_SIZE).max(1);
306
+ let ipg_raw = div_ceil(max_ino, num_groups).max(INODES_PER_BLOCK);
307
+ let inodes_per_group = div_ceil(ipg_raw, INODES_PER_BLOCK) * INODES_PER_BLOCK;
308
+ if inodes_per_group > BLOCKS_PER_GROUP {
309
+ num_groups += 1;
310
+ continue;
311
+ }
312
+ let inode_table_blocks = inodes_per_group / INODES_PER_BLOCK;
313
+
314
+ let mut metadata_blocks: usize = 0;
315
+ let mut usable_data_blocks: usize = 0;
316
+ for g in 0..num_groups {
317
+ let group_meta = (if has_superblock_backup(g) {
318
+ 1 + gdt_blocks
319
+ } else {
320
+ 0
321
+ }) + 2
322
+ + inode_table_blocks;
323
+ metadata_blocks += group_meta;
324
+ usable_data_blocks += BLOCKS_PER_GROUP.saturating_sub(group_meta);
325
+ }
326
+ if usable_data_blocks < total_data_blocks + 16 {
327
+ num_groups += 1;
328
+ continue;
329
+ }
330
+
331
+ // Exact block count: full groups up to last group, then only needed blocks in last group
332
+ // (with a small floor so group 0 has at least 64 blocks).
333
+ let needed_total = (metadata_blocks + total_data_blocks + 8).max(64);
334
+ let needed_groups = div_ceil(needed_total, BLOCKS_PER_GROUP).max(1);
335
+ if needed_groups > num_groups {
336
+ num_groups = needed_groups;
337
+ continue;
338
+ }
339
+ // Make sure the last group has at least its own metadata + 1 block.
340
+ let last_group = num_groups - 1;
341
+ let last_group_start = last_group * BLOCKS_PER_GROUP;
342
+ let last_group_meta = (if has_superblock_backup(last_group) {
343
+ 1 + gdt_blocks
344
+ } else {
345
+ 0
346
+ }) + 2
347
+ + inode_table_blocks;
348
+ let total_blocks = needed_total.max(last_group_start + last_group_meta + 1);
349
+ let total_blocks = total_blocks.min(num_groups * BLOCKS_PER_GROUP);
350
+ break (inodes_per_group, inode_table_blocks, gdt_blocks, total_blocks);
351
+ };
352
+
353
+ let total_inodes = num_groups * inodes_per_group;
354
+ let image_len = total_blocks
355
+ .checked_mul(BLOCK_SIZE)
356
+ .ok_or_else(|| Error::new("ext2 image size overflow"))?;
357
+ let mut image = vec![0u8; image_len];
358
+
359
+ struct GroupLayout {
360
+ start: usize,
361
+ blocks: usize,
362
+ has_sb: bool,
363
+ block_bitmap: usize,
364
+ inode_bitmap: usize,
365
+ inode_table: usize,
366
+ data_start: usize,
367
+ next_free_block: usize,
368
+ used_dirs: u16,
369
+ }
370
+
371
+ let mut groups: Vec<GroupLayout> = Vec::with_capacity(num_groups);
372
+ for g in 0..num_groups {
373
+ let start = g * BLOCKS_PER_GROUP;
374
+ let blocks = (total_blocks - start).min(BLOCKS_PER_GROUP);
375
+ let has_sb = has_superblock_backup(g);
376
+ let mut cursor = start;
377
+ if has_sb {
378
+ cursor += 1 + gdt_blocks;
379
+ }
380
+ let block_bitmap = cursor;
381
+ cursor += 1;
382
+ let inode_bitmap = cursor;
383
+ cursor += 1;
384
+ let inode_table = cursor;
385
+ cursor += inode_table_blocks;
386
+ let data_start = cursor;
387
+ groups.push(GroupLayout {
388
+ start,
389
+ blocks,
390
+ has_sb,
391
+ block_bitmap,
392
+ inode_bitmap,
393
+ inode_table,
394
+ data_start,
395
+ next_free_block: data_start,
396
+ used_dirs: 0,
397
+ });
398
+ }
399
+
400
+ // Mark metadata blocks as allocated in each group's block bitmap.
401
+ let set_bit = |image: &mut [u8], bitmap_block: usize, bit: usize| {
402
+ let byte_idx = bitmap_block * BLOCK_SIZE + (bit / 8);
403
+ image[byte_idx] |= 1u8 << (bit % 8);
404
+ };
405
+
406
+ for group in &groups {
407
+ for b in group.start..group.data_start {
408
+ set_bit(&mut image, group.block_bitmap, b - group.start);
409
+ }
410
+ // Pad unused bits past group.blocks to 1 as required by e2fsck.
411
+ for bit in group.blocks..BLOCKS_PER_GROUP {
412
+ set_bit(&mut image, group.block_bitmap, bit);
413
+ }
414
+ // Pad unused inode bitmap bits past inodes_per_group to 1.
415
+ for bit in inodes_per_group..(BLOCK_SIZE * 8) {
416
+ set_bit(&mut image, group.inode_bitmap, bit);
417
+ }
418
+ }
419
+
420
+ // Mark reserved inodes 1..10 as used in group 0's inode bitmap.
421
+ for reserved in 1..FIRST_NON_RESERVED_INO {
422
+ set_bit(&mut image, groups[0].inode_bitmap, (reserved - 1) as usize);
423
+ }
424
+
425
+ let mut alloc_group = 0usize;
426
+ let mut alloc_block = |image: &mut [u8], groups: &mut [GroupLayout]| -> Result<u32, Error> {
427
+ while alloc_group < groups.len() {
428
+ let group = &mut groups[alloc_group];
429
+ if group.next_free_block < group.start + group.blocks {
430
+ let blk = group.next_free_block;
431
+ group.next_free_block += 1;
432
+ let rel = blk - group.start;
433
+ let byte_idx = group.block_bitmap * BLOCK_SIZE + (rel / 8);
434
+ image[byte_idx] |= 1u8 << (rel % 8);
435
+ return Ok(blk as u32);
436
+ }
437
+ alloc_group += 1;
438
+ }
439
+ Err(Error::new("ext2 image ran out of data blocks"))
440
+ };
441
+
442
+ // Write every inode and its data blocks.
443
+ let mut large_file_used = false;
444
+ for (idx, inode) in planned.iter().enumerate() {
445
+ let ino_zero = (inode.ino - 1) as usize;
446
+ let g = ino_zero / inodes_per_group;
447
+ let local_ino = ino_zero % inodes_per_group;
448
+ set_bit(&mut image, groups[g].inode_bitmap, local_ino);
449
+ if inode.is_dir {
450
+ groups[g].used_dirs += 1;
451
+ }
452
+
453
+ let payload = &rendered_payloads[idx];
454
+ let mut i_block = [0u8; 60];
455
+ let mut allocated_blocks: u32 = 0;
456
+
457
+ let is_fast_symlink = matches!(inode.payload, InodePayload::Symlink(_)) && payload.len() <= 60;
458
+ if is_fast_symlink {
459
+ i_block[..payload.len()].copy_from_slice(payload);
460
+ } else if !payload.is_empty() {
461
+ let mut data_block_nums: Vec<u32> = Vec::with_capacity(div_ceil(payload.len(), BLOCK_SIZE));
462
+ for chunk in payload.chunks(BLOCK_SIZE) {
463
+ let blk = alloc_block(&mut image, &mut groups)?;
464
+ let dst = (blk as usize) * BLOCK_SIZE;
465
+ image[dst..dst + chunk.len()].copy_from_slice(chunk);
466
+ data_block_nums.push(blk);
467
+ allocated_blocks += 1;
468
+ }
469
+
470
+ // Direct pointers [0..12)
471
+ for (slot, &blk) in data_block_nums.iter().take(12).enumerate() {
472
+ i_block[slot * 4..slot * 4 + 4].copy_from_slice(&blk.to_le_bytes());
473
+ }
474
+
475
+ // Single indirect pointer [12]
476
+ if data_block_nums.len() > 12 {
477
+ let ind_blk = alloc_block(&mut image, &mut groups)?;
478
+ allocated_blocks += 1;
479
+ i_block[12 * 4..13 * 4].copy_from_slice(&ind_blk.to_le_bytes());
480
+ let base = (ind_blk as usize) * BLOCK_SIZE;
481
+ for (slot, &blk) in data_block_nums.iter().skip(12).take(PTRS_PER_BLOCK).enumerate()
482
+ {
483
+ image[base + slot * 4..base + slot * 4 + 4].copy_from_slice(&blk.to_le_bytes());
484
+ }
485
+ }
486
+
487
+ // Double indirect pointer [13]
488
+ if data_block_nums.len() > 12 + PTRS_PER_BLOCK {
489
+ let dind_blk = alloc_block(&mut image, &mut groups)?;
490
+ allocated_blocks += 1;
491
+ i_block[13 * 4..14 * 4].copy_from_slice(&dind_blk.to_le_bytes());
492
+ let dind_base = (dind_blk as usize) * BLOCK_SIZE;
493
+ let rest = &data_block_nums[12 + PTRS_PER_BLOCK..];
494
+ if rest.len() > PTRS_PER_BLOCK * PTRS_PER_BLOCK {
495
+ return Err(Error::new("file exceeds maximum ext2 double-indirect size"));
496
+ }
497
+ for (outer_slot, chunk) in rest.chunks(PTRS_PER_BLOCK).enumerate() {
498
+ let ind_blk = alloc_block(&mut image, &mut groups)?;
499
+ allocated_blocks += 1;
500
+ image[dind_base + outer_slot * 4..dind_base + outer_slot * 4 + 4]
501
+ .copy_from_slice(&ind_blk.to_le_bytes());
502
+ let ind_base = (ind_blk as usize) * BLOCK_SIZE;
503
+ for (inner_slot, &blk) in chunk.iter().enumerate() {
504
+ image[ind_base + inner_slot * 4..ind_base + inner_slot * 4 + 4]
505
+ .copy_from_slice(&blk.to_le_bytes());
506
+ }
507
+ }
508
+ }
509
+ }
510
+
511
+ let size64 = payload.len() as u64;
512
+ if size64 >= 0x8000_0000 && matches!(inode.payload, InodePayload::File(_)) {
513
+ large_file_used = true;
514
+ }
515
+ let i_size_lo = (size64 & 0xFFFF_FFFF) as u32;
516
+ let i_size_hi = if matches!(inode.payload, InodePayload::File(_)) {
517
+ (size64 >> 32) as u32
518
+ } else {
519
+ 0
520
+ };
521
+ let i_blocks_512 = allocated_blocks.saturating_mul((BLOCK_SIZE / 512) as u32);
522
+ let inode_offset = groups[g].inode_table * BLOCK_SIZE + local_ino * INODE_SIZE;
523
+ let slot = &mut image[inode_offset..inode_offset + INODE_SIZE];
524
+ slot[0..2].copy_from_slice(&inode.mode.to_le_bytes());
525
+ slot[2..4].copy_from_slice(&((inode.uid & 0xFFFF) as u16).to_le_bytes());
526
+ slot[4..8].copy_from_slice(&i_size_lo.to_le_bytes());
527
+ slot[8..12].copy_from_slice(&inode.mtime.to_le_bytes()); // atime
528
+ slot[12..16].copy_from_slice(&inode.mtime.to_le_bytes()); // ctime
529
+ slot[16..20].copy_from_slice(&inode.mtime.to_le_bytes()); // mtime
530
+ slot[24..26].copy_from_slice(&((inode.gid & 0xFFFF) as u16).to_le_bytes());
531
+ slot[26..28].copy_from_slice(&inode.links.to_le_bytes());
532
+ slot[28..32].copy_from_slice(&i_blocks_512.to_le_bytes());
533
+ slot[40..100].copy_from_slice(&i_block);
534
+ slot[108..112].copy_from_slice(&i_size_hi.to_le_bytes());
535
+ slot[120..122].copy_from_slice(&(((inode.uid >> 16) & 0xFFFF) as u16).to_le_bytes());
536
+ slot[122..124].copy_from_slice(&(((inode.gid >> 16) & 0xFFFF) as u16).to_le_bytes());
537
+ }
538
+
539
+ // Count free blocks & free inodes per group directly from bitmaps for guaranteed consistency.
540
+ let mut total_free_blocks: u32 = 0;
541
+ let mut total_free_inodes: u32 = 0;
542
+ let mut gdt_raw = vec![0u8; gdt_blocks * BLOCK_SIZE];
543
+
544
+ for (g, group) in groups.iter().enumerate() {
545
+ let mut free_blocks: u16 = 0;
546
+ for bit in 0..group.blocks {
547
+ let byte = image[group.block_bitmap * BLOCK_SIZE + (bit / 8)];
548
+ if (byte & (1u8 << (bit % 8))) == 0 {
549
+ free_blocks += 1;
550
+ }
551
+ }
552
+ let mut free_inodes: u16 = 0;
553
+ for bit in 0..inodes_per_group {
554
+ let byte = image[group.inode_bitmap * BLOCK_SIZE + (bit / 8)];
555
+ if (byte & (1u8 << (bit % 8))) == 0 {
556
+ free_inodes += 1;
557
+ }
558
+ }
559
+ total_free_blocks += u32::from(free_blocks);
560
+ total_free_inodes += u32::from(free_inodes);
561
+
562
+ let desc = &mut gdt_raw[g * 32..g * 32 + 32];
563
+ desc[0..4].copy_from_slice(&(group.block_bitmap as u32).to_le_bytes());
564
+ desc[4..8].copy_from_slice(&(group.inode_bitmap as u32).to_le_bytes());
565
+ desc[8..12].copy_from_slice(&(group.inode_table as u32).to_le_bytes());
566
+ desc[12..14].copy_from_slice(&free_blocks.to_le_bytes());
567
+ desc[14..16].copy_from_slice(&free_inodes.to_le_bytes());
568
+ desc[16..18].copy_from_slice(&group.used_dirs.to_le_bytes());
569
+ }
570
+
571
+ // Build superblock (1024 bytes, at offset 1024 in group 0 and offset 0 in backup superblock groups).
572
+ let mut sb = [0u8; 1024];
573
+ sb[0..4].copy_from_slice(&(total_inodes as u32).to_le_bytes());
574
+ sb[4..8].copy_from_slice(&(total_blocks as u32).to_le_bytes());
575
+ sb[8..12].copy_from_slice(&0u32.to_le_bytes()); // r_blocks_count
576
+ sb[12..16].copy_from_slice(&total_free_blocks.to_le_bytes());
577
+ sb[16..20].copy_from_slice(&total_free_inodes.to_le_bytes());
578
+ sb[20..24].copy_from_slice(&0u32.to_le_bytes()); // first_data_block = 0 for 4 KiB blocks
579
+ sb[24..28].copy_from_slice(&2u32.to_le_bytes()); // log_block_size = 2 (4096)
580
+ sb[28..32].copy_from_slice(&2u32.to_le_bytes()); // log_frag_size = 2
581
+ sb[32..36].copy_from_slice(&(BLOCKS_PER_GROUP as u32).to_le_bytes());
582
+ sb[36..40].copy_from_slice(&(BLOCKS_PER_GROUP as u32).to_le_bytes());
583
+ sb[40..44].copy_from_slice(&(inodes_per_group as u32).to_le_bytes());
584
+ sb[52..54].copy_from_slice(&0u16.to_le_bytes()); // mnt_count
585
+ sb[54..56].copy_from_slice(&0xFFFFu16.to_le_bytes()); // max_mnt_count (-1)
586
+ sb[56..58].copy_from_slice(&EXT2_SUPER_MAGIC.to_le_bytes());
587
+ sb[58..60].copy_from_slice(&EXT2_VALID_FS.to_le_bytes());
588
+ sb[60..62].copy_from_slice(&EXT2_ERRORS_CONTINUE.to_le_bytes());
589
+ sb[72..76].copy_from_slice(&EXT2_OS_LINUX.to_le_bytes());
590
+ sb[76..80].copy_from_slice(&EXT2_DYNAMIC_REV.to_le_bytes());
591
+ sb[84..88].copy_from_slice(&FIRST_NON_RESERVED_INO.to_le_bytes());
592
+ sb[88..90].copy_from_slice(&(INODE_SIZE as u16).to_le_bytes());
593
+ // Features
594
+ let ro_compat = EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER
595
+ | if large_file_used {
596
+ EXT2_FEATURE_RO_COMPAT_LARGE_FILE
597
+ } else {
598
+ 0
599
+ };
600
+ sb[92..96].copy_from_slice(&0u32.to_le_bytes()); // feature_compat
601
+ sb[96..100].copy_from_slice(&EXT2_FEATURE_INCOMPAT_FILETYPE.to_le_bytes());
602
+ sb[100..104].copy_from_slice(&ro_compat.to_le_bytes());
603
+ // Deterministic UUID (v4-shaped constant for reproducible SHA-256).
604
+ let uuid: [u8; 16] = [
605
+ 0x53, 0x68, 0x69, 0x70, 0x5a, 0x6f, 0x4e, 0x65, 0x80, 0x4f, 0x43, 0x49, 0x52, 0x4f, 0x4f,
606
+ 0x54,
607
+ ];
608
+ sb[104..120].copy_from_slice(&uuid);
609
+ let volume_name = b"shipzone-oci";
610
+ sb[120..120 + volume_name.len()].copy_from_slice(volume_name);
611
+
612
+ // Write superblock + GDT into group 0 and every SPARSE_SUPER backup group.
613
+ for (g, group) in groups.iter().enumerate() {
614
+ if !group.has_sb {
615
+ continue;
616
+ }
617
+ let mut group_sb = sb;
618
+ group_sb[90..92].copy_from_slice(&(g as u16).to_le_bytes()); // s_block_group_nr
619
+ let sb_offset = if g == 0 {
620
+ 1024
621
+ } else {
622
+ group.start * BLOCK_SIZE
623
+ };
624
+ image[sb_offset..sb_offset + 1024].copy_from_slice(&group_sb);
625
+ let gdt_offset = (group.start + 1) * BLOCK_SIZE;
626
+ image[gdt_offset..gdt_offset + gdt_raw.len()].copy_from_slice(&gdt_raw);
627
+ }
628
+
629
+ let mut out = OpenOptions::new()
630
+ .write(true)
631
+ .create(true)
632
+ .truncate(true)
633
+ .mode(0o600)
634
+ .open(output_path)
635
+ .map_err(|_| Error::new("unable to create ext2 rootfs output file"))?;
636
+ out.write_all(&image)
637
+ .map_err(|_| Error::new("unable to write ext2 rootfs output file"))?;
638
+ out.sync_all()
639
+ .map_err(|_| Error::new("unable to sync ext2 rootfs output file"))?;
640
+ Ok(image_len as u64)
641
+ }
642
+
643
+ #[cfg(test)]
644
+ mod tests {
645
+ use super::*;
646
+ use crate::oci_tar::{apply_oci_layers, write_tar_entry, write_tar_trailer, TarEntry, TarEntryKind};
647
+ use std::process::Command;
648
+
649
+ #[test]
650
+ fn builds_valid_ext2_image_checked_by_e2fsck() {
651
+ let dir = std::env::temp_dir().join(format!(
652
+ "runnerworkspace-extfs-test-{}",
653
+ std::process::id()
654
+ ));
655
+ let _ = std::fs::remove_dir_all(&dir);
656
+ std::fs::create_dir_all(&dir).unwrap();
657
+
658
+ let layer_path = dir.join("layer.tar");
659
+ let mut tar = Vec::new();
660
+ // Small file, large file (> 12 direct blocks to exercise indirect blocks), symlink, hardlink.
661
+ write_tar_entry(
662
+ &mut tar,
663
+ &TarEntry {
664
+ path: "bin".into(),
665
+ mode: 0o755,
666
+ uid: 0,
667
+ gid: 0,
668
+ mtime: 100,
669
+ kind: TarEntryKind::Directory,
670
+ },
671
+ )
672
+ .unwrap();
673
+ write_tar_entry(
674
+ &mut tar,
675
+ &TarEntry {
676
+ path: "bin/busybox".into(),
677
+ mode: 0o755,
678
+ uid: 0,
679
+ gid: 0,
680
+ mtime: 100,
681
+ kind: TarEntryKind::File(vec![0xAB; 128 * 1024]),
682
+ },
683
+ )
684
+ .unwrap();
685
+ write_tar_entry(
686
+ &mut tar,
687
+ &TarEntry {
688
+ path: "bin/sh".into(),
689
+ mode: 0o777,
690
+ uid: 0,
691
+ gid: 0,
692
+ mtime: 100,
693
+ kind: TarEntryKind::Symlink(b"busybox".to_vec()),
694
+ },
695
+ )
696
+ .unwrap();
697
+ write_tar_entry(
698
+ &mut tar,
699
+ &TarEntry {
700
+ path: "bin/ash".into(),
701
+ mode: 0o755,
702
+ uid: 0,
703
+ gid: 0,
704
+ mtime: 100,
705
+ kind: TarEntryKind::Hardlink("bin/busybox".into()),
706
+ },
707
+ )
708
+ .unwrap();
709
+ write_tar_entry(
710
+ &mut tar,
711
+ &TarEntry {
712
+ path: "longlink".into(),
713
+ mode: 0o777,
714
+ uid: 65532,
715
+ gid: 65532,
716
+ mtime: 100,
717
+ kind: TarEntryKind::Symlink(vec![b'x'; 120]),
718
+ },
719
+ )
720
+ .unwrap();
721
+ write_tar_trailer(&mut tar).unwrap();
722
+ std::fs::write(&layer_path, &tar).unwrap();
723
+
724
+ let root = apply_oci_layers(&[layer_path.as_path()], 16 * 1024 * 1024).unwrap();
725
+ let img1 = dir.join("rootfs1.ext2");
726
+ let img2 = dir.join("rootfs2.ext2");
727
+ let size1 = write_ext2_image(&root, &img1).unwrap();
728
+ let size2 = write_ext2_image(&root, &img2).unwrap();
729
+ assert_eq!(size1, size2);
730
+ assert_eq!(std::fs::read(&img1).unwrap(), std::fs::read(&img2).unwrap());
731
+
732
+ if Path::new("/usr/sbin/e2fsck").exists() {
733
+ let status = Command::new("/usr/sbin/e2fsck")
734
+ .args(["-f", "-n", img1.to_str().unwrap()])
735
+ .output()
736
+ .expect("run e2fsck");
737
+ assert!(
738
+ status.status.success(),
739
+ "e2fsck failed: stdout={} stderr={}",
740
+ String::from_utf8_lossy(&status.stdout),
741
+ String::from_utf8_lossy(&status.stderr)
742
+ );
743
+ }
744
+
745
+ let _ = std::fs::remove_dir_all(&dir);
746
+ }
747
+ }