Posted: . At: 8:21 AM. This was 6 months ago. Post ID: 18704
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


Windows XP file system source code. This should be very interesting.


Windows XP used the NTFS filesystem as well as the FAT32 file system. This is the New Technology File System. I am uploading this source code as it might be very interesting to a fan of Windows XP who wants to get an insight into how the filesystem code is written. Windows XP is from 2001 and has code in it dating to 1989. This is amazing. The source code below is from the NTFS source code, this is shutdown code.

\base\fs\ntfs\shutdown.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*++
 
Copyright (c) 1989  Microsoft Corporation
 
Module Name:
 
    Shutdown.c
 
Abstract:
 
    This module implements the file system shutdown routine for Ntfs
 
Author:
 
    Gary Kimura     [GaryKi]    19-Aug-1991
 
Revision History:
 
--*/
 
#include "NtfsProc.h"
 
//
//  Interal support routine
//
 
VOID
NtfsCheckpointVolumeUntilDone (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    );
 
//
//  Local debug trace level
//
 
#define Dbg                              (DEBUG_TRACE_SHUTDOWN)
 

NTSTATUS
NtfsFsdShutdown (
    IN PVOLUME_DEVICE_OBJECT VolumeDeviceObject,
    IN PIRP Irp
    )
 
/*++
 
Routine Description:
 
    This routine implements the FSD part of shutdown.  Note that Shutdown will
    never be done asynchronously so we will never need the Fsp counterpart
    to shutdown.
 
    This is the shutdown routine for the Ntfs file system device driver.
    This routine locks the global file system lock and then syncs all the
    mounted volumes.
 
Arguments:
 
    VolumeDeviceObject - Supplies the volume device object where the
        file exists
 
    Irp - Supplies the Irp being processed
 
Return Value:
 
    NTSTATUS - Always STATUS_SUCCESS
 
--*/
 
