summaryrefslogtreecommitdiffstats
path: root/private/mvdm/v86/monitor/i386/proflib.c
blob: 06276a82025c4c954a9e5ca82cd0bf03d9cd6cdc (plain) (blame)
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
/*++

Copyright (c) 1990  Microsoft Corporation

Module Name:

   proflib.c

Abstract:

    This module contains the implementation of a rudimentry user-mode
    profiler.

Usage:

    There are 4 routines, RtlInitializeProfile, RtlStartProfile,
    RtlStopProfile, and RtlAnalyzeProfile.  To initialize profiling
    invoke RtlInitializeProfile, this routine is only called once and
    goes through the address space looking for code regions of images
    and DLLs.  To start profiling call RtlStartProfile.  To stop
    profiling call RtlStopProfile.  Note that RtlStartProfile and
    RtlStopProfile can be called repeatedly to profile only key
    "hot spots", For example:
                RtlStartProfile ();
                hot spot...
                RtlStopProfile ();
                ....
                RtlStartProfile ();
                hot spot...
                RtlStopProfile ();

    To analyze the results call RtlAnalyzeProfile.  This too can
    be called repeatedly (it stops profiling during the analysis
    phase and does NOT restart profiling).  It also does not
    zero out the values after reporting.

Author:

    Lou Perazzoli (loup) 4-Oct-1990

Revision History:

--*/

#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <string.h>
#include <stdio.h>
#include <\nt\private\ntos\dll\ldrp.h>

NTSTATUS
InitializeKernelProfile ( VOID );

#define PAGE_SIZE 4096

typedef struct _PROFILE_BLOCK {
    HANDLE Handle;
    PVOID ImageBase;  //actual base in image header
    PULONG CodeStart;
    ULONG CodeLength;
    PULONG Buffer;
    ULONG BufferSize;
    ULONG TextNumber;
    ULONG BucketSize;
    PVOID MappedImageBase;  //actual base where mapped locally.
    PSZ ImageName;
} PROFILE_BLOCK;


#define MAX_PROFILE_COUNT 50

PROFILE_BLOCK ProfileObject[MAX_PROFILE_COUNT];

ULONG NumberOfProfileObjects = 0;
PIMAGE_DEBUG_INFO KernelDebugInfo;

//
// Image name to perform kernel mode analysis upon.
//

#define IMAGE_NAME "\\SystemRoot\\ntoskrnl.exe"

//
// Define map data file if the produced data file should be
// a mapped file (currently named "kernprof.dat").
//

// #define MAP_DATA_FILE

//
// Define map as image if the image to be profiled should be mapped
// as an image rather than as data.
//

// #define MAP_AS_IMAGE

#define MAX_PROFILE_COUNT 50

extern ULONG ProfInt;

NTSTATUS
RtlInitializeProfile (
    IN BOOLEAN KernelToo
    )

/*++

Routine Description:

    This routine initializes profiling for the current process.

Arguments:

    KernelToo - Set to TRUE if kernel code should be profiled as
                well as user code.

Return Value:

    Returns the status of the last NtCreateProfile.

--*/

