[NTFS]
[reactos.git] / drivers / filesystems / ntfs / mft.c
index 5d61f53..f3ac318 100644 (file)
@@ -135,6 +135,8 @@ FindAttribute(PDEVICE_EXTENSION Vcb,
                 DPRINT("Found context\n");
                 *AttrCtx = PrepareAttributeContext(Attribute);
 
+                (*AttrCtx)->FileMFTIndex = MftRecord->MFTRecordNumber;
+
                 if (Offset != NULL)
                     *Offset = Context.Offset;
 
@@ -151,7 +153,7 @@ FindAttribute(PDEVICE_EXTENSION Vcb,
 }
 
 
-ULONG
+ULONGLONG
 AttributeAllocatedLength(PNTFS_ATTR_RECORD AttrRecord)
 {
     if (AttrRecord->IsNonResident)
@@ -170,57 +172,188 @@ AttributeDataLength(PNTFS_ATTR_RECORD AttrRecord)
         return AttrRecord->Resident.ValueLength;
 }
 
+void
+InternalSetResidentAttributeLength(PNTFS_ATTR_CONTEXT AttrContext,
+                                   PFILE_RECORD_HEADER FileRecord,
+                                   ULONG AttrOffset,
+                                   ULONG DataSize)
+{
+    PNTFS_ATTR_RECORD Destination = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
+    ULONG NextAttributeOffset;
+
+    DPRINT("InternalSetResidentAttributeLength( %p, %p, %lu, %lu )\n", AttrContext, FileRecord, AttrOffset, DataSize);
+
+    // update ValueLength Field
+    AttrContext->Record.Resident.ValueLength =
+    Destination->Resident.ValueLength = DataSize;
+
+    // calculate the record length and end marker offset
+    AttrContext->Record.Length =
+    Destination->Length = DataSize + AttrContext->Record.Resident.ValueOffset;
+    NextAttributeOffset = AttrOffset + AttrContext->Record.Length;
+
+    // Ensure NextAttributeOffset is aligned to an 8-byte boundary
+    if (NextAttributeOffset % 8 != 0)
+    {
+        USHORT Padding = 8 - (NextAttributeOffset % 8);
+        NextAttributeOffset += Padding;
+        AttrContext->Record.Length += Padding;
+        Destination->Length += Padding;
+    }
+    
+    // advance Destination to the final "attribute" and write the end type
+    Destination = (PNTFS_ATTR_RECORD)((ULONG_PTR)Destination + Destination->Length);
+    Destination->Type = AttributeEnd;
+
+    // write the final marker (which shares the same offset and type as the Length field)
+    Destination->Length = FILE_RECORD_END;
+
+    FileRecord->BytesInUse = NextAttributeOffset + (sizeof(ULONG) * 2);
+}
 
+/**
+*   @parameter FileRecord
+*   Pointer to a file record. Must be a full record at least 
+*   Fcb->Vcb->NtfsInfo.BytesPerFileRecord bytes large, not just the header.
+*/
 NTSTATUS
 SetAttributeDataLength(PFILE_OBJECT FileObject,
                        PNTFS_FCB Fcb,
                        PNTFS_ATTR_CONTEXT AttrContext,
                        ULONG AttrOffset,
                        PFILE_RECORD_HEADER FileRecord,
-                       PDEVICE_EXTENSION DeviceExt,
                        PLARGE_INTEGER DataSize)
 {
+    NTSTATUS Status = STATUS_SUCCESS;
+    ULONG BytesPerCluster = Fcb->Vcb->NtfsInfo.BytesPerCluster;
+
+    // are we truncating the file?
+    if (DataSize->QuadPart < AttributeDataLength(&AttrContext->Record))
+    {
+        if (!MmCanFileBeTruncated(FileObject->SectionObjectPointer, DataSize))
+        {
+            DPRINT1("Can't truncate a memory-mapped file!\n");
+            return STATUS_USER_MAPPED_FILE;
+        }
+    }
+
     if (AttrContext->Record.IsNonResident)
     {
+        ULONGLONG AllocationSize = ROUND_UP(DataSize->QuadPart, BytesPerCluster);
+        PNTFS_ATTR_RECORD DestinationAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
+        ULONG ExistingClusters = AttrContext->Record.NonResident.AllocatedSize / BytesPerCluster;
+
         // do we need to increase the allocation size?
-        if (AttrContext->Record.NonResident.AllocatedSize < DataSize->QuadPart)
-        {            
-            DPRINT1("FixMe: Increasing allocation size is unimplemented!\n");
-            return STATUS_NOT_IMPLEMENTED;
+        if (AttrContext->Record.NonResident.AllocatedSize < AllocationSize)
+        {              
+            ULONG ClustersNeeded = (AllocationSize / BytesPerCluster) - ExistingClusters;
+            LARGE_INTEGER LastClusterInDataRun;
+            ULONG NextAssignedCluster;
+            ULONG AssignedClusters;
+
+            NTSTATUS Status = GetLastClusterInDataRun(Fcb->Vcb, &AttrContext->Record, (PULONGLONG)&LastClusterInDataRun.QuadPart);
+
+            DPRINT1("GetLastClusterInDataRun returned: %I64u\n", LastClusterInDataRun.QuadPart);
+            DPRINT1("Highest VCN of record: %I64u\n", AttrContext->Record.NonResident.HighestVCN);
+
+            while (ClustersNeeded > 0)
+            {
+                Status = NtfsAllocateClusters(Fcb->Vcb,
+                                              LastClusterInDataRun.LowPart + 1,
+                                              ClustersNeeded,
+                                              &NextAssignedCluster,
+                                              &AssignedClusters);
+                
+                if (!NT_SUCCESS(Status))
+                {
+                    DPRINT1("Error: Unable to allocate requested clusters!\n");
+                    return Status;
+                }
+
+                // now we need to add the clusters we allocated to the data run
+                Status = AddRun(Fcb->Vcb, AttrContext, AttrOffset, FileRecord, NextAssignedCluster, AssignedClusters);
+                if (!NT_SUCCESS(Status))
+                {
+                    DPRINT1("Error: Unable to add data run!\n");
+                    return Status;
+                }
+
+                ClustersNeeded -= AssignedClusters;
+                LastClusterInDataRun.LowPart = NextAssignedCluster + AssignedClusters - 1;
+            }
+        }
+        else if (AttrContext->Record.NonResident.AllocatedSize > AllocationSize)
+        {
+            // shrink allocation size
+            ULONG ClustersToFree = ExistingClusters - (AllocationSize / BytesPerCluster);
+            Status = FreeClusters(Fcb->Vcb, AttrContext, AttrOffset, FileRecord, ClustersToFree);
         }
 
         // TODO: is the file compressed, encrypted, or sparse?
 
         // NOTE: we need to have acquired the main resource exclusively, as well as(?) the PagingIoResource
 
-        // TODO: update the allocated size on-disk
-        DPRINT("Allocated Size: %I64u\n", AttrContext->Record.NonResident.AllocatedSize);
-
+        Fcb->RFCB.AllocationSize.QuadPart = AllocationSize;
+        AttrContext->Record.NonResident.AllocatedSize = AllocationSize;
         AttrContext->Record.NonResident.DataSize = DataSize->QuadPart;
         AttrContext->Record.NonResident.InitializedSize = DataSize->QuadPart;
 
-        Fcb->RFCB.FileSize = *DataSize;
-        Fcb->RFCB.ValidDataLength = *DataSize;
-
-        DPRINT("Data Size: %I64u\n", Fcb->RFCB.FileSize.QuadPart);
+        DestinationAttribute->NonResident.AllocatedSize = AllocationSize;
+        DestinationAttribute->NonResident.DataSize = DataSize->QuadPart;
+        DestinationAttribute->NonResident.InitializedSize = DataSize->QuadPart;
 
-        //NtfsDumpFileAttributes(Fcb->Vcb, FileRecord);
+        DPRINT("Allocated Size: %I64u\n", DestinationAttribute->NonResident.AllocatedSize);
+    }
+    else
+    {
+        // resident attribute
 
-        // copy the attribute back into the FileRecord
-        RtlCopyMemory((PCHAR)FileRecord + AttrOffset, &AttrContext->Record, AttrContext->Record.Length);
+        // find the next attribute
+        ULONG NextAttributeOffset = AttrOffset + AttrContext->Record.Length;
+        PNTFS_ATTR_RECORD NextAttribute = (PNTFS_ATTR_RECORD)((PCHAR)FileRecord + NextAttributeOffset);
 
         //NtfsDumpFileAttributes(Fcb->Vcb, FileRecord);
 
-        // write the updated file record back to disk
-        UpdateFileRecord(Fcb->Vcb, Fcb->MFTIndex, FileRecord);
+        // Do we need to increase the data length?
+        if (DataSize->QuadPart > AttrContext->Record.Resident.ValueLength)
+        {
+            // There's usually padding at the end of a record. Do we need to extend past it?
+            ULONG MaxValueLength = AttrContext->Record.Length - AttrContext->Record.Resident.ValueOffset;
+            if (MaxValueLength < DataSize->LowPart)
+            {
+                // If this is the last attribute, we could move the end marker to the very end of the file record
+                MaxValueLength += Fcb->Vcb->NtfsInfo.BytesPerFileRecord - NextAttributeOffset - (sizeof(ULONG) * 2);
 
-        CcSetFileSizes(FileObject, (PCC_FILE_SIZES)&Fcb->RFCB.AllocationSize);
+                if (MaxValueLength < DataSize->LowPart || NextAttribute->Type != AttributeEnd)
+                {
+                    DPRINT1("FIXME: Need to convert attribute to non-resident!\n");
+                    return STATUS_NOT_IMPLEMENTED;
+                }
+            }
+        }
+        else if (DataSize->LowPart < AttrContext->Record.Resident.ValueLength)
+        {
+            // we need to decrease the length
+            if (NextAttribute->Type != AttributeEnd)
+            {
+                DPRINT1("FIXME: Don't know how to decrease length of resident attribute unless it's the final attribute!\n");
+                return STATUS_NOT_IMPLEMENTED;
+            }
+        }
+
+        InternalSetResidentAttributeLength(AttrContext, FileRecord, AttrOffset, DataSize->LowPart);
     }
-    else
+
+    //NtfsDumpFileAttributes(Fcb->Vcb, FileRecord);
+
+    // write the updated file record back to disk
+    Status = UpdateFileRecord(Fcb->Vcb, Fcb->MFTIndex, FileRecord);
+
+    if (NT_SUCCESS(Status))
     {
-        // we can't yet handle resident attributes
-        DPRINT1("FixMe: Can't handle increasing length of resident attribute\n");
-        return STATUS_NOT_IMPLEMENTED;
+        Fcb->RFCB.FileSize = *DataSize;
+        Fcb->RFCB.ValidDataLength = *DataSize;
+        CcSetFileSizes(FileObject, (PCC_FILE_SIZES)&Fcb->RFCB.AllocationSize);
     }
 
     return STATUS_SUCCESS;
@@ -460,31 +593,78 @@ WriteAttribute(PDEVICE_EXTENSION Vcb,
     PUCHAR SourceBuffer = Buffer;
     LONGLONG StartingOffset;
 
-    DPRINT("WriteAttribute(%p, %p, %I64U, %p, %lu)\n", Vcb, Context, Offset, Buffer, Length);
+    DPRINT("WriteAttribute(%p, %p, %I64u, %p, %lu, %p)\n", Vcb, Context, Offset, Buffer, Length, RealLengthWritten);
+
+    *RealLengthWritten = 0;
 
     // is this a resident attribute?
     if (!Context->Record.IsNonResident)
     {
-        DPRINT1("FIXME: Writing to resident NTFS records (small files) is not supported at this time.\n");
-        // (TODO: This should be really easy to implement)
+        ULONG AttributeOffset;
+        PNTFS_ATTR_CONTEXT FoundContext;
+        PFILE_RECORD_HEADER FileRecord;
 
-        /* LeftOver code from ReadAttribute(), may be helpful:
-        if (Offset > Context->Record.Resident.ValueLength)
-        return 0;
         if (Offset + Length > Context->Record.Resident.ValueLength)
-        Length = (ULONG)(Context->Record.Resident.ValueLength - Offset);
-        RtlCopyMemory(Buffer, (PCHAR)&Context->Record + Context->Record.Resident.ValueOffset + Offset, Length);
-        return Length;*/
+        {
+            DPRINT1("DRIVER ERROR: Attribute is too small!\n");
+            return STATUS_INVALID_PARAMETER;
+        }
+
+        FileRecord = ExAllocatePoolWithTag(NonPagedPool, Vcb->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
 
-        return STATUS_NOT_IMPLEMENTED; // until we implement it
+        if (!FileRecord)
+        {
+            DPRINT1("Error: Couldn't allocate file record!\n");
+            return STATUS_NO_MEMORY;
+        }
+
+        // read the file record
+        ReadFileRecord(Vcb, Context->FileMFTIndex, FileRecord);
+
+        // find where to write the attribute data to
+        Status = FindAttribute(Vcb, FileRecord,
+                               Context->Record.Type,
+                               (PCWSTR)((PCHAR)&Context->Record + Context->Record.NameOffset),
+                               Context->Record.NameLength,
+                               &FoundContext,
+                               &AttributeOffset);
+
+        if (!NT_SUCCESS(Status))
+        {
+            DPRINT1("ERROR: Couldn't find matching attribute!\n");
+            ExFreePoolWithTag(FileRecord, TAG_NTFS);
+            return Status;
+        }
+
+        DPRINT("Offset: %I64u, AttributeOffset: %u, ValueOffset: %u\n", Offset, AttributeOffset, Context->Record.Resident.ValueLength);
+        Offset += AttributeOffset + Context->Record.Resident.ValueOffset;
+        
+        if (Offset + Length > Vcb->NtfsInfo.BytesPerFileRecord)
+        {
+            DPRINT1("DRIVER ERROR: Data being written extends past end of file record!\n");
+            ReleaseAttributeContext(FoundContext);
+            ExFreePoolWithTag(FileRecord, TAG_NTFS);
+            return STATUS_INVALID_PARAMETER;
+        }
+
+        // copy the data being written into the file record
+        RtlCopyMemory((PCHAR)FileRecord + Offset, Buffer, Length);
+
+        Status = UpdateFileRecord(Vcb, Context->FileMFTIndex, FileRecord);
+
+        ReleaseAttributeContext(FoundContext);
+        ExFreePoolWithTag(FileRecord, TAG_NTFS);
+
+        if (NT_SUCCESS(Status))
+            *RealLengthWritten = Length;
+
+        return Status;
     }
 
     // This is a non-resident attribute.
 
     // I. Find the corresponding start data run.       
 
-    *RealLengthWritten = 0;
-
     // FIXME: Cache seems to be non-working. Disable it for now
     //if(Context->CacheRunOffset <= Offset && Offset < Context->CacheRunOffset + Context->CacheRunLength * Volume->ClusterSize)
     /*if (0)
@@ -679,6 +859,7 @@ ReadFileRecord(PDEVICE_EXTENSION Vcb,
     }
 
     /* Apply update sequence array fixups. */
+    DPRINT("Sequence number: %u\n", file->SequenceNumber);
     return FixupUpdateSequenceArray(Vcb, &file->Ntfs);
 }
 
@@ -909,13 +1090,14 @@ UpdateFileRecord(PDEVICE_EXTENSION Vcb,
     // write the file record to the master file table
     Status = WriteAttribute(Vcb, Vcb->MFTContext, index * Vcb->NtfsInfo.BytesPerFileRecord, (const PUCHAR)file, Vcb->NtfsInfo.BytesPerFileRecord, &BytesWritten);
 
-    // TODO: Update MFT mirror
-
     if (!NT_SUCCESS(Status))
     {
-        DPRINT1("UpdateFileRecord failed: %I64u written, %u expected\n", BytesWritten, Vcb->NtfsInfo.BytesPerFileRecord);
+        DPRINT1("UpdateFileRecord failed: %I64u written, %lu expected\n", BytesWritten, Vcb->NtfsInfo.BytesPerFileRecord);
     }
 
+    // remove the fixup array (so the file record pointer can still be used)
+    FixupUpdateSequenceArray(Vcb, &file->Ntfs);
+
     return Status;
 }