{
    TOP_LEVEL_CONTEXT TopLevelContext;
    PTOP_LEVEL_CONTEXT ThreadTopLevelContext;
 
    IRP_CONTEXT LocalIrpContext;
    PIRP_CONTEXT IrpContext = &LocalIrpContext;
 
    PLIST_ENTRY Links;
    PVCB Vcb;
    PIRP NewIrp;
    KEVENT Event;
 
    UNREFERENCED_PARAMETER( VolumeDeviceObject );
 
    DebugTrace( +1, Dbg, ("NtfsFsdShutdown\n") );
 
    FsRtlEnterFileSystem();
 
    //
    //  Allocate an Irp Context that we can use in our procedure calls
    //  and we know that shutdown will always be synchronous
    //
 
    ThreadTopLevelContext = NtfsInitializeTopLevelIrp( &TopLevelContext, FALSE, FALSE );
 
    NtfsInitializeIrpContext( Irp, TRUE, &IrpContext );
 
    NtfsUpdateIrpContextWithTopLevel( IrpContext, ThreadTopLevelContext );
 
    //
    //  Get everyone else out of the way
    //
 
    if (!NtfsAcquireExclusiveGlobal( IrpContext, BooleanFlagOn( IrpContext->State, IRP_CONTEXT_STATE_WAIT ))) {
        NtfsRaiseStatus( IrpContext, STATUS_CANT_WAIT, NULL, NULL );
    }
 
    try {
 
        BOOLEAN AcquiredFiles;
        BOOLEAN AcquiredCheckpoint;
 
        //
        //  Initialize an event for doing calls down to
        //  our target device objects
        //
 
        KeInitializeEvent( &Event, NotificationEvent, FALSE );
 
        //
        //  For every volume that is mounted we will flush the
        //  volume and then shutdown the target device objects.
        //
 
        for (Links = NtfsData.VcbQueue.Flink;
             Links != &NtfsData.VcbQueue;
             Links = Links->Flink) {
 
            ASSERT( FlagOn( IrpContext->State, IRP_CONTEXT_STATE_OWNS_TOP_LEVEL ));
 
            //
            //  Get the Vcb and put it in the IrpContext.
            //
 
            Vcb = CONTAINING_RECORD(Links, VCB, VcbLinks);
            IrpContext->Vcb = Vcb;
 
            //
            //  If we have already been called before for this volume
            //  (and yes this does happen), skip this volume as no writes
            //  have been allowed since the first shutdown.
            //
 
            if ( FlagOn( Vcb->VcbState, VCB_STATE_FLAG_SHUTDOWN ) ) {
 
                continue;
            }
 
            //
            //  Clear the Mft defrag flag to stop any actions behind our backs.
            //
 
            NtfsAcquireCheckpoint( IrpContext, Vcb );
            ClearFlag( Vcb->MftDefragState, VCB_MFT_DEFRAG_PERMITTED );
            NtfsReleaseCheckpoint( IrpContext, Vcb );
 
            AcquiredFiles = FALSE;
            AcquiredCheckpoint = FALSE;
 
            try {
 
                if (FlagOn( Vcb->VcbState, VCB_STATE_VOLUME_MOUNTED )) {
 
                    //
                    //  Start by locking out all other checkpoint
                    //  operations.
                    //
 
                    NtfsAcquireCheckpoint( IrpContext, Vcb );
 
                    while (FlagOn( Vcb->CheckpointFlags, VCB_CHECKPOINT_SYNC_FLAGS )) {
 
                        //
                        //  Release the checkpoint event because we cannot checkpoint now.
                        //
 
                        NtfsReleaseCheckpoint( IrpContext, Vcb );
 
                        NtfsWaitOnCheckpointNotify( IrpContext, Vcb );
 
                        NtfsAcquireCheckpoint( IrpContext, Vcb );
                    }
 
                    SetFlag( Vcb->CheckpointFlags, VCB_CHECKPOINT_SYNC_FLAGS );
                    NtfsResetCheckpointNotify( IrpContext, Vcb );
                    NtfsReleaseCheckpoint( IrpContext, Vcb );
                    AcquiredCheckpoint = TRUE;
 
                    NtfsAcquireAllFiles( IrpContext, Vcb, TRUE, TRUE, FALSE );
                    AcquiredFiles = TRUE;
 
                    SetFlag( Vcb->VcbState, VCB_STATE_VOL_PURGE_IN_PROGRESS );
 
                    if (!FlagOn( Vcb->VcbState, VCB_STATE_LOCKED)) {
                        NtfsCheckpointVolumeUntilDone( IrpContext, Vcb );
                    }
                    NtfsCommitCurrentTransaction( IrpContext );
 
                    //
                    //  Bug 308819. We find that transactions continue to happen at times even after shutdown
                    //  has been flagged. If we stop the log file, then currently we don't check for
                    //  NULL LSNs getting returned by NtfsWriteLog. As a result our metadata can get
                    //  corrupted. Until we rectify this, let's just not stop the log file in shutdown.
                    //
                    //  NtfsStopLogFile( Vcb );
                    //
 
                    NtfsAcquireCheckpoint( IrpContext, Vcb );
                    ClearFlag( Vcb->CheckpointFlags,
                               VCB_CHECKPOINT_SYNC_FLAGS | VCB_DUMMY_CHECKPOINT_POSTED);
                    NtfsSetCheckpointNotify( IrpContext, Vcb );
                    NtfsReleaseCheckpoint( IrpContext, Vcb );
                    AcquiredCheckpoint = FALSE;
 
                    NewIrp = IoBuildSynchronousFsdRequest( IRP_MJ_SHUTDOWN,
                                                           Vcb->TargetDeviceObject,
                                                           NULL,
                                                           0,
                                                           NULL,
                                                           &Event,
                                                           NULL );
 
                    if (NewIrp == NULL) {
 
                        NtfsRaiseStatus( IrpContext, STATUS_INSUFFICIENT_RESOURCES, NULL, NULL );
                    }
 
                    if (NT_SUCCESS(IoCallDriver( Vcb->TargetDeviceObject, NewIrp ))) {
 
                        (VOID) KeWaitForSingleObject( &Event,
                                                      Executive,
                                                      KernelMode,
                                                      FALSE,
                                                      NULL );
 
                        KeClearEvent( &Event );
                    }
                }
 
            } except( EXCEPTION_EXECUTE_HANDLER ) {
 
                NtfsMinimumExceptionProcessing( IrpContext );
            }
 
            if (AcquiredCheckpoint) {
 
                NtfsAcquireCheckpoint( IrpContext, Vcb );
                ClearFlag( Vcb->CheckpointFlags,
                           VCB_CHECKPOINT_SYNC_FLAGS | VCB_DUMMY_CHECKPOINT_POSTED);
                NtfsSetCheckpointNotify( IrpContext, Vcb );
                NtfsReleaseCheckpoint( IrpContext, Vcb );
            }
 
            SetFlag( Vcb->VcbState, VCB_STATE_FLAG_SHUTDOWN );
            ClearFlag( Vcb->VcbState, VCB_STATE_VOL_PURGE_IN_PROGRESS );
 
            if (AcquiredFiles) {
 
                NtfsReleaseAllFiles( IrpContext, Vcb, TRUE );
            }
        }
 
    } finally {
 
        NtfsReleaseGlobal( IrpContext );
 
        NtfsCompleteRequest( IrpContext, Irp, STATUS_SUCCESS );
        ASSERT( IoGetTopLevelIrp() != (PIRP) &TopLevelContext );
    }
 
    DebugTrace( -1, Dbg, ("NtfsFsdShutdown -> STATUS_SUCCESS\n") );
 
    FsRtlExitFileSystem();
 
    return STATUS_SUCCESS;
}
 