{

    NTSTATUS status, LocalStatus;
    HANDLE CurrentProcessHandle;
    ULONG BufferSize;
    PVOID ImageBase;
    ULONG CodeLength;
    PULONG Buffer;
    PPEB Peb;
    PLDR_DATA_TABLE_ENTRY LdrDataTableEntry;
    PSZ ImageName;
    PLIST_ENTRY Next;
    ULONG ExportSize, DebugSize;
    PIMAGE_EXPORT_DIRECTORY ExportDirectory;
    PIMAGE_DEBUG_DIRECTORY DebugDirectory;
    PIMAGE_DEBUG_INFO DebugInfo;
    BOOLEAN PreviousPrivState;

    //
    // Locate all the executables in the address and create a
    // seperate profile object for each one.
    //

    CurrentProcessHandle = NtCurrentProcess();

    Peb = NtCurrentPeb();

    Next = Peb->Ldr->InMemoryOrderModuleList.Flink;
    while ( Next != &Peb->Ldr->InMemoryOrderModuleList) {
        LdrDataTableEntry
            = (PLDR_DATA_TABLE_ENTRY) (CONTAINING_RECORD(Next,LDR_DATA_TABLE_ENTRY,InMemoryOrderLinks));

        ImageBase = LdrDataTableEntry->DllBase;
        if ( Peb->ImageBaseAddress == ImageBase ) {
            ImageName = "TheApplication";
        } else {
            ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)RtlImageDirectoryEntryToData(
                               ImageBase,
                               TRUE,
                               IMAGE_DIRECTORY_ENTRY_EXPORT,
                               &ExportSize);

            ImageName =  (PSZ)((ULONG)ImageBase + ExportDirectory->Name);
        }
        if (NumberOfProfileObjects > MAX_PROFILE_COUNT) {
            break;
        }

        ProfileObject[NumberOfProfileObjects].ImageBase = ImageBase;
        ProfileObject[NumberOfProfileObjects].ImageName = ImageName;
        ProfileObject[NumberOfProfileObjects].MappedImageBase = ImageBase;

        //
        // Locate the code range and start profiling.
        //

        DebugDirectory = (PIMAGE_DEBUG_DIRECTORY)RtlImageDirectoryEntryToData(
                    ImageBase, TRUE, IMAGE_DIRECTORY_ENTRY_DEBUG, &DebugSize);

        if (!DebugDirectory) {
            DbgPrint ("RtlInitializeProfile : No debug directory\n");
            return STATUS_INVALID_IMAGE_FORMAT;
        }

        DebugInfo = (PIMAGE_DEBUG_INFO)((ULONG)ImageBase + DebugDirectory->AddressOfRawData);

        ProfileObject[NumberOfProfileObjects].CodeStart = (PULONG)((ULONG)ImageBase + DebugInfo->RvaToFirstByteOfCode);
        CodeLength = (DebugInfo->RvaToLastByteOfCode - DebugInfo->RvaToFirstByteOfCode) - 1;
        ProfileObject[NumberOfProfileObjects].CodeLength = CodeLength;

        ProfileObject[NumberOfProfileObjects].TextNumber = 1;

        //
        // Analyze the size of the code and create a reasonably sized
        // profile object.
        //

        BufferSize = (CodeLength >> 1) + 4;
        Buffer = NULL;

        status = NtAllocateVirtualMemory (CurrentProcessHandle,
                                          (PVOID *)&Buffer,
                                          0,
                                          &BufferSize,
                                          MEM_RESERVE | MEM_COMMIT,
                                          PAGE_READWRITE);

        if (!NT_SUCCESS(status)) {
            DbgPrint ("alloc VM failed %lx\n",status);
            return status;
        }


        status = RtlAdjustPrivilege(
                     SE_PROF_SINGLE_PROCESS_PRIVILEGE,
                     TRUE,              //Enable
                     FALSE,             //not impersonating
                     &PreviousPrivState //Remember if it will need to be cleared
                     );

        if (!NT_SUCCESS(status) || status == STATUS_NOT_ALL_ASSIGNED) {
            DbgPrint("Enable system profile privilege failed - status 0x%lx\n",
                     status);
        }


        ProfileObject[NumberOfProfileObjects].Buffer = Buffer;
        ProfileObject[NumberOfProfileObjects].BufferSize = BufferSize;
        ProfileObject[NumberOfProfileObjects].BucketSize = 3;

        status = NtCreateProfile (
                    &ProfileObject[NumberOfProfileObjects].Handle,
                    CurrentProcessHandle,
                    ProfileObject[NumberOfProfileObjects].CodeStart,
                    CodeLength,
                    ProfileObject[NumberOfProfileObjects].BucketSize,
                    ProfileObject[NumberOfProfileObjects].Buffer ,
                    ProfileObject[NumberOfProfileObjects].BufferSize,
                    ProfileTime,
                    (KAFFINITY)-1);

        if (PreviousPrivState == FALSE) {
            LocalStatus = RtlAdjustPrivilege(
                             SE_PROF_SINGLE_PROCESS_PRIVILEGE,
                             FALSE,             //Disable
                             FALSE,             //not impersonating
                             &PreviousPrivState //Don't care if it was already enabled
                             );
            if (!NT_SUCCESS(LocalStatus) || LocalStatus == STATUS_NOT_ALL_ASSIGNED) {
                DbgPrint("Disable system profile privilege failed - status 0x%lx\n",
                         LocalStatus);
            }
        }

        if (status != STATUS_SUCCESS) {
            DbgPrint("create profile %x failed - status %lx\n",
                   ProfileObject[NumberOfProfileObjects].ImageName,status);
            return status;
        }

        NumberOfProfileObjects += 1;

        Next = Next->Flink;
    }

    if (KernelToo) {

        if (NumberOfProfileObjects > MAX_PROFILE_COUNT) {
            return status;
        }
        status = InitializeKernelProfile();
    }
    return status;

}
NTSTATUS
InitializeKernelProfile (
    VOID
    )

