Posted: . At: 1:59 PM. This was 1 year ago. Post ID: 17798
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 boot code. This is very interesting.


I have just found some very interesting source code from Windows XP. This is the Assembler code that performs the beginning of the boot process to start up Windows XP. This is i386 code, may not be used anymore, but I thought it would be very interesting for sure.

x86mboot.asm
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
        page    ,132
;
;   Microsoft Confidential
;   Copyright (C) Microsoft Corporation 1983-1997
;   All Rights Reserved.
;
;
;   This is the standard boot record that will be shipped on all hard disks.
;   It contains:
;
;   1.  Code to load (and give control to) the active boot record for 1 of 4
;       possible operating systems.
;
;   2.  A partition table at the end of the boot record, followed by the
;       required signature.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
VOLBOOT_ORG             EQU 7c00h
SIZE_SECTOR             EQU 512
 
;
; Partition table entry structure and other related stuff
;
Part_Active             EQU 0
Part_StartHead          EQU 1
Part_StartSector        EQU 2
Part_StartCylinder      EQU 3
Part_Type               EQU 4
Part_EndHead            EQU 5
Part_EndSector          EQU 6
Part_EndCylinder        EQU 7
Part_AbsoluteSector     EQU 8
Part_AbsoluteSectorH    EQU 10
Part_SectorCount        EQU 12
Part_SectorCountH       EQU 14
 
SIZE_PART_TAB_ENT       EQU 16
NUM_PART_TAB_ENTS       EQU 4
 
PART_TAB_OFF            EQU (SIZE_SECTOR - 2 - (SIZE_PART_TAB_ENT * NUM_PART_TAB_ENTS))
MBR_NT_OFFSET           EQU (PART_TAB_OFF - 6)
MBR_MSG_TABLE_OFFSET    EQU (PART_TAB_OFF - 9)
 
;
; Space we use for temp storage, beyond the end of
; the active partition table entry, and thus safe.
;
UsingBackup             EQU SIZE_PART_TAB_ENT
 
;
; Partition types
;
PART_IFS                EQU 07h
PART_FAT32              EQU 0bh
PART_FAT32_XINT13       EQU 0ch
PART_XINT13             EQU 0eh
 
;
; Filesystem and pbr stuff
;
BOOTSECTRAILSIGH        EQU 0aa55h
FAT32_BACKUP            EQU 6
 
 
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
RELOCATION_ORG  EQU     600h
 
READ_RETRY_CNT  EQU     5
 
 
_data   segment public
        assume  cs:_data,ds:nothing,es:nothing,ss:nothing
 
        org     100h
start100 label near
        org     RELOCATION_ORG
 
;   Move ourselves so that we can load the partition boot record from
;   the active partition at 0:VOLBOOT_ORG without trashing our own code.
;
;   WARNING: We are not executing at 0:RELOCATION_ORG until the far
;   immediate jump, below.  This basically means beware of OFFSETs of
;   any labels until we get there.  Until then, we're still executing at
;   0:VOLBOOT_ORG.
 
reloc_delta = 1Bh
 
start:
        xor     ax,ax
        mov     ss,ax
        mov     sp,VOLBOOT_ORG          ; new stack at 0:7c00
        sti
        push    ax
        pop     es
        assume  es:_data
        push    ax
        pop     ds
        assume  ds:_data
        cld
        mov     si,VOLBOOT_ORG + reloc_delta
        mov     di,RELOCATION_ORG + reloc_delta
        push    ax
        push    di
        mov     cx,SIZE_SECTOR - reloc_delta
        rep     movsb                   ; relocate to 0:0600
        retf
 
;   We are now RELOCATED and are now executing at 0:RELOCATION_ORG.
;
;   Find the active partition.  Once we find it, we also make sure that the
;   remaining partitions are INACTIVE, too.
 
        .errnz  reloc_delta NE $-start  ; make sure reloc_delta is correct
 
        mov     bp,offset tab           ; partition table
        mov     cl,NUM_PART_TAB_ENTS    ; number of table entries (CH==0)
 
active_loop:
        cmp     [bp].Part_Active,ch     ; is this the active entry?
        jl      check_inactive          ; yes
        jne     display_bad             ; no, it must be "00" or "8x"
 
        add     bp,SIZE_PART_TAB_ENT    ; yes, go to next entry
        loop    active_loop
 
        int     18h                     ; no active entries - go to ROM BASIC
 
;   Now make sure the remaining partitions are INACTIVE.
check_inactive:
        mov     si,bp                   ; si = active entry
inactive_loop:
        add     si,SIZE_PART_TAB_ENT    ; point si to next entry
        dec     cx                      ; # entries left
        jz      StartLoad               ; all entries look ok, start load
        cmp     [si],ch                 ; all remaining entries should be zero
        je      inactive_loop           ; this one is ok
 
display_bad:
        mov     al,byte ptr [m1]        ; partition table is bad
 
display_msg:
;
; Al is the offset-256 of the message text. Adjust and
; stick in si so lodsb below will work.
;
        .ERRNZ  RELOCATION_ORG MOD 256
        mov     ah,(RELOCATION_ORG / 256) + 1
        mov     si,ax
 
display_msg1:
        lodsb                           ; get a message character
@@:     cmp     al,0                    ; end of string?
        je      @b                      ; yes, loop infinitely
        mov     bx,7
        mov     ah,14
        int     10h                     ; and display it
        jmp     display_msg1            ; do the entire message
 
;
; Now attempt to read the sector.
;
; We store a data byte indicating whether this is the backup
; sector, at the byte just beyond the end of the partition table entry.
; We know there's nothing there we care about any more, so this
; is harmless.
;
; BP is the address of the active partition entry.
; AX and CX are currently zero.
;
StartLoad:
        mov     byte ptr [bp].UsingBackup,cl    ; not backup sector
        call    ReadSector
        jnc     CheckPbr
trybackup:
        inc     byte ptr [bp].UsingBackup
 
;
; Switch to backup sector for NTFS and FAT32.
;
if 0
;
; (tedm) for NTFS this code is actually worthless since other code,
; such as ntldr and the filesystem itself won't all do the right thing.
; For example the filesystem won't recognize the volume if sector 0
; can be read but is bad.
;
        cmp     byte ptr [bp].Part_Type,PART_IFS
        jne     tryfat32
;
; We assume here that type 7 is NTFS.
; Back up to end of partition by using the end CHS and subtracting 1
; from the sector #. There is no check for the case where we underflow
; and wrap a head -- it is assumed that partitions are at least head-aligned.
; There is also no check for the case where the start sector and sector count
; are both maxdword and so adding them overflows.
;
        mov     al,[bp].Part_EndHead    ; make start head same as end head
        mov     [bp].Part_StartHead,al
        mov     ax,[bp].Part_EndSector  ; ax = end sector and cylinder
        dec     al                      ; start sector = end sector minus 1
        mov     [bp].Part_StartSector,ax
        mov     ax,[bp].Part_SectorCount
        mov     dx,[bp].Part_SectorCountH
        add     [bp].Part_AbsoluteSector,ax
        adc     [bp].Part_AbsoluteSectorH,dx
        sub     word ptr [bp].Part_AbsoluteSector,1
        sbb     word ptr [bp].Part_AbsoluteSectorH,0
        jmp     short RestartLoad
endif
 
tryfat32:
        cmp     byte ptr [bp].Part_Type,PART_FAT32
        je      fat32backup
        cmp     byte ptr [bp].Part_Type,PART_FAT32_XINT13
        je      fat32backup
        mov     al,byte ptr [m2]        ; unknown fs, so no backup sector
        jne     display_msg
 
fat32backup:
;
; There is no check for the case where adding to the sector value
; in the start CHS overflows and wraps to the next head. It is assumed
; that partitions are at least head-aligned and that hard drives have
; at least FAT32_BACKUP+1 sectors per track.
;
        add     byte ptr [bp].Part_StartSector,FAT32_BACKUP
        add     word ptr [bp].Part_AbsoluteSector,FAT32_BACKUP
        adc     word ptr [bp].Part_AbsoluteSectorH,0
 
RestartLoad:
        call    ReadSector
        jnc     CheckPbr
        mov     al,byte ptr [m2]        ; can't load, we're done.
        jmp     short display_msg
 
CheckPbr:
        cmp     word ptr ds:[VOLBOOT_ORG + SIZE_SECTOR - 2],BOOTSECTRAILSIGH
        je      done
;
; Not a valid filesystem boot sector. Switch to backup if this
; isn't already the backup.
;
        cmp     byte ptr [bp].UsingBackup,0
        je      trybackup
        mov     al,byte ptr [m3]
        jmp     short display_msg
 
;
; Jump to PBR. We pass a pointer to the table entry that booted us
; in bp. If we used the backup boot sector, then that table entry
; will have been altered, but neither NTFS not FAT32 use the pointer
; in BP, and no other fs type will have been loaded via the backup
; boot sector, so this isn't an issue.
;
done:
        mov     di,sp                   ; DI -> start of PBR
        push    ds                      ; prepare for RETF, which is
        push    di                      ; smaller than JMP 0:VOLBOOT_ORG
        mov     si,bp                   ; pass boot partition table entry address
        retf                            ; start executing PBR
 
 
ReadSector proc near
 
        mov     di,5                    ; retry count
;
; Calculate the maximum sector # that can be addressed via
; conventional int13. Note that the max # of heads is 256
; and the maximum # of sectors per track is 63. Thus the maximum
; # of sectors per cylinder is something less than a 16-bit quantity.
;
        mov     dl,[bp].Part_Active     ;
        mov     ah,8                    ; get disk params
        int     13h
        jc      nonxint13               ; strange case, fall back to std int13
 
        mov     al,cl
        and     al,3fh                  ; al = # of sectors per track
        cbw                             ; ax = # of sectors per track (ah=0)
 
        mov     bl,dh                   ; bl = max head # (0-based)
        mov     bh,ah                   ; bh = 0
        inc     bx                      ; bx = # of heads
 
        mul     bx                      ; ax = sectors per cylinder, dx = 0
 
        mov     dx,cx                   ; dx = cylinder/sector in int13 format
        xchg    dl,dh                   ; dl = low 8 bits of cylinder
        mov     cl,6
        shr     dh,cl                   ; dx = max cylinder # (0-based)
        inc     dx                      ; dx = # cylinders
 
        mul     dx                      ; dx:ax = # sectors visible via int13
 
;
; If the sector # we're reading is less than the than number of
; addressable sectors, use conventional int 13
;
        cmp     [bp].Part_AbsoluteSectorH,dx
        ja      xint13
        jb      nonxint13
        cmp     [bp].Part_AbsoluteSector,ax
        jae     xint13
 
nonxint13:
        mov     ax,201h
        mov     bx,VOLBOOT_ORG          ; es:bx = read address (0:7c00)
        mov     cx,[bp].Part_StartSector
        mov     dx,[bp].Part_Active
        int     13h
        jnc     endread
        dec     di                      ; retry? (does not affect carry)
        jz      endread                 ; carry set for return
        xor     ah,ah                   ; ah = 0 (reset disk system)
        mov     dl,[bp].Part_Active     ; dl = int13 unit #
        int     13h
        jmp     short nonxint13
 
xint13:
;
; We want to avoid calling xint13 unless we know it's available
; since we don't trust all BIOSes to not hang if we attempt an xint13 read.
; If xint13 isn't supported we won't be able to boot, but at least
; we'll give an error message instead of just a black screen.
;
        mov     dl,[bp].Part_Active     ; unit #
.286
        pusha
        mov     bx,055AAh               ; signature
        mov     ah,41h                  ; perform X13 interrogation
        int     13h                     ;
        jc      endread1                ; call failed
        cmp     bx,0AA55h               ; did our signature get flipped?
        jne     endread1                ; no
        test    cl,1                    ; is there X13 support?
        jz      endread1                ; no
        popa
 