VOID
NtfsCheckpointVolumeUntilDone (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )
 
/*++
 
Routine Description:
 
    This routine keeps trying to checkpoint/flush a volume until it
    works.  Doing clean checkpoints and looping back to retry on log file full.
 
Arguments:
 
    Vcb - Vcb to checkpoint til done
 
Return Value:
 
    None
 
--*/
 
{
    NTSTATUS Status;
 
    do {
 
        Status = STATUS_SUCCESS;
 
        try {
            NtfsCheckpointVolume( IrpContext,
                                  Vcb,
                                  TRUE,
                                  TRUE,
                                  TRUE,
                                  0,
                                  Vcb->LastRestartArea );
        } except( (Status = GetExceptionCode()), EXCEPTION_EXECUTE_HANDLER ) {
 
            NtfsMinimumExceptionProcessing( IrpContext );
        }
 
        if (!NT_SUCCESS(Status)) {
 
            //
            //  To make sure that we can access all of our streams correctly,
            //  we first restore all of the higher sizes before aborting the
            //  transaction.  Then we restore all of the lower sizes after
            //  the abort, so that all Scbs are finally restored.
            //
 
            NtfsRestoreScbSnapshots( IrpContext, TRUE );
            NtfsAbortTransaction( IrpContext, IrpContext->Vcb, NULL );
            NtfsRestoreScbSnapshots( IrpContext, FALSE );
 
            //
            //  A clean volume checkpoint should never get log file full
            //
 
            if (Status == STATUS_LOG_FILE_FULL) {
 
                //
                //  Make sure we don't leave the error code in the top-level
                //  IrpContext field.
                //
 
                ASSERT( IrpContext->TransactionId == 0 );
                IrpContext->ExceptionStatus = STATUS_SUCCESS;
 
                NtfsCheckpointVolume( IrpContext,
                                      Vcb,
                                      TRUE,
                                      TRUE,
                                      FALSE,
                                      0,
                                      Vcb->LastRestartArea );
            }
        }
 
    } while (Status == STATUS_LOG_FILE_FULL);
}

The source code of fdisk is also included in this upload. Here is a sample, this is a central include file for the fdisk utility.

\base\fs\utils\fdisk\fdisk.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*++
 
Copyright (c) 1991-1994  Microsoft Corporation
 
Module Name:
 
    fdisk.h
 
Abstract:
 
    Central include file for Disk Administrator
 
Author:
 
    Edward (Ted) Miller  (TedM)  11/15/91
 
Environment:
 
    User process.
 
Notes:
 
Revision History:
 
    11-Nov-93 (bobri) added doublespace and commit support.
    2-Feb-94  (bobri) removed ArcInst dependency in build.
 
--*/
 
//#define UNICODE
 
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <ntdddisk.h>
#include <ntdskreg.h>
#include <ntddft.h>
 
//
// These defines are for virtualized types in partitp.h, low.h,
// fdengine.c, etc.
//
#define STATUS_CODE             NTSTATUS
#define OK_STATUS               STATUS_SUCCESS
#define RETURN_OUT_OF_MEMORY    return(STATUS_NO_MEMORY);
#define HANDLE_T                HANDLE
#define HANDLE_PT               PHANDLE
#define AllocateMemory          Malloc
#define ReallocateMemory        Realloc
#define FreeMemory              Free
 
#include <windows.h>
 
#include <stdarg.h>
 
#include "fdtypes.h"
#include "fdproto.h"
#include "fdconst.h"
#include "fdglob.h"
#include "fdres.h"
#include "fdiskmsg.h"
#include "fdhelpid.h"
 
 
#define PERSISTENT_DATA(region) ((PPERSISTENT_REGION_DATA)((region)->PersistentData))
 
#define GET_FT_OBJECT(region)   ((region)->PersistentData ? PERSISTENT_DATA(region)->FtObject : NULL)
#define SET_FT_OBJECT(region,o) (PERSISTENT_DATA(region)->FtObject = o)
 
 
#define EC(x) RtlNtStatusToDosError(x)
 
// assertion checking, logging
 
#if DBG
 