/*++

Routine Description:

    This routine initializes profiling for the kernel for the
    current process.

Arguments:

    None.

Return Value:

    Returns the status of the last NtCreateProfile.

--*/

{

    //BUGBUG daveh I think that the new working set size calculation is
    //             generating the number of pages, when the api expects
    //             the number of bytes.

    STRING Name3;
    IO_STATUS_BLOCK IoStatus;
    HANDLE FileHandle, KernelSection;
    OBJECT_ATTRIBUTES ObjectAttributes;
    PVOID ImageBase;
    ULONG ViewSize;
    ULONG CodeLength;
    NTSTATUS status, LocalStatus;
    HANDLE CurrentProcessHandle;
    QUOTA_LIMITS QuotaLimits;
    PVOID Buffer;
    ULONG Cells;
    ULONG BucketSize;
    UNICODE_STRING Unicode;
    ULONG DebugSize;
    PVOID KernelBase;
    PIMAGE_NT_HEADERS KernelNtHeaders;
    PIMAGE_DEBUG_DIRECTORY DebugDirectory;
    BOOLEAN PreviousPrivState;

    RtlInitString (&Name3, IMAGE_NAME);
    CurrentProcessHandle = NtCurrentProcess();

    status = RtlAnsiStringToUnicodeString(&Unicode,(PANSI_STRING)&Name3,TRUE);
    ASSERT(NT_SUCCESS(status));
    InitializeObjectAttributes( &ObjectAttributes,
                                &Unicode,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL );

    //
    // Open the file as readable and executable.
    //

    status = NtOpenFile ( &FileHandle,
                          FILE_READ_DATA | FILE_EXECUTE,
                          &ObjectAttributes,
                          &IoStatus,
                          FILE_SHARE_READ,
                          0L);
    RtlFreeUnicodeString(&Unicode);

    if (!NT_SUCCESS(status)) {
        DbgPrint("open file failed status %lx\n", status);
        NtTerminateProcess(NtCurrentProcess(),STATUS_SUCCESS);
    }

    InitializeObjectAttributes( &ObjectAttributes, NULL, 0, NULL, NULL );

    //
    // For normal images they would be mapped as an image, but
    // the kernel has no debug section (as yet) information, hence it
    // must be mapped as a file.
    //

    status = NtCreateSection (&KernelSection,
                              SECTION_MAP_EXECUTE,
                              &ObjectAttributes,
                              0,
                              PAGE_READONLY,
                              SEC_IMAGE,
                              FileHandle);

    if (!NT_SUCCESS(status)) {
        DbgPrint("create image section failed  status %lx\n", status);
        return(status);
    }

    ViewSize = 0;

    //
    // Map a view of the section into the address space.
    //

    KernelBase = NULL;

    status = NtMapViewOfSection (KernelSection,
                                 CurrentProcessHandle,
                                 (PVOID *)&KernelBase,
                                 0L,
                                 0,
                                 NULL,
                                 &ViewSize,
                                 ViewUnmap,
                                 0,
                                 PAGE_EXECUTE);

    if (!NT_SUCCESS(status)) {
        if (status != STATUS_IMAGE_NOT_AT_BASE) {
            DbgPrint("map section status %lx base %lx size %lx\n", status,
                KernelBase, ViewSize);
        }
    }

    KernelNtHeaders = (PIMAGE_NT_HEADERS)RtlImageNtHeader(KernelBase);

    ImageBase = (PVOID)KernelNtHeaders->OptionalHeader.ImageBase;

    DebugDirectory = (PIMAGE_DEBUG_DIRECTORY)RtlImageDirectoryEntryToData(
                KernelBase, TRUE, IMAGE_DIRECTORY_ENTRY_DEBUG, &DebugSize);

    if (!DebugDirectory) {
        DbgPrint("InitializeKernelProfile : No debug directory\n");
        return STATUS_INVALID_IMAGE_FORMAT;
    }

    KernelDebugInfo = (PIMAGE_DEBUG_INFO)((ULONG)KernelBase + DebugDirectory->AddressOfRawData);
    CodeLength = (KernelDebugInfo->RvaToLastByteOfCode - KernelDebugInfo->RvaToFirstByteOfCode) -1;

    //
    // Just create a 512K byte buffer.
    //

    ViewSize = 1024 * 512;
    Buffer = NULL;

    status = NtAllocateVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&Buffer,
                                      0,
                                      &ViewSize,
                                      MEM_RESERVE | MEM_COMMIT,
                                      PAGE_READWRITE);

    if (!NT_SUCCESS(status)) {
        DbgPrint ("alloc VM failed %lx\n",status);
        NtTerminateProcess(NtCurrentProcess(),STATUS_SUCCESS);
    }

    //
    // Calculate the bucket size for the profile.
    //

    Cells = ((CodeLength / (ViewSize >> 2)) >> 2);
    BucketSize = 2;

    while (Cells != 0) {
        Cells = Cells >> 1;
        BucketSize += 1;
    }

    ProfileObject[NumberOfProfileObjects].Buffer = Buffer;
    ProfileObject[NumberOfProfileObjects].MappedImageBase = KernelBase;
    ProfileObject[NumberOfProfileObjects].BufferSize = 1 + (CodeLength >> (BucketSize - 2));
    ProfileObject[NumberOfProfileObjects].CodeStart = (PULONG)((ULONG)ImageBase + KernelDebugInfo->RvaToFirstByteOfCode);
    ProfileObject[NumberOfProfileObjects].CodeLength = CodeLength;
    ProfileObject[NumberOfProfileObjects].TextNumber = 1;
    ProfileObject[NumberOfProfileObjects].ImageBase = ImageBase;
    ProfileObject[NumberOfProfileObjects].ImageName = "ntoskrnl";
    ProfileObject[NumberOfProfileObjects].BucketSize = BucketSize;


    //
    // Increase the working set to lock down a bigger buffer.
    //

    status = NtQueryInformationProcess (CurrentProcessHandle,
                                        ProcessQuotaLimits,
                                        &QuotaLimits,
                                        sizeof(QUOTA_LIMITS),
                                        NULL );

    if (!NT_SUCCESS(status)) {
        DbgPrint ("query process info failed %lx\n",status);
        NtTerminateProcess(NtCurrentProcess(),STATUS_SUCCESS);
    }

    QuotaLimits.MaximumWorkingSetSize += ViewSize / PAGE_SIZE;
    QuotaLimits.MinimumWorkingSetSize += ViewSize / PAGE_SIZE;

    status = NtSetInformationProcess (CurrentProcessHandle,
                                  ProcessQuotaLimits,
                                  &QuotaLimits,
                                  sizeof(QUOTA_LIMITS));
    if (!NT_SUCCESS(status)) {
        DbgPrint ("setting working set failed %lx\n",status);
        return status;
    }

    status = RtlAdjustPrivilege(
                 SE_PROF_SINGLE_PROCESS_PRIVILEGE,
                 TRUE,              //Enable
                 FALSE,             //not impersonating
                 &PreviousPrivState //Remember if it will need to be cleared
                 );

    if (!NT_SUCCESS(status) || status == STATUS_NOT_ALL_ASSIGNED) {
        DbgPrint("Enable process profile privilege failed - status 0x%lx\n",
                 status);
    }

    status = NtCreateProfile (
                &ProfileObject[NumberOfProfileObjects].Handle,
                CurrentProcessHandle,
                ProfileObject[NumberOfProfileObjects].CodeStart,
                CodeLength,
                ProfileObject[NumberOfProfileObjects].BucketSize,
                ProfileObject[NumberOfProfileObjects].Buffer ,
                ProfileObject[NumberOfProfileObjects].BufferSize,
                ProfileTime,
                (KAFFINITY)-1);

    if (PreviousPrivState == FALSE) {
        LocalStatus = RtlAdjustPrivilege(
                         SE_PROF_SINGLE_PROCESS_PRIVILEGE,
                         FALSE,             //Disable
                         FALSE,             //not impersonating
                         &PreviousPrivState //Don't care if it was already enabled
                         );
        if (!NT_SUCCESS(LocalStatus) || LocalStatus == STATUS_NOT_ALL_ASSIGNED) {
            DbgPrint("Disable system profile privilege failed - status 0x%lx\n",
                     LocalStatus);
        }
    }

    if (status != STATUS_SUCCESS) {
        DbgPrint("create kernel profile %s failed - status %lx\n",
                   ProfileObject[NumberOfProfileObjects].ImageName,status);
    }

    NumberOfProfileObjects += 1;

    return status;
}


