3 * By John Hodge (thePowersGang)
8 * Reference: ntfsdoc.pdf
19 int NTFS_Install(char **Arguments);
20 int NTFS_Detect(int FD);
21 tVFS_Node *NTFS_InitDevice(const char *Devices, const char **Options);
22 void NTFS_Unmount(tVFS_Node *Node);
23 // - MFT Related Functions
24 tNTFS_FILE_Header *NTFS_GetMFT(tNTFS_Disk *Disk, Uint32 MFTEntry);
25 void NTFS_ReleaseMFT(tNTFS_Disk *Disk, Uint32 MFTEntry, tNTFS_FILE_Header *Entry);
26 tNTFS_Attrib *NTFS_GetAttrib(tNTFS_Disk *Disk, Uint32 MFTEntry, int Type, const char *Name, int DesIdx);
27 size_t NTFS_ReadAttribData(tNTFS_Attrib *Attrib, Uint64 Offset, size_t Length, void *Buffer);
28 void NTFS_DumpEntry(tNTFS_Disk *Disk, Uint32 Entry);
31 MODULE_DEFINE(0, 0x0A /*v0.1*/, FS_NTFS, NTFS_Install, NULL);
32 tVFS_Driver gNTFS_FSInfo = {
34 .Detect = NTFS_Detect,
35 .InitDevice = NTFS_InitDevice,
36 .Unmount = NTFS_Unmount,
37 .GetNodeFromINode = NULL
39 tVFS_NodeType gNTFS_DirType = {
40 .TypeName = "NTFS-Dir",
41 .ReadDir = NTFS_ReadDir,
42 .FindDir = NTFS_FindDir,
45 tVFS_NodeType gNTFS_FileType = {
46 .TypeName = "NTFS-File",
47 .Read = NTFS_ReadFile,
51 tNTFS_Disk gNTFS_Disks;
55 * \brief Installs the NTFS driver
57 int NTFS_Install(char **Arguments)
59 VFS_AddDriver( &gNTFS_FSInfo );
64 * \brief Detect if a volume is NTFS
66 int NTFS_Detect(int FD)
69 VFS_ReadAt(FD, 0, 512, &bs);
71 if( bs.BytesPerSector == 0 || (bs.BytesPerSector & 511) )
74 Uint64 ncluster = bs.TotalSectorCount / bs.SectorsPerCluster;
75 if( bs.MFTStart >= ncluster || bs.MFTMirrorStart >= ncluster )
78 if( memcmp(bs.SystemID, "NTFS ", 8) != 0 )
85 * \brief Mount a NTFS volume
87 tVFS_Node *NTFS_InitDevice(const char *Device, const char **Options)
92 disk = calloc( sizeof(tNTFS_Disk), 1 );
94 disk->FD = VFS_Open(Device, VFS_OPENFLAG_READ);
100 VFS_ReadAt(disk->FD, 0, 512, &bs);
103 Log_Debug("FS_NTFS", "Jump = %02x%02x%02x",
107 Log_Debug("FS_NTFS", "SystemID = %02x%02x%02x%02x%02x%02x%02x%02x (%8C)",
108 bs.SystemID[0], bs.SystemID[1], bs.SystemID[2], bs.SystemID[3],
109 bs.SystemID[4], bs.SystemID[5], bs.SystemID[6], bs.SystemID[7],
112 Log_Debug("FS_NTFS", "BytesPerSector = %i", bs.BytesPerSector);
113 Log_Debug("FS_NTFS", "SectorsPerCluster = %i", bs.SectorsPerCluster);
114 Log_Debug("FS_NTFS", "MediaDescriptor = 0x%x", bs.MediaDescriptor);
115 Log_Debug("FS_NTFS", "SectorsPerTrack = %i", bs.SectorsPerTrack);
116 Log_Debug("FS_NTFS", "Heads = %i", bs.Heads);
117 Log_Debug("FS_NTFS", "TotalSectorCount = 0x%llx", bs.TotalSectorCount);
118 Log_Debug("FS_NTFS", "MFTStart = 0x%llx", bs.MFTStart);
119 Log_Debug("FS_NTFS", "MFTMirrorStart = 0x%llx", bs.MFTMirrorStart);
120 Log_Debug("FS_NTFS", "ClustersPerMFTRecord = %i", bs.ClustersPerMFTRecord);
121 Log_Debug("FS_NTFS", "ClustersPerIndexRecord = %i", bs.ClustersPerIndexRecord);
122 Log_Debug("FS_NTFS", "SerialNumber = 0x%llx", bs.SerialNumber);
125 disk->ClusterSize = bs.BytesPerSector * bs.SectorsPerCluster;
126 disk->MFTBase = bs.MFTStart;
127 Log_Debug("NTFS", "Cluster Size = %i KiB", disk->ClusterSize/1024);
128 Log_Debug("NTFS", "MFT Base = %i", disk->MFTBase);
129 Log_Debug("NTFS", "TotalSectorCount = 0x%x", bs.TotalSectorCount);
131 if( bs.ClustersPerMFTRecord < 0 ) {
132 disk->MFTRecSize = 1 << (-bs.ClustersPerMFTRecord);
135 disk->MFTRecSize = bs.ClustersPerMFTRecord * disk->ClusterSize;
137 //NTFS_DumpEntry(disk, 0); // $MFT
138 //NTFS_DumpEntry(disk, 3); // $VOLUME
140 disk->InodeCache = Inode_GetHandle(NTFS_FreeNode);
142 disk->MFTDataAttr = NULL;
143 disk->MFTDataAttr = NTFS_GetAttrib(disk, 0, NTFS_FileAttrib_Data, "", 0);
144 //NTFS_DumpEntry(disk, 5); // .
146 disk->RootDir.I30Root = NTFS_GetAttrib(disk, 5, NTFS_FileAttrib_IndexRoot, "$I30", 0);
147 disk->RootDir.I30Allocation = NTFS_GetAttrib(disk, 5, NTFS_FileAttrib_IndexAllocation, "$I30", 0);
148 disk->RootDir.Node.Inode = 5; // MFT Ent #5 is filesystem root
149 disk->RootDir.Node.ImplPtr = disk;
150 disk->RootDir.Node.Type = &gNTFS_DirType;
151 disk->RootDir.Node.Flags = VFS_FFLAG_DIRECTORY;
153 disk->RootDir.Node.UID = 0;
154 disk->RootDir.Node.GID = 0;
156 disk->RootDir.Node.NumACLs = 1;
157 disk->RootDir.Node.ACLs = &gVFS_ACL_EveryoneRX;
161 // Read from allocation
162 char buf[disk->ClusterSize];
163 size_t len = NTFS_ReadAttribData(disk->RootDir.I30Allocation, 0, sizeof(buf), buf);
164 Debug_HexDump("RootDir allocation", buf, len);
168 return &disk->RootDir.Node;
172 * \brief Unmount an NTFS Disk
174 void NTFS_Unmount(tVFS_Node *Node)
176 tNTFS_Disk *Disk = Node->ImplPtr;
181 void NTFS_Close(tVFS_Node *Node)
183 tNTFS_Disk *Disk = Node->ImplPtr;
184 Inode_UncacheNode(Disk->InodeCache, Node->Inode);
187 void NTFS_FreeNode(tVFS_Node *Node)
189 if( Node->Type == &gNTFS_DirType ) {
190 tNTFS_Directory *Dir = (void*)Node;
191 NTFS_FreeAttrib(Dir->I30Root);
192 NTFS_FreeAttrib(Dir->I30Allocation);
195 tNTFS_File *File = (void*)Node;
196 NTFS_FreeAttrib(File->Data);
200 int NTFS_int_ApplyUpdateSequence(void *Buffer, size_t BufLen, const Uint16 *Sequence, size_t NumEntries)
202 Uint16 cksum = Sequence[0];
203 LOG("cksum = %04x", cksum);
205 Uint16 *buf16 = Buffer;
206 for( int i = 0; i < NumEntries-1; i ++ )
208 size_t ofs = (i+1)*512 - 2;
209 if( ofs + 2 > BufLen ) {
211 Log_Warning("NTFS", "%x > %x", ofs+2, BufLen);
213 Uint16 *cksum_word = &buf16[ofs/2];
214 LOG("[%i]: %04x => %04x", i, Sequence[i], *cksum_word);
215 if( *cksum_word != cksum ) {
216 Log_Warning("NTFS", "Disk corruption detected");
219 *cksum_word = Sequence[i];
224 tNTFS_FILE_Header *NTFS_GetMFT(tNTFS_Disk *Disk, Uint32 MFTEntry)
226 // TODO: Cache MFT allocation for short-term
229 tNTFS_FILE_Header *ret = malloc( Disk->MFTRecSize );
231 Log_Warning("FS_NTFS", "malloc() fail!");
235 // NOTE: The MFT is a file, and can get fragmented
236 if( !Disk->MFTDataAttr ) {
237 VFS_ReadAt( Disk->FD,
238 Disk->MFTBase * Disk->ClusterSize + MFTEntry * Disk->MFTRecSize,
243 NTFS_ReadAttribData(Disk->MFTDataAttr, MFTEntry * Disk->MFTRecSize, Disk->MFTRecSize, ret);
246 NTFS_int_ApplyUpdateSequence(ret, Disk->MFTRecSize,
247 (void*)((char*)ret + ret->UpdateSequenceOfs), ret->UpdateSequenceSize
253 void NTFS_ReleaseMFT(tNTFS_Disk *Disk, Uint32 MFTEntry, tNTFS_FILE_Header *Entry)
258 static inline Uint64 _getVariableLengthInt(const void *Ptr, int Length, int bExtend)
260 const Uint8 *data = Ptr;
262 for( int i = 0; i < Length; i ++ )
263 bits |= (Uint64)data[i] << (i*8);
264 if( bExtend && Length && data[Length-1] & 0x80 ) {
265 for( int i = Length; i < 8; i ++ )
266 bits |= 0xFF << (i*8);
271 const void *_GetDataRun(const void *ptr, const void *limit, Uint64 LastLCN, Uint64 *Count, Uint64 *LCN)
275 LOG("Clean end of list");
279 const Uint8 *data = ptr;
282 Uint8 ofsSize = data[0] >> 4;
283 Uint8 lenSize = data[0] & 0xF;
284 LOG("ofsSize = %i, lenSize = %i", ofsSize, lenSize);
287 if( lenSize > 8 || lenSize < 1 )
289 if( data + 1 + ofsSize + lenSize > (const Uint8*)limit )
293 *Count = _getVariableLengthInt(data + 1, lenSize, 0);
296 *LCN = LastLCN + (Sint64)_getVariableLengthInt(data + 1 + lenSize, ofsSize, 1);
299 return data + 1 + ofsSize + lenSize;
302 tNTFS_Attrib *NTFS_GetAttrib(tNTFS_Disk *Disk, Uint32 MFTEntry, int Type, const char *Name, int DesIdx)
304 ENTER("pDisk xMFTEntry xType sName iDesIdx",
305 Disk, MFTEntry, Type, Name, DesIdx);
307 // TODO: Scan cache of attributes
310 tNTFS_FILE_Header *hdr = NTFS_GetMFT(Disk, MFTEntry);
311 LOG("hdr = %p", hdr);
313 tNTFS_FILE_Attrib *attr;
314 for( size_t ofs = hdr->FirstAttribOfs; ofs < hdr->RecordSize; ofs += attr->Size )
316 attr = (void*)( (tVAddr)hdr + ofs );
318 if( ofs + 4 > hdr->RecordSize )
321 if( attr->Type == 0xFFFFFFFF )
323 // Sanity #2: Type,Size
324 if( ofs + 8 > hdr->RecordSize )
326 // Sanity #3: Reported size
327 if( attr->Size < sizeof(attr->Resident) )
329 // Sanity #4: Reported size fits
330 if( ofs + attr->Size > hdr->RecordSize )
333 // - Chceck if this attribute is the one requested
334 LOG("Type check %x == %x", attr->Type, Type);
335 if( attr->Type != Type )
338 if( attr->NameOffset + attr->NameLength*2 > attr->Size ) {
341 const void *name16 = (char*)attr + attr->NameOffset;
342 LOG("Name check: '%s' == '%.*ls'",
343 Name, attr->NameLength, name16);
344 if( UTF16_CompareWithUTF8(attr->NameLength, name16, Name) != 0 )
347 LOG("Idx check %i", curIdx);
348 if( curIdx++ != DesIdx )
351 // - Construct (and cache) attribute description
352 ASSERT(attr->NameOffset % 1 == 0);
353 Uint16 *name16 = (Uint16*)attr + attr->NameOffset/2;
354 size_t namelen = UTF16_ConvertToUTF8(0, NULL, attr->NameLength, name16);
355 size_t edatalen = (attr->NonresidentFlag ? 0 : attr->Resident.AttribLen);
356 tNTFS_Attrib *ret = malloc( sizeof(tNTFS_Attrib) + namelen + 1 + edatalen );
360 if( attr->NonresidentFlag )
361 ret->Name = (void*)(ret + 1);
363 ret->ResidentData = ret + 1;
364 ret->Name = (char*)ret->ResidentData + edatalen;
368 ret->Type = attr->Type;
369 UTF16_ConvertToUTF8(namelen+1, ret->Name, attr->NameLength, name16);
370 ret->IsResident = !(attr->NonresidentFlag);
372 LOG("Creating with %x '%s'", ret->Type, ret->Name);
374 if( attr->NonresidentFlag )
376 ret->DataSize = attr->NonResident.RealSize;
377 ret->NonResident.CompressionUnitL2Size = attr->NonResident.CompressionUnitSize;
378 ret->NonResident.FirstPopulatedCluster = attr->NonResident.StartingVCN;
380 const char *limit = (char*)attr + attr->Size;
382 const char *datarun = (char*)attr + attr->NonResident.DataRunOfs;
383 while( (datarun = _GetDataRun(datarun, limit, 0, NULL, NULL)) )
385 LOG("nruns = %i", nruns);
386 // Allocate data runs
387 ret->NonResident.nRuns = nruns;
388 ret->NonResident.Runs = malloc( sizeof(tNTFS_AttribDataRun) * nruns );
390 datarun = (char*)attr + attr->NonResident.DataRunOfs;
392 while( datarun && i < nruns )
394 tNTFS_AttribDataRun *run = &ret->NonResident.Runs[i];
395 datarun = _GetDataRun(datarun,limit, lastLCN, &run->Count, &run->LCN);
396 LOG("Run %i: %llx+%llx", i, run->LCN, run->Count);
403 ret->DataSize = edatalen;
404 memcpy(ret->ResidentData, (char*)attr + attr->Resident.AttribOfs, edatalen);
405 Debug_HexDump("GetAttrib Resident", ret->ResidentData, edatalen);
408 NTFS_ReleaseMFT(Disk, MFTEntry, hdr);
414 NTFS_ReleaseMFT(Disk, MFTEntry, hdr);
419 void NTFS_FreeAttrib(tNTFS_Attrib *Attrib)
425 size_t NTFS_ReadAttribData(tNTFS_Attrib *Attrib, Uint64 Offset, size_t Length, void *Buffer)
429 if( Offset >= Attrib->DataSize )
431 if( Length > Attrib->DataSize )
432 Length = Attrib->DataSize;
433 if( Offset + Length > Attrib->DataSize )
434 Length = Attrib->DataSize - Offset;
436 if( Attrib->IsResident )
438 memcpy(Buffer, Attrib->ResidentData, Length);
444 tNTFS_Disk *Disk = Attrib->Disk;
445 Uint64 first_cluster = Offset / Disk->ClusterSize;
446 size_t cluster_ofs = Offset % Disk->ClusterSize;
447 if( first_cluster < Attrib->NonResident.FirstPopulatedCluster ) {
448 Log_Warning("NTFS", "TODO: Ofs < FirstVCN");
450 first_cluster -= Attrib->NonResident.FirstPopulatedCluster;
451 if( Attrib->NonResident.CompressionUnitL2Size )
454 Log_Warning("NTFS", "Compression unsupported");
455 // NOTE: Compressed blocks show up in pairs of runs
456 // - The first contains the compressed data
457 // - The second is a placeholder 'sparse' (LCN=0) to align to the compression unit
461 // Iterate through data runs until the desired run is located
462 for( int i = 0; i < Attrib->NonResident.nRuns && Length; i ++ )
464 tNTFS_AttribDataRun *run = &Attrib->NonResident.Runs[i];
465 if( first_cluster > run->Count ) {
466 first_cluster -= run->Count;
469 size_t avail_bytes = (run->Count-first_cluster)*Disk->ClusterSize - cluster_ofs;
470 if( avail_bytes > Length )
471 avail_bytes = Length;
472 // Read from this extent
473 if( run->LCN == 0 ) {
474 memset(Buffer, 0, avail_bytes);
478 (run->LCN + first_cluster)*Disk->ClusterSize + cluster_ofs,
483 Length -= avail_bytes;
484 Buffer += avail_bytes;
496 * \brief Dumps a MFT Entry
498 void NTFS_DumpEntry(tNTFS_Disk *Disk, Uint32 Entry)
500 tNTFS_FILE_Attrib *attr;
504 tNTFS_FILE_Header *hdr = NTFS_GetMFT(Disk, Entry);
506 Log_Warning("FS_NTFS", "malloc() fail!");
510 Log_Debug("FS_NTFS", "MFT Entry #%i", Entry);
511 Log_Debug("FS_NTFS", "- Magic = 0x%08x (%4C)", hdr->Magic, &hdr->Magic);
512 Log_Debug("FS_NTFS", "- UpdateSequenceOfs = 0x%x", hdr->UpdateSequenceOfs);
513 Log_Debug("FS_NTFS", "- UpdateSequenceSize = 0x%x", hdr->UpdateSequenceSize);
514 Log_Debug("FS_NTFS", "- LSN = 0x%x", hdr->LSN);
515 Log_Debug("FS_NTFS", "- SequenceNumber = %i", hdr->SequenceNumber);
516 Log_Debug("FS_NTFS", "- HardLinkCount = %i", hdr->HardLinkCount);
517 Log_Debug("FS_NTFS", "- FirstAttribOfs = 0x%x", hdr->FirstAttribOfs);
518 Log_Debug("FS_NTFS", "- Flags = 0x%x", hdr->Flags);
519 Log_Debug("FS_NTFS", "- RecordSize = 0x%x", hdr->RecordSize);
520 Log_Debug("FS_NTFS", "- RecordSpace = 0x%x", hdr->RecordSpace);
521 Log_Debug("FS_NTFS", "- Reference = 0x%llx", hdr->Reference);
522 Log_Debug("FS_NTFS", "- NextAttribID = 0x%04x", hdr->NextAttribID);
524 attr = (void*)( (char*)hdr + hdr->FirstAttribOfs );
526 while( (tVAddr)attr < (tVAddr)hdr + hdr->RecordSize )
528 if(attr->Type == 0xFFFFFFFF) break;
529 Log_Debug("FS_NTFS", "- Attribute %i", i ++);
530 Log_Debug("FS_NTFS", " > Type = 0x%x", attr->Type);
531 Log_Debug("FS_NTFS", " > Size = 0x%x", attr->Size);
532 Log_Debug("FS_NTFS", " > ResidentFlag = 0x%x", attr->NonresidentFlag);
533 Log_Debug("FS_NTFS", " > NameLength = %i", attr->NameLength);
534 Log_Debug("FS_NTFS", " > NameOffset = 0x%x", attr->NameOffset);
535 Log_Debug("FS_NTFS", " > Flags = 0x%x", attr->Flags);
536 Log_Debug("FS_NTFS", " > AttributeID = 0x%x", attr->AttributeID);
538 Uint16 *name16 = (void*)((char*)attr + attr->NameOffset);
539 size_t len = UTF16_ConvertToUTF8(0, NULL, attr->NameLength, name16);
541 UTF16_ConvertToUTF8(len+1, name, attr->NameLength, name16);
542 Log_Debug("FS_NTFS", " > Name = '%s'", name);
544 if( !attr->NonresidentFlag ) {
545 Log_Debug("FS_NTFS", " > AttribLen = 0x%x", attr->Resident.AttribLen);
546 Log_Debug("FS_NTFS", " > AttribOfs = 0x%x", attr->Resident.AttribOfs);
547 Log_Debug("FS_NTFS", " > IndexedFlag = 0x%x", attr->Resident.IndexedFlag);
548 Debug_HexDump("FS_NTFS",
549 (void*)( (tVAddr)attr + attr->Resident.AttribOfs ),
550 attr->Resident.AttribLen
554 Log_Debug("FS_NTFS", " > StartingVCN = 0x%llx", attr->NonResident.StartingVCN);
555 Log_Debug("FS_NTFS", " > LastVCN = 0x%llx", attr->NonResident.LastVCN);
556 Log_Debug("FS_NTFS", " > DataRunOfs = 0x%x", attr->NonResident.DataRunOfs);
557 Log_Debug("FS_NTFS", " > CompressionUnitSize = 0x%x", attr->NonResident.CompressionUnitSize);
558 Log_Debug("FS_NTFS", " > AllocatedSize = 0x%llx", attr->NonResident.AllocatedSize);
559 Log_Debug("FS_NTFS", " > RealSize = 0x%llx", attr->NonResident.RealSize);
560 Log_Debug("FS_NTFS", " > InitiatedSize = 0x%llx", attr->NonResident.InitiatedSize);
561 Debug_HexDump("FS_NTFS",
562 (char*)attr + attr->NonResident.DataRunOfs,
563 attr->Size - attr->NonResident.DataRunOfs
567 attr = (void*)( (tVAddr)attr + attr->Size );
570 NTFS_ReleaseMFT(Disk, Entry, hdr);