#define     FDASSERT(expr)  if(!(expr)) FdiskAssertFailedRoutine(#expr,__FILE__,__LINE__);
#define     FDLOG(X) FdLog X
 
VOID
FdLog(
    IN int   Level,
    IN PCHAR FormatString,
    ...
    );
 
VOID
LOG_DISK_REGISTRY(
    IN PCHAR          RoutineName,
    IN PDISK_REGISTRY DiskRegistry
    );
 
VOID
LOG_ONE_DISK_REGISTRY_DISK_ENTRY(
    IN PCHAR             RoutineName     OPTIONAL,
    IN PDISK_DESCRIPTION DiskDescription
    );
 
VOID
LOG_DRIVE_LAYOUT(
    IN PDRIVE_LAYOUT_INFORMATION DriveLayout
    );
 
VOID
InitLogging(
    VOID
    );
 
extern PVOID LogFile;
 
#else
 
#define     FDASSERT(expr)
#define     FDLOG(X)
#define     LOG_DISK_REGISTRY(x,y)
#define     LOG_ONE_DISK_REGISTRY_DISK_ENTRY(x,y)
#define     LOG_DRIVE_LAYOUT(x)
 
#endif

Here is the source code of chkdsk. I am sure someone is interested in this.

\base\fs\utils\chkdsk\chkdsk.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/*++
 
Copyright (c) 1991-2000 Microsoft Corporation
 
Module Name:
 
        chkdsk.cxx
 
Abstract:
 
        Chkdsk is a program that checks your disk for corruption and/or bad sectors.
 
Author:
 
        Bill McJohn (billmc) 12-April-91
 
Revision History:
 
--*/
 
#define _NTAPI_ULIB_
 
#include "ulib.hxx"
 
#include "arg.hxx"
#include "chkmsg.hxx"
#include "rtmsg.h"
#include "wstring.hxx"
#include "path.hxx"
 
#include "system.hxx"
#include "ifssys.hxx"
#include "substrng.hxx"
 
#include "ulibcl.hxx"
#include "ifsentry.hxx"
 
#include "keyboard.hxx"
 
#include "supera.hxx"           // for CHKDSK_EXIT_*
 
int __cdecl
main(
        )