VOID
RtlpWriteProfileLine(
    IN HANDLE ProfileHandle,
    IN PSZ Line,
    IN int nbytes
    )
{
    IO_STATUS_BLOCK IoStatusBlock;

    NtWriteFile(
        ProfileHandle,
        NULL,
        NULL,
        NULL,
        &IoStatusBlock,
        Line,
        (ULONG)nbytes,
        NULL,
        NULL
        );

}


HANDLE
RtlpOpenProfileOutputFile()
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    HANDLE Handle;
    UNICODE_STRING FileName;
    IO_STATUS_BLOCK IoStatusBlock;
    BOOLEAN TranslationStatus;
    RTL_RELATIVE_NAME RelativeName;
    PVOID FreeBuffer;


    TranslationStatus = RtlDosPathNameToNtPathName_U(
                            L"\\profile.out",
                            &FileName,
                            NULL,
                            &RelativeName
                            );

    if ( !TranslationStatus ) {
        return NULL;
        }
    FreeBuffer = FileName.Buffer;

    if ( RelativeName.RelativeName.Length ) {
        FileName = *(PUNICODE_STRING)&RelativeName.RelativeName;
        }
    else {
        RelativeName.ContainingDirectory = NULL;
        }

    InitializeObjectAttributes(
        &Obja,
        &FileName,
        OBJ_CASE_INSENSITIVE,
        RelativeName.ContainingDirectory,
        NULL
        );

    Status = NtCreateFile(
                &Handle,
                FILE_APPEND_DATA | SYNCHRONIZE,
                &Obja,
                &IoStatusBlock,
                NULL,
                FILE_ATTRIBUTE_NORMAL,
                FILE_SHARE_READ,
                FILE_OPEN_IF,
                FILE_SYNCHRONOUS_IO_NONALERT,
                NULL,
                0L
                );

    RtlFreeHeap(RtlProcessHeap(),0,FreeBuffer);
    if ( !NT_SUCCESS(Status) ) {
        return NULL;
        }

    return Handle;
}

