Create the AHCI branch for Aman's work
[reactos.git] / boot / freeldr / freeldr / lib / fs / fat.c
1 /*
2 * FreeLoader
3 * Copyright (C) 1998-2003 Brian Palmer <brianp@sginet.com>
4 * Copyright (C) 2009 Hervé Poussineau
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include <freeldr.h>
22
23 #define NDEBUG
24 #include <debug.h>
25
26 DBG_DEFAULT_CHANNEL(FILESYSTEM);
27
28 ULONG FatDetermineFatType(PFAT_BOOTSECTOR FatBootSector, ULONGLONG PartitionSectorCount);
29 PVOID FatBufferDirectory(PFAT_VOLUME_INFO Volume, ULONG DirectoryStartCluster, ULONG* EntryCountPointer, BOOLEAN RootDirectory);
30 BOOLEAN FatSearchDirectoryBufferForFile(PFAT_VOLUME_INFO Volume, PVOID DirectoryBuffer, ULONG EntryCount, PCHAR FileName, PFAT_FILE_INFO FatFileInfoPointer);
31 ARC_STATUS FatLookupFile(PFAT_VOLUME_INFO Volume, PCSTR FileName, ULONG DeviceId, PFAT_FILE_INFO FatFileInfoPointer);
32 void FatParseShortFileName(PCHAR Buffer, PDIRENTRY DirEntry);
33 BOOLEAN FatGetFatEntry(PFAT_VOLUME_INFO Volume, ULONG Cluster, ULONG* ClusterPointer);
34 ULONG FatCountClustersInChain(PFAT_VOLUME_INFO Volume, ULONG StartCluster);
35 ULONG* FatGetClusterChainArray(PFAT_VOLUME_INFO Volume, ULONG StartCluster);
36 BOOLEAN FatReadClusterChain(PFAT_VOLUME_INFO Volume, ULONG StartClusterNumber, ULONG NumberOfClusters, PVOID Buffer);
37 BOOLEAN FatReadPartialCluster(PFAT_VOLUME_INFO Volume, ULONG ClusterNumber, ULONG StartingOffset, ULONG Length, PVOID Buffer);
38 BOOLEAN FatReadVolumeSectors(PFAT_VOLUME_INFO Volume, ULONG SectorNumber, ULONG SectorCount, PVOID Buffer);
39
40 #define TAG_FAT_CHAIN 'CtaT'
41 #define TAG_FAT_FILE 'FtaF'
42 #define TAG_FAT_VOLUME 'VtaF'
43 #define TAG_FAT_BUFFER 'BtaF'
44
45 typedef struct _FAT_VOLUME_INFO
46 {
47 ULONG BytesPerSector; /* Number of bytes per sector */
48 ULONG SectorsPerCluster; /* Number of sectors per cluster */
49 ULONG FatSectorStart; /* Starting sector of 1st FAT table */
50 ULONG ActiveFatSectorStart; /* Starting sector of active FAT table */
51 ULONG NumberOfFats; /* Number of FAT tables */
52 ULONG SectorsPerFat; /* Sectors per FAT table */
53 ULONG RootDirSectorStart; /* Starting sector of the root directory (non-fat32) */
54 ULONG RootDirSectors; /* Number of sectors of the root directory (non-fat32) */
55 ULONG RootDirStartCluster; /* Starting cluster number of the root directory (fat32 only) */
56 ULONG DataSectorStart; /* Starting sector of the data area */
57 ULONG FatType; /* FAT12, FAT16, FAT32, FATX16 or FATX32 */
58 ULONG DeviceId;
59 } FAT_VOLUME_INFO;
60
61 PFAT_VOLUME_INFO FatVolumes[MAX_FDS];
62
63 VOID FatSwapFatBootSector(PFAT_BOOTSECTOR Obj)
64 {
65 SW(Obj, BytesPerSector);
66 SW(Obj, ReservedSectors);
67 SW(Obj, RootDirEntries);
68 SW(Obj, TotalSectors);
69 SW(Obj, SectorsPerFat);
70 SW(Obj, SectorsPerTrack);
71 SW(Obj, NumberOfHeads);
72 SD(Obj, HiddenSectors);
73 SD(Obj, TotalSectorsBig);
74 SD(Obj, VolumeSerialNumber);
75 SW(Obj, BootSectorMagic);
76 }
77
78 VOID FatSwapFat32BootSector(PFAT32_BOOTSECTOR Obj)
79 {
80 SW(Obj, BytesPerSector);
81 SW(Obj, ReservedSectors);
82 SW(Obj, RootDirEntries);
83 SW(Obj, TotalSectors);
84 SW(Obj, SectorsPerFat);
85 SW(Obj, NumberOfHeads);
86 SD(Obj, HiddenSectors);
87 SD(Obj, TotalSectorsBig);
88 SD(Obj, SectorsPerFatBig);
89 SW(Obj, ExtendedFlags);
90 SW(Obj, FileSystemVersion);
91 SD(Obj, RootDirStartCluster);
92 SW(Obj, FsInfo);
93 SW(Obj, BackupBootSector);
94 SD(Obj, VolumeSerialNumber);
95 SW(Obj, BootSectorMagic);
96 }
97
98 VOID FatSwapFatXBootSector(PFATX_BOOTSECTOR Obj)
99 {
100 SD(Obj, VolumeSerialNumber);
101 SD(Obj, SectorsPerCluster);
102 SW(Obj, NumberOfFats);
103 }
104
105 VOID FatSwapDirEntry(PDIRENTRY Obj)
106 {
107 SW(Obj, CreateTime);
108 SW(Obj, CreateDate);
109 SW(Obj, LastAccessDate);
110 SW(Obj, ClusterHigh);
111 SW(Obj, Time);
112 SW(Obj, Date);
113 SW(Obj, ClusterLow);
114 SD(Obj, Size);
115 }
116
117 VOID FatSwapLFNDirEntry(PLFN_DIRENTRY Obj)
118 {
119 int i;
120 SW(Obj, StartCluster);
121 for(i = 0; i < 5; i++)
122 Obj->Name0_4[i] = SWAPW(Obj->Name0_4[i]);
123 for(i = 0; i < 6; i++)
124 Obj->Name5_10[i] = SWAPW(Obj->Name5_10[i]);
125 for(i = 0; i < 2; i++)
126 Obj->Name11_12[i] = SWAPW(Obj->Name11_12[i]);
127 }
128
129 VOID FatSwapFatXDirEntry(PFATX_DIRENTRY Obj)
130 {
131 SD(Obj, StartCluster);
132 SD(Obj, Size);
133 SW(Obj, Time);
134 SW(Obj, Date);
135 SW(Obj, CreateTime);
136 SW(Obj, CreateDate);
137 SW(Obj, LastAccessTime);
138 SW(Obj, LastAccessDate);
139 }
140
141 BOOLEAN FatOpenVolume(PFAT_VOLUME_INFO Volume, PFAT_BOOTSECTOR BootSector, ULONGLONG PartitionSectorCount)
142 {
143 char ErrMsg[80];
144 ULONG FatSize;
145 PFAT_BOOTSECTOR FatVolumeBootSector;
146 PFAT32_BOOTSECTOR Fat32VolumeBootSector;
147 PFATX_BOOTSECTOR FatXVolumeBootSector;
148
149 TRACE("FatOpenVolume() DeviceId = %d\n", Volume->DeviceId);
150
151 //
152 // Allocate the memory to hold the boot sector
153 //
154 FatVolumeBootSector = (PFAT_BOOTSECTOR)BootSector;
155 Fat32VolumeBootSector = (PFAT32_BOOTSECTOR)BootSector;
156 FatXVolumeBootSector = (PFATX_BOOTSECTOR)BootSector;
157
158 // Get the FAT type
159 Volume->FatType = FatDetermineFatType(FatVolumeBootSector, PartitionSectorCount);
160
161 // Dump boot sector (and swap it for big endian systems)
162 TRACE("Dumping boot sector:\n");
163 if (ISFATX(Volume->FatType))
164 {
165 FatSwapFatXBootSector(FatXVolumeBootSector);
166 TRACE("sizeof(FATX_BOOTSECTOR) = 0x%x.\n", sizeof(FATX_BOOTSECTOR));
167
168 TRACE("FileSystemType: %c%c%c%c.\n", FatXVolumeBootSector->FileSystemType[0], FatXVolumeBootSector->FileSystemType[1], FatXVolumeBootSector->FileSystemType[2], FatXVolumeBootSector->FileSystemType[3]);
169 TRACE("VolumeSerialNumber: 0x%x\n", FatXVolumeBootSector->VolumeSerialNumber);
170 TRACE("SectorsPerCluster: %d\n", FatXVolumeBootSector->SectorsPerCluster);
171 TRACE("NumberOfFats: %d\n", FatXVolumeBootSector->NumberOfFats);
172 TRACE("Unknown: 0x%x\n", FatXVolumeBootSector->Unknown);
173
174 TRACE("FatType %s\n", Volume->FatType == FATX16 ? "FATX16" : "FATX32");
175
176 }
177 else if (Volume->FatType == FAT32)
178 {
179 FatSwapFat32BootSector(Fat32VolumeBootSector);
180 TRACE("sizeof(FAT32_BOOTSECTOR) = 0x%x.\n", sizeof(FAT32_BOOTSECTOR));
181
182 TRACE("JumpBoot: 0x%x 0x%x 0x%x\n", Fat32VolumeBootSector->JumpBoot[0], Fat32VolumeBootSector->JumpBoot[1], Fat32VolumeBootSector->JumpBoot[2]);
183 TRACE("OemName: %c%c%c%c%c%c%c%c\n", Fat32VolumeBootSector->OemName[0], Fat32VolumeBootSector->OemName[1], Fat32VolumeBootSector->OemName[2], Fat32VolumeBootSector->OemName[3], Fat32VolumeBootSector->OemName[4], Fat32VolumeBootSector->OemName[5], Fat32VolumeBootSector->OemName[6], Fat32VolumeBootSector->OemName[7]);
184 TRACE("BytesPerSector: %d\n", Fat32VolumeBootSector->BytesPerSector);
185 TRACE("SectorsPerCluster: %d\n", Fat32VolumeBootSector->SectorsPerCluster);
186 TRACE("ReservedSectors: %d\n", Fat32VolumeBootSector->ReservedSectors);
187 TRACE("NumberOfFats: %d\n", Fat32VolumeBootSector->NumberOfFats);
188 TRACE("RootDirEntries: %d\n", Fat32VolumeBootSector->RootDirEntries);
189 TRACE("TotalSectors: %d\n", Fat32VolumeBootSector->TotalSectors);
190 TRACE("MediaDescriptor: 0x%x\n", Fat32VolumeBootSector->MediaDescriptor);
191 TRACE("SectorsPerFat: %d\n", Fat32VolumeBootSector->SectorsPerFat);
192 TRACE("SectorsPerTrack: %d\n", Fat32VolumeBootSector->SectorsPerTrack);
193 TRACE("NumberOfHeads: %d\n", Fat32VolumeBootSector->NumberOfHeads);
194 TRACE("HiddenSectors: %d\n", Fat32VolumeBootSector->HiddenSectors);
195 TRACE("TotalSectorsBig: %d\n", Fat32VolumeBootSector->TotalSectorsBig);
196 TRACE("SectorsPerFatBig: %d\n", Fat32VolumeBootSector->SectorsPerFatBig);
197 TRACE("ExtendedFlags: 0x%x\n", Fat32VolumeBootSector->ExtendedFlags);
198 TRACE("FileSystemVersion: 0x%x\n", Fat32VolumeBootSector->FileSystemVersion);
199 TRACE("RootDirStartCluster: %d\n", Fat32VolumeBootSector->RootDirStartCluster);
200 TRACE("FsInfo: %d\n", Fat32VolumeBootSector->FsInfo);
201 TRACE("BackupBootSector: %d\n", Fat32VolumeBootSector->BackupBootSector);
202 TRACE("Reserved: 0x%x\n", Fat32VolumeBootSector->Reserved);
203 TRACE("DriveNumber: 0x%x\n", Fat32VolumeBootSector->DriveNumber);
204 TRACE("Reserved1: 0x%x\n", Fat32VolumeBootSector->Reserved1);
205 TRACE("BootSignature: 0x%x\n", Fat32VolumeBootSector->BootSignature);
206 TRACE("VolumeSerialNumber: 0x%x\n", Fat32VolumeBootSector->VolumeSerialNumber);
207 TRACE("VolumeLabel: %c%c%c%c%c%c%c%c%c%c%c\n", Fat32VolumeBootSector->VolumeLabel[0], Fat32VolumeBootSector->VolumeLabel[1], Fat32VolumeBootSector->VolumeLabel[2], Fat32VolumeBootSector->VolumeLabel[3], Fat32VolumeBootSector->VolumeLabel[4], Fat32VolumeBootSector->VolumeLabel[5], Fat32VolumeBootSector->VolumeLabel[6], Fat32VolumeBootSector->VolumeLabel[7], Fat32VolumeBootSector->VolumeLabel[8], Fat32VolumeBootSector->VolumeLabel[9], Fat32VolumeBootSector->VolumeLabel[10]);
208 TRACE("FileSystemType: %c%c%c%c%c%c%c%c\n", Fat32VolumeBootSector->FileSystemType[0], Fat32VolumeBootSector->FileSystemType[1], Fat32VolumeBootSector->FileSystemType[2], Fat32VolumeBootSector->FileSystemType[3], Fat32VolumeBootSector->FileSystemType[4], Fat32VolumeBootSector->FileSystemType[5], Fat32VolumeBootSector->FileSystemType[6], Fat32VolumeBootSector->FileSystemType[7]);
209 TRACE("BootSectorMagic: 0x%x\n", Fat32VolumeBootSector->BootSectorMagic);
210 }
211 else
212 {
213 FatSwapFatBootSector(FatVolumeBootSector);
214 TRACE("sizeof(FAT_BOOTSECTOR) = 0x%x.\n", sizeof(FAT_BOOTSECTOR));
215
216 TRACE("JumpBoot: 0x%x 0x%x 0x%x\n", FatVolumeBootSector->JumpBoot[0], FatVolumeBootSector->JumpBoot[1], FatVolumeBootSector->JumpBoot[2]);
217 TRACE("OemName: %c%c%c%c%c%c%c%c\n", FatVolumeBootSector->OemName[0], FatVolumeBootSector->OemName[1], FatVolumeBootSector->OemName[2], FatVolumeBootSector->OemName[3], FatVolumeBootSector->OemName[4], FatVolumeBootSector->OemName[5], FatVolumeBootSector->OemName[6], FatVolumeBootSector->OemName[7]);
218 TRACE("BytesPerSector: %d\n", FatVolumeBootSector->BytesPerSector);
219 TRACE("SectorsPerCluster: %d\n", FatVolumeBootSector->SectorsPerCluster);
220 TRACE("ReservedSectors: %d\n", FatVolumeBootSector->ReservedSectors);
221 TRACE("NumberOfFats: %d\n", FatVolumeBootSector->NumberOfFats);
222 TRACE("RootDirEntries: %d\n", FatVolumeBootSector->RootDirEntries);
223 TRACE("TotalSectors: %d\n", FatVolumeBootSector->TotalSectors);
224 TRACE("MediaDescriptor: 0x%x\n", FatVolumeBootSector->MediaDescriptor);
225 TRACE("SectorsPerFat: %d\n", FatVolumeBootSector->SectorsPerFat);
226 TRACE("SectorsPerTrack: %d\n", FatVolumeBootSector->SectorsPerTrack);
227 TRACE("NumberOfHeads: %d\n", FatVolumeBootSector->NumberOfHeads);
228 TRACE("HiddenSectors: %d\n", FatVolumeBootSector->HiddenSectors);
229 TRACE("TotalSectorsBig: %d\n", FatVolumeBootSector->TotalSectorsBig);
230 TRACE("DriveNumber: 0x%x\n", FatVolumeBootSector->DriveNumber);
231 TRACE("Reserved1: 0x%x\n", FatVolumeBootSector->Reserved1);
232 TRACE("BootSignature: 0x%x\n", FatVolumeBootSector->BootSignature);
233 TRACE("VolumeSerialNumber: 0x%x\n", FatVolumeBootSector->VolumeSerialNumber);
234 TRACE("VolumeLabel: %c%c%c%c%c%c%c%c%c%c%c\n", FatVolumeBootSector->VolumeLabel[0], FatVolumeBootSector->VolumeLabel[1], FatVolumeBootSector->VolumeLabel[2], FatVolumeBootSector->VolumeLabel[3], FatVolumeBootSector->VolumeLabel[4], FatVolumeBootSector->VolumeLabel[5], FatVolumeBootSector->VolumeLabel[6], FatVolumeBootSector->VolumeLabel[7], FatVolumeBootSector->VolumeLabel[8], FatVolumeBootSector->VolumeLabel[9], FatVolumeBootSector->VolumeLabel[10]);
235 TRACE("FileSystemType: %c%c%c%c%c%c%c%c\n", FatVolumeBootSector->FileSystemType[0], FatVolumeBootSector->FileSystemType[1], FatVolumeBootSector->FileSystemType[2], FatVolumeBootSector->FileSystemType[3], FatVolumeBootSector->FileSystemType[4], FatVolumeBootSector->FileSystemType[5], FatVolumeBootSector->FileSystemType[6], FatVolumeBootSector->FileSystemType[7]);
236 TRACE("BootSectorMagic: 0x%x\n", FatVolumeBootSector->BootSectorMagic);
237 }
238
239 //
240 // Check the boot sector magic
241 //
242 if (! ISFATX(Volume->FatType) && FatVolumeBootSector->BootSectorMagic != 0xaa55)
243 {
244 sprintf(ErrMsg, "Invalid boot sector magic (expected 0xaa55 found 0x%x)",
245 FatVolumeBootSector->BootSectorMagic);
246 FileSystemError(ErrMsg);
247 return FALSE;
248 }
249
250 //
251 // Check the FAT cluster size
252 // We do not support clusters bigger than 64k
253 //
254 if ((ISFATX(Volume->FatType) && 64 * 1024 < FatXVolumeBootSector->SectorsPerCluster * 512) ||
255 (! ISFATX(Volume->FatType) && 64 * 1024 < FatVolumeBootSector->SectorsPerCluster * FatVolumeBootSector->BytesPerSector))
256 {
257 FileSystemError("This file system has cluster sizes bigger than 64k.\nFreeLoader does not support this.");
258 return FALSE;
259 }
260
261 //
262 // Get the sectors per FAT,
263 // root directory starting sector,
264 // and data sector start
265 //
266 if (ISFATX(Volume->FatType))
267 {
268 Volume->BytesPerSector = 512;
269 Volume->SectorsPerCluster = SWAPD(FatXVolumeBootSector->SectorsPerCluster);
270 Volume->FatSectorStart = (4096 / Volume->BytesPerSector);
271 Volume->ActiveFatSectorStart = Volume->FatSectorStart;
272 Volume->NumberOfFats = 1;
273 FatSize = (ULONG)(PartitionSectorCount / Volume->SectorsPerCluster *
274 (Volume->FatType == FATX16 ? 2 : 4));
275 Volume->SectorsPerFat = (((FatSize + 4095) / 4096) * 4096) / Volume->BytesPerSector;
276
277 Volume->RootDirSectorStart = Volume->FatSectorStart + Volume->NumberOfFats * Volume->SectorsPerFat;
278 Volume->RootDirSectors = FatXVolumeBootSector->SectorsPerCluster;
279
280 Volume->DataSectorStart = Volume->RootDirSectorStart + Volume->RootDirSectors;
281 }
282 else if (Volume->FatType != FAT32)
283 {
284 Volume->BytesPerSector = FatVolumeBootSector->BytesPerSector;
285 Volume->SectorsPerCluster = FatVolumeBootSector->SectorsPerCluster;
286 Volume->FatSectorStart = FatVolumeBootSector->ReservedSectors;
287 Volume->ActiveFatSectorStart = Volume->FatSectorStart;
288 Volume->NumberOfFats = FatVolumeBootSector->NumberOfFats;
289 Volume->SectorsPerFat = FatVolumeBootSector->SectorsPerFat;
290
291 Volume->RootDirSectorStart = Volume->FatSectorStart + Volume->NumberOfFats * Volume->SectorsPerFat;
292 Volume->RootDirSectors = ((FatVolumeBootSector->RootDirEntries * 32) + (Volume->BytesPerSector - 1)) / Volume->BytesPerSector;
293
294 Volume->DataSectorStart = Volume->RootDirSectorStart + Volume->RootDirSectors;
295 }
296 else
297 {
298 Volume->BytesPerSector = Fat32VolumeBootSector->BytesPerSector;
299 Volume->SectorsPerCluster = Fat32VolumeBootSector->SectorsPerCluster;
300 Volume->FatSectorStart = Fat32VolumeBootSector->ReservedSectors;
301 Volume->ActiveFatSectorStart = Volume->FatSectorStart +
302 ((Fat32VolumeBootSector->ExtendedFlags & 0x80) ? ((Fat32VolumeBootSector->ExtendedFlags & 0x0f) * Fat32VolumeBootSector->SectorsPerFatBig) : 0);
303 Volume->NumberOfFats = Fat32VolumeBootSector->NumberOfFats;
304 Volume->SectorsPerFat = Fat32VolumeBootSector->SectorsPerFatBig;
305
306 Volume->RootDirStartCluster = Fat32VolumeBootSector->RootDirStartCluster;
307 Volume->DataSectorStart = Volume->FatSectorStart + Volume->NumberOfFats * Volume->SectorsPerFat;
308
309 //
310 // Check version
311 // we only work with version 0
312 //
313 if (Fat32VolumeBootSector->FileSystemVersion != 0)
314 {
315 FileSystemError("FreeLoader is too old to work with this FAT32 filesystem.\nPlease update FreeLoader.");
316 return FALSE;
317 }
318 }
319
320 return TRUE;
321 }
322
323 ULONG FatDetermineFatType(PFAT_BOOTSECTOR FatBootSector, ULONGLONG PartitionSectorCount)
324 {
325 ULONG RootDirSectors;
326 ULONG DataSectorCount;
327 ULONG SectorsPerFat;
328 ULONG TotalSectors;
329 ULONG CountOfClusters;
330 PFAT32_BOOTSECTOR Fat32BootSector = (PFAT32_BOOTSECTOR)FatBootSector;
331 PFATX_BOOTSECTOR FatXBootSector = (PFATX_BOOTSECTOR)FatBootSector;
332
333 if (0 == strncmp(FatXBootSector->FileSystemType, "FATX", 4))
334 {
335 CountOfClusters = (ULONG)(PartitionSectorCount / FatXBootSector->SectorsPerCluster);
336 if (CountOfClusters < 65525)
337 {
338 /* Volume is FATX16 */
339 return FATX16;
340 }
341 else
342 {
343 /* Volume is FAT32 */
344 return FATX32;
345 }
346 }
347 else
348 {
349 RootDirSectors = ((SWAPW(FatBootSector->RootDirEntries) * 32) + (SWAPW(FatBootSector->BytesPerSector) - 1)) / SWAPW(FatBootSector->BytesPerSector);
350 SectorsPerFat = SWAPW(FatBootSector->SectorsPerFat) ? SWAPW(FatBootSector->SectorsPerFat) : SWAPD(Fat32BootSector->SectorsPerFatBig);
351 TotalSectors = SWAPW(FatBootSector->TotalSectors) ? SWAPW(FatBootSector->TotalSectors) : SWAPD(FatBootSector->TotalSectorsBig);
352 DataSectorCount = TotalSectors - (SWAPW(FatBootSector->ReservedSectors) + (FatBootSector->NumberOfFats * SectorsPerFat) + RootDirSectors);
353
354 //mjl
355 if (FatBootSector->SectorsPerCluster == 0)
356 CountOfClusters = 0;
357 else
358 CountOfClusters = DataSectorCount / FatBootSector->SectorsPerCluster;
359
360 if (CountOfClusters < 4085)
361 {
362 /* Volume is FAT12 */
363 return FAT12;
364 }
365 else if (CountOfClusters < 65525)
366 {
367 /* Volume is FAT16 */
368 return FAT16;
369 }
370 else
371 {
372 /* Volume is FAT32 */
373 return FAT32;
374 }
375 }
376 }
377
378 typedef struct _DIRECTORY_BUFFER
379 {
380 LIST_ENTRY Link;
381 PVOID Volume;
382 ULONG DirectoryStartCluster;
383 ULONG DirectorySize;
384 UCHAR Data[];
385 } DIRECTORY_BUFFER, *PDIRECTORY_BUFFER;
386
387 LIST_ENTRY DirectoryBufferListHead = {&DirectoryBufferListHead, &DirectoryBufferListHead};
388
389 PVOID FatBufferDirectory(PFAT_VOLUME_INFO Volume, ULONG DirectoryStartCluster, ULONG *DirectorySize, BOOLEAN RootDirectory)
390 {
391 PDIRECTORY_BUFFER DirectoryBuffer;
392 PLIST_ENTRY Entry;
393
394 TRACE("FatBufferDirectory() DirectoryStartCluster = %d RootDirectory = %s\n", DirectoryStartCluster, (RootDirectory ? "TRUE" : "FALSE"));
395
396 /*
397 * For FAT32, the root directory is nothing special. We can treat it the same
398 * as a subdirectory.
399 */
400 if (RootDirectory && Volume->FatType == FAT32)
401 {
402 DirectoryStartCluster = Volume->RootDirStartCluster;
403 RootDirectory = FALSE;
404 }
405
406 /* Search the list for a match */
407 for (Entry = DirectoryBufferListHead.Flink;
408 Entry != &DirectoryBufferListHead;
409 Entry = Entry->Flink)
410 {
411 DirectoryBuffer = CONTAINING_RECORD(Entry, DIRECTORY_BUFFER, Link);
412
413 /* Check if it matches */
414 if ((DirectoryBuffer->Volume == Volume) &&
415 (DirectoryBuffer->DirectoryStartCluster == DirectoryStartCluster))
416 {
417 TRACE("Found cached buffer\n");
418 *DirectorySize = DirectoryBuffer->DirectorySize;
419 return DirectoryBuffer->Data;
420 }
421 }
422
423 //
424 // Calculate the size of the directory
425 //
426 if (RootDirectory)
427 {
428 *DirectorySize = Volume->RootDirSectors * Volume->BytesPerSector;
429 }
430 else
431 {
432 *DirectorySize = FatCountClustersInChain(Volume, DirectoryStartCluster) * Volume->SectorsPerCluster * Volume->BytesPerSector;
433 }
434
435 //
436 // Attempt to allocate memory for directory buffer
437 //
438 TRACE("Trying to allocate (DirectorySize) %d bytes.\n", *DirectorySize);
439 DirectoryBuffer = FrLdrTempAlloc(*DirectorySize + sizeof(DIRECTORY_BUFFER),
440 TAG_FAT_BUFFER);
441
442 if (DirectoryBuffer == NULL)
443 {
444 return NULL;
445 }
446
447 //
448 // Now read directory contents into DirectoryBuffer
449 //
450 if (RootDirectory)
451 {
452 if (!FatReadVolumeSectors(Volume, Volume->RootDirSectorStart, Volume->RootDirSectors, DirectoryBuffer->Data))
453 {
454 FrLdrTempFree(DirectoryBuffer, TAG_FAT_BUFFER);
455 return NULL;
456 }
457 }
458 else
459 {
460 if (!FatReadClusterChain(Volume, DirectoryStartCluster, 0xFFFFFFFF, DirectoryBuffer->Data))
461 {
462 FrLdrTempFree(DirectoryBuffer, TAG_FAT_BUFFER);
463 return NULL;
464 }
465 }
466
467 /* Enqueue it in the list */
468 DirectoryBuffer->Volume = Volume;
469 DirectoryBuffer->DirectoryStartCluster = DirectoryStartCluster;
470 DirectoryBuffer->DirectorySize = *DirectorySize;
471 InsertTailList(&DirectoryBufferListHead, &DirectoryBuffer->Link);
472
473 return DirectoryBuffer->Data;
474 }
475
476 BOOLEAN FatSearchDirectoryBufferForFile(PFAT_VOLUME_INFO Volume, PVOID DirectoryBuffer, ULONG DirectorySize, PCHAR FileName, PFAT_FILE_INFO FatFileInfoPointer)
477 {
478 ULONG EntryCount;
479 ULONG CurrentEntry;
480 CHAR LfnNameBuffer[265];
481 CHAR ShortNameBuffer[20];
482 ULONG StartCluster;
483 DIRENTRY OurDirEntry;
484 LFN_DIRENTRY OurLfnDirEntry;
485 PDIRENTRY DirEntry = &OurDirEntry;
486 PLFN_DIRENTRY LfnDirEntry = &OurLfnDirEntry;
487
488 EntryCount = DirectorySize / sizeof(DIRENTRY);
489
490 TRACE("FatSearchDirectoryBufferForFile() DirectoryBuffer = 0x%x EntryCount = %d FileName = %s\n", DirectoryBuffer, EntryCount, FileName);
491
492 memset(ShortNameBuffer, 0, 13 * sizeof(CHAR));
493 memset(LfnNameBuffer, 0, 261 * sizeof(CHAR));
494
495 for (CurrentEntry=0; CurrentEntry<EntryCount; CurrentEntry++, DirectoryBuffer = ((PDIRENTRY)DirectoryBuffer)+1)
496 {
497 OurLfnDirEntry = *((PLFN_DIRENTRY) DirectoryBuffer);
498 FatSwapLFNDirEntry(LfnDirEntry);
499 OurDirEntry = *((PDIRENTRY) DirectoryBuffer);
500 FatSwapDirEntry(DirEntry);
501
502 //TRACE("Dumping directory entry %d:\n", CurrentEntry);
503 //DbgDumpBuffer(DPRINT_FILESYSTEM, DirEntry, sizeof(DIRENTRY));
504
505 //
506 // Check if this is the last file in the directory
507 // If DirEntry[0] == 0x00 then that means all the
508 // entries after this one are unused. If this is the
509 // last entry then we didn't find the file in this directory.
510 //
511 if (DirEntry->FileName[0] == '\0')
512 {
513 return FALSE;
514 }
515
516 //
517 // Check if this is a deleted entry or not
518 //
519 if (DirEntry->FileName[0] == '\xE5')
520 {
521 memset(ShortNameBuffer, 0, 13 * sizeof(CHAR));
522 memset(LfnNameBuffer, 0, 261 * sizeof(CHAR));
523 continue;
524 }
525
526 //
527 // Check if this is a LFN entry
528 // If so it needs special handling
529 //
530 if (DirEntry->Attr == ATTR_LONG_NAME)
531 {
532 //
533 // Check to see if this is a deleted LFN entry, if so continue
534 //
535 if (LfnDirEntry->SequenceNumber & 0x80)
536 {
537 continue;
538 }
539
540 //
541 // Mask off high two bits of sequence number
542 // and make the sequence number zero-based
543 //
544 LfnDirEntry->SequenceNumber &= 0x3F;
545 LfnDirEntry->SequenceNumber--;
546
547 //
548 // Get all 13 LFN entry characters
549 //
550 if (LfnDirEntry->Name0_4[0] != 0xFFFF)
551 {
552 LfnNameBuffer[0 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name0_4[0];
553 }
554 if (LfnDirEntry->Name0_4[1] != 0xFFFF)
555 {
556 LfnNameBuffer[1 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name0_4[1];
557 }
558 if (LfnDirEntry->Name0_4[2] != 0xFFFF)
559 {
560 LfnNameBuffer[2 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name0_4[2];
561 }
562 if (LfnDirEntry->Name0_4[3] != 0xFFFF)
563 {
564 LfnNameBuffer[3 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name0_4[3];
565 }
566 if (LfnDirEntry->Name0_4[4] != 0xFFFF)
567 {
568 LfnNameBuffer[4 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name0_4[4];
569 }
570 if (LfnDirEntry->Name5_10[0] != 0xFFFF)
571 {
572 LfnNameBuffer[5 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name5_10[0];
573 }
574 if (LfnDirEntry->Name5_10[1] != 0xFFFF)
575 {
576 LfnNameBuffer[6 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name5_10[1];
577 }
578 if (LfnDirEntry->Name5_10[2] != 0xFFFF)
579 {
580 LfnNameBuffer[7 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name5_10[2];
581 }
582 if (LfnDirEntry->Name5_10[3] != 0xFFFF)
583 {
584 LfnNameBuffer[8 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name5_10[3];
585 }
586 if (LfnDirEntry->Name5_10[4] != 0xFFFF)
587 {
588 LfnNameBuffer[9 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name5_10[4];
589 }
590 if (LfnDirEntry->Name5_10[5] != 0xFFFF)
591 {
592 LfnNameBuffer[10 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name5_10[5];
593 }
594 if (LfnDirEntry->Name11_12[0] != 0xFFFF)
595 {
596 LfnNameBuffer[11 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name11_12[0];
597 }
598 if (LfnDirEntry->Name11_12[1] != 0xFFFF)
599 {
600 LfnNameBuffer[12 + (LfnDirEntry->SequenceNumber * 13)] = (UCHAR)LfnDirEntry->Name11_12[1];
601 }
602
603 //TRACE("Dumping long name buffer:\n");
604 //DbgDumpBuffer(DPRINT_FILESYSTEM, LfnNameBuffer, 260);
605
606 continue;
607 }
608
609 //
610 // Check for the volume label attribute
611 // and skip over this entry if found
612 //
613 if (DirEntry->Attr & ATTR_VOLUMENAME)
614 {
615 memset(ShortNameBuffer, 0, 13 * sizeof(UCHAR));
616 memset(LfnNameBuffer, 0, 261 * sizeof(UCHAR));
617 continue;
618 }
619
620 //
621 // If we get here then we've found a short file name
622 // entry and LfnNameBuffer contains the long file
623 // name or zeroes. All we have to do now is see if the
624 // file name matches either the short or long file name
625 // and fill in the FAT_FILE_INFO structure if it does
626 // or zero our buffers and continue looking.
627 //
628
629 //
630 // Get short file name
631 //
632 FatParseShortFileName(ShortNameBuffer, DirEntry);
633
634 //TRACE("Entry: %d LFN = %s\n", CurrentEntry, LfnNameBuffer);
635 //TRACE("Entry: %d DOS name = %s\n", CurrentEntry, ShortNameBuffer);
636
637 //
638 // See if the file name matches either the short or long name
639 //
640 if (((strlen(FileName) == strlen(LfnNameBuffer)) && (_stricmp(FileName, LfnNameBuffer) == 0)) ||
641 ((strlen(FileName) == strlen(ShortNameBuffer)) && (_stricmp(FileName, ShortNameBuffer) == 0))) {
642 //
643 // We found the entry, now fill in the FAT_FILE_INFO struct
644 //
645 FatFileInfoPointer->Attributes = DirEntry->Attr;
646 FatFileInfoPointer->FileSize = DirEntry->Size;
647 FatFileInfoPointer->FilePointer = 0;
648
649 TRACE("MSDOS Directory Entry:\n");
650 TRACE("FileName[11] = %c%c%c%c%c%c%c%c%c%c%c\n", DirEntry->FileName[0], DirEntry->FileName[1], DirEntry->FileName[2], DirEntry->FileName[3], DirEntry->FileName[4], DirEntry->FileName[5], DirEntry->FileName[6], DirEntry->FileName[7], DirEntry->FileName[8], DirEntry->FileName[9], DirEntry->FileName[10]);
651 TRACE("Attr = 0x%x\n", DirEntry->Attr);
652 TRACE("ReservedNT = 0x%x\n", DirEntry->ReservedNT);
653 TRACE("TimeInTenths = %d\n", DirEntry->TimeInTenths);
654 TRACE("CreateTime = %d\n", DirEntry->CreateTime);
655 TRACE("CreateDate = %d\n", DirEntry->CreateDate);
656 TRACE("LastAccessDate = %d\n", DirEntry->LastAccessDate);
657 TRACE("ClusterHigh = 0x%x\n", DirEntry->ClusterHigh);
658 TRACE("Time = %d\n", DirEntry->Time);
659 TRACE("Date = %d\n", DirEntry->Date);
660 TRACE("ClusterLow = 0x%x\n", DirEntry->ClusterLow);
661 TRACE("Size = %d\n", DirEntry->Size);
662
663 //
664 // Get the cluster chain
665 //
666 StartCluster = ((ULONG)DirEntry->ClusterHigh << 16) + DirEntry->ClusterLow;
667 TRACE("StartCluster = 0x%x\n", StartCluster);
668 FatFileInfoPointer->FileFatChain = FatGetClusterChainArray(Volume, StartCluster);
669
670 //
671 // See if memory allocation failed
672 //
673 if (FatFileInfoPointer->FileFatChain == NULL)
674 {
675 return FALSE;
676 }
677
678 return TRUE;
679 }
680
681 //
682 // Nope, no match - zero buffers and continue looking
683 //
684 memset(ShortNameBuffer, 0, 13 * sizeof(UCHAR));
685 memset(LfnNameBuffer, 0, 261 * sizeof(UCHAR));
686 continue;
687 }
688
689 return FALSE;
690 }
691
692 static BOOLEAN FatXSearchDirectoryBufferForFile(PFAT_VOLUME_INFO Volume, PVOID DirectoryBuffer, ULONG DirectorySize, PCHAR FileName, PFAT_FILE_INFO FatFileInfoPointer)
693 {
694 ULONG EntryCount;
695 ULONG CurrentEntry;
696 SIZE_T FileNameLen;
697 FATX_DIRENTRY OurDirEntry;
698 PFATX_DIRENTRY DirEntry = &OurDirEntry;
699
700 EntryCount = DirectorySize / sizeof(FATX_DIRENTRY);
701
702 TRACE("FatXSearchDirectoryBufferForFile() DirectoryBuffer = 0x%x EntryCount = %d FileName = %s\n", DirectoryBuffer, EntryCount, FileName);
703
704 FileNameLen = strlen(FileName);
705
706 for (CurrentEntry = 0; CurrentEntry < EntryCount; CurrentEntry++, DirectoryBuffer = ((PFATX_DIRENTRY)DirectoryBuffer)+1)
707 {
708 OurDirEntry = *(PFATX_DIRENTRY) DirectoryBuffer;
709 FatSwapFatXDirEntry(&OurDirEntry);
710 if (0xff == DirEntry->FileNameSize)
711 {
712 break;
713 }
714 if (0xe5 == DirEntry->FileNameSize)
715 {
716 continue;
717 }
718 if (FileNameLen == DirEntry->FileNameSize &&
719 0 == _strnicmp(FileName, DirEntry->FileName, FileNameLen))
720 {
721 /*
722 * We found the entry, now fill in the FAT_FILE_INFO struct
723 */
724 FatFileInfoPointer->FileSize = DirEntry->Size;
725 FatFileInfoPointer->FilePointer = 0;
726
727 TRACE("FATX Directory Entry:\n");
728 TRACE("FileNameSize = %d\n", DirEntry->FileNameSize);
729 TRACE("Attr = 0x%x\n", DirEntry->Attr);
730 TRACE("StartCluster = 0x%x\n", DirEntry->StartCluster);
731 TRACE("Size = %d\n", DirEntry->Size);
732 TRACE("Time = %d\n", DirEntry->Time);
733 TRACE("Date = %d\n", DirEntry->Date);
734 TRACE("CreateTime = %d\n", DirEntry->CreateTime);
735 TRACE("CreateDate = %d\n", DirEntry->CreateDate);
736 TRACE("LastAccessTime = %d\n", DirEntry->LastAccessTime);
737 TRACE("LastAccessDate = %d\n", DirEntry->LastAccessDate);
738
739 /*
740 * Get the cluster chain
741 */
742 FatFileInfoPointer->FileFatChain = FatGetClusterChainArray(Volume, DirEntry->StartCluster);
743
744 /*
745 * See if memory allocation failed
746 */
747 if (NULL == FatFileInfoPointer->FileFatChain)
748 {
749 return FALSE;
750 }
751
752 return TRUE;
753 }
754 }
755
756 return FALSE;
757 }
758
759 /*
760 * FatLookupFile()
761 * This function searches the file system for the
762 * specified filename and fills in an FAT_FILE_INFO structure
763 * with info describing the file, etc. returns ARC error code
764 */
765 ARC_STATUS FatLookupFile(PFAT_VOLUME_INFO Volume, PCSTR FileName, ULONG DeviceId, PFAT_FILE_INFO FatFileInfoPointer)
766 {
767 UINT32 i;
768 ULONG NumberOfPathParts;
769 CHAR PathPart[261];
770 PVOID DirectoryBuffer;
771 ULONG DirectoryStartCluster = 0;
772 ULONG DirectorySize;
773 FAT_FILE_INFO FatFileInfo;
774
775 TRACE("FatLookupFile() FileName = %s\n", FileName);
776
777 memset(FatFileInfoPointer, 0, sizeof(FAT_FILE_INFO));
778
779 //
780 // Figure out how many sub-directories we are nested in
781 //
782 NumberOfPathParts = FsGetNumPathParts(FileName);
783
784 //
785 // Loop once for each part
786 //
787 for (i=0; i<NumberOfPathParts; i++)
788 {
789 //
790 // Get first path part
791 //
792 FsGetFirstNameFromPath(PathPart, FileName);
793
794 //
795 // Advance to the next part of the path
796 //
797 for (; (*FileName != '\\') && (*FileName != '/') && (*FileName != '\0'); FileName++)
798 {
799 }
800 FileName++;
801
802 //
803 // Buffer the directory contents
804 //
805 DirectoryBuffer = FatBufferDirectory(Volume, DirectoryStartCluster, &DirectorySize, (i == 0) );
806 if (DirectoryBuffer == NULL)
807 {
808 return ENOMEM;
809 }
810
811 //
812 // Search for file name in directory
813 //
814 if (ISFATX(Volume->FatType))
815 {
816 if (!FatXSearchDirectoryBufferForFile(Volume, DirectoryBuffer, DirectorySize, PathPart, &FatFileInfo))
817 {
818 return ENOENT;
819 }
820 }
821 else
822 {
823 if (!FatSearchDirectoryBufferForFile(Volume, DirectoryBuffer, DirectorySize, PathPart, &FatFileInfo))
824 {
825 return ENOENT;
826 }
827 }
828
829 //
830 // If we have another sub-directory to go then
831 // grab the start cluster and free the fat chain array
832 //
833 if ((i+1) < NumberOfPathParts)
834 {
835 //
836 // Check if current entry is a directory
837 //
838 if (!(FatFileInfo.Attributes & ATTR_DIRECTORY))
839 {
840 FrLdrTempFree(FatFileInfo.FileFatChain, TAG_FAT_CHAIN);
841 return ENOTDIR;
842 }
843 DirectoryStartCluster = FatFileInfo.FileFatChain[0];
844 FrLdrTempFree(FatFileInfo.FileFatChain, TAG_FAT_CHAIN);
845 FatFileInfo.FileFatChain = NULL;
846 }
847 }
848
849 memcpy(FatFileInfoPointer, &FatFileInfo, sizeof(FAT_FILE_INFO));
850
851 return ESUCCESS;
852 }
853
854 /*
855 * FatParseFileName()
856 * This function parses a directory entry name which
857 * is in the form of "FILE EXT" and puts it in Buffer
858 * in the form of "file.ext"
859 */
860 void FatParseShortFileName(PCHAR Buffer, PDIRENTRY DirEntry)
861 {
862 ULONG Idx;
863
864 Idx = 0;
865 RtlZeroMemory(Buffer, 13);
866
867 //
868 // Fixup first character
869 //
870 if (DirEntry->FileName[0] == 0x05)
871 {
872 DirEntry->FileName[0] = 0xE5;
873 }
874
875 //
876 // Get the file name
877 //
878 while (Idx < 8)
879 {
880 if (DirEntry->FileName[Idx] == ' ')
881 {
882 break;
883 }
884
885 Buffer[Idx] = DirEntry->FileName[Idx];
886 Idx++;
887 }
888
889 //
890 // Get extension
891 //
892 if ((DirEntry->FileName[8] != ' '))
893 {
894 Buffer[Idx++] = '.';
895 Buffer[Idx++] = (DirEntry->FileName[8] == ' ') ? '\0' : DirEntry->FileName[8];
896 Buffer[Idx++] = (DirEntry->FileName[9] == ' ') ? '\0' : DirEntry->FileName[9];
897 Buffer[Idx++] = (DirEntry->FileName[10] == ' ') ? '\0' : DirEntry->FileName[10];
898 }
899
900 //TRACE("FatParseShortFileName() ShortName = %s\n", Buffer);
901 }
902
903 /*
904 * FatGetFatEntry()
905 * returns the Fat entry for a given cluster number
906 */
907 BOOLEAN FatGetFatEntry(PFAT_VOLUME_INFO Volume, ULONG Cluster, ULONG* ClusterPointer)
908 {
909 ULONG fat = 0;
910 UINT32 FatOffset;
911 UINT32 ThisFatSecNum;
912 UINT32 ThisFatEntOffset;
913 ULONG SectorCount;
914 PUCHAR ReadBuffer;
915 BOOLEAN Success = TRUE;
916
917 //TRACE("FatGetFatEntry() Retrieving FAT entry for cluster %d.\n", Cluster);
918
919 // We need a buffer for 2 secors
920 ReadBuffer = FrLdrTempAlloc(2 * Volume->BytesPerSector, TAG_FAT_BUFFER);
921 if (!ReadBuffer)
922 {
923 return FALSE;
924 }
925
926 switch(Volume->FatType)
927 {
928 case FAT12:
929
930 FatOffset = Cluster + (Cluster / 2);
931 ThisFatSecNum = Volume->ActiveFatSectorStart + (FatOffset / Volume->BytesPerSector);
932 ThisFatEntOffset = (FatOffset % Volume->BytesPerSector);
933
934 TRACE("FatOffset: %d\n", FatOffset);
935 TRACE("ThisFatSecNum: %d\n", ThisFatSecNum);
936 TRACE("ThisFatEntOffset: %d\n", ThisFatEntOffset);
937
938 if (ThisFatEntOffset == (Volume->BytesPerSector - 1))
939 {
940 SectorCount = 2;
941 }
942 else
943 {
944 SectorCount = 1;
945 }
946
947 if (!FatReadVolumeSectors(Volume, ThisFatSecNum, SectorCount, ReadBuffer))
948 {
949 Success = FALSE;
950 break;
951 }
952
953 fat = *((USHORT *) (ReadBuffer + ThisFatEntOffset));
954 fat = SWAPW(fat);
955 if (Cluster & 0x0001)
956 fat = fat >> 4; /* Cluster number is ODD */
957 else
958 fat = fat & 0x0FFF; /* Cluster number is EVEN */
959
960 break;
961
962 case FAT16:
963 case FATX16:
964
965 FatOffset = (Cluster * 2);
966 ThisFatSecNum = Volume->ActiveFatSectorStart + (FatOffset / Volume->BytesPerSector);
967 ThisFatEntOffset = (FatOffset % Volume->BytesPerSector);
968
969 if (!FatReadVolumeSectors(Volume, ThisFatSecNum, 1, ReadBuffer))
970 {
971 Success = FALSE;
972 break;
973 }
974
975 fat = *((USHORT *) (ReadBuffer + ThisFatEntOffset));
976 fat = SWAPW(fat);
977
978 break;
979
980 case FAT32:
981 case FATX32:
982
983 FatOffset = (Cluster * 4);
984 ThisFatSecNum = Volume->ActiveFatSectorStart + (FatOffset / Volume->BytesPerSector);
985 ThisFatEntOffset = (FatOffset % Volume->BytesPerSector);
986
987 if (!FatReadVolumeSectors(Volume, ThisFatSecNum, 1, ReadBuffer))
988 {
989 return FALSE;
990 }
991
992 // Get the fat entry
993 fat = (*((ULONG *) (ReadBuffer + ThisFatEntOffset))) & 0x0FFFFFFF;
994 fat = SWAPD(fat);
995
996 break;
997
998 default:
999 ERR("Unknown FAT type %d\n", Volume->FatType);
1000 Success = FALSE;
1001 break;
1002 }
1003
1004 //TRACE("FAT entry is 0x%x.\n", fat);
1005
1006 FrLdrTempFree(ReadBuffer, TAG_FAT_BUFFER);
1007
1008 *ClusterPointer = fat;
1009
1010 return Success;
1011 }
1012
1013 ULONG FatCountClustersInChain(PFAT_VOLUME_INFO Volume, ULONG StartCluster)
1014 {
1015 ULONG ClusterCount = 0;
1016
1017 TRACE("FatCountClustersInChain() StartCluster = %d\n", StartCluster);
1018
1019 while (1)
1020 {
1021 //
1022 // If end of chain then break out of our cluster counting loop
1023 //
1024 if (((Volume->FatType == FAT12) && (StartCluster >= 0xff8)) ||
1025 ((Volume->FatType == FAT16 || Volume->FatType == FATX16) && (StartCluster >= 0xfff8)) ||
1026 ((Volume->FatType == FAT32 || Volume->FatType == FATX32) && (StartCluster >= 0x0ffffff8)))
1027 {
1028 break;
1029 }
1030
1031 //
1032 // Increment count
1033 //
1034 ClusterCount++;
1035
1036 //
1037 // Get next cluster
1038 //
1039 if (!FatGetFatEntry(Volume, StartCluster, &StartCluster))
1040 {
1041 return 0;
1042 }
1043 }
1044
1045 TRACE("FatCountClustersInChain() ClusterCount = %d\n", ClusterCount);
1046
1047 return ClusterCount;
1048 }
1049
1050 ULONG* FatGetClusterChainArray(PFAT_VOLUME_INFO Volume, ULONG StartCluster)
1051 {
1052 ULONG ClusterCount;
1053 ULONG ArraySize;
1054 ULONG* ArrayPointer;
1055 ULONG Idx;
1056
1057 TRACE("FatGetClusterChainArray() StartCluster = %d\n", StartCluster);
1058
1059 ClusterCount = FatCountClustersInChain(Volume, StartCluster) + 1; // Lets get the 0x0ffffff8 on the end of the array
1060 ArraySize = ClusterCount * sizeof(ULONG);
1061
1062 //
1063 // Allocate array memory
1064 //
1065 ArrayPointer = FrLdrTempAlloc(ArraySize, TAG_FAT_CHAIN);
1066
1067 if (ArrayPointer == NULL)
1068 {
1069 return NULL;
1070 }
1071
1072 //
1073 // Loop through and set array values
1074 //
1075 for (Idx=0; Idx<ClusterCount; Idx++)
1076 {
1077 //
1078 // Set current cluster
1079 //
1080 ArrayPointer[Idx] = StartCluster;
1081
1082 //
1083 // Don't try to get next cluster for last cluster
1084 //
1085 if (((Volume->FatType == FAT12) && (StartCluster >= 0xff8)) ||
1086 ((Volume->FatType == FAT16 || Volume->FatType == FATX16) && (StartCluster >= 0xfff8)) ||
1087 ((Volume->FatType == FAT32 || Volume->FatType == FATX32) && (StartCluster >= 0x0ffffff8)))
1088 {
1089 Idx++;
1090 break;
1091 }
1092
1093 //
1094 // Get next cluster
1095 //
1096 if (!FatGetFatEntry(Volume, StartCluster, &StartCluster))
1097 {
1098 FrLdrTempFree(ArrayPointer, TAG_FAT_CHAIN);
1099 return NULL;
1100 }
1101 }
1102
1103 return ArrayPointer;
1104 }
1105
1106 /*
1107 * FatReadClusterChain()
1108 * Reads the specified clusters into memory
1109 */
1110 BOOLEAN FatReadClusterChain(PFAT_VOLUME_INFO Volume, ULONG StartClusterNumber, ULONG NumberOfClusters, PVOID Buffer)
1111 {
1112 ULONG ClusterStartSector;
1113
1114 TRACE("FatReadClusterChain() StartClusterNumber = %d NumberOfClusters = %d Buffer = 0x%x\n", StartClusterNumber, NumberOfClusters, Buffer);
1115
1116 while (NumberOfClusters > 0)
1117 {
1118
1119 //TRACE("FatReadClusterChain() StartClusterNumber = %d NumberOfClusters = %d Buffer = 0x%x\n", StartClusterNumber, NumberOfClusters, Buffer);
1120 //
1121 // Calculate starting sector for cluster
1122 //
1123 ClusterStartSector = ((StartClusterNumber - 2) * Volume->SectorsPerCluster) + Volume->DataSectorStart;
1124
1125 //
1126 // Read cluster into memory
1127 //
1128 if (!FatReadVolumeSectors(Volume, ClusterStartSector, Volume->SectorsPerCluster, Buffer))
1129 {
1130 return FALSE;
1131 }
1132
1133 //
1134 // Decrement count of clusters left to read
1135 //
1136 NumberOfClusters--;
1137
1138 //
1139 // Increment buffer address by cluster size
1140 //
1141 Buffer = (PVOID)((ULONG_PTR)Buffer + (Volume->SectorsPerCluster * Volume->BytesPerSector));
1142
1143 //
1144 // Get next cluster
1145 //
1146 if (!FatGetFatEntry(Volume, StartClusterNumber, &StartClusterNumber))
1147 {
1148 return FALSE;
1149 }
1150
1151 //
1152 // If end of chain then break out of our cluster reading loop
1153 //
1154 if (((Volume->FatType == FAT12) && (StartClusterNumber >= 0xff8)) ||
1155 ((Volume->FatType == FAT16 || Volume->FatType == FATX16) && (StartClusterNumber >= 0xfff8)) ||
1156 ((Volume->FatType == FAT32 || Volume->FatType == FATX32) && (StartClusterNumber >= 0x0ffffff8)))
1157 {
1158 break;
1159 }
1160 }
1161
1162 return TRUE;
1163 }
1164
1165 /*
1166 * FatReadPartialCluster()
1167 * Reads part of a cluster into memory
1168 */
1169 BOOLEAN FatReadPartialCluster(PFAT_VOLUME_INFO Volume, ULONG ClusterNumber, ULONG StartingOffset, ULONG Length, PVOID Buffer)
1170 {
1171 ULONG ClusterStartSector;
1172 ULONG SectorOffset, ReadSize, SectorCount;
1173 PUCHAR ReadBuffer;
1174 BOOLEAN Success = FALSE;
1175
1176 //TRACE("FatReadPartialCluster() ClusterNumber = %d StartingOffset = %d Length = %d Buffer = 0x%x\n", ClusterNumber, StartingOffset, Length, Buffer);
1177
1178 ClusterStartSector = ((ClusterNumber - 2) * Volume->SectorsPerCluster) + Volume->DataSectorStart;
1179
1180 // This is the offset of the data in sectors
1181 SectorOffset = (StartingOffset / Volume->BytesPerSector);
1182 StartingOffset %= Volume->BytesPerSector;
1183
1184 // Calculate how many sectors we need to read
1185 SectorCount = (StartingOffset + Length + Volume->BytesPerSector - 1) / Volume->BytesPerSector;
1186
1187 // Calculate rounded up read size
1188 ReadSize = SectorCount * Volume->BytesPerSector;
1189
1190 ReadBuffer = FrLdrTempAlloc(ReadSize, TAG_FAT_BUFFER);
1191 if (!ReadBuffer)
1192 {
1193 return FALSE;
1194 }
1195
1196 if (FatReadVolumeSectors(Volume, ClusterStartSector + SectorOffset, SectorCount, ReadBuffer))
1197 {
1198 memcpy(Buffer, ReadBuffer + StartingOffset, Length);
1199 Success = TRUE;
1200 }
1201
1202 FrLdrTempFree(ReadBuffer, TAG_FAT_BUFFER);
1203
1204 return Success;
1205 }
1206
1207 /*
1208 * FatReadFile()
1209 * Reads BytesToRead from open file and
1210 * returns the number of bytes read in BytesRead
1211 */
1212 BOOLEAN FatReadFile(PFAT_FILE_INFO FatFileInfo, ULONG BytesToRead, ULONG* BytesRead, PVOID Buffer)
1213 {
1214 PFAT_VOLUME_INFO Volume = FatFileInfo->Volume;
1215 ULONG ClusterNumber;
1216 ULONG OffsetInCluster;
1217 ULONG LengthInCluster;
1218 ULONG NumberOfClusters;
1219 ULONG BytesPerCluster;
1220
1221 TRACE("FatReadFile() BytesToRead = %d Buffer = 0x%x\n", BytesToRead, Buffer);
1222
1223 if (BytesRead != NULL)
1224 {
1225 *BytesRead = 0;
1226 }
1227
1228 //
1229 // If they are trying to read past the
1230 // end of the file then return success
1231 // with BytesRead == 0
1232 //
1233 if (FatFileInfo->FilePointer >= FatFileInfo->FileSize)
1234 {
1235 return TRUE;
1236 }
1237
1238 //
1239 // If they are trying to read more than there is to read
1240 // then adjust the amount to read
1241 //
1242 if ((FatFileInfo->FilePointer + BytesToRead) > FatFileInfo->FileSize)
1243 {
1244 BytesToRead = (FatFileInfo->FileSize - FatFileInfo->FilePointer);
1245 }
1246
1247 //
1248 // Ok, now we have to perform at most 3 calculations
1249 // I'll draw you a picture (using nifty ASCII art):
1250 //
1251 // CurrentFilePointer -+
1252 // |
1253 // +----------------+
1254 // |
1255 // +-----------+-----------+-----------+-----------+
1256 // | Cluster 1 | Cluster 2 | Cluster 3 | Cluster 4 |
1257 // +-----------+-----------+-----------+-----------+
1258 // | |
1259 // +---------------+--------------------+
1260 // |
1261 // BytesToRead -------+
1262 //
1263 // 1 - The first calculation (and read) will align
1264 // the file pointer with the next cluster.
1265 // boundary (if we are supposed to read that much)
1266 // 2 - The next calculation (and read) will read
1267 // in all the full clusters that the requested
1268 // amount of data would cover (in this case
1269 // clusters 2 & 3).
1270 // 3 - The last calculation (and read) would read
1271 // in the remainder of the data requested out of
1272 // the last cluster.
1273 //
1274
1275 BytesPerCluster = Volume->SectorsPerCluster * Volume->BytesPerSector;
1276
1277 //
1278 // Only do the first read if we
1279 // aren't aligned on a cluster boundary
1280 //
1281 if (FatFileInfo->FilePointer % BytesPerCluster)
1282 {
1283 //
1284 // Do the math for our first read
1285 //
1286 ClusterNumber = (FatFileInfo->FilePointer / BytesPerCluster);
1287 ClusterNumber = FatFileInfo->FileFatChain[ClusterNumber];
1288 OffsetInCluster = (FatFileInfo->FilePointer % BytesPerCluster);
1289 LengthInCluster = (BytesToRead > (BytesPerCluster - OffsetInCluster)) ? (BytesPerCluster - OffsetInCluster) : BytesToRead;
1290
1291 //
1292 // Now do the read and update BytesRead, BytesToRead, FilePointer, & Buffer
1293 //
1294 if (!FatReadPartialCluster(Volume, ClusterNumber, OffsetInCluster, LengthInCluster, Buffer))
1295 {
1296 return FALSE;
1297 }
1298 if (BytesRead != NULL)
1299 {
1300 *BytesRead += LengthInCluster;
1301 }
1302 BytesToRead -= LengthInCluster;
1303 FatFileInfo->FilePointer += LengthInCluster;
1304 Buffer = (PVOID)((ULONG_PTR)Buffer + LengthInCluster);
1305 }
1306
1307 //
1308 // Do the math for our second read (if any data left)
1309 //
1310 if (BytesToRead > 0)
1311 {
1312 //
1313 // Determine how many full clusters we need to read
1314 //
1315 NumberOfClusters = (BytesToRead / BytesPerCluster);
1316
1317 if (NumberOfClusters > 0)
1318 {
1319 ClusterNumber = (FatFileInfo->FilePointer / BytesPerCluster);
1320 ClusterNumber = FatFileInfo->FileFatChain[ClusterNumber];
1321
1322 //
1323 // Now do the read and update BytesRead, BytesToRead, FilePointer, & Buffer
1324 //
1325 if (!FatReadClusterChain(Volume, ClusterNumber, NumberOfClusters, Buffer))
1326 {
1327 return FALSE;
1328 }
1329 if (BytesRead != NULL)
1330 {
1331 *BytesRead += (NumberOfClusters * BytesPerCluster);
1332 }
1333 BytesToRead -= (NumberOfClusters * BytesPerCluster);
1334 FatFileInfo->FilePointer += (NumberOfClusters * BytesPerCluster);
1335 Buffer = (PVOID)((ULONG_PTR)Buffer + (NumberOfClusters * BytesPerCluster));
1336 }
1337 }
1338
1339 //
1340 // Do the math for our third read (if any data left)
1341 //
1342 if (BytesToRead > 0)
1343 {
1344 ClusterNumber = (FatFileInfo->FilePointer / BytesPerCluster);
1345 ClusterNumber = FatFileInfo->FileFatChain[ClusterNumber];
1346
1347 //
1348 // Now do the read and update BytesRead, BytesToRead, FilePointer, & Buffer
1349 //
1350 if (!FatReadPartialCluster(Volume, ClusterNumber, 0, BytesToRead, Buffer))
1351 {
1352 return FALSE;
1353 }
1354 if (BytesRead != NULL)
1355 {
1356 *BytesRead += BytesToRead;
1357 }
1358 FatFileInfo->FilePointer += BytesToRead;
1359 BytesToRead -= BytesToRead;
1360 Buffer = (PVOID)((ULONG_PTR)Buffer + BytesToRead);
1361 }
1362
1363 return TRUE;
1364 }
1365
1366 BOOLEAN FatReadVolumeSectors(PFAT_VOLUME_INFO Volume, ULONG SectorNumber, ULONG SectorCount, PVOID Buffer)
1367 {
1368 LARGE_INTEGER Position;
1369 ULONG Count;
1370 ARC_STATUS Status;
1371
1372 //TRACE("FatReadVolumeSectors(): SectorNumber %d, SectorCount %d, Buffer %p\n",
1373 // SectorNumber, SectorCount, Buffer);
1374
1375 //
1376 // Seek to right position
1377 //
1378 Position.QuadPart = (ULONGLONG)SectorNumber * 512;
1379 Status = ArcSeek(Volume->DeviceId, &Position, SeekAbsolute);
1380 if (Status != ESUCCESS)
1381 {
1382 TRACE("FatReadVolumeSectors() Failed to seek\n");
1383 return FALSE;
1384 }
1385
1386 //
1387 // Read data
1388 //
1389 Status = ArcRead(Volume->DeviceId, Buffer, SectorCount * 512, &Count);
1390 if (Status != ESUCCESS || Count != SectorCount * 512)
1391 {
1392 TRACE("FatReadVolumeSectors() Failed to read\n");
1393 return FALSE;
1394 }
1395
1396 // Return success
1397 return TRUE;
1398 }
1399
1400 ARC_STATUS FatClose(ULONG FileId)
1401 {
1402 PFAT_FILE_INFO FileHandle = FsGetDeviceSpecific(FileId);
1403
1404 if (FileHandle->FileFatChain) FrLdrTempFree(FileHandle->FileFatChain, TAG_FAT_CHAIN);
1405 FrLdrTempFree(FileHandle, TAG_FAT_FILE);
1406
1407 return ESUCCESS;
1408 }
1409
1410 ARC_STATUS FatGetFileInformation(ULONG FileId, FILEINFORMATION* Information)
1411 {
1412 PFAT_FILE_INFO FileHandle = FsGetDeviceSpecific(FileId);
1413
1414 RtlZeroMemory(Information, sizeof(FILEINFORMATION));
1415 Information->EndingAddress.LowPart = FileHandle->FileSize;
1416 Information->CurrentAddress.LowPart = FileHandle->FilePointer;
1417
1418 TRACE("FatGetFileInformation() FileSize = %d\n",
1419 Information->EndingAddress.LowPart);
1420 TRACE("FatGetFileInformation() FilePointer = %d\n",
1421 Information->CurrentAddress.LowPart);
1422
1423 return ESUCCESS;
1424 }
1425
1426 ARC_STATUS FatOpen(CHAR* Path, OPENMODE OpenMode, ULONG* FileId)
1427 {
1428 PFAT_VOLUME_INFO FatVolume;
1429 FAT_FILE_INFO TempFileInfo;
1430 PFAT_FILE_INFO FileHandle;
1431 ULONG DeviceId;
1432 BOOLEAN IsDirectory;
1433 ARC_STATUS Status;
1434
1435 if (OpenMode != OpenReadOnly && OpenMode != OpenDirectory)
1436 return EACCES;
1437
1438 DeviceId = FsGetDeviceId(*FileId);
1439 FatVolume = FatVolumes[DeviceId];
1440
1441 TRACE("FatOpen() FileName = %s\n", Path);
1442
1443 RtlZeroMemory(&TempFileInfo, sizeof(TempFileInfo));
1444 Status = FatLookupFile(FatVolume, Path, DeviceId, &TempFileInfo);
1445 if (Status != ESUCCESS)
1446 return ENOENT;
1447
1448 //
1449 // Check if caller opened what he expected (dir vs file)
1450 //
1451 IsDirectory = (TempFileInfo.Attributes & ATTR_DIRECTORY) != 0;
1452 if (IsDirectory && OpenMode != OpenDirectory)
1453 return EISDIR;
1454 else if (!IsDirectory && OpenMode != OpenReadOnly)
1455 return ENOTDIR;
1456
1457 FileHandle = FrLdrTempAlloc(sizeof(FAT_FILE_INFO), TAG_FAT_FILE);
1458 if (!FileHandle)
1459 return ENOMEM;
1460
1461 RtlCopyMemory(FileHandle, &TempFileInfo, sizeof(FAT_FILE_INFO));
1462 FileHandle->Volume = FatVolume;
1463
1464 FsSetDeviceSpecific(*FileId, FileHandle);
1465 return ESUCCESS;
1466 }
1467
1468 ARC_STATUS FatRead(ULONG FileId, VOID* Buffer, ULONG N, ULONG* Count)
1469 {
1470 PFAT_FILE_INFO FileHandle = FsGetDeviceSpecific(FileId);
1471 BOOLEAN Success;
1472
1473 //
1474 // Call old read method
1475 //
1476 Success = FatReadFile(FileHandle, N, Count, Buffer);
1477
1478 //
1479 // Check for success
1480 //
1481 if (Success)
1482 return ESUCCESS;
1483 else
1484 return EIO;
1485 }
1486
1487 ARC_STATUS FatSeek(ULONG FileId, LARGE_INTEGER* Position, SEEKMODE SeekMode)
1488 {
1489 PFAT_FILE_INFO FileHandle = FsGetDeviceSpecific(FileId);
1490
1491 TRACE("FatSeek() NewFilePointer = %lu\n", Position->LowPart);
1492
1493 if (SeekMode != SeekAbsolute)
1494 return EINVAL;
1495 if (Position->HighPart != 0)
1496 return EINVAL;
1497 if (Position->LowPart >= FileHandle->FileSize)
1498 return EINVAL;
1499
1500 FileHandle->FilePointer = Position->LowPart;
1501 return ESUCCESS;
1502 }
1503
1504 const DEVVTBL FatFuncTable =
1505 {
1506 FatClose,
1507 FatGetFileInformation,
1508 FatOpen,
1509 FatRead,
1510 FatSeek,
1511 L"fastfat",
1512 };
1513
1514 const DEVVTBL* FatMount(ULONG DeviceId)
1515 {
1516 PFAT_VOLUME_INFO Volume;
1517 UCHAR Buffer[512];
1518 PFAT_BOOTSECTOR BootSector = (PFAT_BOOTSECTOR)Buffer;
1519 PFAT32_BOOTSECTOR BootSector32 = (PFAT32_BOOTSECTOR)Buffer;
1520 PFATX_BOOTSECTOR BootSectorX = (PFATX_BOOTSECTOR)Buffer;
1521 FILEINFORMATION FileInformation;
1522 LARGE_INTEGER Position;
1523 ULONG Count;
1524 ULARGE_INTEGER SectorCount;
1525 ARC_STATUS Status;
1526
1527 //
1528 // Allocate data for volume information
1529 //
1530 Volume = FrLdrTempAlloc(sizeof(FAT_VOLUME_INFO), TAG_FAT_VOLUME);
1531 if (!Volume)
1532 return NULL;
1533 RtlZeroMemory(Volume, sizeof(FAT_VOLUME_INFO));
1534
1535 //
1536 // Read the BootSector
1537 //
1538 Position.HighPart = 0;
1539 Position.LowPart = 0;
1540 Status = ArcSeek(DeviceId, &Position, SeekAbsolute);
1541 if (Status != ESUCCESS)
1542 {
1543 FrLdrTempFree(Volume, TAG_FAT_VOLUME);
1544 return NULL;
1545 }
1546 Status = ArcRead(DeviceId, Buffer, sizeof(Buffer), &Count);
1547 if (Status != ESUCCESS || Count != sizeof(Buffer))
1548 {
1549 FrLdrTempFree(Volume, TAG_FAT_VOLUME);
1550 return NULL;
1551 }
1552
1553 //
1554 // Check if BootSector is valid. If no, return early
1555 //
1556 if (!RtlEqualMemory(BootSector->FileSystemType, "FAT12 ", 8) &&
1557 !RtlEqualMemory(BootSector->FileSystemType, "FAT16 ", 8) &&
1558 !RtlEqualMemory(BootSector32->FileSystemType, "FAT32 ", 8) &&
1559 !RtlEqualMemory(BootSectorX->FileSystemType, "FATX", 4))
1560 {
1561 FrLdrTempFree(Volume, TAG_FAT_VOLUME);
1562 return NULL;
1563 }
1564
1565 //
1566 // Determine sector count
1567 //
1568 Status = ArcGetFileInformation(DeviceId, &FileInformation);
1569 if (Status != ESUCCESS)
1570 {
1571 FrLdrTempFree(Volume, TAG_FAT_VOLUME);
1572 return NULL;
1573 }
1574 SectorCount.HighPart = FileInformation.EndingAddress.HighPart;
1575 SectorCount.LowPart = FileInformation.EndingAddress.LowPart;
1576 SectorCount.QuadPart /= SECTOR_SIZE;
1577
1578 //
1579 // Keep device id
1580 //
1581 Volume->DeviceId = DeviceId;
1582
1583 //
1584 // Really open the volume
1585 //
1586 if (!FatOpenVolume(Volume, BootSector, SectorCount.QuadPart))
1587 {
1588 FrLdrTempFree(Volume, TAG_FAT_VOLUME);
1589 return NULL;
1590 }
1591
1592 //
1593 // Remember FAT volume information
1594 //
1595 FatVolumes[DeviceId] = Volume;
1596
1597 //
1598 // Return success
1599 //
1600 return &FatFuncTable;
1601 }