/*++
 
Routine Description:
 
    Entry point for chkdsk.exe.  This function parses the arguments,
    determines the appropriate file system (by querying the volume),
    and invokes the appropriate version of chkdsk.
 
    The arguments accepted by Chkdsk are:
 
        /f                  Fix errors on drive
        /v                  Verbose operation
        drive:              drive to check
        file-name           files to check for contiguity
                            (Note that HPFS ignores file-name parameters).
        /x                  Force the volume to dismount first if necessary (implied /f)
        /i                  include index entries checking during index verification
        /c                  include cycles checking during index verification
        /r                  locate bad sectors and recover readable information
        /l[:size]           change or display log file size
 
--*/
{
    DSTRING         CurrentDirectory;
    DSTRING         FsName;
    DSTRING         FsNameAndVersion;
    DSTRING         LibraryName;
    DSTRING         DosDriveName;
    DSTRING         CurrentDrive;
    DSTRING         NtDriveName;
    PWSTRING        p;
    HANDLE          FsUtilityHandle;
    DSTRING         ChkdskString;
    DSTRING         Colon;
    CHKDSKEX_FN     ChkdskEx = NULL;
    PWSTRING        pwstring;
    BOOLEAN         fix;
    BOOLEAN         resize_logfile;
    ULONG           logfile_size;
    FSTRING         acolon, bcolon;
    ULONG           exit_status;
 
    ARGUMENT_LEXEMIZER  Lexemizer;
    ARRAY               EmptyArray;
    ARRAY               ArgumentArray;
    FLAG_ARGUMENT       ArgumentHelp;
    FLAG_ARGUMENT       ArgumentForce;
    FLAG_ARGUMENT       ArgumentFix;
    FLAG_ARGUMENT       ArgumentVerbose;
    FLAG_ARGUMENT       ArgumentRecover;
    LONG_ARGUMENT       ArgumentAlgorithm;
    FLAG_ARGUMENT       ArgumentSkipIndexScan;
    FLAG_ARGUMENT       ArgumentSkipCycleScan;
    FLAG_ARGUMENT       ArgumentResize;
    LONG_ARGUMENT       ArgumentResizeLong;
    STRING_ARGUMENT     ArgumentProgramName;
    PATH_ARGUMENT       ArgumentPath;
 
 
    CHKDSK_MESSAGE      Message;
    NTSTATUS            Status;
    DWORD               oldErrorMode;
    PATH_ANALYZE_CODE   rst;
    PPATH               ppath;
    PATH                fullpath;
    PATH                drivepath;
    DSTRING             drivename;
    DSTRING             drive_path_string;
    BOOLEAN             is_drivepath_invalid = TRUE;
    DSTRING             ntfs_name;
    USHORT              algorithm;
 
    CHKDSKEX_FN_PARAM   param;
 
 
    if( !Message.Initialize( Get_Standard_Output_Stream(),
                             Get_Standard_Input_Stream() ) ) {
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
#if defined(PRE_RELEASE_NOTICE)
    Message.Set(MSG_CHK_PRE_RELEASE_NOTICE);
    Message.Display();
#endif
 
    // Initialize the colon string in case we need it later:
 
    if( !Colon.Initialize( ":" ) ||
        !ntfs_name.Initialize( "NTFS" )) {
 
        Message.Set( MSG_CHK_NO_MEMORY );
        Message.Display( "" );
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
 
    // Parse the arguments.  First, initialize all the
    // parsing machinery.  Then put the potential arguments
    // into the argument array,
 
    if( !ArgumentArray.Initialize( 5, 1 )               ||
        !EmptyArray.Initialize( 5, 1 )                  ||
        !Lexemizer.Initialize( &EmptyArray )            ||
        !ArgumentHelp.Initialize( "/?" )                ||
        !ArgumentForce.Initialize( "/X" )               ||
        !ArgumentFix.Initialize( "/F" )                 ||
        !ArgumentVerbose.Initialize( "/V" )             ||
        !ArgumentRecover.Initialize( "/R" )             ||
        !ArgumentAlgorithm.Initialize( "/I:*" )         ||
        !ArgumentSkipIndexScan.Initialize( "/I" )       ||
        !ArgumentSkipCycleScan.Initialize( "/C" )       ||
        !ArgumentResize.Initialize( "/L" )              ||
        !ArgumentResizeLong.Initialize( "/L:*" )        ||
        !ArgumentProgramName.Initialize( "*" )          ||
        !ArgumentPath.Initialize( "*", FALSE ) ) {
 
        Message.Set( MSG_CHK_NO_MEMORY );
        Message.Display( "" );
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    // CHKDSK is not case sensitive.
 
    Lexemizer.SetCaseSensitive( FALSE );
 
    if( !ArgumentArray.Put( &ArgumentProgramName )  ||
        !ArgumentArray.Put( &ArgumentHelp )         ||
        !ArgumentArray.Put( &ArgumentForce )        ||
        !ArgumentArray.Put( &ArgumentFix )          ||
        !ArgumentArray.Put( &ArgumentVerbose )      ||
        !ArgumentArray.Put( &ArgumentRecover )      ||
        !ArgumentArray.Put( &ArgumentAlgorithm )    ||
        !ArgumentArray.Put( &ArgumentSkipIndexScan )||
        !ArgumentArray.Put( &ArgumentSkipCycleScan )||
        !ArgumentArray.Put( &ArgumentResize )       ||
        !ArgumentArray.Put( &ArgumentResizeLong )   ||
        !ArgumentArray.Put( &ArgumentPath ) ) {
 
        Message.Set( MSG_CHK_NO_MEMORY );
        Message.Display( "" );
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    // Parse.  Note that PrepareToParse will, by default, pick
    // up the command line.
 
    if( !Lexemizer.PrepareToParse() ) {
 
        Message.Set( MSG_CHK_NO_MEMORY );
        Message.Display( "" );
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
 
    // If the parsing failed, display a helpful command line summary.
 
    if( !Lexemizer.DoParsing( &ArgumentArray ) ) {
 
        Message.Set(MSG_INVALID_PARAMETER);
        Message.Display("%W", pwstring = Lexemizer.QueryInvalidArgument());
        DELETE(pwstring);
 
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
 
    // If the user requested help, give it.
 
    if( ArgumentHelp.QueryFlag() ) {
 
        Message.Set( MSG_CHK_USAGE_HEADER );
        Message.Display( "" );
        Message.Set( MSG_BLANK_LINE );
        Message.Display( "" );
        Message.Set( MSG_CHK_COMMAND_LINE );
        Message.Display( "" );
        Message.Set( MSG_BLANK_LINE );
        Message.Display( "" );
        Message.Set( MSG_CHK_DRIVE );
        Message.Display( "" );
        Message.Set( MSG_CHK_USG_FILENAME );
        Message.Display( "" );
        Message.Set( MSG_CHK_F_SWITCH );
        Message.Display( "" );
        Message.Set( MSG_CHK_V_SWITCH );
        Message.Display( "" );
 
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
 
    if (!ArgumentPath.IsValueSet()) {
 
        if (!SYSTEM::QueryCurrentDosDriveName(&DosDriveName) ||
            !drivepath.Initialize(&DosDriveName)) {
            return CHKDSK_EXIT_COULD_NOT_CHK;
        }
        ppath = &drivepath;
    } else {
        ppath = ArgumentPath.GetPath();
#if defined(RUN_ON_NT4)
        if (!DosDriveName.Initialize(ppath->GetPathString()))
            return CHKDSK_EXIT_COULD_NOT_CHK;
#endif
    }
 
#if !defined(RUN_ON_NT4)
    rst = ppath->AnalyzePath(&DosDriveName,
                             &fullpath,
                             &drive_path_string);
 
    switch (rst) {
        case PATH_OK:
        case PATH_COULD_BE_FLOPPY:
            is_drivepath_invalid = fullpath.IsDrive() ||
                                   (fullpath.GetPathString()->QueryChCount() == 0);
            if (ppath->IsGuidVolName()) {
                if (!drivename.Initialize(&DosDriveName))
                    return CHKDSK_EXIT_COULD_NOT_CHK;
            } else {
                if (!drivename.Initialize(fullpath.GetPathString()))
                    return CHKDSK_EXIT_COULD_NOT_CHK;
            }
 
            if (fullpath.GetPathString()->QueryChCount() == 2 &&
                fullpath.GetPathString()->QueryChAt(1) == (WCHAR)':') {
                // if there is a drive letter for this drive, use it
                // instead of the guid volume name
                if (!DosDriveName.Initialize(fullpath.GetPathString())) {
                    return CHKDSK_EXIT_COULD_NOT_CHK;
                }
            }
            if (!fullpath.AppendString(&drive_path_string) ||
                !drivepath.Initialize(&drive_path_string))
                return CHKDSK_EXIT_COULD_NOT_CHK;
            break;
 
        case PATH_OUT_OF_MEMORY:
            DebugPrint("Out of memory.\n");
            return CHKDSK_EXIT_COULD_NOT_CHK;
 
        case PATH_NO_MOUNT_POINT_FOR_VOLUME_NAME_PATH:
            Message.Set(MSG_CHK_NO_MOUNT_POINT_FOR_GUID_VOLNAME_PATH);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
 
        default:
            Message.Set(MSG_CHK_BAD_DRIVE_PATH_FILENAME);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
    }
#endif
 
    if (!DosDriveName.Strupr()) {
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    // disable popups while we determine the drive type
    oldErrorMode = SetErrorMode( SEM_FAILCRITICALERRORS );
 
    // Make sure that drive is of a correct type.
 
    switch (SYSTEM::QueryDriveType(&DosDriveName)) {
 
        case RemoteDrive:
            SetErrorMode( oldErrorMode );
            Message.Set(MSG_CHK_CANT_NETWORK);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
 
#if 0
        case CdRomDrive:
            SetErrorMode( oldErrorMode );
            Message.Set(MSG_CHK_CANT_CDROM);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
#endif
 
        default:
            break;
 
    }
 
    SetErrorMode( oldErrorMode );
 
    if (!SYSTEM::QueryCurrentDosDriveName(&CurrentDrive)) {
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    // /R ==> /F
    // /X ==> /F
 
    fix = ArgumentFix.QueryFlag() ||
          ArgumentForce.QueryFlag() ||
          ArgumentRecover.QueryFlag();
 
    //      From here on we want to deal with an NT drive name:
 
    if (!IFS_SYSTEM::DosDriveNameToNtDriveName(&DosDriveName, &NtDriveName)) {
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    // disable popups while we determine the file system name and version
    oldErrorMode = SetErrorMode( SEM_FAILCRITICALERRORS );
 
    // Determine the type of the file system.
    // Ask the volume what file system it has.  The
    // IFS utilities for file system xxxx are in Uxxxx.DLL.
    //
 
    if (!IFS_SYSTEM::QueryFileSystemName(&NtDriveName,
                                         &FsName,
                                         &Status,
                                         &FsNameAndVersion )) {
 
        SetErrorMode( oldErrorMode );
 
        if( Status == STATUS_ACCESS_DENIED ) {
 
            Message.Set( MSG_DASD_ACCESS_DENIED );
            Message.Display( "" );
 
        } else if( Status != STATUS_SUCCESS ) {
 
            Message.Set( MSG_CANT_DASD );
            Message.Display( "" );
 
        } else {
 
            Message.Set( MSG_FS_NOT_DETERMINED );
            Message.Display( "%W", &drivename );
        }
 
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    // re-enable hardware popups
    SetErrorMode( oldErrorMode );
 
    if (FsName == ntfs_name && drive_path_string.QueryChCount()) {
        Message.Set(MSG_CHK_BAD_DRIVE_PATH_FILENAME);
        Message.Display();
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    Message.SetLoggingEnabled();
 
    Message.Set( MSG_CHK_RUNNING );
    Message.Log( "%W", &drivename );
 
    Message.Set( MSG_FILE_SYSTEM_TYPE );
    Message.Display( "%W", &FsName );
 
 
    if ( !FsName.Strupr() ) {
       return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    DSTRING fat32_name;
 
    if ( !fat32_name.Initialize("FAT32") ) {
       return CHKDSK_EXIT_COULD_NOT_CHK;
 
    }
 
    if ( FsName == fat32_name ) {
       FsName.Initialize("FAT");
    }
 
 
    if ( !LibraryName.Initialize( "U" ) ||
         !LibraryName.Strcat( &FsName ) ||
         !ChkdskString.Initialize( "ChkdskEx" ) ) {
 
         Message.Set( MSG_CHK_NO_MEMORY );
         Message.Display( "" );
         return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    if (fix && (CurrentDrive == DosDriveName)) {
 
        Message.Set(MSG_CANT_LOCK_CURRENT_DRIVE);
        Message.Display();
 
        if (IsNEC_98) {
 
            DP_DRIVE    dpdrive;
 
            dpdrive.Initialize(&NtDriveName, &Message);
 
            if (dpdrive.IsFloppy()) {
            return CHKDSK_EXIT_COULD_NOT_CHK;
            }
 
        } else {
 
            acolon.Initialize((PWSTR) L"A:");
            bcolon.Initialize((PWSTR) L"B:");
 
            if (!DosDriveName.Stricmp(&acolon) ||
                !DosDriveName.Stricmp(&bcolon)) {
 
                return CHKDSK_EXIT_COULD_NOT_CHK;
            }
 
        }
 
        // Fall through so that the lock fails and then the
        // run autochk on reboot logic kicks in.
        //
    }
 
    if (ArgumentAlgorithm.IsValueSet() && ArgumentSkipIndexScan.QueryFlag()) {
 
        Message.Set(MSG_CHK_ALGORITHM_AND_SKIP_INDEX_SPECIFIED);
        Message.Display();
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
    if (ArgumentAlgorithm.IsValueSet()) {
 
        if (ArgumentAlgorithm.QueryLong() < 0 ||
            ArgumentAlgorithm.QueryLong() > CHKDSK_MAX_ALGORITHM_VALUE) {
 
            Message.Set(MSG_CHK_INCORRECT_ALGORITHM_VALUE);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
        } else
            algorithm = (USHORT)ArgumentAlgorithm.QueryLong();
 
    } else
        algorithm = 0;
 
    if (ArgumentSkipIndexScan.QueryFlag() || ArgumentAlgorithm.IsValueSet()) {
 
        if (0 != FsName.Stricmp( &ntfs_name )) {
 
            Message.Set(MSG_CHK_SKIP_INDEX_NOT_NTFS);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
        }
 
    }
 
    if (ArgumentSkipCycleScan.QueryFlag()) {
 
        if (0 != FsName.Stricmp( &ntfs_name )) {
 
            Message.Set(MSG_CHK_SKIP_CYCLE_NOT_NTFS);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
        }
 
    }
 
    // Does the user want to resize the logfile?  This is only sensible
    // for NTFS.  If she specified a size of zero, print an error message
    // because that's a poor choice and will confuse the untfs code,
    // which assumes that zero means resize to the default size.
    //
 
    resize_logfile = ArgumentResize.IsValueSet() || ArgumentResizeLong.IsValueSet();
 
    if (resize_logfile) {
 
        if (0 != FsName.Stricmp( &ntfs_name )) {
 
            Message.Set(MSG_CHK_LOGFILE_NOT_NTFS);
            Message.Display();
            return CHKDSK_EXIT_COULD_NOT_CHK;
        }
 
        if (ArgumentResizeLong.IsValueSet()) {
 
            if (ArgumentResizeLong.QueryLong() <= 0) {
 
                Message.Set(MSG_CHK_WONT_ZERO_LOGFILE);
                Message.Display();
                return CHKDSK_EXIT_COULD_NOT_CHK;
            }
 
            if (ArgumentResizeLong.QueryLong() > MAXULONG/1024) {
                Message.Set(MSG_CHK_NTFS_SPECIFIED_LOGFILE_SIZE_TOO_BIG);
                Message.Display();
                return CHKDSK_EXIT_COULD_NOT_CHK;
            }
            logfile_size = ArgumentResizeLong.QueryLong() * 1024;
        } else {
 
            logfile_size = 0;
        }
    }
 
    if ((ChkdskEx =
        (CHKDSKEX_FN)SYSTEM::QueryLibraryEntryPoint( &LibraryName,
                                                     &ChkdskString,
                                                     &FsUtilityHandle )) !=
        NULL ) {
 
        if (fix &&
            !KEYBOARD::EnableBreakHandling()) {
            return CHKDSK_EXIT_COULD_NOT_CHK;
        }
 
        //
        // setup parameter block v1.0 to be passed to ChkdskEx
        //
 
        param.Major = 1;
        param.Minor = 1;
        param.Flags = (ArgumentVerbose.QueryFlag() ? CHKDSK_VERBOSE : 0);
        param.Flags |= (ArgumentRecover.QueryFlag() ? CHKDSK_RECOVER : 0);
        param.Flags |= (ArgumentForce.QueryFlag() ? CHKDSK_FORCE : 0);
        param.Flags |= (resize_logfile ? CHKDSK_RESIZE_LOGFILE : 0);
        param.Flags |= (ArgumentSkipIndexScan.QueryFlag() ? CHKDSK_SKIP_INDEX_SCAN : 0);
        param.Flags |= (ArgumentSkipCycleScan.QueryFlag() ? CHKDSK_SKIP_CYCLE_SCAN : 0);
        param.Flags |= (ArgumentAlgorithm.IsValueSet() ? CHKDSK_ALGORITHM_SPECIFIED : 0);
        param.LogFileSize = logfile_size;
        param.PathToCheck = &fullpath;
        param.RootPath = (is_drivepath_invalid) ? NULL : &drivepath;
        param.Algorithm = algorithm;
 
        if (fix) {
            ChkdskEx( &NtDriveName,
                      &Message,
                      fix,
                      &param,
                      &exit_status );
        } else {
 
//disable C4509 warning about nonstandard ext: SEH + destructor
#pragma warning(disable:4509)
 
            __try {
                ChkdskEx( &NtDriveName,
                          &Message,
                          fix,
                          &param,
                          &exit_status );
            } __except (EXCEPTION_EXECUTE_HANDLER) {
 
                // If we get an access violation during read-only mode
                // CHKDSK then it's because the file system is partying
                // on the volume while we are.
 
                Message.Set(MSG_CHK_NTFS_ERRORS_FOUND);
                Message.Display();
                exit_status = CHKDSK_EXIT_ERRS_NOT_FIXED;
            }
        }
 
        if (CHKDSK_EXIT_ERRS_FIXED == exit_status && !fix) {
            exit_status = CHKDSK_EXIT_ERRS_NOT_FIXED;
        }
 
        SYSTEM::FreeLibraryHandle( FsUtilityHandle );
 
        if (fix &&
            !KEYBOARD::DisableBreakHandling()) {
 
            return 1;
        }
 
    } else {
 
        Message.Set( MSG_FS_NOT_SUPPORTED );
        Message.Display( "%s%W", "CHKDSK", &FsName );
        Message.Set( MSG_BLANK_LINE );
        Message.Display( "" );
 
        return CHKDSK_EXIT_COULD_NOT_CHK;
    }
 
//    Message.Set(MSG_CHK_NTFS_MESSAGE);
//    Message.Display("%s%d", "Exit Status ", exit_status);
 
    return exit_status;
}

Download this source code below. People are looking for the NTFS source code so here it is. This would be very good for reverse engineering for open-source coders. The fastfat folder has the FAT source code. There is also the source code of Udfs as well, this is used on DVD filesystems. Yet another filesystem it would be excellent to see the workings of. Another included dump is the code of remotefs. This is used for mounting SAMBAs mounts over a network. And the source of NPFS. Named Pipe File system driver for Windows. Which would also be interesting to trawl through.

Here is a tiny sample of the NPFS code.

\base\fs\npfs\npfs.rc
1
2
3
4
5
6
7
8
9
10
11
#include <windows.h>
 
#include <ntverp.h>
 
#define	VER_FILETYPE	VFT_DRV
#define	VER_FILESUBTYPE	VFT2_DRV_SYSTEM
#define VER_FILEDESCRIPTION_STR     "NPFS Driver"
#define VER_INTERNALNAME_STR        "npfs.sys"
#define VER_ORIGINALFILENAME_STR    "npfs.sys"
 
#include "common.ver"

Download link:

https://www.securitronlinux.com/doomstuff/fs.7z


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.