VOID
RtlpDeleteProfileOutputFile()
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    HANDLE Handle;
    UNICODE_STRING FileName;
    IO_STATUS_BLOCK IoStatusBlock;
    FILE_DISPOSITION_INFORMATION Disposition;
    BOOLEAN TranslationStatus;
    RTL_RELATIVE_NAME RelativeName;
    PVOID FreeBuffer;

    TranslationStatus = RtlDosPathNameToNtPathName_U(
                            L"\\profile.out",
                            &FileName,
                            NULL,
                            &RelativeName
                            );

    if ( !TranslationStatus ) {
        return;
        }

    FreeBuffer = FileName.Buffer;

    if ( RelativeName.RelativeName.Length ) {
        FileName = *(PUNICODE_STRING)&RelativeName.RelativeName;
        }
    else {
        RelativeName.ContainingDirectory = NULL;
        }

    InitializeObjectAttributes(
        &Obja,
        &FileName,
        OBJ_CASE_INSENSITIVE,
        RelativeName.ContainingDirectory,
        NULL
        );

    //
    // Open the file for delete access
    //

    Status = NtOpenFile(
                &Handle,
                (ACCESS_MASK)DELETE | SYNCHRONIZE,
                &Obja,
                &IoStatusBlock,
                FILE_SHARE_DELETE,
                FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE
                );
    RtlFreeHeap(RtlProcessHeap(),0,FreeBuffer);
    if ( !NT_SUCCESS(Status) ) {
        return;
        }

    //
    // Delete the file
    //
    Disposition.DeleteFile = TRUE;

    Status = NtSetInformationFile(
                Handle,
                &IoStatusBlock,
                &Disposition,
                sizeof(Disposition),
                FileDispositionInformation
                );

    NtClose(Handle);
}




