[NTFS] - Add some helper functions for new features. Add some fixes. Add support...
[reactos.git] / drivers / filesystems / ntfs / mft.c
1 /*
2 * ReactOS kernel
3 * Copyright (C) 2002, 2014 ReactOS Team
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
18 *
19 * COPYRIGHT: See COPYING in the top level directory
20 * PROJECT: ReactOS kernel
21 * FILE: drivers/filesystem/ntfs/mft.c
22 * PURPOSE: NTFS filesystem driver
23 * PROGRAMMERS: Eric Kohl
24 * Valentin Verkhovsky
25 * Pierre Schweitzer (pierre@reactos.org)
26 * Hervé Poussineau (hpoussin@reactos.org)
27 * Trevor Thompson
28 */
29
30 /* INCLUDES *****************************************************************/
31
32 #include "ntfs.h"
33 #include <ntintsafe.h>
34
35 #define NDEBUG
36 #include <debug.h>
37
38 /* FUNCTIONS ****************************************************************/
39
40 PNTFS_ATTR_CONTEXT
41 PrepareAttributeContext(PNTFS_ATTR_RECORD AttrRecord)
42 {
43 PNTFS_ATTR_CONTEXT Context;
44
45 Context = ExAllocatePoolWithTag(NonPagedPool,
46 sizeof(NTFS_ATTR_CONTEXT),
47 TAG_NTFS);
48 if(!Context)
49 {
50 DPRINT1("Error: Unable to allocate memory for context!\n");
51 return NULL;
52 }
53
54 // Allocate memory for a copy of the attribute
55 Context->pRecord = ExAllocatePoolWithTag(NonPagedPool, AttrRecord->Length, TAG_NTFS);
56 if(!Context->pRecord)
57 {
58 DPRINT1("Error: Unable to allocate memory for attribute record!\n");
59 ExFreePoolWithTag(Context, TAG_NTFS);
60 return NULL;
61 }
62
63 // Copy the attribute
64 RtlCopyMemory(Context->pRecord, AttrRecord, AttrRecord->Length);
65
66 if (AttrRecord->IsNonResident)
67 {
68 LONGLONG DataRunOffset;
69 ULONGLONG DataRunLength;
70 ULONGLONG NextVBN = 0;
71 PUCHAR DataRun = (PUCHAR)((ULONG_PTR)Context->pRecord + Context->pRecord->NonResident.MappingPairsOffset);
72
73 Context->CacheRun = DataRun;
74 Context->CacheRunOffset = 0;
75 Context->CacheRun = DecodeRun(Context->CacheRun, &DataRunOffset, &DataRunLength);
76 Context->CacheRunLength = DataRunLength;
77 if (DataRunOffset != -1)
78 {
79 /* Normal run. */
80 Context->CacheRunStartLCN =
81 Context->CacheRunLastLCN = DataRunOffset;
82 }
83 else
84 {
85 /* Sparse run. */
86 Context->CacheRunStartLCN = -1;
87 Context->CacheRunLastLCN = 0;
88 }
89 Context->CacheRunCurrentOffset = 0;
90
91 // Convert the data runs to a map control block
92 if (!NT_SUCCESS(ConvertDataRunsToLargeMCB(DataRun, &Context->DataRunsMCB, &NextVBN)))
93 {
94 DPRINT1("Unable to convert data runs to MCB!\n");
95 ExFreePoolWithTag(Context->pRecord, TAG_NTFS);
96 ExFreePoolWithTag(Context, TAG_NTFS);
97 return NULL;
98 }
99 }
100
101 return Context;
102 }
103
104
105 VOID
106 ReleaseAttributeContext(PNTFS_ATTR_CONTEXT Context)
107 {
108 if (Context->pRecord->IsNonResident)
109 {
110 FsRtlUninitializeLargeMcb(&Context->DataRunsMCB);
111 }
112
113 if(Context->pRecord)
114 ExFreePoolWithTag(Context->pRecord, TAG_NTFS);
115
116 ExFreePoolWithTag(Context, TAG_NTFS);
117 }
118
119
120 /**
121 * @name FindAttribute
122 * @implemented
123 *
124 * Searches a file record for an attribute matching the given type and name.
125 *
126 * @param Offset
127 * Optional pointer to a ULONG that will receive the offset of the found attribute
128 * from the beginning of the record. Can be set to NULL.
129 */
130 NTSTATUS
131 FindAttribute(PDEVICE_EXTENSION Vcb,
132 PFILE_RECORD_HEADER MftRecord,
133 ULONG Type,
134 PCWSTR Name,
135 ULONG NameLength,
136 PNTFS_ATTR_CONTEXT * AttrCtx,
137 PULONG Offset)
138 {
139 BOOLEAN Found;
140 NTSTATUS Status;
141 FIND_ATTR_CONTXT Context;
142 PNTFS_ATTR_RECORD Attribute;
143
144 DPRINT("FindAttribute(%p, %p, 0x%x, %S, %lu, %p, %p)\n", Vcb, MftRecord, Type, Name, NameLength, AttrCtx, Offset);
145
146 Found = FALSE;
147 Status = FindFirstAttribute(&Context, Vcb, MftRecord, FALSE, &Attribute);
148 while (NT_SUCCESS(Status))
149 {
150 if (Attribute->Type == Type && Attribute->NameLength == NameLength)
151 {
152 if (NameLength != 0)
153 {
154 PWCHAR AttrName;
155
156 AttrName = (PWCHAR)((PCHAR)Attribute + Attribute->NameOffset);
157 DPRINT("%.*S, %.*S\n", Attribute->NameLength, AttrName, NameLength, Name);
158 if (RtlCompareMemory(AttrName, Name, NameLength * sizeof(WCHAR)) == (NameLength * sizeof(WCHAR)))
159 {
160 Found = TRUE;
161 }
162 }
163 else
164 {
165 Found = TRUE;
166 }
167
168 if (Found)
169 {
170 /* Found it, fill up the context and return. */
171 DPRINT("Found context\n");
172 *AttrCtx = PrepareAttributeContext(Attribute);
173
174 (*AttrCtx)->FileMFTIndex = MftRecord->MFTRecordNumber;
175
176 if (Offset != NULL)
177 *Offset = Context.Offset;
178
179 FindCloseAttribute(&Context);
180 return STATUS_SUCCESS;
181 }
182 }
183
184 Status = FindNextAttribute(&Context, &Attribute);
185 }
186
187 FindCloseAttribute(&Context);
188 return STATUS_OBJECT_NAME_NOT_FOUND;
189 }
190
191
192 ULONGLONG
193 AttributeAllocatedLength(PNTFS_ATTR_RECORD AttrRecord)
194 {
195 if (AttrRecord->IsNonResident)
196 return AttrRecord->NonResident.AllocatedSize;
197 else
198 return ALIGN_UP_BY(AttrRecord->Resident.ValueLength, ATTR_RECORD_ALIGNMENT);
199 }
200
201
202 ULONGLONG
203 AttributeDataLength(PNTFS_ATTR_RECORD AttrRecord)
204 {
205 if (AttrRecord->IsNonResident)
206 return AttrRecord->NonResident.DataSize;
207 else
208 return AttrRecord->Resident.ValueLength;
209 }
210
211 /**
212 * @name IncreaseMftSize
213 * @implemented
214 *
215 * Increases the size of the master file table on a volume, increasing the space available for file records.
216 *
217 * @param Vcb
218 * Pointer to the VCB (DEVICE_EXTENSION) of the target volume.
219 *
220 *
221 * @param CanWait
222 * Boolean indicating if the function is allowed to wait for exclusive access to the master file table.
223 * This will only be relevant if the MFT doesn't have any free file records and needs to be enlarged.
224 *
225 * @return
226 * STATUS_SUCCESS on success.
227 * STATUS_INSUFFICIENT_RESOURCES if an allocation fails.
228 * STATUS_INVALID_PARAMETER if there was an error reading the Mft's bitmap.
229 * STATUS_CANT_WAIT if CanWait was FALSE and the function could not get immediate, exclusive access to the MFT.
230 *
231 * @remarks
232 * Increases the size of the Master File Table by 64 records. Bitmap entries for the new records are cleared,
233 * and the bitmap is also enlarged if needed. Mimicking Windows' behavior when enlarging the mft is still TODO.
234 * This function will wait for exlusive access to the volume fcb.
235 */
236 NTSTATUS
237 IncreaseMftSize(PDEVICE_EXTENSION Vcb, BOOLEAN CanWait)
238 {
239 PNTFS_ATTR_CONTEXT BitmapContext;
240 LARGE_INTEGER BitmapSize;
241 LARGE_INTEGER DataSize;
242 LONGLONG BitmapSizeDifference;
243 ULONG NewRecords = ATTR_RECORD_ALIGNMENT * 8; // Allocate one new record for every bit of every byte we'll be adding to the bitmap
244 ULONG DataSizeDifference = Vcb->NtfsInfo.BytesPerFileRecord * NewRecords;
245 ULONG BitmapOffset;
246 PUCHAR BitmapBuffer;
247 ULONGLONG BitmapBytes;
248 ULONGLONG NewBitmapSize;
249 ULONGLONG FirstNewMftIndex;
250 ULONG BytesRead;
251 ULONG LengthWritten;
252 PFILE_RECORD_HEADER BlankFileRecord;
253 ULONG i;
254 NTSTATUS Status;
255
256 DPRINT1("IncreaseMftSize(%p, %s)\n", Vcb, CanWait ? "TRUE" : "FALSE");
257
258 // We need exclusive access to the mft while we change its size
259 if (!ExAcquireResourceExclusiveLite(&(Vcb->DirResource), CanWait))
260 {
261 return STATUS_CANT_WAIT;
262 }
263
264 // Create a blank file record that will be used later
265 BlankFileRecord = NtfsCreateEmptyFileRecord(Vcb);
266 if (!BlankFileRecord)
267 {
268 DPRINT1("Error: Unable to create empty file record!\n");
269 return STATUS_INSUFFICIENT_RESOURCES;
270 }
271
272 // Clear the flags (file record is not in use)
273 BlankFileRecord->Flags = 0;
274
275 // Find the bitmap attribute of master file table
276 Status = FindAttribute(Vcb, Vcb->MasterFileTable, AttributeBitmap, L"", 0, &BitmapContext, NULL);
277 if (!NT_SUCCESS(Status))
278 {
279 DPRINT1("ERROR: Couldn't find $BITMAP attribute of Mft!\n");
280 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
281 ExReleaseResourceLite(&(Vcb->DirResource));
282 return Status;
283 }
284
285 // Get size of Bitmap Attribute
286 BitmapSize.QuadPart = AttributeDataLength(BitmapContext->pRecord);
287
288 // Calculate the new mft size
289 DataSize.QuadPart = AttributeDataLength(Vcb->MFTContext->pRecord) + DataSizeDifference;
290
291 // Find the index of the first Mft entry that will be created
292 FirstNewMftIndex = AttributeDataLength(Vcb->MFTContext->pRecord) / Vcb->NtfsInfo.BytesPerFileRecord;
293
294 // Determine how many bytes will make up the bitmap
295 BitmapBytes = DataSize.QuadPart / Vcb->NtfsInfo.BytesPerFileRecord / 8;
296 if ((DataSize.QuadPart / Vcb->NtfsInfo.BytesPerFileRecord) % 8 != 0)
297 BitmapBytes++;
298
299 // Windows will always keep the number of bytes in a bitmap as a multiple of 8, so no bytes are wasted on slack
300 BitmapBytes = ALIGN_UP_BY(BitmapBytes, ATTR_RECORD_ALIGNMENT);
301
302 // Determine how much we need to adjust the bitmap size (it's possible we don't)
303 BitmapSizeDifference = BitmapBytes - BitmapSize.QuadPart;
304 NewBitmapSize = max(BitmapSize.QuadPart + BitmapSizeDifference, BitmapSize.QuadPart);
305
306 // Allocate memory for the bitmap
307 BitmapBuffer = ExAllocatePoolWithTag(NonPagedPool, NewBitmapSize, TAG_NTFS);
308 if (!BitmapBuffer)
309 {
310 DPRINT1("ERROR: Unable to allocate memory for bitmap attribute!\n");
311 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
312 ExReleaseResourceLite(&(Vcb->DirResource));
313 ReleaseAttributeContext(BitmapContext);
314 return STATUS_INSUFFICIENT_RESOURCES;
315 }
316
317 // Zero the bytes we'll be adding
318 RtlZeroMemory(BitmapBuffer, NewBitmapSize);
319
320 // Read the bitmap attribute
321 BytesRead = ReadAttribute(Vcb,
322 BitmapContext,
323 0,
324 (PCHAR)BitmapBuffer,
325 BitmapSize.LowPart);
326 if (BytesRead != BitmapSize.LowPart)
327 {
328 DPRINT1("ERROR: Bytes read != Bitmap size!\n");
329 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
330 ExReleaseResourceLite(&(Vcb->DirResource));
331 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
332 ReleaseAttributeContext(BitmapContext);
333 return STATUS_INVALID_PARAMETER;
334 }
335
336 // Increase the mft size
337 Status = SetNonResidentAttributeDataLength(Vcb, Vcb->MFTContext, Vcb->MftDataOffset, Vcb->MasterFileTable, &DataSize);
338 if (!NT_SUCCESS(Status))
339 {
340 DPRINT1("ERROR: Failed to set size of $MFT data attribute!\n");
341 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
342 ExReleaseResourceLite(&(Vcb->DirResource));
343 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
344 ReleaseAttributeContext(BitmapContext);
345 return Status;
346 }
347
348 // We'll need to find the bitmap again, because its offset will have changed after resizing the data attribute
349 ReleaseAttributeContext(BitmapContext);
350 Status = FindAttribute(Vcb, Vcb->MasterFileTable, AttributeBitmap, L"", 0, &BitmapContext, &BitmapOffset);
351 if (!NT_SUCCESS(Status))
352 {
353 DPRINT1("ERROR: Couldn't find $BITMAP attribute of Mft!\n");
354 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
355 ExReleaseResourceLite(&(Vcb->DirResource));
356 return Status;
357 }
358
359 // If the bitmap grew
360 if (BitmapSizeDifference > 0)
361 {
362 // Set the new bitmap size
363 BitmapSize.QuadPart = NewBitmapSize;
364 if (BitmapContext->pRecord->IsNonResident)
365 Status = SetNonResidentAttributeDataLength(Vcb, BitmapContext, BitmapOffset, Vcb->MasterFileTable, &BitmapSize);
366 else
367 Status = SetResidentAttributeDataLength(Vcb, BitmapContext, BitmapOffset, Vcb->MasterFileTable, &BitmapSize);
368
369 if (!NT_SUCCESS(Status))
370 {
371 DPRINT1("ERROR: Failed to set size of bitmap attribute!\n");
372 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
373 ExReleaseResourceLite(&(Vcb->DirResource));
374 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
375 ReleaseAttributeContext(BitmapContext);
376 return Status;
377 }
378 }
379
380 NtfsDumpFileAttributes(Vcb, Vcb->MasterFileTable);
381
382 // Update the file record with the new attribute sizes
383 Status = UpdateFileRecord(Vcb, Vcb->VolumeFcb->MFTIndex, Vcb->MasterFileTable);
384 if (!NT_SUCCESS(Status))
385 {
386 DPRINT1("ERROR: Failed to update $MFT file record!\n");
387 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
388 ExReleaseResourceLite(&(Vcb->DirResource));
389 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
390 ReleaseAttributeContext(BitmapContext);
391 return Status;
392 }
393
394 // Write out the new bitmap
395 Status = WriteAttribute(Vcb, BitmapContext, 0, BitmapBuffer, NewBitmapSize, &LengthWritten, Vcb->MasterFileTable);
396 if (!NT_SUCCESS(Status))
397 {
398 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
399 ExReleaseResourceLite(&(Vcb->DirResource));
400 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
401 ReleaseAttributeContext(BitmapContext);
402 DPRINT1("ERROR: Couldn't write to bitmap attribute of $MFT!\n");
403 return Status;
404 }
405
406 // Create blank records for the new file record entries.
407 for (i = 0; i < NewRecords; i++)
408 {
409 Status = UpdateFileRecord(Vcb, FirstNewMftIndex + i, BlankFileRecord);
410 if (!NT_SUCCESS(Status))
411 {
412 DPRINT1("ERROR: Failed to write blank file record!\n");
413 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
414 ExReleaseResourceLite(&(Vcb->DirResource));
415 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
416 ReleaseAttributeContext(BitmapContext);
417 return Status;
418 }
419 }
420
421 // Update the mft mirror
422 Status = UpdateMftMirror(Vcb);
423
424 // Cleanup
425 ExFreePoolWithTag(BlankFileRecord, TAG_NTFS);
426 ExReleaseResourceLite(&(Vcb->DirResource));
427 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
428 ReleaseAttributeContext(BitmapContext);
429
430 return Status;
431 }
432
433 /**
434 * @name MoveAttributes
435 * @implemented
436 *
437 * Moves a block of attributes to a new location in the file Record. The attribute at FirstAttributeToMove
438 * and every attribute after that will be moved to MoveTo.
439 *
440 * @param DeviceExt
441 * Pointer to the DEVICE_EXTENSION (VCB) of the target volume.
442 *
443 * @param FirstAttributeToMove
444 * Pointer to the first NTFS_ATTR_RECORD that needs to be moved. This pointer must reside within a file record.
445 *
446 * @param FirstAttributeOffset
447 * Offset of FirstAttributeToMove relative to the beginning of the file record.
448 *
449 * @param MoveTo
450 * ULONG_PTR with the memory location that will be the new location of the first attribute being moved.
451 *
452 * @return
453 * The new location of the final attribute (i.e. AttributeEnd marker).
454 */
455 PNTFS_ATTR_RECORD
456 MoveAttributes(PDEVICE_EXTENSION DeviceExt,
457 PNTFS_ATTR_RECORD FirstAttributeToMove,
458 ULONG FirstAttributeOffset,
459 ULONG_PTR MoveTo)
460 {
461 // Get the size of all attributes after this one
462 ULONG MemBlockSize = 0;
463 PNTFS_ATTR_RECORD CurrentAttribute = FirstAttributeToMove;
464 ULONG CurrentOffset = FirstAttributeOffset;
465 PNTFS_ATTR_RECORD FinalAttribute;
466
467 while (CurrentAttribute->Type != AttributeEnd && CurrentOffset < DeviceExt->NtfsInfo.BytesPerFileRecord)
468 {
469 CurrentOffset += CurrentAttribute->Length;
470 MemBlockSize += CurrentAttribute->Length;
471 CurrentAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)CurrentAttribute + CurrentAttribute->Length);
472 }
473
474 FinalAttribute = (PNTFS_ATTR_RECORD)(MoveTo + MemBlockSize);
475 MemBlockSize += sizeof(ULONG) * 2; // Add the AttributeEnd and file record end
476
477 ASSERT(MemBlockSize % ATTR_RECORD_ALIGNMENT == 0);
478
479 // Move the attributes after this one
480 RtlMoveMemory((PCHAR)MoveTo, FirstAttributeToMove, MemBlockSize);
481
482 return FinalAttribute;
483 }
484
485 NTSTATUS
486 InternalSetResidentAttributeLength(PDEVICE_EXTENSION DeviceExt,
487 PNTFS_ATTR_CONTEXT AttrContext,
488 PFILE_RECORD_HEADER FileRecord,
489 ULONG AttrOffset,
490 ULONG DataSize)
491 {
492 PNTFS_ATTR_RECORD Destination = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
493 PNTFS_ATTR_RECORD NextAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)Destination + Destination->Length);
494 PNTFS_ATTR_RECORD FinalAttribute;
495 ULONG OldAttributeLength = Destination->Length;
496 ULONG NextAttributeOffset;
497
498 DPRINT1("InternalSetResidentAttributeLength( %p, %p, %p, %lu, %lu )\n", DeviceExt, AttrContext, FileRecord, AttrOffset, DataSize);
499
500 ASSERT(!AttrContext->pRecord->IsNonResident);
501
502 // Update ValueLength Field
503 Destination->Resident.ValueLength = DataSize;
504
505 // Calculate the record length and end marker offset
506 Destination->Length = ALIGN_UP_BY(DataSize + AttrContext->pRecord->Resident.ValueOffset, ATTR_RECORD_ALIGNMENT);
507 NextAttributeOffset = AttrOffset + Destination->Length;
508
509 // Ensure NextAttributeOffset is aligned to an 8-byte boundary
510 ASSERT(NextAttributeOffset % ATTR_RECORD_ALIGNMENT == 0);
511
512 // Will the new attribute be larger than the old one?
513 if (Destination->Length > OldAttributeLength)
514 {
515 // Free the old copy of the attribute in the context, as it will be the wrong length
516 ExFreePoolWithTag(AttrContext->pRecord, TAG_NTFS);
517
518 // Create a new copy of the attribute record for the context
519 AttrContext->pRecord = ExAllocatePoolWithTag(NonPagedPool, Destination->Length, TAG_NTFS);
520 if (!AttrContext->pRecord)
521 {
522 DPRINT1("Unable to allocate memory for attribute!\n");
523 return STATUS_INSUFFICIENT_RESOURCES;
524 }
525 RtlZeroMemory((PVOID)((ULONG_PTR)AttrContext->pRecord + OldAttributeLength), Destination->Length - OldAttributeLength);
526 RtlCopyMemory(AttrContext->pRecord, Destination, OldAttributeLength);
527 }
528
529 // Are there attributes after this one that need to be moved?
530 if (NextAttribute->Type != AttributeEnd)
531 {
532 // Move the attributes after this one
533 FinalAttribute = MoveAttributes(DeviceExt, NextAttribute, NextAttributeOffset, (ULONG_PTR)Destination + Destination->Length);
534 }
535 else
536 {
537 // advance to the final "attribute," adjust for the changed length of the attribute we're resizing
538 FinalAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)NextAttribute - OldAttributeLength + Destination->Length);
539 }
540
541 // Update pRecord's length
542 AttrContext->pRecord->Length = Destination->Length;
543 AttrContext->pRecord->Resident.ValueLength = DataSize;
544
545 // set the file record end
546 SetFileRecordEnd(FileRecord, FinalAttribute, FILE_RECORD_END);
547
548 //NtfsDumpFileRecord(DeviceExt, FileRecord);
549
550 return STATUS_SUCCESS;
551 }
552
553 /**
554 * @parameter FileRecord
555 * Pointer to a file record. Must be a full record at least
556 * Fcb->Vcb->NtfsInfo.BytesPerFileRecord bytes large, not just the header.
557 */
558 NTSTATUS
559 SetAttributeDataLength(PFILE_OBJECT FileObject,
560 PNTFS_FCB Fcb,
561 PNTFS_ATTR_CONTEXT AttrContext,
562 ULONG AttrOffset,
563 PFILE_RECORD_HEADER FileRecord,
564 PLARGE_INTEGER DataSize)
565 {
566 NTSTATUS Status = STATUS_SUCCESS;
567
568 DPRINT1("SetAttributeDataLength(%p, %p, %p, %lu, %p, %I64u)\n",
569 FileObject,
570 Fcb,
571 AttrContext,
572 AttrOffset,
573 FileRecord,
574 DataSize->QuadPart);
575
576 // are we truncating the file?
577 if (DataSize->QuadPart < AttributeDataLength(AttrContext->pRecord))
578 {
579 if (!MmCanFileBeTruncated(FileObject->SectionObjectPointer, DataSize))
580 {
581 DPRINT1("Can't truncate a memory-mapped file!\n");
582 return STATUS_USER_MAPPED_FILE;
583 }
584 }
585
586 if (AttrContext->pRecord->IsNonResident)
587 {
588 Status = SetNonResidentAttributeDataLength(Fcb->Vcb,
589 AttrContext,
590 AttrOffset,
591 FileRecord,
592 DataSize);
593 }
594 else
595 {
596 // resident attribute
597 Status = SetResidentAttributeDataLength(Fcb->Vcb,
598 AttrContext,
599 AttrOffset,
600 FileRecord,
601 DataSize);
602 }
603
604 if (!NT_SUCCESS(Status))
605 {
606 DPRINT1("ERROR: Failed to set size of attribute!\n");
607 return Status;
608 }
609
610 //NtfsDumpFileAttributes(Fcb->Vcb, FileRecord);
611
612 // write the updated file record back to disk
613 Status = UpdateFileRecord(Fcb->Vcb, Fcb->MFTIndex, FileRecord);
614
615 if (NT_SUCCESS(Status))
616 {
617 if (AttrContext->pRecord->IsNonResident)
618 Fcb->RFCB.AllocationSize.QuadPart = AttrContext->pRecord->NonResident.AllocatedSize;
619 else
620 Fcb->RFCB.AllocationSize = *DataSize;
621 Fcb->RFCB.FileSize = *DataSize;
622 Fcb->RFCB.ValidDataLength = *DataSize;
623 CcSetFileSizes(FileObject, (PCC_FILE_SIZES)&Fcb->RFCB.AllocationSize);
624 }
625
626 return STATUS_SUCCESS;
627 }
628
629 /**
630 * @name SetFileRecordEnd
631 * @implemented
632 *
633 * This small function sets a new endpoint for the file record. It set's the final
634 * AttrEnd->Type to AttributeEnd and recalculates the bytes used by the file record.
635 *
636 * @param FileRecord
637 * Pointer to the file record whose endpoint (length) will be set.
638 *
639 * @param AttrEnd
640 * Pointer to section of memory that will receive the AttributeEnd marker. This must point
641 * to memory allocated for the FileRecord. Must be aligned to an 8-byte boundary (relative to FileRecord).
642 *
643 * @param EndMarker
644 * This value will be written after AttributeEnd but isn't critical at all. When Windows resizes
645 * a file record, it preserves the final ULONG that previously ended the record, even though this
646 * value is (to my knowledge) never used. We emulate this behavior.
647 *
648 */
649 VOID
650 SetFileRecordEnd(PFILE_RECORD_HEADER FileRecord,
651 PNTFS_ATTR_RECORD AttrEnd,
652 ULONG EndMarker)
653 {
654 // Ensure AttrEnd is aligned on an 8-byte boundary, relative to FileRecord
655 ASSERT(((ULONG_PTR)AttrEnd - (ULONG_PTR)FileRecord) % ATTR_RECORD_ALIGNMENT == 0);
656
657 // mark the end of attributes
658 AttrEnd->Type = AttributeEnd;
659
660 // Restore the "file-record-end marker." The value is never checked but this behavior is consistent with Win2k3.
661 AttrEnd->Length = EndMarker;
662
663 // recalculate bytes in use
664 FileRecord->BytesInUse = (ULONG_PTR)AttrEnd - (ULONG_PTR)FileRecord + sizeof(ULONG) * 2;
665 }
666
667 /**
668 * @name SetNonResidentAttributeDataLength
669 * @implemented
670 *
671 * Called by SetAttributeDataLength() to set the size of a non-resident attribute. Doesn't update the file record.
672 *
673 * @param Vcb
674 * Pointer to a DEVICE_EXTENSION describing the target disk.
675 *
676 * @param AttrContext
677 * PNTFS_ATTR_CONTEXT describing the location of the attribute whose size is being set.
678 *
679 * @param AttrOffset
680 * Offset, from the beginning of the record, of the attribute being sized.
681 *
682 * @param FileRecord
683 * Pointer to a file record containing the attribute to be resized. Must be a complete file record,
684 * not just the header.
685 *
686 * @param DataSize
687 * Pointer to a LARGE_INTEGER describing the new size of the attribute's data.
688 *
689 * @return
690 * STATUS_SUCCESS on success;
691 * STATUS_INSUFFICIENT_RESOURCES if an allocation fails.
692 * STATUS_INVALID_PARAMETER if we can't find the last cluster in the data run.
693 *
694 * @remarks
695 * Called by SetAttributeDataLength() and IncreaseMftSize(). Use SetAttributeDataLength() unless you have a good
696 * reason to use this. Doesn't update the file record on disk. Doesn't inform the cache controller of changes with
697 * any associated files. Synchronization is the callers responsibility.
698 */
699 NTSTATUS
700 SetNonResidentAttributeDataLength(PDEVICE_EXTENSION Vcb,
701 PNTFS_ATTR_CONTEXT AttrContext,
702 ULONG AttrOffset,
703 PFILE_RECORD_HEADER FileRecord,
704 PLARGE_INTEGER DataSize)
705 {
706 NTSTATUS Status = STATUS_SUCCESS;
707 ULONG BytesPerCluster = Vcb->NtfsInfo.BytesPerCluster;
708 ULONGLONG AllocationSize = ROUND_UP(DataSize->QuadPart, BytesPerCluster);
709 PNTFS_ATTR_RECORD DestinationAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
710 ULONG ExistingClusters = AttrContext->pRecord->NonResident.AllocatedSize / BytesPerCluster;
711
712 ASSERT(AttrContext->pRecord->IsNonResident);
713
714 // do we need to increase the allocation size?
715 if (AttrContext->pRecord->NonResident.AllocatedSize < AllocationSize)
716 {
717 ULONG ClustersNeeded = (AllocationSize / BytesPerCluster) - ExistingClusters;
718 LARGE_INTEGER LastClusterInDataRun;
719 ULONG NextAssignedCluster;
720 ULONG AssignedClusters;
721
722 if (ExistingClusters == 0)
723 {
724 LastClusterInDataRun.QuadPart = 0;
725 }
726 else
727 {
728 if (!FsRtlLookupLargeMcbEntry(&AttrContext->DataRunsMCB,
729 (LONGLONG)AttrContext->pRecord->NonResident.HighestVCN,
730 (PLONGLONG)&LastClusterInDataRun.QuadPart,
731 NULL,
732 NULL,
733 NULL,
734 NULL))
735 {
736 DPRINT1("Error looking up final large MCB entry!\n");
737
738 // Most likely, HighestVCN went above the largest mapping
739 DPRINT1("Highest VCN of record: %I64u\n", AttrContext->pRecord->NonResident.HighestVCN);
740 return STATUS_INVALID_PARAMETER;
741 }
742 }
743
744 DPRINT("LastClusterInDataRun: %I64u\n", LastClusterInDataRun.QuadPart);
745 DPRINT("Highest VCN of record: %I64u\n", AttrContext->pRecord->NonResident.HighestVCN);
746
747 while (ClustersNeeded > 0)
748 {
749 Status = NtfsAllocateClusters(Vcb,
750 LastClusterInDataRun.LowPart + 1,
751 ClustersNeeded,
752 &NextAssignedCluster,
753 &AssignedClusters);
754
755 if (!NT_SUCCESS(Status))
756 {
757 DPRINT1("Error: Unable to allocate requested clusters!\n");
758 return Status;
759 }
760
761 // now we need to add the clusters we allocated to the data run
762 Status = AddRun(Vcb, AttrContext, AttrOffset, FileRecord, NextAssignedCluster, AssignedClusters);
763 if (!NT_SUCCESS(Status))
764 {
765 DPRINT1("Error: Unable to add data run!\n");
766 return Status;
767 }
768
769 ClustersNeeded -= AssignedClusters;
770 LastClusterInDataRun.LowPart = NextAssignedCluster + AssignedClusters - 1;
771 }
772 }
773 else if (AttrContext->pRecord->NonResident.AllocatedSize > AllocationSize)
774 {
775 // shrink allocation size
776 ULONG ClustersToFree = ExistingClusters - (AllocationSize / BytesPerCluster);
777 Status = FreeClusters(Vcb, AttrContext, AttrOffset, FileRecord, ClustersToFree);
778 }
779
780 // TODO: is the file compressed, encrypted, or sparse?
781
782 AttrContext->pRecord->NonResident.AllocatedSize = AllocationSize;
783 AttrContext->pRecord->NonResident.DataSize = DataSize->QuadPart;
784 AttrContext->pRecord->NonResident.InitializedSize = DataSize->QuadPart;
785
786 DestinationAttribute->NonResident.AllocatedSize = AllocationSize;
787 DestinationAttribute->NonResident.DataSize = DataSize->QuadPart;
788 DestinationAttribute->NonResident.InitializedSize = DataSize->QuadPart;
789
790 // HighestVCN seems to be set incorrectly somewhere. Apply a hack-fix to reset it.
791 // HACKHACK FIXME: Fix for sparse files; this math won't work in that case.
792 AttrContext->pRecord->NonResident.HighestVCN = ((ULONGLONG)AllocationSize / Vcb->NtfsInfo.BytesPerCluster) - 1;
793 DestinationAttribute->NonResident.HighestVCN = AttrContext->pRecord->NonResident.HighestVCN;
794
795 DPRINT("Allocated Size: %I64u\n", DestinationAttribute->NonResident.AllocatedSize);
796
797 return Status;
798 }
799
800 /**
801 * @name SetResidentAttributeDataLength
802 * @implemented
803 *
804 * Called by SetAttributeDataLength() to set the size of a non-resident attribute. Doesn't update the file record.
805 *
806 * @param Vcb
807 * Pointer to a DEVICE_EXTENSION describing the target disk.
808 *
809 * @param AttrContext
810 * PNTFS_ATTR_CONTEXT describing the location of the attribute whose size is being set.
811 *
812 * @param AttrOffset
813 * Offset, from the beginning of the record, of the attribute being sized.
814 *
815 * @param FileRecord
816 * Pointer to a file record containing the attribute to be resized. Must be a complete file record,
817 * not just the header.
818 *
819 * @param DataSize
820 * Pointer to a LARGE_INTEGER describing the new size of the attribute's data.
821 *
822 * @return
823 * STATUS_SUCCESS on success;
824 * STATUS_INSUFFICIENT_RESOURCES if an allocation fails.
825 * STATUS_INVALID_PARAMETER if AttrContext describes a non-resident attribute.
826 * STATUS_NOT_IMPLEMENTED if requested to decrease the size of an attribute that isn't the
827 * last attribute listed in the file record.
828 *
829 * @remarks
830 * Called by SetAttributeDataLength() and IncreaseMftSize(). Use SetAttributeDataLength() unless you have a good
831 * reason to use this. Doesn't update the file record on disk. Doesn't inform the cache controller of changes with
832 * any associated files. Synchronization is the callers responsibility.
833 */
834 NTSTATUS
835 SetResidentAttributeDataLength(PDEVICE_EXTENSION Vcb,
836 PNTFS_ATTR_CONTEXT AttrContext,
837 ULONG AttrOffset,
838 PFILE_RECORD_HEADER FileRecord,
839 PLARGE_INTEGER DataSize)
840 {
841 NTSTATUS Status;
842
843 // find the next attribute
844 ULONG NextAttributeOffset = AttrOffset + AttrContext->pRecord->Length;
845 PNTFS_ATTR_RECORD NextAttribute = (PNTFS_ATTR_RECORD)((PCHAR)FileRecord + NextAttributeOffset);
846
847 ASSERT(!AttrContext->pRecord->IsNonResident);
848
849 //NtfsDumpFileAttributes(Vcb, FileRecord);
850
851 // Do we need to increase the data length?
852 if (DataSize->QuadPart > AttrContext->pRecord->Resident.ValueLength)
853 {
854 // There's usually padding at the end of a record. Do we need to extend past it?
855 ULONG MaxValueLength = AttrContext->pRecord->Length - AttrContext->pRecord->Resident.ValueOffset;
856 if (MaxValueLength < DataSize->LowPart)
857 {
858 // If this is the last attribute, we could move the end marker to the very end of the file record
859 MaxValueLength += Vcb->NtfsInfo.BytesPerFileRecord - NextAttributeOffset - (sizeof(ULONG) * 2);
860
861 if (MaxValueLength < DataSize->LowPart || NextAttribute->Type != AttributeEnd)
862 {
863 // convert attribute to non-resident
864 PNTFS_ATTR_RECORD Destination = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
865 PNTFS_ATTR_RECORD NewRecord;
866 LARGE_INTEGER AttribDataSize;
867 PVOID AttribData;
868 ULONG NewRecordLength;
869 ULONG EndAttributeOffset;
870 ULONG LengthWritten;
871
872 DPRINT1("Converting attribute to non-resident.\n");
873
874 AttribDataSize.QuadPart = AttrContext->pRecord->Resident.ValueLength;
875
876 // Is there existing data we need to back-up?
877 if (AttribDataSize.QuadPart > 0)
878 {
879 AttribData = ExAllocatePoolWithTag(NonPagedPool, AttribDataSize.QuadPart, TAG_NTFS);
880 if (AttribData == NULL)
881 {
882 DPRINT1("ERROR: Couldn't allocate memory for attribute data. Can't migrate to non-resident!\n");
883 return STATUS_INSUFFICIENT_RESOURCES;
884 }
885
886 // read data to temp buffer
887 Status = ReadAttribute(Vcb, AttrContext, 0, AttribData, AttribDataSize.QuadPart);
888 if (!NT_SUCCESS(Status))
889 {
890 DPRINT1("ERROR: Unable to read attribute before migrating!\n");
891 ExFreePoolWithTag(AttribData, TAG_NTFS);
892 return Status;
893 }
894 }
895
896 // Start by turning this attribute into a 0-length, non-resident attribute, then enlarge it.
897
898 // The size of a 0-length, non-resident attribute will be 0x41 + the size of the attribute name, aligned to an 8-byte boundary
899 NewRecordLength = ALIGN_UP_BY(0x41 + (AttrContext->pRecord->NameLength * sizeof(WCHAR)), ATTR_RECORD_ALIGNMENT);
900
901 // Create a new attribute record that will store the 0-length, non-resident attribute
902 NewRecord = ExAllocatePoolWithTag(NonPagedPool, NewRecordLength, TAG_NTFS);
903
904 // Zero out the NonResident structure
905 RtlZeroMemory(NewRecord, NewRecordLength);
906
907 // Copy the data that's common to both non-resident and resident attributes
908 RtlCopyMemory(NewRecord, AttrContext->pRecord, FIELD_OFFSET(NTFS_ATTR_RECORD, Resident.ValueLength));
909
910 // if there's a name
911 if (AttrContext->pRecord->NameLength != 0)
912 {
913 // copy the name
914 // An attribute name will be located at offset 0x18 for a resident attribute, 0x40 for non-resident
915 RtlCopyMemory((PCHAR)((ULONG_PTR)NewRecord + 0x40),
916 (PCHAR)((ULONG_PTR)AttrContext->pRecord + 0x18),
917 AttrContext->pRecord->NameLength * sizeof(WCHAR));
918 }
919
920 // update the mapping pairs offset, which will be 0x40 (size of a non-resident header) + length in bytes of the name
921 NewRecord->NonResident.MappingPairsOffset = 0x40 + (AttrContext->pRecord->NameLength * sizeof(WCHAR));
922
923 // update the end of the file record
924 // calculate position of end markers (1 byte for empty data run)
925 EndAttributeOffset = AttrOffset + NewRecord->NonResident.MappingPairsOffset + 1;
926 EndAttributeOffset = ALIGN_UP_BY(EndAttributeOffset, ATTR_RECORD_ALIGNMENT);
927
928 // Update the length
929 NewRecord->Length = EndAttributeOffset - AttrOffset;
930
931 ASSERT(NewRecord->Length == NewRecordLength);
932
933 // Copy the new attribute record into the file record
934 RtlCopyMemory(Destination, NewRecord, NewRecord->Length);
935
936 // Update the file record end
937 SetFileRecordEnd(FileRecord,
938 (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + EndAttributeOffset),
939 FILE_RECORD_END);
940
941 // Initialize the MCB, potentially catch an exception
942 _SEH2_TRY
943 {
944 FsRtlInitializeLargeMcb(&AttrContext->DataRunsMCB, NonPagedPool);
945 }
946 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
947 {
948 DPRINT1("Unable to create LargeMcb!\n");
949 if (AttribDataSize.QuadPart > 0)
950 ExFreePoolWithTag(AttribData, TAG_NTFS);
951 _SEH2_YIELD(return _SEH2_GetExceptionCode());
952 } _SEH2_END;
953
954 // Mark the attribute as non-resident (we wait until after we know the LargeMcb was initialized)
955 NewRecord->IsNonResident = Destination->IsNonResident = 1;
956
957 // Update file record on disk
958 Status = UpdateFileRecord(Vcb, AttrContext->FileMFTIndex, FileRecord);
959 if (!NT_SUCCESS(Status))
960 {
961 DPRINT1("ERROR: Couldn't update file record to continue migration!\n");
962 if (AttribDataSize.QuadPart > 0)
963 ExFreePoolWithTag(AttribData, TAG_NTFS);
964 return Status;
965 }
966
967 // Now we need to free the old copy of the attribute record in the context and replace it with the new one
968 ExFreePoolWithTag(AttrContext->pRecord, TAG_NTFS);
969 AttrContext->pRecord = NewRecord;
970
971 // Now we can treat the attribute as non-resident and enlarge it normally
972 Status = SetNonResidentAttributeDataLength(Vcb, AttrContext, AttrOffset, FileRecord, DataSize);
973 if (!NT_SUCCESS(Status))
974 {
975 DPRINT1("ERROR: Unable to migrate resident attribute!\n");
976 if (AttribDataSize.QuadPart > 0)
977 ExFreePoolWithTag(AttribData, TAG_NTFS);
978 return Status;
979 }
980
981 // restore the back-up attribute, if we made one
982 if (AttribDataSize.QuadPart > 0)
983 {
984 Status = WriteAttribute(Vcb, AttrContext, 0, AttribData, AttribDataSize.QuadPart, &LengthWritten, FileRecord);
985 if (!NT_SUCCESS(Status))
986 {
987 DPRINT1("ERROR: Unable to write attribute data to non-resident clusters during migration!\n");
988 // TODO: Reverse migration so no data is lost
989 ExFreePoolWithTag(AttribData, TAG_NTFS);
990 return Status;
991 }
992
993 ExFreePoolWithTag(AttribData, TAG_NTFS);
994 }
995 }
996 }
997 }
998
999 // set the new length of the resident attribute (if we didn't migrate it)
1000 if (!AttrContext->pRecord->IsNonResident)
1001 return InternalSetResidentAttributeLength(Vcb, AttrContext, FileRecord, AttrOffset, DataSize->LowPart);
1002
1003 return STATUS_SUCCESS;
1004 }
1005
1006 ULONG
1007 ReadAttribute(PDEVICE_EXTENSION Vcb,
1008 PNTFS_ATTR_CONTEXT Context,
1009 ULONGLONG Offset,
1010 PCHAR Buffer,
1011 ULONG Length)
1012 {
1013 ULONGLONG LastLCN;
1014 PUCHAR DataRun;
1015 LONGLONG DataRunOffset;
1016 ULONGLONG DataRunLength;
1017 LONGLONG DataRunStartLCN;
1018 ULONGLONG CurrentOffset;
1019 ULONG ReadLength;
1020 ULONG AlreadyRead;
1021 NTSTATUS Status;
1022
1023 //TEMPTEMP
1024 PUCHAR TempBuffer;
1025
1026 if (!Context->pRecord->IsNonResident)
1027 {
1028 // We need to truncate Offset to a ULONG for pointer arithmetic
1029 // The check below should ensure that Offset is well within the range of 32 bits
1030 ULONG LittleOffset = (ULONG)Offset;
1031
1032 // Ensure that offset isn't beyond the end of the attribute
1033 if (Offset > Context->pRecord->Resident.ValueLength)
1034 return 0;
1035 if (Offset + Length > Context->pRecord->Resident.ValueLength)
1036 Length = (ULONG)(Context->pRecord->Resident.ValueLength - Offset);
1037
1038 RtlCopyMemory(Buffer, (PVOID)((ULONG_PTR)Context->pRecord + Context->pRecord->Resident.ValueOffset + LittleOffset), Length);
1039 return Length;
1040 }
1041
1042 /*
1043 * Non-resident attribute
1044 */
1045
1046 /*
1047 * I. Find the corresponding start data run.
1048 */
1049
1050 AlreadyRead = 0;
1051
1052 // FIXME: Cache seems to be non-working. Disable it for now
1053 //if(Context->CacheRunOffset <= Offset && Offset < Context->CacheRunOffset + Context->CacheRunLength * Volume->ClusterSize)
1054 if (0)
1055 {
1056 DataRun = Context->CacheRun;
1057 LastLCN = Context->CacheRunLastLCN;
1058 DataRunStartLCN = Context->CacheRunStartLCN;
1059 DataRunLength = Context->CacheRunLength;
1060 CurrentOffset = Context->CacheRunCurrentOffset;
1061 }
1062 else
1063 {
1064 //TEMPTEMP
1065 ULONG UsedBufferSize;
1066 TempBuffer = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
1067
1068 LastLCN = 0;
1069 CurrentOffset = 0;
1070
1071 // This will be rewritten in the next iteration to just use the DataRuns MCB directly
1072 ConvertLargeMCBToDataRuns(&Context->DataRunsMCB,
1073 TempBuffer,
1074 Vcb->NtfsInfo.BytesPerFileRecord,
1075 &UsedBufferSize);
1076
1077 DataRun = TempBuffer;
1078
1079 while (1)
1080 {
1081 DataRun = DecodeRun(DataRun, &DataRunOffset, &DataRunLength);
1082 if (DataRunOffset != -1)
1083 {
1084 /* Normal data run. */
1085 DataRunStartLCN = LastLCN + DataRunOffset;
1086 LastLCN = DataRunStartLCN;
1087 }
1088 else
1089 {
1090 /* Sparse data run. */
1091 DataRunStartLCN = -1;
1092 }
1093
1094 if (Offset >= CurrentOffset &&
1095 Offset < CurrentOffset + (DataRunLength * Vcb->NtfsInfo.BytesPerCluster))
1096 {
1097 break;
1098 }
1099
1100 if (*DataRun == 0)
1101 {
1102 return AlreadyRead;
1103 }
1104
1105 CurrentOffset += DataRunLength * Vcb->NtfsInfo.BytesPerCluster;
1106 }
1107 }
1108
1109 /*
1110 * II. Go through the run list and read the data
1111 */
1112
1113 ReadLength = (ULONG)min(DataRunLength * Vcb->NtfsInfo.BytesPerCluster - (Offset - CurrentOffset), Length);
1114 if (DataRunStartLCN == -1)
1115 {
1116 RtlZeroMemory(Buffer, ReadLength);
1117 Status = STATUS_SUCCESS;
1118 }
1119 else
1120 {
1121 Status = NtfsReadDisk(Vcb->StorageDevice,
1122 DataRunStartLCN * Vcb->NtfsInfo.BytesPerCluster + Offset - CurrentOffset,
1123 ReadLength,
1124 Vcb->NtfsInfo.BytesPerSector,
1125 (PVOID)Buffer,
1126 FALSE);
1127 }
1128 if (NT_SUCCESS(Status))
1129 {
1130 Length -= ReadLength;
1131 Buffer += ReadLength;
1132 AlreadyRead += ReadLength;
1133
1134 if (ReadLength == DataRunLength * Vcb->NtfsInfo.BytesPerCluster - (Offset - CurrentOffset))
1135 {
1136 CurrentOffset += DataRunLength * Vcb->NtfsInfo.BytesPerCluster;
1137 DataRun = DecodeRun(DataRun, &DataRunOffset, &DataRunLength);
1138 if (DataRunOffset != (ULONGLONG)-1)
1139 {
1140 DataRunStartLCN = LastLCN + DataRunOffset;
1141 LastLCN = DataRunStartLCN;
1142 }
1143 else
1144 DataRunStartLCN = -1;
1145 }
1146
1147 while (Length > 0)
1148 {
1149 ReadLength = (ULONG)min(DataRunLength * Vcb->NtfsInfo.BytesPerCluster, Length);
1150 if (DataRunStartLCN == -1)
1151 RtlZeroMemory(Buffer, ReadLength);
1152 else
1153 {
1154 Status = NtfsReadDisk(Vcb->StorageDevice,
1155 DataRunStartLCN * Vcb->NtfsInfo.BytesPerCluster,
1156 ReadLength,
1157 Vcb->NtfsInfo.BytesPerSector,
1158 (PVOID)Buffer,
1159 FALSE);
1160 if (!NT_SUCCESS(Status))
1161 break;
1162 }
1163
1164 Length -= ReadLength;
1165 Buffer += ReadLength;
1166 AlreadyRead += ReadLength;
1167
1168 /* We finished this request, but there still data in this data run. */
1169 if (Length == 0 && ReadLength != DataRunLength * Vcb->NtfsInfo.BytesPerCluster)
1170 break;
1171
1172 /*
1173 * Go to next run in the list.
1174 */
1175
1176 if (*DataRun == 0)
1177 break;
1178 CurrentOffset += DataRunLength * Vcb->NtfsInfo.BytesPerCluster;
1179 DataRun = DecodeRun(DataRun, &DataRunOffset, &DataRunLength);
1180 if (DataRunOffset != -1)
1181 {
1182 /* Normal data run. */
1183 DataRunStartLCN = LastLCN + DataRunOffset;
1184 LastLCN = DataRunStartLCN;
1185 }
1186 else
1187 {
1188 /* Sparse data run. */
1189 DataRunStartLCN = -1;
1190 }
1191 } /* while */
1192
1193 } /* if Disk */
1194
1195 // TEMPTEMP
1196 if (Context->pRecord->IsNonResident)
1197 ExFreePoolWithTag(TempBuffer, TAG_NTFS);
1198
1199 Context->CacheRun = DataRun;
1200 Context->CacheRunOffset = Offset + AlreadyRead;
1201 Context->CacheRunStartLCN = DataRunStartLCN;
1202 Context->CacheRunLength = DataRunLength;
1203 Context->CacheRunLastLCN = LastLCN;
1204 Context->CacheRunCurrentOffset = CurrentOffset;
1205
1206 return AlreadyRead;
1207 }
1208
1209
1210 /**
1211 * @name WriteAttribute
1212 * @implemented
1213 *
1214 * Writes an NTFS attribute to the disk. It presently borrows a lot of code from ReadAttribute(),
1215 * and it still needs more documentation / cleaning up.
1216 *
1217 * @param Vcb
1218 * Volume Control Block indicating which volume to write the attribute to
1219 *
1220 * @param Context
1221 * Pointer to an NTFS_ATTR_CONTEXT that has information about the attribute
1222 *
1223 * @param Offset
1224 * Offset, in bytes, from the beginning of the attribute indicating where to start
1225 * writing data
1226 *
1227 * @param Buffer
1228 * The data that's being written to the device
1229 *
1230 * @param Length
1231 * How much data will be written, in bytes
1232 *
1233 * @param RealLengthWritten
1234 * Pointer to a ULONG which will receive how much data was written, in bytes
1235 *
1236 * @param FileRecord
1237 * Optional pointer to a FILE_RECORD_HEADER that contains a copy of the file record
1238 * being written to. Can be NULL, in which case the file record will be read from disk.
1239 * If not-null, WriteAttribute() will skip reading from disk, and FileRecord
1240 * will be updated with the newly-written attribute before the function returns.
1241 *
1242 * @return
1243 * STATUS_SUCCESS if successful, an error code otherwise. STATUS_NOT_IMPLEMENTED if
1244 * writing to a sparse file.
1245 *
1246 * @remarks Note that in this context the word "attribute" isn't referring read-only, hidden,
1247 * etc. - the file's data is actually stored in an attribute in NTFS parlance.
1248 *
1249 */
1250
1251 NTSTATUS
1252 WriteAttribute(PDEVICE_EXTENSION Vcb,
1253 PNTFS_ATTR_CONTEXT Context,
1254 ULONGLONG Offset,
1255 const PUCHAR Buffer,
1256 ULONG Length,
1257 PULONG RealLengthWritten,
1258 PFILE_RECORD_HEADER FileRecord)
1259 {
1260 ULONGLONG LastLCN;
1261 PUCHAR DataRun;
1262 LONGLONG DataRunOffset;
1263 ULONGLONG DataRunLength;
1264 LONGLONG DataRunStartLCN;
1265 ULONGLONG CurrentOffset;
1266 ULONG WriteLength;
1267 NTSTATUS Status;
1268 PUCHAR SourceBuffer = Buffer;
1269 LONGLONG StartingOffset;
1270 BOOLEAN FileRecordAllocated = FALSE;
1271
1272 //TEMPTEMP
1273 PUCHAR TempBuffer;
1274
1275
1276 DPRINT("WriteAttribute(%p, %p, %I64u, %p, %lu, %p, %p)\n", Vcb, Context, Offset, Buffer, Length, RealLengthWritten, FileRecord);
1277
1278 *RealLengthWritten = 0;
1279
1280 // is this a resident attribute?
1281 if (!Context->pRecord->IsNonResident)
1282 {
1283 ULONG AttributeOffset;
1284 PNTFS_ATTR_CONTEXT FoundContext;
1285 PNTFS_ATTR_RECORD Destination;
1286
1287 // Ensure requested data is within the bounds of the attribute
1288 ASSERT(Offset + Length <= Context->pRecord->Resident.ValueLength);
1289
1290 if (Offset + Length > Context->pRecord->Resident.ValueLength)
1291 {
1292 DPRINT1("DRIVER ERROR: Attribute is too small!\n");
1293 return STATUS_INVALID_PARAMETER;
1294 }
1295
1296 // Do we need to read the file record?
1297 if (FileRecord == NULL)
1298 {
1299 FileRecord = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
1300 if (!FileRecord)
1301 {
1302 DPRINT1("Error: Couldn't allocate file record!\n");
1303 return STATUS_NO_MEMORY;
1304 }
1305
1306 FileRecordAllocated = TRUE;
1307
1308 // read the file record
1309 ReadFileRecord(Vcb, Context->FileMFTIndex, FileRecord);
1310 }
1311
1312 // find where to write the attribute data to
1313 Status = FindAttribute(Vcb, FileRecord,
1314 Context->pRecord->Type,
1315 (PCWSTR)((ULONG_PTR)Context->pRecord + Context->pRecord->NameOffset),
1316 Context->pRecord->NameLength,
1317 &FoundContext,
1318 &AttributeOffset);
1319
1320 if (!NT_SUCCESS(Status))
1321 {
1322 DPRINT1("ERROR: Couldn't find matching attribute!\n");
1323 if(FileRecordAllocated)
1324 ExFreePoolWithTag(FileRecord, TAG_NTFS);
1325 return Status;
1326 }
1327
1328 Destination = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttributeOffset);
1329
1330 DPRINT("Offset: %I64u, AttributeOffset: %u, ValueOffset: %u\n", Offset, AttributeOffset, Context->pRecord->Resident.ValueLength);
1331
1332 // Will we be writing past the end of the allocated file record?
1333 if (Offset + Length + AttributeOffset + Context->pRecord->Resident.ValueOffset > Vcb->NtfsInfo.BytesPerFileRecord)
1334 {
1335 DPRINT1("DRIVER ERROR: Data being written extends past end of file record!\n");
1336 ReleaseAttributeContext(FoundContext);
1337 if (FileRecordAllocated)
1338 ExFreePoolWithTag(FileRecord, TAG_NTFS);
1339 return STATUS_INVALID_PARAMETER;
1340 }
1341
1342 // copy the data being written into the file record. We cast Offset to ULONG, which is safe because it's range has been verified.
1343 RtlCopyMemory((PCHAR)((ULONG_PTR)Destination + Context->pRecord->Resident.ValueOffset + (ULONG)Offset), Buffer, Length);
1344
1345 Status = UpdateFileRecord(Vcb, Context->FileMFTIndex, FileRecord);
1346
1347 // Update the context's copy of the resident attribute
1348 ASSERT(Context->pRecord->Length == Destination->Length);
1349 RtlCopyMemory((PVOID)Context->pRecord, Destination, Context->pRecord->Length);
1350
1351 ReleaseAttributeContext(FoundContext);
1352 if (FileRecordAllocated)
1353 ExFreePoolWithTag(FileRecord, TAG_NTFS);
1354
1355 if (NT_SUCCESS(Status))
1356 *RealLengthWritten = Length;
1357
1358 return Status;
1359 }
1360
1361 // This is a non-resident attribute.
1362
1363 // I. Find the corresponding start data run.
1364
1365 // FIXME: Cache seems to be non-working. Disable it for now
1366 //if(Context->CacheRunOffset <= Offset && Offset < Context->CacheRunOffset + Context->CacheRunLength * Volume->ClusterSize)
1367 /*if (0)
1368 {
1369 DataRun = Context->CacheRun;
1370 LastLCN = Context->CacheRunLastLCN;
1371 DataRunStartLCN = Context->CacheRunStartLCN;
1372 DataRunLength = Context->CacheRunLength;
1373 CurrentOffset = Context->CacheRunCurrentOffset;
1374 }
1375 else*/
1376 {
1377 ULONG UsedBufferSize;
1378 LastLCN = 0;
1379 CurrentOffset = 0;
1380
1381 // This will be rewritten in the next iteration to just use the DataRuns MCB directly
1382 TempBuffer = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
1383
1384 ConvertLargeMCBToDataRuns(&Context->DataRunsMCB,
1385 TempBuffer,
1386 Vcb->NtfsInfo.BytesPerFileRecord,
1387 &UsedBufferSize);
1388
1389 DataRun = TempBuffer;
1390
1391 while (1)
1392 {
1393 DataRun = DecodeRun(DataRun, &DataRunOffset, &DataRunLength);
1394 if (DataRunOffset != -1)
1395 {
1396 // Normal data run.
1397 // DPRINT1("Writing to normal data run, LastLCN %I64u DataRunOffset %I64d\n", LastLCN, DataRunOffset);
1398 DataRunStartLCN = LastLCN + DataRunOffset;
1399 LastLCN = DataRunStartLCN;
1400 }
1401 else
1402 {
1403 // Sparse data run. We can't support writing to sparse files yet
1404 // (it may require increasing the allocation size).
1405 DataRunStartLCN = -1;
1406 DPRINT1("FIXME: Writing to sparse files is not supported yet!\n");
1407 return STATUS_NOT_IMPLEMENTED;
1408 }
1409
1410 // Have we reached the data run we're trying to write to?
1411 if (Offset >= CurrentOffset &&
1412 Offset < CurrentOffset + (DataRunLength * Vcb->NtfsInfo.BytesPerCluster))
1413 {
1414 break;
1415 }
1416
1417 if (*DataRun == 0)
1418 {
1419 // We reached the last assigned cluster
1420 // TODO: assign new clusters to the end of the file.
1421 // (Presently, this code will rarely be reached, the write will usually have already failed by now)
1422 // [We can reach here by creating a new file record when the MFT isn't large enough]
1423 DPRINT1("FIXME: Master File Table needs to be enlarged.\n");
1424 return STATUS_END_OF_FILE;
1425 }
1426
1427 CurrentOffset += DataRunLength * Vcb->NtfsInfo.BytesPerCluster;
1428 }
1429 }
1430
1431 // II. Go through the run list and write the data
1432
1433 /* REVIEWME -- As adapted from NtfsReadAttribute():
1434 We seem to be making a special case for the first applicable data run, but I'm not sure why.
1435 Does it have something to do with (not) caching? Is this strategy equally applicable to writing? */
1436
1437 WriteLength = (ULONG)min(DataRunLength * Vcb->NtfsInfo.BytesPerCluster - (Offset - CurrentOffset), Length);
1438
1439 StartingOffset = DataRunStartLCN * Vcb->NtfsInfo.BytesPerCluster + Offset - CurrentOffset;
1440
1441 // Write the data to the disk
1442 Status = NtfsWriteDisk(Vcb->StorageDevice,
1443 StartingOffset,
1444 WriteLength,
1445 Vcb->NtfsInfo.BytesPerSector,
1446 (PVOID)SourceBuffer);
1447
1448 // Did the write fail?
1449 if (!NT_SUCCESS(Status))
1450 {
1451 Context->CacheRun = DataRun;
1452 Context->CacheRunOffset = Offset;
1453 Context->CacheRunStartLCN = DataRunStartLCN;
1454 Context->CacheRunLength = DataRunLength;
1455 Context->CacheRunLastLCN = LastLCN;
1456 Context->CacheRunCurrentOffset = CurrentOffset;
1457
1458 return Status;
1459 }
1460
1461 Length -= WriteLength;
1462 SourceBuffer += WriteLength;
1463 *RealLengthWritten += WriteLength;
1464
1465 // Did we write to the end of the data run?
1466 if (WriteLength == DataRunLength * Vcb->NtfsInfo.BytesPerCluster - (Offset - CurrentOffset))
1467 {
1468 // Advance to the next data run
1469 CurrentOffset += DataRunLength * Vcb->NtfsInfo.BytesPerCluster;
1470 DataRun = DecodeRun(DataRun, &DataRunOffset, &DataRunLength);
1471
1472 if (DataRunOffset != (ULONGLONG)-1)
1473 {
1474 DataRunStartLCN = LastLCN + DataRunOffset;
1475 LastLCN = DataRunStartLCN;
1476 }
1477 else
1478 DataRunStartLCN = -1;
1479 }
1480
1481 // Do we have more data to write?
1482 while (Length > 0)
1483 {
1484 // Make sure we don't write past the end of the current data run
1485 WriteLength = (ULONG)min(DataRunLength * Vcb->NtfsInfo.BytesPerCluster, Length);
1486
1487 // Are we dealing with a sparse data run?
1488 if (DataRunStartLCN == -1)
1489 {
1490 DPRINT1("FIXME: Don't know how to write to sparse files yet! (DataRunStartLCN == -1)\n");
1491 return STATUS_NOT_IMPLEMENTED;
1492 }
1493 else
1494 {
1495 // write the data to the disk
1496 Status = NtfsWriteDisk(Vcb->StorageDevice,
1497 DataRunStartLCN * Vcb->NtfsInfo.BytesPerCluster,
1498 WriteLength,
1499 Vcb->NtfsInfo.BytesPerSector,
1500 (PVOID)SourceBuffer);
1501 if (!NT_SUCCESS(Status))
1502 break;
1503 }
1504
1505 Length -= WriteLength;
1506 SourceBuffer += WriteLength;
1507 *RealLengthWritten += WriteLength;
1508
1509 // We finished this request, but there's still data in this data run.
1510 if (Length == 0 && WriteLength != DataRunLength * Vcb->NtfsInfo.BytesPerCluster)
1511 break;
1512
1513 // Go to next run in the list.
1514
1515 if (*DataRun == 0)
1516 {
1517 // that was the last run
1518 if (Length > 0)
1519 {
1520 // Failed sanity check.
1521 DPRINT1("Encountered EOF before expected!\n");
1522 return STATUS_END_OF_FILE;
1523 }
1524
1525 break;
1526 }
1527
1528 // Advance to the next data run
1529 CurrentOffset += DataRunLength * Vcb->NtfsInfo.BytesPerCluster;
1530 DataRun = DecodeRun(DataRun, &DataRunOffset, &DataRunLength);
1531 if (DataRunOffset != -1)
1532 {
1533 // Normal data run.
1534 DataRunStartLCN = LastLCN + DataRunOffset;
1535 LastLCN = DataRunStartLCN;
1536 }
1537 else
1538 {
1539 // Sparse data run.
1540 DataRunStartLCN = -1;
1541 }
1542 } // end while (Length > 0) [more data to write]
1543
1544 // TEMPTEMP
1545 if (Context->pRecord->IsNonResident)
1546 ExFreePoolWithTag(TempBuffer, TAG_NTFS);
1547
1548 Context->CacheRun = DataRun;
1549 Context->CacheRunOffset = Offset + *RealLengthWritten;
1550 Context->CacheRunStartLCN = DataRunStartLCN;
1551 Context->CacheRunLength = DataRunLength;
1552 Context->CacheRunLastLCN = LastLCN;
1553 Context->CacheRunCurrentOffset = CurrentOffset;
1554
1555 return Status;
1556 }
1557
1558 NTSTATUS
1559 ReadFileRecord(PDEVICE_EXTENSION Vcb,
1560 ULONGLONG index,
1561 PFILE_RECORD_HEADER file)
1562 {
1563 ULONGLONG BytesRead;
1564
1565 DPRINT("ReadFileRecord(%p, %I64x, %p)\n", Vcb, index, file);
1566
1567 BytesRead = ReadAttribute(Vcb, Vcb->MFTContext, index * Vcb->NtfsInfo.BytesPerFileRecord, (PCHAR)file, Vcb->NtfsInfo.BytesPerFileRecord);
1568 if (BytesRead != Vcb->NtfsInfo.BytesPerFileRecord)
1569 {
1570 DPRINT1("ReadFileRecord failed: %I64u read, %lu expected\n", BytesRead, Vcb->NtfsInfo.BytesPerFileRecord);
1571 return STATUS_PARTIAL_COPY;
1572 }
1573
1574 /* Apply update sequence array fixups. */
1575 DPRINT("Sequence number: %u\n", file->SequenceNumber);
1576 return FixupUpdateSequenceArray(Vcb, &file->Ntfs);
1577 }
1578
1579
1580 /**
1581 * Searches a file's parent directory (given the parent's index in the mft)
1582 * for the given file. Upon finding an index entry for that file, updates
1583 * Data Size and Allocated Size values in the $FILE_NAME attribute of that entry.
1584 *
1585 * (Most of this code was copied from NtfsFindMftRecord)
1586 */
1587 NTSTATUS
1588 UpdateFileNameRecord(PDEVICE_EXTENSION Vcb,
1589 ULONGLONG ParentMFTIndex,
1590 PUNICODE_STRING FileName,
1591 BOOLEAN DirSearch,
1592 ULONGLONG NewDataSize,
1593 ULONGLONG NewAllocationSize,
1594 BOOLEAN CaseSensitive)
1595 {
1596 PFILE_RECORD_HEADER MftRecord;
1597 PNTFS_ATTR_CONTEXT IndexRootCtx;
1598 PINDEX_ROOT_ATTRIBUTE IndexRoot;
1599 PCHAR IndexRecord;
1600 PINDEX_ENTRY_ATTRIBUTE IndexEntry, IndexEntryEnd;
1601 NTSTATUS Status;
1602 ULONG CurrentEntry = 0;
1603
1604 DPRINT("UpdateFileNameRecord(%p, %I64d, %wZ, %s, %I64u, %I64u, %s)\n",
1605 Vcb,
1606 ParentMFTIndex,
1607 FileName,
1608 DirSearch ? "TRUE" : "FALSE",
1609 NewDataSize,
1610 NewAllocationSize,
1611 CaseSensitive ? "TRUE" : "FALSE");
1612
1613 MftRecord = ExAllocatePoolWithTag(NonPagedPool,
1614 Vcb->NtfsInfo.BytesPerFileRecord,
1615 TAG_NTFS);
1616 if (MftRecord == NULL)
1617 {
1618 return STATUS_INSUFFICIENT_RESOURCES;
1619 }
1620
1621 Status = ReadFileRecord(Vcb, ParentMFTIndex, MftRecord);
1622 if (!NT_SUCCESS(Status))
1623 {
1624 ExFreePoolWithTag(MftRecord, TAG_NTFS);
1625 return Status;
1626 }
1627
1628 ASSERT(MftRecord->Ntfs.Type == NRH_FILE_TYPE);
1629 Status = FindAttribute(Vcb, MftRecord, AttributeIndexRoot, L"$I30", 4, &IndexRootCtx, NULL);
1630 if (!NT_SUCCESS(Status))
1631 {
1632 ExFreePoolWithTag(MftRecord, TAG_NTFS);
1633 return Status;
1634 }
1635
1636 IndexRecord = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerIndexRecord, TAG_NTFS);
1637 if (IndexRecord == NULL)
1638 {
1639 ReleaseAttributeContext(IndexRootCtx);
1640 ExFreePoolWithTag(MftRecord, TAG_NTFS);
1641 return STATUS_INSUFFICIENT_RESOURCES;
1642 }
1643
1644 Status = ReadAttribute(Vcb, IndexRootCtx, 0, IndexRecord, AttributeDataLength(IndexRootCtx->pRecord));
1645 if (!NT_SUCCESS(Status))
1646 {
1647 DPRINT1("ERROR: Failed to read Index Root!\n");
1648 ExFreePoolWithTag(IndexRecord, TAG_NTFS);
1649 ReleaseAttributeContext(IndexRootCtx);
1650 ExFreePoolWithTag(MftRecord, TAG_NTFS);
1651 }
1652
1653 IndexRoot = (PINDEX_ROOT_ATTRIBUTE)IndexRecord;
1654 IndexEntry = (PINDEX_ENTRY_ATTRIBUTE)((PCHAR)&IndexRoot->Header + IndexRoot->Header.FirstEntryOffset);
1655 // Index root is always resident.
1656 IndexEntryEnd = (PINDEX_ENTRY_ATTRIBUTE)(IndexRecord + IndexRoot->Header.TotalSizeOfEntries);
1657
1658 DPRINT("IndexRecordSize: %x IndexBlockSize: %x\n", Vcb->NtfsInfo.BytesPerIndexRecord, IndexRoot->SizeOfEntry);
1659
1660 Status = UpdateIndexEntryFileNameSize(Vcb,
1661 MftRecord,
1662 IndexRecord,
1663 IndexRoot->SizeOfEntry,
1664 IndexEntry,
1665 IndexEntryEnd,
1666 FileName,
1667 &CurrentEntry,
1668 &CurrentEntry,
1669 DirSearch,
1670 NewDataSize,
1671 NewAllocationSize,
1672 CaseSensitive);
1673
1674 if (Status == STATUS_PENDING)
1675 {
1676 // we need to write the index root attribute back to disk
1677 ULONG LengthWritten;
1678 Status = WriteAttribute(Vcb, IndexRootCtx, 0, (PUCHAR)IndexRecord, AttributeDataLength(IndexRootCtx->pRecord), &LengthWritten, MftRecord);
1679 if (!NT_SUCCESS(Status))
1680 {
1681 DPRINT1("ERROR: Couldn't update Index Root!\n");
1682 }
1683
1684 }
1685
1686 ReleaseAttributeContext(IndexRootCtx);
1687 ExFreePoolWithTag(IndexRecord, TAG_NTFS);
1688 ExFreePoolWithTag(MftRecord, TAG_NTFS);
1689
1690 return Status;
1691 }
1692
1693 /**
1694 * Recursively searches directory index and applies the size update to the $FILE_NAME attribute of the
1695 * proper index entry.
1696 * (Heavily based on BrowseIndexEntries)
1697 */
1698 NTSTATUS
1699 UpdateIndexEntryFileNameSize(PDEVICE_EXTENSION Vcb,
1700 PFILE_RECORD_HEADER MftRecord,
1701 PCHAR IndexRecord,
1702 ULONG IndexBlockSize,
1703 PINDEX_ENTRY_ATTRIBUTE FirstEntry,
1704 PINDEX_ENTRY_ATTRIBUTE LastEntry,
1705 PUNICODE_STRING FileName,
1706 PULONG StartEntry,
1707 PULONG CurrentEntry,
1708 BOOLEAN DirSearch,
1709 ULONGLONG NewDataSize,
1710 ULONGLONG NewAllocatedSize,
1711 BOOLEAN CaseSensitive)
1712 {
1713 NTSTATUS Status;
1714 ULONG RecordOffset;
1715 PINDEX_ENTRY_ATTRIBUTE IndexEntry;
1716 PNTFS_ATTR_CONTEXT IndexAllocationCtx;
1717 ULONGLONG IndexAllocationSize;
1718 PINDEX_BUFFER IndexBuffer;
1719
1720 DPRINT("UpdateIndexEntrySize(%p, %p, %p, %lu, %p, %p, %wZ, %lu, %lu, %s, %I64u, %I64u, %s)\n",
1721 Vcb,
1722 MftRecord,
1723 IndexRecord,
1724 IndexBlockSize,
1725 FirstEntry,
1726 LastEntry,
1727 FileName,
1728 *StartEntry,
1729 *CurrentEntry,
1730 DirSearch ? "TRUE" : "FALSE",
1731 NewDataSize,
1732 NewAllocatedSize,
1733 CaseSensitive ? "TRUE" : "FALSE");
1734
1735 // find the index entry responsible for the file we're trying to update
1736 IndexEntry = FirstEntry;
1737 while (IndexEntry < LastEntry &&
1738 !(IndexEntry->Flags & NTFS_INDEX_ENTRY_END))
1739 {
1740 if ((IndexEntry->Data.Directory.IndexedFile & NTFS_MFT_MASK) > NTFS_FILE_FIRST_USER_FILE &&
1741 *CurrentEntry >= *StartEntry &&
1742 IndexEntry->FileName.NameType != NTFS_FILE_NAME_DOS &&
1743 CompareFileName(FileName, IndexEntry, DirSearch, CaseSensitive))
1744 {
1745 *StartEntry = *CurrentEntry;
1746 IndexEntry->FileName.DataSize = NewDataSize;
1747 IndexEntry->FileName.AllocatedSize = NewAllocatedSize;
1748 // indicate that the caller will still need to write the structure to the disk
1749 return STATUS_PENDING;
1750 }
1751
1752 (*CurrentEntry) += 1;
1753 ASSERT(IndexEntry->Length >= sizeof(INDEX_ENTRY_ATTRIBUTE));
1754 IndexEntry = (PINDEX_ENTRY_ATTRIBUTE)((PCHAR)IndexEntry + IndexEntry->Length);
1755 }
1756
1757 /* If we're already browsing a subnode */
1758 if (IndexRecord == NULL)
1759 {
1760 return STATUS_OBJECT_PATH_NOT_FOUND;
1761 }
1762
1763 /* If there's no subnode */
1764 if (!(IndexEntry->Flags & NTFS_INDEX_ENTRY_NODE))
1765 {
1766 return STATUS_OBJECT_PATH_NOT_FOUND;
1767 }
1768
1769 Status = FindAttribute(Vcb, MftRecord, AttributeIndexAllocation, L"$I30", 4, &IndexAllocationCtx, NULL);
1770 if (!NT_SUCCESS(Status))
1771 {
1772 DPRINT("Corrupted filesystem!\n");
1773 return Status;
1774 }
1775
1776 IndexAllocationSize = AttributeDataLength(IndexAllocationCtx->pRecord);
1777 Status = STATUS_OBJECT_PATH_NOT_FOUND;
1778 for (RecordOffset = 0; RecordOffset < IndexAllocationSize; RecordOffset += IndexBlockSize)
1779 {
1780 ReadAttribute(Vcb, IndexAllocationCtx, RecordOffset, IndexRecord, IndexBlockSize);
1781 Status = FixupUpdateSequenceArray(Vcb, &((PFILE_RECORD_HEADER)IndexRecord)->Ntfs);
1782 if (!NT_SUCCESS(Status))
1783 {
1784 break;
1785 }
1786
1787 IndexBuffer = (PINDEX_BUFFER)IndexRecord;
1788 ASSERT(IndexBuffer->Ntfs.Type == NRH_INDX_TYPE);
1789 ASSERT(IndexBuffer->Header.AllocatedSize + FIELD_OFFSET(INDEX_BUFFER, Header) == IndexBlockSize);
1790 FirstEntry = (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)&IndexBuffer->Header + IndexBuffer->Header.FirstEntryOffset);
1791 LastEntry = (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)&IndexBuffer->Header + IndexBuffer->Header.TotalSizeOfEntries);
1792 ASSERT(LastEntry <= (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)IndexBuffer + IndexBlockSize));
1793
1794 Status = UpdateIndexEntryFileNameSize(NULL,
1795 NULL,
1796 NULL,
1797 0,
1798 FirstEntry,
1799 LastEntry,
1800 FileName,
1801 StartEntry,
1802 CurrentEntry,
1803 DirSearch,
1804 NewDataSize,
1805 NewAllocatedSize,
1806 CaseSensitive);
1807 if (Status == STATUS_PENDING)
1808 {
1809 // write the index record back to disk
1810 ULONG Written;
1811
1812 // first we need to update the fixup values for the index block
1813 Status = AddFixupArray(Vcb, &((PFILE_RECORD_HEADER)IndexRecord)->Ntfs);
1814 if (!NT_SUCCESS(Status))
1815 {
1816 DPRINT1("Error: Failed to update fixup sequence array!\n");
1817 break;
1818 }
1819
1820 Status = WriteAttribute(Vcb, IndexAllocationCtx, RecordOffset, (const PUCHAR)IndexRecord, IndexBlockSize, &Written, MftRecord);
1821 if (!NT_SUCCESS(Status))
1822 {
1823 DPRINT1("ERROR Performing write!\n");
1824 break;
1825 }
1826
1827 Status = STATUS_SUCCESS;
1828 break;
1829 }
1830 if (NT_SUCCESS(Status))
1831 {
1832 break;
1833 }
1834 }
1835
1836 ReleaseAttributeContext(IndexAllocationCtx);
1837 return Status;
1838 }
1839
1840 /**
1841 * @name UpdateFileRecord
1842 * @implemented
1843 *
1844 * Writes a file record to the master file table, at a given index.
1845 *
1846 * @param Vcb
1847 * Pointer to the DEVICE_EXTENSION of the target drive being written to.
1848 *
1849 * @param MftIndex
1850 * Target index in the master file table to store the file record.
1851 *
1852 * @param FileRecord
1853 * Pointer to the complete file record which will be written to the master file table.
1854 *
1855 * @return
1856 * STATUS_SUCCESSFUL on success. An error passed from WriteAttribute() otherwise.
1857 *
1858 */
1859 NTSTATUS
1860 UpdateFileRecord(PDEVICE_EXTENSION Vcb,
1861 ULONGLONG MftIndex,
1862 PFILE_RECORD_HEADER FileRecord)
1863 {
1864 ULONG BytesWritten;
1865 NTSTATUS Status = STATUS_SUCCESS;
1866
1867 DPRINT("UpdateFileRecord(%p, 0x%I64x, %p)\n", Vcb, MftIndex, FileRecord);
1868
1869 // Add the fixup array to prepare the data for writing to disk
1870 AddFixupArray(Vcb, &FileRecord->Ntfs);
1871
1872 // write the file record to the master file table
1873 Status = WriteAttribute(Vcb,
1874 Vcb->MFTContext,
1875 MftIndex * Vcb->NtfsInfo.BytesPerFileRecord,
1876 (const PUCHAR)FileRecord,
1877 Vcb->NtfsInfo.BytesPerFileRecord,
1878 &BytesWritten,
1879 FileRecord);
1880
1881 if (!NT_SUCCESS(Status))
1882 {
1883 DPRINT1("UpdateFileRecord failed: %lu written, %lu expected\n", BytesWritten, Vcb->NtfsInfo.BytesPerFileRecord);
1884 }
1885
1886 // remove the fixup array (so the file record pointer can still be used)
1887 FixupUpdateSequenceArray(Vcb, &FileRecord->Ntfs);
1888
1889 return Status;
1890 }
1891
1892
1893 NTSTATUS
1894 FixupUpdateSequenceArray(PDEVICE_EXTENSION Vcb,
1895 PNTFS_RECORD_HEADER Record)
1896 {
1897 USHORT *USA;
1898 USHORT USANumber;
1899 USHORT USACount;
1900 USHORT *Block;
1901
1902 USA = (USHORT*)((PCHAR)Record + Record->UsaOffset);
1903 USANumber = *(USA++);
1904 USACount = Record->UsaCount - 1; /* Exclude the USA Number. */
1905 Block = (USHORT*)((PCHAR)Record + Vcb->NtfsInfo.BytesPerSector - 2);
1906
1907 DPRINT("FixupUpdateSequenceArray(%p, %p)\nUSANumber: %u\tUSACount: %u\n", Vcb, Record, USANumber, USACount);
1908
1909 while (USACount)
1910 {
1911 if (*Block != USANumber)
1912 {
1913 DPRINT1("Mismatch with USA: %u read, %u expected\n" , *Block, USANumber);
1914 return STATUS_UNSUCCESSFUL;
1915 }
1916 *Block = *(USA++);
1917 Block = (USHORT*)((PCHAR)Block + Vcb->NtfsInfo.BytesPerSector);
1918 USACount--;
1919 }
1920
1921 return STATUS_SUCCESS;
1922 }
1923
1924 /**
1925 * @name AddNewMftEntry
1926 * @implemented
1927 *
1928 * Adds a file record to the master file table of a given device.
1929 *
1930 * @param FileRecord
1931 * Pointer to a complete file record which will be saved to disk.
1932 *
1933 * @param DeviceExt
1934 * Pointer to the DEVICE_EXTENSION of the target drive.
1935 *
1936 * @param DestinationIndex
1937 * Pointer to a ULONGLONG which will receive the MFT index where the file record was stored.
1938 *
1939 * @param CanWait
1940 * Boolean indicating if the function is allowed to wait for exclusive access to the master file table.
1941 * This will only be relevant if the MFT doesn't have any free file records and needs to be enlarged.
1942 *
1943 * @return
1944 * STATUS_SUCCESS on success.
1945 * STATUS_OBJECT_NAME_NOT_FOUND if we can't find the MFT's $Bitmap or if we weren't able
1946 * to read the attribute.
1947 * STATUS_INSUFFICIENT_RESOURCES if we can't allocate enough memory for a copy of $Bitmap.
1948 * STATUS_CANT_WAIT if CanWait was FALSE and the function could not get immediate, exclusive access to the MFT.
1949 */
1950 NTSTATUS
1951 AddNewMftEntry(PFILE_RECORD_HEADER FileRecord,
1952 PDEVICE_EXTENSION DeviceExt,
1953 PULONGLONG DestinationIndex,
1954 BOOLEAN CanWait)
1955 {
1956 NTSTATUS Status = STATUS_SUCCESS;
1957 ULONGLONG MftIndex;
1958 RTL_BITMAP Bitmap;
1959 ULONGLONG BitmapDataSize;
1960 ULONGLONG AttrBytesRead;
1961 PUCHAR BitmapData;
1962 PUCHAR BitmapBuffer;
1963 ULONG LengthWritten;
1964 PNTFS_ATTR_CONTEXT BitmapContext;
1965 LARGE_INTEGER BitmapBits;
1966 UCHAR SystemReservedBits;
1967
1968 DPRINT1("AddNewMftEntry(%p, %p, %p, %s)\n", FileRecord, DeviceExt, DestinationIndex, CanWait ? "TRUE" : "FALSE");
1969
1970 // First, we have to read the mft's $Bitmap attribute
1971
1972 // Find the attribute
1973 Status = FindAttribute(DeviceExt, DeviceExt->MasterFileTable, AttributeBitmap, L"", 0, &BitmapContext, NULL);
1974 if (!NT_SUCCESS(Status))
1975 {
1976 DPRINT1("ERROR: Couldn't find $Bitmap attribute of master file table!\n");
1977 return Status;
1978 }
1979
1980 // Get size of bitmap
1981 BitmapDataSize = AttributeDataLength(BitmapContext->pRecord);
1982
1983 // RtlInitializeBitmap wants a ULONG-aligned pointer, and wants the memory passed to it to be a ULONG-multiple
1984 // Allocate a buffer for the $Bitmap attribute plus enough to ensure we can get a ULONG-aligned pointer
1985 BitmapBuffer = ExAllocatePoolWithTag(NonPagedPool, BitmapDataSize + sizeof(ULONG), TAG_NTFS);
1986 if (!BitmapBuffer)
1987 {
1988 ReleaseAttributeContext(BitmapContext);
1989 return STATUS_INSUFFICIENT_RESOURCES;
1990 }
1991
1992 // Get a ULONG-aligned pointer for the bitmap itself
1993 BitmapData = (PUCHAR)ALIGN_UP_BY((ULONG_PTR)BitmapBuffer, sizeof(ULONG));
1994
1995 // read $Bitmap attribute
1996 AttrBytesRead = ReadAttribute(DeviceExt, BitmapContext, 0, (PCHAR)BitmapData, BitmapDataSize);
1997
1998 if (AttrBytesRead != BitmapDataSize)
1999 {
2000 DPRINT1("ERROR: Unable to read $Bitmap attribute of master file table!\n");
2001 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
2002 ReleaseAttributeContext(BitmapContext);
2003 return STATUS_OBJECT_NAME_NOT_FOUND;
2004 }
2005
2006 // We need to backup the bits for records 0x10 - 0x17 (3rd byte of bitmap) and mark these records
2007 // as in-use so we don't assign files to those indices. They're reserved for the system (e.g. ChkDsk).
2008 SystemReservedBits = BitmapData[2];
2009 BitmapData[2] = 0xff;
2010
2011 // Calculate bit count
2012 BitmapBits.QuadPart = AttributeDataLength(DeviceExt->MFTContext->pRecord) /
2013 DeviceExt->NtfsInfo.BytesPerFileRecord;
2014 if (BitmapBits.HighPart != 0)
2015 {
2016 DPRINT1("\tFIXME: bitmap sizes beyond 32bits are not yet supported! (Your NTFS volume is too large)\n");
2017 NtfsGlobalData->EnableWriteSupport = FALSE;
2018 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
2019 ReleaseAttributeContext(BitmapContext);
2020 return STATUS_NOT_IMPLEMENTED;
2021 }
2022
2023 // convert buffer into bitmap
2024 RtlInitializeBitMap(&Bitmap, (PULONG)BitmapData, BitmapBits.LowPart);
2025
2026 // set next available bit, preferrably after 23rd bit
2027 MftIndex = RtlFindClearBitsAndSet(&Bitmap, 1, 24);
2028 if ((LONG)MftIndex == -1)
2029 {
2030 DPRINT1("Couldn't find free space in MFT for file record, increasing MFT size.\n");
2031
2032 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
2033 ReleaseAttributeContext(BitmapContext);
2034
2035 // Couldn't find a free record in the MFT, add some blank records and try again
2036 Status = IncreaseMftSize(DeviceExt, CanWait);
2037 if (!NT_SUCCESS(Status))
2038 {
2039 DPRINT1("ERROR: Couldn't find space in MFT for file or increase MFT size!\n");
2040 return Status;
2041 }
2042
2043 return AddNewMftEntry(FileRecord, DeviceExt, DestinationIndex, CanWait);
2044 }
2045
2046 DPRINT1("Creating file record at MFT index: %I64u\n", MftIndex);
2047
2048 // update file record with index
2049 FileRecord->MFTRecordNumber = MftIndex;
2050
2051 // [BitmapData should have been updated via RtlFindClearBitsAndSet()]
2052
2053 // Restore the system reserved bits
2054 BitmapData[2] = SystemReservedBits;
2055
2056 // write the bitmap back to the MFT's $Bitmap attribute
2057 Status = WriteAttribute(DeviceExt, BitmapContext, 0, BitmapData, BitmapDataSize, &LengthWritten, FileRecord);
2058 if (!NT_SUCCESS(Status))
2059 {
2060 DPRINT1("ERROR encountered when writing $Bitmap attribute!\n");
2061 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
2062 ReleaseAttributeContext(BitmapContext);
2063 return Status;
2064 }
2065
2066 // update the file record (write it to disk)
2067 Status = UpdateFileRecord(DeviceExt, MftIndex, FileRecord);
2068
2069 if (!NT_SUCCESS(Status))
2070 {
2071 DPRINT1("ERROR: Unable to write file record!\n");
2072 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
2073 ReleaseAttributeContext(BitmapContext);
2074 return Status;
2075 }
2076
2077 *DestinationIndex = MftIndex;
2078
2079 ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
2080 ReleaseAttributeContext(BitmapContext);
2081
2082 return Status;
2083 }
2084
2085 /**
2086 * @name NtfsAddFilenameToDirectory
2087 * @implemented
2088 *
2089 * Adds a $FILE_NAME attribute to a given directory index.
2090 *
2091 * @param DeviceExt
2092 * Points to the target disk's DEVICE_EXTENSION.
2093 *
2094 * @param DirectoryMftIndex
2095 * Mft index of the parent directory which will receive the file.
2096 *
2097 * @param FileReferenceNumber
2098 * File reference of the file to be added to the directory. This is a combination of the
2099 * Mft index and sequence number.
2100 *
2101 * @param FilenameAttribute
2102 * Pointer to the FILENAME_ATTRIBUTE of the file being added to the directory.
2103 *
2104 * @param CaseSensitive
2105 * Boolean indicating if the function should operate in case-sensitive mode. This will be TRUE
2106 * if an application created the file with the FILE_FLAG_POSIX_SEMANTICS flag.
2107 *
2108 * @return
2109 * STATUS_SUCCESS on success.
2110 * STATUS_INSUFFICIENT_RESOURCES if an allocation fails.
2111 * STATUS_NOT_IMPLEMENTED if target address isn't at the end of the given file record.
2112 *
2113 * @remarks
2114 * WIP - Can only support a few files in a directory.
2115 * One FILENAME_ATTRIBUTE is added to the directory's index for each link to that file. So, each
2116 * file which contains one FILENAME_ATTRIBUTE for a long name and another for the 8.3 name, will
2117 * get both attributes added to its parent directory.
2118 */
2119 NTSTATUS
2120 NtfsAddFilenameToDirectory(PDEVICE_EXTENSION DeviceExt,
2121 ULONGLONG DirectoryMftIndex,
2122 ULONGLONG FileReferenceNumber,
2123 PFILENAME_ATTRIBUTE FilenameAttribute,
2124 BOOLEAN CaseSensitive)
2125 {
2126 NTSTATUS Status = STATUS_SUCCESS;
2127 PFILE_RECORD_HEADER ParentFileRecord;
2128 PNTFS_ATTR_CONTEXT IndexRootContext;
2129 PINDEX_ROOT_ATTRIBUTE I30IndexRoot;
2130 ULONG IndexRootOffset;
2131 ULONGLONG I30IndexRootLength;
2132 ULONG LengthWritten;
2133 PINDEX_ROOT_ATTRIBUTE NewIndexRoot;
2134 ULONG AttributeLength;
2135 PNTFS_ATTR_RECORD NextAttribute;
2136 PB_TREE NewTree;
2137 ULONG BtreeIndexLength;
2138 ULONG MaxIndexRootSize;
2139 PB_TREE_KEY NewLeftKey;
2140 PB_TREE_FILENAME_NODE NewRightHandNode;
2141
2142 // Allocate memory for the parent directory
2143 ParentFileRecord = ExAllocatePoolWithTag(NonPagedPool,
2144 DeviceExt->NtfsInfo.BytesPerFileRecord,
2145 TAG_NTFS);
2146 if (!ParentFileRecord)
2147 {
2148 DPRINT1("ERROR: Couldn't allocate memory for file record!\n");
2149 return STATUS_INSUFFICIENT_RESOURCES;
2150 }
2151
2152 // Open the parent directory
2153 Status = ReadFileRecord(DeviceExt, DirectoryMftIndex, ParentFileRecord);
2154 if (!NT_SUCCESS(Status))
2155 {
2156 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2157 DPRINT1("ERROR: Couldn't read parent directory with index %I64u\n",
2158 DirectoryMftIndex);
2159 return Status;
2160 }
2161
2162 #ifndef NDEBUG
2163 DPRINT1("Dumping old parent file record:\n");
2164 NtfsDumpFileRecord(DeviceExt, ParentFileRecord);
2165 #endif
2166
2167 // Find the index root attribute for the directory
2168 Status = FindAttribute(DeviceExt,
2169 ParentFileRecord,
2170 AttributeIndexRoot,
2171 L"$I30",
2172 4,
2173 &IndexRootContext,
2174 &IndexRootOffset);
2175 if (!NT_SUCCESS(Status))
2176 {
2177 DPRINT1("ERROR: Couldn't find $I30 $INDEX_ROOT attribute for parent directory with MFT #: %I64u!\n",
2178 DirectoryMftIndex);
2179 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2180 return Status;
2181 }
2182
2183 // Find the maximum index size given what the file record can hold
2184 // First, find the max index size assuming index root is the last attribute
2185 MaxIndexRootSize = DeviceExt->NtfsInfo.BytesPerFileRecord // Start with the size of a file record
2186 - IndexRootOffset // Subtract the length of everything that comes before index root
2187 - IndexRootContext->pRecord->Resident.ValueOffset // Subtract the length of the attribute header for index root
2188 - sizeof(INDEX_ROOT_ATTRIBUTE) // Subtract the length of the index root header
2189 - (sizeof(ULONG) * 2); // Subtract the length of the file record end marker and padding
2190
2191 // Are there attributes after this one?
2192 NextAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)ParentFileRecord + IndexRootOffset + IndexRootContext->pRecord->Length);
2193 if (NextAttribute->Type != AttributeEnd)
2194 {
2195 // Find the length of all attributes after this one, not counting the end marker
2196 ULONG LengthOfAttributes = 0;
2197 PNTFS_ATTR_RECORD CurrentAttribute = NextAttribute;
2198 while (CurrentAttribute->Type != AttributeEnd)
2199 {
2200 LengthOfAttributes += CurrentAttribute->Length;
2201 CurrentAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)CurrentAttribute + CurrentAttribute->Length);
2202 }
2203
2204 // Leave room for the existing attributes
2205 MaxIndexRootSize -= LengthOfAttributes;
2206 }
2207
2208 // Allocate memory for the index root data
2209 I30IndexRootLength = AttributeDataLength(IndexRootContext->pRecord);
2210 I30IndexRoot = ExAllocatePoolWithTag(NonPagedPool, I30IndexRootLength, TAG_NTFS);
2211 if (!I30IndexRoot)
2212 {
2213 DPRINT1("ERROR: Couldn't allocate memory for index root attribute!\n");
2214 ReleaseAttributeContext(IndexRootContext);
2215 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2216 return STATUS_INSUFFICIENT_RESOURCES;
2217 }
2218
2219 // Read the Index Root
2220 Status = ReadAttribute(DeviceExt, IndexRootContext, 0, (PCHAR)I30IndexRoot, I30IndexRootLength);
2221 if (!NT_SUCCESS(Status))
2222 {
2223 DPRINT1("ERROR: Couln't read index root attribute for Mft index #%I64u\n", DirectoryMftIndex);
2224 ReleaseAttributeContext(IndexRootContext);
2225 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2226 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2227 return Status;
2228 }
2229
2230 // Convert the index to a B*Tree
2231 Status = CreateBTreeFromIndex(DeviceExt,
2232 ParentFileRecord,
2233 IndexRootContext,
2234 I30IndexRoot,
2235 &NewTree);
2236 if (!NT_SUCCESS(Status))
2237 {
2238 DPRINT1("ERROR: Failed to create B-Tree from Index!\n");
2239 ReleaseAttributeContext(IndexRootContext);
2240 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2241 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2242 return Status;
2243 }
2244
2245 #ifndef NDEBUG
2246 DumpBTree(NewTree);
2247 #endif
2248
2249 // Insert the key for the file we're adding
2250 Status = NtfsInsertKey(NewTree,
2251 FileReferenceNumber,
2252 FilenameAttribute,
2253 NewTree->RootNode,
2254 CaseSensitive,
2255 MaxIndexRootSize,
2256 I30IndexRoot->SizeOfEntry,
2257 &NewLeftKey,
2258 &NewRightHandNode);
2259 if (!NT_SUCCESS(Status))
2260 {
2261 DPRINT1("ERROR: Failed to insert key into B-Tree!\n");
2262 DestroyBTree(NewTree);
2263 ReleaseAttributeContext(IndexRootContext);
2264 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2265 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2266 return Status;
2267 }
2268
2269 #ifndef NDEBUG
2270 DumpBTree(NewTree);
2271 #endif
2272
2273 // The root node can't be split
2274 ASSERT(NewLeftKey == NULL);
2275 ASSERT(NewRightHandNode == NULL);
2276
2277 // Convert B*Tree back to Index
2278
2279 // Updating the index allocation can change the size available for the index root,
2280 // And if the index root is demoted, the index allocation will need to be updated again,
2281 // which may change the size available for index root... etc.
2282 // My solution is to decrease index root to the size it would be if it was demoted,
2283 // then UpdateIndexAllocation will have an accurate representation of the maximum space
2284 // it can use in the file record. There's still a chance that the act of allocating an
2285 // index node after demoting the index root will increase the size of the file record beyond
2286 // it's limit, but if that happens, an attribute-list will most definitely be needed.
2287 // This a bit hacky, but it seems to be functional.
2288
2289 // Calculate the minimum size of the index root attribute, considering one dummy key and one VCN
2290 LARGE_INTEGER MinIndexRootSize;
2291 MinIndexRootSize.QuadPart = sizeof(INDEX_ROOT_ATTRIBUTE) // size of the index root headers
2292 + 0x18; // Size of dummy key with a VCN for a subnode
2293 ASSERT(MinIndexRootSize.QuadPart % ATTR_RECORD_ALIGNMENT == 0);
2294
2295 // Temporarily shrink the index root to it's minimal size
2296 AttributeLength = MinIndexRootSize.LowPart;
2297 AttributeLength += sizeof(INDEX_ROOT_ATTRIBUTE);
2298
2299
2300 // FIXME: IndexRoot will probably be invalid until we're finished. If we fail before we finish, the directory will probably be toast.
2301 // The potential for catastrophic data-loss exists!!! :)
2302
2303 // Update the length of the attribute in the file record of the parent directory
2304 Status = InternalSetResidentAttributeLength(DeviceExt,
2305 IndexRootContext,
2306 ParentFileRecord,
2307 IndexRootOffset,
2308 AttributeLength);
2309 if (!NT_SUCCESS(Status))
2310 {
2311 DPRINT1("ERROR: Unable to set length of index root!\n");
2312 DestroyBTree(NewTree);
2313 ReleaseAttributeContext(IndexRootContext);
2314 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2315 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2316 return Status;
2317 }
2318
2319 // Update the index allocation
2320 Status = UpdateIndexAllocation(DeviceExt, NewTree, I30IndexRoot->SizeOfEntry, ParentFileRecord);
2321 if (!NT_SUCCESS(Status))
2322 {
2323 DPRINT1("ERROR: Failed to update index allocation from B-Tree!\n");
2324 DestroyBTree(NewTree);
2325 ReleaseAttributeContext(IndexRootContext);
2326 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2327 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2328 return Status;
2329 }
2330
2331 #ifndef NDEBUG
2332 DPRINT1("Index Allocation updated\n");
2333 DumpBTree(NewTree);
2334 #endif
2335
2336 // Find the maximum index root size given what the file record can hold
2337 // First, find the max index size assuming index root is the last attribute
2338 ULONG NewMaxIndexRootSize =
2339 DeviceExt->NtfsInfo.BytesPerFileRecord // Start with the size of a file record
2340 - IndexRootOffset // Subtract the length of everything that comes before index root
2341 - IndexRootContext->pRecord->Resident.ValueOffset // Subtract the length of the attribute header for index root
2342 - sizeof(INDEX_ROOT_ATTRIBUTE) // Subtract the length of the index root header
2343 - (sizeof(ULONG) * 2); // Subtract the length of the file record end marker and padding
2344
2345 // Are there attributes after this one?
2346 NextAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)ParentFileRecord + IndexRootOffset + IndexRootContext->pRecord->Length);
2347 if (NextAttribute->Type != AttributeEnd)
2348 {
2349 // Find the length of all attributes after this one, not counting the end marker
2350 ULONG LengthOfAttributes = 0;
2351 PNTFS_ATTR_RECORD CurrentAttribute = NextAttribute;
2352 while (CurrentAttribute->Type != AttributeEnd)
2353 {
2354 LengthOfAttributes += CurrentAttribute->Length;
2355 CurrentAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)CurrentAttribute + CurrentAttribute->Length);
2356 }
2357
2358 // Leave room for the existing attributes
2359 NewMaxIndexRootSize -= LengthOfAttributes;
2360 }
2361
2362 // The index allocation and index bitmap may have grown, leaving less room for the index root,
2363 // so now we need to double-check that index root isn't too large
2364 ULONG NodeSize = GetSizeOfIndexEntries(NewTree->RootNode);
2365 if (NodeSize > NewMaxIndexRootSize)
2366 {
2367 DPRINT1("Demoting index root.\nNodeSize: 0x%lx\nNewMaxIndexRootSize: 0x%lx\n", NodeSize, NewMaxIndexRootSize);
2368
2369 Status = DemoteBTreeRoot(NewTree);
2370 if (!NT_SUCCESS(Status))
2371 {
2372 DPRINT1("ERROR: Failed to demote index root!\n");
2373 DestroyBTree(NewTree);
2374 ReleaseAttributeContext(IndexRootContext);
2375 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2376 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2377 return Status;
2378 }
2379
2380 // We need to update the index allocation once more
2381 Status = UpdateIndexAllocation(DeviceExt, NewTree, I30IndexRoot->SizeOfEntry, ParentFileRecord);
2382 if (!NT_SUCCESS(Status))
2383 {
2384 DPRINT1("ERROR: Failed to update index allocation from B-Tree!\n");
2385 DestroyBTree(NewTree);
2386 ReleaseAttributeContext(IndexRootContext);
2387 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2388 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2389 return Status;
2390 }
2391
2392 // re-recalculate max size of index root
2393 NewMaxIndexRootSize =
2394 // Find the maximum index size given what the file record can hold
2395 // First, find the max index size assuming index root is the last attribute
2396 DeviceExt->NtfsInfo.BytesPerFileRecord // Start with the size of a file record
2397 - IndexRootOffset // Subtract the length of everything that comes before index root
2398 - IndexRootContext->pRecord->Resident.ValueOffset // Subtract the length of the attribute header for index root
2399 - sizeof(INDEX_ROOT_ATTRIBUTE) // Subtract the length of the index root header
2400 - (sizeof(ULONG) * 2); // Subtract the length of the file record end marker and padding
2401
2402 // Are there attributes after this one?
2403 NextAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)ParentFileRecord + IndexRootOffset + IndexRootContext->pRecord->Length);
2404 if (NextAttribute->Type != AttributeEnd)
2405 {
2406 // Find the length of all attributes after this one, not counting the end marker
2407 ULONG LengthOfAttributes = 0;
2408 PNTFS_ATTR_RECORD CurrentAttribute = NextAttribute;
2409 while (CurrentAttribute->Type != AttributeEnd)
2410 {
2411 LengthOfAttributes += CurrentAttribute->Length;
2412 CurrentAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)CurrentAttribute + CurrentAttribute->Length);
2413 }
2414
2415 // Leave room for the existing attributes
2416 NewMaxIndexRootSize -= LengthOfAttributes;
2417 }
2418
2419
2420 }
2421
2422 // Create the Index Root from the B*Tree
2423 Status = CreateIndexRootFromBTree(DeviceExt, NewTree, NewMaxIndexRootSize, &NewIndexRoot, &BtreeIndexLength);
2424 if (!NT_SUCCESS(Status))
2425 {
2426 DPRINT1("ERROR: Failed to create Index root from B-Tree!\n");
2427 DestroyBTree(NewTree);
2428 ReleaseAttributeContext(IndexRootContext);
2429 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2430 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2431 return Status;
2432 }
2433
2434 // We're done with the B-Tree now
2435 DestroyBTree(NewTree);
2436
2437 // Write back the new index root attribute to the parent directory file record
2438
2439 // First, we need to resize the attribute.
2440 // CreateIndexRootFromBTree() should have verified that the index root fits within MaxIndexSize.
2441 // We can't set the size as we normally would, because $INDEX_ROOT must always be resident.
2442 AttributeLength = NewIndexRoot->Header.AllocatedSize + FIELD_OFFSET(INDEX_ROOT_ATTRIBUTE, Header);
2443
2444 if (AttributeLength != IndexRootContext->pRecord->Resident.ValueLength)
2445 {
2446 // Update the length of the attribute in the file record of the parent directory
2447 Status = InternalSetResidentAttributeLength(DeviceExt,
2448 IndexRootContext,
2449 ParentFileRecord,
2450 IndexRootOffset,
2451 AttributeLength);
2452 if (!NT_SUCCESS(Status))
2453 {
2454 ExFreePoolWithTag(NewIndexRoot, TAG_NTFS);
2455 ReleaseAttributeContext(IndexRootContext);
2456 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2457 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2458 DPRINT1("ERROR: Unable to set resident attribute length!\n");
2459 return Status;
2460 }
2461
2462 }
2463
2464 NT_ASSERT(ParentFileRecord->BytesInUse <= DeviceExt->NtfsInfo.BytesPerFileRecord);
2465
2466 Status = UpdateFileRecord(DeviceExt, DirectoryMftIndex, ParentFileRecord);
2467 if (!NT_SUCCESS(Status))
2468 {
2469 DPRINT1("ERROR: Failed to update file record of directory with index: %llx\n", DirectoryMftIndex);
2470 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2471 ExFreePoolWithTag(NewIndexRoot, TAG_NTFS);
2472 ReleaseAttributeContext(IndexRootContext);
2473 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2474 return Status;
2475 }
2476
2477 // Write the new index root to disk
2478 Status = WriteAttribute(DeviceExt,
2479 IndexRootContext,
2480 0,
2481 (PUCHAR)NewIndexRoot,
2482 AttributeLength,
2483 &LengthWritten,
2484 ParentFileRecord);
2485 if (!NT_SUCCESS(Status) || LengthWritten != AttributeLength)
2486 {
2487 DPRINT1("ERROR: Unable to write new index root attribute to parent directory!\n");
2488 ExFreePoolWithTag(NewIndexRoot, TAG_NTFS);
2489 ReleaseAttributeContext(IndexRootContext);
2490 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2491 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2492 return Status;
2493 }
2494
2495 // re-read the parent file record, so we can dump it
2496 Status = ReadFileRecord(DeviceExt, DirectoryMftIndex, ParentFileRecord);
2497 if (!NT_SUCCESS(Status))
2498 {
2499 DPRINT1("ERROR: Couldn't read parent directory after messing with it!\n");
2500 }
2501 else
2502 {
2503 #ifndef NDEBUG
2504 DPRINT1("Dumping new B-Tree:\n");
2505
2506 Status = CreateBTreeFromIndex(DeviceExt, ParentFileRecord, IndexRootContext, NewIndexRoot, &NewTree);
2507 if (!NT_SUCCESS(Status))
2508 {
2509 DPRINT1("ERROR: Couldn't re-create b-tree\n");
2510 return Status;
2511 }
2512
2513 DumpBTree(NewTree);
2514
2515 DestroyBTree(NewTree);
2516
2517 NtfsDumpFileRecord(DeviceExt, ParentFileRecord);
2518 #endif
2519 }
2520
2521 // Cleanup
2522 ExFreePoolWithTag(NewIndexRoot, TAG_NTFS);
2523 ReleaseAttributeContext(IndexRootContext);
2524 ExFreePoolWithTag(I30IndexRoot, TAG_NTFS);
2525 ExFreePoolWithTag(ParentFileRecord, TAG_NTFS);
2526
2527 return Status;
2528 }
2529
2530 NTSTATUS
2531 AddFixupArray(PDEVICE_EXTENSION Vcb,
2532 PNTFS_RECORD_HEADER Record)
2533 {
2534 USHORT *pShortToFixUp;
2535 ULONG ArrayEntryCount = Record->UsaCount - 1;
2536 ULONG Offset = Vcb->NtfsInfo.BytesPerSector - 2;
2537 ULONG i;
2538
2539 PFIXUP_ARRAY fixupArray = (PFIXUP_ARRAY)((UCHAR*)Record + Record->UsaOffset);
2540
2541 DPRINT("AddFixupArray(%p, %p)\n fixupArray->USN: %u, ArrayEntryCount: %u\n", Vcb, Record, fixupArray->USN, ArrayEntryCount);
2542
2543 fixupArray->USN++;
2544
2545 for (i = 0; i < ArrayEntryCount; i++)
2546 {
2547 DPRINT("USN: %u\tOffset: %u\n", fixupArray->USN, Offset);
2548
2549 pShortToFixUp = (USHORT*)((PCHAR)Record + Offset);
2550 fixupArray->Array[i] = *pShortToFixUp;
2551 *pShortToFixUp = fixupArray->USN;
2552 Offset += Vcb->NtfsInfo.BytesPerSector;
2553 }
2554
2555 return STATUS_SUCCESS;
2556 }
2557
2558 NTSTATUS
2559 ReadLCN(PDEVICE_EXTENSION Vcb,
2560 ULONGLONG lcn,
2561 ULONG count,
2562 PVOID buffer)
2563 {
2564 LARGE_INTEGER DiskSector;
2565
2566 DiskSector.QuadPart = lcn;
2567
2568 return NtfsReadSectors(Vcb->StorageDevice,
2569 DiskSector.u.LowPart * Vcb->NtfsInfo.SectorsPerCluster,
2570 count * Vcb->NtfsInfo.SectorsPerCluster,
2571 Vcb->NtfsInfo.BytesPerSector,
2572 buffer,
2573 FALSE);
2574 }
2575
2576
2577 BOOLEAN
2578 CompareFileName(PUNICODE_STRING FileName,
2579 PINDEX_ENTRY_ATTRIBUTE IndexEntry,
2580 BOOLEAN DirSearch,
2581 BOOLEAN CaseSensitive)
2582 {
2583 BOOLEAN Ret, Alloc = FALSE;
2584 UNICODE_STRING EntryName;
2585
2586 EntryName.Buffer = IndexEntry->FileName.Name;
2587 EntryName.Length =
2588 EntryName.MaximumLength = IndexEntry->FileName.NameLength * sizeof(WCHAR);
2589
2590 if (DirSearch)
2591 {
2592 UNICODE_STRING IntFileName;
2593 if (!CaseSensitive)
2594 {
2595 NT_VERIFY(NT_SUCCESS(RtlUpcaseUnicodeString(&IntFileName, FileName, TRUE)));
2596 Alloc = TRUE;
2597 }
2598 else
2599 {
2600 IntFileName = *FileName;
2601 }
2602
2603 Ret = FsRtlIsNameInExpression(&IntFileName, &EntryName, !CaseSensitive, NULL);
2604
2605 if (Alloc)
2606 {
2607 RtlFreeUnicodeString(&IntFileName);
2608 }
2609
2610 return Ret;
2611 }
2612 else
2613 {
2614 return (RtlCompareUnicodeString(FileName, &EntryName, !CaseSensitive) == 0);
2615 }
2616 }
2617
2618 /**
2619 * @name UpdateMftMirror
2620 * @implemented
2621 *
2622 * Backs-up the first ~4 master file table entries to the $MFTMirr file.
2623 *
2624 * @param Vcb
2625 * Pointer to an NTFS_VCB for the volume whose Mft mirror is being updated.
2626 *
2627 * @returninja livecd
2628
2629 * STATUS_SUCCESS on success.
2630 * STATUS_INSUFFICIENT_RESOURCES if an allocation failed.
2631 * STATUS_UNSUCCESSFUL if we couldn't read the master file table.
2632 *
2633 * @remarks
2634 * NTFS maintains up-to-date copies of the first several mft entries in the $MFTMirr file. Usually, the first 4 file
2635 * records from the mft are stored. The exact number of entries is determined by the size of $MFTMirr's $DATA.
2636 * If $MFTMirr is not up-to-date, chkdsk will reject every change it can find prior to when $MFTMirr was last updated.
2637 * Therefore, it's recommended to call this function if the volume changes considerably. For instance, IncreaseMftSize()
2638 * relies on this function to keep chkdsk from deleting the mft entries it creates. Note that under most instances, creating
2639 * or deleting a file will not affect the first ~four mft entries, and so will not require updating the mft mirror.
2640 */
2641 NTSTATUS
2642 UpdateMftMirror(PNTFS_VCB Vcb)
2643 {
2644 PFILE_RECORD_HEADER MirrorFileRecord;
2645 PNTFS_ATTR_CONTEXT MirrDataContext;
2646 PNTFS_ATTR_CONTEXT MftDataContext;
2647 PCHAR DataBuffer;
2648 ULONGLONG DataLength;
2649 NTSTATUS Status;
2650 ULONG BytesRead;
2651 ULONG LengthWritten;
2652
2653 // Allocate memory for the Mft mirror file record
2654 MirrorFileRecord = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
2655 if (!MirrorFileRecord)
2656 {
2657 DPRINT1("Error: Failed to allocate memory for $MFTMirr!\n");
2658 return STATUS_INSUFFICIENT_RESOURCES;
2659 }
2660
2661 // Read the Mft Mirror file record
2662 Status = ReadFileRecord(Vcb, NTFS_FILE_MFTMIRR, MirrorFileRecord);
2663 if (!NT_SUCCESS(Status))
2664 {
2665 DPRINT1("ERROR: Failed to read $MFTMirr!\n");
2666 ExFreePoolWithTag(MirrorFileRecord, TAG_NTFS);
2667 return Status;
2668 }
2669
2670 // Find the $DATA attribute of $MFTMirr
2671 Status = FindAttribute(Vcb, MirrorFileRecord, AttributeData, L"", 0, &MirrDataContext, NULL);
2672 if (!NT_SUCCESS(Status))
2673 {
2674 DPRINT1("ERROR: Couldn't find $DATA attribute!\n");
2675 ExFreePoolWithTag(MirrorFileRecord, TAG_NTFS);
2676 return Status;
2677 }
2678
2679 // Find the $DATA attribute of $MFT
2680 Status = FindAttribute(Vcb, Vcb->MasterFileTable, AttributeData, L"", 0, &MftDataContext, NULL);
2681 if (!NT_SUCCESS(Status))
2682 {
2683 DPRINT1("ERROR: Couldn't find $DATA attribute!\n");
2684 ReleaseAttributeContext(MirrDataContext);
2685 ExFreePoolWithTag(MirrorFileRecord, TAG_NTFS);
2686 return Status;
2687 }
2688
2689 // Get the size of the mirror's $DATA attribute
2690 DataLength = AttributeDataLength(MirrDataContext->pRecord);
2691
2692 ASSERT(DataLength % Vcb->NtfsInfo.BytesPerFileRecord == 0);
2693
2694 // Create buffer for the mirror's $DATA attribute
2695 DataBuffer = ExAllocatePoolWithTag(NonPagedPool, DataLength, TAG_NTFS);
2696 if (!DataBuffer)
2697 {
2698 DPRINT1("Error: Couldn't allocate memory for $DATA buffer!\n");
2699 ReleaseAttributeContext(MftDataContext);
2700 ReleaseAttributeContext(MirrDataContext);
2701 ExFreePoolWithTag(MirrorFileRecord, TAG_NTFS);
2702 return STATUS_INSUFFICIENT_RESOURCES;
2703 }
2704
2705 ASSERT(DataLength < ULONG_MAX);
2706
2707 // Back up the first several entries of the Mft's $DATA Attribute
2708 BytesRead = ReadAttribute(Vcb, MftDataContext, 0, DataBuffer, (ULONG)DataLength);
2709 if (BytesRead != (ULONG)DataLength)
2710 {
2711 DPRINT1("Error: Failed to read $DATA for $MFTMirr!\n");
2712 ReleaseAttributeContext(MftDataContext);
2713 ReleaseAttributeContext(MirrDataContext);
2714 ExFreePoolWithTag(DataBuffer, TAG_NTFS);
2715 ExFreePoolWithTag(MirrorFileRecord, TAG_NTFS);
2716 return STATUS_UNSUCCESSFUL;
2717 }
2718
2719 // Write the mirror's $DATA attribute
2720 Status = WriteAttribute(Vcb,
2721 MirrDataContext,
2722 0,
2723 (PUCHAR)DataBuffer,
2724 DataLength,
2725 &LengthWritten,
2726 MirrorFileRecord);
2727 if (!NT_SUCCESS(Status))
2728 {
2729 DPRINT1("ERROR: Failed to write $DATA attribute of $MFTMirr!\n");
2730 }
2731
2732 // Cleanup
2733 ReleaseAttributeContext(MftDataContext);
2734 ReleaseAttributeContext(MirrDataContext);
2735 ExFreePoolWithTag(DataBuffer, TAG_NTFS);
2736 ExFreePoolWithTag(MirrorFileRecord, TAG_NTFS);
2737
2738 return Status;
2739 }
2740
2741 #if 0
2742 static
2743 VOID
2744 DumpIndexEntry(PINDEX_ENTRY_ATTRIBUTE IndexEntry)
2745 {
2746 DPRINT1("Entry: %p\n", IndexEntry);
2747 DPRINT1("\tData.Directory.IndexedFile: %I64x\n", IndexEntry->Data.Directory.IndexedFile);
2748 DPRINT1("\tLength: %u\n", IndexEntry->Length);
2749 DPRINT1("\tKeyLength: %u\n", IndexEntry->KeyLength);
2750 DPRINT1("\tFlags: %x\n", IndexEntry->Flags);
2751 DPRINT1("\tReserved: %x\n", IndexEntry->Reserved);
2752 DPRINT1("\t\tDirectoryFileReferenceNumber: %I64x\n", IndexEntry->FileName.DirectoryFileReferenceNumber);
2753 DPRINT1("\t\tCreationTime: %I64u\n", IndexEntry->FileName.CreationTime);
2754 DPRINT1("\t\tChangeTime: %I64u\n", IndexEntry->FileName.ChangeTime);
2755 DPRINT1("\t\tLastWriteTime: %I64u\n", IndexEntry->FileName.LastWriteTime);
2756 DPRINT1("\t\tLastAccessTime: %I64u\n", IndexEntry->FileName.LastAccessTime);
2757 DPRINT1("\t\tAllocatedSize: %I64u\n", IndexEntry->FileName.AllocatedSize);
2758 DPRINT1("\t\tDataSize: %I64u\n", IndexEntry->FileName.DataSize);
2759 DPRINT1("\t\tFileAttributes: %x\n", IndexEntry->FileName.FileAttributes);
2760 DPRINT1("\t\tNameLength: %u\n", IndexEntry->FileName.NameLength);
2761 DPRINT1("\t\tNameType: %x\n", IndexEntry->FileName.NameType);
2762 DPRINT1("\t\tName: %.*S\n", IndexEntry->FileName.NameLength, IndexEntry->FileName.Name);
2763 }
2764 #endif
2765
2766 NTSTATUS
2767 BrowseIndexEntries(PDEVICE_EXTENSION Vcb,
2768 PFILE_RECORD_HEADER MftRecord,
2769 PCHAR IndexRecord,
2770 ULONG IndexBlockSize,
2771 PINDEX_ENTRY_ATTRIBUTE FirstEntry,
2772 PINDEX_ENTRY_ATTRIBUTE LastEntry,
2773 PUNICODE_STRING FileName,
2774 PULONG StartEntry,
2775 PULONG CurrentEntry,
2776 BOOLEAN DirSearch,
2777 BOOLEAN CaseSensitive,
2778 ULONGLONG *OutMFTIndex)
2779 {
2780 NTSTATUS Status;
2781 ULONG RecordOffset;
2782 PINDEX_ENTRY_ATTRIBUTE IndexEntry;
2783 PNTFS_ATTR_CONTEXT IndexAllocationCtx;
2784 ULONGLONG IndexAllocationSize;
2785 PINDEX_BUFFER IndexBuffer;
2786
2787 DPRINT("BrowseIndexEntries(%p, %p, %p, %lu, %p, %p, %wZ, %lu, %lu, %s, %s, %p)\n",
2788 Vcb,
2789 MftRecord,
2790 IndexRecord,
2791 IndexBlockSize,
2792 FirstEntry,
2793 LastEntry,
2794 FileName,
2795 *StartEntry,
2796 *CurrentEntry,
2797 DirSearch ? "TRUE" : "FALSE",
2798 CaseSensitive ? "TRUE" : "FALSE",
2799 OutMFTIndex);
2800
2801 IndexEntry = FirstEntry;
2802 while (IndexEntry < LastEntry &&
2803 !(IndexEntry->Flags & NTFS_INDEX_ENTRY_END))
2804 {
2805 if ((IndexEntry->Data.Directory.IndexedFile & NTFS_MFT_MASK) >= NTFS_FILE_FIRST_USER_FILE &&
2806 *CurrentEntry >= *StartEntry &&
2807 IndexEntry->FileName.NameType != NTFS_FILE_NAME_DOS &&
2808 CompareFileName(FileName, IndexEntry, DirSearch, CaseSensitive))
2809 {
2810 *StartEntry = *CurrentEntry;
2811 *OutMFTIndex = (IndexEntry->Data.Directory.IndexedFile & NTFS_MFT_MASK);
2812 return STATUS_SUCCESS;
2813 }
2814
2815 (*CurrentEntry) += 1;
2816 ASSERT(IndexEntry->Length >= sizeof(INDEX_ENTRY_ATTRIBUTE));
2817 IndexEntry = (PINDEX_ENTRY_ATTRIBUTE)((PCHAR)IndexEntry + IndexEntry->Length);
2818 }
2819
2820 /* If we're already browsing a subnode */
2821 if (IndexRecord == NULL)
2822 {
2823 return STATUS_OBJECT_PATH_NOT_FOUND;
2824 }
2825
2826 /* If there's no subnode */
2827 if (!(IndexEntry->Flags & NTFS_INDEX_ENTRY_NODE))
2828 {
2829 return STATUS_OBJECT_PATH_NOT_FOUND;
2830 }
2831
2832 Status = FindAttribute(Vcb, MftRecord, AttributeIndexAllocation, L"$I30", 4, &IndexAllocationCtx, NULL);
2833 if (!NT_SUCCESS(Status))
2834 {
2835 DPRINT1("Corrupted filesystem!\n");
2836 return Status;
2837 }
2838
2839 IndexAllocationSize = AttributeDataLength(IndexAllocationCtx->pRecord);
2840 Status = STATUS_OBJECT_PATH_NOT_FOUND;
2841 for (RecordOffset = 0; RecordOffset < IndexAllocationSize; RecordOffset += IndexBlockSize)
2842 {
2843 ReadAttribute(Vcb, IndexAllocationCtx, RecordOffset, IndexRecord, IndexBlockSize);
2844 Status = FixupUpdateSequenceArray(Vcb, &((PFILE_RECORD_HEADER)IndexRecord)->Ntfs);
2845 if (!NT_SUCCESS(Status))
2846 {
2847 break;
2848 }
2849
2850 IndexBuffer = (PINDEX_BUFFER)IndexRecord;
2851 ASSERT(IndexBuffer->Ntfs.Type == NRH_INDX_TYPE);
2852 ASSERT(IndexBuffer->Header.AllocatedSize + FIELD_OFFSET(INDEX_BUFFER, Header) == IndexBlockSize);
2853 FirstEntry = (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)&IndexBuffer->Header + IndexBuffer->Header.FirstEntryOffset);
2854 LastEntry = (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)&IndexBuffer->Header + IndexBuffer->Header.TotalSizeOfEntries);
2855 ASSERT(LastEntry <= (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)IndexBuffer + IndexBlockSize));
2856
2857 Status = BrowseIndexEntries(NULL,
2858 NULL,
2859 NULL,
2860 0,
2861 FirstEntry,
2862 LastEntry,
2863 FileName,
2864 StartEntry,
2865 CurrentEntry,
2866 DirSearch,
2867 CaseSensitive,
2868 OutMFTIndex);
2869 if (NT_SUCCESS(Status))
2870 {
2871 break;
2872 }
2873 }
2874
2875 ReleaseAttributeContext(IndexAllocationCtx);
2876 return Status;
2877 }
2878
2879 NTSTATUS
2880 NtfsFindMftRecord(PDEVICE_EXTENSION Vcb,
2881 ULONGLONG MFTIndex,
2882 PUNICODE_STRING FileName,
2883 PULONG FirstEntry,
2884 BOOLEAN DirSearch,
2885 BOOLEAN CaseSensitive,
2886 ULONGLONG *OutMFTIndex)
2887 {
2888 PFILE_RECORD_HEADER MftRecord;
2889 PNTFS_ATTR_CONTEXT IndexRootCtx;
2890 PINDEX_ROOT_ATTRIBUTE IndexRoot;
2891 PCHAR IndexRecord;
2892 PINDEX_ENTRY_ATTRIBUTE IndexEntry, IndexEntryEnd;
2893 NTSTATUS Status;
2894 ULONG CurrentEntry = 0;
2895
2896 DPRINT("NtfsFindMftRecord(%p, %I64d, %wZ, %lu, %s, %s, %p)\n",
2897 Vcb,
2898 MFTIndex,
2899 FileName,
2900 *FirstEntry,
2901 DirSearch ? "TRUE" : "FALSE",
2902 CaseSensitive ? "TRUE" : "FALSE",
2903 OutMFTIndex);
2904
2905 MftRecord = ExAllocatePoolWithTag(NonPagedPool,
2906 Vcb->NtfsInfo.BytesPerFileRecord,
2907 TAG_NTFS);
2908 if (MftRecord == NULL)
2909 {
2910 return STATUS_INSUFFICIENT_RESOURCES;
2911 }
2912
2913 Status = ReadFileRecord(Vcb, MFTIndex, MftRecord);
2914 if (!NT_SUCCESS(Status))
2915 {
2916 ExFreePoolWithTag(MftRecord, TAG_NTFS);
2917 return Status;
2918 }
2919
2920 ASSERT(MftRecord->Ntfs.Type == NRH_FILE_TYPE);
2921 Status = FindAttribute(Vcb, MftRecord, AttributeIndexRoot, L"$I30", 4, &IndexRootCtx, NULL);
2922 if (!NT_SUCCESS(Status))
2923 {
2924 ExFreePoolWithTag(MftRecord, TAG_NTFS);
2925 return Status;
2926 }
2927
2928 IndexRecord = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerIndexRecord, TAG_NTFS);
2929 if (IndexRecord == NULL)
2930 {
2931 ReleaseAttributeContext(IndexRootCtx);
2932 ExFreePoolWithTag(MftRecord, TAG_NTFS);
2933 return STATUS_INSUFFICIENT_RESOURCES;
2934 }
2935
2936 ReadAttribute(Vcb, IndexRootCtx, 0, IndexRecord, Vcb->NtfsInfo.BytesPerIndexRecord);
2937 IndexRoot = (PINDEX_ROOT_ATTRIBUTE)IndexRecord;
2938 IndexEntry = (PINDEX_ENTRY_ATTRIBUTE)((PCHAR)&IndexRoot->Header + IndexRoot->Header.FirstEntryOffset);
2939 /* Index root is always resident. */
2940 IndexEntryEnd = (PINDEX_ENTRY_ATTRIBUTE)(IndexRecord + IndexRoot->Header.TotalSizeOfEntries);
2941 ReleaseAttributeContext(IndexRootCtx);
2942
2943 DPRINT("IndexRecordSize: %x IndexBlockSize: %x\n", Vcb->NtfsInfo.BytesPerIndexRecord, IndexRoot->SizeOfEntry);
2944
2945 Status = BrowseIndexEntries(Vcb,
2946 MftRecord,
2947 IndexRecord,
2948 IndexRoot->SizeOfEntry,
2949 IndexEntry,
2950 IndexEntryEnd,
2951 FileName,
2952 FirstEntry,
2953 &CurrentEntry,
2954 DirSearch,
2955 CaseSensitive,
2956 OutMFTIndex);
2957
2958 ExFreePoolWithTag(IndexRecord, TAG_NTFS);
2959 ExFreePoolWithTag(MftRecord, TAG_NTFS);
2960
2961 return Status;
2962 }
2963
2964 NTSTATUS
2965 NtfsLookupFileAt(PDEVICE_EXTENSION Vcb,
2966 PUNICODE_STRING PathName,
2967 BOOLEAN CaseSensitive,
2968 PFILE_RECORD_HEADER *FileRecord,
2969 PULONGLONG MFTIndex,
2970 ULONGLONG CurrentMFTIndex)
2971 {
2972 UNICODE_STRING Current, Remaining;
2973 NTSTATUS Status;
2974 ULONG FirstEntry = 0;
2975
2976 DPRINT("NtfsLookupFileAt(%p, %wZ, %s, %p, %p, %I64x)\n",
2977 Vcb,
2978 PathName,
2979 CaseSensitive ? "TRUE" : "FALSE",
2980 FileRecord,
2981 MFTIndex,
2982 CurrentMFTIndex);
2983
2984 FsRtlDissectName(*PathName, &Current, &Remaining);
2985
2986 while (Current.Length != 0)
2987 {
2988 DPRINT("Current: %wZ\n", &Current);
2989
2990 Status = NtfsFindMftRecord(Vcb, CurrentMFTIndex, &Current, &FirstEntry, FALSE, CaseSensitive, &CurrentMFTIndex);
2991 if (!NT_SUCCESS(Status))
2992 {
2993 return Status;
2994 }
2995
2996 if (Remaining.Length == 0)
2997 break;
2998
2999 FsRtlDissectName(Current, &Current, &Remaining);
3000 }
3001
3002 *FileRecord = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
3003 if (*FileRecord == NULL)
3004 {
3005 DPRINT("NtfsLookupFileAt: Can't allocate MFT record\n");
3006 return STATUS_INSUFFICIENT_RESOURCES;
3007 }
3008
3009 Status = ReadFileRecord(Vcb, CurrentMFTIndex, *FileRecord);
3010 if (!NT_SUCCESS(Status))
3011 {
3012 DPRINT("NtfsLookupFileAt: Can't read MFT record\n");
3013 ExFreePoolWithTag(*FileRecord, TAG_NTFS);
3014 return Status;
3015 }
3016
3017 *MFTIndex = CurrentMFTIndex;
3018
3019 return STATUS_SUCCESS;
3020 }
3021
3022 NTSTATUS
3023 NtfsLookupFile(PDEVICE_EXTENSION Vcb,
3024 PUNICODE_STRING PathName,
3025 BOOLEAN CaseSensitive,
3026 PFILE_RECORD_HEADER *FileRecord,
3027 PULONGLONG MFTIndex)
3028 {
3029 return NtfsLookupFileAt(Vcb, PathName, CaseSensitive, FileRecord, MFTIndex, NTFS_FILE_ROOT);
3030 }
3031
3032 /**
3033 * @name NtfsDumpFileRecord
3034 * @implemented
3035 *
3036 * Provides diagnostic information about a file record. Prints a hex dump
3037 * of the entire record (based on the size reported by FileRecord->ByesInUse),
3038 * then prints a dump of each attribute.
3039 *
3040 * @param Vcb
3041 * Pointer to a DEVICE_EXTENSION describing the volume.
3042 *
3043 * @param FileRecord
3044 * Pointer to the file record to be analyzed.
3045 *
3046 * @remarks
3047 * FileRecord must be a complete file record at least FileRecord->BytesAllocated
3048 * in size, and not just the header.
3049 *
3050 */
3051 VOID
3052 NtfsDumpFileRecord(PDEVICE_EXTENSION Vcb,
3053 PFILE_RECORD_HEADER FileRecord)
3054 {
3055 ULONG i, j;
3056
3057 // dump binary data, 8 bytes at a time
3058 for (i = 0; i < FileRecord->BytesInUse; i += 8)
3059 {
3060 // display current offset, in hex
3061 DbgPrint("\t%03x\t", i);
3062
3063 // display hex value of each of the next 8 bytes
3064 for (j = 0; j < 8; j++)
3065 DbgPrint("%02x ", *(PUCHAR)((ULONG_PTR)FileRecord + i + j));
3066 DbgPrint("\n");
3067 }
3068
3069 NtfsDumpFileAttributes(Vcb, FileRecord);
3070 }
3071
3072 NTSTATUS
3073 NtfsFindFileAt(PDEVICE_EXTENSION Vcb,
3074 PUNICODE_STRING SearchPattern,
3075 PULONG FirstEntry,
3076 PFILE_RECORD_HEADER *FileRecord,
3077 PULONGLONG MFTIndex,
3078 ULONGLONG CurrentMFTIndex,
3079 BOOLEAN CaseSensitive)
3080 {
3081 NTSTATUS Status;
3082
3083 DPRINT("NtfsFindFileAt(%p, %wZ, %lu, %p, %p, %I64x, %s)\n",
3084 Vcb,
3085 SearchPattern,
3086 *FirstEntry,
3087 FileRecord,
3088 MFTIndex,
3089 CurrentMFTIndex,
3090 (CaseSensitive ? "TRUE" : "FALSE"));
3091
3092 Status = NtfsFindMftRecord(Vcb, CurrentMFTIndex, SearchPattern, FirstEntry, TRUE, CaseSensitive, &CurrentMFTIndex);
3093 if (!NT_SUCCESS(Status))
3094 {
3095 DPRINT("NtfsFindFileAt: NtfsFindMftRecord() failed with status 0x%08lx\n", Status);
3096 return Status;
3097 }
3098
3099 *FileRecord = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
3100 if (*FileRecord == NULL)
3101 {
3102 DPRINT("NtfsFindFileAt: Can't allocate MFT record\n");
3103 return STATUS_INSUFFICIENT_RESOURCES;
3104 }
3105
3106 Status = ReadFileRecord(Vcb, CurrentMFTIndex, *FileRecord);
3107 if (!NT_SUCCESS(Status))
3108 {
3109 DPRINT("NtfsFindFileAt: Can't read MFT record\n");
3110 ExFreePoolWithTag(*FileRecord, TAG_NTFS);
3111 return Status;
3112 }
3113
3114 *MFTIndex = CurrentMFTIndex;
3115
3116 return STATUS_SUCCESS;
3117 }
3118
3119 /* EOF */