doxint13:
        pusha                           ; save regs
        push    0                       ; push dword of 0
        push    0                       ; (high 32 bits of sector #)
        push    [bp].Part_AbsoluteSectorH
        push    [bp].Part_AbsoluteSector ; low 32 bits of sector #
        push    0
        push    VOLBOOT_ORG             ; transfer address
        push    1                       ; 1 sector
        push    16                      ; packet size and reserved byte
 
        mov     ah,42h                  ; extended read
        mov     si,sp                   ; ds:si points to parameter packet
        int     13h                     ; dl already set from above
 
        popa                            ; pop param packet off stack
        popa                            ; get real registers back
        jnc     endread
        dec     di                      ; retry? (does not affect carry)
        jz      endread                 ; carry set for return
        xor     ah,ah                   ; ah = 0 (reset disk system)
        mov     dl,[bp].Part_Active     ; dl = int13 unit #
        int     13h
        jmp     short doxint13
 
endread1:
        popa
        stc                             ; this is the error case
.8086
endread:
        ret
ReadSector endp
 
;
; Message table.
;
; We put English messages here as a placeholder only, so that in case
; anyone uses bootmbr.h without patching new messages in, things will
; still be correct (in English, but at least functional).
;
_m1:    db      "Invalid partition table",0
_m2:    db      "Error loading operating system",0
_m3:    db      "Missing operating system",0
 
;
; Now build a table with the low byte of the offset to each message.
; Code that patches the boot sector messages updates this table.
;
        .errnz  ($ - start) GT MBR_MSG_TABLE_OFFSET
        org     RELOCATION_ORG + MBR_MSG_TABLE_OFFSET
 
m1:     db (OFFSET _m1 - RELOCATION_ORG) - 256
m2:     db (OFFSET _m2 - RELOCATION_ORG) - 256
m3:     db (OFFSET _m3 - RELOCATION_ORG) - 256
 
 
        .errnz  ($ - start) NE MBR_NT_OFFSET
        dd      0                       ; NT disk administrator signature
        dw      0
 
        .errnz  ($ - start) GT PART_TAB_OFF
 
        org     RELOCATION_ORG + PART_TAB_OFF
tab:                            ;partition table
        dw      0,0             ;partition 1 begin
        dw      0,0             ;partition 1 end
        dw      0,0             ;partition 1 relative sector (low, high parts)
        dw      0,0             ;partition 1 # of sectors (low, high parts)
        dw      0,0             ;partition 2 begin
        dw      0,0             ;partition 2 end
        dw      0,0             ;partition 2 relative sector
        dw      0,0             ;partition 2 # of sectors
        dw      0,0             ;partition 3 begin
        dw      0,0             ;partition 3 end
        dw      0,0             ;partition 3 relative sector
        dw      0,0             ;partition 3 # of sectors
        dw      0,0             ;partition 4 begin
        dw      0,0             ;partition 4 end
        dw      0,0             ;partition 4 relative sector
        dw      0,0             ;partition 4 # of sectors
 
    .errnz  ($ - tab)   NE (SIZE_PART_TAB_ENT * NUM_PART_TAB_ENTS)
    .errnz  ($ - start) NE (SIZE_SECTOR - 2)
 
signa   dw      BOOTSECTRAILSIGH ;signature
 
    .errnz  ($ - start) NE SIZE_SECTOR
 
_data   ends
 
        end start100

This is the bootmbr.h file, this is also part of the boot process.

bootmbr.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
#define X86BOOTCODE_SIZE 512
 
 
unsigned char x86BootCode[] = {
51,192,142,208,188,0,124,251,80,7,80,31,252,190,27,124,
191,27,6,80,87,185,229,1,243,164,203,189,190,7,177,4,
56,110,0,124,9,117,19,131,197,16,226,244,205,24,139,245,
131,198,16,73,116,25,56,44,116,246,160,181,7,180,7,139,
240,172,60,0,116,252,187,7,0,180,14,205,16,235,242,136,
78,16,232,70,0,115,42,254,70,16,128,126,4,11,116,11,
128,126,4,12,116,5,160,182,7,117,210,128,70,2,6,131,
70,8,6,131,86,10,0,232,33,0,115,5,160,182,7,235,
188,129,62,254,125,85,170,116,11,128,126,16,0,116,200,160,
183,7,235,169,139,252,30,87,139,245,203,191,5,0,138,86,
0,180,8,205,19,114,35,138,193,36,63,152,138,222,138,252,
67,247,227,139,209,134,214,177,6,210,238,66,247,226,57,86,
10,119,35,114,5,57,70,8,115,28,184,1,2,187,0,124,
139,78,2,139,86,0,205,19,115,81,79,116,78,50,228,138,
86,0,205,19,235,228,138,86,0,96,187,170,85,180,65,205,
19,114,54,129,251,85,170,117,48,246,193,1,116,43,97,96,
106,0,106,0,255,118,10,255,118,8,106,0,104,0,124,106,
1,106,16,180,66,139,244,205,19,97,97,115,14,79,116,11,
50,228,138,86,0,205,19,235,214,97,249,195,73,110,118,97,
108,105,100,32,112,97,114,116,105,116,105,111,110,32,116,97,
98,108,101,0,69,114,114,111,114,32,108,111,97,100,105,110,
103,32,111,112,101,114,97,116,105,110,103,32,115,121,115,116,
101,109,0,77,105,115,115,105,110,103,32,111,112,101,114,97,
116,105,110,103,32,115,121,115,116,101,109,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,44,68,99,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,170
};

And finally, this is the Assembler code to boot an NTFS filesystem.

ntfsboot.asm
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
        page    ,132
        title   ntfsboot - NTFS boot loader
        name    ntfsboot
 
; The ROM in the IBM PC starts the boot process by performing a hardware
; initialization and a verification of all external devices.  If all goes
; well, it will then load from the boot drive the sector from track 0, head 0,
; sector 1.  This sector is placed at physical address 07C00h.
;
; The boot code's sole resposiblity is to find NTLDR, load it at
; address 2000:0000, and then jump to it.
;
; The boot code understands the structure of the NTFS root directory,
; and is capable of reading files.  There is no contiguity restriction.
;
; DEBUG EQU 1
MASM    equ     1
        .xlist
        .286
 
A_DEFINED EQU 1
 
    include ntfs.inc
 
DoubleWord      struc
lsw     dw      ?
msw     dw      ?
DoubleWord      ends
 
;
; The following are various segments used by the boot loader. The first
; two are the segments where the boot sector is initially loaded and where
; the boot sector is relocated to.  The third is the static location
; where the NTLDR is loaded.
;
 
BootSeg segment at 07c0h        ; this is where the MBR loads us initially.
BootSeg ends
 
NewSeg  segment at 0d00h        ; this is where we'll relocate to.
NewSeg  ends                    ; enough for 16 boot sectors +
                                ;       4-sector scratch
                                ; below where we'll load NTLDR.
 
LdrSeg segment at 2000h         ; we want to load the loader at 2000:0000
LdrSeg ends
 
;/********************** START OF SPECIFICATIONS ************************/
;/*                                                                     */
;/* SUBROUTINE NAME: ntfsboot                                           */
;/*                                                                     */
;/* DESCRIPTIVE NAME: Bootstrap loader                                  */
;/*                                                                     */
;/* FUNCTION:    To load NTLDR into memory.                             */
;/*                                                                     */
;/* NOTES:       ntfsboot is loaded by the ROM BIOS (Int 19H) at        */
;/*              physical memory location 0000:7C00H.                   */
;/*              ntfsboot runs in real mode.                            */
;/*              This boot record is for NTFS volumes only.             */
;/*                                                                     */
;/* ENTRY POINT: ntfsboot                                               */
;/* LINKAGE:     Jump (far) from Int 19H                                */
;/*                                                                     */
;/* INPUT:       CS:IP = 0000:7C00H                                     */
;/*              SS:SP = 0030:00FAH (CBIOS dependent)                   */
;/*                                                                     */
;/* EXIT-NORMAL: DL = INT 13 drive number we booted from                */
;/*              Jmp to main in NTLDR                                   */
;/*                                                                     */
;/* EXIT-ERROR:  None                                                   */
;/*                                                                     */
;/* EFFECTS:     NTLDR is loaded into the physical memory               */
;/*                location 00020000H                                   */
;/*                                                                     */
;/*********************** END OF SPECIFICATIONS *************************/
BootCode segment        ;would like to use BootSeg here, but LINK flips its lid
        assume  cs:BootCode,ds:nothing,es:nothing,ss:nothing
 
        org     0               ; start at beginning of segment, not 0100h.
 
        public  _ntfsboot
_ntfsboot label near
        jmp     start
    .errnz  ($-_ntfsboot) GT (3)        ;<FATAL PROBLEM: JMP is more than three bytes>
 
    org 3
 
Version                 db      "NTFS    "      ; Signature, must be "NTFS    "
BPB                     label   byte
BytesPerSector          dw      512             ; Size of a physical sector
SectorsPerCluster       db      1               ; Sectors per allocation unit
 
;
; Traditionally the next 7 bytes were the reserved sector count, fat count,
; root dir entry count, and the small volume sector count. However all of
; these fields must be 0 on NTFS volumes.
;
; We use this space to store some temporary variables used by the boot code,
; which avoids the need for separate space in sector 0 to store them.
; We also take advantage of the free 0-initialization to save some space
; by avoiding the code to initialize them.
;
; Note that ideally we'd want to use an unused field for the SectorCount
; and initialize it to 16. This would let us save a few bytes by avoiding
; code to explicitly initialize this value before we read the 16 boot sectors.
; However setup and other code tends to preserve the entire bpb area when
; it updates boot code, so we avoid a dependency here and initialize
; the value explicitly to 16 in the first part of the boot code.
;
SectorCount             dw      0               ; number of sectors to read
SectorBase              dd      0               ; start sector for read request
HaveXInt13              db      0               ; extended int13 available flag
 
Media                   db      0f8h            ; Media byte
FatSectors              dw      0               ; (always 0 on NTFS)
SectorsPerTrack         dw      0               ; Sectors per track
Heads                   dw      0               ; Number of surfaces
HiddenSectors           dd      0               ; partition start LBA
 
;
; The field below is traditionally the large sector count and is
; always 0 on NTFS. We use it here for a value the boot code calculates,
; namely the number of sectors visible on the drive via conventional int13.
;
Int13Sectors            dd      0
 
DriveNumber             db      80h             ; int13 unit number
 
                        db      3 dup (?)       ; alignment filler
 
;
; The following is the rest of the NTFS Sector Zero information.
; The offsets of most of these fields cannot be changed without changing
; all code that validates, formats, recognizes, etc, NTFS volumes.
; In other words, don't change it.
;
SectorsOnVolume         db (size LARGE_INTEGER) dup (?)
MftStartLcn             db (size LARGE_INTEGER) dup (?)
Mft2StartLcn            db (size LARGE_INTEGER) dup (?)
ClustersPerFrs          dd ?
DefClustersPerBuf       dd ?
SerialNumber            db (size LARGE_INTEGER) dup (?)
CheckSum                dd ?
 
;
; Make sure size of fields matches what fs_rec.sys thinks is should be
;
        .errnz          ($-_ntfsboot) NE (54h)
 
;****************************************************************************
start:
;
;       First of all, set up the segments we need (stack and data).
;
        cli
        xor     ax,ax                   ; Set up the stack to just before
        mov     ss,ax                   ; this code.  It'll be moved after
        mov     sp,7c00h                ; we relocate.
        sti
 
        mov     ax,Bootseg              ; Address BPB with DS.
        mov     ds,ax
        assume  ds:BootCode
 
        call    Int13SecCnt             ; determine range of regular int13
 
;
; Read bootcode and jump to code in sector 1.
; Assumes HaveXInt13 and SectorBase are initialized to 0,
; which they are since they are stored in areas of the BPB
; that must be 0 on NTFS volumes.
;
        mov     ax,NewSeg
        mov     es,ax
        xor     bx,bx                   ; es:bx = transfer address
 
        mov     byte ptr SectorCount,16 ; word field is 0 on-disk so byte init is OK
        call    ReadSectors
 
        push    NewSeg
        push    offset mainboot
        retf
 
;
; Determine the number of sectors addressable via
; conventional int13. If we can't get drive params for some reason
; then something is very wrong -- we'll try to force the caller
; to use conventional int13 by maxing out the sector count.
;
; Input: ds addresses start of first sector
;
; Output: in eax; also stored in Int13Sectors variable.
;
; Preserves: assume none.
;
Int13SecCnt proc near
        mov     dl,DriveNumber          ; int13 unit number
        mov     ah,8                    ; get drive params
        int     13h                     ; call BIOS
        jnc     @f                      ; no error, procede
        mov     cx,-1                   ; strange case, fake registers to force
        mov     dh,cl                   ; use of standard int13 (set all vals to max)
@@:
.386
        movzx   eax,dh                  ; eax = max head # (0-255)
        inc     ax                      ; eax = heads (1-256)
        movzx   edx,cl                  ; edx = sectors per track + cyl bits
        and     dl,3fh                  ; edx = sectors per track (1-63)
        mul     dx                      ; eax = sectors per cylinder, edx = 0
        xchg    cl,ch
        shr     ch,6                    ; cx = max cylinder # (0-1023)
        inc     cx                      ; cx = cylinders (1-1024)
        movzx   ecx,cx                  ; ecx = cylinders (1-1024)
        mul     ecx                     ; eax = sectors visible via int13, edx = 0
        mov     Int13Sectors,eax        ; save # sectors addressable via int13
.286
        ret
Int13SecCnt endp
 
;
; Determine whether extended int13 services are available on the boot drive.
;
; Stores result (boolean) in HaveXInt13 variable.
;
; Preserves: assume none.
;
HaveInt13Ext proc near
        mov     ah,41h
        mov     bx,055aah
        mov     dl,DriveNumber
        int     13h
        jc      @f                      ; error from int13 means no xint13
        cmp     bx,0aa55h               ; absence of sig means no xint13
        jne     @f
        test    cl,1                    ; bit 0 off means no xint13
        jz      @f
        inc     byte ptr HaveXInt13     ; xint13 is available
@@:     ret
HaveInt13Ext endp
 
 
;
; Read SectorCount sectors starting at logical sector SectorBase,
; into es:bx, using extended int13 if necessary.
;
; Preserves all
;
ReadSectors proc near
.386
        pushad                          ; save registers
        push    ds
        push    es
 
read_loop:
        mov     eax,SectorBase          ; logical starting sector
        add     eax,HiddenSectors       ; eax = physical starting sector
        cmp     eax,Int13Sectors        ; determine if standard int13 is ok
        jb      stdint13
 
        push    ds                      ; preserve ds
 
        db      66h                     ; hand-coded 32-bit push of 8-bit immediate
        push    0                       ; high 32 bits of sector #
        push    eax                     ; low 32 bits of sector #
        push    es
        push    bx                      ; transfer address
        push    dword ptr 10010h        ; transfer 1 sector, packet size = 16
 
        cmp     byte ptr HaveXInt13,0
        jne     @f                      ; already know we have xint13 available
        call    HaveInt13Ext            ; see if we have it
        cmp     byte ptr HaveXInt13,0
 
        je      BootErr$he              ; need it but don't have it
 
@@:     mov     ah,42h                  ; extended read
        mov     dl,DriveNumber          ; dl = int13 unit #
        push    ss
        pop     ds
        mov     si,sp                   ; ds:si -> param packet
 
        int     13h
 
        pop     eax                     ; throw away first 4 bytes of param packet
        pop     bx                      ; restore es:bx from param packet
        pop     es
        pop     eax                     ; throw away last 8 bytes of param packet
        pop     eax                     ; without clobbering carry flag
 
        pop     ds                      ; restore ds
 
        jmp     short did_read
 
stdint13:
        xor     edx,edx                 ; edx:eax = absolute sector number
        movzx   ecx,SectorsPerTrack     ; ecx = sectors per track
        div     ecx                     ; eax = track, edx = sector within track (0-62)
        inc     dl                      ; dl = sector within track (1-63)
        mov     cl,dl                   ; cl = sector within track
        mov     edx,eax
        shr     edx,16                  ; dx:ax = track
        div     Heads                   ; ax = cylinder (0-1023), dx = head (0-255)
        xchg    dl,dh                   ; dh = head
        mov     dl,DriveNumber          ; dl = int13 unit #
        mov     ch,al                   ; ch = bits 0-7 of cylinder
        shl     ah,6
        or      cl,ah                   ; bits 6-7 of cl = bits 8-9 of cylinder
        mov     ax,201h                 ; read 1 sector
        int     13h
did_read:
        jc      BootErr$he
 
read_next:
        mov     ax,es                   ; advance transfer address
        add     ax,20h                  ; by moving segment register along
        mov     es,ax                   ; thus no 64K limit on transfer length
 
        inc     SectorBase              ; advance sector number
        dec     SectorCount             ; see if done
        jnz     read_loop               ; not done
 
        pop     es
        pop     ds
        popad                           ; restore registers
.286
        ret
ReadSectors endp
 
BootErr$he:
 
        mov     al,byte ptr TXT_MSG_SYSINIT_BOOT_ERROR
BootErr2:
 
        call    BootErr$print
        mov     al,byte ptr TXT_MSG_SYSINIT_REBOOT
        call    BootErr$print
        sti
        jmp     $                       ; Wait forever
 
BootErr$print:
;
; al is offset - 256 of message. Adjust to form real offset
; and stick in si so lodsb below will work.
;
        mov     ah,1
        mov     si,ax
 
BootErr$print1:
        lodsb                           ; Get next character
        cmp     al,0
        je      BootErr$Done
        mov     ah,14                   ; Write teletype
        mov     bx,7                    ; Attribute
        int     10h                     ; Print it
        jmp     BootErr$print1
BootErr$Done:
        ret
 
;****************************************************************************
 
;
; Message table.
;
; We put English messages here as a placeholder only, so that in case
; anyone uses bootntfs.h without patching new messages in, things will
; still be correct (in English, but at least functional).
;
MSG_SYSINIT_BOOT_ERROR:
 
        DB      13,10,'A disk read error occurred',0
 
MSG_SYSINIT_FILE_NOT_FD:
 
        DB      13,10,'NTLDR is missing',0
 
MSG_SYSINIT_NTLDR_CMPRS:
 
        DB      13,10,'NTLDR is compressed',0
 
MSG_SYSINIT_REBOOT:
 
        DB      13,10,'Press Ctrl+Alt+Del to restart',13,10,0
 
;
; Now build a table with the low byte of the offset to each message.
; Code that patches the boot sector messages updates this table.
;
        .errnz ($-_ntfsboot) GT (512-8)
        ORG     512 - 8
TXT_MSG_SYSINIT_BOOT_ERROR:
        db OFFSET (MSG_SYSINIT_BOOT_ERROR - _ntfsboot) - 256
TXT_MSG_SYSINIT_FILE_NOT_FD:
        db OFFSET (MSG_SYSINIT_FILE_NOT_FD - _ntfsboot) - 256
TXT_MSG_SYSINIT_NTLDR_CMPRS:
        db OFFSET (MSG_SYSINIT_NTLDR_CMPRS - _ntfsboot) - 256
TXT_MSG_SYSINIT_REBOOT:
        db OFFSET (MSG_SYSINIT_REBOOT - _ntfsboot) - 256
 
        .errnz ($-_ntfsboot) NE (512-4)
        db      0,0,55h,0aah
 
;   Name we look for.  ntldr_length is the number of characters,
;   ntldr_name is the name itself.  Note that it is not NULL
;   terminated, and doesn't need to be.
;
ntldr_name_length   dw  5
 
ntldr_name          dw  'N', 'T', 'L', 'D', 'R'
 
;   Predefined name for index-related attributes associated with an
;   index over $FILE_NAME
;
index_name_length   dw 4
index_name          dw '$', 'I', '3', '0'
 
;   Global variables.  These offsets are all relative to NewSeg.
;
AttrList            dd 0e000h   ; Offset of buffer to hold attribute list
MftFrs              dd  3000h   ; Offset of general scratch buffer for FRS
SegmentsInMft       dd   ?      ; number of FRS's with MFT Data attribute records
RootIndexFrs        dd   ?      ; Offset of Root Index FRS
AllocationIndexFrs  dd   ?      ; Offset of Allocation Index FRS        ; KPeery
BitmapIndexFrs      dd   ?      ; Offset of Bitmap Index FRS            ; KPeery
IndexRoot           dd   ?      ; Offset of Root Index $INDEX_ROOT attribute
IndexAllocation     dd   ?      ; Offset of Root Index $INDEX_ALLOCATION attribute
IndexBitmap         dd   ?      ; Offset of Root Index $BITMAP attribute
NtldrFrs            dd   ?      ; Offset of NTLDR FRS
NtldrData           dd   ?      ; Offset of NTLDR $DATA attribute
IndexBlockBuffer    dd   ?      ; Offset of current index buffer
IndexBitmapBuffer   dd   ?      ; Offset of index bitmap buffer
NextBuffer          dd   ?      ; Offset of next free byte in buffer space
 
BytesPerCluster     dd   ?      ; Bytes per cluster
BytesPerFrs         dd   ?      ; Bytes per File Record Segment
 
;
; For floppyless booting, winnt32.exe creates c:\$win_nt$.~bt\bootsec.dat and
; places an entry in boot.ini for it (the boot selection says something
; like "Windows NT Setup or Upgrade"). When that is selected, the boot loader
; loads 16 sectors worth of data from bootsect.dat into d000 (which is where
; the first sector of this code would have loaded it) and jumps into it at
; a known location of 256h. That was correct in earlier versions of NT
; but is not correct now because the 4 fields below were added to this sector.
;
; Note that 0000 is "add [bx+si],al" which because of the way the boot loader
; is written happens to be a benign add of 0 to something in segment 7c0,
; which doesn't seem to hose anything but is still somewhat random.
;
; We code in a jump here so as this new code proliferates we get this
; cleaned up.
;
        .errnz  $-_ntfsboot ne 256h
SectorsPerFrs label dword       ; Sectors per File Record Segment
                    jmp short mainboot
                    nop
                    nop
        .errnz  $-_ntfsboot ne 25ah
 
MftLcnFrs               dd  ?   ; Offset scratch FRS buffer for LookupMftLcn
BytesPerIndexBlock      dd  ?   ; Bytes per index alloc block in root index
ClustersPerIndexBlock   dd  ?   ; Clusters per index alloc block in root index
SectorsPerIndexBlock    dd  ?   ; Sectors per index block in root index
 
.386
 
SAVE_ALL    macro
 
    push    es
    push    ds
    pushad
 
endm
 
RESTORE_ALL macro
 
    popad
    nop
    pop     ds
    pop     es
 
endm
 
 
;****************************************************************************
;
; mainboot - entry point after 16 boot sectors have been read in
;
;
mainboot proc   far
 
;       Get the new ds and the new stack.  Note that ss is zero.
;
        mov     ax, cs                  ; Set DS to CS
        mov     ds, ax
 
        shl     ax, 4                   ; convert to an offset.
        cli
        mov     sp, ax                  ; load new stack, just before boot code.
        sti
 
;
; Reinitialize xint13-related variables
;
        call    Int13SecCnt             ; determine range of regular int13
 
;       Set up the FRS buffers.  The MFT buffer is in a fixed
;       location, and the other three come right after it.  The
;       buffer for index allocation blocks comes after that.
;
 
;       Compute the useful constants associated with the volume
;
        movzx   eax, BytesPerSector     ; eax = Bytes per Sector
        movzx   ebx, SectorsPerCluster  ; ebx = Sectors Per Cluster
        mul     ebx                     ; eax = Bytes per Cluster
        mov     BytesPerCluster, eax
 
        mov     ecx, ClustersPerFrs     ; ecx = clusters per frs
        cmp     cl, 0                   ; is ClustersPerFrs less than zero?
        jg      mainboot$1
 
;       If the ClustersPerFrs field is negative, we calculate the number
;       of bytes per FRS by negating the value and using that as a shif count.
;
 
        neg     cl
        mov     eax, 1
        shl     eax, cl                 ; eax = bytes per frs
        jmp     mainboot$2
 
mainboot$1:
 
;       Otherwise if ClustersPerFrs was positive, we multiply by bytes
;       per cluster.
 
        mov     eax, BytesPerCluster
        mul     ecx                     ; eax = bytes per frs
 
mainboot$2:
 
        mov     BytesPerFrs, eax
        movzx   ebx, BytesPerSector
        xor     edx, edx                ; zero high part of dividend
        div     ebx                     ; eax = sectors per frs
        mov     SectorsPerFrs, eax
 
 
;       Set up the MFT FRS's---this will read all the $DATA attribute
;       records for the MFT.
;
 
        call    SetupMft
 
;       Set up the remaining FRS buffers.  The RootIndex FRS comes
;       directly after the last MFT FRS, followed by the NTLdr FRS
;       and the Index Block buffer.
;
        mov     ecx, NextBuffer
        mov     RootIndexFrs, ecx
 
        add     ecx, BytesPerFrs            ; AllocationFrs may be different
        mov     AllocationIndexFrs, ecx     ; from RootIndexFrs - KPeery
 
        add     ecx, BytesPerFrs            ; BitmapFrs may be different
        mov     BitmapIndexFrs, ecx         ; from RootIndexFrs - KPeery
 
        add     ecx, BytesPerFrs
        mov     NtldrFrs, ecx
 
        add     ecx, BytesPerFrs
        mov     IndexBlockBuffer, ecx
 
;
;       Read the root index, allocation index and bitmap FRS's and locate
;       the interesting attributes.
;
 
        mov     eax, $INDEX_ROOT
        mov     ecx, RootIndexFrs
        call    LoadIndexFrs
 
        or      eax, eax
 
        jz      BootErr$he
 
        mov     IndexRoot, eax          ; offset in Frs buffer
 
        mov     eax, $INDEX_ALLOCATION  ; Attribute type code
        mov     ecx, AllocationIndexFrs ; FRS to search
        call    LoadIndexFrs
 
        mov     IndexAllocation, eax
 
        mov     eax, $BITMAP            ; Attribute type code
        mov     ecx, BitmapIndexFrs     ; FRS to search
        call    LoadIndexFrs
 
        mov     IndexBitmap, eax
 
;       Consistency check: the index root must exist, and it
;       must be resident.
;
        mov     eax, IndexRoot
        or      eax, eax
 
        jz      BootErr$he
 
        cmp     [eax].ATTR_FormCode, RESIDENT_FORM
 
        jne     BootErr$he
 
 
;       Determine the size of the index allocation buffer based
;       on information in the $INDEX_ROOT attribute.  The index
;       bitmap buffer comes immediately after the index block buffer.
;
;       eax -> $INDEX_ROOT attribute record
;
        lea     edx, [eax].ATTR_FormUnion   ; edx -> resident info
        add     ax, [edx].RES_ValueOffset   ; eax -> value of $INDEX_ROOT
 
        movzx   ecx, [eax].IR_ClustersPerBuffer
        mov     ClustersPerIndexBlock, ecx
 
        mov     ecx, [eax].IR_BytesPerBuffer
        mov     BytesPerIndexBlock, ecx
 
        mov     eax, BytesPerIndexBlock
        movzx   ecx, BytesPerSector
        xor     edx, edx
        div     ecx                     ; eax = sectors per index block
        mov     SectorsPerIndexBlock, eax
 
        mov     eax, IndexBlockBuffer
        add     eax, BytesPerIndexBlock
        mov     IndexBitmapBuffer, eax
 
;       Next consistency check: if the $INDEX_ALLOCATION attribute
;       exists, the $INDEX_BITMAP attribute must also exist.
;
        cmp     IndexAllocation, 0
        je      mainboot30
 
        cmp     IndexBitmap, 0          ; since IndexAllocation exists, the
 
        je      BootErr$he              ;  bitmap must exist, too.
 
;       Since the bitmap exists, we need to read it into the bitmap
;       buffer.  If it's resident, we can just copy the data.
;
 
        mov     ebx, IndexBitmap        ; ebx -> index bitmap attribute
        push    ds
        pop     es
        mov     edi, IndexBitmapBuffer  ; es:edi -> index bitmap buffer
 
        call    ReadWholeAttribute
 
mainboot30:
;
;       OK, we've got the index-related attributes.
;
        movzx   ecx, ntldr_name_length  ; ecx = name length in characters
        mov     eax, offset ntldr_name  ; eax -> name
 
        call    FindFile
 
        or      eax, eax
        jz      BootErr$fnf
 
;       Read the FRS for NTLDR and find its data attribute.
;
;       eax -> Index Entry for NTLDR.
;
        mov     eax, [eax].IE_FileReference.REF_LowPart
 
        push    ds
        pop     es              ; es:edi = target buffer
        mov     edi, NtldrFrs
 
        call    ReadFrs
 
        mov     eax, NtldrFrs   ; pointer to FRS
        mov     ebx, $DATA      ; requested attribute type
        mov     ecx, 0          ; attribute name length in characters
        mov     edx, 0          ; attribute name (NULL if none)
 
        call    LocateAttributeRecord
 
;       eax -> $DATA attribute for NTLDR
;
        or      eax, eax        ; if eax is zero, attribute not found.
        jnz     mainboot$FoundData
 
;
;       The ntldr $DATA segment is fragmented.  Search the attribute list
;       for the $DATA member.  And load it from there.
;
        mov     ecx, $DATA             ; Attribute type code
        mov     eax, NtldrFrs          ; FRS to search
 
        call    SearchAttrList         ; search attribute list for FRN
                                       ; of specified ($DATA)
 
        or      eax, eax               ; if eax is zero, attribute not found.
        jz      BootErr$fnf
 
;
;       We found the FRN of the $DATA attribute; load that into memory.
;
        push    ds
        pop     es                     ; es:edi = target buffer
        mov     edi, NtldrFrs
 
        call    ReadFrs
 
;
;       Determine the beginning offset of the $DATA in the FRS
;
        mov     eax, NtldrFrs   ; pointer to FRS
        mov     ebx, $DATA      ; requested attribute type
        mov     ecx, 0          ; attribute name length in characters
        mov     edx, 0          ; attribute name (NULL if none)
 
        call    LocateAttributeRecord
 
;       eax -> $DATA attribute for NTLDR
;
        or      eax, eax        ; if eax is zero, attribute not found.
        jz      BootErr$fnf
 
mainboot$FoundData:
 
;       Get the attribute record header flags, and make sure none of the
;       `compressed' bits are set
 
        movzx   ebx, [eax].ATTR_Flags
        and     ebx, ATTRIBUTE_FLAG_COMPRESSION_MASK
        jnz     BootErr$ntc
 
        mov     ebx, eax        ; ebx -> $DATA attribute for NTLDR
 
        push    LdrSeg
        pop     es              ; es = segment addres to read into
        sub     edi, edi        ; es:edi = buffer address
 
        call    ReadWholeAttribute
 
;
; We've loaded NTLDR--jump to it.
;
; Before we go to NTLDR, set up the registers the way it wants them:
;       DL = INT 13 drive number we booted from
;
        mov     dl, DriveNumber
        mov     ax,1000
        mov     es, ax                  ; we don't really need this
        lea     si, BPB
        sub     ax,ax
        push    LdrSeg
        push    ax
        retf                            ; "return" to NTLDR.
 
mainboot endp
 
.386
;****************************************************************************
;
;   ReadClusters - Reads a run of clusters from the disk.
;
;   ENTRY:  eax == LCN to read
;           edx == clusters to read
;           es:edi -> Target buffer
;
;   USES:   none (preserves all registers)
;
ReadClusters proc near
 
    SAVE_ALL
 
    mov     ebx, edx                ; ebx = clusters to read.
    movzx   ecx, SectorsPerCluster  ; ecx = cluster factor
 
    mul     ecx                 ; Convert LCN to sectors (wipes out edx!)
    mov     SectorBase, eax     ; Store starting sector in SectorBase
 
    mov     eax, ebx            ; eax = number of clusters
    mul     ecx                 ; Convert EAX to sectors (wipes out edx!)
    mov     SectorCount, ax     ; Store number of sectors in SectorCount
 
;
;   Note that ReadClusters gets its target buffer in es:edi but calls
;   the ReadSectors worker function that takes a target in es:bx--we need
;   to normalize es:edi so that we don't overflow bx.
;
    mov     bx, di
    and     bx, 0Fh
    mov     ax, es
    shr     edi, 4
    add     ax, di              ; ax:bx -> target buffer
 
    push    ax
    pop     es                  ; es:bx -> target buffer
 
    call    ReadSectors
 
    RESTORE_ALL
    ret
 
ReadClusters endp
 
;
;****************************************************************************
;
;   LocateAttributeRecord   --  Find an attribute record in an FRS.
;
;   ENTRY:  EAX -- pointer to FRS
;           EBX -- desired attribute type code
;           ECX -- length of attribute name in characters
;           EDX -- pointer to attribute name
;
;   EXIT:   EAX points at attribute record (0 indicates not found)
;
;   USES:   All
;
LocateAttributeRecord proc near
 
; get the first attribute record.
;
        add     ax, word ptr[eax].FRS_FirstAttribute
 
;       eax -> next attribute record to investigate.
;       ebx == desired type
;       ecx == name length
;       edx -> pointer to name
;
lar10:
        cmp     [eax].ATTR_TypeCode, 0ffffffffh
        je      lar99
 
        cmp     dword ptr[eax].ATTR_TypeCode, ebx
        jne     lar80
 
;       this record is a potential match.  Compare the names:
;
;       eax -> candidate record
;       ebx == desired type
;       ecx == name length
;       edx -> pointer to name
;
        or      ecx, ecx    ; Did the caller pass in a name length?
        jnz     lar20
 
;       We want an attribute with no name--the current record is
;       a match if and only if it has no name.
;
        cmp     [eax].ATTR_NameLength, 0
        jne     lar80       ; Not a match.
 
;       It's a match, and eax is set up correctly, so return.
;
        ret
 
;       We want a named attribute.
;
;       eax -> candidate record
;       ebx == desired type
;       ecx == name length
;       edx -> pointer to name
;
lar20:
        cmp     cl, [eax].ATTR_NameLength
        jne     lar80       ; Not a match.
 
;       Convert name in current record to uppercase.
;
        mov     esi, eax
        add     si, word ptr[eax].ATTR_NameOffset
 
        call    UpcaseName
 
;       eax -> candidate record
;       ebx == desired type
;       ecx == name length
;       edx -> pointer to name
;       esi -> Name in current record (upcased)
;
        push    ecx         ; save cx
 
        push    ds          ; Copy data segment into es
        pop     es
        mov     edi, edx    ; note that esi is already set up.
 
        repe cmpsw          ; zero flag is set if equal
 
        pop     ecx         ; restore cx
 
        jnz     lar80       ; not a match
 
;       eax points at a matching record.
;
        ret
 
;
;   This record doesn't match; go on to the next.
;
;       eax -> rejected candidate attribute record
;       ebx == desired type
;       ecx == Name length
;       edx -> desired name
;
lar80:  cmp     [eax].ATTR_RecordLength, 0  ; if the record length is zero
        je      lar99                       ; the FRS is corrupt.
 
        add     eax, [eax].ATTR_RecordLength; Go to next record
        jmp     lar10                       ; and try again
 
;       Didn't find it.
;
lar99:  sub     eax, eax
        ret
 
LocateAttributeRecord endp
 
;****************************************************************************
;
;   LocateIndexEntry   --  Find an index entry in a file name index
;
;   ENTRY:  EAX -> pointer to index header
;           EBX -> file name to find
;           ECX == length of file name in characters
;
;   EXIT:   EAX points at index entry.  NULL to indicate failure.
;
;   USES:   All
;
LocateIndexEntry proc near
 
;       Convert the input name to upper-case
;
 
        mov     esi, ebx
        call    UpcaseName
 
ifdef DEBUG
        call    PrintName
        call    Debug2
endif ; DEBUG
 
        add     eax, [eax].IH_FirstIndexEntry
 
;       EAX -> current entry
;       EBX -> file name to find
;       ECX == length of file name in characters
;
lie10:  test    [eax].IE_Flags, INDEX_ENTRY_END ; Is it the end entry?
        jnz     lie99
 
        lea     edx, [eax].IE_Value         ; edx -> FILE_NAME attribute value
 
ifdef DEBUG
;       DEBUG CODE -- list file names as they are examined
 
        SAVE_ALL
 
        call    Debug3
        movzx   ecx, [edx].FN_FileNameLength    ; ecx = chars in name
        lea     esi, [edx].FN_FileName          ; esi -> name
        call    PrintName
 
        RESTORE_ALL
endif ; DEBUG
 
;       EAX -> current entry
;       EBX -> file name to find
;       ECX == length of file name in characters
;       EDX -> FILE_NAME attribute
 
        cmp     cl, [edx].FN_FileNameLength ; Is name the right length?
        jne     lie80
 
        lea     esi, [edx].FN_FileName      ; Get name from FILE_NAME structure
 
        call    UpcaseName
 
        push    ecx         ; save ecx
 
        push    ds
        pop     es          ; copy data segment into es for cmpsw
        mov     edi, ebx    ; edi->search name (esi already set up)
        repe    cmpsw       ; zero flag is set if they're equal
 
        pop     ecx         ; restore ecx
 
        jnz     lie80
 
;       the current entry matches the search name, and eax points at it.
;
        ret
 
;       The current entry is not a match--get the next one.
;           EAX -> current entry
;           EBX -> file name to find
;           ECX == length of file name in characters
;
lie80:  cmp     [eax].IE_Length, 0      ; If the entry length is zero
        je      lie99                   ; then the index block is corrupt.
 
        add     ax, [eax].IE_Length     ; Get the next entry.
 
        jmp     lie10
 
 
;   Name not found in this block.  Set eax to zero and return
;
lie99:  xor     eax, eax
        ret
 
LocateIndexEntry endp
 
;****************************************************************************
;
;   ReadWholeAttribute - Read an entire attribute value
;
;   ENTRY:  ebx -> attribute
;           es:edi -> target buffer
;
;   USES:   ALL
;
ReadWholeAttribute proc near
 
        cmp     [ebx].ATTR_FormCode, RESIDENT_FORM
        jne      rwa10
 
;       The attribute is resident.
;       ebx -> attribute
;       es:edi -> target buffer
;
 
        SAVE_ALL
 
        lea     edx, [ebx].ATTR_FormUnion   ; edx -> resident form info
        mov     ecx, [edx].RES_ValueLength  ; ecx = bytes in value
        mov     esi, ebx                    ; esi -> attribute
        add     si, [edx].RES_ValueOffset   ; esi -> attribute value
 
        rep     movsb                       ; copy bytes from value to buffer
 
        RESTORE_ALL
 
        ret                                 ; That's all!
 
rwa10:
;
;       The attribute type is non-resident.  Just call
;       ReadNonresidentAttribute starting at VCN 0 and
;       asking for the whole thing.
;
;       ebx -> attribute
;       es:edi -> target buffer
;
        lea     edx, [ebx].ATTR_FormUnion   ; edx -> nonresident form info
        mov     ecx, [edx].NONRES_HighestVcn.LowPart; ecx = HighestVcn
        inc     ecx                         ; ecx = clusters in attribute
 
        sub     eax, eax                    ; eax = 0 (first VCN to read)
 
        call    ReadNonresidentAttribute
 
        ret
 
ReadWholeAttribute endp
 
;****************************************************************************
;
;   ReadNonresidentAttribute - Read clusters from a nonresident attribute
;
;   ENTRY:  EAX == First VCN to read
;           EBX -> Attribute
;           ECX == Number of clusters to read
;           ES:EDI == Target of read
;
;   EXIT:   None.
;
;   USES:   None (preserves all registers with SAVE_ALL/RESTORE_ALL)
;
ReadNonresidentAttribute proc near
 
        SAVE_ALL
 
        cmp     [ebx].ATTR_FormCode, NONRESIDENT_FORM
        je      ReadNR10
 
;       This attribute is not resident--the disk is corrupt.
 
        jmp     BootErr$he
 
ReadNR10:
;       eax == Next VCN to read
;       ebx -> Attribute
;       ecx -> Remaining clusters to read
;       es:edi -> Target of read
;
 
        cmp     ecx, 0
        jne     ReadNR20
 
;       Nothing left to read--return success.
;
        RESTORE_ALL
        ret
 
ReadNR20:
        push    ebx ; pointer to attribute
        push    eax ; Current VCN
 
        push    ecx
        push    edi
        push    es
 
        call    ComputeLcn  ; eax = LCN to read, ecx = run length
        mov     edx, ecx    ; edx = remaining run length
 
        pop     es
        pop     edi
        pop     ecx
 
 
;       eax == LCN to read
;       ecx == remaining clusters to read
;       edx == remaining clusters in current run
;       es:edi == Target of read
;       TOS == Current VCN
;       TOS + 4 == pointer to attribute
;
        cmp     ecx, edx
        jge     ReadNR30
 
;       Run length is greater than remaining request; only read
;       remaining request.
;
        mov     edx, ecx    ; edx = Remaining request
 
ReadNR30:
;       eax == LCN to read
;       ecx == remaining clusters to read
;       edx == clusters to read in current run
;       es:edi == Target of read
;       TOS == Current VCN
;       TOS +  == pointer to attribute
;
 
        call    ReadClusters
 
        sub     ecx, edx            ; Decrement clusters remaining in request
        mov     ebx, edx            ; ebx = clusters read
 
        mov     eax, edx            ; eax = clusters read
        movzx   edx, SectorsPerCluster
        mul     edx                 ; eax = sectors read (wipes out edx!)
        movzx   edx, BytesPerSector
        mul     edx                 ; eax = bytes read (wipes out edx!)
 
        add     edi, eax            ; Update target of read
 
        pop     eax                 ; eax = previous VCN
        add     eax, ebx            ; update VCN to read
 
        pop     ebx                 ; ebx -> attribute
        jmp     ReadNR10
 
 
ReadNonresidentAttribute endp
 
;****************************************************************************
;
;   ReadIndexBlockSectors - Read sectors from an index allocation attribute
;
;   ENTRY:  EAX == First VBN to read
;           EBX -> Attribute
;           ECX == Number of sectors to read
;           ES:EDI == Target of read
;
;   EXIT:   None.
;
;   USES:   None (preserves all registers with SAVE_ALL/RESTORE_ALL)
;
ReadIndexBlockSectors proc near
 
        SAVE_ALL
 
        cmp     [ebx].ATTR_FormCode, NONRESIDENT_FORM
        je      ReadIBS_10
 
;       This attribute is resident--the disk is corrupt.
 
        jmp     BootErr$he
 
ReadIBS_10:
;       eax == Next VBN to read
;       ebx -> Attribute
;       ecx -> Remaining sectors to read
;       es:edi -> Target of read
;
 
        cmp     ecx, 0
        jne     ReadIBS_20
 
;       Nothing left to read--return success.
;
 
 
        RESTORE_ALL
        ret
 
ReadIBS_20:
        push    ebx ; pointer to attribute
        push    eax ; Current VBN
 
        push    ecx
        push    edi
        push    es
 
        ; Convert eax from a VBN back to a VCN by dividing by SectorsPerCluster.
        ; The remainder of this division is the sector offset in the cluster we
        ; want.  Then use the mapping information to get the LCN for this VCN,
        ; then multiply to get back to LBN.
        ;
 
        push    ecx         ; save remaining sectors in request
 
        xor     edx, edx    ; zero high part of dividend
        movzx   ecx, SectorsPerCluster
        div     ecx         ; edx = remainder
        push    edx         ; save remainder
 
        call    ComputeLcn  ; eax = LCN to read, ecx = remaining run length
 
        movzx   ebx, SectorsPerCluster
        mul     ebx         ; eax = LBN of cluster, edx = 0
        pop     edx         ; edx = remainder
        add     eax, edx    ; eax = LBN we want
        push    eax         ; save LBN
 
        movzx   eax, SectorsPerCluster
        mul     ecx         ; eax = remaining run length in sectors, edx = 0
        mov     edx, eax    ; edx = remaining run length
 
        pop     eax         ; eax = LBN
        pop     ecx         ; ecx = remaining sectors in request
 
        pop     es
        pop     edi
        pop     ecx
 
 
;       eax == LBN to read
;       ecx == remaining sectors to read
;       edx == remaining sectors in current run
;       es:edi == Target of read
;       TOS == Current VCN
;       TOS + 4 == pointer to attribute
;
        cmp     ecx, edx
        jge     ReadIBS_30
 
;       Run length is greater than remaining request; only read
;       remaining request.
;
        mov     edx, ecx    ; edx = Remaining request
 
ReadIBS_30:
;       eax == LBN to read
;       ecx == remaining sectors to read
;       edx == sectors to read in current run
;       es:edi == Target of read
;       TOS == Current VCN
;       TOS +  == pointer to attribute
;
 
        mov     SectorBase, eax
        mov     SectorCount, dx
 
;       We have a pointer to the target buffer in es:edi, but we want that
;       in es:bx for ReadSectors.
;
 
        SAVE_ALL
 
        mov     bx, di
        and     bx, 0Fh
        mov     ax, es
        shr     edi, 4
        add     ax, di              ; ax:bx -> target buffer
 
        push    ax
        pop     es                  ; es:bx -> target buffer
 
        call    ReadSectors
 
        RESTORE_ALL
 
        sub     ecx, edx            ; Decrement sectors remaining in request
        mov     ebx, edx            ; ebx = sectors read
 
        mov     eax, edx            ; eax = sectors read
        movzx   edx, BytesPerSector
        mul     edx                 ; eax = bytes read (wipes out edx!)
 
        add     edi, eax            ; Update target of read
 
        pop     eax                 ; eax = previous VBN
        add     eax, ebx            ; update VBN to read
 
        pop     ebx                 ; ebx -> attribute
        jmp     ReadIBS_10
 
 
ReadIndexBlockSectors endp
 
 
;****************************************************************************
;
;   MultiSectorFixup - fixup a structure read off the disk
;                      to reflect Update Sequence Array.
;
;   ENTRY:  ES:EDI = Target buffer
;
;   USES:   none (preserves all registers with SAVE_ALL/RESTORE_ALL)
;
;   Note: ES:EDI must point at a structure which is protected
;         by an update sequence array, and which begins with
;         a multi-sector-header structure.
;
MultiSectorFixup proc near
 
    SAVE_ALL
 
    movzx   ebx, es:[edi].MSH_UpdateArrayOfs    ; ebx = update array offset
    movzx   ecx, es:[edi].MSH_UpdateArraySize   ; ecx = update array size
 
    or      ecx, ecx        ; if the size of the update sequence array
 
    jz      BootErr$he      ; is zero, this structure is corrupt.
 
    add     ebx, edi        ; es:ebx -> update sequence array count word
    add     ebx, 2          ; es:ebx -> 1st entry of update array
 
    add     edi, SEQUENCE_NUMBER_STRIDE - 2 ; es:edi->last word of first chunk
    dec     ecx             ; decrement to reflect count word
 
MSF10:
 
;   ecx = number of entries remaining in update sequence array
;   es:ebx -> next entry in update sequence array
;   es:edi -> next target word for update sequence array
 
    or      ecx, ecx
    jz      MSF30
 
    mov     ax, word ptr es:[ebx]   ; copy next update sequence array entry
    mov     word ptr es:[edi], ax   ; to next target word
 
    add     ebx, 2                      ; go on to next entry
    add     edi, SEQUENCE_NUMBER_STRIDE ; go on to next target
 
    dec     ecx
 
 
    jmp     MSF10
 
MSF30:
 
    RESTORE_ALL
 
    ret
 
MultiSectorFixup endp
 
;****************************************************************************
;
;   SetupMft - Reads MFT File Record Segments into the LBN array
;
;   ENTRY:  none.
;
;   EXIT:   NextBuffer is set to the free byte after the last MFT FRS
;           SegmentsInMft is initialized
;
;
SetupMft proc near
 
        SAVE_ALL
 
;       Initialize SegmentsInMft and NextBuffer as if the MFT
;       had only one FRS.
;
        mov     eax, 1
        mov     SegmentsInMft, eax
 
        mov     eax, MftFrs                     ; this is the scratch mft buffer
        add     eax, BytesPerFrs
        mov     MftLcnFrs,eax                   ; this is the scratch mft buffer for lookup
        add     eax, BytesPerFrs
        mov     NextBuffer, eax
 
 
;       Read FRS 0 into the first MFT FRS buffer, being sure
;       to resolve the Update Sequence Array.  Remember the physical
;       location in the Lbn array.
;
 
        mov     eax, MftStartLcn.LowPart
        movzx   ebx, SectorsPerCluster
        mul     ebx                             ; eax = mft starting sector
 
        mov     ebx, NextBuffer                 ; Store this location in the Lbn array
        mov     [bx], eax
        mov     SectorBase, eax                 ; SectorBase = mft starting sector for read
        add     bx, 4
        mov     eax, SectorsPerFrs
        mov     [bx], eax                       ; Store the sector count in the Lcn array
        mov     SectorCount, ax                 ; SectorCount = SectorsPerFrs
        add     bx, 4
        mov     NextBuffer, ebx                 ; Remember the next Lbn array location
 
        mov     ebx, MftFrs                     ; Read the sectors into the MftFrs scratch buffer
 
        push    ds
        pop     es
 
        call    ReadSectors
        mov     edi, ebx                        ; es:edi = buffer
 
        call    MultiSectorFixup
 
;       Determine whether the MFT has an Attribute List attribute
 
        mov     eax, MftFrs
        mov     ebx, $ATTRIBUTE_LIST
        mov     ecx, 0
        mov     edx, 0
 
        call    LocateAttributeRecord
 
        or      eax, eax        ; If there's no Attribute list,
        jz      SetupMft99      ;    we're done!
 
;       Read the attribute list.
;       eax -> attribute list attribute
;
        mov     ebx, eax        ; ebx -> attribute list attribute
        push    ds
        pop     es              ; copy ds into es
        mov     edi, AttrList   ; ds:edi->attribute list buffer
 
        call    ReadWholeAttribute
 
        mov     ebx, AttrList   ; ebx -> first attribute list entry
 
;       Now, traverse the attribute list looking for the first
;       entry for the $DATA type.  We know it must have at least
;       one.
;
;       ebx -> first attribute list entry
;
 
SetupMft10:
        cmp     [bx].ATTRLIST_TypeCode, $DATA
        je      SetupMft30
 
        add     bx,[bx].ATTRLIST_Length
        jmp     SetupMft10
 
 
SetupMft20:
;       Scan forward through the attribute list entries for the
;       $DATA attribute, reading each referenced FRS.  Note that
;       there will be at least one non-$DATA entry after the entries
;       for the $DATA attribute, since there's a $BITMAP.
;
;       ebx -> Next attribute list entry
;       NextBuffer    -> Target for next mapping information
;       MftFrs        -> Target of next read
;       SegmentsInMft == number of MFT segments read so far
;
 
;       Find the physical sector and sector count for the runs for this
;       file record (max 2 runs).  The mapping for this must already
;       be in a file record already visited.  Find the Vcn and cluster
;       offset for this FRS.  Use LookupMftLcn to find the Lcn.
 
        push    ebx                 ; Save the current position in the attribute list
 
;       Convert from Frs to sectors, then to Vcn
 
        mov     eax, [bx].ATTRLIST_SegmentReference.REF_LowPart
        mul     SectorsPerFrs
        push    eax                 ; Remember the VBN
        xor     edx, edx
        movzx   ebx, SectorsPerCluster
        div     ebx                 ; eax = VCN
        push    edx                 ; save remainder, this is cluster offset
 
        call    ComputeMftLcn       ; eax = LCN
 
        or      eax, eax            ; LCN equal to zero?
 
        jz      BootErr$he          ; zero is not a possible LCN
 
        mov     ecx, SectorsPerFrs  ; ecx = Number of sectors remaining for this file record
 
;       Change the LCN back into an LBN and add the remainder back in to get
;       the sector we want to read.
 
        movzx   ebx, SectorsPerCluster
        mul     ebx                 ; eax = cluster first LBN
        pop     edx                 ; edx = sector remainder
        add     eax, edx            ; eax = desired LBN
 
;       Store this in the current Lcn array slot
 
        mov     ebx, NextBuffer
        mov     [bx], eax           ; Store the starting sector
        add     bx, 4
        movzx   eax, SectorsPerCluster
        sub     eax, edx
 
        cmp     eax, ecx            ; Check if we have too many sectors
        jbe     SetupMft60
        mov     eax, ecx            ; Limit ourselves to the sectors remaining
SetupMft60:
        mov     [bx], eax           ; Store the sector count
 
;       If we have a complete file record skip to process the attribute entry
 
SetupMft70:
        sub     ecx, eax            ; Subtract these sectors from remaining sectors
        pop     edx                 ; Get the previous starting VBN (restores stack also)
 
        jz      SetupMft50
 
;       This may be a split file record.  Go ahead and get the next piece.
 
        add     eax, edx            ; Add the sector count for the last run to the start Vbn for the run
                                    ; This is the next Vbn to read
        push    eax                 ; Save the Vbn
 
        xor     edx, edx            ; Convert to Vcn, there should be no remainder this time
        movzx   ebx, SectorsPerCluster
        div     ebx                 ; eax = VCN
 
        push    ecx                 ; Save the remaining sectors
        call    ComputeMftLcn       ; eax = LCN
        pop     ecx                 ; Restore the remaining sectors
 
        or      eax, eax            ; LCN equal to zero?
        jz      BootErr$he          ; zero is not a possible LCN
 
;       Change the LCN back into a LBN to get the starting sector we want to read.
 
        movzx   ebx, SectorsPerCluster
        mul     ebx                 ; eax = cluster first LBN
 
;       If this sector is the contiguous with the other half of the run
;       make it appear to be single longer run.
 
        mov     ebx, NextBuffer     ; Recover the last run
        mov     edx, [bx]
        add     bx, 4
        add     edx, [bx]           ; This is the next potential LBN
 
        cmp     edx, eax            ; Check if we are at the contiguous LBN
        jne     SetupMft80
 
;       Append this to the previous run.
 
        movzx   eax, SectorsPerCluster
        cmp     eax, ecx            ; Check if have more sectors than we need
        jbe     SetupMft90
        mov     eax, ecx
SetupMft90:
 
        add     [bx], eax
        jmp     SetupMft70          ; Loop to see if there more work to do
 
;       This is multiple runs.  Update the next entry.
 
SetupMft80:
        add     bx, 4
        mov     NextBuffer, ebx    ; advance our NextBuffer pointer
 
        mov     [bx], eax          ; fill in the next run start sector
        add     bx, 4
 
        movzx   eax, SectorsPerCluster
        cmp     eax, ecx            ; Check if have more sectors than we need
        jbe     SetupMft100
        mov     eax, ecx
SetupMft100:
        mov     [bx], eax          ; and count
        jmp     SetupMft70         ; Loop to see if there is more work to do
 
SetupMft50:
 
;       Advance the count of Frs segments and the NextBuffer pointer
 
        add     bx, 4
        inc     SegmentsInMft
        mov     NextBuffer, ebx
 
        pop     ebx
 
;       Go on to the next attribute list entry
 
SetupMft30:
        add     bx,[bx].ATTRLIST_Length
        cmp     [bx].ATTRLIST_TypeCode, $DATA
        je      SetupMft20
 
SetupMft99:
 
        RESTORE_ALL
        ret
 
SetupMft endp
 
;****************************************************************************
;
;   ComputeMftLcn   --  Computes the LCN for a cluster of the MFT
;
;
;   ENTRY:  EAX == VCN
;
;   EXIT:   EAX == LCN
;
;   USES:   ALL
;
ComputeMftLcn proc near
 
        mov     edx, eax                ; edx = VCN
 
        mov     ecx, SegmentsInMft      ; ecx = # of FRS's to search
 
        mov     esi,MftLcnFrs
        add     esi,BytesPerFrs         ; si -> FRS LBN list
 
MftLcn10:
;       ECX == number of remaining FRS's to search
;       EDX == VCN
;       EBX == Buffer to read into
;       ESI == LBN array
;       EDI == Number of sectors to read
;
        push    edx                     ; save VCN
        push    ecx                     ; save MFT segment count
        push    edx                     ; save VCN again
 
;       Read the sectors for the given FRS
 
        mov     ebx,MftLcnFrs
        mov     edi,SectorsPerFrs
 
;       Read these sectors
 
MftLcn40:
        mov     eax,[si]                ; Get the start sector and sector count
        mov     SectorBase,eax
        add     si,4
        mov     eax,[si]
        mov     SectorCount,ax
        add     si,4
 
        push    ds
        pop     es
 
        call    ReadSectors
 
;       Check if we have more data to read
 
        sub     edi, eax
        je      MftLcn30
 
;       Read the next run
 
        mul     BytesPerSector          ; move forward in the buffer, results in ax:dx
        add     bx,ax
        jmp     MftLcn40
 
MftLcn30:
 
;       Do the multi sector fixup
 
        mov     edi,MftLcnFrs
        push    ds
        pop     es
 
        call    MultiSectorFixup
 
        mov     eax, MftLcnFrs
        mov     ebx, $DATA
        mov     ecx, 0
        mov     edx, ecx
 
        call    LocateAttributeRecord
 
;       EAX -> $DATA attribute
;       TOS == VCN
;       TOS + 4 == number of remaining FRS's to search
;       TOS + 8 -> FRS being searched
;       TOS +12 == VCN
 
        or      eax, eax
 
        jz      BootErr$he  ; No $DATA attribute in this FRS!
 
        mov     ebx, eax    ; ebx -> attribute
        pop     eax         ; eax = VCN
 
;       EAX == VCN
;       EBX -> $DATA attribute
;       TOS number of remaining FRS's to search
;       TOS + 4 == FRS being searched
;       TOS + 8 == VCN
 
        push    esi
        call    ComputeLcn
        pop     esi
 
        or      eax, eax
        jz      MftLcn20
 
;       Found our LCN.  Clean up the stack and return.
;
;       EAX == LCN
;       TOS number of remaining FRS's to search
;       TOS + 4 == FRS being searched
;       TOS + 8 == VCN
;
        pop     ebx
        pop     ebx     ; clean up the stack
 
        ret
 
MftLcn20:
;
;       Didn't find the VCN in this FRS; try the next one.
;
;       TOS number of remaining FRS's to search
;       TOS + 4 -> FRS being searched
;       TOS + 8 == VCN
;
        pop     ecx     ; ecx = number of FRS's remaining, including current
        pop     edx     ; edx = VCN
 
        loop    MftLcn10            ; decrement cx and try next FRS
 
;       This VCN was not found.
;
        xor     eax, eax
        ret
 
 
ComputeMftLcn endp
 
;****************************************************************************
;
;   ReadMftSectors - Read sectors from the MFT
;
;   ENTRY:  EAX == starting VBN
;           ECX == number of sectors to read
;           ES:EDI == Target buffer
;
;   USES:   none (preserves all registers with SAVE_ALL/RESTORE_ALL)
;
ReadMftSectors proc near
 
    SAVE_ALL
 
RMS$Again:
 
    push    eax                     ; save starting VBN
    push    ecx                     ; save sector count
 
;   Divide the VBN by SectorsPerCluster to get the VCN
 
    xor     edx, edx                ; zero high part of dividend
    movzx   ebx, SectorsPerCluster
    div     ebx                     ; eax = VCN
    push    edx                     ; save remainder
    push    edi                     ; save the target buffer
 
    call    ComputeMftLcn           ; eax = LCN
    pop     edi                     ; recover the buffer
 
    or      eax, eax                ; LCN equal to zero?
 
    jz      BootErr$he              ; zero is not a possible LCN
 
;   Change the LCN back into a LBN and add the remainder back in to get
;   the sector we want to read, which goes into SectorBase.
;
 
    movzx   ebx, SectorsPerCluster
    mul     ebx                     ; eax = cluster first LBN
    pop     edx                     ; edx = sector remainder
    add     eax, edx                ; eax = desired LBN
 
    mov     SectorBase, eax
 
 
 
;
;   Figure out how many sectors to read this time; we never attempt
;   to read more than one cluster at a time.
;
 
    pop     ecx                     ; ecx = sectors to read
 
    movzx   ebx, SectorsPerCluster
    cmp     ecx,ebx
    jle     RMS10
 
;
;   Read only a single cluster at a time, to avoid problems with fragmented
;   runs in the mft.
;
 
    mov     SectorCount, bx         ; this time read 1 cluster
    sub     ecx, ebx                ; ecx = sectors remaining to read
 
    pop     eax                     ; eax = VBN
    add     eax, ebx                ; VBN += sectors this read
 
 
    push    eax                     ; save next VBN
    push    ecx                     ; save remaining sector count
 
    jmp     RMS20
 
RMS10:
 
    pop     eax                     ; eax = VBN
    add     eax, ecx                ; VBN += sectors this read
    push    eax                     ; save next VBN
 
    mov     SectorCount, cx
    mov     ecx, 0
    push    ecx                     ; save remaining sector count (0)
 
RMS20:
 
 
;   The target buffer was passed in es:edi, but we want it in es:bx.
;   Do the conversion.
;
 
    push    es                      ; save buffer pointer
    push    edi
 
    mov     bx, di
    and     bx, 0Fh
    mov     ax, es
    shr     edi, 4
    add     ax, di                  ; ax:bx -> target buffer
 
    push    ax
    pop     es                      ; es:bx -> target buffer
 
    call    ReadSectors
 
    pop     edi                     ; restore buffer pointer
    pop     es
 
    add     edi, BytesPerCluster    ; increment buf ptr by one cluster
 
    pop     ecx                     ; restore remaining sector count
    pop     eax                     ; restore starting VBN
 
    cmp     ecx, 0                  ; are we done?
    jg      RMS$Again               ; repeat until desired == 0
 
 
    RESTORE_ALL
    ret
 
ReadMftSectors endp
 
 
;****************************************************************************
;
;   ReadFrs - Read an FRS
;
;   ENTRY:  EAX == FRS number
;           ES:EDI == Target buffer
;
;   USES:  none (preserves all registers with SAVE_ALL/RESTORE_ALL)
;
ReadFrs proc near
 
    SAVE_ALL
 
    mul     SectorsPerFrs       ; eax = sector number in MFT DATA attribute
                                ; (note that mul wipes out edx!)
 
    mov     ecx, SectorsPerFrs  ; number of sectors to read
 
    call    ReadMftSectors
    call    MultiSectorFixup
 
    RESTORE_ALL
    ret
 
ReadFrs endp
 
;****************************************************************************
;
;   ReadIndexBlock - read an index block from the root index.
;
;   ENTRY:  EAX == Block number
;
;   USES:  none (preserves all registers with SAVE_ALL/RESTORE_ALL)
;
ReadIndexBlock proc near
 
    SAVE_ALL
 
    mul     SectorsPerIndexBlock        ; eax = first VBN to read
                                        ; (note that mul wipes out edx!)
    mov     ebx, IndexAllocation        ; ebx -> $INDEX_ALLOCATION attribute
    mov     ecx, SectorsPerIndexBlock   ; ecx == Sectors to read
 
    push    ds
    pop     es
    mov     edi, IndexBlockBuffer       ; es:edi -> index block buffer
 
    call    ReadIndexBlockSectors
 
    call    MultiSectorFixup
 
    RESTORE_ALL
    ret
 
ReadIndexBlock endp
 
;****************************************************************************
;
;   IsBlockInUse - Checks the index bitmap to see if an index
;                  allocation block is in use.
;
;   ENTRY:  EAX == block number
;
;   EXIT:   Carry flag clear if block is in use
;           Carry flag set   if block is not in use.
;
IsBlockInUse proc near
 
        push    eax
        push    ebx
        push    ecx
 
        mov     ebx, IndexBitmapBuffer
 
        mov     ecx, eax    ; ecx = block number
        shr     eax, 3      ; eax = byte number
        and     ecx, 7      ; ecx = bit number in byte
 
        add     ebx, eax    ; ebx -> byte to test
 
        mov     eax, 1
        shl     eax, cl     ; eax = mask
 
        test    byte ptr[ebx], al
 
        jz      IBU10
 
        clc                 ; Block is not in use.
        jmp     IBU20
 
IBU10:  stc                 ; Block is in use.
 
IBU20:
        pop     ecx
        pop     ebx
        pop     eax         ; restore registers
 
        ret
 
IsBlockInUse endp
 
;****************************************************************************
;
;   ComputeLcn - Converts a VCN into an LCN
;
;   ENTRY:  EAX -> VCN
;           EBX -> Attribute
;
;   EXIT:   EAX -> LCN  (zero indicates not found)
;           ECX -> Remaining run length
;
;   USES:   ALL.
;
ComputeLcn proc near
 
        cmp     [ebx].ATTR_FormCode, NONRESIDENT_FORM
        je      clcn10
 
        sub     eax, eax    ; This is a resident attribute.
        ret
 
clcn10: lea     esi, [ebx].ATTR_FormUnion   ; esi -> nonresident info of attrib
 
;       eax -> VCN
;       ebx -> Attribute
;       esi -> Nonresident information of attribute record
;
;       See if the desired VCN is in range.
 
        mov     edx, [esi].NONRES_HighestVcn.LowPart ; edx = HighestVcn
        cmp     eax, edx
        ja      clcn15      ; VCN is greater than HighestVcn
 
        mov     edx, [esi].NONRES_LowestVcn.LowPart ; edx = LowestVcn
        cmp     eax, edx
        jae     clcn20
 
clcn15:
        sub     eax, eax    ; VCN is not in range
        ret
 
clcn20:
;       eax -> VCN
;       ebx -> Attribute
;       esi -> Nonresident information of attribute record
;       edx -> LowestVcn
;
        add     bx, [esi].NONRES_MappingPairOffset  ; ebx -> mapping pairs
        sub     esi, esi                            ; esi = 0
 
clcn30:
;       eax == VCN to find
;       ebx -> Current mapping pair count byte
;       edx == Current VCN
;       esi == Current LCN
;
        cmp     byte ptr[ebx], 0    ; if count byte is zero...
        je      clcn99              ;  ... we're done (and didn't find it)
 
;       Update CurrentLcn
;
        call    LcnFromMappingPair
        add     esi, ecx            ; esi = current lcn for this mapping pair
 
        call    VcnFromMappingPair
 
;       eax == VCN to find
;       ebx -> Current mapping pair count byte
;       ecx == DeltaVcn for current mapping pair
;       edx == Current VCN
;       esi == Current LCN
;
        add     ecx, edx            ; ecx = NextVcn
 
        cmp     eax, ecx            ; If target < NextVcn ...
        jl      clcn80              ;   ... we found the right mapping pair.
 
;       Go on to next mapping pair.
;
        mov     edx, ecx            ; CurrentVcn = NextVcn
 
        push    eax
 
        movzx   ecx, byte ptr[ebx]  ; ecx = count byte
        mov     eax, ecx            ; eax = count byte
        and     eax, 0fh            ; eax = number of vcn bytes
        shr     ecx, 4              ; ecx = number of lcn bytes
 
        add     ebx, ecx
        add     ebx, eax
        inc     ebx                 ; ebx -> next count byte
 
        pop     eax
        jmp     clcn30
 
clcn80:
;       We found the mapping pair we want.
;
;       eax == target VCN
;       ebx -> mapping pair count byte
;       edx == Starting VCN of run
;       ecx == Next VCN (ie. start of next run)
;       esi == starting LCN of run
;
        sub     ecx, eax            ; ecx = remaining run length
        sub     eax, edx            ; eax = offset into run
        add     eax, esi            ; eax = LCN to return
 
        ret
 
;       The target VCN is not in this attribute.
 
clcn99: sub     eax, eax    ; Not found.
        ret
 
 
ComputeLcn endp
 
;****************************************************************************
;
;   VcnFromMappingPair
;
;   ENTRY:  EBX -> Mapping Pair count byte
;
;   EXIT:   ECX == DeltaVcn from mapping pair
;
;   USES:   ECX
;
VcnFromMappingPair proc near
 
        sub     ecx, ecx            ; ecx = 0
        mov     cl, byte ptr[ebx]   ; ecx = count byte
        and     cl, 0fh             ; ecx = v
 
        cmp     ecx, 0              ; if ecx is zero, volume is corrupt.
        jne     VFMP5
 
        sub     ecx, ecx
        ret
 
VFMP5:
        push    ebx
        push    edx
 
        add     ebx, ecx            ; ebx -> last byte of compressed vcn
 
        movsx   edx, byte ptr[ebx]
        dec     ecx
        dec     ebx
 
;       ebx -> Next byte to add in
;       ecx == Number of bytes remaining
;       edx == Accumulated value
;
VFMP10: cmp     ecx, 0              ; When ecx == 0, we're done.
        je      VFMP20
 
        shl     edx, 8
        mov     dl, byte ptr[ebx]
 
        dec     ebx                 ; Back up through bytes to process.
        dec     ecx                 ; One less byte to process.
 
        jmp     VFMP10
 
VFMP20:
;       edx == Accumulated value to return
 
        mov     ecx, edx
 
        pop     edx
        pop     ebx
 
        ret
 
VcnFromMappingPair endp
 
 
;****************************************************************************
;
;   LcnFromMappingPair
;
;   ENTRY:  EBX -> Mapping Pair count byte
;
;   EXIT:   ECX == DeltaLcn from mapping pair
;
;   USES:   ECX
;
LcnFromMappingPair proc near
 
        push    ebx
        push    edx
 
        sub     edx, edx            ; edx = 0
        mov     dl, byte ptr[ebx]   ; edx = count byte
        and     edx, 0fh            ; edx = v
 
        sub     ecx, ecx            ; ecx = 0
        mov     cl, byte ptr[ebx]   ; ecx = count byte
        shr     cl, 4               ; ecx = l
 
        cmp     ecx, 0              ; if ecx is zero, volume is corrupt.
        jne     LFMP5
 
        sub     ecx, ecx
 
        pop     edx
        pop     ebx
        ret
 
LFMP5:
;       ebx -> count byte
;       ecx == l
;       edx == v
;
 
        add     ebx, edx            ; ebx -> last byte of compressed vcn
        add     ebx, ecx            ; ebx -> last byte of compressed lcn
 
        movsx   edx, byte ptr[ebx]
        dec     ecx
        dec     ebx
 
;       ebx -> Next byte to add in
;       ecx == Number of bytes remaining
;       edx == Accumulated value
;
LFMP10: cmp     ecx, 0              ; When ecx == 0, we're done.
        je      LFMP20
 
        shl     edx, 8
        mov     dl, byte ptr[ebx]
 
        dec     ebx                 ; Back up through bytes to process.
        dec     ecx                 ; One less byte to process.
 
        jmp     LFMP10
 
LFMP20:
;       edx == Accumulated value to return
 
        mov     ecx, edx
 
        pop     edx
        pop     ebx
 
        ret
 
LcnFromMappingPair endp
 
;****************************************************************************
;
; UpcaseName - Converts the name of the file to all upper-case
;
;       ENTRY:  ESI -> Name
;               ECX -> Length of name
;
;       USES:   none
;
UpcaseName proc   near
 
 
        or      ecx, ecx
        jnz     UN5
 
        ret
 
UN5:
        push    ecx
        push    esi
 
UN10:
        cmp     word ptr[esi], 'a'      ; if it's less than 'a'
        jl      UN20                    ; leave it alone
 
        cmp     word ptr[esi], 'z'      ; if it's greater than 'z'
        jg      UN20                    ; leave it alone.
 
        sub     word ptr[esi], 'a'-'A'  ; the letter is lower-case--convert it.
UN20:
        add     esi, 2                  ; move on to next unicode character
        loop    UN10
 
        pop     esi
        pop     ecx
 
        ret
UpcaseName endp
 
;****************************************************************************
;
;   FindFile - Locates the index entry for a file in the root index.
;
;   ENTRY:  EAX -> name to find
;           ECX == length of file name in characters
;
;   EXIT:   EAX -> Index Entry.  NULL to indicate failure.
;
;   USES:   ALL
;
FindFile proc near
 
        push    eax     ; name address
        push    ecx     ; name length
 
;       First, search the index root.
;
;       eax -> name to find
;       ecx == name length
;       TOS == name length
;       TOS+4 -> name to find
;
        mov     edx, eax                    ; edx -> name to find
        mov     eax, IndexRoot              ; eax -> &INDEX_ROOT attribute
        lea     ebx, [eax].ATTR_FormUnion   ; ebx -> resident info
        add     ax, [ebx].RES_ValueOffset   ; eax -> Index Root value
 
        lea     eax, [eax].IR_IndexHeader   ; eax -> Index Header
 
        mov     ebx, edx                    ; ebx -> name to find
 
        call    LocateIndexEntry
 
        or      eax, eax
        jz      FindFile20
 
;       Found it in the root!  The result is already in eax.
;       Clean up the stack and return.
;
        pop     ecx
        pop     ecx
        ret
 
FindFile20:
;
;       We didn't find the index entry we want in the root, so we have to
;       crawl through the index allocation buffers.
;
;       TOS == name length
;       TOS+4 -> name to find
;
        mov     eax, IndexAllocation
        or      eax, eax
        jnz     FindFile30
 
;       There is no index allocation attribute; clean up
;       the stack and return failure.
;
        pop     ecx
        pop     ecx
        xor     eax, eax
        ret
 
FindFile30:
;
;       Search the index allocation blocks for the name we want.
;       Instead of searching in tree order, we'll just start with
;       the last one and work our way backwards.
;
;       TOS == name length
;       TOS+4 -> name to find
;
        mov     edx, IndexAllocation        ; edx -> index allocation attr.
        lea     edx, [edx].ATTR_FormUnion   ; edx -> nonresident form info
        mov     eax, [edx].NONRES_HighestVcn.LowPart; eax = HighestVcn
        inc     eax                         ; eax = clusters in attribute
 
        mov     ebx, BytesPerCluster
        mul     ebx                         ; eax = bytes in attribute
 
        xor     edx, edx
        div     BytesPerIndexBlock          ; convert bytes to index blocks
 
        push    eax                         ; number of blocks to process
 
FindFile40:
;
;       TOS == remaining index blocks to search
;       TOS + 4 == name length
;       TOS + 8 -> name to find
;
        pop     eax         ; eax == number of remaining blocks
 
        or      eax, eax
        jz      FindFile90
 
        dec     eax         ; eax == number of next block to process
                            ;        and number of remaining blocks
 
        push    eax
 
;       eax == block number to process
;       TOS == remaining index blocks to search
;       TOS + 4 == name length
;       TOS + 8 -> name to find
;
;       See if the block is in use; if not, go on to next.
 
        call    IsBlockInUse
        jc      FindFile40      ; c set if not in use
 
;       eax == block number to process
;       TOS == remaining index blocks to search
;       TOS + 4 == name length
;       TOS + 8 -> name to find
;
 
        call    ReadIndexBlock
 
        pop     edx         ; edx == remaining buffers to search
        pop     ecx         ; ecx == name length
        pop     ebx         ; ebx -> name
 
        push    ebx
        push    ecx
        push    edx
 
;       ebx -> name to find
;       ecx == name length in characters
;       TOS == remaining blocks to process
;       TOS + 4 == name length
;       TOS + 8 -> name
;
;       Index buffer to search is in index allocation block buffer.
;
        mov     eax, IndexBlockBuffer       ; eax -> Index allocation block
        lea     eax, [eax].IB_IndexHeader   ; eax -> Index Header
 
        call    LocateIndexEntry            ; eax -> found entry
 
        or      eax, eax
        jz      FindFile40
 
;       Found it!
;
;       eax -> Found entry
;       TOS == remaining blocks to process
;       TOS + 4 == name length
;       TOS + 8 -> name
;
        pop     ecx
        pop     ecx
        pop     ecx ; clean up stack
        ret
 
FindFile90:
;
;       Name not found.
;
;       TOS == name length
;       TOS + 4 -> name to find
;
        pop     ecx
        pop     ecx         ; clean up stack.
        xor     eax, eax    ; zero out eax.
        ret
 
 
FindFile endp
 
ifdef DEBUG
;****************************************************************************
;
;   DumpIndexBlock - dumps the index block buffer
;
DumpIndexBlock proc near
 
    SAVE_ALL
 
    mov     esi, IndexBlockBuffer
 
    mov     ecx, 20h    ; dwords to dump
 
DIB10:
 
    test    ecx, 3
    jnz     DIB20
    call    DebugNewLine
 
DIB20:
 
    lodsd
    call    PrintNumber
    loop    DIB10
 
    RESTORE_ALL
    ret
 
DumpIndexBlock endp
 
;****************************************************************************
;
;   DebugNewLine
;
DebugNewLine proc near
 
    SAVE_ALL
 
    xor     eax, eax
    xor     ebx, ebx
 
    mov     al, 0dh
    mov     ah, 14
    mov     bx, 7
    int     10h
 
    mov     al, 0ah
    mov     ah, 14
    mov     bx, 7
    int     10h
 
    RESTORE_ALL
    ret
 
DebugNewLine endp
 
 
;****************************************************************************
;
;   PrintName  -   Display a unicode name
;
;   ENTRY:  DS:ESI  -> null-terminated string
;           ECX     == characters in string
;
;   USES:   None.
;
PrintName proc near
 
 
    SAVE_ALL
 
    or      ecx, ecx
    jnz     PrintName10
 
    call    DebugNewLine
 
    RESTORE_ALL
 
    ret
 
PrintName10:
 
    xor     eax, eax
    xor     ebx, ebx
 
    lodsw
 
    mov     ah, 14  ; write teletype
    mov     bx, 7   ; attribute
    int     10h     ; print it
    loop    PrintName10
 
    call    DebugNewLine
 
    RESTORE_ALL
    ret
 
PrintName endp
 
;****************************************************************************
;
;   DebugPrint  -   Display a debug string.
;
;   ENTRY:  DS:SI  -> null-terminated string
;
;   USES:   None.
;
.286
DebugPrint proc near
 
    pusha
 
DbgPr20:
 
    lodsb
    cmp     al, 0
    je      DbgPr30
 
    mov     ah, 14  ; write teletype
    mov     bx, 7   ; attribute
    int     10h     ; print it
    jmp     DbgPr20
 
DbgPr30:
 
    popa
    nop
    ret
 
DebugPrint endp
 
;****************************************************************************
;
;
;   PrintNumber
;
;   ENTRY: EAX == number to print
;
;   PRESERVES ALL REGISTERS
;
.386
PrintNumber proc near
 
 
    SAVE_ALL
 
    mov     ecx, 8      ; number of digits in a DWORD
 
PrintNumber10:
 
    mov     edx, eax
    and     edx, 0fh    ; edx = lowest-order digit
    push    edx         ; put it on the stack
    shr     eax, 4      ; drop low-order digit
    loop    PrintNumber10
 
    mov     ecx, 8      ; number of digits on stack.
 
PrintNumber20:
 
    pop     eax         ; eax = next digit to print
    cmp     eax, 9
    jg      PrintNumber22
 
    add     eax, '0'
    jmp     PrintNumber25
 
PrintNumber22:
 
    sub     eax, 10
    add     eax, 'A'
 
PrintNumber25:
 
    xor     ebx, ebx
 
    mov     ah, 14
    mov     bx, 7
    int     10h
    loop    PrintNumber20
 
;   Print a space to separate numbers
 
    mov     al, ' '
    mov     ah, 14
    mov     bx, 7
    int     10h
 
    RESTORE_ALL
 
    call    Pause
 
    ret
 
PrintNumber endp
 
 
;****************************************************************************
;
;   Debug0 - Print debug string 0 -- used for checkpoints in mainboot
;
Debug0 proc near
 
    SAVE_ALL
 
    mov     si, offset DbgString0
    call    BootErr$Print1
 
    RESTORE_ALL
 
    ret
 
Debug0 endp
 
;****************************************************************************
;
;   Debug1 - Print debug string 1 --
;
Debug1 proc near
 
    SAVE_ALL
 
    mov     si, offset DbgString1
    call    BootErr$Print1
 
    RESTORE_ALL
 
    ret
 
Debug1 endp
 
;****************************************************************************
;
;   Debug2 - Print debug string 2
;
Debug2 proc near
 
    SAVE_ALL
 
    mov     si, offset DbgString2
    call    BootErr$Print1
 
    RESTORE_ALL
 
    ret
 
Debug2 endp
 
;****************************************************************************
;
;   Debug3 - Print debug string 3 --
;
Debug3 proc near
 
    SAVE_ALL
 
    mov     si, offset DbgString3
    call    BootErr$Print1
 
    RESTORE_ALL
 
    ret
 
Debug3 endp
 
;****************************************************************************
;
;   Debug4 - Print debug string 4
;
Debug4 proc near
 
    SAVE_ALL
 
    mov     si, offset DbgString4
    call    BootErr$Print1
 
    RESTORE_ALL
 
    ret
 
Debug4 endp
 
;****************************************************************************
;
;   Pause - Pause for about 1/2 a second.  Simply count until you overlap
;           to zero.
;
Pause proc near
 
    push eax
    mov  eax, 0fff10000h
 
PauseLoopy:
    inc  eax
 
    or   eax, eax
    jnz  PauseLoopy
 
    pop  eax
    ret
 
Pause endp
 
endif ; DEBUG
 
;*************************************************************************
;
;       LoadIndexFrs  -  For the requested index type code locate and
;                        load the associated Frs.
;
;       ENTRY: EAX - requested index type code
;              ECX - Points to empty Frs buffer
;
;       EXIT:  EAX - points to offset in Frs buffer of requested index type
;                    code or Zero if not found.
;       USES:  All
;
LoadIndexFrs    proc    near
 
        push    ecx                     ; save FRS buffer for later
        push    eax                     ; save index type code for later
 
        mov     eax, ROOT_FILE_NAME_INDEX_NUMBER
        push    ds
        pop     es
        mov     edi, ecx                ; es:edi = target buffer
 
        call    ReadFrs
 
        mov     eax, ecx                ; FRS to search
 
        pop     ebx                     ; Attribute type code
        push    ebx
        movzx   ecx, index_name_length  ; Attribute name length
        mov     edx, offset index_name  ; Attribute name
 
        call    LocateAttributeRecord
 
        pop     ebx
        pop     ecx
 
        or      eax, eax
        jnz     LoadIndexFrs$Exit      ; if found in root return
 
;
;       if not found in current Frs, search in attribute list
;
                                       ; EBX - holds Attribute type code
        mov     eax, ecx               ; FRS to search
        mov     ecx, ebx               ; type code
        push    eax                    ; save Frs
        push    ebx                    ; save type code
 
        call    SearchAttrList          ; search attribute list for FRN
                                        ; of specified ($INDEX_ROOT,
                                        ; $INDEX_ALLOCATION, or $BITMAP)
 
        ; EAX - holds FRN for Frs, or Zero
 
        pop     ebx                     ; Attribute type code (used later)
        pop     edi                     ; es:edi = target buffer
 
        or      eax, eax                ; if we cann't find it in attribute
        jz      LoadIndexFrs$Exit       ; list then we are hosed
 
 
;       We should now have the File Record Number where the index for the
;       specified type code we are searching for is,  load this into the
;       Frs target buffer.
;
;       EAX - holds FRN
;       EBX - holds type code
;       EDI - holds target buffer
 
        push    ds
        pop     es
 
        call    ReadFrs
 
;
;       Now determine the offset in the Frs of the index
;
 
;       EBX - holds type code
 
        mov     eax, edi                ; Frs to search
        movzx   ecx, index_name_length  ; Attribute name length
        mov     edx, offset index_name  ; Attribute name
 
        call    LocateAttributeRecord
 
;       EAX -  holds offset or Zero.
 
 
LoadIndexFrs$Exit:
        ret
 
LoadIndexFrs    endp
 
 
;****************************************************************************
;
;   SearchAttrList
;
;   Search the Frs for the attribute list.  Then search the attribute list
;   for the specifed type code.  When you find it return the FRN in the
;   attribute list entry found or Zero if no match found.
;
;   ENTRY: ECX - type code to search attrib list for
;          EAX - Frs buffer holding head of attribute list
;   EXIT:  EAX - FRN file record number to load, Zero if none.
;
;   USES: All
;
SearchAttrList proc  near
 
        push    ecx                     ; type code to search for in
                                        ; attrib list
 
                                        ; EAX - holds Frs to search
        mov     ebx, $ATTRIBUTE_LIST    ; Attribute type code
        mov     ecx, 0                  ; Attribute name length
        mov     edx, 0                  ; Attribute name
 
        call    LocateAttributeRecord
 
        or      eax, eax                      ; If there's no Attribute list,
        jz      SearchAttrList$NotFoundIndex1 ; We are done
 
;       Read the attribute list.
;       eax -> attribute list attribute
 
        mov     ebx, eax        ; ebx -> attribute list attribute
        push    ds
        pop     es              ; copy ds into es
        mov     edi, AttrList   ; ds:edi->attribute list buffer
 
        call    ReadWholeAttribute
 
        push    ds
        pop     es
        mov     ebx, AttrList   ; es:ebx -> first attribute list entry
 
;       Now, traverse the attribute list looking for the entry for
;       the Index type code.
;
;       ebx -> first attribute list entry
;
 
        pop     ecx                            ; Get Index Type code
 
 
SearchAttrList$LookingForIndex:
 
ifdef DEBUG
        SAVE_ALL
 
        mov     eax, es:[bx].ATTRLIST_TypeCode
        call    PrintNumber
        movzx   eax, es:[bx].ATTRLIST_Length
        call    PrintNumber
        mov     eax, es
        call    PrintNumber
        mov     eax, ebx
        call    PrintNumber
        push    es
        pop     ds
        movzx   ecx, es:[bx].ATTRLIST_NameLength    ; ecx = chars in name
        lea     esi, es:[bx].ATTRLIST_Name          ; esi -> name
        call    PrintName
 
        RESTORE_ALL
endif ; DEBUG
 
        cmp     es:[bx].ATTRLIST_TypeCode, ecx
        je      SearchAttrList$FoundIndex
 
        cmp     es:[bx].ATTRLIST_TypeCode, $END   ; reached invalid attribute
        je      SearchAttrList$NotFoundIndex2     ; so must be at end
 
        cmp     es:[bx].ATTRLIST_Length, 0
        je      SearchAttrList$NotFoundIndex2     ; reached end of list and
                                                  ; nothing found
        movzx   eax, es:[bx].ATTRLIST_Length
        add     bx, ax
 
        mov     ax, bx
        and     ax, 08000h                        ; test for roll over
        jz      SearchAttrList$LookingForIndex
 
        ;  If we rolled over then increment to the next es 32K segment and
        ;  zero off the high bits of bx
 
        mov     ax, es
        add     ax, 800h
        mov     es, ax
 
        and     bx, 07fffh
 
        jmp     SearchAttrList$LookingForIndex
 
SearchAttrList$FoundIndex:
 
        ;  found the index, return the FRN
 
        mov     eax, es:[bx].ATTRLIST_SegmentReference.REF_LowPart
        ret
 
 
SearchAttrList$NotFoundIndex1:
        pop     ecx
SearchAttrList$NotFoundIndex2:
        xor     eax, eax
        ret
 
SearchAttrList endp
 
;
; Boot message printing, relocated from sector 0 to sace space
;
BootErr$fnf:
        mov     al,byte ptr TXT_MSG_SYSINIT_FILE_NOT_FD
        jmp     BootErr2
BootErr$ntc:
        mov     al,byte ptr TXT_MSG_SYSINIT_NTLDR_CMPRS
        jmp     BootErr2
 
ifdef DEBUG
DbgString0      db  "Debug Point 0", 0Dh, 0Ah, 0
DbgString1      db  "Debug Point 1", 0Dh, 0Ah, 0
DbgString2      db  "Debug Point 2", 0Dh, 0Ah, 0
DbgString3      db  "Debug Point 3", 0Dh, 0Ah, 0
DbgString4      db  "Debug Point 4", 0Dh, 0Ah, 0
 
endif ; DEBUG
 
        .errnz  ($-_ntfsboot) GT 8192   ; <FATAL PROBLEM: main boot record exceeds available space>
 
        org     8192
 
BootCode ends
 
         end _ntfsboot

It is very interesting to see such old programming code, booting a filesystem may not be that hard after all. Windows XP is very old now, but at least we can see how the boot process works now.

Here is a complete archive of the Windows XP boot code, this might be very interesting to someone who is experimenting with Windows XP.

https://www.securitronlinux.com/doomstuff/boot.zip


Leave a Comment

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