NTSTATUS
RtlStartProfile (
    VOID
    )
/*++

Routine Description:

    This routine starts all profile objects which have been initialized.

Arguments:

    None.

Return Value:

    Returns the status of the last NtStartProfile.

--*/

{
    ULONG i;
    NTSTATUS status;
    QUOTA_LIMITS QuotaLimits;

    NtSetIntervalProfile(ProfInt,ProfileTime);
    RtlpDeleteProfileOutputFile();

    for (i = 0; i < NumberOfProfileObjects; i++) {

        status = NtStartProfile (ProfileObject[i].Handle);

        if (status == STATUS_WORKING_SET_QUOTA) {

           //
           // Increase the working set to lock down a bigger buffer.
           //

           status = NtQueryInformationProcess (NtCurrentProcess(),
                                               ProcessQuotaLimits,
                                               &QuotaLimits,
                                               sizeof(QUOTA_LIMITS),
                                               NULL );

           if (!NT_SUCCESS(status)) {
               DbgPrint ("query process info failed %lx\n",status);
               return status;

           }

           QuotaLimits.MaximumWorkingSetSize +=
                 10 * PAGE_SIZE + ProfileObject[i].BufferSize;
           QuotaLimits.MinimumWorkingSetSize +=
                 10 * PAGE_SIZE + ProfileObject[i].BufferSize;

           status = NtSetInformationProcess (NtCurrentProcess(),
                                         ProcessQuotaLimits,
                                         &QuotaLimits,
                                         sizeof(QUOTA_LIMITS));
           if (!NT_SUCCESS(status)) {
               DbgPrint ("setting working set failed %lx\n",status);
               return status;
           }
           status = NtStartProfile (ProfileObject[i].Handle);
        }

        if (status != STATUS_SUCCESS) {
            DbgPrint("start profile %s failed - status %lx\n",
                ProfileObject[i].ImageName, status);
            return status;
        }
    }
    return status;
}
NTSTATUS
RtlStopProfile (
    VOID
    )

