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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use super::BLOCK_SZ;
use alloc::{
format,
string::{String, ToString},
vec::Vec,
};
use core::{convert::TryInto, fmt::Debug, mem};
pub const BAD_BLOCK: u32 = 0x0FFF_FFF7;
pub const DIR_ENTRY_UNUSED: u8 = 0xe5;
pub const DIR_ENTRY_LAST_AND_UNUSED: u8 = 0x0;
pub const LAST_LONG_ENTRY: u8 = 0x40u8;
#[derive(Debug, Clone, Copy)]
#[repr(packed)]
pub struct BPB {
pub bs_jmp_boot: [u8; 3],
pub bs_oem_name: [u8; 8],
pub byts_per_sec: u16,
pub sec_per_clus: u8,
pub rsvd_sec_cnt: u16,
pub num_fats: u8,
pub root_ent_cnt: u16,
pub tot_sec16: u16,
pub media: u8,
pub fat_sz16: u16,
pub sec_per_trk: u16,
pub num_heads: u16,
pub hidd_sec: u32,
pub tot_sec32: u32,
pub fat_sz32: u32,
pub ext_flags: u16,
pub fs_ver: u16,
pub root_clus: u32,
pub fs_info: u16,
pub bk_boot_sec: u16,
pub reserved: [u8; 12],
pub drv_num: u8,
pub resvered1: u8,
pub boot_sig: u8,
pub vol_id: u32,
pub vol_lab: [u8; 11],
pub fil_sys_type: [u8; 8],
}
pub enum FatType {
FAT32,
FAT16,
FAT12,
}
impl BPB {
#[inline(always)]
pub fn is_valid(&self) -> bool {
self.root_dir_sec() == 0
&& self.tot_sec16 == 0
&& self.count_of_cluster() >= 66625
&& self.fat_sz16 == 0
&& self.root_ent_cnt == 0
}
#[inline(always)]
pub fn data_sector_count(&self) -> u32 {
self.tot_sec32
- (self.rsvd_sec_cnt as u32
+ self.num_fats as u32 * self.fat_sz32
+ self.root_dir_sec())
}
#[inline(always)]
pub fn count_of_cluster(&self) -> u32 {
self.data_sector_count() / (self.sec_per_clus as u32)
}
#[inline(always)]
pub fn clus_size(&self) -> u32 {
(self.byts_per_sec * (self.sec_per_clus as u16)) as u32
}
#[inline(always)]
pub fn root_dir_sec(&self) -> u32 {
(((self.root_ent_cnt * 32) + (self.byts_per_sec - 1)) / (self.byts_per_sec)) as u32
}
#[inline(always)]
pub fn data_sector_beg(&self) -> u32 {
self.first_data_sector()
}
#[inline(always)]
pub fn first_data_sector(&self) -> u32 {
let fat_sz: u32;
if self.fat_sz16 != 0 {
fat_sz = self.fat_sz16 as u32;
} else {
fat_sz = self.fat_sz32 as u32;
}
(self.rsvd_sec_cnt as u32) + (self.num_fats as u32) * fat_sz + self.root_dir_sec()
}
#[inline(always)]
pub fn fat_type(&self) -> FatType {
if self.count_of_cluster() < 4085 {
FatType::FAT12
} else if self.count_of_cluster() < 65525 {
FatType::FAT16
} else {
FatType::FAT32
}
}
}
#[derive(Debug, Clone)]
#[repr(C)]
pub struct FSInfo {
lead_sig: u32,
reserved1: [u8; 480],
struc_sig: u32,
free_count: u32,
nxt_free: u32,
reserved2: [u8; 12],
trail_sig: u32,
}
impl FSInfo {
#[allow(unused)]
#[allow(unused)]
fn free_clus(clus_num: usize) {}
}
#[derive(PartialEq, Clone, Copy)]
pub enum DiskInodeType {
File,
Directory,
}
pub type DataBlock = [u8; BLOCK_SZ];
#[derive(PartialEq, Debug, Clone, Copy)]
#[repr(u8)]
pub enum FATDiskInodeType {
AttrClear = 0,
AttrReadOnly = 0x01,
AttrHidden = 0x02,
AttrSystem = 0x04,
AttrVolumeID = 0x08,
AttrDirectory = 0x10,
AttrArchive = 0x20,
AttrLongName = 0x0F,
}
pub union FATDirEnt {
pub short_entry: FATShortDirEnt,
pub long_entry: FATLongDirEnt,
}
impl Debug for FATDirEnt {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if !self.is_long() {
f.debug_struct("FATDirEnt")
.field("SHORT", unsafe { &self.short_entry })
.finish()
} else {
f.debug_struct("FATDirEnt")
.field("LONG", unsafe { &self.long_entry })
.finish()
}
}
}
impl FATDirEnt {
pub fn gen_short_name_numtail(v: Vec<FATDirEnt>, name_res: &mut [u8; 11]) {
if v.iter()
.find(|i| i.get_short_name_array()[..] == name_res[..])
.is_none()
{
return;
}
let mut baselen: usize = name_res
.iter()
.enumerate()
.find(|i| *i.1 == ' ' as u8)
.map_or_else(|| 8, |i| i.0);
let numtail2_baselen = 2;
let numtail_baselen = 6;
if baselen > 6 {
baselen = numtail_baselen;
name_res[7] = ' ' as u8;
}
name_res[baselen] = '~' as u8;
for i in 1..10 {
name_res[baselen + 1] = i + '0' as u8;
if v.iter()
.find(|i| i.get_short_name_array()[..] == name_res[..])
.is_none()
{
return;
}
}
let jiffies = 19382022;
let mut i = jiffies & 0xffff;
let sz = ((jiffies >> 10) & 0x7) as u8;
if baselen > 2 {
baselen = numtail2_baselen;
name_res[7] = ' ' as u8;
}
name_res[baselen + 4] = '~' as u8;
name_res[baselen + 5] = '1' as u8 + sz;
loop {
name_res[baselen..baselen + 4]
.copy_from_slice(&(format!("{:04X}", i).as_bytes())[0..4]);
if v.iter()
.find(|i| i.get_short_name_array()[..] == name_res[..])
.is_none()
{
break;
}
i -= 11;
}
}
pub fn gen_short_name_prefix(mut s: String) -> String {
s.remove_matches(' ');
s.make_ascii_uppercase();
let split_res = s.rsplit_once('.');
let (base, ext) = if split_res.is_some() {
split_res.unwrap()
} else {
(&s[..], "")
};
let (base, ext) = if base.len() == 0 && ext.len() != 0 {
(ext, base)
} else {
(base, ext)
};
let base = {
let mut i = 0;
while i != base.len() && base[i..].starts_with('.') {
i += 1;
}
if i == base.len() {
base
} else {
&base[i..]
}
};
let base = base.trim_start_matches('.');
let base = if ext.len() != 0 || base.len() != 0 {
format!("{: <8}", base.split_at(8.min(base.len())).0)
} else {
"".to_string()
};
let ext = if ext.len() != 0 || base.len() != 0 {
format!("{: <3}", ext.split_at(3.min(ext.len())).0)
} else {
"".to_string()
};
[base, ext].concat()
}
pub fn get_ord(&self) -> usize {
self.ord()
}
pub fn empty() -> Self {
Self {
short_entry: FATShortDirEnt::empty(),
}
}
pub fn unused_not_last_entry() -> Self {
let mut i = Self::empty();
i.as_bytes_mut()[0] = DIR_ENTRY_UNUSED;
i
}
pub fn unused_and_last_entry() -> Self {
let mut i = Self::empty();
i.as_bytes_mut()[0] = DIR_ENTRY_LAST_AND_UNUSED;
i.as_bytes_mut()[11] = 0u8;
i
}
pub fn as_bytes(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const _ as usize as *const u8,
mem::size_of::<Self>(),
)
}
}
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(
self as *mut _ as usize as *mut u8,
mem::size_of::<Self>(),
)
}
}
pub fn is_last_long_dir_ent(&self) -> bool {
if let Some(i) = self.get_long_ent() {
if (i.ord & LAST_LONG_ENTRY) != 0 {
true
} else {
false
}
} else {
false
}
}
pub fn ord(&self) -> usize {
if let Some(i) = self.get_long_ent() {
(i.ord & (LAST_LONG_ENTRY - 1)) as usize
} else {
0
}
}
pub fn set_size(&mut self, size: u32) {
{
self.short_entry.file_size = size
};
}
pub fn get_fst_clus(&self) -> u32 {
if !self.is_short() {
panic!("this cluster is not a short dir ent")
}
unsafe { self.short_entry.get_first_clus() }
}
pub fn set_fst_clus(&mut self, fst_clus: u32) {
if !self.is_short() {
panic!("this cluster is not a short dir ent")
}
unsafe {
self.short_entry.set_fst_clus(fst_clus);
}
}
pub fn is_long(&self) -> bool {
unsafe { self.short_entry.attr == FATDiskInodeType::AttrLongName }
}
#[allow(unused)]
pub fn is_short(&self) -> bool {
!self.is_long()
}
pub fn get_short_ent(&self) -> Option<&FATShortDirEnt> {
if !self.is_long() {
unsafe { Some(&(self.short_entry)) }
} else {
None
}
}
pub fn get_long_ent(&self) -> Option<&FATLongDirEnt> {
if self.is_long() {
unsafe { Some(&(self.long_entry)) }
} else {
None
}
}
pub fn get_name(&self) -> String {
unsafe {
if self.is_long() {
self.long_entry.name()
} else {
self.short_entry.name()
}
}
}
pub fn get_short_name_array(&self) -> [u8; 11] {
unsafe { self.short_entry.name }
}
pub fn unused(&self) -> bool {
self.last_and_unused() || self.unused_not_last()
}
pub fn unused_not_last(&self) -> bool {
unsafe { self.long_entry.ord == DIR_ENTRY_UNUSED }
}
pub fn last_and_unused(&self) -> bool {
unsafe { self.long_entry.ord == DIR_ENTRY_LAST_AND_UNUSED }
}
}
#[derive(Debug, Clone, Copy)]
#[repr(packed)]
pub struct FATShortDirEnt {
pub name: [u8; 11],
pub attr: FATDiskInodeType,
pub nt_res: u8,
pub crt_time_teenth: u8,
pub crt_time: u16,
pub crt_date: u16,
pub last_acc_date: u16,
pub fst_clus_hi: u16,
pub wrt_time: u16,
pub wrt_date: u16,
pub fst_clus_lo: u16,
pub file_size: u32,
}
impl FATShortDirEnt {
pub fn from_name(name: [u8; 11], fst_clus: u32, file_type: DiskInodeType) -> Self {
let mut short_ent = Self::empty();
short_ent.set_fst_clus(fst_clus);
short_ent.name.copy_from_slice(&name);
if file_type == DiskInodeType::Directory {
short_ent.attr = FATDiskInodeType::AttrDirectory;
} else {
short_ent.attr = FATDiskInodeType::AttrArchive;
}
return short_ent;
}
pub fn empty() -> Self {
Self {
name: [0; 11],
attr: FATDiskInodeType::AttrArchive,
nt_res: 0,
crt_time_teenth: 0,
crt_time: 0,
crt_date: 0,
last_acc_date: 0,
fst_clus_hi: 0,
wrt_time: 0,
wrt_date: 0,
fst_clus_lo: 0,
file_size: 0,
}
}
pub fn set_fst_clus(&mut self, fst_clus: u32) {
self.fst_clus_hi = (fst_clus >> 16) as u16;
self.fst_clus_lo = (fst_clus & 0b1111_1111_1111_1111) as u16;
}
pub fn get_first_clus(&self) -> u32 {
(self.fst_clus_lo as u32) | ((self.fst_clus_hi as u32) << 16)
}
pub fn is_dir(&self) -> bool {
self.attr == FATDiskInodeType::AttrDirectory
}
#[allow(unused)]
pub fn is_file(&self) -> bool {
self.attr == FATDiskInodeType::AttrArchive
|| self.attr == FATDiskInodeType::AttrHidden
|| self.attr == FATDiskInodeType::AttrSystem
|| self.attr == FATDiskInodeType::AttrReadOnly
}
}
impl FATShortDirEnt {
pub fn name(&self) -> String {
let basic_name_len = (0..8).find(|i| self.name[*i] == ' ' as u8).unwrap_or(8);
let ext_name_len = (0..3).find(|i| self.name[8 + *i] == ' ' as u8).unwrap_or(3);
macro_rules! as_u8str {
($a:expr) => {
core::str::from_utf8(&$a).unwrap()
};
}
{
if ext_name_len != 0 {
[
as_u8str!(self.name[..basic_name_len]),
as_u8str!(['.' as u8][..]),
as_u8str!(self.name[8..8 + ext_name_len]),
]
.concat()
} else {
as_u8str!(self.name[0..basic_name_len]).to_string()
}
}
}
}
pub const LONG_DIR_ENT_NAME_CAPACITY: usize = 13;
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(packed)]
pub struct FATLongDirEnt {
ord: u8,
name1: [u16; 5],
attr: FATDiskInodeType,
ldir_type: u8,
chk_sum: u8,
name2: [u16; 6],
fst_clus_lo: u16,
name3: [u16; 2],
}
impl FATLongDirEnt {
pub fn empty() -> Self {
Self {
ord: 0u8,
name1: [0u16; 5],
attr: FATDiskInodeType::AttrLongName,
ldir_type: 0u8,
chk_sum: 0u8,
name2: [0u16; 6],
fst_clus_lo: 0u16,
name3: [0u16; 2],
}
}
pub fn from_name_slice(is_last_ent: bool, order: usize, partial_name: [u16; 13]) -> Self {
let mut long_ent = Self::empty();
unsafe {
core::ptr::addr_of_mut!(long_ent.name1)
.write_unaligned(partial_name[..5].try_into().expect("Failed to cast!"));
core::ptr::addr_of_mut!(long_ent.name2)
.write_unaligned(partial_name[5..11].try_into().expect("Failed to cast!"));
core::ptr::addr_of_mut!(long_ent.name3)
.write_unaligned(partial_name[11..].try_into().expect("Failed to cast!"));
}
assert!(order < 0x47);
long_ent.ord = order as u8;
if is_last_ent {
long_ent.ord |= LAST_LONG_ENTRY;
}
long_ent
}
pub fn name(&self) -> String {
let mut name_all: [u16; LONG_DIR_ENT_NAME_CAPACITY] = [0u16; LONG_DIR_ENT_NAME_CAPACITY];
name_all[..5].copy_from_slice(unsafe { &core::ptr::addr_of!(self.name1).read_unaligned() });
name_all[5..11]
.copy_from_slice(unsafe { &core::ptr::addr_of!(self.name2).read_unaligned() });
name_all[11..]
.copy_from_slice(unsafe { &core::ptr::addr_of!(self.name3).read_unaligned() });
let len = (0..name_all.len())
.find(|i| name_all[*i] == 0)
.unwrap_or(name_all.len());
String::from_utf16_lossy(&name_all[..len])
}
}