/*++

Routine Description:

    This routine stops all profile objects which have been initialized.

Arguments:

    None.

Return Value:

    Returns the status of the last NtStopProfile.

--*/

{
    ULONG i;
    NTSTATUS status;

    for (i = 0; i < NumberOfProfileObjects; i++) {
        status = NtStopProfile (ProfileObject[i].Handle);
        if (status != STATUS_SUCCESS) {
            DbgPrint("stop profile %s failed - status %lx\n",
                   ProfileObject[i].ImageName,status);
            return status;
        }
    }
    return status;
}

NTSTATUS
RtlAnalyzeProfile (
    VOID
    )

/*++

Routine Description:

    This routine does the analysis of all the profile buffers and
    correlates hits to the appropriate symbol table.

Arguments:

    None.

Return Value:

    None.

--*/

{


    RTL_SYMBOL_INFORMATION ThisSymbol;
    RTL_SYMBOL_INFORMATION LastSymbol;
    ULONG CountAtSymbol;
    NTSTATUS Status;
    ULONG Va;
    HANDLE ProfileHandle;
    CHAR Line[512];
    int i,n;
    PULONG Buffer, BufferEnd, Counter;


    ProfileHandle = RtlpOpenProfileOutputFile();
    ASSERT(ProfileHandle);

    for (i = 0; i < NumberOfProfileObjects; i++) {
        Status = NtStopProfile (ProfileObject[i].Handle);
        }


    //
    // The new profiler
    //

    for (i = 0; i < NumberOfProfileObjects; i++)  {

        LastSymbol.Value = 0;
        CountAtSymbol = 0;

        //
        // Sum the total number of cells written.
        //

        BufferEnd = ProfileObject[i].Buffer + (
                    ProfileObject[i].BufferSize / sizeof(ULONG));
        Buffer = ProfileObject[i].Buffer;

        for ( Counter = Buffer; Counter < BufferEnd; Counter += 1 ) {
            if ( *Counter ) {

                //
                // Now we have an an address relative to the buffer
                // base.
                //

                Va = (ULONG)((PUCHAR)Counter - (PUCHAR)Buffer);
                Va = Va * ( 1 << (ProfileObject[i].BucketSize - 2));

                //
                // Add in the image base and the base of the
                // code to get the Va in the image
                //

                Va = Va + (ULONG)ProfileObject[i].CodeStart;

                Status = RtlLookupSymbolByAddress(
                            ProfileObject[i].ImageBase,
                            NULL,
                            (PVOID)Va,
                            0x4000,
                            &ThisSymbol,
                            NULL
                            );
                if ( NT_SUCCESS(Status) ) {
                    if ( LastSymbol.Value && LastSymbol.Value == ThisSymbol.Value ) {
                        CountAtSymbol += *Counter;
                    }
                    else {
                        if ( LastSymbol.Value ) {
                            if ( CountAtSymbol ) {
                                n= sprintf(Line,"%d,%s,%S\n",
                                    CountAtSymbol,
                                    ProfileObject[i].ImageName,
                                    &LastSymbol.Name
                                    );
                                RtlpWriteProfileLine(ProfileHandle,Line,n);
                            }
                        }
                        CountAtSymbol = *Counter;
                        LastSymbol = ThisSymbol;
                    }
                }
            }
        }
        if ( CountAtSymbol ) {
            n= sprintf(Line,"%d,%s,%S\n",
                CountAtSymbol,
                ProfileObject[i].ImageName,
                &LastSymbol.Name
                );
            RtlpWriteProfileLine(ProfileHandle,Line,n);
        }
    }

    for (i = 0; i < NumberOfProfileObjects; i++) {
        Buffer = ProfileObject[i].Buffer;
        RtlZeroMemory(Buffer,ProfileObject[i].BufferSize);
    }
    NtClose(ProfileHandle);
    return Status;
}